diff --git a/README.md b/README.md index 5c0ccd2..7482644 100644 --- a/README.md +++ b/README.md @@ -242,9 +242,9 @@ jobs: FACTORY_API_KEY: ${{ secrets.FACTORY_API_KEY }} ``` -## API Reference +## Documentation -See [PLAN.md](./PLAN.md) for the complete API specification. +Full documentation is available at [activadee.github.io/droid-sdk](https://activadee.github.io/droid-sdk/). ## License diff --git a/docs/README.md b/docs/README.md index b28211a..3757a1c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,41 +1,39 @@ -# Website +# Droid SDK Documentation -This website is built using [Docusaurus](https://docusaurus.io/), a modern static website generator. +This documentation site is built with [Docusaurus](https://docusaurus.io/). -## Installation +## Structure -```bash -yarn +``` +docs/ +├── content/ # Documentation content (MDX files) +│ ├── introduction.mdx +│ ├── quickstart.mdx +│ ├── installation.mdx +│ ├── api-reference/ +│ ├── concepts/ +│ └── guides/ +├── src/ # Custom React components and CSS +├── static/ # Static assets (images, etc.) +├── docusaurus.config.ts +├── sidebars.ts +└── package.json ``` -## Local Development +## Development ```bash -yarn start +cd docs +bun install +bun start ``` -This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server. - ## Build ```bash -yarn build +bun run build ``` -This command generates static content into the `build` directory and can be served using any static contents hosting service. - ## Deployment -Using SSH: - -```bash -USE_SSH=true yarn deploy -``` - -Not using SSH: - -```bash -GIT_USER= yarn deploy -``` - -If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch. +The site is deployed to GitHub Pages at [activadee.github.io/droid-sdk](https://activadee.github.io/droid-sdk/). diff --git a/docs/api-reference/classes/droid.mdx b/docs/api-reference/classes/droid.mdx deleted file mode 100644 index d567925..0000000 --- a/docs/api-reference/classes/droid.mdx +++ /dev/null @@ -1,205 +0,0 @@ ---- -title: Droid -description: Main entry point for the Droid SDK ---- - -# Droid - -The `Droid` class is the main entry point for the SDK. It provides methods for executing prompts and managing conversation threads. - -## Import - -```typescript -import { Droid, MODELS } from '@activade/droid-sdk'; -``` - -## Constructor - -```typescript -new Droid(config?: DroidConfig) -``` - -Creates a new Droid instance with the specified configuration. - -### Parameters - - - Configuration options for the Droid instance. - - - - Working directory for CLI operations. - - - AI model to use for generation. - - - Level of autonomous decision-making: `'default'`, `'low'`, `'medium'`, or `'high'`. - - - Reasoning intensity: `'off'`, `'none'`, `'low'`, `'medium'`, or `'high'`. - - - Path to the Droid CLI binary. - - - Maximum execution time in milliseconds. - - - - -### Example - -```typescript -const droid = new Droid({ - model: MODELS.CLAUDE_SONNET, - autonomyLevel: 'high', - reasoningEffort: 'medium', - cwd: '/path/to/project', - timeout: 300000 -}); -``` - -## Properties - -### config - -```typescript -get config(): Readonly -``` - -Returns the current configuration as a readonly object. - -```typescript -const droid = new Droid({ model: MODELS.CLAUDE_SONNET }); -console.log(droid.config.model); // 'claude-sonnet-4-5-20250929' -``` - -## Methods - -### startThread() - -```typescript -startThread(options?: ThreadOptions): Thread -``` - -Creates a new conversation thread for multi-turn interactions. - - - Thread-specific configuration that overrides instance defaults. - - -**Returns:** A new `Thread` instance. - -```typescript -const thread = droid.startThread({ - autonomyLevel: 'high', - enabledTools: ['file_read', 'file_write'] -}); - -await thread.run('Create a REST API'); -await thread.run('Add authentication'); - -console.log('Session ID:', thread.id); -``` - -### resumeThread() - -```typescript -resumeThread(sessionId: string, options?: ThreadOptions): Thread -``` - -Resumes a previously created conversation thread. - - - The unique session identifier from a previous thread. - - - Thread-specific configuration overrides. - - -**Returns:** A `Thread` instance connected to the existing session. - -```typescript -const thread = droid.resumeThread('session_abc123...'); -await thread.run('What did we work on last time?'); -``` - -### exec() - -```typescript -exec(prompt: string, options?: ExecOptions): Promise -``` - -Executes a single prompt without maintaining conversation state. - - - The natural language prompt to execute. - - - Execution options including model, output schema, etc. - - -**Returns:** A promise resolving to the execution result. - -**Throws:** -- `ExecutionError` - If the CLI execution fails -- `TimeoutError` - If the operation exceeds the configured timeout -- `CliNotFoundError` - If the Droid CLI is not installed - -```typescript -const result = await droid.exec('Generate a UUID'); -console.log(result.finalResponse); -``` - -### listTools() - -```typescript -listTools(model?: string): Promise -``` - -Lists all available tools for the configured or specified model. - - - Model ID to query tools for (defaults to instance model). - - -**Returns:** A promise resolving to an array of tool names. - -```typescript -const tools = await droid.listTools(); -console.log('Available tools:', tools); -// ['file_read', 'file_write', 'shell_exec', ...] -``` - -## Full Example - -```typescript -import { Droid, MODELS } from '@activade/droid-sdk'; -import { z } from 'zod'; - -const droid = new Droid({ - model: MODELS.CLAUDE_SONNET, - autonomyLevel: 'high', - cwd: './my-project' -}); - -// One-shot execution -const result = await droid.exec('Create a hello world function'); -console.log(result.finalResponse); - -// Multi-turn conversation -const thread = droid.startThread(); -await thread.run('Create a React component'); -await thread.run('Add unit tests for it'); - -// Structured output -const schema = z.object({ - name: z.string(), - version: z.string() -}); - -const pkgResult = await droid.exec('Get package info as JSON'); -const pkg = pkgResult.parse(schema); -console.log(pkg.name, pkg.version); -``` diff --git a/docs/api-reference/classes/thread.mdx b/docs/api-reference/classes/thread.mdx deleted file mode 100644 index cfcd096..0000000 --- a/docs/api-reference/classes/thread.mdx +++ /dev/null @@ -1,226 +0,0 @@ ---- -title: Thread -description: Multi-turn conversation management ---- - -# Thread - -The `Thread` class manages multi-turn conversations with the Droid AI. It maintains context across prompts and supports both synchronous and streaming execution. - -## Import - -```typescript -import { Droid } from '@activade/droid-sdk'; - -// Threads are created via Droid methods -const droid = new Droid(); -const thread = droid.startThread(); -``` - -## Properties - -### id - -```typescript -get id(): string | undefined -``` - -The unique session identifier for this thread. Returns `undefined` until the first prompt is executed. - -```typescript -const thread = droid.startThread(); -console.log(thread.id); // undefined - -await thread.run('Hello'); -console.log(thread.id); // 'session_abc123...' -``` - -### cwd - -```typescript -get cwd(): string -``` - -The working directory for this thread's CLI operations. - -```typescript -const thread = droid.startThread({ cwd: '/projects/my-app' }); -console.log(thread.cwd); // '/projects/my-app' -``` - -## Methods - -### run() - -```typescript -run(prompt: string, options?: RunOptions): Promise -``` - -Executes a prompt and waits for the complete response. - - - The natural language prompt to execute. - - - Run-specific configuration. - - - - JSON Schema for structured output. - - - Path to a file containing the prompt. - - - File attachments to include with the prompt. - - - Override the model for this run. - - - Override the autonomy level for this run. - - - - -**Returns:** A promise resolving to the execution result. - -```typescript -const result = await thread.run('Create a function to sort an array'); -console.log(result.finalResponse); - -// Access tool calls -for (const call of result.toolCalls) { - console.log(`Used tool: ${call.toolName}`); -} -``` - -### runStreamed() - -```typescript -runStreamed(prompt: string, options?: RunOptions): Promise -``` - -Executes a prompt with real-time streaming of events. - - - The natural language prompt to execute. - - - Run-specific configuration. - - -**Returns:** A `StreamedTurn` containing an async event iterator and result promise. - -```typescript -const { events, result } = await thread.runStreamed('Build a REST API'); - -for await (const event of events) { - switch (event.type) { - case 'message': - console.log(`[${event.role}] ${event.text}`); - break; - case 'tool_call': - console.log(`Calling: ${event.toolName}`); - break; - case 'tool_result': - console.log(`Result: ${event.isError ? 'ERROR' : 'OK'}`); - break; - case 'completion': - console.log(`Completed in ${event.durationMs}ms`); - break; - } -} - -const finalResult = await result; -``` - -## StreamedTurn - -The return type of `runStreamed()`: - -```typescript -interface StreamedTurn { - events: AsyncIterable; - result: Promise; -} -``` - -### Event Types - -| Type | Description | Properties | -|------|-------------|------------| -| `system` | System init | `cwd`, `session_id`, `tools`, `model` | -| `message` | Message | `role`, `text`, `id`, `timestamp` | -| `tool_call` | Tool call | `toolName`, `parameters`, `id` | -| `tool_result` | Tool result | `toolName`, `value`, `isError` | -| `completion` | Complete | `finalText`, `durationMs`, `numTurns` | -| `turn.failed` | Failed | `error.message`, `error.code` | - -### Type Guards - -Use type guards for type-safe event handling: - -```typescript -import { - isToolCallEvent, - isToolResultEvent, - isMessageEvent -} from '@activade/droid-sdk'; - -for await (const event of events) { - if (isToolCallEvent(event)) { - // TypeScript knows event is ToolCallEvent - console.log(event.toolName, event.parameters); - } -} -``` - -## File Attachments - -Attach files to provide context: - -```typescript -const result = await thread.run('Describe this image', { - attachments: [ - { path: './screenshot.png', type: 'image' } - ] -}); - -const result = await thread.run('Review these files', { - attachments: [ - { path: './src/main.ts', type: 'text', description: 'Main entry' }, - { path: './data.json', type: 'data' } - ] -}); -``` - -## Full Example - -```typescript -import { Droid, MODELS, isToolCallEvent } from '@activade/droid-sdk'; - -const droid = new Droid({ model: MODELS.CLAUDE_SONNET }); -const thread = droid.startThread(); - -// First turn -await thread.run('Create a TypeScript function to validate emails'); - -// Follow-up with context -await thread.run('Add support for custom domain restrictions'); - -// Streaming execution -const { events, result } = await thread.runStreamed('Write tests'); - -for await (const event of events) { - if (isToolCallEvent(event)) { - console.log(`Tool: ${event.toolName}`); - } -} - -const finalResult = await result; -console.log('Tests created:', finalResult.finalResponse); - -// Save session for later -console.log('Session ID:', thread.id); -``` diff --git a/docs/api-reference/classes/turn-result.mdx b/docs/api-reference/classes/turn-result.mdx deleted file mode 100644 index f4c8d66..0000000 --- a/docs/api-reference/classes/turn-result.mdx +++ /dev/null @@ -1,267 +0,0 @@ ---- -title: TurnResult -description: Execution result wrapper with parsing and accessors ---- - -# TurnResult - -The `TurnResult` class encapsulates all data from a single AI interaction, including the final response, tool calls, messages, and execution metadata. - -## Import - -```typescript -import { TurnResult } from '@activade/droid-sdk'; - -// TurnResult is returned from Thread.run() and Droid.exec() -const result = await thread.run('Generate code'); -``` - -## Properties - -### finalResponse - -```typescript -readonly finalResponse: string -``` - -The final text response from the AI. For structured output, this contains JSON that can be parsed using `parse()` or `tryParse()`. - -### items - -```typescript -readonly items: AnyTurnItem[] -``` - -All items from this execution turn (messages, tool calls, tool results) in chronological order. - -### sessionId - -```typescript -readonly sessionId: string -``` - -The unique session identifier. Use with `Droid.resumeThread()` to continue the conversation. - -### durationMs - -```typescript -readonly durationMs: number -``` - -Total execution time in milliseconds. - -### numTurns - -```typescript -readonly numTurns: number -``` - -Number of conversation turns in this execution. - -### isError - -```typescript -readonly isError: boolean -``` - -Whether the execution resulted in an error. - -## Methods - -### parse() - -```typescript -parse(schema: { parse: (data: unknown) => T }): T -``` - -Parses the final response as JSON and validates against a schema. - - - A schema with a `parse` method (e.g., Zod schema). - - -**Returns:** The parsed and validated data. - -**Throws:** -- `ParseError` - If the response is not valid JSON -- Schema error - If validation fails - -```typescript -import { z } from 'zod'; - -const UserSchema = z.object({ - id: z.number(), - name: z.string(), - email: z.string().email() -}); - -const result = await thread.run('Generate a user object as JSON'); -const user = result.parse(UserSchema); -// TypeScript knows: user.id is number, user.name is string, etc. -``` - -### tryParse() - -```typescript -tryParse(schema: { safeParse: (data: unknown) => { success: boolean; data?: T } }): T | null -``` - -Attempts to parse the final response, returning `null` on failure. - -```typescript -const config = result.tryParse(ConfigSchema); - -if (config) { - console.log('Config:', config); -} else { - console.log('No valid config in response'); -} -``` - -### toolCalls - -```typescript -get toolCalls(): ToolCallItem[] -``` - -All tool calls made during this execution. - -```typescript -for (const call of result.toolCalls) { - console.log(`Tool: ${call.toolName}`); - console.log(`Params: ${JSON.stringify(call.parameters)}`); -} -``` - -### toolResults - -```typescript -get toolResults(): ToolResultItem[] -``` - -All tool results from this execution. - -```typescript -for (const toolResult of result.toolResults) { - if (toolResult.isError) { - console.error(`${toolResult.toolName} failed: ${toolResult.value}`); - } else { - console.log(`${toolResult.toolName} succeeded`); - } -} -``` - -### messages - -```typescript -get messages(): MessageItem[] -``` - -All messages (user and assistant) from this execution. - -### assistantMessages - -```typescript -get assistantMessages(): MessageItem[] -``` - -Assistant messages only, excluding user prompts. - -```typescript -for (const msg of result.assistantMessages) { - console.log(`[${new Date(msg.timestamp).toISOString()}] ${msg.text}`); -} -``` - -### toJSON() - -```typescript -toJSON(): TurnResultData -``` - -Converts the result to a plain JSON-serializable object. - -```typescript -// Save to file -fs.writeFileSync('result.json', JSON.stringify(result.toJSON(), null, 2)); -``` - -## Item Types - -### MessageItem - -```typescript -interface MessageItem { - type: 'message'; - role: 'user' | 'assistant'; - id: string; - text: string; - timestamp: number; -} -``` - -### ToolCallItem - -```typescript -interface ToolCallItem { - type: 'tool_call'; - id: string; - messageId: string; - toolId: string; - toolName: string; - parameters: Record; - timestamp: number; -} -``` - -### ToolResultItem - -```typescript -interface ToolResultItem { - type: 'tool_result'; - id: string; - messageId: string; - toolId: string; - toolName: string; - isError: boolean; - value: string; - timestamp: number; -} -``` - -## Full Example - -```typescript -import { Droid } from '@activade/droid-sdk'; -import { z } from 'zod'; - -const droid = new Droid(); -const thread = droid.startThread(); - -const result = await thread.run('Create a config file and return the config as JSON'); - -// Access metadata -console.log(`Session: ${result.sessionId}`); -console.log(`Duration: ${result.durationMs}ms`); -console.log(`Turns: ${result.numTurns}`); -console.log(`Error: ${result.isError}`); - -// Access tool activity -console.log(`Tool calls: ${result.toolCalls.length}`); -for (const call of result.toolCalls) { - const resultItem = result.toolResults.find(r => r.toolId === call.toolId); - console.log(` ${call.toolName}: ${resultItem?.isError ? 'FAILED' : 'OK'}`); -} - -// Parse structured output -const ConfigSchema = z.object({ - port: z.number(), - host: z.string(), - debug: z.boolean().optional() -}); - -const config = result.tryParse(ConfigSchema); -if (config) { - console.log(`Server: ${config.host}:${config.port}`); -} -``` diff --git a/docs/api-reference/overview.mdx b/docs/api-reference/overview.mdx deleted file mode 100644 index 50c3b82..0000000 --- a/docs/api-reference/overview.mdx +++ /dev/null @@ -1,126 +0,0 @@ ---- -title: API Overview -description: Complete reference for the Droid SDK API ---- - -# API Reference - -This section provides comprehensive documentation for all classes, types, and functions in the Droid SDK. - -## Core Classes - - - - Main entry point for the SDK - - - Multi-turn conversation management - - - Execution result wrapper - - - -## Quick Reference - -### Creating a Droid Instance - -```typescript -import { Droid, MODELS } from '@activade/droid-sdk'; - -const droid = new Droid({ - model: MODELS.CLAUDE_SONNET, - autonomyLevel: 'high', - reasoningEffort: 'medium', - cwd: '/path/to/project', - timeout: 600000 -}); -``` - -### Configuration Options - -| Option | Type | Default | Description | -|--------|------|---------|-------------| -| `model` | `ModelId \| string` | - | AI model to use | -| `autonomyLevel` | `'default' \| 'low' \| 'medium' \| 'high'` | `'default'` | Autonomous decision level | -| `reasoningEffort` | `'off' \| 'none' \| 'low' \| 'medium' \| 'high'` | - | Reasoning intensity | -| `cwd` | `string` | `process.cwd()` | Working directory | -| `timeout` | `number` | `600000` | Timeout in milliseconds | -| `droidPath` | `string` | `'droid'` | Path to CLI binary | - -### Available Models - -```typescript -import { MODELS } from '@activade/droid-sdk'; - -// Anthropic -MODELS.CLAUDE_OPUS // claude-opus-4-5-20251101 -MODELS.CLAUDE_SONNET // claude-sonnet-4-5-20250929 -MODELS.CLAUDE_HAIKU // claude-haiku-4-5-20251001 - -// OpenAI -MODELS.GPT_5_1 // gpt-5.1 -MODELS.GPT_5_1_CODEX // gpt-5.1-codex -MODELS.GPT_5_2 // gpt-5.2 - -// Google -MODELS.GEMINI_3_PRO // gemini-3-pro-preview -MODELS.GEMINI_3_FLASH // gemini-3-flash-preview - -// Open Source -MODELS.DROID_CORE // glm-4.6 -``` - -### Error Classes - -| Error | Description | -|-------|-------------| -| `DroidError` | Base class for all SDK errors | -| `CliNotFoundError` | CLI binary not found | -| `ExecutionError` | CLI execution failed | -| `ParseError` | JSON parsing failed | -| `TimeoutError` | Operation timed out | -| `StreamError` | Stream reading failed | - -### Event Types - -| Event Type | Description | -|------------|-------------| -| `system` | System initialization | -| `message` | User or assistant message | -| `tool_call` | Tool invocation | -| `tool_result` | Tool result | -| `completion` | Turn completed | -| `turn.failed` | Turn failed | - -## Import Patterns - -```typescript -// Main SDK -import { Droid, Thread, TurnResult, MODELS } from '@activade/droid-sdk'; - -// Error classes -import { - DroidError, - CliNotFoundError, - ExecutionError, - ParseError, - TimeoutError, - StreamError -} from '@activade/droid-sdk'; - -// Event types and guards -import { - isToolCallEvent, - isToolResultEvent, - isMessageEvent, - type StreamEvent, - type ToolCallEvent -} from '@activade/droid-sdk'; - -// CLI utilities (separate entry point) -import { ensureDroidCli, isDroidCliInstalled } from '@activade/droid-sdk/cli'; - -// Model utilities -import { getModelInfo, isValidModel, MODEL_INFO } from '@activade/droid-sdk'; -``` diff --git a/docs/docs/api-reference/classes/droid.mdx b/docs/content/api-reference/classes/droid.mdx similarity index 100% rename from docs/docs/api-reference/classes/droid.mdx rename to docs/content/api-reference/classes/droid.mdx diff --git a/docs/docs/api-reference/classes/thread.mdx b/docs/content/api-reference/classes/thread.mdx similarity index 100% rename from docs/docs/api-reference/classes/thread.mdx rename to docs/content/api-reference/classes/thread.mdx diff --git a/docs/docs/api-reference/classes/turn-result.mdx b/docs/content/api-reference/classes/turn-result.mdx similarity index 100% rename from docs/docs/api-reference/classes/turn-result.mdx rename to docs/content/api-reference/classes/turn-result.mdx diff --git a/docs/api-reference/cli/installer.mdx b/docs/content/api-reference/cli/installer.mdx similarity index 100% rename from docs/api-reference/cli/installer.mdx rename to docs/content/api-reference/cli/installer.mdx diff --git a/docs/api-reference/cli/process.mdx b/docs/content/api-reference/cli/process.mdx similarity index 100% rename from docs/api-reference/cli/process.mdx rename to docs/content/api-reference/cli/process.mdx diff --git a/docs/api-reference/errors/cli-not-found-error.mdx b/docs/content/api-reference/errors/cli-not-found-error.mdx similarity index 100% rename from docs/api-reference/errors/cli-not-found-error.mdx rename to docs/content/api-reference/errors/cli-not-found-error.mdx diff --git a/docs/api-reference/errors/droid-error.mdx b/docs/content/api-reference/errors/droid-error.mdx similarity index 100% rename from docs/api-reference/errors/droid-error.mdx rename to docs/content/api-reference/errors/droid-error.mdx diff --git a/docs/api-reference/errors/execution-error.mdx b/docs/content/api-reference/errors/execution-error.mdx similarity index 100% rename from docs/api-reference/errors/execution-error.mdx rename to docs/content/api-reference/errors/execution-error.mdx diff --git a/docs/api-reference/errors/parse-error.mdx b/docs/content/api-reference/errors/parse-error.mdx similarity index 100% rename from docs/api-reference/errors/parse-error.mdx rename to docs/content/api-reference/errors/parse-error.mdx diff --git a/docs/api-reference/errors/stream-error.mdx b/docs/content/api-reference/errors/stream-error.mdx similarity index 100% rename from docs/api-reference/errors/stream-error.mdx rename to docs/content/api-reference/errors/stream-error.mdx diff --git a/docs/api-reference/errors/timeout-error.mdx b/docs/content/api-reference/errors/timeout-error.mdx similarity index 100% rename from docs/api-reference/errors/timeout-error.mdx rename to docs/content/api-reference/errors/timeout-error.mdx diff --git a/docs/api-reference/models/model-info.mdx b/docs/content/api-reference/models/model-info.mdx similarity index 100% rename from docs/api-reference/models/model-info.mdx rename to docs/content/api-reference/models/model-info.mdx diff --git a/docs/api-reference/models/overview.mdx b/docs/content/api-reference/models/overview.mdx similarity index 100% rename from docs/api-reference/models/overview.mdx rename to docs/content/api-reference/models/overview.mdx diff --git a/docs/docs/api-reference/overview.mdx b/docs/content/api-reference/overview.mdx similarity index 100% rename from docs/docs/api-reference/overview.mdx rename to docs/content/api-reference/overview.mdx diff --git a/docs/api-reference/types/config.mdx b/docs/content/api-reference/types/config.mdx similarity index 100% rename from docs/api-reference/types/config.mdx rename to docs/content/api-reference/types/config.mdx diff --git a/docs/api-reference/types/events.mdx b/docs/content/api-reference/types/events.mdx similarity index 100% rename from docs/api-reference/types/events.mdx rename to docs/content/api-reference/types/events.mdx diff --git a/docs/api-reference/types/options.mdx b/docs/content/api-reference/types/options.mdx similarity index 100% rename from docs/api-reference/types/options.mdx rename to docs/content/api-reference/types/options.mdx diff --git a/docs/api-reference/types/turn-items.mdx b/docs/content/api-reference/types/turn-items.mdx similarity index 100% rename from docs/api-reference/types/turn-items.mdx rename to docs/content/api-reference/types/turn-items.mdx diff --git a/docs/concepts/droid.mdx b/docs/content/concepts/droid.mdx similarity index 100% rename from docs/concepts/droid.mdx rename to docs/content/concepts/droid.mdx diff --git a/docs/concepts/streaming.mdx b/docs/content/concepts/streaming.mdx similarity index 100% rename from docs/concepts/streaming.mdx rename to docs/content/concepts/streaming.mdx diff --git a/docs/concepts/structured-output.mdx b/docs/content/concepts/structured-output.mdx similarity index 100% rename from docs/concepts/structured-output.mdx rename to docs/content/concepts/structured-output.mdx diff --git a/docs/concepts/threads.mdx b/docs/content/concepts/threads.mdx similarity index 100% rename from docs/concepts/threads.mdx rename to docs/content/concepts/threads.mdx diff --git a/docs/docs/guides/ci-cd.mdx b/docs/content/guides/ci-cd.mdx similarity index 100% rename from docs/docs/guides/ci-cd.mdx rename to docs/content/guides/ci-cd.mdx diff --git a/docs/docs/guides/error-handling.mdx b/docs/content/guides/error-handling.mdx similarity index 100% rename from docs/docs/guides/error-handling.mdx rename to docs/content/guides/error-handling.mdx diff --git a/docs/docs/guides/file-attachments.mdx b/docs/content/guides/file-attachments.mdx similarity index 100% rename from docs/docs/guides/file-attachments.mdx rename to docs/content/guides/file-attachments.mdx diff --git a/docs/docs/guides/multi-turn.mdx b/docs/content/guides/multi-turn.mdx similarity index 100% rename from docs/docs/guides/multi-turn.mdx rename to docs/content/guides/multi-turn.mdx diff --git a/docs/docs/installation.mdx b/docs/content/installation.mdx similarity index 100% rename from docs/docs/installation.mdx rename to docs/content/installation.mdx diff --git a/docs/docs/introduction.mdx b/docs/content/introduction.mdx similarity index 100% rename from docs/docs/introduction.mdx rename to docs/content/introduction.mdx diff --git a/docs/docs/quickstart.mdx b/docs/content/quickstart.mdx similarity index 100% rename from docs/docs/quickstart.mdx rename to docs/content/quickstart.mdx diff --git a/docs/docs/api-reference/cli/installer.mdx b/docs/docs/api-reference/cli/installer.mdx deleted file mode 100644 index 83bee90..0000000 --- a/docs/docs/api-reference/cli/installer.mdx +++ /dev/null @@ -1,141 +0,0 @@ ---- -title: CLI Installer -description: Functions for installing and managing the Droid CLI ---- - -# CLI Installer - -Functions for detecting and installing the Droid CLI binary. - -## Import - -```typescript -import { - isDroidCliInstalled, - getDroidCliPath, - ensureDroidCli -} from '@activade/droid-sdk/cli'; -``` - -## isDroidCliInstalled() - -Check if the CLI is installed: - -```typescript -async function isDroidCliInstalled(): Promise -``` - -### Example - -```typescript -const installed = await isDroidCliInstalled(); -if (!installed) { - console.log('CLI not found, installing...'); - await ensureDroidCli(); -} -``` - -## getDroidCliPath() - -Get the path to an installed CLI: - -```typescript -async function getDroidCliPath(): Promise -``` - -### Example - -```typescript -const path = await getDroidCliPath(); -if (path) { - console.log('CLI found at:', path); -} else { - console.log('CLI not installed'); -} -``` - -## ensureDroidCli() - -Install the CLI if not present: - -```typescript -async function ensureDroidCli(options?: InstallOptions): Promise -``` - -### Parameters - -```typescript -interface InstallOptions { - /** Progress callback */ - onProgress?: (progress: InstallProgress) => void; - - /** Force reinstall even if already installed */ - force?: boolean; -} - -interface InstallProgress { - /** Current phase of installation */ - phase: 'checking' | 'downloading' | 'installing' | 'complete'; - - /** Human-readable progress message */ - message: string; - - /** Progress percentage (0-100), if available */ - percent?: number; -} -``` - -### Example - -```typescript -const cliPath = await ensureDroidCli({ - onProgress: (progress) => { - console.log(`[${progress.phase}] ${progress.message}`); - if (progress.percent !== undefined) { - console.log(`Progress: ${progress.percent}%`); - } - } -}); - -console.log('CLI ready at:', cliPath); -``` - -### Force Reinstall - -```typescript -await ensureDroidCli({ force: true }); -``` - -## Full Example - -```typescript -import { Droid } from '@activade/droid-sdk'; -import { ensureDroidCli, isDroidCliInstalled } from '@activade/droid-sdk/cli'; - -async function setup() { - // Check and install if needed - if (!(await isDroidCliInstalled())) { - console.log('Installing Droid CLI...'); - await ensureDroidCli({ - onProgress: (p) => console.log(` ${p.message}`) - }); - } - - // Now safe to create Droid instance - const droid = new Droid(); - return droid; -} -``` - -## CI/CD Usage - -```typescript -// In CI, install quietly -await ensureDroidCli({ - onProgress: (p) => { - if (p.phase === 'complete') { - console.log('CLI installed successfully'); - } - } -}); -``` diff --git a/docs/docs/api-reference/cli/process.mdx b/docs/docs/api-reference/cli/process.mdx deleted file mode 100644 index 30c70c5..0000000 --- a/docs/docs/api-reference/cli/process.mdx +++ /dev/null @@ -1,188 +0,0 @@ ---- -title: CLI Process -description: Low-level CLI process management functions ---- - -# CLI Process - -Low-level functions for spawning and managing CLI processes. These are primarily used internally but are exported for advanced use cases. - -## Import - -```typescript -import { - spawnDroid, - spawnDroidStreaming, - execDroidJson, - listDroidTools, - findDroidPath -} from '@activade/droid-sdk/cli'; -``` - -## findDroidPath() - -Locate the CLI binary: - -```typescript -async function findDroidPath(customPath?: string): Promise -``` - -### Example - -```typescript -try { - const path = await findDroidPath(); - console.log('Found CLI at:', path); -} catch (error) { - if (error instanceof CliNotFoundError) { - console.log('Searched:', error.searchedPaths); - } -} -``` - -## spawnDroid() - -Spawn a CLI process and wait for completion: - -```typescript -async function spawnDroid(options: SpawnOptions): Promise -``` - -### SpawnOptions - -```typescript -interface SpawnOptions { - prompt: string; - cwd?: string; - droidPath?: string; - model?: string; - outputFormat?: OutputFormat; - timeout?: number; - autonomyLevel?: AutonomyLevel; - reasoningEffort?: ReasoningEffort; - outputSchema?: JsonSchema; - sessionId?: string; - enabledTools?: string[]; - promptFile?: string; - attachments?: FileAttachment[]; -} -``` - -### DroidProcessResult - -```typescript -interface DroidProcessResult { - stdout: string; - stderr: string; - exitCode: number | null; -} -``` - -### Example - -```typescript -const result = await spawnDroid({ - prompt: 'Hello', - cwd: '/my/project', - outputFormat: 'json' -}); - -console.log('Output:', result.stdout); -console.log('Exit code:', result.exitCode); -``` - -## spawnDroidStreaming() - -Spawn a CLI process with streaming output: - -```typescript -async function spawnDroidStreaming( - options: SpawnOptions -): Promise -``` - -### StreamingDroidProcess - -```typescript -interface StreamingDroidProcess { - stdout: ReadableStream; - stderr: ReadableStream; - exitCode: Promise; -} -``` - -### Example - -```typescript -const process = await spawnDroidStreaming({ - prompt: 'Build feature', - outputFormat: 'stream-json' -}); - -const reader = process.stdout.getReader(); -while (true) { - const { done, value } = await reader.read(); - if (done) break; - console.log('Chunk:', new TextDecoder().decode(value)); -} - -const exitCode = await process.exitCode; -``` - -## execDroidJson() - -Execute and parse JSON response: - -```typescript -async function execDroidJson(options: SpawnOptions): Promise -``` - -### Example - -```typescript -const result = await execDroidJson({ - prompt: 'Generate data', - cwd: '/project' -}); - -console.log('Session:', result.session_id); -console.log('Response:', result.result); -``` - -## listDroidTools() - -List available tools: - -```typescript -async function listDroidTools( - droidPath?: string, - model?: string -): Promise -``` - -### Example - -```typescript -const tools = await listDroidTools(); -console.log('Available tools:', tools); -// ['Read', 'Write', 'Bash', 'Glob', 'Grep', ...] -``` - -## Advanced Usage - -```typescript -import { - spawnDroidStreaming, - parseJsonLines -} from '@activade/droid-sdk/cli'; - -// Custom streaming with event parsing -const process = await spawnDroidStreaming({ - prompt: 'Complex task', - outputFormat: 'stream-json' -}); - -for await (const event of parseJsonLines(process.stdout)) { - console.log('Event:', event); -} -``` diff --git a/docs/docs/api-reference/errors/cli-not-found-error.mdx b/docs/docs/api-reference/errors/cli-not-found-error.mdx deleted file mode 100644 index cd0f412..0000000 --- a/docs/docs/api-reference/errors/cli-not-found-error.mdx +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: CliNotFoundError -description: Thrown when the Droid CLI is not installed ---- - -# CliNotFoundError - -Thrown when the Droid CLI binary cannot be found on the system. - -## Import - -```typescript -import { CliNotFoundError, ensureDroidCli } from '@activade/droid-sdk'; -``` - -## Properties - -### searchedPaths - -```typescript -readonly searchedPaths: string[] -``` - -List of paths that were searched for the CLI. - -## Usage - -```typescript -try { - await droid.exec('Hello'); -} catch (error) { - if (error instanceof CliNotFoundError) { - console.log('CLI not found in:', error.searchedPaths); - - // Auto-install the CLI - await ensureDroidCli(); - - // Retry the operation - await droid.exec('Hello'); - } -} -``` - -## Common Causes - -1. **CLI not installed** - Run the installation script -2. **PATH not configured** - Add CLI location to PATH -3. **Custom path not set** - Configure `droidPath` in Droid options - -## Solutions - -### Install the CLI - -```bash -curl -fsSL https://app.factory.ai/cli | sh -``` - -### Use Auto-installer - -```typescript -import { ensureDroidCli } from '@activade/droid-sdk/cli'; - -await ensureDroidCli({ - onProgress: (p) => console.log(`[${p.phase}] ${p.message}`) -}); -``` - -### Specify Custom Path - -```typescript -const droid = new Droid({ - droidPath: '/custom/path/to/droid' -}); -``` diff --git a/docs/docs/api-reference/errors/droid-error.mdx b/docs/docs/api-reference/errors/droid-error.mdx deleted file mode 100644 index 283e768..0000000 --- a/docs/docs/api-reference/errors/droid-error.mdx +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: DroidError -description: Base error class for all SDK errors ---- - -# DroidError - -The base class for all Droid SDK errors. Extend this for custom error handling. - -## Import - -```typescript -import { DroidError } from '@activade/droid-sdk'; -``` - -## Usage - -```typescript -try { - await droid.exec('Do something'); -} catch (error) { - if (error instanceof DroidError) { - // Handle any SDK error - console.error('SDK error:', error.message); - } -} -``` - -## Properties - -### message - -```typescript -readonly message: string -``` - -Human-readable error description. - -### name - -```typescript -readonly name: string -``` - -Error class name (`'DroidError'` or subclass name). - -## Error Hierarchy - -``` -DroidError -├── CliNotFoundError -├── ExecutionError -├── ParseError -├── TimeoutError -└── StreamError -``` - -## Catching All SDK Errors - -```typescript -import { DroidError } from '@activade/droid-sdk'; - -async function safeDroidOperation() { - try { - return await droid.exec('Generate code'); - } catch (error) { - if (error instanceof DroidError) { - // Log and handle SDK errors - console.error(`Droid SDK error: ${error.name} - ${error.message}`); - return null; - } - // Re-throw unknown errors - throw error; - } -} -``` diff --git a/docs/docs/api-reference/errors/execution-error.mdx b/docs/docs/api-reference/errors/execution-error.mdx deleted file mode 100644 index b6622e6..0000000 --- a/docs/docs/api-reference/errors/execution-error.mdx +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: ExecutionError -description: Thrown when CLI execution fails ---- - -# ExecutionError - -Thrown when the Droid CLI process exits with an error. - -## Import - -```typescript -import { ExecutionError } from '@activade/droid-sdk'; -``` - -## Properties - -### exitCode - -```typescript -readonly exitCode: number | null -``` - -The CLI process exit code, or `null` if unavailable. - -### stderr - -```typescript -readonly stderr: string -``` - -Standard error output from the CLI. - -### stdout - -```typescript -readonly stdout: string -``` - -Standard output from the CLI (may contain partial results). - -## Usage - -```typescript -try { - await droid.exec('Risky operation'); -} catch (error) { - if (error instanceof ExecutionError) { - console.error('Execution failed:'); - console.error('Exit code:', error.exitCode); - console.error('Error output:', error.stderr); - console.error('Standard output:', error.stdout); - } -} -``` - -## Common Causes - -1. **Invalid prompt** - Malformed or empty prompt -2. **Permission denied** - Insufficient permissions for file operations -3. **Tool failure** - A tool returned an error -4. **API error** - Backend API returned an error - -## Debugging - -```typescript -try { - await droid.exec(prompt); -} catch (error) { - if (error instanceof ExecutionError) { - // Log full error details - console.error({ - message: error.message, - exitCode: error.exitCode, - stderr: error.stderr, - stdout: error.stdout - }); - - // Check for specific error patterns - if (error.stderr.includes('permission denied')) { - console.log('Try running with higher autonomy level'); - } - } -} -``` diff --git a/docs/docs/api-reference/errors/parse-error.mdx b/docs/docs/api-reference/errors/parse-error.mdx deleted file mode 100644 index 2ee3677..0000000 --- a/docs/docs/api-reference/errors/parse-error.mdx +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: ParseError -description: Thrown when JSON parsing fails ---- - -# ParseError - -Thrown when attempting to parse a non-JSON response. - -## Import - -```typescript -import { ParseError } from '@activade/droid-sdk'; -``` - -## Properties - -### rawText - -```typescript -readonly rawText: string -``` - -The original text that failed to parse. - -## Usage - -```typescript -import { z } from 'zod'; - -const Schema = z.object({ name: z.string() }); - -try { - const data = result.parse(Schema); -} catch (error) { - if (error instanceof ParseError) { - console.error('Not valid JSON'); - console.error('Raw response:', error.rawText); - } -} -``` - -## Distinguishing Parse Errors - -```typescript -import { ParseError } from '@activade/droid-sdk'; -import { z } from 'zod'; - -try { - const data = result.parse(MySchema); -} catch (error) { - if (error instanceof ParseError) { - // Response was not valid JSON - console.error('JSON syntax error:', error.message); - console.error('Response was:', error.rawText); - } else if (error instanceof z.ZodError) { - // JSON was valid but didn't match schema - console.error('Validation errors:', error.issues); - } -} -``` - -## Using tryParse Instead - -For optional JSON parsing, use `tryParse()` to avoid exceptions: - -```typescript -const data = result.tryParse(MySchema); - -if (data) { - console.log('Parsed:', data); -} else { - console.log('Response was not valid JSON'); - console.log('Raw response:', result.finalResponse); -} -``` - -## Prompting for Better JSON - -If you frequently get ParseError, improve your prompts: - -```typescript -// Better prompt for JSON output -const result = await droid.exec(` - Analyze the file and return ONLY a JSON object with this structure: - { - "lines": number, - "functions": number, - "complexity": "low" | "medium" | "high" - } - - Return ONLY the JSON, no other text. -`); -``` diff --git a/docs/docs/api-reference/errors/stream-error.mdx b/docs/docs/api-reference/errors/stream-error.mdx deleted file mode 100644 index bcaeaed..0000000 --- a/docs/docs/api-reference/errors/stream-error.mdx +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: StreamError -description: Thrown when stream processing fails ---- - -# StreamError - -Thrown when reading or processing a streaming response fails. - -## Import - -```typescript -import { StreamError } from '@activade/droid-sdk'; -``` - -## Properties - -### cause - -```typescript -readonly cause?: Error -``` - -The underlying error that caused the stream failure, if available. - -## Usage - -```typescript -try { - const { events, result } = await thread.runStreamed('Build feature'); - - for await (const event of events) { - // Process events - } - - await result; -} catch (error) { - if (error instanceof StreamError) { - console.error('Stream failed:', error.message); - if (error.cause) { - console.error('Caused by:', error.cause); - } - } -} -``` - -## Common Causes - -1. **Connection interrupted** - Network issues during streaming -2. **Process terminated** - CLI process was killed -3. **Invalid stream data** - Malformed JSON in stream -4. **Resource exhaustion** - Out of memory or file descriptors - -## Handling Stream Errors - -```typescript -async function resilientStream(thread: Thread, prompt: string) { - const maxRetries = 3; - - for (let attempt = 0; attempt < maxRetries; attempt++) { - try { - const { events, result } = await thread.runStreamed(prompt); - - for await (const event of events) { - if (event.type === 'turn.failed') { - throw new Error(event.error.message); - } - // Process event - } - - return await result; - } catch (error) { - if (error instanceof StreamError && attempt < maxRetries - 1) { - console.log(`Stream error, retrying (${attempt + 1}/${maxRetries})`); - await new Promise(r => setTimeout(r, 1000 * (attempt + 1))); - continue; - } - throw error; - } - } -} -``` - -## Inline Error Events - -Note that some errors come as events rather than thrown exceptions: - -```typescript -for await (const event of events) { - if (event.type === 'turn.failed') { - // Error during execution (not a StreamError) - console.error('Turn failed:', event.error); - break; - } -} -``` diff --git a/docs/docs/api-reference/errors/timeout-error.mdx b/docs/docs/api-reference/errors/timeout-error.mdx deleted file mode 100644 index 96a1763..0000000 --- a/docs/docs/api-reference/errors/timeout-error.mdx +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: TimeoutError -description: Thrown when operations exceed the timeout ---- - -# TimeoutError - -Thrown when an operation takes longer than the configured timeout. - -## Import - -```typescript -import { TimeoutError } from '@activade/droid-sdk'; -``` - -## Properties - -### timeoutMs - -```typescript -readonly timeoutMs: number -``` - -The timeout value in milliseconds that was exceeded. - -## Usage - -```typescript -try { - await droid.exec('Complex long-running task'); -} catch (error) { - if (error instanceof TimeoutError) { - console.error(`Timed out after ${error.timeoutMs}ms`); - } -} -``` - -## Preventing Timeouts - -### Increase Timeout - -```typescript -const droid = new Droid({ - timeout: 600000 // 10 minutes -}); -``` - -### Per-execution Timeout - -```typescript -// Use a longer timeout for specific operations -const result = await droid.exec('Build entire project', { - timeout: 900000 // 15 minutes -}); -``` - -## Handling Timeouts Gracefully - -```typescript -async function executeWithFallback(prompt: string) { - const droid = new Droid({ timeout: 60000 }); - - try { - return await droid.exec(prompt); - } catch (error) { - if (error instanceof TimeoutError) { - console.log('Operation timed out, trying with streaming...'); - - // Fall back to streaming for progress visibility - const thread = droid.startThread(); - const { events, result } = await thread.runStreamed(prompt); - - for await (const event of events) { - console.log('Progress:', event.type); - } - - return await result; - } - throw error; - } -} -``` - -## Default Timeout - -The default timeout is 600000ms (10 minutes). For complex operations, consider: - -1. Breaking into smaller tasks -2. Using streaming for progress visibility -3. Increasing the timeout value diff --git a/docs/docs/api-reference/models/model-info.mdx b/docs/docs/api-reference/models/model-info.mdx deleted file mode 100644 index b5dd14e..0000000 --- a/docs/docs/api-reference/models/model-info.mdx +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: Model Info -description: Model metadata and utilities ---- - -# Model Info - -Utilities for working with model metadata. - -## Import - -```typescript -import { - getModelInfo, - isValidModel, - MODEL_INFO -} from '@activade/droid-sdk'; -``` - -## MODEL_INFO - -Registry of model metadata: - -```typescript -const MODEL_INFO: Record = { - 'claude-opus-4-5-20251101': { - id: 'claude-opus-4-5-20251101', - name: 'Claude Opus 4.5', - provider: 'anthropic', - contextWindow: 200000, - maxOutput: 16384 - }, - 'claude-sonnet-4-5-20250929': { - id: 'claude-sonnet-4-5-20250929', - name: 'Claude Sonnet 4.5', - provider: 'anthropic', - contextWindow: 200000, - maxOutput: 16384 - }, - // ... more models -}; -``` - -## ModelInfo Interface - -```typescript -interface ModelInfo { - /** Model identifier */ - id: ModelId; - - /** Human-readable model name */ - name: string; - - /** Model provider */ - provider: 'anthropic' | 'openai' | 'google' | 'open-source'; - - /** Context window size in tokens */ - contextWindow: number; - - /** Maximum output tokens */ - maxOutput: number; -} -``` - -## getModelInfo() - -Get metadata for a model: - -```typescript -function getModelInfo(modelId: string): ModelInfo | undefined -``` - -### Example - -```typescript -const info = getModelInfo('claude-sonnet-4-5-20250929'); - -if (info) { - console.log(`${info.name} by ${info.provider}`); - console.log(`Context: ${info.contextWindow} tokens`); - console.log(`Max output: ${info.maxOutput} tokens`); -} -``` - -## isValidModel() - -Check if a model ID is valid: - -```typescript -function isValidModel(modelId: string): modelId is ModelId -``` - -### Example - -```typescript -const modelId = 'claude-sonnet-4-5-20250929'; - -if (isValidModel(modelId)) { - // TypeScript knows modelId is ModelId - const droid = new Droid({ model: modelId }); -} -``` - -## Practical Examples - -### Model Comparison - -```typescript -import { MODEL_INFO, MODELS } from '@activade/droid-sdk'; - -// Compare context windows -const sonnet = MODEL_INFO[MODELS.CLAUDE_SONNET]; -const haiku = MODEL_INFO[MODELS.CLAUDE_HAIKU]; - -console.log(`Sonnet context: ${sonnet.contextWindow}`); -console.log(`Haiku context: ${haiku.contextWindow}`); -``` - -### Selecting by Provider - -```typescript -import { MODEL_INFO, ModelId } from '@activade/droid-sdk'; - -function getAnthropicModels(): ModelId[] { - return Object.values(MODEL_INFO) - .filter(m => m.provider === 'anthropic') - .map(m => m.id); -} -``` - -### Validation - -```typescript -function createDroid(modelId: string) { - if (!isValidModel(modelId)) { - throw new Error(`Unknown model: ${modelId}`); - } - - const info = getModelInfo(modelId)!; - console.log(`Using ${info.name}`); - - return new Droid({ model: modelId }); -} -``` diff --git a/docs/docs/api-reference/models/overview.mdx b/docs/docs/api-reference/models/overview.mdx deleted file mode 100644 index f30b4cb..0000000 --- a/docs/docs/api-reference/models/overview.mdx +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: Models Overview -description: Available AI models and configuration ---- - -# Models - -The SDK supports multiple AI models from different providers. - -## Available Models - -```typescript -import { MODELS } from '@activade/droid-sdk'; -``` - -### Anthropic Claude - -| Constant | Model ID | Description | -|----------|----------|-------------| -| `MODELS.CLAUDE_OPUS` | `claude-opus-4-5-20251101` | Most capable, best for complex tasks | -| `MODELS.CLAUDE_SONNET` | `claude-sonnet-4-5-20250929` | Balanced performance and speed | -| `MODELS.CLAUDE_HAIKU` | `claude-haiku-4-5-20251001` | Fastest, best for simple tasks | - -### OpenAI GPT - -| Constant | Model ID | Description | -|----------|----------|-------------| -| `MODELS.GPT_5_1` | `gpt-5.1` | GPT-5.1 base model | -| `MODELS.GPT_5_1_CODEX` | `gpt-5.1-codex` | Optimized for code | -| `MODELS.GPT_5_2` | `gpt-5.2` | Latest GPT-5 variant | - -### Google Gemini - -| Constant | Model ID | Description | -|----------|----------|-------------| -| `MODELS.GEMINI_3_PRO` | `gemini-3-pro-preview` | Gemini 3 Pro preview | -| `MODELS.GEMINI_3_FLASH` | `gemini-3-flash-preview` | Fast Gemini variant | - -### Open Source - -| Constant | Model ID | Description | -|----------|----------|-------------| -| `MODELS.DROID_CORE` | `glm-4.6` | Open source GLM model | - -## Usage - -```typescript -import { Droid, MODELS } from '@activade/droid-sdk'; - -// Using a constant -const droid = new Droid({ model: MODELS.CLAUDE_SONNET }); - -// Using a string -const droid = new Droid({ model: 'claude-sonnet-4-5-20250929' }); - -// Override per-thread -const thread = droid.startThread({ model: MODELS.CLAUDE_OPUS }); - -// Override per-run -const result = await thread.run('Task', { model: MODELS.CLAUDE_HAIKU }); -``` - -## Model Selection - -Choose based on your needs: - -| Use Case | Recommended Model | -|----------|------------------| -| Complex analysis | `CLAUDE_OPUS` | -| General development | `CLAUDE_SONNET` | -| Quick tasks | `CLAUDE_HAIKU` | -| Code generation | `GPT_5_1_CODEX` | -| Fast iteration | `GEMINI_3_FLASH` | - -## ModelId Type - -```typescript -type ModelId = - | 'claude-opus-4-5-20251101' - | 'claude-sonnet-4-5-20250929' - | 'claude-haiku-4-5-20251001' - | 'gpt-5.1' - | 'gpt-5.1-codex' - | 'gpt-5.2' - | 'gemini-3-pro-preview' - | 'gemini-3-flash-preview' - | 'glm-4.6'; -``` - -The `model` configuration accepts either a `ModelId` or any string for custom/new models. diff --git a/docs/docs/api-reference/types/config.mdx b/docs/docs/api-reference/types/config.mdx deleted file mode 100644 index 01ed417..0000000 --- a/docs/docs/api-reference/types/config.mdx +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: Configuration Types -description: SDK configuration interfaces and defaults ---- - -# Configuration Types - -Types for configuring Droid instances. - -## DroidConfig - -Main configuration interface for the Droid class. - -```typescript -interface DroidConfig { - /** Working directory for CLI operations */ - cwd?: string; - - /** AI model to use */ - model?: ModelId | string; - - /** Level of autonomous decision-making */ - autonomyLevel?: AutonomyLevel; - - /** Reasoning intensity for the AI */ - reasoningEffort?: ReasoningEffort; - - /** Path to the Droid CLI binary */ - droidPath?: string; - - /** Maximum execution time in milliseconds */ - timeout?: number; -} -``` - -## Usage - -```typescript -import { Droid, MODELS } from '@activade/droid-sdk'; - -const config: DroidConfig = { - model: MODELS.CLAUDE_SONNET, - autonomyLevel: 'high', - reasoningEffort: 'medium', - cwd: '/path/to/project', - timeout: 300000, - droidPath: '/custom/bin/droid' -}; - -const droid = new Droid(config); -``` - -## Defaults - -| Property | Default Value | -|----------|--------------| -| `cwd` | `process.cwd()` | -| `model` | (none) | -| `autonomyLevel` | `'default'` | -| `reasoningEffort` | (none) | -| `droidPath` | `'droid'` | -| `timeout` | `600000` (10 min) | - -## Constants - -```typescript -/** Default execution timeout in milliseconds (10 minutes) */ -const DEFAULT_TIMEOUT = 600000; - -/** Default CLI binary name */ -const DEFAULT_DROID_PATH = 'droid'; -``` - -## Config Immutability - -The config is frozen after construction: - -```typescript -const droid = new Droid({ model: MODELS.CLAUDE_SONNET }); - -// Read config -console.log(droid.config.model); // 'claude-sonnet-4-5-20250929' - -// Config is readonly -droid.config.model = 'other'; // TypeScript error -``` diff --git a/docs/docs/api-reference/types/events.mdx b/docs/docs/api-reference/types/events.mdx deleted file mode 100644 index 51f057b..0000000 --- a/docs/docs/api-reference/types/events.mdx +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: Event Types -description: Streaming event types and type guards ---- - -# Event Types - -Types for streaming events emitted during execution. - -## StreamEvent - -Union type of all possible events: - -```typescript -type StreamEvent = - | SystemInitEvent - | MessageEvent - | ToolCallEvent - | ToolResultEvent - | TurnCompletedEvent - | TurnFailedEvent; -``` - -## SystemInitEvent - -Emitted at the start of execution: - -```typescript -interface SystemInitEvent { - type: 'system'; - cwd: string; - session_id: string; - tools: string[]; - model: string; -} -``` - -## MessageEvent - -User or assistant messages: - -```typescript -interface MessageEvent { - type: 'message'; - role: 'user' | 'assistant'; - id: string; - text: string; - timestamp: number; -} -``` - -## ToolCallEvent - -Tool invocations: - -```typescript -interface ToolCallEvent { - type: 'tool_call'; - id: string; - messageId: string; - toolId: string; - toolName: string; - parameters: Record; - timestamp: number; -} -``` - -## ToolResultEvent - -Tool execution results: - -```typescript -interface ToolResultEvent { - type: 'tool_result'; - id: string; - messageId: string; - toolId: string; - toolName: string; - isError: boolean; - value: string; - timestamp: number; -} -``` - -## TurnCompletedEvent - -Successful completion: - -```typescript -interface TurnCompletedEvent { - type: 'completion'; - finalText: string; - durationMs: number; - numTurns: number; -} -``` - -## TurnFailedEvent - -Execution failure: - -```typescript -interface TurnFailedEvent { - type: 'turn.failed'; - error: { - message: string; - code?: string; - }; -} -``` - -## Type Guards - -Import type guards for type-safe event handling: - -```typescript -import { - isSystemInitEvent, - isMessageEvent, - isToolCallEvent, - isToolResultEvent, - isTurnCompletedEvent, - isTurnFailedEvent -} from '@activade/droid-sdk'; - -for await (const event of events) { - if (isToolCallEvent(event)) { - // TypeScript knows: event is ToolCallEvent - console.log(event.toolName, event.parameters); - } - - if (isMessageEvent(event)) { - // TypeScript knows: event is MessageEvent - console.log(`[${event.role}] ${event.text}`); - } -} -``` - -## Type Guard Functions - -```typescript -function isSystemInitEvent(e: StreamEvent): e is SystemInitEvent; -function isMessageEvent(e: StreamEvent): e is MessageEvent; -function isToolCallEvent(e: StreamEvent): e is ToolCallEvent; -function isToolResultEvent(e: StreamEvent): e is ToolResultEvent; -function isTurnCompletedEvent(e: StreamEvent): e is TurnCompletedEvent; -function isTurnFailedEvent(e: StreamEvent): e is TurnFailedEvent; -``` - -## Complete Example - -```typescript -import { - isMessageEvent, - isToolCallEvent, - isToolResultEvent, - isTurnFailedEvent -} from '@activade/droid-sdk'; - -const { events, result } = await thread.runStreamed('Build feature'); - -for await (const event of events) { - if (isMessageEvent(event) && event.role === 'assistant') { - console.log('AI:', event.text); - } - - if (isToolCallEvent(event)) { - console.log(`Running: ${event.toolName}`); - } - - if (isToolResultEvent(event)) { - console.log(` ${event.isError ? '✗' : '✓'} ${event.toolName}`); - } - - if (isTurnFailedEvent(event)) { - console.error('Failed:', event.error.message); - } -} -``` diff --git a/docs/docs/api-reference/types/options.mdx b/docs/docs/api-reference/types/options.mdx deleted file mode 100644 index f9853d3..0000000 --- a/docs/docs/api-reference/types/options.mdx +++ /dev/null @@ -1,150 +0,0 @@ ---- -title: Option Types -description: Execution and thread option types ---- - -# Option Types - -Types for configuring thread and execution options. - -## AutonomyLevel - -Controls how independently the AI operates: - -```typescript -type AutonomyLevel = 'default' | 'low' | 'medium' | 'high'; -``` - -| Level | Behavior | -|-------|----------| -| `default` | Standard confirmation prompts | -| `low` | Conservative, confirms most operations | -| `medium` | Balanced autonomy | -| `high` | Maximum autonomy, minimal confirmations | - -## ReasoningEffort - -Controls reasoning intensity: - -```typescript -type ReasoningEffort = 'off' | 'none' | 'low' | 'medium' | 'high'; -``` - -## OutputFormat - -Output format for CLI operations: - -```typescript -type OutputFormat = 'text' | 'json' | 'stream-json'; -``` - -## ThreadOptions - -Options for creating threads: - -```typescript -interface ThreadOptions { - /** Override working directory */ - cwd?: string; - - /** Override autonomy level */ - autonomyLevel?: AutonomyLevel; - - /** Restrict available tools */ - enabledTools?: string[]; - - /** Override model */ - model?: string; -} -``` - -## RunOptions - -Options for run/runStreamed: - -```typescript -interface RunOptions { - /** JSON Schema for structured output */ - outputSchema?: JsonSchema; - - /** Path to a prompt file */ - promptFile?: string; - - /** File attachments */ - attachments?: FileAttachment[]; - - /** Override model for this run */ - model?: string; - - /** Override autonomy level */ - autonomyLevel?: AutonomyLevel; -} -``` - -## ExecOptions - -Options for one-shot execution: - -```typescript -interface ExecOptions extends RunOptions { - /** Override working directory */ - cwd?: string; - - /** Override timeout */ - timeout?: number; -} -``` - -## FileAttachment - -File attachment for prompts: - -```typescript -interface FileAttachment { - /** Path to the file */ - path: string; - - /** Type of file */ - type: 'image' | 'text' | 'data'; - - /** Optional description */ - description?: string; -} -``` - -## JsonSchema - -JSON Schema for structured output: - -```typescript -interface JsonSchema { - type?: string; - properties?: Record; - items?: JsonSchema; - required?: string[]; - enum?: unknown[]; - description?: string; - [key: string]: unknown; -} -``` - -## Usage Example - -```typescript -const thread = droid.startThread({ - autonomyLevel: 'high', - enabledTools: ['Read', 'Write'] -}); - -const result = await thread.run('Analyze code', { - attachments: [ - { path: './src/main.ts', type: 'text' } - ], - outputSchema: { - type: 'object', - properties: { - issues: { type: 'array' } - } - } -}); -``` diff --git a/docs/docs/api-reference/types/turn-items.mdx b/docs/docs/api-reference/types/turn-items.mdx deleted file mode 100644 index 0e76c71..0000000 --- a/docs/docs/api-reference/types/turn-items.mdx +++ /dev/null @@ -1,161 +0,0 @@ ---- -title: Turn Item Types -description: Types for turn results and items ---- - -# Turn Item Types - -Types representing items within a turn result. - -## AnyTurnItem - -Union of all item types: - -```typescript -type AnyTurnItem = MessageItem | ToolCallItem | ToolResultItem; -``` - -## MessageItem - -Represents a message in the conversation: - -```typescript -interface MessageItem { - type: 'message'; - role: 'user' | 'assistant'; - id: string; - text: string; - timestamp: number; -} -``` - -## ToolCallItem - -Represents a tool invocation: - -```typescript -interface ToolCallItem { - type: 'tool_call'; - id: string; - messageId: string; - toolId: string; - toolName: string; - parameters: Record; - timestamp: number; -} -``` - -## ToolResultItem - -Represents a tool execution result: - -```typescript -interface ToolResultItem { - type: 'tool_result'; - id: string; - messageId: string; - toolId: string; - toolName: string; - isError: boolean; - value: string; - timestamp: number; -} -``` - -## TurnResultData - -Serializable turn result data: - -```typescript -interface TurnResultData { - sessionId: string; - finalResponse: string; - items: AnyTurnItem[]; - durationMs: number; - numTurns: number; - isError: boolean; -} -``` - -## JsonResult - -Response from JSON-mode execution: - -```typescript -interface JsonResult { - session_id: string; - is_error: boolean; - duration_ms: number; - num_turns: number; - result: string; -} -``` - -## Usage Examples - -### Accessing Items - -```typescript -const result = await thread.run('Create a file'); - -// All items in order -for (const item of result.items) { - console.log(item.type, item.timestamp); -} - -// Filter by type -const messages = result.messages; -const toolCalls = result.toolCalls; -const toolResults = result.toolResults; -``` - -### Correlating Tool Calls and Results - -```typescript -for (const call of result.toolCalls) { - const callResult = result.toolResults.find( - r => r.toolId === call.toolId - ); - - console.log(`${call.toolName}:`, callResult?.isError ? 'FAILED' : 'OK'); -} -``` - -### Serializing Results - -```typescript -const result = await thread.run('Build feature'); - -// Convert to plain object -const data = result.toJSON(); - -// Save to file -fs.writeFileSync('result.json', JSON.stringify(data, null, 2)); - -// Structure matches TurnResultData -console.log(data.sessionId); -console.log(data.items.length); -``` - -### Type Narrowing - -```typescript -for (const item of result.items) { - switch (item.type) { - case 'message': - // item is MessageItem - console.log(`[${item.role}] ${item.text}`); - break; - - case 'tool_call': - // item is ToolCallItem - console.log(`Call: ${item.toolName}`); - break; - - case 'tool_result': - // item is ToolResultItem - console.log(`Result: ${item.isError ? 'Error' : 'Success'}`); - break; - } -} -``` diff --git a/docs/docs/concepts/droid.mdx b/docs/docs/concepts/droid.mdx deleted file mode 100644 index a5e71c5..0000000 --- a/docs/docs/concepts/droid.mdx +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: The Droid Class -description: Understanding the main SDK entry point ---- - -# The Droid Class - -The `Droid` class is your gateway to the Factory Droid CLI. It manages configuration, creates conversation threads, and executes AI-powered tasks. - -## Core Responsibilities - -The Droid class handles: - -- **Configuration Management** - Model selection, timeouts, autonomy levels -- **Thread Creation** - Starting new or resuming existing conversations -- **One-shot Execution** - Running single prompts without conversation state -- **Tool Discovery** - Listing available AI tools - -## Creating an Instance - -```typescript -import { Droid, MODELS } from '@activade/droid-sdk'; - -const droid = new Droid({ - model: MODELS.CLAUDE_SONNET, - autonomyLevel: 'high', - cwd: './my-project', - timeout: 300000 -}); -``` - -## Configuration Options - -| Option | Type | Default | Description | -|--------|------|---------|-------------| -| `model` | `ModelId \| string` | - | AI model to use | -| `autonomyLevel` | `AutonomyLevel` | `'default'` | Level of autonomous decision-making | -| `reasoningEffort` | `ReasoningEffort` | - | Reasoning intensity | -| `cwd` | `string` | `process.cwd()` | Working directory for CLI operations | -| `timeout` | `number` | `600000` | Maximum execution time in ms | -| `droidPath` | `string` | `'droid'` | Path to CLI binary | - -## Autonomy Levels - -The autonomy level controls how independently the AI makes decisions: - -- **`default`** - Standard behavior, asks for confirmation on risky operations -- **`low`** - More conservative, confirms most file operations -- **`medium`** - Balanced autonomy for routine tasks -- **`high`** - Maximum autonomy, executes most operations without confirmation - -```typescript -// High autonomy for automated workflows -const automatedDroid = new Droid({ autonomyLevel: 'high' }); - -// Low autonomy for careful review -const reviewDroid = new Droid({ autonomyLevel: 'low' }); -``` - -## Execution Patterns - -### One-shot Execution - -Use `exec()` for stateless, single-prompt operations: - -```typescript -const result = await droid.exec('Generate a random UUID'); -console.log(result.finalResponse); -``` - -### Threaded Conversations - -Use threads for multi-turn conversations with context: - -```typescript -const thread = droid.startThread(); -await thread.run('Create a REST API'); -await thread.run('Add authentication'); // Has context from previous turn -``` - -## Best Practices - -1. **Reuse Droid instances** - Create once, use for multiple operations -2. **Match autonomy to use case** - Higher for automation, lower for interactive -3. **Set appropriate timeouts** - Longer for complex tasks -4. **Use structured output** - For programmatic response handling diff --git a/docs/docs/concepts/streaming.mdx b/docs/docs/concepts/streaming.mdx deleted file mode 100644 index 4a60123..0000000 --- a/docs/docs/concepts/streaming.mdx +++ /dev/null @@ -1,210 +0,0 @@ ---- -title: Streaming Events -description: Real-time event handling during AI execution ---- - -# Streaming Events - -Streaming provides real-time visibility into AI execution, allowing you to display progress, handle tool calls, and respond to events as they occur. - -## Basic Streaming - -```typescript -const { events, result } = await thread.runStreamed('Create a web server'); - -for await (const event of events) { - console.log(event.type, event); -} - -const finalResult = await result; -``` - -## Event Types - -### System Event - -Emitted at the start with session metadata: - -```typescript -{ - type: 'system', - cwd: '/path/to/project', - session_id: 'session_abc123', - tools: ['Read', 'Write', 'Bash', ...], - model: 'claude-sonnet-4-5-20250929' -} -``` - -### Message Event - -User or assistant text messages: - -```typescript -{ - type: 'message', - role: 'assistant', - id: 'msg_123', - text: 'I will create the server...', - timestamp: 1704067200000 -} -``` - -### Tool Call Event - -When the AI invokes a tool: - -```typescript -{ - type: 'tool_call', - id: 'tc_456', - messageId: 'msg_123', - toolId: 'tool_789', - toolName: 'Write', - parameters: { - path: 'server.ts', - content: '...' - }, - timestamp: 1704067201000 -} -``` - -### Tool Result Event - -Tool execution results: - -```typescript -{ - type: 'tool_result', - id: 'tr_012', - messageId: 'msg_123', - toolId: 'tool_789', - toolName: 'Write', - isError: false, - value: 'File written successfully', - timestamp: 1704067202000 -} -``` - -### Completion Event - -Execution completed successfully: - -```typescript -{ - type: 'completion', - finalText: 'Server created at server.ts', - durationMs: 5432, - numTurns: 1 -} -``` - -### Turn Failed Event - -Execution failed: - -```typescript -{ - type: 'turn.failed', - error: { - message: 'Command timed out', - code: 'TIMEOUT' - } -} -``` - -## Type Guards - -Use type guards for type-safe event handling: - -```typescript -import { - isMessageEvent, - isToolCallEvent, - isToolResultEvent, - isTurnCompletedEvent, - isTurnFailedEvent -} from '@activade/droid-sdk'; - -for await (const event of events) { - if (isMessageEvent(event)) { - // TypeScript knows: event.role, event.text - console.log(`[${event.role}] ${event.text}`); - } - - if (isToolCallEvent(event)) { - // TypeScript knows: event.toolName, event.parameters - console.log(`Calling ${event.toolName}`); - } - - if (isToolResultEvent(event)) { - // TypeScript knows: event.isError, event.value - if (event.isError) { - console.error(`Tool failed: ${event.value}`); - } - } -} -``` - -## Building a Progress UI - -```typescript -const { events, result } = await thread.runStreamed(prompt); - -for await (const event of events) { - switch (event.type) { - case 'message': - if (event.role === 'assistant') { - updateUI({ message: event.text }); - } - break; - - case 'tool_call': - updateUI({ - status: 'working', - tool: event.toolName, - action: `Running ${event.toolName}...` - }); - break; - - case 'tool_result': - updateUI({ - status: event.isError ? 'error' : 'success', - result: event.value - }); - break; - - case 'completion': - updateUI({ - status: 'complete', - duration: `${event.durationMs}ms` - }); - break; - - case 'turn.failed': - updateUI({ - status: 'failed', - error: event.error.message - }); - break; - } -} -``` - -## StreamedTurn Structure - -```typescript -interface StreamedTurn { - events: AsyncIterable; - result: Promise; -} -``` - -- **events** - Async iterator of events as they occur -- **result** - Promise that resolves to the final TurnResult - -## Best Practices - -1. **Always await result** - Even if you only need events -2. **Handle all event types** - Especially `turn.failed` -3. **Use type guards** - For type-safe event handling -4. **Stream for long tasks** - Better UX than waiting diff --git a/docs/docs/concepts/structured-output.mdx b/docs/docs/concepts/structured-output.mdx deleted file mode 100644 index a5090e9..0000000 --- a/docs/docs/concepts/structured-output.mdx +++ /dev/null @@ -1,181 +0,0 @@ ---- -title: Structured Output -description: Parse AI responses into typed data structures ---- - -# Structured Output - -The SDK supports parsing AI responses into strongly-typed data structures using Zod schemas. - -## Basic Usage - -```typescript -import { Droid } from '@activade/droid-sdk'; -import { z } from 'zod'; - -const droid = new Droid(); - -const UserSchema = z.object({ - id: z.number(), - name: z.string(), - email: z.string().email() -}); - -const result = await droid.exec('Generate a user object as JSON'); -const user = result.parse(UserSchema); - -// TypeScript knows the type: -console.log(user.id); // number -console.log(user.name); // string -console.log(user.email); // string -``` - -## Parse Methods - -### parse() - Strict Parsing - -Throws on invalid data: - -```typescript -const ConfigSchema = z.object({ - port: z.number(), - host: z.string() -}); - -try { - const config = result.parse(ConfigSchema); - console.log(`Server: ${config.host}:${config.port}`); -} catch (error) { - if (error instanceof ParseError) { - console.error('Invalid JSON:', error.message); - } - // Schema validation errors are thrown as-is -} -``` - -### tryParse() - Safe Parsing - -Returns `null` on failure: - -```typescript -const config = result.tryParse(ConfigSchema); - -if (config) { - console.log('Config:', config); -} else { - console.log('Response was not valid config JSON'); -} -``` - -## Complex Schemas - -### Nested Objects - -```typescript -const ProjectSchema = z.object({ - name: z.string(), - version: z.string(), - dependencies: z.record(z.string()), - scripts: z.object({ - build: z.string().optional(), - test: z.string().optional() - }) -}); - -const result = await droid.exec('Analyze package.json and return as JSON'); -const project = result.parse(ProjectSchema); -``` - -### Arrays - -```typescript -const TodoSchema = z.object({ - id: z.number(), - title: z.string(), - completed: z.boolean() -}); - -const TodoListSchema = z.array(TodoSchema); - -const result = await droid.exec('Generate 5 todo items as JSON array'); -const todos = result.parse(TodoListSchema); -``` - -### Unions and Optionals - -```typescript -const ResponseSchema = z.object({ - status: z.enum(['success', 'error']), - data: z.union([ - z.object({ users: z.array(z.string()) }), - z.object({ error: z.string() }) - ]).optional() -}); -``` - -## JSON Schema Output - -For direct schema specification in prompts: - -```typescript -const result = await thread.run('Generate user data', { - outputSchema: { - type: 'object', - properties: { - id: { type: 'number' }, - name: { type: 'string' } - }, - required: ['id', 'name'] - } -}); -``` - -## Error Handling - -```typescript -import { ParseError } from '@activade/droid-sdk'; -import { z } from 'zod'; - -try { - const data = result.parse(MySchema); -} catch (error) { - if (error instanceof ParseError) { - // Response was not valid JSON - console.error('JSON parse failed:', error.message); - console.error('Raw response:', error.rawText); - } else if (error instanceof z.ZodError) { - // JSON was valid but didn't match schema - console.error('Validation failed:', error.issues); - } -} -``` - -## Prompting for JSON - -For best results, be explicit about JSON format: - -```typescript -// Good - explicit JSON request -const result = await droid.exec( - 'Analyze the codebase and return a JSON object with: ' + - '{ files: number, lines: number, languages: string[] }' -); - -// Better - with example -const result = await droid.exec(` - Analyze the codebase and return JSON like: - { - "files": 42, - "lines": 1234, - "languages": ["TypeScript", "JavaScript"] - } -`); -``` - -## Best Practices - -1. **Use tryParse for optional data** - When JSON might not be present -2. **Use parse for required data** - When you need guaranteed structure -3. **Define precise schemas** - Be specific about types and constraints -4. **Handle both error types** - ParseError and ZodError -5. **Prompt clearly** - Ask explicitly for JSON with structure hints diff --git a/docs/docs/concepts/threads.mdx b/docs/docs/concepts/threads.mdx deleted file mode 100644 index 1f266ef..0000000 --- a/docs/docs/concepts/threads.mdx +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: Conversation Threads -description: Managing multi-turn AI conversations ---- - -# Conversation Threads - -Threads maintain context across multiple prompts, enabling natural multi-turn conversations with the AI. - -## Creating Threads - -Threads are created from a Droid instance: - -```typescript -import { Droid } from '@activade/droid-sdk'; - -const droid = new Droid(); -const thread = droid.startThread(); -``` - -## Thread Lifecycle - -``` -┌─────────────┐ ┌─────────────┐ ┌─────────────┐ -│ Create │────▶│ Execute │────▶│ Resume │ -│ (new) │ │ (run/ │ │ (later) │ -│ │ │ stream) │ │ │ -└─────────────┘ └─────────────┘ └─────────────┘ - │ │ │ - │ ▼ │ - │ ┌─────────────┐ │ - │ │ Session │◀────────────┘ - └──────────▶│ ID │ - └─────────────┘ -``` - -## Multi-turn Conversations - -Each prompt in a thread builds on previous context: - -```typescript -const thread = droid.startThread(); - -// Turn 1: Create initial code -await thread.run('Create a UserService class with CRUD methods'); - -// Turn 2: AI remembers the UserService -await thread.run('Add validation to the create method'); - -// Turn 3: AI has full context -await thread.run('Write unit tests for the validation'); -``` - -## Session Persistence - -Threads can be resumed across process restarts: - -```typescript -// First session -const thread = droid.startThread(); -await thread.run('Start building a payment system'); -const sessionId = thread.id; -// Save sessionId to database/file - -// Later session -const resumedThread = droid.resumeThread(sessionId); -await resumedThread.run('Continue with refund handling'); -``` - -## Thread Options - -Override Droid configuration per-thread: - -```typescript -const thread = droid.startThread({ - autonomyLevel: 'high', // Override autonomy - enabledTools: ['Read', 'Write', 'Bash'], // Limit tools - cwd: '/specific/project' // Different working directory -}); -``` - -## Execution Methods - -### Synchronous Execution - -Wait for the complete response: - -```typescript -const result = await thread.run('Create a config file'); -console.log(result.finalResponse); -``` - -### Streaming Execution - -Process events in real-time: - -```typescript -const { events, result } = await thread.runStreamed('Build a complex feature'); - -for await (const event of events) { - if (event.type === 'tool_call') { - console.log(`Using: ${event.toolName}`); - } -} - -const finalResult = await result; -``` - -## Thread vs Exec - -| Feature | Thread | Exec | -|---------|--------|------| -| Context | Maintained | None | -| Session ID | Yes | Per-call | -| Resume | Yes | No | -| Use case | Multi-turn | One-shot | - -## Best Practices - -1. **Use threads for related tasks** - Keep context across related operations -2. **Save session IDs** - Enable resumption for long-running projects -3. **Use exec for isolated tasks** - When context isn't needed -4. **Stream for long operations** - Better UX with progress updates diff --git a/docs/docusaurus.config.ts b/docs/docusaurus.config.ts index d9e342c..3b79fef 100644 --- a/docs/docusaurus.config.ts +++ b/docs/docusaurus.config.ts @@ -29,6 +29,7 @@ const config: Config = { 'classic', { docs: { + path: 'content', sidebarPath: './sidebars.ts', editUrl: 'https://github.com/activadee/droid-sdk/tree/main/docs/', routeBasePath: '/', diff --git a/docs/guides/ci-cd.mdx b/docs/guides/ci-cd.mdx deleted file mode 100644 index 2ce515c..0000000 --- a/docs/guides/ci-cd.mdx +++ /dev/null @@ -1,223 +0,0 @@ ---- -title: CI/CD Integration -description: Using the SDK in automated pipelines ---- - -# CI/CD Integration - -The Droid SDK is designed for integration into CI/CD pipelines, enabling AI-powered automation in your development workflow. - -## Setup - -### Installing in CI - -```yaml -# GitHub Actions -- name: Install Droid CLI - run: curl -fsSL https://app.factory.ai/cli | sh - -- name: Install dependencies - run: npm install -``` - -Or use the SDK's auto-installer: - -```typescript -import { ensureDroidCli } from '@activade/droid-sdk/cli'; - -// Automatically install if not present -await ensureDroidCli({ - onProgress: (p) => console.log(`[${p.phase}] ${p.message}`) -}); -``` - -### Environment Configuration - -```yaml -env: - # Set any required API keys - ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} -``` - -## Common Use Cases - -### Automated Code Review - -```typescript -import { Droid, MODELS } from '@activade/droid-sdk'; -import { execSync } from 'child_process'; - -async function reviewPR() { - const droid = new Droid({ - model: MODELS.CLAUDE_SONNET, - autonomyLevel: 'low' // Read-only operations - }); - - // Get changed files - const diff = execSync('git diff origin/main').toString(); - - const result = await droid.exec(` - Review this code diff for: - - Bugs and potential issues - - Security vulnerabilities - - Code style violations - - Diff: - ${diff} - `); - - return result.finalResponse; -} -``` - -### Automated Documentation - -```typescript -async function generateDocs() { - const droid = new Droid({ autonomyLevel: 'high' }); - const thread = droid.startThread(); - - await thread.run('Analyze the src/ directory and update README.md'); - await thread.run('Generate API documentation for public exports'); - - // Commit changes - execSync('git add README.md docs/'); - execSync('git commit -m "docs: auto-update documentation"'); -} -``` - -### Test Generation - -```typescript -async function generateTests(changedFiles: string[]) { - const droid = new Droid({ autonomyLevel: 'high' }); - - for (const file of changedFiles) { - if (!file.endsWith('.test.ts')) { - await droid.exec(`Generate unit tests for ${file}`); - } - } -} -``` - -## GitHub Actions Example - -```yaml -name: AI Code Review - -on: - pull_request: - branches: [main] - -jobs: - review: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - uses: actions/setup-node@v4 - with: - node-version: '20' - - - name: Install Droid CLI - run: curl -fsSL https://app.factory.ai/cli | sh - - - name: Install dependencies - run: npm install - - - name: Run AI Review - run: npx tsx scripts/ai-review.ts - env: - ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - - - name: Comment on PR - uses: actions/github-script@v7 - with: - script: | - const fs = require('fs'); - const review = fs.readFileSync('review.md', 'utf8'); - github.rest.issues.createComment({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: context.issue.number, - body: review - }); -``` - -## Best Practices - -### 1. Use Appropriate Autonomy - -```typescript -// CI environments should typically use lower autonomy -const droid = new Droid({ - autonomyLevel: 'low', // Safer for automated runs - timeout: 300000 // 5 minute timeout -}); -``` - -### 2. Handle Errors Gracefully - -```typescript -async function ciTask() { - try { - const result = await droid.exec('Analyze codebase'); - return { success: true, output: result.finalResponse }; - } catch (error) { - console.error('AI task failed:', error); - // Don't fail the whole pipeline for AI errors - return { success: false, error: error.message }; - } -} -``` - -### 3. Set Timeouts - -```typescript -const droid = new Droid({ - timeout: 180000 // 3 minutes - reasonable for CI -}); -``` - -### 4. Cache CLI Installation - -```yaml -- name: Cache Droid CLI - uses: actions/cache@v4 - with: - path: ~/.local/bin/droid - key: droid-cli-${{ runner.os }} -``` - -### 5. Use Structured Output - -```typescript -import { z } from 'zod'; - -const ReviewSchema = z.object({ - issues: z.array(z.object({ - severity: z.enum(['error', 'warning', 'info']), - file: z.string(), - line: z.number().optional(), - message: z.string() - })), - summary: z.string() -}); - -const result = await droid.exec('Review code and return JSON'); -const review = result.tryParse(ReviewSchema); - -if (review && review.issues.some(i => i.severity === 'error')) { - process.exit(1); // Fail pipeline on errors -} -``` - -## Security Considerations - -1. **Store API keys as secrets** - Never commit credentials -2. **Use read-only mode** - Lower autonomy prevents unwanted changes -3. **Validate outputs** - Don't blindly trust AI-generated code -4. **Limit scope** - Restrict working directory and available tools -5. **Review before merge** - AI suggestions should be reviewed diff --git a/docs/guides/error-handling.mdx b/docs/guides/error-handling.mdx deleted file mode 100644 index c753577..0000000 --- a/docs/guides/error-handling.mdx +++ /dev/null @@ -1,245 +0,0 @@ ---- -title: Error Handling -description: Gracefully handling SDK errors ---- - -# Error Handling - -The Droid SDK provides specific error classes for different failure scenarios, enabling precise error handling in your applications. - -## Error Hierarchy - -``` -DroidError (base) -├── CliNotFoundError -├── ExecutionError -├── ParseError -├── TimeoutError -└── StreamError -``` - -## Error Types - -### CliNotFoundError - -Thrown when the Droid CLI is not installed: - -```typescript -import { CliNotFoundError, ensureDroidCli } from '@activade/droid-sdk'; - -try { - const result = await droid.exec('Hello'); -} catch (error) { - if (error instanceof CliNotFoundError) { - console.log('CLI not found, installing...'); - await ensureDroidCli(); - } -} -``` - -### ExecutionError - -Thrown when CLI execution fails: - -```typescript -import { ExecutionError } from '@activade/droid-sdk'; - -try { - const result = await droid.exec('Perform risky operation'); -} catch (error) { - if (error instanceof ExecutionError) { - console.error('Execution failed:', error.message); - console.error('Exit code:', error.exitCode); - console.error('Stderr:', error.stderr); - } -} -``` - -### ParseError - -Thrown when JSON parsing fails: - -```typescript -import { ParseError } from '@activade/droid-sdk'; - -try { - const data = result.parse(MySchema); -} catch (error) { - if (error instanceof ParseError) { - console.error('Not valid JSON:', error.message); - console.error('Raw text:', error.rawText); - } -} -``` - -### TimeoutError - -Thrown when operations exceed the timeout: - -```typescript -import { TimeoutError } from '@activade/droid-sdk'; - -try { - const result = await droid.exec('Complex operation'); -} catch (error) { - if (error instanceof TimeoutError) { - console.error(`Operation timed out after ${error.timeoutMs}ms`); - } -} -``` - -### StreamError - -Thrown when stream processing fails: - -```typescript -import { StreamError } from '@activade/droid-sdk'; - -try { - const { events } = await thread.runStreamed('Build feature'); - for await (const event of events) { - // Process events - } -} catch (error) { - if (error instanceof StreamError) { - console.error('Stream error:', error.message); - } -} -``` - -## Comprehensive Error Handling - -```typescript -import { - Droid, - DroidError, - CliNotFoundError, - ExecutionError, - TimeoutError, - ParseError, - StreamError, - ensureDroidCli -} from '@activade/droid-sdk'; - -async function safeExecute(prompt: string) { - const droid = new Droid({ timeout: 60000 }); - - try { - return await droid.exec(prompt); - } catch (error) { - if (error instanceof CliNotFoundError) { - console.log('Installing CLI...'); - await ensureDroidCli(); - // Retry - return await droid.exec(prompt); - } - - if (error instanceof TimeoutError) { - console.error('Operation timed out. Try with higher timeout.'); - throw error; - } - - if (error instanceof ExecutionError) { - console.error('Execution failed:', error.message); - throw error; - } - - if (error instanceof DroidError) { - // Catch-all for other SDK errors - console.error('SDK error:', error.message); - throw error; - } - - // Unknown error - throw error; - } -} -``` - -## Retry Patterns - -### Simple Retry - -```typescript -async function withRetry( - fn: () => Promise, - maxRetries = 3 -): Promise { - let lastError: Error | undefined; - - for (let i = 0; i < maxRetries; i++) { - try { - return await fn(); - } catch (error) { - lastError = error as Error; - - // Don't retry certain errors - if (error instanceof CliNotFoundError) throw error; - if (error instanceof ParseError) throw error; - - // Wait before retry - await new Promise(r => setTimeout(r, 1000 * (i + 1))); - } - } - - throw lastError; -} - -// Usage -const result = await withRetry(() => droid.exec('Generate code')); -``` - -### Exponential Backoff - -```typescript -async function withExponentialBackoff( - fn: () => Promise, - options = { maxRetries: 3, baseDelay: 1000 } -): Promise { - for (let i = 0; i < options.maxRetries; i++) { - try { - return await fn(); - } catch (error) { - if (i === options.maxRetries - 1) throw error; - - const delay = options.baseDelay * Math.pow(2, i); - await new Promise(r => setTimeout(r, delay)); - } - } - throw new Error('Unreachable'); -} -``` - -## Streaming Error Handling - -```typescript -async function safeStream(thread: Thread, prompt: string) { - try { - const { events, result } = await thread.runStreamed(prompt); - - for await (const event of events) { - if (event.type === 'turn.failed') { - console.error('Turn failed:', event.error.message); - // Handle inline error - break; - } - // Process other events - } - - return await result; - } catch (error) { - if (error instanceof StreamError) { - console.error('Stream interrupted:', error.message); - } - throw error; - } -} -``` - -## Best Practices - -1. **Catch specific errors** - Handle each error type appropriately -2. **Use the error hierarchy** - Catch `DroidError` as fallback -3. **Implement retries** - For transient failures -4. **Log error details** - Use error properties for debugging -5. **Handle stream errors inline** - Check for `turn.failed` events diff --git a/docs/guides/file-attachments.mdx b/docs/guides/file-attachments.mdx deleted file mode 100644 index 9bf0a4b..0000000 --- a/docs/guides/file-attachments.mdx +++ /dev/null @@ -1,178 +0,0 @@ ---- -title: File Attachments -description: Providing context through file attachments ---- - -# File Attachments - -File attachments allow you to provide additional context to the AI by including files with your prompts. - -## Attachment Types - -The SDK supports several attachment types: - -| Type | Description | Use Cases | -|------|-------------|-----------| -| `image` | Image files | Screenshots, diagrams, UI mockups | -| `text` | Text files | Source code, configs, logs | -| `data` | Data files | JSON, CSV, structured data | - -## Basic Usage - -```typescript -const result = await thread.run('Describe this image', { - attachments: [ - { path: './screenshot.png', type: 'image' } - ] -}); -``` - -## Image Attachments - -Attach images for visual analysis: - -```typescript -// Single image -const result = await thread.run('What does this UI show?', { - attachments: [ - { path: './mockup.png', type: 'image' } - ] -}); - -// Multiple images -const result = await thread.run('Compare these two designs', { - attachments: [ - { path: './design-v1.png', type: 'image' }, - { path: './design-v2.png', type: 'image' } - ] -}); -``` - -## Text Attachments - -Attach text files for code review or analysis: - -```typescript -// Code review -const result = await thread.run('Review this code for security issues', { - attachments: [ - { path: './src/auth.ts', type: 'text', description: 'Authentication module' } - ] -}); - -// Multiple files with context -const result = await thread.run('How do these modules interact?', { - attachments: [ - { path: './src/user.ts', type: 'text', description: 'User model' }, - { path: './src/auth.ts', type: 'text', description: 'Auth service' }, - { path: './src/api.ts', type: 'text', description: 'API routes' } - ] -}); -``` - -## Data Attachments - -Attach structured data files: - -```typescript -// JSON data -const result = await thread.run('Analyze this API response', { - attachments: [ - { path: './response.json', type: 'data' } - ] -}); - -// Configuration analysis -const result = await thread.run('Review our build configuration', { - attachments: [ - { path: './tsconfig.json', type: 'data' }, - { path: './package.json', type: 'data' } - ] -}); -``` - -## File Attachment Interface - -```typescript -interface FileAttachment { - /** Path to the file */ - path: string; - - /** Type of file content */ - type: 'image' | 'text' | 'data'; - - /** Optional description for context */ - description?: string; -} -``` - -## Practical Examples - -### Screenshot Analysis - -```typescript -async function analyzeScreenshot(screenshotPath: string) { - const droid = new Droid(); - const thread = droid.startThread(); - - const result = await thread.run( - 'Analyze this screenshot and identify any UI issues or improvements', - { - attachments: [ - { path: screenshotPath, type: 'image' } - ] - } - ); - - return result.finalResponse; -} -``` - -### Code Review Workflow - -```typescript -async function reviewChanges(files: string[]) { - const droid = new Droid(); - const thread = droid.startThread(); - - const attachments = files.map(file => ({ - path: file, - type: 'text' as const, - description: `File: ${file}` - })); - - const result = await thread.run( - 'Review these files for bugs, security issues, and code quality', - { attachments } - ); - - return result.finalResponse; -} -``` - -### Error Log Analysis - -```typescript -async function analyzeErrors(logPath: string) { - const droid = new Droid(); - - const result = await droid.exec( - 'Analyze this log file and summarize the errors', - { - attachments: [ - { path: logPath, type: 'text', description: 'Application error log' } - ] - } - ); - - return result.finalResponse; -} -``` - -## Best Practices - -1. **Use descriptions** - Help the AI understand file purpose -2. **Limit file size** - Large files may be truncated -3. **Choose correct type** - Affects how content is processed -4. **Group related files** - Attach files that work together -5. **Be specific in prompts** - Reference attachments in your prompt diff --git a/docs/guides/multi-turn.mdx b/docs/guides/multi-turn.mdx deleted file mode 100644 index 66004ab..0000000 --- a/docs/guides/multi-turn.mdx +++ /dev/null @@ -1,173 +0,0 @@ ---- -title: Multi-turn Conversations -description: Building complex interactions across multiple prompts ---- - -# Multi-turn Conversations - -Multi-turn conversations allow you to build complex features incrementally, with the AI maintaining context from previous interactions. - -## Basic Multi-turn Flow - -```typescript -import { Droid, MODELS } from '@activade/droid-sdk'; - -const droid = new Droid({ model: MODELS.CLAUDE_SONNET }); -const thread = droid.startThread(); - -// Turn 1: Set up the project -await thread.run('Create a new Express.js REST API project structure'); - -// Turn 2: Add specific functionality (AI remembers the project) -await thread.run('Add a /users endpoint with CRUD operations'); - -// Turn 3: Continue building (AI has full context) -await thread.run('Add JWT authentication middleware'); - -// Turn 4: Finish up -await thread.run('Add unit tests for the authentication'); -``` - -## Saving and Resuming Sessions - -Sessions persist beyond process restarts: - -```typescript -// Initial session -async function startProject() { - const droid = new Droid(); - const thread = droid.startThread(); - - await thread.run('Initialize a React TypeScript project'); - await thread.run('Create a basic component structure'); - - // Save the session ID - return thread.id; -} - -// Resume later -async function continueProject(sessionId: string) { - const droid = new Droid(); - const thread = droid.resumeThread(sessionId); - - // AI remembers the React project - await thread.run('Add routing with React Router'); - await thread.run('Create a navigation component'); -} -``` - -## Building Features Incrementally - -### Step-by-step Feature Development - -```typescript -const thread = droid.startThread(); - -// Step 1: Design -const design = await thread.run( - 'Design a user authentication system. List the components needed.' -); -console.log('Design:', design.finalResponse); - -// Step 2: Data models -await thread.run('Create the User and Session data models'); - -// Step 3: Core logic -await thread.run('Implement the authentication service'); - -// Step 4: API layer -await thread.run('Create login and logout API endpoints'); - -// Step 5: Middleware -await thread.run('Add authentication middleware'); - -// Step 6: Tests -await thread.run('Write tests for the authentication flow'); -``` - -### Iterative Refinement - -```typescript -const thread = droid.startThread(); - -// Initial implementation -await thread.run('Create a function to validate email addresses'); - -// Refine based on requirements -await thread.run('Add support for custom TLDs'); - -// Handle edge cases -await thread.run('Handle emails with + signs and dots'); - -// Optimize -await thread.run('Optimize for performance with large lists'); -``` - -## Managing Long Sessions - -### Checking Session State - -```typescript -const thread = droid.startThread(); -await thread.run('Start working on feature X'); - -// Thread ID is available after first run -console.log('Session:', thread.id); - -// Check what's been done -const status = await thread.run('Summarize what we have done so far'); -console.log(status.finalResponse); -``` - -### Session Storage Patterns - -```typescript -// Store in a database -interface ProjectSession { - projectId: string; - sessionId: string; - createdAt: Date; - lastActivity: Date; -} - -async function saveSession(projectId: string, sessionId: string) { - await db.sessions.upsert({ - projectId, - sessionId, - lastActivity: new Date() - }); -} - -async function getSession(projectId: string): Promise { - const session = await db.sessions.findOne({ projectId }); - return session?.sessionId ?? null; -} -``` - -## Parallel Thread Execution - -Run multiple threads concurrently: - -```typescript -const droid = new Droid(); - -// Create multiple threads -const featureThread = droid.startThread(); -const testThread = droid.startThread(); -const docsThread = droid.startThread(); - -// Run in parallel -const [feature, tests, docs] = await Promise.all([ - featureThread.run('Implement user profile feature'), - testThread.run('Write test suite for API endpoints'), - docsThread.run('Generate API documentation') -]); -``` - -## Best Practices - -1. **Be specific** - Clear prompts lead to better context retention -2. **Reference previous work** - "Now add tests for the function we just created" -3. **Save session IDs** - For long-running projects -4. **Use summaries** - Ask for summaries to verify context -5. **Start fresh when needed** - New threads for unrelated work diff --git a/docs/installation.mdx b/docs/installation.mdx deleted file mode 100644 index c05f854..0000000 --- a/docs/installation.mdx +++ /dev/null @@ -1,165 +0,0 @@ ---- -title: Installation -description: Install the Droid SDK and CLI in your project ---- - -# Installation - -## SDK Installation - -Install the Droid SDK using your preferred package manager: - - - - ```bash - npm install @activade/droid-sdk - ``` - - - ```bash - bun add @activade/droid-sdk - ``` - - - ```bash - yarn add @activade/droid-sdk - ``` - - - ```bash - pnpm add @activade/droid-sdk - ``` - - - -## CLI Installation - -The Droid SDK requires the Factory Droid CLI to be installed. You have two options: - -### Option 1: Manual Installation - -Install the CLI globally: - -```bash -curl -fsSL https://app.factory.ai/cli | sh -``` - -### Option 2: Automatic Installation - -Use the SDK's built-in installer: - -```typescript -import { ensureDroidCli } from '@activade/droid-sdk/cli'; - -// Install CLI if not already present -const cliPath = await ensureDroidCli({ - onProgress: (progress) => { - console.log(`[${progress.phase}] ${progress.message}`); - } -}); - -console.log('CLI installed at:', cliPath); -``` - -## Optional Dependencies - -### Zod 4+ (Recommended) - -For structured output validation, install Zod 4 or later: - -```bash -npm install zod@^4 -``` - -Then use it with the SDK: - -```typescript -import { z } from 'zod'; - -const schema = z.object({ - name: z.string(), - version: z.string() -}); - -const result = await droid.exec('Get package info as JSON'); -const data = result.parse(schema); -``` - -## TypeScript Configuration - -The SDK is written in TypeScript and includes type definitions. Ensure your `tsconfig.json` includes: - -```json -{ - "compilerOptions": { - "target": "ES2020", - "module": "ESNext", - "moduleResolution": "bundler", - "strict": true - } -} -``` - -## Verification - -Verify your installation: - -```typescript -import { Droid, MODELS } from '@activade/droid-sdk'; - -const droid = new Droid({ model: MODELS.CLAUDE_SONNET }); - -// List available tools -const tools = await droid.listTools(); -console.log('Available tools:', tools); - -// Test execution -const result = await droid.exec('Say hello'); -console.log(result.finalResponse); -``` - -## Environment Variables - -The SDK respects these environment variables: - -| Variable | Description | -|----------|-------------| -| `PATH` | System PATH for finding the CLI | -| `HOME` | Home directory for CLI installation | - -## Troubleshooting - -### CLI Not Found - -If you get a `CliNotFoundError`: - -```typescript -import { CliNotFoundError, ensureDroidCli } from '@activade/droid-sdk'; - -try { - await droid.exec('Hello'); -} catch (error) { - if (error instanceof CliNotFoundError) { - console.log('Installing CLI...'); - await ensureDroidCli(); - } -} -``` - -### Permission Issues - -On Unix systems, ensure the CLI is executable: - -```bash -chmod +x ~/.local/bin/droid -``` - -### Timeout Errors - -Increase the timeout for long operations: - -```typescript -const droid = new Droid({ - timeout: 600000 // 10 minutes -}); -``` diff --git a/docs/introduction.mdx b/docs/introduction.mdx deleted file mode 100644 index ffb36ba..0000000 --- a/docs/introduction.mdx +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: Introduction -description: TypeScript SDK for Factory Droid CLI - AI-powered code generation and automation ---- - -# Droid SDK - -The Droid SDK provides a programmatic TypeScript/JavaScript interface to the Factory Droid CLI, enabling AI-powered code generation and task automation in your applications. - -## What is Droid? - -Droid is Factory's AI development agent that can: - -- Generate and modify code based on natural language prompts -- Execute multi-turn conversations with context retention -- Use tools like file operations, shell commands, and web requests -- Support multiple AI models (Claude, GPT, Gemini, and more) - -## Why Use the SDK? - -The SDK wraps the Droid CLI to enable: - - - - Integrate AI code generation into CI/CD pipelines and automation workflows - - - Maintain context across multiple prompts with persistent sessions - - - Observe tool calls and intermediate results as they happen - - - Parse AI responses with Zod schemas for type-safe data - - - -## Quick Example - -```typescript -import { Droid, MODELS } from '@activade/droid-sdk'; - -const droid = new Droid({ - model: MODELS.CLAUDE_SONNET, - autonomyLevel: 'high' -}); - -// One-shot execution -const result = await droid.exec('Create a hello world function'); -console.log(result.finalResponse); - -// Multi-turn conversation -const thread = droid.startThread(); -await thread.run('Create a React component'); -await thread.run('Add unit tests for it'); -``` - -## Features - -- **Thread-based conversations**: Maintain context across multiple prompts -- **Session persistence**: Resume conversations across process restarts -- **Real-time streaming**: Observe tool calls as they happen -- **Structured output**: Validate responses with Zod schemas -- **Automatic CLI installation**: Install the CLI programmatically if needed -- **Multiple model support**: Claude, GPT, Gemini, and more - -## Next Steps - - - - Get up and running in minutes - - - Detailed installation instructions - - - Complete API documentation - - - Learn through practical examples - - diff --git a/docs/quickstart.mdx b/docs/quickstart.mdx deleted file mode 100644 index 7ab0fbc..0000000 --- a/docs/quickstart.mdx +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: Quick Start -description: Get started with the Droid SDK in under 5 minutes ---- - -# Quick Start - -This guide will get you up and running with the Droid SDK in just a few minutes. - -## Prerequisites - -- Node.js 18+ or Bun 1.0+ -- Factory Droid CLI installed (or let the SDK install it for you) - -## Installation - - - - ```bash - npm install @activade/droid-sdk - ``` - - - ```bash - bun add @activade/droid-sdk - ``` - - - ```bash - yarn add @activade/droid-sdk - ``` - - - ```bash - pnpm add @activade/droid-sdk - ``` - - - -## Basic Usage - -### 1. Create a Droid Instance - -```typescript -import { Droid, MODELS } from '@activade/droid-sdk'; - -const droid = new Droid({ - model: MODELS.CLAUDE_SONNET, - cwd: process.cwd() -}); -``` - -### 2. Execute a Prompt - -```typescript -// One-shot execution -const result = await droid.exec('Create a TypeScript function that validates email addresses'); - -console.log(result.finalResponse); -console.log(`Completed in ${result.durationMs}ms`); -``` - -### 3. Multi-turn Conversation - -```typescript -// Start a conversation thread -const thread = droid.startThread(); - -// First prompt - establish context -await thread.run('Create a REST API for a todo list'); - -// Follow-up - the AI remembers the previous context -await thread.run('Add authentication using JWT'); - -// Another follow-up -await thread.run('Write tests for the authentication'); - -// Save session for later -console.log('Session ID:', thread.id); -``` - -### 4. Resume a Conversation - -```typescript -// Resume a previous conversation -const thread = droid.resumeThread('session_abc123...'); - -await thread.run('What did we work on last time?'); -``` - -## Streaming Example - -For real-time progress updates: - -```typescript -const thread = droid.startThread(); -const { events, result } = await thread.runStreamed('Build a React component'); - -// Process events as they arrive -for await (const event of events) { - switch (event.type) { - case 'tool_call': - console.log(`Calling: ${event.toolName}`); - break; - case 'tool_result': - console.log(`Result: ${event.isError ? 'ERROR' : 'OK'}`); - break; - case 'message': - console.log(`[${event.role}] ${event.text.slice(0, 100)}...`); - break; - } -} - -// Get final result -const finalResult = await result; -console.log('Done:', finalResult.finalResponse); -``` - -## Structured Output - -Parse AI responses with Zod schemas: - -```typescript -import { z } from 'zod'; - -const TaskSchema = z.object({ - title: z.string(), - priority: z.enum(['low', 'medium', 'high']), - completed: z.boolean() -}); - -const result = await thread.run('Create a task object as JSON'); -const task = result.parse(TaskSchema); - -console.log(task.title); // TypeScript knows this is a string -console.log(task.priority); // TypeScript knows this is 'low' | 'medium' | 'high' -``` - -## Next Steps - - - - Learn about Droid, Threads, and TurnResults - - - Master real-time event handling - - - Handle errors gracefully - - - Complete API documentation - -