Skip to main content

CLI Usage

The SDK can be used outside of React - in CLI tools, server-side scripts, and background jobs.

Installation

pnpm add @dgidgi-one/sdk
# or
npm install @dgidgi-one/sdk

Basic Setup

import { createClient, projects, auth } from "@dgidgi-one/sdk";

// Initialize client
const client = createClient({
baseURL: process.env.DGIDGI_API_URL || "https://api.dgidgi.one/api/v1",
});

// Set access token if you have one
client.setTokens({
accessToken: process.env.DGIDGI_ACCESS_TOKEN,
expiresAt: Date.now() + 3600000, // 1 hour
});

Authentication Methods

The DgiDgi CLI uses a secure Device Authorization flow:

# Opens browser for authentication
dgidgi login

# Shows verification code and waits for browser approval
# Security Verification Code: 78F00A1A
# Open this URL to authenticate: https://console.dgidgi.one/en/cli-auth?loginId=...

API Key Authentication (For automation/CI)

For server-side applications and CI/CD:

# Login with API key
dgidgi login --token chy_sdk_xxxxxxxxxxxx

# Or use environment variable
export DGIDGI_API_KEY=chy_sdk_xxxxxxxxxxxx
dgidgi login
const client = createClient({
baseURL: "https://api.dgidgi.one/api/v1",
accessToken: process.env.DGIDGI_API_KEY,
});

CLI Example

Project Management CLI

#!/usr/bin/env node
import { createClient, projects, agents } from "@dgidgi-one/sdk";
import { program } from "commander";

const client = createClient({
baseURL: process.env.DGIDGI_API_URL,
});

program
.name("dgidgi")
.description("DgiDgi CLI")
.version("1.0.0");

program
.command("projects")
.description("List all projects")
.action(async () => {
const { data } = await projects.list();
data.forEach(p => console.log(`${p.id}\t${p.name}`));
});

program
.command("project <id>")
.description("Get project details")
.action(async (id) => {
const project = await projects.get(id);
console.log(JSON.stringify(project, null, 2));
});

program
.command("create-project")
.description("Create a new project")
.requiredOption("-n, --name <name>", "Project name")
.option("-d, --description <desc>", "Description")
.action(async (options) => {
const project = await projects.create({
name: options.name,
description: options.description,
});
console.log(`Created project: ${project.id}`);
});

program
.command("agents")
.description("List all agents")
.action(async () => {
const { data } = await agents.list();
data.forEach(a => console.log(`${a.id}\t${a.name}\t${a.status}`));
});

program.parse();

Chat CLI

#!/usr/bin/env node
import { createClient, chat } from "@dgidgi-one/sdk";
import * as readline from "readline";

const client = createClient({
baseURL: process.env.DGIDGI_API_URL,
});

async function main() {
// Create or get session
const session = await chat.sessions.create({
projectId: process.env.PROJECT_ID,
title: "CLI Chat",
});

console.log(`Session: ${session.id}`);
console.log("Type 'exit' to quit\n");

const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});

const askQuestion = () => {
rl.question("You: ", async (input) => {
if (input.toLowerCase() === "exit") {
rl.close();
return;
}

// Stream response
process.stdout.write("AI: ");
for await (const { event, data } of client.stream(
`/chat/${session.id}/stream`,
{ method: "POST", body: { content: input } }
)) {
if (event === "token") {
process.stdout.write((data as { text: string }).text);
}
}
console.log("\n");

askQuestion();
});
};

askQuestion();
}

main().catch(console.error);

Server-Side Scripts

Batch Processing

import { createClient, projects, ai } from "@dgidgi-one/sdk";

const client = createClient({
baseURL: process.env.DGIDGI_API_URL,
});

async function processAllProjects() {
const { data: projectList } = await projects.list();

for (const project of projectList) {
console.log(`Processing: ${project.name}`);

// Generate documentation
const docs = await ai.generate({
prompt: `Generate README for project: ${project.name}`,
model: "gpt-4o",
});

// Update project
await projects.documents.create(project.id, {
title: "README.md",
content: docs.content,
type: "markdown",
});

console.log(` Generated docs for ${project.name}`);
}
}

processAllProjects();

Background Jobs

import { createClient, agents } from "@dgidgi-one/sdk";

const client = createClient({
baseURL: process.env.DGIDGI_API_URL,
});

// Background job to clean up old agent runs
async function cleanupOldRuns() {
const { data: agentList } = await agents.list();

for (const agent of agentList) {
const runs = await agents.runs.list(agent.id, {
status: "completed",
olderThan: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), // 7 days
});

for (const run of runs.data) {
await agents.runs.delete(agent.id, run.id);
console.log(`Deleted run: ${run.id}`);
}
}
}

// Run as cron job
cleanupOldRuns();

Node.js Integration

Express Middleware

import express from "express";
import { createClient, projects } from "@dgidgi-one/sdk";

const app = express();
const dgidgiClient = createClient({
baseURL: process.env.DGIDGI_API_URL,
});

// Proxy endpoint
app.get("/api/projects", async (req, res) => {
try {
const data = await projects.list();
res.json(data);
} catch (error) {
res.status(error.status || 500).json({ error: error.message });
}
});

// Webhook handler
app.post("/webhooks/dgidgi", async (req, res) => {
const { event, data } = req.body;

switch (event) {
case "project.created":
console.log("New project:", data.projectId);
break;
case "agent.completed":
console.log("Agent finished:", data.agentId);
break;
}

res.status(200).send("OK");
});

Worker Threads

import { Worker, isMainThread, parentPort } from "worker_threads";
import { createClient, ai } from "@dgidgi-one/sdk";

if (isMainThread) {
// Main thread - spawn workers
const worker = new Worker(__filename);
worker.postMessage({ task: "generate", prompt: "Write a function" });
worker.on("message", (result) => console.log("Result:", result));
} else {
// Worker thread
const client = createClient({
baseURL: process.env.DGIDGI_API_URL,
});

parentPort?.on("message", async ({ task, prompt }) => {
if (task === "generate") {
const result = await ai.generate({ prompt, model: "gpt-4o" });
parentPort?.postMessage(result);
}
});
}

Environment Variables

# Required
DGIDGI_API_URL=https://api.dgidgi.one/api/v1

# Authentication (for automation/CI)
DGIDGI_API_KEY=chy_sdk_xxxxxxxxxxxx

# Optional
DGIDGI_TIMEOUT=120000
DGIDGI_DEBUG=true
Interactive vs Automated
  • Interactive (CLI): Use dgidgi login for browser-based authentication
  • Automated (CI/CD): Use DGIDGI_API_KEY environment variable

Error Handling

import { createClient, SDKError } from "@dgidgi-one/sdk";

async function safeRequest() {
try {
return await projects.list();
} catch (error) {
if (error instanceof SDKError) {
switch (error.status) {
case 401:
console.error("Authentication failed. Check credentials.");
process.exit(1);
case 403:
console.error("Permission denied.");
process.exit(1);
case 429:
console.error("Rate limited. Waiting...");
await new Promise(r => setTimeout(r, 60000));
return safeRequest(); // Retry
default:
console.error(`API Error: ${error.message}`);
throw error;
}
}
throw error;
}
}

TypeScript Configuration

// tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"strict": true
}
}

Testing with SDK

import { createClient, projects } from "@dgidgi-one/sdk";
import { describe, it, expect, beforeAll } from "vitest";

describe("Projects API", () => {
beforeAll(() => {
createClient({
baseURL: process.env.TEST_API_URL,
});
});

it("should list projects", async () => {
const { data } = await projects.list();
expect(Array.isArray(data)).toBe(true);
});

it("should create and delete project", async () => {
const project = await projects.create({
name: "Test Project",
description: "For testing",
});
expect(project.id).toBeDefined();

await projects.delete(project.id);
});
});