@evolvingmachines/sdk 0.0.55 → 0.0.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts DELETED
@@ -1,3257 +0,0 @@
1
- import { EventEmitter } from 'events';
2
- import * as zod from 'zod';
3
- import { z } from 'zod';
4
- export { E2BConfig, E2BProvider, createE2BProvider } from '@evolvingmachines/e2b';
5
- export { DaytonaConfig, DaytonaProvider, createDaytonaProvider } from '@evolvingmachines/daytona';
6
- export { ModalConfig, ModalProvider, createModalProvider } from '@evolvingmachines/modal';
7
-
8
- /**
9
- * ACP-inspired output types for unified agent event streaming.
10
- * These types are independent of @agentclientprotocol/sdk.
11
- *
12
- * ACP schema reference:
13
- * MANUS-API/KNOWLEDGE/acp-typescript-sdk/src/schema/types.gen.ts
14
- * (SessionUpdate, ContentBlock, ImageContent, TextContent, ToolCall, ToolCallUpdate, Plan)
15
- *
16
- * INTERNAL REFERENCE - JSDoc stripped from published package.
17
- *
18
- * @example Event Flow
19
- * ```
20
- * agent_message_chunk → Text/image streaming from agent
21
- * agent_thought_chunk → Reasoning (Codex) or thinking (Claude)
22
- * user_message_chunk → User message echo (Gemini)
23
- * tool_call → Tool started (status: pending/in_progress)
24
- * tool_call_update → Tool finished (status: completed/failed)
25
- * plan → TodoWrite updates
26
- * ```
27
- *
28
- * @example UI Integration
29
- * ```ts
30
- * evolve.on('content', (event: OutputEvent) => {
31
- * switch (event.update.sessionUpdate) {
32
- * case 'agent_message_chunk':
33
- * appendToChat(event.update.content);
34
- * break;
35
- * case 'tool_call':
36
- * addToolCard(event.update.toolCallId, event.update.title);
37
- * break;
38
- * case 'tool_call_update':
39
- * updateToolCard(event.update.toolCallId, event.update.status);
40
- * break;
41
- * }
42
- * });
43
- * ```
44
- */
45
- /**
46
- * Tool operation category for UI grouping/icons.
47
- *
48
- * | Kind | Tools | Icon suggestion |
49
- * |------|-------|-----------------|
50
- * | read | Read, NotebookRead | 📄 |
51
- * | edit | Edit, Write, NotebookEdit | ✏️ |
52
- * | delete | (future) | 🗑️ |
53
- * | move | (future) | 📦 |
54
- * | search | Glob, Grep, LS | 🔍 |
55
- * | execute | Bash, BashOutput, KillShell | ⚡ |
56
- * | think | Task (subagent) | 🧠 |
57
- * | fetch | WebFetch, WebSearch | 🌐 |
58
- * | switch_mode | ExitPlanMode | 🔀 |
59
- * | other | MCP tools, unknown | ❓ |
60
- */
61
- type ToolKind = "read" | "edit" | "delete" | "move" | "search" | "execute" | "think" | "fetch" | "switch_mode" | "other";
62
- /**
63
- * Tool execution lifecycle.
64
- *
65
- * Flow: pending → in_progress → completed|failed
66
- *
67
- * - pending: Tool call received, not yet executing
68
- * - in_progress: Tool is executing (Codex command_execution)
69
- * - completed: Tool finished successfully
70
- * - failed: Tool errored (check content for error message)
71
- */
72
- type ToolCallStatus = "pending" | "in_progress" | "completed" | "failed";
73
- /**
74
- * Plan/Todo item status.
75
- */
76
- type PlanEntryStatus = "pending" | "in_progress" | "completed";
77
- /**
78
- * Text content block.
79
- */
80
- interface TextContent {
81
- type: "text";
82
- text: string;
83
- }
84
- /**
85
- * Image content block (base64 or URL).
86
- */
87
- interface ImageContent {
88
- type: "image";
89
- /** Base64-encoded image data */
90
- data: string;
91
- /** MIME type (e.g., "image/png") */
92
- mimeType: string;
93
- /** Optional URL if image is remote */
94
- uri?: string;
95
- }
96
- /**
97
- * Diff content for file edits.
98
- */
99
- interface DiffContent {
100
- type: "diff";
101
- /** File path being edited */
102
- path: string;
103
- /** Original text (null for new files) */
104
- oldText: string | null;
105
- /** New text after edit */
106
- newText: string;
107
- }
108
- /**
109
- * Content that can appear in messages.
110
- */
111
- type ContentBlock = TextContent | ImageContent;
112
- /**
113
- * Content attached to tool calls.
114
- * Either wrapped content or a diff.
115
- */
116
- type ToolCallContent = {
117
- type: "content";
118
- content: ContentBlock;
119
- } | DiffContent;
120
- /**
121
- * File location affected by a tool call.
122
- */
123
- interface ToolCallLocation {
124
- /** Absolute file path */
125
- path: string;
126
- /** Line number (0-indexed for Read offset) */
127
- line?: number;
128
- }
129
- /**
130
- * Todo/plan entry from TodoWrite.
131
- */
132
- interface PlanEntry {
133
- /** Task description */
134
- content: string;
135
- /** Current status */
136
- status: PlanEntryStatus;
137
- /** Priority level */
138
- priority: "high" | "medium" | "low";
139
- }
140
- /**
141
- * All possible session update types.
142
- * Discriminated union on `sessionUpdate` field.
143
- */
144
- type SessionUpdate = AgentMessageChunk | AgentThoughtChunk | UserMessageChunk | ToolCall | ToolCallUpdate | Plan;
145
- /**
146
- * Streaming text/image from agent.
147
- * May arrive in multiple chunks - concatenate text.
148
- */
149
- interface AgentMessageChunk {
150
- sessionUpdate: "agent_message_chunk";
151
- content: ContentBlock;
152
- }
153
- /**
154
- * Agent reasoning/thinking (not shown to end user by default).
155
- * - Codex: "reasoning" item type
156
- * - Claude: "thinking" content block
157
- */
158
- interface AgentThoughtChunk {
159
- sessionUpdate: "agent_thought_chunk";
160
- content: ContentBlock;
161
- }
162
- /**
163
- * User message echo (primarily from Gemini).
164
- */
165
- interface UserMessageChunk {
166
- sessionUpdate: "user_message_chunk";
167
- content: ContentBlock;
168
- }
169
- /**
170
- * Tool call started.
171
- *
172
- * Match with ToolCallUpdate via `toolCallId`.
173
- *
174
- * @example Claude Read tool
175
- * ```json
176
- * {
177
- * "sessionUpdate": "tool_call",
178
- * "toolCallId": "toolu_01ABC...",
179
- * "title": "Read /src/index.ts (1 - 100)",
180
- * "kind": "read",
181
- * "status": "pending",
182
- * "locations": [{ "path": "/src/index.ts", "line": 0 }]
183
- * }
184
- * ```
185
- */
186
- interface ToolCall {
187
- sessionUpdate: "tool_call";
188
- /** Unique ID to match with ToolCallUpdate */
189
- toolCallId: string;
190
- /** Human-readable title (e.g., "`npm install`", "Read /path/file.ts") */
191
- title: string;
192
- /** Tool category for UI grouping */
193
- kind: ToolKind;
194
- /** Execution status */
195
- status: ToolCallStatus;
196
- /** Original tool input parameters */
197
- rawInput?: unknown;
198
- /** Diff for edits, description for commands */
199
- content?: ToolCallContent[];
200
- /** File paths affected */
201
- locations?: ToolCallLocation[];
202
- }
203
- /**
204
- * Tool call completed/failed.
205
- *
206
- * Match with ToolCall via `toolCallId`.
207
- *
208
- * @example Successful completion
209
- * ```json
210
- * {
211
- * "sessionUpdate": "tool_call_update",
212
- * "toolCallId": "toolu_01ABC...",
213
- * "status": "completed",
214
- * "content": [{ "type": "content", "content": { "type": "text", "text": "..." } }]
215
- * }
216
- * ```
217
- *
218
- * @example Failed tool
219
- * ```json
220
- * {
221
- * "sessionUpdate": "tool_call_update",
222
- * "toolCallId": "toolu_01ABC...",
223
- * "status": "failed",
224
- * "content": [{ "type": "content", "content": { "type": "text", "text": "```\nError: ...\n```" } }]
225
- * }
226
- * ```
227
- *
228
- * @example Browser-Use MCP tool response
229
- * The browser-use MCP tool returns a JSON string in content[].content.text:
230
- * ```json
231
- * {
232
- * "sessionUpdate": "tool_call_update",
233
- * "toolCallId": "...",
234
- * "status": "completed",
235
- * "content": [{
236
- * "type": "content",
237
- * "content": {
238
- * "type": "text",
239
- * "text": "{\"live_url\":\"https://...\",\"screenshot_url\":\"https://...\",\"steps\":[{\"screenshot_url\":\"https://...\"}]}"
240
- * }
241
- * }]
242
- * }
243
- * ```
244
- * The `text` field contains a JSON string with:
245
- * - `live_url`: URL for live browser view (VNC/noVNC)
246
- * - `screenshot_url`: URL for screenshot image
247
- * - `steps[].screenshot_url`: Alternative location for screenshots
248
- */
249
- interface ToolCallUpdate {
250
- sessionUpdate: "tool_call_update";
251
- /** Matches ToolCall.toolCallId */
252
- toolCallId: string;
253
- /** Final status */
254
- status?: ToolCallStatus;
255
- /** Updated title (e.g., "Exited Plan Mode") */
256
- title?: string;
257
- /** Output content or error message */
258
- content?: ToolCallContent[];
259
- /** Updated locations (rare) */
260
- locations?: ToolCallLocation[];
261
- }
262
- /**
263
- * Todo list update from TodoWrite tool.
264
- * Replaces entire todo list on each update.
265
- */
266
- interface Plan {
267
- sessionUpdate: "plan";
268
- /** All current plan entries */
269
- entries: PlanEntry[];
270
- }
271
- /**
272
- * Top-level event emitted by Evolve 'content' event.
273
- *
274
- * @example
275
- * ```ts
276
- * evolve.on('content', (event: OutputEvent) => {
277
- * console.log(event.sessionId, event.update.sessionUpdate);
278
- * });
279
- * ```
280
- */
281
- interface OutputEvent {
282
- /** Session ID (from agent, may be undefined) */
283
- sessionId?: string;
284
- /** The session update payload */
285
- update: SessionUpdate;
286
- }
287
-
288
- /**
289
- * Agent Registry
290
- *
291
- * Single source of truth for agent-specific behavior.
292
- * All differences between agents are data, not code.
293
- *
294
- * Evidence: sdk-rewrite-v3.md Agent Registry section
295
- */
296
-
297
- /** Model configuration */
298
- interface ModelInfo {
299
- /** Model alias (short name used with --model) */
300
- alias: string;
301
- /** Full model ID */
302
- modelId: string;
303
- /** What this model is best for */
304
- description: string;
305
- }
306
- /** MCP configuration for an agent */
307
- interface McpConfigInfo {
308
- /** Settings directory (e.g., "~/.claude") */
309
- settingsDir: string;
310
- /** Config filename (e.g., "settings.json" or "config.toml") */
311
- filename: string;
312
- /** Config format */
313
- format: "json" | "toml";
314
- /** Whether to use workingDir for project-level config (Claude only) */
315
- projectConfig?: boolean;
316
- }
317
- /** Options for building agent commands */
318
- interface BuildCommandOptions {
319
- prompt: string;
320
- model: string;
321
- isResume: boolean;
322
- sessionId?: string;
323
- reasoningEffort?: string;
324
- isDirectMode?: boolean;
325
- /** Skills enabled for this run */
326
- skills?: string[];
327
- }
328
- interface AgentRegistryEntry {
329
- /** Sandbox image/template identifier (provider maps to its own concept) */
330
- image: string;
331
- /** Environment variable name for API key */
332
- apiKeyEnv: string;
333
- /** Environment variable name for OAuth (file path or token depending on agent) */
334
- oauthEnv?: string;
335
- /** OAuth credentials filename (e.g., "auth.json" for Codex, "oauth_creds.json" for Gemini) */
336
- oauthFileName?: string;
337
- /** Environment variable to set when OAuth is active (e.g., GOOGLE_GENAI_USE_GCA=true for Gemini) */
338
- oauthActivationEnv?: {
339
- key: string;
340
- value: string;
341
- };
342
- /** Environment variable name for base URL, if this CLI supports one */
343
- baseUrlEnv?: string;
344
- /** Default model alias */
345
- defaultModel: string;
346
- /** Available models for this agent */
347
- models: ModelInfo[];
348
- /** System prompt filename (e.g., "CLAUDE.md") */
349
- systemPromptFile: string;
350
- /** MCP configuration */
351
- mcpConfig: McpConfigInfo;
352
- /** Build the CLI command for this agent */
353
- buildCommand: (opts: BuildCommandOptions) => string;
354
- /** Extra setup step (e.g., codex login) */
355
- setupCommand?: string;
356
- /** Gateway path prefix for CLIs that use a provider-native passthrough endpoint */
357
- gatewayPath?: string;
358
- /** Default base URL for direct mode (only needed if provider requires specific endpoint, e.g., Qwen → Dashscope) */
359
- defaultBaseUrl?: string;
360
- /** Available beta headers for this agent (for reference) */
361
- availableBetas?: Record<string, string>;
362
- /** Skills configuration for this agent */
363
- skillsConfig: SkillsConfig;
364
- /** Multi-provider env mapping: model prefix → keyEnv (for CLIs like OpenCode that resolve provider from model string) */
365
- providerEnvMap?: Record<string, {
366
- keyEnv: string;
367
- }>;
368
- /** Env var for inline config (e.g., OPENCODE_CONFIG_CONTENT) — used in gateway mode to set provider base URLs */
369
- gatewayConfigEnv?: string;
370
- /** Gateway-only model aliases for CLIs whose native model IDs differ from LiteLLM route names */
371
- gatewayModelAliases?: Record<string, string>;
372
- /** Direct-mode model aliases for CLIs whose public model names differ from CLI-native model IDs */
373
- directModelAliases?: Record<string, string>;
374
- /** Do not set provider API key env in gateway mode (used when routing via generated settings instead) */
375
- skipApiKeyEnvInGateway?: boolean;
376
- /** Dedicated Droid settings file for Evolve gateway custom model routing */
377
- droidGatewaySettings?: {
378
- settingsPath: string;
379
- displayName: string;
380
- provider: "generic-chat-completion-api" | "openai" | "anthropic";
381
- maxOutputTokens?: number;
382
- };
383
- /** Environment variable that CLI reads for custom outbound HTTP headers */
384
- customHeadersEnv?: string;
385
- /** Format for custom headers env var: "newline" (Claude) or "comma" (Gemini). Default: "newline" */
386
- customHeadersFormat?: "newline" | "comma";
387
- /**
388
- * Per-env-var spend tracking for CLIs that support env_http_headers in config
389
- * (e.g., Codex TOML). Maps LiteLLM header names to env var names that the CLI
390
- * reads at request time. Alternative to customHeadersEnv for agents without a
391
- * single custom-headers env var.
392
- */
393
- spendTrackingEnvs?: {
394
- /** Env var name for x-litellm-customer-id value */
395
- sessionTagEnv: string;
396
- /** Env var name for x-litellm-tags value */
397
- runTagEnv: string;
398
- };
399
- /**
400
- * Config-file-based spend tracking for CLIs that read custom headers from a
401
- * JSON settings file (e.g., Qwen settings.json → model.generationConfig.customHeaders).
402
- * The SDK writes headers to this file before each run.
403
- * Source-verified: Qwen reads customHeaders from settings.json, not env vars.
404
- */
405
- spendTrackingJsonConfig?: {
406
- /** JSON path to the customHeaders object (dot-separated) */
407
- headersPath: string;
408
- };
409
- /**
410
- * TOML provider-based spend tracking for CLIs that read custom_headers from a
411
- * provider entry in config.toml (e.g., Kimi Code).
412
- * The SDK writes a provider+model entry with custom_headers before each run.
413
- * Source-verified: Kimi Code reads custom_headers from
414
- * providers[name].custom_headers in ~/.kimi-code/config.toml.
415
- */
416
- spendTrackingTomlProvider?: {
417
- /** Config file path (e.g., "~/.kimi-code/config.toml") */
418
- configPath: string;
419
- /** Provider name in config (e.g., "evolve-gateway") */
420
- providerName: string;
421
- /** Model entry name (e.g., "evolve-default") */
422
- modelName: string;
423
- /** Max context size for the model entry */
424
- maxContextSize: number;
425
- };
426
- /** Additional directories to include in checkpoint tar (beyond mcpConfig.settingsDir).
427
- * Used for agents like OpenCode that spread state across XDG directories. */
428
- checkpointDirs?: string[];
429
- /** Additional relative paths to exclude from checkpoint tar. */
430
- checkpointExcludes?: string[];
431
- }
432
- /**
433
- * Registry of all supported agents.
434
- *
435
- * Each agent defines a buildCommand function that constructs the CLI command.
436
- * This is type-safe and handles conditional logic cleanly.
437
- */
438
- declare const AGENT_REGISTRY: Record<AgentType, AgentRegistryEntry>;
439
- /**
440
- * Get registry entry for an agent type
441
- */
442
- declare function getAgentConfig(agentType: AgentType): AgentRegistryEntry;
443
- /**
444
- * Check if an agent type is valid
445
- */
446
- declare function isValidAgentType(type: string): type is AgentType;
447
- /**
448
- * Expand path with ~ to /home/user
449
- */
450
- declare function expandPath(path: string): string;
451
- /**
452
- * Get MCP settings path for an agent
453
- */
454
- declare function getMcpSettingsPath(agentType: AgentType): string;
455
- /**
456
- * Get MCP settings directory for an agent
457
- */
458
- declare function getMcpSettingsDir(agentType: AgentType): string;
459
-
460
- interface ManagedSecretRef {
461
- name: string;
462
- as?: string;
463
- }
464
- interface ManagedSecretMetadata {
465
- id: string;
466
- name: string;
467
- allowedHosts: string[];
468
- allowedPathPrefixes: string[];
469
- allowedMethods: string[];
470
- createdAt: string;
471
- updatedAt: string;
472
- lastUsedAt: string | null;
473
- }
474
- interface ManagedSecretsClientConfig {
475
- apiKey?: string;
476
- dashboardUrl?: string;
477
- }
478
- interface ManagedSecretsClient {
479
- list(): Promise<ManagedSecretMetadata[]>;
480
- }
481
- declare function managedSecrets(config?: ManagedSecretsClientConfig): ManagedSecretsClient;
482
-
483
- /** Result of a completed sandbox command */
484
- interface SandboxCommandResult {
485
- exitCode: number;
486
- stdout: string;
487
- stderr: string;
488
- }
489
- /** Handle to a running background process in sandbox */
490
- interface SandboxCommandHandle {
491
- readonly processId: string;
492
- wait(): Promise<SandboxCommandResult>;
493
- kill(): Promise<boolean>;
494
- }
495
- /** Information about a running process */
496
- interface ProcessInfo {
497
- processId: string;
498
- cmd: string;
499
- args: string[];
500
- envs: Record<string, string>;
501
- cwd?: string;
502
- tag?: string;
503
- }
504
- /** Options for command execution */
505
- interface SandboxRunOptions {
506
- timeoutMs?: number;
507
- envs?: Record<string, string>;
508
- cwd?: string;
509
- onStdout?: (data: string) => void;
510
- onStderr?: (data: string) => void;
511
- }
512
- /** Options for spawning background processes in sandbox */
513
- interface SandboxSpawnOptions extends SandboxRunOptions {
514
- stdin?: boolean;
515
- }
516
- /** Options for creating a sandbox */
517
- interface SandboxCreateOptions {
518
- /** Sandbox image/template ID. Provider uses its default if not specified. */
519
- image?: string;
520
- envs?: Record<string, string>;
521
- metadata?: Record<string, string>;
522
- timeoutMs?: number;
523
- workingDirectory?: string;
524
- }
525
- /** Command execution capabilities */
526
- interface SandboxCommands {
527
- run(command: string, options?: SandboxRunOptions): Promise<SandboxCommandResult>;
528
- spawn(command: string, options?: SandboxSpawnOptions): Promise<SandboxCommandHandle>;
529
- list(): Promise<ProcessInfo[]>;
530
- kill(processId: string): Promise<boolean>;
531
- }
532
- /** File system operations */
533
- interface SandboxFiles {
534
- read(path: string): Promise<string | Uint8Array>;
535
- write(path: string, content: string | Buffer | ArrayBuffer | Uint8Array): Promise<void>;
536
- writeBatch(files: Array<{
537
- path: string;
538
- data: string | Buffer | ArrayBuffer | Uint8Array;
539
- }>): Promise<void>;
540
- makeDir(path: string): Promise<void>;
541
- }
542
- /** Sandbox instance */
543
- interface SandboxInstance {
544
- readonly sandboxId: string;
545
- readonly commands: SandboxCommands;
546
- readonly files: SandboxFiles;
547
- /** Get host URL for a port */
548
- getHost(port: number): Promise<string>;
549
- kill(): Promise<void>;
550
- pause(): Promise<void>;
551
- }
552
- /** Sandbox lifecycle management - providers implement this */
553
- interface SandboxProvider {
554
- /** Provider type identifier (e.g., "e2b") */
555
- readonly providerType: string;
556
- /** Human-readable provider name for logging */
557
- readonly name?: string;
558
- create(options: SandboxCreateOptions): Promise<SandboxInstance>;
559
- connect(sandboxId: string, timeoutMs?: number): Promise<SandboxInstance>;
560
- }
561
- /** Supported agent types (headless CLI agents only, no ACP) */
562
- type AgentType = "claude" | "codex" | "gemini" | "qwen" | "kimi" | "opencode" | "droid";
563
- /** Agent type constants for use in code */
564
- declare const AGENT_TYPES: {
565
- readonly CLAUDE: "claude";
566
- readonly CODEX: "codex";
567
- readonly GEMINI: "gemini";
568
- readonly QWEN: "qwen";
569
- readonly KIMI: "kimi";
570
- readonly OPENCODE: "opencode";
571
- readonly DROID: "droid";
572
- };
573
- /** Workspace mode determines folder structure and system prompt */
574
- type WorkspaceMode = "knowledge" | "swe";
575
- /** Available skills that can be enabled */
576
- type SkillName = "pdf" | "dev-browser" | (string & {});
577
- /** Browser automation providers that can be enabled explicitly */
578
- type BrowserProvider = "browser-use" | "actionbook" | "agent-browser";
579
- /** Browser providers backed by Evolve-managed browser transport. */
580
- type ManagedBrowserProvider = "actionbook" | "agent-browser";
581
- /** Actionbook browser configuration. */
582
- interface ActionbookBrowserConfig {
583
- provider: "actionbook";
584
- /** Use Evolve-managed remote browser transport. Defaults to false for object config. */
585
- remote?: boolean;
586
- /** Reusable provider-native browser profile for managed remote browser sessions. */
587
- profile?: string;
588
- }
589
- /** Agent-browser browser configuration. */
590
- interface AgentBrowserConfig {
591
- provider: "agent-browser";
592
- /** Use Evolve-managed remote browser transport. Defaults to false for object config. */
593
- remote?: boolean;
594
- /** Reusable provider-native browser profile for managed remote browser sessions. */
595
- profile?: string;
596
- }
597
- /** Default managed browser configuration. */
598
- interface DefaultBrowserConfig {
599
- provider?: undefined;
600
- /** Defaults to true for the default managed agent-browser path. */
601
- remote?: boolean;
602
- /** Reusable provider-native browser profile for managed remote browser sessions. */
603
- profile?: string;
604
- }
605
- /** Browser automation configuration. */
606
- type BrowserConfig = BrowserProvider | DefaultBrowserConfig | ActionbookBrowserConfig | AgentBrowserConfig;
607
- /** Saved browser login selector exposed to a run. Empty/omitted means all enabled browser logins. */
608
- interface BrowserCredentialScopeEntry {
609
- website: string;
610
- /** One-word label for the saved credential, such as "qa-admin" or "work"; not the website username or email. */
611
- accountLabel?: string;
612
- /** Python bridge wire shape. Prefer accountLabel in TypeScript. */
613
- account_label?: string;
614
- }
615
- /** Browser login MCP configuration for managed remote agent-browser runs. */
616
- interface BrowserCredentialsConfig {
617
- allow?: BrowserCredentialScopeEntry[];
618
- }
619
- /** Marketplace plugin shape for CLIs with explicit plugin install commands. */
620
- interface MarketplaceAgentPluginConfig {
621
- /** Marketplace URL/source to register in the sandbox user profile */
622
- marketplace: string;
623
- /** Plugin identifier, usually plugin@marketplace */
624
- plugin: string;
625
- }
626
- /** Gemini extension install shape. */
627
- interface GeminiAgentPluginConfig {
628
- /** GitHub URL or local path for the extension */
629
- source: string;
630
- /** Optional git ref to install */
631
- ref?: string;
632
- /** Enable extension auto-update */
633
- autoUpdate?: boolean;
634
- /** Enable pre-release versions */
635
- preRelease?: boolean;
636
- /** Skip extension settings prompts during install */
637
- skipSettings?: boolean;
638
- }
639
- /** Codex marketplace registration shape. */
640
- interface CodexAgentPluginConfig {
641
- /** Marketplace source to register */
642
- marketplace: string;
643
- /** Optional git ref to pin */
644
- ref?: string;
645
- /** Optional sparse checkout paths for Git-backed marketplaces */
646
- sparse?: string[];
647
- }
648
- /** Agent plugin/extension config. Shape is validated against the selected agent at runtime. */
649
- type AgentPluginConfig = MarketplaceAgentPluginConfig | GeminiAgentPluginConfig | CodexAgentPluginConfig;
650
- /** Skills configuration for an agent */
651
- interface SkillsConfig {
652
- /** Source directory where skills are staged */
653
- sourceDir: string;
654
- /** Target directory where skills are copied for this CLI */
655
- targetDir: string;
656
- }
657
- /** Reasoning effort for CLIs/models that support it; valid values vary by model. */
658
- type ReasoningEffort = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max" | "thinking" | "no-thinking";
659
- /** MCP Server Configuration */
660
- interface McpServerConfig {
661
- command?: string;
662
- args?: string[];
663
- cwd?: string;
664
- url?: string;
665
- env?: Record<string, string>;
666
- headers?: Record<string, string>;
667
- bearerTokenEnvVar?: string;
668
- httpHeaders?: Record<string, string>;
669
- envHttpHeaders?: Record<string, string>;
670
- envVars?: string[];
671
- type?: "stdio" | "sse" | "http";
672
- }
673
- /** File map for uploads/downloads: { "filename.txt": content } */
674
- type FileMap = Record<string, string | Buffer | ArrayBuffer | Uint8Array>;
675
- /**
676
- * JSON Schema object (draft-07 compatible)
677
- *
678
- * Use this when you want to pass a raw JSON Schema instead of a Zod schema.
679
- * JSON Schema allows runtime validation modes via SchemaValidationOptions.
680
- */
681
- type JsonSchema = Record<string, unknown>;
682
- /**
683
- * Validation mode presets for JSON Schema validation
684
- *
685
- * - strict: Exact type matching, fail on any mismatch, no defaults filled
686
- * - loose: Aggressive coercion (string↔number, null→empty values), fill defaults (default)
687
- *
688
- * Null handling (when schema expects string/number/boolean):
689
- * - strict: Validation fails
690
- * - loose: null→"" (string), null→0 (number), null→false (boolean)
691
- *
692
- * Note: These modes only apply to JSON Schema. Zod schemas define their own
693
- * strictness via .passthrough(), .strip(), z.coerce, etc.
694
- */
695
- type ValidationMode = "strict" | "loose";
696
- /**
697
- * Options for JSON Schema validation (Ajv options)
698
- *
699
- * Either use a preset mode or provide individual options.
700
- * Individual options override the preset if both provided.
701
- */
702
- interface SchemaValidationOptions {
703
- /** Preset validation mode (applied first, then individual options override). Default: "loose" */
704
- mode?: ValidationMode;
705
- /** Coerce types. false=none, true=basic (string↔number), "array"=aggressive (incl. null→empty). Default: false */
706
- coerceTypes?: boolean | "array";
707
- /** Remove properties not in schema. true | 'all' | 'failing'. Default: false */
708
- removeAdditional?: boolean | "all" | "failing";
709
- /** Fill in default values from schema. Default: true */
710
- useDefaults?: boolean;
711
- /** Collect all errors vs stop at first. Default: true */
712
- allErrors?: boolean;
713
- }
714
- /**
715
- * Validation mode preset definitions
716
- */
717
- declare const VALIDATION_PRESETS: Record<ValidationMode, Required<Omit<SchemaValidationOptions, "mode">>>;
718
- /** Configuration passed to withAgent() */
719
- interface AgentConfig {
720
- /** Agent type (default: "claude") */
721
- type?: AgentType;
722
- /** Evolve API key for gateway mode (default: EVOLVE_API_KEY env var) */
723
- apiKey?: string;
724
- /** Provider API key for direct mode / BYOK (default: provider env var) */
725
- providerApiKey?: string;
726
- /** OAuth token for Claude Max subscription (default: CLAUDE_CODE_OAUTH_TOKEN env var) */
727
- oauthToken?: string;
728
- /** Provider base URL for direct mode (default: provider env var or registry default) */
729
- providerBaseUrl?: string;
730
- /** Model to use (optional, uses agent's default if omitted) */
731
- model?: string;
732
- /** Reasoning effort for models that support it */
733
- reasoningEffort?: ReasoningEffort;
734
- }
735
- /** Resolved agent config (output of resolution, not an extension of input) */
736
- interface ResolvedAgentConfig {
737
- type: AgentType;
738
- apiKey: string;
739
- baseUrl?: string;
740
- isDirectMode: boolean;
741
- isOAuth?: boolean;
742
- /** File content for file-based OAuth (Codex) */
743
- oauthFileContent?: string;
744
- model?: string;
745
- reasoningEffort?: ReasoningEffort;
746
- }
747
- /** Options for Agent constructor */
748
- interface AgentOptions {
749
- /** Sandbox provider (e.g., E2B) */
750
- sandboxProvider?: SandboxProvider;
751
- /** Additional environment secrets */
752
- secrets?: Record<string, string>;
753
- /** Dashboard-stored managed secrets exposed through opaque env vars. */
754
- managedSecrets?: {
755
- secrets: ManagedSecretRef[];
756
- apiKey: string;
757
- dashboardUrl?: string;
758
- };
759
- /** Existing sandbox ID to connect to */
760
- sandboxId?: string;
761
- /** Working directory path */
762
- workingDirectory?: string;
763
- /** Workspace mode */
764
- workspaceMode?: WorkspaceMode;
765
- /** Custom system prompt (appended to workspace template in both modes) */
766
- systemPrompt?: string;
767
- /** Context files (uploaded to context/ folder) */
768
- context?: FileMap;
769
- /** Workspace files (uploaded to working directory) */
770
- files?: FileMap;
771
- /** MCP server configurations */
772
- mcpServers?: Record<string, McpServerConfig>;
773
- /** Runtime browser prompt fragment appended to the agent system prompt */
774
- browserPrompt?: string;
775
- /** Evolve-managed browser transport for browser automation */
776
- managedBrowser?: {
777
- provider: ManagedBrowserProvider;
778
- apiKey: string;
779
- dashboardUrl?: string;
780
- profile?: string;
781
- };
782
- /** Run-scoped browser login MCP setup. Requires managed remote agent-browser. */
783
- browserCredentials?: {
784
- apiKey: string;
785
- dashboardUrl?: string;
786
- config?: BrowserCredentialsConfig;
787
- };
788
- /** Evolve-managed app integrations */
789
- integrations?: IntegrationsSetup & {
790
- apiKey: string;
791
- dashboardUrl?: string;
792
- };
793
- /** Evolve-managed provider routing tokens for dashboard-stored BYOK provider keys. */
794
- providerRouting?: {
795
- apiKey: string;
796
- dashboardUrl?: string;
797
- };
798
- /** Plugins/extensions to install in the sandbox user profile before first run */
799
- plugins?: AgentPluginConfig[];
800
- /** Skills to enable (e.g., ["pdf", "dev-browser"]) */
801
- skills?: SkillName[];
802
- /**
803
- * Schema for structured output validation
804
- *
805
- * Accepts either:
806
- * - Zod schema: z.object({ ... }) - validated with Zod's safeParse
807
- * - JSON Schema: { type: "object", properties: { ... } } - validated with Ajv
808
- *
809
- * Auto-detected based on presence of .safeParse method.
810
- */
811
- schema?: zod.ZodType<unknown> | JsonSchema;
812
- /**
813
- * Validation options for JSON Schema (ignored for Zod schemas)
814
- *
815
- * Use preset modes or individual Ajv options.
816
- *
817
- * @example
818
- * // Preset mode
819
- * schemaOptions: { mode: 'loose' }
820
- *
821
- * // Individual options
822
- * schemaOptions: { coerceTypes: true, useDefaults: true }
823
- */
824
- schemaOptions?: SchemaValidationOptions;
825
- /** Session tag prefix (default: "evolve") */
826
- sessionTagPrefix?: string;
827
- /** Observability metadata for trace grouping (generic key-value, domain-agnostic) */
828
- observability?: Record<string, unknown>;
829
- /** Resolved storage configuration (set via Evolve.withStorage()) */
830
- storage?: ResolvedStorageConfig;
831
- }
832
- /** Options for run() */
833
- interface RunOptions {
834
- /** The prompt to send to the agent */
835
- prompt: string;
836
- /** Timeout in milliseconds (default: 1 hour) */
837
- timeoutMs?: number;
838
- /** Run in background (returns immediately, process continues) */
839
- background?: boolean;
840
- /** Restore from checkpoint ID or "latest" before running (requires .withStorage()) */
841
- from?: string;
842
- /** Optional comment for the auto-checkpoint created after this run */
843
- checkpointComment?: string;
844
- }
845
- /** Options for executeCommand() */
846
- interface ExecuteCommandOptions {
847
- /** Timeout in milliseconds (default: 1 hour) */
848
- timeoutMs?: number;
849
- /** Run in background (default: false) */
850
- background?: boolean;
851
- }
852
- /** High-level sandbox lifecycle state */
853
- type SandboxLifecycleState = "booting" | "error" | "ready" | "running" | "paused" | "stopped";
854
- /** High-level agent runtime state */
855
- type AgentRuntimeState = "idle" | "running" | "interrupted" | "error";
856
- /** Lifecycle transition reason */
857
- type LifecycleReason = "browser_ready" | "sandbox_boot" | "sandbox_connected" | "sandbox_ready" | "sandbox_pause" | "sandbox_resume" | "sandbox_killed" | "sandbox_error" | "run_start" | "run_complete" | "run_interrupted" | "run_failed" | "run_background_complete" | "run_background_failed" | "command_start" | "command_complete" | "command_interrupted" | "command_failed" | "command_background_complete" | "command_background_failed";
858
- /** Browser runtime info exposed to host applications. */
859
- interface BrowserRuntimeInfo {
860
- liveUrl: string;
861
- /** Dashboard session ID for trace/replay APIs, present for managed browsers. */
862
- sessionId?: string;
863
- /** Session tag for checkpoint correlation, present for managed browsers. */
864
- sessionTag?: string;
865
- }
866
- /** Lifecycle event emitted by the runtime */
867
- interface LifecycleEvent {
868
- sandboxId: string | null;
869
- sandbox: SandboxLifecycleState;
870
- agent: AgentRuntimeState;
871
- timestamp: string;
872
- reason: LifecycleReason;
873
- browser?: BrowserRuntimeInfo;
874
- }
875
- /** Snapshot of current runtime status */
876
- interface SessionStatus {
877
- sandboxId: string | null;
878
- sandbox: SandboxLifecycleState;
879
- agent: AgentRuntimeState;
880
- activeProcessId: string | null;
881
- hasRun: boolean;
882
- timestamp: string;
883
- browser?: BrowserRuntimeInfo;
884
- }
885
- /** Response from run() and executeCommand() */
886
- interface AgentResponse {
887
- /** Sandbox ID for session management */
888
- sandboxId: string;
889
- /** Dashboard session ID for trace/replay APIs, present in gateway mode when known. */
890
- sessionId?: string;
891
- /** Managed browser runtime info, present when a remote browser is configured. */
892
- browser?: Pick<BrowserRuntimeInfo, "liveUrl">;
893
- /** Run ID for spend/cost attribution (present for run(), undefined for executeCommand()) */
894
- runId?: string;
895
- /** Exit code of the command */
896
- exitCode: number;
897
- /** Standard output */
898
- stdout: string;
899
- /** Standard error */
900
- stderr: string;
901
- /** Checkpoint info if storage configured and run succeeded (undefined otherwise) */
902
- checkpoint?: CheckpointInfo;
903
- }
904
- /** Cost breakdown for a single run() invocation */
905
- interface RunCost {
906
- /** Run ID matching AgentResponse.runId */
907
- runId: string;
908
- /** 1-based chronological position in session */
909
- index: number;
910
- /** Total cost in USD (includes platform margin) */
911
- cost: number;
912
- /** Token counts */
913
- tokens: {
914
- prompt: number;
915
- completion: number;
916
- };
917
- /** Model used (e.g., "claude-opus-4-8"). Last observed model if multiple models used in a run. */
918
- model: string;
919
- /** Number of LLM API requests in this run */
920
- requests: number;
921
- /** ISO timestamp when this data was fetched */
922
- asOf: string;
923
- /** False if recent LLM calls may still be batching (~60s delay) */
924
- isComplete: boolean;
925
- /** True if spend log pagination was capped — totals may be understated */
926
- truncated: boolean;
927
- }
928
- /** Cost breakdown for an entire agent session (all runs) */
929
- interface SessionCost {
930
- /** Session tag matching agent.getSessionTag() */
931
- sessionTag: string;
932
- /** Total cost across all runs in USD */
933
- totalCost: number;
934
- /** Aggregate token counts */
935
- totalTokens: {
936
- prompt: number;
937
- completion: number;
938
- };
939
- /** Per-run breakdown, chronological order */
940
- runs: RunCost[];
941
- /** ISO timestamp when this data was fetched */
942
- asOf: string;
943
- /** False if session is still active or recently ended */
944
- isComplete: boolean;
945
- /** True if spend log pagination was capped — totals may be understated */
946
- truncated: boolean;
947
- }
948
- /** Result from getOutputFiles() with optional schema validation */
949
- interface OutputResult<T = unknown> {
950
- /** Output files from output/ folder */
951
- files: FileMap;
952
- /** Parsed and validated result.json data (null if no schema or validation failed) */
953
- data: T | null;
954
- /** Validation or parse error message, if any */
955
- error?: string;
956
- /** Raw result.json string when parse or validation failed (for debugging) */
957
- rawData?: string;
958
- }
959
- /** Callbacks for streaming output */
960
- interface StreamCallbacks {
961
- /** Called for each stdout chunk */
962
- onStdout?: (data: string) => void;
963
- /** Called for each stderr chunk */
964
- onStderr?: (data: string) => void;
965
- /** Called for each parsed content event */
966
- onContent?: (event: OutputEvent) => void;
967
- /** Called for sandbox/agent lifecycle transitions */
968
- onLifecycle?: (event: LifecycleEvent) => void;
969
- }
970
- /**
971
- * Configuration for managed integrations.
972
- */
973
- /** Tool filter configuration per app */
974
- type IntegrationToolsFilter = string[] | {
975
- enable: string[];
976
- } | {
977
- disable: string[];
978
- } | {
979
- tags: string[];
980
- };
981
- interface IntegrationsConfig {
982
- /**
983
- * Apps to expose to the agent.
984
- *
985
- * @example
986
- * apps: ["github", "gmail", "linear"]
987
- */
988
- apps: string[];
989
- /**
990
- * Per-app tool filtering.
991
- *
992
- * @example
993
- * tools: {
994
- * github: { enable: ["github_create_issue", "github_list_repos"] },
995
- * gmail: { disable: ["gmail_delete_email"] },
996
- * slack: { tags: ["readOnlyHint"] }
997
- * }
998
- */
999
- tools?: Record<string, IntegrationToolsFilter>;
1000
- /**
1001
- * Pin specific connected accounts by account ID or account label.
1002
- */
1003
- accounts?: Record<string, string[]>;
1004
- /**
1005
- * API keys for apps that use API-key auth.
1006
- * Requires a matching authConfigs entry for each app.
1007
- */
1008
- keys?: Record<string, string>;
1009
- /**
1010
- * Custom auth config IDs per app.
1011
- */
1012
- authConfigs?: Record<string, string>;
1013
- }
1014
- /**
1015
- * Managed integrations setup.
1016
- */
1017
- interface IntegrationsSetup extends IntegrationsConfig {
1018
- /**
1019
- * Integration user ID. Use "root" for dashboard-owned/private accounts,
1020
- * or your app's stable end-user ID for per-user accounts.
1021
- */
1022
- userId: string;
1023
- }
1024
- /**
1025
- * Storage configuration for .withStorage()
1026
- *
1027
- * BYOK mode: provide url (e.g., "s3://my-bucket/prefix/")
1028
- * Gateway mode: omit url (uses Evolve-managed storage)
1029
- *
1030
- * @example
1031
- * // BYOK — user's own S3 bucket
1032
- * .withStorage({ url: "s3://my-bucket/agent-snapshots/" })
1033
- *
1034
- * // BYOK — Cloudflare R2
1035
- * .withStorage({ url: "s3://my-bucket/prefix/", endpoint: "https://acct.r2.cloudflarestorage.com" })
1036
- *
1037
- * // Gateway — Evolve-managed storage
1038
- * .withStorage()
1039
- */
1040
- interface StorageConfig {
1041
- /** S3 URL: "s3://bucket/prefix" or "https://endpoint/bucket/prefix" */
1042
- url?: string;
1043
- /** Explicit bucket name (overrides URL parsing) */
1044
- bucket?: string;
1045
- /** Key prefix (overrides URL parsing) */
1046
- prefix?: string;
1047
- /** AWS region (default from env or us-east-1) */
1048
- region?: string;
1049
- /** Custom S3 endpoint (R2, MinIO, GCS) */
1050
- endpoint?: string;
1051
- /** Explicit credentials (default: AWS SDK credential chain) */
1052
- credentials?: {
1053
- accessKeyId: string;
1054
- secretAccessKey: string;
1055
- };
1056
- }
1057
- /** Resolved storage configuration (internal) */
1058
- interface ResolvedStorageConfig {
1059
- bucket: string;
1060
- prefix: string;
1061
- region: string;
1062
- endpoint?: string;
1063
- credentials?: {
1064
- accessKeyId: string;
1065
- secretAccessKey: string;
1066
- };
1067
- mode: "byok" | "gateway";
1068
- gatewayUrl?: string;
1069
- gatewayApiKey?: string;
1070
- }
1071
- /**
1072
- * Checkpoint info returned after a successful run
1073
- *
1074
- * Pass `checkpoint.id` as `from` to restore into a fresh sandbox.
1075
- */
1076
- interface CheckpointInfo {
1077
- /** Checkpoint ID — pass as `from` to restore */
1078
- id: string;
1079
- /** SHA-256 of tar.gz — integrity verification */
1080
- hash: string;
1081
- /** Session tag at checkpoint time — lineage tracking */
1082
- tag: string;
1083
- /** ISO 8601 timestamp */
1084
- timestamp: string;
1085
- /** Archive size in bytes */
1086
- sizeBytes?: number;
1087
- /** Agent type that produced this checkpoint */
1088
- agentType?: string;
1089
- /** Model that produced this checkpoint */
1090
- model?: string;
1091
- /** Workspace mode used when checkpoint was created */
1092
- workspaceMode?: string;
1093
- /** Parent checkpoint ID — the checkpoint this was restored from (lineage tracking) */
1094
- parentId?: string;
1095
- /** User-provided label for this checkpoint */
1096
- comment?: string;
1097
- }
1098
- /** Options for StorageClient.downloadCheckpoint() */
1099
- interface DownloadCheckpointOptions {
1100
- /** Local directory to save to (default: current working directory) */
1101
- to?: string;
1102
- /** Extract the archive (default: true). If false, saves the raw .tar.gz file. */
1103
- extract?: boolean;
1104
- }
1105
- /** Options for StorageClient.downloadFiles() */
1106
- interface DownloadFilesOptions {
1107
- /** Specific file paths to extract (relative to archive root, e.g., "workspace/output/result.json") */
1108
- files?: string[];
1109
- /** Glob patterns to match files (e.g., ["workspace/output/*.json"]) */
1110
- glob?: string[];
1111
- /** Local directory to save files to. If omitted, files are returned in-memory only. */
1112
- to?: string;
1113
- }
1114
- /**
1115
- * Storage client for browsing and fetching checkpoints without an Evolve instance.
1116
- *
1117
- * @example
1118
- * const s = storage({ url: "s3://my-bucket/prefix/" });
1119
- * const checkpoints = await s.listCheckpoints({ tag: "poker-agent" });
1120
- * const files = await s.downloadFiles("latest", { glob: ["workspace/output/*.json"] });
1121
- */
1122
- interface StorageClient {
1123
- /** List checkpoints with optional filtering */
1124
- listCheckpoints(options?: {
1125
- limit?: number;
1126
- tag?: string;
1127
- }): Promise<CheckpointInfo[]>;
1128
- /** Get a specific checkpoint's metadata by ID */
1129
- getCheckpoint(id: string): Promise<CheckpointInfo>;
1130
- /** Download an entire checkpoint archive. Returns the output path. */
1131
- downloadCheckpoint(idOrLatest: string, options?: DownloadCheckpointOptions): Promise<string>;
1132
- /** Download files from a checkpoint as a FileMap. */
1133
- downloadFiles(idOrLatest: string, options?: DownloadFilesOptions): Promise<FileMap>;
1134
- }
1135
-
1136
- interface IntegrationAuthParams {
1137
- userId: string;
1138
- app: string;
1139
- accountLabel?: string;
1140
- apiKey?: string;
1141
- dashboardUrl?: string;
1142
- }
1143
- interface IntegrationAuthResult {
1144
- url: string;
1145
- accountId?: string;
1146
- }
1147
- interface IntegrationAccount {
1148
- userId: string;
1149
- app: string;
1150
- appName?: string;
1151
- appIcon?: string;
1152
- accountLabel?: string;
1153
- status: string;
1154
- accountId?: string;
1155
- updatedAt?: string;
1156
- }
1157
- interface IntegrationAccountListParams {
1158
- userIds: string[];
1159
- app?: string;
1160
- statuses?: string[];
1161
- apiKey?: string;
1162
- dashboardUrl?: string;
1163
- }
1164
- interface IntegrationAccountUpdateParams {
1165
- accountId: string;
1166
- accountLabel?: string;
1167
- apiKey?: string;
1168
- dashboardUrl?: string;
1169
- }
1170
- interface IntegrationAccountDeleteParams {
1171
- accountId: string;
1172
- apiKey?: string;
1173
- dashboardUrl?: string;
1174
- }
1175
- interface IntegrationAccountUpdateResult {
1176
- success: boolean;
1177
- accountId: string;
1178
- accountLabel?: string;
1179
- }
1180
- interface IntegrationAccountDeleteResult {
1181
- success: boolean;
1182
- accountId: string;
1183
- }
1184
-
1185
- /**
1186
- * Unified Agent Implementation
1187
- *
1188
- * Single Agent class that uses registry lookup for agent-specific behavior.
1189
- * All agent differences are data (in registry), not code.
1190
- *
1191
- * Evidence: sdk-rewrite-v3.md Design Decisions section
1192
- */
1193
-
1194
- /**
1195
- * Unified Agent class
1196
- *
1197
- * Uses registry lookup for agent-specific behavior.
1198
- * Tracks hasRun state for continue flag handling.
1199
- */
1200
- declare class Agent {
1201
- private agentConfig;
1202
- private options;
1203
- private sandbox?;
1204
- private hasRun;
1205
- private readonly workingDir;
1206
- private lastRunTimestamp?;
1207
- private readonly registry;
1208
- /** Unified session ID — used for both observability (SessionLogger) and spend tracking (LiteLLM customer-id) */
1209
- private sessionTag;
1210
- /** Previous session tag — preserved across kill()/setSession() so cost queries still work */
1211
- private previousSessionTag?;
1212
- private sessionLogger?;
1213
- private activeCommand?;
1214
- private activeProcessId;
1215
- private activeOperationId;
1216
- private activeOperationKind;
1217
- private nextOperationId;
1218
- private interruptedOperations;
1219
- private sandboxState;
1220
- private agentState;
1221
- private droidSessionId?;
1222
- private managedBrowserSession?;
1223
- private providerRuntimeToken?;
1224
- private managedSecretRuntimeToken?;
1225
- private managedSecretProxy?;
1226
- private readonly skills?;
1227
- private readonly storage?;
1228
- private lastCheckpointId?;
1229
- private readonly zodSchema?;
1230
- private readonly jsonSchema?;
1231
- private readonly schemaOptions?;
1232
- private readonly compiledValidator?;
1233
- constructor(agentConfig: ResolvedAgentConfig, options?: AgentOptions);
1234
- private browserRuntimeInfo;
1235
- private browserResponseInfo;
1236
- private emitLifecycle;
1237
- private invalidateActiveOperation;
1238
- private beginOperation;
1239
- private finalizeOperation;
1240
- private watchBackgroundOperation;
1241
- /**
1242
- * Create Ajv validator instance with configured options
1243
- */
1244
- private createAjvValidator;
1245
- /**
1246
- * Get or create sandbox instance
1247
- */
1248
- getSandbox(callbacks?: StreamCallbacks): Promise<SandboxInstance>;
1249
- /**
1250
- * Build environment variables for sandbox
1251
- */
1252
- private buildEnvironmentVariables;
1253
- private validatedUserSecretsForEnvironment;
1254
- private ensureManagedBrowserSession;
1255
- private ensureProviderRuntimeToken;
1256
- private bindProviderRuntimeToken;
1257
- private setupManagedBrowser;
1258
- private closeManagedBrowserSession;
1259
- private closeProviderRuntimeToken;
1260
- private ensureManagedSecretRuntimeToken;
1261
- private bindManagedSecretRuntimeToken;
1262
- private setupManagedSecretEgress;
1263
- private closeManagedSecretRuntimeToken;
1264
- /**
1265
- * Build the inline gateway config JSON for agents using gatewayConfigEnv
1266
- * (e.g., OpenCode OPENCODE_CONFIG_CONTENT). Centralizes the provider config
1267
- * so buildEnvironmentVariables() and buildRunEnvs() don't duplicate it.
1268
- *
1269
- * Deep-merges with user-provided config from secrets (if any) so that
1270
- * non-litellm providers, plugins, and other settings are preserved.
1271
- * Only patches provider.litellm.models[selectedModel].headers and selected variant metadata.
1272
- *
1273
- * Source-verified: model.headers → provider.ts:1061 → llm.ts:221 → HTTP request.
1274
- */
1275
- private buildGatewayConfigJson;
1276
- private activeProviderRuntimeToken;
1277
- private requireActiveProviderRuntimeToken;
1278
- private ensureSessionLogger;
1279
- private flushSessionLoggerWithTimeout;
1280
- private requiresPreRunDashboardIngest;
1281
- private providerRuntimeHeaderUpdates;
1282
- private shouldExposeProviderRuntimeTokenEnv;
1283
- private buildProviderRuntimeProcessEnvs;
1284
- /**
1285
- * Build per-run env overrides for spend tracking.
1286
- * Merges session + run headers into the custom headers env var,
1287
- * or sets per-env-var values for agents using spendTrackingEnvs.
1288
- * Passed to spawn() so each .run() gets a unique run tag.
1289
- */
1290
- private buildRunEnvs;
1291
- private writeCodexGatewayProviderConfig;
1292
- private captureDroidSession;
1293
- private extractDroidSessionId;
1294
- private findDroidSessionId;
1295
- private loadDroidSessionState;
1296
- private writeDroidSessionState;
1297
- private resolveGatewayModel;
1298
- private resolveCommandModel;
1299
- /**
1300
- * Agent-specific authentication setup
1301
- */
1302
- private setupAgentAuth;
1303
- private writeGeminiGatewayAuthSettings;
1304
- private setupAgentPlugins;
1305
- private assertProviderRuntimeDoesNotExposeGatewayKey;
1306
- /**
1307
- * Setup workspace structure and files
1308
- *
1309
- * @param opts.skipSystemPrompt - When true, skip writing the system prompt file.
1310
- * Used on restore from checkpoint: the tar already contains the correct file.
1311
- */
1312
- private setupWorkspace;
1313
- /**
1314
- * Setup skills for the agent
1315
- *
1316
- * Copies selected skills from source (~/.evolve/skills/) to CLI-specific directory.
1317
- * All CLIs use the same pattern: skills are auto-discovered from their target directory.
1318
- */
1319
- private setupSkills;
1320
- /**
1321
- * Upload context files to context/ folder
1322
- */
1323
- private uploadContextFiles;
1324
- /**
1325
- * Upload workspace files to working directory
1326
- */
1327
- private uploadWorkspaceFiles;
1328
- /**
1329
- * Build the CLI command for running the agent
1330
- */
1331
- private buildCommand;
1332
- /**
1333
- * Run agent with prompt
1334
- *
1335
- * Streams output via callbacks, returns final response.
1336
- */
1337
- run(options: RunOptions, callbacks?: StreamCallbacks): Promise<AgentResponse>;
1338
- /**
1339
- * Execute arbitrary command in sandbox
1340
- */
1341
- executeCommand(command: string, options?: ExecuteCommandOptions, callbacks?: StreamCallbacks): Promise<AgentResponse>;
1342
- /**
1343
- * Upload context files (to context/ folder)
1344
- */
1345
- uploadContext(files: FileMap): Promise<void>;
1346
- /**
1347
- * Upload files to working directory
1348
- */
1349
- uploadFiles(files: FileMap): Promise<void>;
1350
- /**
1351
- * Get output files from output/ folder with optional schema validation
1352
- *
1353
- * Returns files modified after the last run() call.
1354
- * If schema was provided, validates result.json and returns typed data.
1355
- *
1356
- * @param recursive - Include files in subdirectories (default: false)
1357
- */
1358
- getOutputFiles<T = unknown>(recursive?: boolean): Promise<OutputResult<T>>;
1359
- /**
1360
- * Create an explicit checkpoint of the current sandbox state.
1361
- *
1362
- * Requires an active sandbox (call run() first).
1363
- *
1364
- * @param options.comment - Optional label for this checkpoint
1365
- */
1366
- checkpoint(options?: {
1367
- comment?: string;
1368
- }): Promise<CheckpointInfo>;
1369
- /**
1370
- * Get current session (sandbox ID)
1371
- */
1372
- getSession(): string | null;
1373
- /**
1374
- * Set session (sandbox ID) to connect to
1375
- *
1376
- * When reconnecting to an existing sandbox, we assume the agent
1377
- * may have already run commands, so we set hasRun=true to use
1378
- * the continue/resume command template instead of first-run.
1379
- */
1380
- setSession(sandboxId: string): Promise<void>;
1381
- /**
1382
- * Pause sandbox
1383
- */
1384
- pause(callbacks?: StreamCallbacks): Promise<void>;
1385
- /**
1386
- * Resume sandbox
1387
- */
1388
- resume(callbacks?: StreamCallbacks): Promise<void>;
1389
- /**
1390
- * Interrupt active command without killing the sandbox.
1391
- */
1392
- interrupt(callbacks?: StreamCallbacks): Promise<boolean>;
1393
- /**
1394
- * Get current runtime status for sandbox and agent.
1395
- */
1396
- status(): SessionStatus;
1397
- /**
1398
- * Kill sandbox (terminates all processes)
1399
- */
1400
- kill(callbacks?: StreamCallbacks): Promise<void>;
1401
- /**
1402
- * Get host URL for a port
1403
- */
1404
- getHost(port: number): Promise<string>;
1405
- /**
1406
- * Get agent type
1407
- */
1408
- getAgentType(): AgentType;
1409
- /**
1410
- * Get current session tag.
1411
- * Returns null if no active session (before sandbox creation or after kill()).
1412
- * Used for both observability (dashboard traces) and spend tracking (LiteLLM customer-id).
1413
- */
1414
- getSessionTag(): string | null;
1415
- /**
1416
- * Get current session timestamp
1417
- *
1418
- * Returns null if no session has started (run() not called yet).
1419
- */
1420
- getSessionTimestamp(): string | null;
1421
- /**
1422
- * Flush pending observability events without closing the session.
1423
- */
1424
- flushObservability(): Promise<void>;
1425
- /**
1426
- * Tear down the session logger and rotate the session tag.
1427
- * Preserves `previousSessionTag` only if this session had actual activity,
1428
- * so a double kill() or no-op lifecycle call doesn't clobber the real tag.
1429
- * @internal
1430
- */
1431
- private rotateSession;
1432
- /**
1433
- * Fetch spend data from dashboard API.
1434
- * @internal
1435
- */
1436
- private fetchSpend;
1437
- /**
1438
- * Resolve the session tag for cost queries.
1439
- * Uses the active session tag, or falls back to the previous tag after kill()/setSession().
1440
- * @internal
1441
- */
1442
- private resolveSpendTag;
1443
- /**
1444
- * Normalize run payloads for compatibility with older dashboard responses.
1445
- * Older responses may omit `asOf`, `isComplete`, or `truncated` inside `runs[]`.
1446
- * @internal
1447
- */
1448
- private normalizeRunCost;
1449
- /**
1450
- * Normalize session payloads so all `runs[]` conform to `RunCost`.
1451
- * @internal
1452
- */
1453
- private normalizeSessionCost;
1454
- /**
1455
- * Get cost breakdown for the current session (all runs).
1456
- *
1457
- * Queries the dashboard API which proxies to LiteLLM spend logs.
1458
- * Cost data has ~60s latency due to gateway batch writes.
1459
- * Also works after kill() for the most recent session only.
1460
- *
1461
- * Requires gateway mode (EVOLVE_API_KEY).
1462
- */
1463
- getSessionCost(): Promise<SessionCost>;
1464
- /**
1465
- * Get cost for a specific run by ID or index.
1466
- *
1467
- * @param run - Either `{ runId: string }` or `{ index: number }` (1-based, negative = from end)
1468
- *
1469
- * Also works after kill() for the most recent session only.
1470
- * Requires gateway mode (EVOLVE_API_KEY).
1471
- */
1472
- getRunCost(run: {
1473
- runId: string;
1474
- } | {
1475
- index: number;
1476
- }): Promise<RunCost>;
1477
- }
1478
-
1479
- /**
1480
- * Claude JSONL → ACP-style events parser.
1481
- *
1482
- * Native schema source (@anthropic-ai/claude-agent-sdk):
1483
- * MANUS-API/KNOWLEDGE/claude-agent-sdk/cc_sdk_typescript.md
1484
- * (SDKMessage, SDKAssistantMessage, SDKPartialAssistantMessage, Tool Input/Output types)
1485
- *
1486
- * Conversion logic reference:
1487
- * MANUS-API/KNOWLEDGE/claude-code-acp/src/tools.ts
1488
- * (toolInfoFromToolUse, toolUpdateFromToolResult)
1489
- *
1490
- * ACP output schema:
1491
- * MANUS-API/KNOWLEDGE/acp-typescript-sdk/src/schema/types.gen.ts
1492
- */
1493
-
1494
- /**
1495
- * Create a Claude parser instance with its own isolated cache.
1496
- * Each Evolve instance should create its own parser for proper isolation.
1497
- */
1498
- declare function createClaudeParser(): (jsonLine: string) => OutputEvent[] | null;
1499
-
1500
- /**
1501
- * Codex JSONL → ACP-style events parser.
1502
- *
1503
- * Native schema: codex-rs/exec/src/exec_events.rs
1504
- * - ThreadEvent: thread.started, turn.started, turn.completed, item.started, item.updated, item.completed
1505
- * - ThreadItemDetails: AgentMessage, Reasoning, CommandExecution, FileChange, McpToolCall, WebSearch, TodoList, Error
1506
- *
1507
- * ACP output: acp-typescript-sdk/src/schema/types.gen.ts
1508
- * - SessionUpdate: agent_message_chunk, agent_thought_chunk, tool_call, tool_call_update, plan
1509
- *
1510
- * Event mapping:
1511
- * reasoning → agent_thought_chunk (exec_events.rs:134 ReasoningItem { text })
1512
- * agent_message → agent_message_chunk (exec_events.rs:129 AgentMessageItem { text })
1513
- * mcp_tool_call → tool_call/update (exec_events.rs:215 McpToolCallItem)
1514
- * command_execution → tool_call/update (exec_events.rs:151 CommandExecutionItem)
1515
- * file_change → tool_call (exec_events.rs:176 FileChangeItem)
1516
- * todo_list → plan (exec_events.rs:245 TodoListItem { items: TodoItem[] })
1517
- * web_search → tool_call (exec_events.rs:227 WebSearchItem { query })
1518
- */
1519
-
1520
- /**
1521
- * Create a Codex parser instance.
1522
- */
1523
- declare function createCodexParser(): (jsonLine: string) => OutputEvent[] | null;
1524
-
1525
- /**
1526
- * Droid exec parser.
1527
- *
1528
- * Supports the documented headless `--output-format stream-json` lines and the
1529
- * raw `stream-jsonrpc` notification envelope used by Droid's low-level SDK.
1530
- */
1531
-
1532
- declare function createDroidParser(): (jsonLine: string) => OutputEvent[] | null;
1533
-
1534
- /**
1535
- * Gemini JSONL → ACP-style events parser.
1536
- *
1537
- * Native schema (gemini --output-format stream-json):
1538
- * gemini-cli/packages/core/src/output/types.ts
1539
- *
1540
- * Gemini events (types.ts:29-36 JsonStreamEventType):
1541
- * - "init" → types.ts:43-47 InitEvent { session_id, model }
1542
- * - "message" → types.ts:49-54 MessageEvent { role, content, delta? }
1543
- * - "tool_use" → types.ts:56-61 ToolUseEvent { tool_name, tool_id, parameters }
1544
- * - "tool_result" → types.ts:63-72 ToolResultEvent { tool_id, status, output?, error? }
1545
- * - "error" → types.ts:74-78 ErrorEvent { severity, message }
1546
- * - "result" → types.ts:91-99 ResultEvent { status, error?, stats? }
1547
- *
1548
- * ACP output: acp-typescript-sdk/src/schema/types.gen.ts:2449-2464
1549
- */
1550
-
1551
- /**
1552
- * Create a Gemini parser instance.
1553
- */
1554
- declare function createGeminiParser(): (jsonLine: string) => OutputEvent[] | null;
1555
-
1556
- /**
1557
- * Qwen NDJSON → ACP-style events parser.
1558
- *
1559
- * Native schema: KNOWLEDGE/qwen-code/packages/sdk-typescript/src/types/protocol.ts
1560
- * ACP schema: KNOWLEDGE/acp-typescript-sdk/src/schema/types.gen.ts
1561
- *
1562
- * Qwen NDJSON message types (protocol.ts:428-433):
1563
- * - type: "assistant" → SDKAssistantMessage (protocol.ts:102-108)
1564
- * - type: "stream_event" → SDKPartialAssistantMessage (protocol.ts:225-231)
1565
- * - type: "user" → SDKUserMessage (protocol.ts:93-100)
1566
- * - type: "system" → SDKSystemMessage (skipped)
1567
- * - type: "result" → SDKResultMessage (skipped)
1568
- *
1569
- * ContentBlock types (protocol.ts:72-76):
1570
- * - TextBlock (protocol.ts:43-48): { type: 'text', text: string }
1571
- * - ThinkingBlock (protocol.ts:49-54): { type: 'thinking', thinking: string }
1572
- * - ToolUseBlock (protocol.ts:56-62): { type: 'tool_use', id, name, input }
1573
- * - ToolResultBlock (protocol.ts:64-70): { type: 'tool_result', tool_use_id, content?, is_error? }
1574
- *
1575
- * StreamEvent types (protocol.ts:218-223):
1576
- * - message_start, content_block_start, content_block_delta, content_block_stop, message_stop
1577
- */
1578
-
1579
- /**
1580
- * Stateless parser function (creates new parser per call).
1581
- * Use createQwenParser() for stateful streaming parsing.
1582
- *
1583
- * @param line - Single line of NDJSON from qwen CLI
1584
- * @returns Array of OutputEvent objects, or null if line couldn't be parsed
1585
- */
1586
- declare function parseQwenOutput(line: string): OutputEvent[] | null;
1587
-
1588
- /**
1589
- * Unified Parser Entry Point
1590
- *
1591
- * Routes NDJSON lines to the appropriate agent-specific parser.
1592
- * Simple line-based parsing - no buffering needed since CLIs output complete JSON per line.
1593
- */
1594
-
1595
- /** Parser function type */
1596
- type AgentParser = (jsonLine: string) => OutputEvent[] | null;
1597
- /**
1598
- * Create a parser instance for the given agent type.
1599
- * Each Evolve instance should create its own parser for proper isolation.
1600
- *
1601
- * @param agentType - The agent type to create a parser for
1602
- * @returns Parser function that takes NDJSON lines and returns OutputEvents
1603
- */
1604
- declare function createAgentParser(agentType: AgentType): AgentParser;
1605
- /**
1606
- * Parse a single NDJSON line from any agent (creates new parser per call - use createAgentParser for efficiency)
1607
- *
1608
- * @param agentType - The agent type to parse for
1609
- * @param line - Single line of NDJSON output
1610
- * @returns Array of OutputEvent objects, or null if line couldn't be parsed
1611
- */
1612
- declare function parseNdjsonLine(agentType: AgentType, line: string): OutputEvent[] | null;
1613
- /**
1614
- * Parse multiple NDJSON lines (convenience wrapper)
1615
- *
1616
- * @param agentType - The agent type to parse for
1617
- * @param output - Multi-line NDJSON output
1618
- * @returns Array of all parsed OutputEvent objects
1619
- */
1620
- declare function parseNdjsonOutput(agentType: AgentType, output: string): OutputEvent[];
1621
-
1622
- declare const BROWSER_LOGIN_MCP_SERVER_NAME = "browser-login";
1623
- interface BrowserCredentialMetadata {
1624
- id: string;
1625
- website: string;
1626
- accountLabel: string;
1627
- email: string;
1628
- enabled: boolean;
1629
- createdBy: string;
1630
- createdAt: string;
1631
- updatedAt: string;
1632
- lastUsedAt: string | null;
1633
- }
1634
- interface BrowserCredentialsClientConfig {
1635
- apiKey?: string;
1636
- dashboardUrl?: string;
1637
- }
1638
- interface BrowserCredentialCreateInput {
1639
- website: string;
1640
- accountLabel: string;
1641
- email: string;
1642
- password: string;
1643
- }
1644
- type BrowserCredentialDeleteInput = {
1645
- id: string;
1646
- } | {
1647
- website: string;
1648
- accountLabel: string;
1649
- };
1650
- interface BrowserCredentialListOptions {
1651
- website?: string;
1652
- limit?: number;
1653
- offset?: number;
1654
- }
1655
- declare class BrowserCredentialsClient {
1656
- private readonly config;
1657
- constructor(config?: BrowserCredentialsClientConfig);
1658
- private toMetadata;
1659
- list(options?: BrowserCredentialListOptions): Promise<{
1660
- credentials: BrowserCredentialMetadata[];
1661
- total: number;
1662
- count: number;
1663
- offset: number;
1664
- hasMore: boolean;
1665
- }>;
1666
- create(input: BrowserCredentialCreateInput): Promise<{
1667
- status: "created" | "already_exists";
1668
- credential: BrowserCredentialMetadata;
1669
- }>;
1670
- delete(input: BrowserCredentialDeleteInput): Promise<{
1671
- ok: boolean;
1672
- }>;
1673
- }
1674
- declare function browserCredentials(config?: BrowserCredentialsClientConfig): BrowserCredentialsClient;
1675
-
1676
- interface BrowserProfileMetadata {
1677
- id: string;
1678
- profile: string;
1679
- createdAt: string;
1680
- updatedAt: string;
1681
- lastUsedAt: string | null;
1682
- }
1683
- interface BrowserProfilesClientConfig {
1684
- apiKey?: string;
1685
- dashboardUrl?: string;
1686
- }
1687
- interface BrowserProfileDeleteInput {
1688
- profile: string;
1689
- }
1690
- declare class BrowserProfilesClient {
1691
- private readonly config;
1692
- constructor(config?: BrowserProfilesClientConfig);
1693
- private toMetadata;
1694
- list(): Promise<{
1695
- profiles: BrowserProfileMetadata[];
1696
- }>;
1697
- delete(input: BrowserProfileDeleteInput): Promise<{
1698
- ok: boolean;
1699
- }>;
1700
- }
1701
- declare function browserProfiles(config?: BrowserProfilesClientConfig): BrowserProfilesClient;
1702
-
1703
- /**
1704
- * Evolve events
1705
- *
1706
- * Runtime streams:
1707
- * - stdout: Raw NDJSON lines
1708
- * - stderr: Process stderr
1709
- * - content: Parsed OutputEvent
1710
- * - lifecycle: Sandbox/agent lifecycle transitions
1711
- */
1712
- interface EvolveEvents {
1713
- stdout: (chunk: string) => void;
1714
- stderr: (chunk: string) => void;
1715
- content: (event: OutputEvent) => void;
1716
- lifecycle: (event: LifecycleEvent) => void;
1717
- }
1718
- interface EvolveConfig {
1719
- agent?: AgentConfig;
1720
- sandbox?: SandboxProvider;
1721
- workingDirectory?: string;
1722
- workspaceMode?: WorkspaceMode;
1723
- secrets?: Record<string, string>;
1724
- managedSecrets?: ManagedSecretRef[];
1725
- sandboxId?: string;
1726
- systemPrompt?: string;
1727
- context?: FileMap;
1728
- files?: FileMap;
1729
- mcpServers?: Record<string, McpServerConfig>;
1730
- /** Browser automation provider to enable explicitly */
1731
- browser?: BrowserConfig;
1732
- /** Browser login MCP setup for managed remote agent-browser runs */
1733
- browserCredentials?: BrowserCredentialsConfig;
1734
- /** Agent plugins/extensions to install before first run */
1735
- plugins?: AgentPluginConfig[];
1736
- /** Skills to enable (e.g., ["pdf", "dev-browser"]) */
1737
- skills?: SkillName[];
1738
- /** Schema for structured output (Zod or JSON Schema, auto-detected) */
1739
- schema?: z.ZodType<unknown> | JsonSchema;
1740
- /** Validation options for JSON Schema (ignored for Zod) */
1741
- schemaOptions?: SchemaValidationOptions;
1742
- sessionTagPrefix?: string;
1743
- /** Observability metadata for trace grouping (generic key-value, domain-agnostic) */
1744
- observability?: Record<string, unknown>;
1745
- /** Managed integrations config */
1746
- integrations?: IntegrationsSetup;
1747
- /** Storage configuration for checkpointing */
1748
- storage?: StorageConfig;
1749
- }
1750
- /**
1751
- * Evolve orchestrator with builder pattern
1752
- *
1753
- * Usage:
1754
- * ```ts
1755
- * const kit = new Evolve()
1756
- * .withAgent({ type: "claude", apiKey: "sk-..." })
1757
- * .withSandbox(e2bProvider);
1758
- *
1759
- * kit.on("content", (event) => console.log(event));
1760
- *
1761
- * await kit.run({ prompt: "Hello" });
1762
- * ```
1763
- */
1764
- declare class Evolve extends EventEmitter {
1765
- private config;
1766
- private agent?;
1767
- private fallbackSandboxState;
1768
- private fallbackAgentState;
1769
- private fallbackHasRun;
1770
- constructor();
1771
- on<K extends keyof EvolveEvents>(event: K, listener: EvolveEvents[K]): this;
1772
- off<K extends keyof EvolveEvents>(event: K, listener: EvolveEvents[K]): this;
1773
- emit<K extends keyof EvolveEvents>(event: K, ...args: Parameters<EvolveEvents[K]>): boolean;
1774
- /**
1775
- * Configure agent type and API key.
1776
- * If config is undefined, Evolve resolves agent from env.
1777
- */
1778
- withAgent(config?: AgentConfig): this;
1779
- /**
1780
- * Configure sandbox provider
1781
- */
1782
- withSandbox(provider?: SandboxProvider): this;
1783
- /**
1784
- * Set working directory path
1785
- */
1786
- withWorkingDirectory(path: string): this;
1787
- /**
1788
- * Set workspace mode
1789
- * - "knowledge": Creates context/, scripts/, temp/, output/ folders
1790
- * - "swe": Same as knowledge + repo/ folder for code repositories
1791
- */
1792
- withWorkspaceMode(mode: WorkspaceMode): this;
1793
- /**
1794
- * Add environment secrets
1795
- */
1796
- withSecrets(secrets: Record<string, string>): this;
1797
- /**
1798
- * Attach Dashboard-stored managed secrets to the sandbox.
1799
- *
1800
- * The sandbox receives opaque env var values; raw secret values stay server-side.
1801
- */
1802
- withManagedSecrets(secrets: ManagedSecretRef[]): this;
1803
- /**
1804
- * Connect to existing session
1805
- */
1806
- withSession(sandboxId: string): this;
1807
- /**
1808
- * Set custom system prompt
1809
- */
1810
- withSystemPrompt(prompt: string): this;
1811
- /**
1812
- * Add context files (uploaded to context/ folder)
1813
- */
1814
- withContext(files: FileMap): this;
1815
- /**
1816
- * Add workspace files (uploaded to working directory)
1817
- */
1818
- withFiles(files: FileMap): this;
1819
- /**
1820
- * Configure MCP servers
1821
- */
1822
- withMcpServers(servers: Record<string, McpServerConfig>): this;
1823
- /**
1824
- * Enable browser automation.
1825
- *
1826
- * .withBrowser() defaults to agent-browser with Evolve-managed remote browser
1827
- * transport in gateway mode.
1828
- *
1829
- * @example
1830
- * kit.withBrowser() // defaults to remote managed agent-browser
1831
- *
1832
- * @example
1833
- * kit.withBrowser({ provider: "agent-browser", remote: true }) // managed remote agent-browser
1834
- */
1835
- withBrowser(provider?: BrowserConfig | false): this;
1836
- /**
1837
- * Enable saved browser logins for managed remote agent-browser runs.
1838
- *
1839
- * Empty config exposes all enabled browser logins for this Evolve account.
1840
- * Use allow to restrict a run to specific websites and optional account labels.
1841
- */
1842
- withBrowserCredentials(config?: BrowserCredentialsConfig): this;
1843
- /**
1844
- * Install agent plugins/extensions in the sandbox user profile.
1845
- *
1846
- * The selected agent determines the installer:
1847
- * - droid/claude: { marketplace, plugin }
1848
- * - gemini: { source, ref? }
1849
- * - codex: { marketplace, ref?, sparse? }
1850
- */
1851
- withPlugins(plugins: AgentPluginConfig | AgentPluginConfig[]): this;
1852
- /**
1853
- * Enable skills for the agent
1854
- *
1855
- * Skills are specialized capabilities that extend the agent's functionality.
1856
- * Available skills: "pdf", "dev-browser"
1857
- *
1858
- * @example
1859
- * kit.withSkills(["pdf", "dev-browser"])
1860
- */
1861
- withSkills(skills: SkillName[]): this;
1862
- /**
1863
- * Set schema for structured output validation
1864
- *
1865
- * Accepts either:
1866
- * - Zod schema: z.object({ ... }) - validated with Zod's safeParse
1867
- * - JSON Schema: { type: "object", properties: { ... } } - validated with Ajv
1868
- *
1869
- * Auto-detected based on presence of .safeParse method.
1870
- *
1871
- * @param schema - Zod schema or JSON Schema object
1872
- * @param options - Validation options for JSON Schema (ignored for Zod)
1873
- *
1874
- * @example
1875
- * // Zod schema
1876
- * kit.withSchema(z.object({ result: z.string() }))
1877
- *
1878
- * // JSON Schema with validation mode
1879
- * kit.withSchema(
1880
- * { type: "object", properties: { result: { type: "string" } } },
1881
- * { mode: "loose" }
1882
- * )
1883
- */
1884
- withSchema<T>(schema: z.ZodType<T> | JsonSchema, options?: SchemaValidationOptions): this;
1885
- /**
1886
- * Set session tag prefix for observability
1887
- */
1888
- withSessionTagPrefix(prefix: string): this;
1889
- /**
1890
- * @internal Set observability metadata for trace grouping.
1891
- * Used internally by Swarm - not part of public API.
1892
- */
1893
- withObservability(meta: Record<string, unknown>): this;
1894
- /**
1895
- * Enable Evolve-managed integrations.
1896
- *
1897
- * Available only in gateway mode. Integration credentials stay server-side; the
1898
- * sandbox receives an Evolve-scoped MCP proxy.
1899
- */
1900
- withIntegrations(config: IntegrationsSetup): this;
1901
- /**
1902
- * Configure storage for checkpoint persistence
1903
- *
1904
- * BYOK mode: provide URL to your S3-compatible bucket.
1905
- * Gateway mode: omit config (uses Evolve-managed storage, requires EVOLVE_API_KEY).
1906
- *
1907
- * @example
1908
- * // BYOK — user's own S3 bucket
1909
- * kit.withStorage({ url: "s3://my-bucket/agent-snapshots/" })
1910
- *
1911
- * // BYOK — Cloudflare R2
1912
- * kit.withStorage({ url: "s3://my-bucket/prefix/", endpoint: "https://acct.r2.cloudflarestorage.com" })
1913
- *
1914
- * // Gateway — Evolve-managed storage
1915
- * kit.withStorage()
1916
- */
1917
- withStorage(config?: StorageConfig): this;
1918
- /** Static helpers for managed integration auth and observability. */
1919
- static integrations: {
1920
- auth: (params: IntegrationAuthParams) => Promise<IntegrationAuthResult>;
1921
- accounts: {
1922
- list: (params: IntegrationAccountListParams) => Promise<IntegrationAccount[]>;
1923
- update: (params: IntegrationAccountUpdateParams) => Promise<IntegrationAccountUpdateResult>;
1924
- delete: (params: IntegrationAccountDeleteParams) => Promise<IntegrationAccountDeleteResult>;
1925
- };
1926
- };
1927
- /** Static browser credential client for listing, creating, and deleting saved browser logins. */
1928
- static browserCredentials: typeof browserCredentials;
1929
- /** Static browser profile client for listing and deleting reusable browser profiles. */
1930
- static browserProfiles: typeof browserProfiles;
1931
- /** Static managed secrets client for listing Dashboard-stored secret metadata. */
1932
- static managedSecrets: typeof managedSecrets;
1933
- /**
1934
- * Initialize agent on first use
1935
- */
1936
- private initializeAgent;
1937
- /**
1938
- * Create stream callbacks based on registered listeners
1939
- */
1940
- private createStreamCallbacks;
1941
- private emitLifecycleFromStatus;
1942
- /**
1943
- * Run agent with prompt
1944
- *
1945
- * @param from - Restore from checkpoint ID before running (requires .withStorage())
1946
- */
1947
- run({ prompt, timeoutMs, background, from, checkpointComment, }: {
1948
- prompt: string;
1949
- timeoutMs?: number;
1950
- background?: boolean;
1951
- from?: string;
1952
- checkpointComment?: string;
1953
- }): Promise<AgentResponse>;
1954
- /**
1955
- * Execute arbitrary command in sandbox
1956
- */
1957
- executeCommand(command: string, options?: {
1958
- timeoutMs?: number;
1959
- background?: boolean;
1960
- }): Promise<AgentResponse>;
1961
- /**
1962
- * Interrupt active process without killing sandbox.
1963
- */
1964
- interrupt(): Promise<boolean>;
1965
- /**
1966
- * Upload context files (runtime - immediate upload)
1967
- */
1968
- uploadContext(files: FileMap): Promise<void>;
1969
- /**
1970
- * Upload files to workspace (runtime - immediate upload)
1971
- */
1972
- uploadFiles(files: FileMap): Promise<void>;
1973
- /**
1974
- * Get output files from output/ folder with optional schema validation
1975
- *
1976
- * @param recursive - Include files in subdirectories (default: false)
1977
- */
1978
- getOutputFiles<T = unknown>(recursive?: boolean): Promise<OutputResult<T>>;
1979
- /**
1980
- * Create an explicit checkpoint of the current sandbox state.
1981
- *
1982
- * Requires a prior run() call (needs an active sandbox to snapshot).
1983
- *
1984
- * @param options.comment - Optional label for this checkpoint
1985
- */
1986
- checkpoint(options?: {
1987
- comment?: string;
1988
- }): Promise<CheckpointInfo>;
1989
- private _cachedGatewayOverrides;
1990
- /**
1991
- * Resolve gateway credentials from agent config for storage operations.
1992
- * Memoized — agent config is immutable after .withAgent().
1993
- */
1994
- private resolveGatewayOverrides;
1995
- /**
1996
- * List checkpoints (requires .withStorage()).
1997
- *
1998
- * Does not require an agent or sandbox — only storage configuration.
1999
- *
2000
- * @param options.limit - Maximum number of checkpoints to return
2001
- * @param options.tag - Filter by session tag (gateway mode: server-side, BYOK: post-filter)
2002
- */
2003
- listCheckpoints(options?: {
2004
- limit?: number;
2005
- tag?: string;
2006
- }): Promise<CheckpointInfo[]>;
2007
- /**
2008
- * Get a StorageClient bound to this instance's storage configuration.
2009
- * Same API surface as the standalone storage() factory.
2010
- */
2011
- storage(): StorageClient;
2012
- /**
2013
- * Get current session (sandbox ID)
2014
- */
2015
- getSession(): string | null;
2016
- /**
2017
- * Set session to connect to
2018
- */
2019
- setSession(sandboxId: string): Promise<void>;
2020
- /**
2021
- * Get runtime status for sandbox and agent.
2022
- */
2023
- status(): SessionStatus;
2024
- /**
2025
- * Pause sandbox
2026
- */
2027
- pause(): Promise<void>;
2028
- /**
2029
- * Resume sandbox
2030
- */
2031
- resume(): Promise<void>;
2032
- /**
2033
- * Kill sandbox
2034
- */
2035
- kill(): Promise<void>;
2036
- /**
2037
- * Get host URL for a port
2038
- */
2039
- getHost(port: number): Promise<string>;
2040
- /**
2041
- * Get session tag (for observability)
2042
- *
2043
- * Returns null if no session has started (run() not called yet).
2044
- */
2045
- getSessionTag(): string | null;
2046
- /**
2047
- * Get session timestamp (for observability)
2048
- *
2049
- * Returns null if no session has started (run() not called yet).
2050
- */
2051
- getSessionTimestamp(): string | null;
2052
- /**
2053
- * Flush pending observability events without killing sandbox.
2054
- */
2055
- flushObservability(): Promise<void>;
2056
- /**
2057
- * Get cost breakdown for the current session (all runs).
2058
- * Also works after kill() — queries the just-finished session.
2059
- * Requires gateway mode (EVOLVE_API_KEY).
2060
- */
2061
- getSessionCost(): Promise<SessionCost>;
2062
- /**
2063
- * Get cost for a specific run by ID or index.
2064
- * @param run - Either `{ runId: string }` or `{ index: number }` (1-based, negative = from end)
2065
- */
2066
- getRunCost(run: {
2067
- runId: string;
2068
- } | {
2069
- index: number;
2070
- }): Promise<RunCost>;
2071
- }
2072
-
2073
- /**
2074
- * Retry Utility
2075
- *
2076
- * Generic retry with exponential backoff for Swarm operations.
2077
- * Works with any result type that has a status field.
2078
- * Retries on error status by default, with customizable retry conditions.
2079
- */
2080
- /** Any result with a status field (SwarmResult, ReduceResult, etc.) */
2081
- interface RetryableResult {
2082
- status: "success" | "error" | "filtered";
2083
- error?: string;
2084
- }
2085
- /**
2086
- * Per-item retry configuration.
2087
- *
2088
- * @example
2089
- * ```typescript
2090
- * // Basic retry on error
2091
- * { maxAttempts: 3 }
2092
- *
2093
- * // With exponential backoff
2094
- * { maxAttempts: 3, backoffMs: 1000, backoffMultiplier: 2 }
2095
- *
2096
- * // Custom retry condition (when using typed RetryConfig<SwarmResult<T>>)
2097
- * { maxAttempts: 3, retryOn: (r) => r.status === "error" || r.error?.includes("timeout") }
2098
- *
2099
- * // With retry callback for observability
2100
- * { maxAttempts: 3, onItemRetry: (idx, attempt, error) => console.log(`Item ${idx} retry ${attempt}: ${error}`) }
2101
- * ```
2102
- */
2103
- interface RetryConfig<TResult extends RetryableResult = RetryableResult> {
2104
- /** Maximum retry attempts (default: 3) */
2105
- maxAttempts?: number;
2106
- /** Initial backoff in ms (default: 1000) */
2107
- backoffMs?: number;
2108
- /** Exponential backoff multiplier (default: 2) */
2109
- backoffMultiplier?: number;
2110
- /** Custom retry condition (default: status === "error") */
2111
- retryOn?: (result: TResult) => boolean;
2112
- /** Callback invoked before each item retry attempt */
2113
- onItemRetry?: OnItemRetryCallback;
2114
- }
2115
- /** Callback for item retry events */
2116
- type OnItemRetryCallback = (itemIndex: number, attempt: number, error: string) => void;
2117
- /**
2118
- * Execute a function with retry and exponential backoff.
2119
- *
2120
- * Works with any result type that has a `status` field (SwarmResult, ReduceResult, etc.).
2121
- *
2122
- * @param fn - Function that receives attempt number (1-based) and returns a result
2123
- * @param config - Retry configuration (includes optional onRetry callback)
2124
- * @param itemIndex - Item index for callback (default: 0, used for reduce)
2125
- * @returns Result from the function
2126
- *
2127
- * @example
2128
- * ```typescript
2129
- * const result = await executeWithRetry(
2130
- * (attempt) => this.executeMapItem(item, prompt, index, operationId, params, timeout, attempt),
2131
- * { maxAttempts: 3, backoffMs: 1000, onItemRetry: (idx, attempt, error) => console.log(`Item ${idx} retry ${attempt}: ${error}`) },
2132
- * index
2133
- * );
2134
- * ```
2135
- */
2136
- declare function executeWithRetry<TResult extends RetryableResult>(fn: (attempt: number) => Promise<TResult>, config?: RetryConfig<TResult>, itemIndex?: number): Promise<TResult>;
2137
-
2138
- /**
2139
- * Swarm Abstractions - Type Definitions
2140
- *
2141
- * Functional programming for AI agents.
2142
- * map, filter, reduce, bestOf - with AI reasoning.
2143
- */
2144
-
2145
- declare const SWARM_RESULT_BRAND: unique symbol;
2146
- /** Agent override for method options (apiKey inherited from Swarm instance) */
2147
- interface AgentOverride {
2148
- type: AgentType;
2149
- model?: string;
2150
- reasoningEffort?: ReasoningEffort;
2151
- }
2152
- interface SwarmConfig {
2153
- /** Default agent for all operations (defaults to env resolution) */
2154
- agent?: AgentConfig;
2155
- /** Sandbox provider (defaults to E2B via E2B_API_KEY env var) */
2156
- sandbox?: SandboxProvider;
2157
- /** User prefix for worker tags */
2158
- tag?: string;
2159
- /** Max parallel sandboxes globally (default: 4) */
2160
- concurrency?: number;
2161
- /** Per-worker timeout in ms (default: 1 hour) */
2162
- timeoutMs?: number;
2163
- /** Workspace mode (default: SDK default 'knowledge') */
2164
- workspaceMode?: WorkspaceMode;
2165
- /** Default retry configuration for all operations (per-operation config takes precedence) */
2166
- retry?: RetryConfig;
2167
- /** Default MCP servers for all operations (per-operation config takes precedence) */
2168
- mcpServers?: Record<string, McpServerConfig>;
2169
- /** Default skills for all operations (per-operation config takes precedence) */
2170
- skills?: SkillName[];
2171
- /** Default Integrations configuration for all operations (per-operation config takes precedence) */
2172
- integrations?: IntegrationsSetup;
2173
- }
2174
- /** Callback for bestOf candidate completion */
2175
- type OnCandidateCompleteCallback = (itemIndex: number, candidateIndex: number, status: "success" | "error") => void;
2176
- /** Callback for bestOf judge completion */
2177
- type OnJudgeCompleteCallback = (itemIndex: number, winnerIndex: number, reasoning: string) => void;
2178
- interface BestOfConfig {
2179
- /** Number of candidates (>= 2). Required if taskAgents omitted, else inferred from taskAgents.length */
2180
- n?: number;
2181
- /** Evaluation criteria for judge */
2182
- judgeCriteria: string;
2183
- /** Optional: agents for each candidate. If provided, n defaults to taskAgents.length */
2184
- taskAgents?: AgentOverride[];
2185
- /** Optional: override agent for judge */
2186
- judgeAgent?: AgentOverride;
2187
- /** MCP servers for candidates (defaults to operation mcpServers) */
2188
- mcpServers?: Record<string, McpServerConfig>;
2189
- /** MCP servers for judge (defaults to mcpServers) */
2190
- judgeMcpServers?: Record<string, McpServerConfig>;
2191
- /** Skills for candidates (defaults to operation skills) */
2192
- skills?: SkillName[];
2193
- /** Skills for judge (defaults to skills) */
2194
- judgeSkills?: SkillName[];
2195
- /** Integrations config for candidates (defaults to operation integrations) */
2196
- integrations?: IntegrationsSetup;
2197
- /** Integrations config for judge (defaults to integrations) */
2198
- judgeIntegrations?: IntegrationsSetup;
2199
- /** Callback when a candidate completes */
2200
- onCandidateComplete?: OnCandidateCompleteCallback;
2201
- /** Callback when judge completes */
2202
- onJudgeComplete?: OnJudgeCompleteCallback;
2203
- }
2204
- /** Callback for verify worker completion (before verification runs) */
2205
- type OnWorkerCompleteCallback = (itemIndex: number, attempt: number, status: "success" | "error") => void;
2206
- /** Callback for verifier completion */
2207
- type OnVerifierCompleteCallback = (itemIndex: number, attempt: number, passed: boolean, feedback?: string) => void;
2208
- interface VerifyConfig {
2209
- /** Verification criteria - what the output must satisfy */
2210
- criteria: string;
2211
- /** Maximum attempts with feedback (default: 3). Includes initial attempt. */
2212
- maxAttempts?: number;
2213
- /** Optional: override agent for verifier */
2214
- verifierAgent?: AgentOverride;
2215
- /** MCP servers for verifier (defaults to operation mcpServers) */
2216
- verifierMcpServers?: Record<string, McpServerConfig>;
2217
- /** Skills for verifier (defaults to operation skills) */
2218
- verifierSkills?: SkillName[];
2219
- /** Integrations config for verifier (defaults to operation integrations) */
2220
- verifierIntegrations?: IntegrationsSetup;
2221
- /** Callback invoked after each worker completion (before verification) */
2222
- onWorkerComplete?: OnWorkerCompleteCallback;
2223
- /** Callback invoked after each verifier completion */
2224
- onVerifierComplete?: OnVerifierCompleteCallback;
2225
- }
2226
- type OperationType = "map" | "filter" | "reduce" | "bestof-cand" | "bestof-judge" | "verify";
2227
- interface BaseMeta {
2228
- /** Unique identifier for this operation (map/filter/reduce/bestOf call) */
2229
- operationId: string;
2230
- operation: OperationType;
2231
- tag: string;
2232
- sandboxId: string;
2233
- /** Swarm name (from Swarm.config.tag) - identifies the swarm instance */
2234
- swarmName?: string;
2235
- /** Operation name (from params.name) - user-defined label for this operation */
2236
- operationName?: string;
2237
- /** Error retry number (1, 2, 3...) - only present when retrying after error */
2238
- errorRetry?: number;
2239
- /** Verify retry number (1, 2, 3...) - only present when retrying after verify failure */
2240
- verifyRetry?: number;
2241
- /** Candidate index (0, 1, 2...) - only present for bestOf candidates */
2242
- candidateIndex?: number;
2243
- /** Pipeline run identifier - only present when run via Pipeline */
2244
- pipelineRunId?: string;
2245
- /** Pipeline step index - only present when run via Pipeline */
2246
- pipelineStepIndex?: number;
2247
- }
2248
- interface IndexedMeta extends BaseMeta {
2249
- /** Item index in the batch (0, 1, 2...) */
2250
- itemIndex: number;
2251
- }
2252
- interface ReduceMeta extends BaseMeta {
2253
- inputCount: number;
2254
- inputIndices: number[];
2255
- }
2256
- interface JudgeMeta extends BaseMeta {
2257
- candidateCount: number;
2258
- }
2259
- interface VerifyMeta extends BaseMeta {
2260
- /** Total verification attempts made */
2261
- attempts: number;
2262
- }
2263
- /**
2264
- * Result from a single worker (map, filter, bestof candidate).
2265
- *
2266
- * Status meanings:
2267
- * - "success": Positive outcome (agent succeeded / condition passed)
2268
- * - "filtered": Neutral outcome (evaluated but didn't pass condition) - filter only
2269
- * - "error": Negative outcome (agent error)
2270
- *
2271
- * @typeParam T - Data type. Defaults to FileMap when no schema provided.
2272
- */
2273
- interface SwarmResult<T = FileMap> {
2274
- readonly [SWARM_RESULT_BRAND]: true;
2275
- status: "success" | "filtered" | "error";
2276
- /** Parsed result.json if schema provided, else FileMap. Null if failed. */
2277
- data: T | null;
2278
- /** Output files (map/bestof) or original input files (filter) */
2279
- files: FileMap;
2280
- meta: IndexedMeta;
2281
- error?: string;
2282
- /** Raw result.json string when parse or validation failed (for debugging) */
2283
- rawData?: string;
2284
- /** Present when map used bestOf option. Matches BestOfResult structure (minus winner). */
2285
- bestOf?: {
2286
- winnerIndex: number;
2287
- judgeReasoning: string;
2288
- judgeMeta: JudgeMeta;
2289
- candidates: SwarmResult<T>[];
2290
- };
2291
- /** Present when verify option was used. Contains verification outcome. */
2292
- verify?: VerifyInfo;
2293
- }
2294
- /**
2295
- * List of SwarmResults with helper properties.
2296
- * Extends Array so all normal array operations work.
2297
- *
2298
- * Getters:
2299
- * - `.success` - items with positive outcome
2300
- * - `.filtered` - items that didn't pass condition (filter only)
2301
- * - `.error` - items that encountered errors
2302
- *
2303
- * Chaining examples:
2304
- * - `swarm.reduce(results.success, ...)` - forward only successful
2305
- * - `swarm.reduce([...results.success, ...results.filtered], ...)` - forward all evaluated
2306
- */
2307
- declare class SwarmResultList<T = FileMap> extends Array<SwarmResult<T>> {
2308
- /** Returns items with status "success" */
2309
- get success(): SwarmResult<T>[];
2310
- /** Returns items with status "filtered" (didn't pass condition) */
2311
- get filtered(): SwarmResult<T>[];
2312
- /** Returns items with status "error" */
2313
- get error(): SwarmResult<T>[];
2314
- static from<T>(results: SwarmResult<T>[]): SwarmResultList<T>;
2315
- }
2316
- /**
2317
- * Result from reduce operation.
2318
- *
2319
- * @typeParam T - Data type. Defaults to FileMap when no schema provided.
2320
- */
2321
- interface ReduceResult<T = FileMap> {
2322
- status: "success" | "error";
2323
- data: T | null;
2324
- files: FileMap;
2325
- meta: ReduceMeta;
2326
- error?: string;
2327
- /** Raw result.json string when parse or validation failed (for debugging) */
2328
- rawData?: string;
2329
- /** Present when verify option was used. Contains verification outcome. */
2330
- verify?: VerifyInfo;
2331
- }
2332
- /**
2333
- * Result from bestOf operation.
2334
- *
2335
- * @typeParam T - Data type for candidates.
2336
- */
2337
- interface BestOfResult<T = FileMap> {
2338
- winner: SwarmResult<T>;
2339
- winnerIndex: number;
2340
- judgeReasoning: string;
2341
- judgeMeta: JudgeMeta;
2342
- candidates: SwarmResult<T>[];
2343
- }
2344
- /** Fixed schema for bestOf judge output */
2345
- interface JudgeDecision {
2346
- winner: number;
2347
- reasoning: string;
2348
- }
2349
- /** Fixed schema for verify output */
2350
- interface VerifyDecision {
2351
- passed: boolean;
2352
- reasoning: string;
2353
- feedback?: string;
2354
- }
2355
- /** Verification info attached to results when verify option used */
2356
- interface VerifyInfo {
2357
- passed: boolean;
2358
- reasoning: string;
2359
- verifyMeta: VerifyMeta;
2360
- attempts: number;
2361
- }
2362
- type ItemInput = FileMap | SwarmResult<unknown>;
2363
- type PromptFn = (files: FileMap, index: number) => string;
2364
- type Prompt = string | PromptFn;
2365
- /** @internal Pipeline context for observability (set by Pipeline, not user) */
2366
- interface PipelineContext {
2367
- pipelineRunId: string;
2368
- pipelineStepIndex: number;
2369
- }
2370
- /** Parameters for map operation */
2371
- interface MapParams<T> {
2372
- /** Items to process (FileMaps or SwarmResults from previous operation) */
2373
- items: ItemInput[];
2374
- /** Task prompt (string or function(files, index) -> string) */
2375
- prompt: Prompt;
2376
- /** Optional operation name for observability */
2377
- name?: string;
2378
- /** Optional system prompt */
2379
- systemPrompt?: string;
2380
- /** @internal Pipeline context (set by Pipeline, not user) */
2381
- _pipelineContext?: PipelineContext;
2382
- /** Schema for structured output (Zod or JSON Schema) */
2383
- schema?: z.ZodType<T> | JsonSchema;
2384
- /** Validation options for JSON Schema (ignored for Zod) */
2385
- schemaOptions?: SchemaValidationOptions;
2386
- /** Optional agent override */
2387
- agent?: AgentOverride;
2388
- /** MCP servers override (replaces swarm default) */
2389
- mcpServers?: Record<string, McpServerConfig>;
2390
- /** Skills override (replaces swarm default) */
2391
- skills?: SkillName[];
2392
- /** Integrations override (replaces swarm default) */
2393
- integrations?: IntegrationsSetup;
2394
- /** Optional bestOf configuration for N candidates + judge (mutually exclusive with verify) */
2395
- bestOf?: BestOfConfig;
2396
- /** Optional verify configuration for LLM-as-judge quality verification with retry (mutually exclusive with bestOf) */
2397
- verify?: VerifyConfig;
2398
- /** Per-item retry configuration. Typed to allow retryOn access to SwarmResult fields. */
2399
- retry?: RetryConfig<SwarmResult<T>>;
2400
- /** Optional timeout in ms */
2401
- timeoutMs?: number;
2402
- }
2403
- /** Parameters for filter operation */
2404
- interface FilterParams<T> {
2405
- /** Items to filter (FileMaps or SwarmResults from previous operation) */
2406
- items: ItemInput[];
2407
- /** Evaluation prompt - describe what to assess and how (agent outputs result.json) */
2408
- prompt: string;
2409
- /** Optional operation name for observability */
2410
- name?: string;
2411
- /** @internal Pipeline context (set by Pipeline, not user) */
2412
- _pipelineContext?: PipelineContext;
2413
- /** Schema for structured output (Zod or JSON Schema) */
2414
- schema: z.ZodType<T> | JsonSchema;
2415
- /** Validation options for JSON Schema (ignored for Zod) */
2416
- schemaOptions?: SchemaValidationOptions;
2417
- /** Local condition function to determine pass/fail */
2418
- condition: (data: T) => boolean;
2419
- /** Optional system prompt */
2420
- systemPrompt?: string;
2421
- /** Optional agent override */
2422
- agent?: AgentOverride;
2423
- /** MCP servers override (replaces swarm default) */
2424
- mcpServers?: Record<string, McpServerConfig>;
2425
- /** Skills override (replaces swarm default) */
2426
- skills?: SkillName[];
2427
- /** Integrations override (replaces swarm default) */
2428
- integrations?: IntegrationsSetup;
2429
- /** Optional verify configuration for LLM-as-judge quality verification with retry */
2430
- verify?: VerifyConfig;
2431
- /** Per-item retry configuration. Typed to allow retryOn access to SwarmResult fields. */
2432
- retry?: RetryConfig<SwarmResult<T>>;
2433
- /** Optional timeout in ms */
2434
- timeoutMs?: number;
2435
- }
2436
- /** Parameters for reduce operation */
2437
- interface ReduceParams<T> {
2438
- /** Items to reduce (FileMaps or SwarmResults from previous operation) */
2439
- items: ItemInput[];
2440
- /** Synthesis prompt */
2441
- prompt: string;
2442
- /** Optional operation name for observability */
2443
- name?: string;
2444
- /** Optional system prompt */
2445
- systemPrompt?: string;
2446
- /** @internal Pipeline context (set by Pipeline, not user) */
2447
- _pipelineContext?: PipelineContext;
2448
- /** Schema for structured output (Zod or JSON Schema) */
2449
- schema?: z.ZodType<T> | JsonSchema;
2450
- /** Validation options for JSON Schema (ignored for Zod) */
2451
- schemaOptions?: SchemaValidationOptions;
2452
- /** Optional agent override */
2453
- agent?: AgentOverride;
2454
- /** MCP servers override (replaces swarm default) */
2455
- mcpServers?: Record<string, McpServerConfig>;
2456
- /** Skills override (replaces swarm default) */
2457
- skills?: SkillName[];
2458
- /** Integrations override (replaces swarm default) */
2459
- integrations?: IntegrationsSetup;
2460
- /** Optional verify configuration for LLM-as-judge quality verification with retry */
2461
- verify?: VerifyConfig;
2462
- /** Retry configuration (retries entire reduce on error). Typed to allow retryOn access to ReduceResult fields. */
2463
- retry?: RetryConfig<ReduceResult<T>>;
2464
- /** Optional timeout in ms */
2465
- timeoutMs?: number;
2466
- }
2467
- /** Parameters for bestOf operation */
2468
- interface BestOfParams<T> {
2469
- /** Single item to process */
2470
- item: ItemInput;
2471
- /** Task prompt */
2472
- prompt: string;
2473
- /** Optional operation name for observability */
2474
- name?: string;
2475
- /** BestOf configuration (n, judgeCriteria, taskAgents, judgeAgent, mcpServers, skills, integrations) */
2476
- config: BestOfConfig;
2477
- /** Optional system prompt */
2478
- systemPrompt?: string;
2479
- /** Schema for structured output (Zod or JSON Schema) */
2480
- schema?: z.ZodType<T> | JsonSchema;
2481
- /** Validation options for JSON Schema (ignored for Zod) */
2482
- schemaOptions?: SchemaValidationOptions;
2483
- /**
2484
- * Per-candidate retry configuration. Typed to allow retryOn access to SwarmResult fields.
2485
- * Note: Judge always uses default retryOn (status === "error"), ignoring custom retryOn.
2486
- */
2487
- retry?: RetryConfig<SwarmResult<T>>;
2488
- /** Optional timeout in ms */
2489
- timeoutMs?: number;
2490
- }
2491
-
2492
- /**
2493
- * Simple semaphore for global concurrency control.
2494
- *
2495
- * Ensures no more than N sandboxes run concurrently across all swarm operations.
2496
- */
2497
- declare class Semaphore {
2498
- private permits;
2499
- private queue;
2500
- constructor(max: number);
2501
- /**
2502
- * Execute a function under the semaphore.
2503
- * Acquires a permit before running, releases after completion.
2504
- */
2505
- use<T>(fn: () => Promise<T>): Promise<T>;
2506
- private acquire;
2507
- private release;
2508
- }
2509
-
2510
- /**
2511
- * Swarm Abstractions
2512
- *
2513
- * Functional programming for AI agents.
2514
- *
2515
- * @example
2516
- * ```typescript
2517
- * const swarm = new Swarm({
2518
- * agent: { type: "claude", apiKey: "..." },
2519
- * sandbox: createE2BProvider({ apiKey: "..." }),
2520
- * });
2521
- *
2522
- * const analyses = await swarm.map({
2523
- * items: documents,
2524
- * prompt: "Analyze this",
2525
- * });
2526
- *
2527
- * const evaluated = await swarm.filter({
2528
- * items: analyses,
2529
- * prompt: "Evaluate severity",
2530
- * schema: SeveritySchema,
2531
- * condition: r => r.severity === "critical",
2532
- * });
2533
- * // evaluated.success = passed condition
2534
- * // evaluated.filtered = didn't pass condition
2535
- * // evaluated.error = agent errors
2536
- *
2537
- * const report = await swarm.reduce({
2538
- * items: evaluated.success,
2539
- * prompt: "Create summary",
2540
- * });
2541
- * ```
2542
- */
2543
-
2544
- declare class Swarm {
2545
- private config;
2546
- private semaphore;
2547
- constructor(config?: SwarmConfig);
2548
- /**
2549
- * Apply an agent to each item in parallel.
2550
- */
2551
- map<T = FileMap>(params: MapParams<T>): Promise<SwarmResultList<T>>;
2552
- /**
2553
- * Two-step evaluation: agent assesses each item, then local condition applies threshold.
2554
- *
2555
- * 1. Agent sees context files, evaluates per prompt, outputs result.json matching schema
2556
- * 2. Condition function receives parsed data, returns true (success) or false (filtered)
2557
- *
2558
- * Returns ALL items with status:
2559
- * - "success": passed condition
2560
- * - "filtered": evaluated but didn't pass condition
2561
- * - "error": agent error
2562
- *
2563
- * Use `.success` for passing items, `.filtered` for non-passing.
2564
- */
2565
- filter<T>(params: FilterParams<T>): Promise<SwarmResultList<T>>;
2566
- /**
2567
- * Synthesize many items into one.
2568
- */
2569
- reduce<T = FileMap>(params: ReduceParams<T>): Promise<ReduceResult<T>>;
2570
- /**
2571
- * Run N candidates on the same task, judge picks the best.
2572
- */
2573
- bestOf<T = FileMap>(params: BestOfParams<T>): Promise<BestOfResult<T>>;
2574
- private execute;
2575
- private executeMapItem;
2576
- private executeMapItemWithVerify;
2577
- private executeMapItemWithBestOf;
2578
- private executeFilterItem;
2579
- private executeFilterItemWithVerify;
2580
- /**
2581
- * Execute a single bestOf candidate.
2582
- * Used by both standalone bestOf() and map() with bestOf option.
2583
- */
2584
- private executeBestOfCandidate;
2585
- /**
2586
- * Build judge context containing worker task info and candidate outputs.
2587
- */
2588
- private buildJudgeContext;
2589
- /**
2590
- * Execute judge to pick best candidate.
2591
- * Returns RetryableResult-compatible type for use with executeWithRetry.
2592
- */
2593
- private executeBestOfJudge;
2594
- private static readonly DEFAULT_VERIFY_MAX_ATTEMPTS;
2595
- private static readonly VerifyDecisionSchema;
2596
- /**
2597
- * Build verify context containing worker task info and output to verify.
2598
- */
2599
- private buildVerifyContext;
2600
- /**
2601
- * Execute verifier to check if output meets criteria.
2602
- */
2603
- private executeVerify;
2604
- /**
2605
- * Build a retry prompt with verifier feedback.
2606
- */
2607
- private static buildRetryPromptWithFeedback;
2608
- /**
2609
- * Shared verification loop for map, filter, and reduce.
2610
- * Runs worker function, verifies output, retries with feedback if needed.
2611
- *
2612
- * @param workerFn - Function that executes the worker with a given prompt, tag prefix, and attempt index
2613
- * @param params - Common verification parameters
2614
- * @returns Result with verify info attached
2615
- */
2616
- private runWithVerification;
2617
- private generateOperationId;
2618
- /** Convert pipeline context to observability fields */
2619
- private pipelineContextToObservability;
2620
- /** Extract pipeline tracking fields for meta objects */
2621
- private pipelineContextToMeta;
2622
- /**
2623
- * Safely evaluate prompt (string or function).
2624
- * Returns evaluated string or Error if function threw.
2625
- */
2626
- private evaluatePrompt;
2627
- /**
2628
- * Build evaluator context (shared by judge and verify).
2629
- * Creates worker_task/ structure with input files, prompts, schema.
2630
- */
2631
- private buildEvaluatorContext;
2632
- private isSwarmResult;
2633
- private getFiles;
2634
- private getIndex;
2635
- private buildResult;
2636
- private buildErrorResult;
2637
- }
2638
-
2639
- /**
2640
- * Pipeline Types
2641
- *
2642
- * Fluent API for chaining Swarm operations.
2643
- */
2644
-
2645
- /**
2646
- * What filter emits to the next step.
2647
- *
2648
- * - "success": Items that passed condition (default)
2649
- * - "filtered": Items that failed condition
2650
- * - "all": Both success and filtered
2651
- */
2652
- type EmitOption = "success" | "filtered" | "all";
2653
- /** Base fields shared by all step types */
2654
- interface BaseStepConfig {
2655
- /** Step name for observability (appears in events) */
2656
- name?: string;
2657
- /** System prompt override */
2658
- systemPrompt?: string;
2659
- /** Agent override */
2660
- agent?: AgentOverride;
2661
- /** MCP servers override (replaces swarm default for this step) */
2662
- mcpServers?: Record<string, McpServerConfig>;
2663
- /** Skills override (replaces swarm default for this step) */
2664
- skills?: SkillName[];
2665
- /** Integrations override (replaces swarm default for this step) */
2666
- integrations?: IntegrationsSetup;
2667
- /** Timeout in ms */
2668
- timeoutMs?: number;
2669
- }
2670
- /** Map step configuration */
2671
- interface MapConfig<T> extends BaseStepConfig {
2672
- /** Task prompt */
2673
- prompt: Prompt;
2674
- /** Schema for structured output */
2675
- schema?: z.ZodType<T> | JsonSchema;
2676
- /** Validation options for JSON Schema */
2677
- schemaOptions?: SchemaValidationOptions;
2678
- /** BestOf configuration (mutually exclusive with verify) */
2679
- bestOf?: BestOfConfig;
2680
- /** Verify configuration (mutually exclusive with bestOf) */
2681
- verify?: VerifyConfig;
2682
- /** Retry configuration */
2683
- retry?: RetryConfig<SwarmResult<T>>;
2684
- }
2685
- /** Filter step configuration */
2686
- interface FilterConfig<T> extends BaseStepConfig {
2687
- /** Evaluation prompt */
2688
- prompt: string;
2689
- /** Schema for structured output (required) */
2690
- schema: z.ZodType<T> | JsonSchema;
2691
- /** Validation options for JSON Schema */
2692
- schemaOptions?: SchemaValidationOptions;
2693
- /** Condition function to determine pass/fail */
2694
- condition: (data: T) => boolean;
2695
- /** What to emit to next step (default: "success") */
2696
- emit?: EmitOption;
2697
- /** Verify configuration */
2698
- verify?: VerifyConfig;
2699
- /** Retry configuration */
2700
- retry?: RetryConfig<SwarmResult<T>>;
2701
- }
2702
- /** Reduce step configuration */
2703
- interface ReduceConfig<T> extends BaseStepConfig {
2704
- /** Synthesis prompt */
2705
- prompt: string;
2706
- /** Schema for structured output */
2707
- schema?: z.ZodType<T> | JsonSchema;
2708
- /** Validation options for JSON Schema */
2709
- schemaOptions?: SchemaValidationOptions;
2710
- /** Verify configuration */
2711
- verify?: VerifyConfig;
2712
- /** Retry configuration */
2713
- retry?: RetryConfig<ReduceResult<T>>;
2714
- }
2715
- /** @internal Step representation */
2716
- type Step = {
2717
- type: "map";
2718
- config: MapConfig<unknown>;
2719
- } | {
2720
- type: "filter";
2721
- config: FilterConfig<unknown>;
2722
- } | {
2723
- type: "reduce";
2724
- config: ReduceConfig<unknown>;
2725
- };
2726
- /** @internal Step type literal */
2727
- type StepType = "map" | "filter" | "reduce";
2728
- /** Result of a single pipeline step */
2729
- interface StepResult<T = unknown> {
2730
- type: StepType;
2731
- index: number;
2732
- durationMs: number;
2733
- results: SwarmResult<T>[] | ReduceResult<T>;
2734
- }
2735
- /** Final result from pipeline execution */
2736
- interface PipelineResult<T = unknown> {
2737
- /** Unique identifier for this pipeline run */
2738
- pipelineRunId: string;
2739
- steps: StepResult<unknown>[];
2740
- output: SwarmResult<T>[] | ReduceResult<T>;
2741
- totalDurationMs: number;
2742
- }
2743
- /** Step lifecycle event */
2744
- interface StepEvent {
2745
- type: StepType;
2746
- index: number;
2747
- name?: string;
2748
- }
2749
- /** Emitted when step starts */
2750
- interface StepStartEvent extends StepEvent {
2751
- itemCount: number;
2752
- }
2753
- /** Emitted when step completes */
2754
- interface StepCompleteEvent extends StepEvent {
2755
- durationMs: number;
2756
- successCount: number;
2757
- errorCount: number;
2758
- filteredCount: number;
2759
- }
2760
- /** Emitted when step errors */
2761
- interface StepErrorEvent extends StepEvent {
2762
- error: Error;
2763
- }
2764
- /** Emitted on item retry */
2765
- interface ItemRetryEvent {
2766
- stepIndex: number;
2767
- stepName?: string;
2768
- itemIndex: number;
2769
- attempt: number;
2770
- error: string;
2771
- }
2772
- /** Emitted when verify worker completes */
2773
- interface WorkerCompleteEvent {
2774
- stepIndex: number;
2775
- stepName?: string;
2776
- itemIndex: number;
2777
- attempt: number;
2778
- status: "success" | "error";
2779
- }
2780
- /** Emitted when verifier completes */
2781
- interface VerifierCompleteEvent {
2782
- stepIndex: number;
2783
- stepName?: string;
2784
- itemIndex: number;
2785
- attempt: number;
2786
- passed: boolean;
2787
- feedback?: string;
2788
- }
2789
- /** Emitted when bestOf candidate completes */
2790
- interface CandidateCompleteEvent {
2791
- stepIndex: number;
2792
- stepName?: string;
2793
- itemIndex: number;
2794
- candidateIndex: number;
2795
- status: "success" | "error";
2796
- }
2797
- /** Emitted when bestOf judge completes */
2798
- interface JudgeCompleteEvent {
2799
- stepIndex: number;
2800
- stepName?: string;
2801
- itemIndex: number;
2802
- winnerIndex: number;
2803
- reasoning: string;
2804
- }
2805
- /** Event handlers */
2806
- interface PipelineEvents {
2807
- onStepStart?: (event: StepStartEvent) => void;
2808
- onStepComplete?: (event: StepCompleteEvent) => void;
2809
- onStepError?: (event: StepErrorEvent) => void;
2810
- onItemRetry?: (event: ItemRetryEvent) => void;
2811
- onWorkerComplete?: (event: WorkerCompleteEvent) => void;
2812
- onVerifierComplete?: (event: VerifierCompleteEvent) => void;
2813
- onCandidateComplete?: (event: CandidateCompleteEvent) => void;
2814
- onJudgeComplete?: (event: JudgeCompleteEvent) => void;
2815
- }
2816
- /** Event name mapping for chainable .on() */
2817
- type EventName = "stepStart" | "stepComplete" | "stepError" | "itemRetry" | "workerComplete" | "verifierComplete" | "candidateComplete" | "judgeComplete";
2818
- /** Map event name to handler type */
2819
- type EventHandler<E extends EventName> = E extends "stepStart" ? (event: StepStartEvent) => void : E extends "stepComplete" ? (event: StepCompleteEvent) => void : E extends "stepError" ? (event: StepErrorEvent) => void : E extends "itemRetry" ? (event: ItemRetryEvent) => void : E extends "workerComplete" ? (event: WorkerCompleteEvent) => void : E extends "verifierComplete" ? (event: VerifierCompleteEvent) => void : E extends "candidateComplete" ? (event: CandidateCompleteEvent) => void : E extends "judgeComplete" ? (event: JudgeCompleteEvent) => void : never;
2820
- /** Event name to handler type mapping (for chainable .on() style) */
2821
- interface PipelineEventMap {
2822
- stepStart: (event: StepStartEvent) => void;
2823
- stepComplete: (event: StepCompleteEvent) => void;
2824
- stepError: (event: StepErrorEvent) => void;
2825
- itemRetry: (event: ItemRetryEvent) => void;
2826
- workerComplete: (event: WorkerCompleteEvent) => void;
2827
- verifierComplete: (event: VerifierCompleteEvent) => void;
2828
- candidateComplete: (event: CandidateCompleteEvent) => void;
2829
- judgeComplete: (event: JudgeCompleteEvent) => void;
2830
- }
2831
-
2832
- /**
2833
- * Pipeline - Fluent API for Swarm Operations
2834
- *
2835
- * Thin wrapper over Swarm providing method chaining, timing, and events.
2836
- *
2837
- * @example
2838
- * ```typescript
2839
- * const pipeline = new Pipeline(swarm)
2840
- * .map({ prompt: "Analyze..." })
2841
- * .filter({ prompt: "Rate...", schema, condition: d => d.score > 7 })
2842
- * .reduce({ prompt: "Summarize..." });
2843
- *
2844
- * // Run with items
2845
- * const result = await pipeline.run(documents);
2846
- *
2847
- * // Reusable - run with different data
2848
- * await pipeline.run(batch1);
2849
- * await pipeline.run(batch2);
2850
- * ```
2851
- */
2852
-
2853
- /**
2854
- * Pipeline for chaining Swarm operations.
2855
- *
2856
- * Swarm is bound at construction (infrastructure).
2857
- * Items are passed at execution (data).
2858
- * Pipeline is immutable - each method returns a new instance.
2859
- */
2860
- declare class Pipeline<T = FileMap> {
2861
- protected readonly swarm: Swarm;
2862
- protected readonly steps: Step[];
2863
- protected readonly events: PipelineEvents;
2864
- constructor(swarm: Swarm, steps?: Step[], events?: PipelineEvents);
2865
- /** Add a map step to transform items in parallel. */
2866
- map<U>(config: MapConfig<U>): Pipeline<U>;
2867
- /** Add a filter step to evaluate and filter items. */
2868
- filter<U>(config: FilterConfig<U>): Pipeline<U>;
2869
- /** Add a reduce step (terminal - no steps can follow). */
2870
- reduce<U>(config: ReduceConfig<U>): TerminalPipeline<U>;
2871
- /**
2872
- * Register event handlers for step lifecycle.
2873
- *
2874
- * Supports two styles:
2875
- * - Object: `.on({ onStepComplete: fn, onItemRetry: fn })`
2876
- * - Chainable: `.on("stepComplete", fn).on("itemRetry", fn)`
2877
- */
2878
- on(handlers: PipelineEvents): Pipeline<T>;
2879
- on<K extends keyof PipelineEventMap>(event: K, handler: PipelineEventMap[K]): Pipeline<T>;
2880
- /** Execute the pipeline with the given items. */
2881
- run(items: ItemInput[]): Promise<PipelineResult<T>>;
2882
- private executeStep;
2883
- private wrapRetry;
2884
- private wrapVerify;
2885
- private wrapBestOf;
2886
- }
2887
- /** Pipeline after reduce - no more steps can be added. */
2888
- declare class TerminalPipeline<T> extends Pipeline<T> {
2889
- constructor(swarm: Swarm, steps: Step[], events: PipelineEvents);
2890
- /**
2891
- * Register event handlers for step lifecycle.
2892
- *
2893
- * Supports two styles:
2894
- * - Object: `.on({ onStepComplete: fn, onItemRetry: fn })`
2895
- * - Chainable: `.on("stepComplete", fn).on("itemRetry", fn)`
2896
- */
2897
- on(handlers: PipelineEvents): TerminalPipeline<T>;
2898
- on<K extends keyof PipelineEventMap>(event: K, handler: PipelineEventMap[K]): TerminalPipeline<T>;
2899
- /** @throws Cannot add steps after reduce */
2900
- map(): never;
2901
- /** @throws Cannot add steps after reduce */
2902
- filter(): never;
2903
- /** @throws Cannot add steps after reduce */
2904
- reduce(): never;
2905
- }
2906
-
2907
- /**
2908
- * MCP JSON Configuration Writer
2909
- *
2910
- * Handles MCP config for Claude, Gemini, Qwen, Kimi, Droid, and OpenCode agents.
2911
- * Uses registry for paths - no hardcoded values.
2912
- *
2913
- * Transport formats by agent:
2914
- * - Claude: { type: "http"|"sse"|"stdio", url: "..." }
2915
- * - Gemini: { url: "...", type: "http"|"sse" } | { command: "..." }
2916
- * - Qwen: { httpUrl: "..." } | { url: "..." } | { command: "..." }
2917
- * - Kimi Code: { url: "...", transport?: "http"|"sse" } | { command: "...", transport: "stdio" }
2918
- */
2919
-
2920
- /**
2921
- * Write MCP config for Claude agent
2922
- *
2923
- * Claude uses two files:
2924
- * 1. ${workingDir}/.mcp.json - project-level MCP servers
2925
- * 2. ~/.claude/settings.json - enable project MCP servers
2926
- */
2927
- declare function writeClaudeMcpConfig(sandbox: SandboxInstance, workingDir: string, servers: Record<string, McpServerConfig>): Promise<void>;
2928
- /** Write MCP config for Gemini agent */
2929
- declare function writeGeminiMcpConfig(sandbox: SandboxInstance, servers: Record<string, McpServerConfig>): Promise<void>;
2930
- /** Write MCP config for Qwen agent */
2931
- declare function writeQwenMcpConfig(sandbox: SandboxInstance, servers: Record<string, McpServerConfig>): Promise<void>;
2932
- /**
2933
- * Write MCP config for Droid agent
2934
- *
2935
- * Droid supports project-level `.factory/mcp.json`, which keeps MCP config
2936
- * scoped to the sandbox workspace instead of mutating global user config.
2937
- */
2938
- declare function writeDroidMcpConfig(sandbox: SandboxInstance, workingDir: string, servers: Record<string, McpServerConfig>): Promise<void>;
2939
- interface DroidGatewaySettingsConfig {
2940
- settingsPath: string;
2941
- displayName: string;
2942
- model: string;
2943
- baseUrl: string;
2944
- apiKeyEnv: string;
2945
- provider: "generic-chat-completion-api" | "openai" | "anthropic";
2946
- maxOutputTokens?: number;
2947
- }
2948
- /**
2949
- * Write an Evolve-owned Droid settings file for gateway custom-model routing.
2950
- *
2951
- * The command passes this file with `droid --settings`, so it does not alter the
2952
- * user's normal ~/.factory/settings.json inside the sandbox.
2953
- */
2954
- declare function writeDroidGatewaySettings(sandbox: SandboxInstance, config: DroidGatewaySettingsConfig, headers: Record<string, string>): Promise<void>;
2955
-
2956
- /**
2957
- * MCP TOML Configuration Writer
2958
- *
2959
- * Handles MCP config for Codex agent which uses TOML format.
2960
- * Uses registry for paths - no hardcoded values.
2961
- */
2962
-
2963
- /**
2964
- * Write MCP config for Codex agent
2965
- *
2966
- * Codex stores MCP config in ~/.codex/config.toml using TOML format.
2967
- * Format: [mcp_servers.server_name] sections
2968
- */
2969
- declare function writeCodexMcpConfig(sandbox: SandboxInstance, servers: Record<string, McpServerConfig>): Promise<void>;
2970
-
2971
- /**
2972
- * MCP Configuration Module
2973
- *
2974
- * Unified entry point for writing MCP server configs.
2975
- * Routes to the appropriate writer based on agent type.
2976
- */
2977
-
2978
- /**
2979
- * Write MCP server configuration for an agent
2980
- *
2981
- * Routes to the appropriate config writer based on agent type:
2982
- * - Claude: JSON to ${workingDir}/.mcp.json + ~/.claude/settings.json
2983
- * - Codex: TOML to ~/.codex/config.toml
2984
- * - Gemini: JSON to ~/.gemini/settings.json
2985
- * - Qwen: JSON to ~/.qwen/settings.json
2986
- * - Droid: JSON to ${workingDir}/.factory/mcp.json
2987
- * - OpenCode: JSON to ${workingDir}/opencode.json (mcp key)
2988
- */
2989
- declare function writeMcpConfig(agentType: AgentType, sandbox: SandboxInstance, workingDir: string, servers: Record<string, McpServerConfig>): Promise<void>;
2990
-
2991
- /**
2992
- * Prompt Templates
2993
- *
2994
- * Prompts are stored as markdown files for easy editing.
2995
- * They are inlined at build time via tsup's text loader.
2996
- */
2997
-
2998
- /**
2999
- * Workspace system prompt template (knowledge mode)
3000
- *
3001
- * Placeholders:
3002
- * - {{workingDir}} - The working directory path
3003
- */
3004
- declare const WORKSPACE_PROMPT: string;
3005
- /**
3006
- * Workspace system prompt template (SWE mode - includes repo/ folder)
3007
- *
3008
- * Placeholders:
3009
- * - {{workingDir}} - The working directory path
3010
- */
3011
- declare const WORKSPACE_SWE_PROMPT: string;
3012
- /**
3013
- * User system prompt wrapper template
3014
- *
3015
- * Placeholders:
3016
- * - {{systemPrompt}} - The user's system prompt content
3017
- */
3018
- declare const SYSTEM_PROMPT: string;
3019
- /**
3020
- * Structured output schema prompt template (for Swarm abstractions)
3021
- *
3022
- * Placeholders:
3023
- * - {{schema}} - JSON schema for the expected output
3024
- */
3025
- declare const SCHEMA_PROMPT: string;
3026
- /**
3027
- * Actionbook browser automation prompt fragment
3028
- */
3029
- declare const BROWSER_ACTIONBOOK_PROMPT: string;
3030
- /**
3031
- * Judge system prompt template (for Swarm best_of)
3032
- *
3033
- * Placeholders:
3034
- * - {{candidateCount}} - Number of candidates
3035
- * - {{criteria}} - Evaluation criteria
3036
- * - {{fileTree}} - Tree view of context folders
3037
- */
3038
- declare const JUDGE_PROMPT: string;
3039
- /**
3040
- * Verify system prompt template (for Swarm verify option)
3041
- *
3042
- * Placeholders:
3043
- * - {{criteria}} - Verification criteria
3044
- * - {{fileTree}} - Tree view of context folders
3045
- */
3046
- declare const VERIFY_PROMPT: string;
3047
- /**
3048
- * Retry feedback prompt template (for Swarm verify retry)
3049
- *
3050
- * Replaces the user prompt when verification fails and retry is needed.
3051
- *
3052
- * Placeholders:
3053
- * - {{originalPrompt}} - The original user prompt
3054
- * - {{feedback}} - Verifier's feedback on what needs to be fixed
3055
- */
3056
- declare const RETRY_FEEDBACK_PROMPT: string;
3057
- /**
3058
- * Apply template variables to a prompt
3059
- */
3060
- declare function applyTemplate(template: string, variables: Record<string, string>): string;
3061
- /**
3062
- * Build worker system prompt
3063
- *
3064
- * Used by Agent class to generate the system prompt file written to sandbox.
3065
- *
3066
- * @param mode - "knowledge" (default) or "swe" (includes repo/ folder)
3067
- */
3068
- declare function buildWorkerSystemPrompt(options: {
3069
- workingDir: string;
3070
- systemPrompt?: string;
3071
- browserPrompt?: string;
3072
- schema?: z.ZodType<unknown> | Record<string, unknown>;
3073
- mode?: "knowledge" | "swe";
3074
- }): string;
3075
-
3076
- /**
3077
- * Schema Utilities
3078
- *
3079
- * Functions for working with Zod and JSON Schema.
3080
- */
3081
-
3082
- /**
3083
- * Check if a schema is a Zod schema (has safeParse method)
3084
- */
3085
- declare function isZodSchema(schema: unknown): schema is z.ZodType<unknown>;
3086
- /**
3087
- * Convert Zod schema to JSON Schema string
3088
- */
3089
- declare function zodSchemaToJson(schema: z.ZodType<unknown>): string;
3090
- /**
3091
- * Convert JSON Schema object to formatted string
3092
- */
3093
- declare function jsonSchemaToString(schema: Record<string, unknown>): string;
3094
-
3095
- /**
3096
- * File Utilities
3097
- *
3098
- * Functions for reading and writing local files as FileMaps.
3099
- */
3100
-
3101
- /**
3102
- * Read files from a local directory, returning a FileMap.
3103
- *
3104
- * @param localPath - Path to local directory
3105
- * @param recursive - Read subdirectories recursively (default: false)
3106
- * @returns FileMap with relative paths as keys
3107
- *
3108
- * @example
3109
- * // Top-level files only (default)
3110
- * readLocalDir('./folder')
3111
- * // { "file.txt": Buffer }
3112
- *
3113
- * // Recursive - includes subdirectories
3114
- * readLocalDir('./folder', true)
3115
- * // { "file.txt": Buffer, "subdir/nested.txt": Buffer }
3116
- */
3117
- declare function readLocalDir(localPath: string, recursive?: boolean): FileMap;
3118
- /**
3119
- * Save a FileMap to a local directory, creating nested directories as needed.
3120
- *
3121
- * @param localPath - Base directory to save files to
3122
- * @param files - FileMap to save (from getOutputFiles or other source)
3123
- *
3124
- * @example
3125
- * // Save output files to local directory
3126
- * const output = await agent.getOutputFiles(true);
3127
- * saveLocalDir('./output', output.files);
3128
- * // Creates: ./output/file.txt, ./output/subdir/nested.txt, etc.
3129
- */
3130
- declare function saveLocalDir(localPath: string, files: FileMap): void;
3131
-
3132
- /**
3133
- * Storage & Checkpointing Module
3134
- *
3135
- * Provides durable persistence for agent workspaces beyond sandbox lifetime.
3136
- * Supports BYOK (user's S3 bucket) and Gateway (Evolve-managed) modes.
3137
- *
3138
- * Evidence: storage-checkpointing plan v2.2
3139
- */
3140
-
3141
- /**
3142
- * Resolve storage configuration from user input.
3143
- *
3144
- * BYOK mode: URL provided → parse into bucket/prefix, use S3 client directly
3145
- * Gateway mode: no URL → use dashboard API endpoints
3146
- */
3147
- declare function resolveStorageConfig(config: StorageConfig | undefined, isGateway: boolean, gatewayUrl?: string, gatewayApiKey?: string): ResolvedStorageConfig;
3148
- declare function storage(config?: StorageConfig): StorageClient;
3149
-
3150
- /** Options for listing sessions */
3151
- interface ListSessionsOptions {
3152
- /** Max items per page (default: 20, max: 200) */
3153
- limit?: number;
3154
- /** Cursor for pagination (from SessionPage.nextCursor) */
3155
- cursor?: string;
3156
- /** Filter by session state */
3157
- state?: "live" | "ended" | "all";
3158
- /** Filter by agent type (e.g., "claude", "codex") */
3159
- agent?: string;
3160
- /** Filter by tag prefix */
3161
- tagPrefix?: string;
3162
- /** Sort order (default: "newest") */
3163
- sort?: "newest" | "oldest" | "cost";
3164
- }
3165
- /** Paginated list of sessions */
3166
- interface SessionPage {
3167
- items: SessionInfo[];
3168
- nextCursor: string | null;
3169
- hasMore: boolean;
3170
- }
3171
- /** Session metadata */
3172
- interface SessionInfo {
3173
- id: string;
3174
- tag: string;
3175
- agent: string;
3176
- model: string | null;
3177
- provider: string;
3178
- sandboxId: string | null;
3179
- /** Ergonomic state: "live" (still running) or "ended" */
3180
- state: "live" | "ended";
3181
- /** Granular runtime status from dashboard */
3182
- runtimeStatus: "alive" | "dead" | "unknown";
3183
- /** Cost in USD. null if not synced yet. Eventually consistent. */
3184
- cost: number | null;
3185
- createdAt: string;
3186
- endedAt: string | null;
3187
- stepCount: number;
3188
- toolStats: Record<string, number> | null;
3189
- }
3190
- /** Raw parsed JSONL event — no imposed schema */
3191
- type SessionEvent = Record<string, unknown>;
3192
- /** Options for downloading a session trace */
3193
- interface DownloadSessionOptions {
3194
- /** Directory to save the JSONL file (default: cwd) */
3195
- to?: string;
3196
- }
3197
- /** Options for waiting on browser replay readiness */
3198
- interface BrowserReplayOptions {
3199
- /** Max time to wait for replay readiness (default: 600000ms) */
3200
- timeoutMs?: number;
3201
- /** Poll interval while replay is processing (default: 5000ms) */
3202
- intervalMs?: number;
3203
- }
3204
- /** Browser replay metadata and access URLs */
3205
- interface BrowserReplay {
3206
- sessionId: string;
3207
- status: "ready";
3208
- replayUrl: string;
3209
- downloadUrl: string;
3210
- suggestedStartSeconds?: number;
3211
- sizeBytes?: number;
3212
- readyAt?: string;
3213
- }
3214
- /** Options for fetching parsed events */
3215
- interface GetEventsOptions {
3216
- /** Return only events after this index (delta fetching) */
3217
- since?: number;
3218
- }
3219
- /** Configuration for sessions() factory */
3220
- interface SessionsConfig {
3221
- /** API key (default: process.env.EVOLVE_API_KEY) */
3222
- apiKey?: string;
3223
- /** Dashboard URL override (default: DEFAULT_DASHBOARD_URL) */
3224
- dashboardUrl?: string;
3225
- }
3226
- /** Sessions client for querying past sessions and downloading traces */
3227
- interface SessionsClient {
3228
- /** List sessions with optional filtering and pagination */
3229
- list(options?: ListSessionsOptions): Promise<SessionPage>;
3230
- /** Get a single session by ID */
3231
- get(id: string): Promise<SessionInfo>;
3232
- /** Get parsed JSONL events for a session */
3233
- events(id: string, options?: GetEventsOptions): Promise<SessionEvent[]>;
3234
- /** Download raw JSONL trace file. Returns the file path. */
3235
- download(id: string, options?: DownloadSessionOptions): Promise<string>;
3236
- /** Wait for browser replay and return Dashboard-owned replay/download URLs. */
3237
- browserReplay(id: string, options?: BrowserReplayOptions): Promise<BrowserReplay>;
3238
- }
3239
-
3240
- /**
3241
- * Create a SessionsClient for querying past sessions and downloading traces.
3242
- *
3243
- * Gateway-only — requires EVOLVE_API_KEY.
3244
- *
3245
- * @example
3246
- * ```ts
3247
- * import { sessions } from "@evolvingmachines/sdk";
3248
- *
3249
- * const s = sessions();
3250
- * const page = await s.list({ limit: 20, state: "ended" });
3251
- * const events = await s.events(page.items[0].id);
3252
- * await s.download(page.items[0].id, { to: "./traces" });
3253
- * ```
3254
- */
3255
- declare function sessions(config?: SessionsConfig): SessionsClient;
3256
-
3257
- export { AGENT_REGISTRY, AGENT_TYPES, type ActionbookBrowserConfig, Agent, type AgentBrowserConfig, type AgentConfig, type AgentOptions, type AgentOverride, type AgentParser, type AgentPluginConfig, type AgentRegistryEntry, type AgentResponse, type AgentRuntimeState, type AgentType, BROWSER_ACTIONBOOK_PROMPT, BROWSER_LOGIN_MCP_SERVER_NAME, type BaseMeta, type BestOfConfig, type BestOfParams, type BestOfResult, type BrowserConfig, type BrowserCredentialCreateInput, type BrowserCredentialDeleteInput, type BrowserCredentialListOptions, type BrowserCredentialMetadata, type BrowserCredentialScopeEntry, BrowserCredentialsClient, type BrowserCredentialsClientConfig, type BrowserCredentialsConfig, type BrowserProfileDeleteInput, type BrowserProfileMetadata, BrowserProfilesClient, type BrowserProfilesClientConfig, type BrowserProvider, type BrowserReplay, type BrowserReplayOptions, type BrowserRuntimeInfo, type CandidateCompleteEvent, type CheckpointInfo, type CodexAgentPluginConfig, type DefaultBrowserConfig, type DownloadCheckpointOptions, type DownloadFilesOptions, type DownloadSessionOptions, type EmitOption, type EventHandler, type EventName, Evolve, type EvolveConfig, type EvolveEvents, type ExecuteCommandOptions, type FileMap, type FilterConfig, type FilterParams, type GeminiAgentPluginConfig, type GetEventsOptions, type IndexedMeta, type IntegrationAccount, type IntegrationAccountDeleteParams, type IntegrationAccountDeleteResult, type IntegrationAccountListParams, type IntegrationAccountUpdateParams, type IntegrationAccountUpdateResult, type IntegrationAuthParams, type IntegrationAuthResult, type IntegrationToolsFilter, type IntegrationsConfig, type IntegrationsSetup, type ItemInput, type ItemRetryEvent, JUDGE_PROMPT, type JsonSchema, type JudgeCompleteEvent, type JudgeDecision, type JudgeMeta, type LifecycleEvent, type LifecycleReason, type ListSessionsOptions, type ManagedBrowserProvider, type ManagedSecretMetadata, type ManagedSecretRef, type ManagedSecretsClient, type ManagedSecretsClientConfig, type MapConfig, type MapParams, type MarketplaceAgentPluginConfig, type McpConfigInfo, type McpServerConfig, type ModelInfo, type OnCandidateCompleteCallback, type OnItemRetryCallback, type OnJudgeCompleteCallback, type OnVerifierCompleteCallback, type OnWorkerCompleteCallback, type OperationType, type OutputEvent, type OutputResult, Pipeline, type PipelineContext, type PipelineEventMap, type PipelineEvents, type PipelineResult, type ProcessInfo, type Prompt, type PromptFn, RETRY_FEEDBACK_PROMPT, type ReasoningEffort, type ReduceConfig, type ReduceMeta, type ReduceParams, type ReduceResult, type ResolvedStorageConfig, type RetryConfig, type RunCost, type RunOptions, SCHEMA_PROMPT, SWARM_RESULT_BRAND, SYSTEM_PROMPT, type SandboxCommandHandle, type SandboxCommandResult, type SandboxCommands, type SandboxCreateOptions, type SandboxFiles, type SandboxInstance, type SandboxLifecycleState, type SandboxProvider, type SandboxRunOptions, type SandboxSpawnOptions, type SchemaValidationOptions, Semaphore, type SessionCost, type SessionEvent, type SessionInfo, type SessionPage, type SessionStatus, type SessionsClient, type SessionsConfig, type SkillName, type SkillsConfig, type StepCompleteEvent, type StepErrorEvent, type StepEvent, type StepResult, type StepStartEvent, type StorageClient, type StorageConfig, type StreamCallbacks, Swarm, type SwarmConfig, type SwarmResult, SwarmResultList, TerminalPipeline, VALIDATION_PRESETS, VERIFY_PROMPT, type ValidationMode, type VerifierCompleteEvent, type VerifyConfig, type VerifyDecision, type VerifyInfo, type VerifyMeta, WORKSPACE_PROMPT, WORKSPACE_SWE_PROMPT, type WorkerCompleteEvent, type WorkspaceMode, applyTemplate, browserCredentials, browserProfiles, buildWorkerSystemPrompt, createAgentParser, createClaudeParser, createCodexParser, createDroidParser, createGeminiParser, executeWithRetry, expandPath, getAgentConfig, getMcpSettingsDir, getMcpSettingsPath, isValidAgentType, isZodSchema, jsonSchemaToString, managedSecrets, parseNdjsonLine, parseNdjsonOutput, parseQwenOutput, readLocalDir, resolveStorageConfig, saveLocalDir, sessions, storage, writeClaudeMcpConfig, writeCodexMcpConfig, writeDroidGatewaySettings, writeDroidMcpConfig, writeGeminiMcpConfig, writeMcpConfig, writeQwenMcpConfig, zodSchemaToJson };