agent-worker 0.18.0 → 0.19.0

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.mts CHANGED
@@ -1,889 +1,289 @@
1
- import { LanguageModel } from "ai";
2
- import { BashToolkit, CreateBashToolOptions, createBashTool } from "bash-tool";
3
- import { z } from "zod/v4";
1
+ import { Hono } from "hono";
2
+ import { AgentDefinition, AgentResponse, AgentWorker, AgentWorkerConfig, BackendType, CreateSkillToolOptions, Logger, ProviderConfig, ScheduleConfig, SendOptions, SendOptions as SendOptions$1, SessionState, SkillImporter, SkillToolkit, StepInfo, createSkillTool } from "@moniro/agent-loop";
3
+ import { ConversationLog, PersonalContextProvider, ThinThread } from "@moniro/agent-worker";
4
+ import { AgentInstruction, AgentLoop, EventKind, EventSink, Message, ParsedWorkflow, Workspace } from "@moniro/workspace";
4
5
 
5
- //#region src/backends/model-maps.d.ts
6
- /**
7
- * Model Translation Maps — Single Source of Truth
8
- *
9
- * All backend-specific model naming and translation logic lives here.
10
- * Both `backends/types.ts` and `workflow/loop/types.ts` re-export from this module.
11
- */
12
- /** Backend type (union of all supported backends) */
13
- type BackendType = "default" | "claude" | "cursor" | "codex" | "opencode" | "mock";
14
- //#endregion
15
- //#region src/backends/types.d.ts
16
- interface BackendConfig {
17
- type: BackendType;
18
- /** Model identifier (interpretation depends on backend) */
19
- model?: string;
20
- /** Additional CLI flags or SDK options */
21
- options?: Record<string, unknown>;
22
- }
23
- interface BackendResponse {
24
- content: string;
25
- /** Tool calls made during execution (if supported) */
26
- toolCalls?: Array<{
27
- name: string;
28
- arguments: unknown;
29
- result: unknown;
30
- }>;
31
- /** Usage statistics (if available) */
32
- usage?: {
33
- input: number;
34
- output: number;
35
- total: number;
36
- };
37
- }
38
- interface Backend {
39
- readonly type: BackendType;
40
- /** Send a message and get a response */
41
- send(message: string, options?: {
42
- system?: string;
43
- }): Promise<BackendResponse>;
44
- /** Check if the backend is available (CLI installed, API key set, etc.) */
45
- isAvailable?(): Promise<boolean>;
46
- /** Get backend info for display */
47
- getInfo?(): {
48
- name: string;
49
- version?: string;
50
- model?: string;
51
- };
52
- /** Abort any running operations and cleanup resources */
53
- abort?(): void;
54
- }
55
- //#endregion
56
- //#region src/workflow/types.d.ts
57
- /**
58
- * Custom provider configuration for API endpoint overrides.
59
- * Allows pointing any compatible SDK at a different base URL.
60
- *
61
- * Examples:
62
- * provider: anthropic # string → built-in provider
63
- * provider: # object → custom endpoint
64
- * name: anthropic
65
- * base_url: https://api.minimax.io/anthropic/v1
66
- * api_key: $MINIMAX_API_KEY
67
- */
68
- interface ProviderConfig {
69
- /** Provider SDK name (e.g., 'anthropic', 'openai') */
70
- name: string;
71
- /** Override base URL for the provider */
72
- base_url?: string;
73
- /** API key — env var reference with '$' prefix (e.g., '$MINIMAX_API_KEY') or literal value */
74
- api_key?: string;
75
- }
76
- //#endregion
77
- //#region src/agent/types.d.ts
78
- /**
79
- * Message status for streaming/response tracking
80
- */
81
- type MessageStatus = "responding" | "complete";
82
- /**
83
- * Extended message with status for tracking streaming state
84
- */
85
- interface AgentMessage {
86
- role: "user" | "assistant" | "system" | "tool";
87
- content: string;
88
- /** Message status - 'responding' while streaming, 'complete' when done */
89
- status?: MessageStatus;
90
- /** Timestamp when message started */
91
- timestamp?: string;
92
- }
93
- /**
94
- * Approval check — static boolean or dynamic function
95
- */
96
- type ApprovalCheck = boolean | ((args: Record<string, unknown>) => boolean);
97
- /**
98
- * Tool info returned by getTools() — read-only view
99
- */
100
- interface ToolInfo {
101
- name: string;
102
- description?: string;
103
- needsApproval: boolean;
104
- }
105
- /**
106
- * A pending tool call awaiting user approval
107
- */
108
- interface PendingApproval {
109
- /** Unique approval ID */
110
- id: string;
111
- /** Tool name */
112
- toolName: string;
113
- /** Tool call ID from the model */
114
- toolCallId: string;
115
- /** Arguments passed to the tool */
116
- arguments: Record<string, unknown>;
117
- /** When the approval was requested */
118
- requestedAt: string;
119
- /** Current status */
120
- status: "pending" | "approved" | "denied";
121
- /** Denial reason if denied */
122
- denyReason?: string;
123
- }
124
- /**
125
- * A single tool call with its result
126
- */
127
- interface ToolCall {
128
- name: string;
129
- arguments: Record<string, unknown>;
130
- result: unknown;
131
- timing: number;
132
- }
133
- /**
134
- * Token usage statistics
135
- */
136
- interface TokenUsage {
137
- input: number;
138
- output: number;
139
- total: number;
140
- }
141
- /**
142
- * Response from a single message exchange
143
- */
144
- interface AgentResponse {
145
- /** Final text content */
146
- content: string;
147
- /** All tool calls made during this turn */
148
- toolCalls: ToolCall[];
149
- /** Tool calls awaiting approval (response is incomplete until approved) */
150
- pendingApprovals: PendingApproval[];
151
- /** Token usage */
152
- usage: TokenUsage;
153
- /** Response latency in ms */
154
- latency: number;
155
- }
156
- /**
157
- * Session configuration
158
- */
159
- interface SessionConfig {
160
- /** Model identifier (e.g., 'openai/gpt-5.2' or 'anthropic:claude-sonnet-4-5') */
161
- model: string;
162
- /** System prompt */
163
- system: string;
164
- /** AI SDK tools — Record<name, tool()> */
165
- tools?: Record<string, unknown>;
166
- /** Per-tool approval config — Record<name, boolean | (args) => boolean> */
167
- approval?: Record<string, ApprovalCheck>;
168
- /** Maximum tokens for response (default: 4096) */
169
- maxTokens?: number;
170
- /** Maximum tool call steps per turn (default: 200) */
171
- maxSteps?: number;
172
- }
173
- /**
174
- * Persisted session state for restoration
175
- */
176
- interface SessionState {
177
- /** Session ID to restore */
178
- id: string;
179
- /** Creation timestamp */
180
- createdAt: string;
181
- /** Conversation messages with status */
182
- messages: AgentMessage[];
183
- /** Accumulated token usage */
184
- totalUsage: TokenUsage;
185
- /** Pending tool approvals */
186
- pendingApprovals: PendingApproval[];
187
- }
188
- /**
189
- * Exported transcript for analysis
190
- */
191
- interface Transcript {
192
- sessionId: string;
193
- model: string;
194
- system: string;
195
- messages: AgentMessage[];
196
- totalUsage: TokenUsage;
197
- createdAt: string;
198
- }
199
- //#endregion
200
- //#region src/agent/worker.d.ts
201
- /**
202
- * Extended worker config that supports both SDK and CLI backends.
203
- * When a backend is provided, send() delegates to it instead of ToolLoopAgent.
204
- * This enables unified worker management regardless of backend type.
205
- */
206
- interface AgentWorkerConfig extends SessionConfig {
207
- /** CLI backend - when provided, send() delegates to this backend */
208
- backend?: Backend;
209
- /** Provider configuration — when set, model is resolved via createModelWithProvider */
210
- provider?: string | ProviderConfig;
211
- }
212
- /**
213
- * Step finish callback info
214
- */
215
- interface StepInfo {
216
- stepNumber: number;
217
- toolCalls: ToolCall[];
218
- usage: TokenUsage;
219
- }
220
- /**
221
- * Options for send() method
222
- */
223
- interface SendOptions {
224
- /** Auto-approve all tool calls that require approval (default: true) */
225
- autoApprove?: boolean;
226
- /** Callback after each agent step */
227
- onStepFinish?: (info: StepInfo) => void | Promise<void>;
228
- }
229
- /**
230
- * AgentWorker - Stateful worker for controlled agent execution
231
- *
232
- * Uses ToolLoopAgent internally for multi-step reasoning loops.
233
- * Maintains conversation state across multiple send() calls,
234
- * enabling improvisational testing where you observe responses
235
- * and decide next actions.
236
- *
237
- * Tools are AI SDK tool() objects passed as Record<name, tool()>.
238
- * Approval is configured separately via Record<name, check>.
239
- */
240
- declare class AgentWorker {
241
- readonly id: string;
242
- readonly model: string;
243
- readonly system: string;
244
- readonly createdAt: string;
245
- private tools;
246
- private approval;
247
- private maxTokens;
248
- private maxSteps;
249
- private messages;
250
- private totalUsage;
251
- private pendingApprovals;
252
- private backend;
253
- private provider;
254
- private cachedAgent;
255
- private toolsChanged;
256
- /**
257
- * Whether this session supports tool management (SDK backend only)
258
- */
259
- get supportsTools(): boolean;
260
- /**
261
- * Convert AgentMessage[] to ModelMessage[] for AI SDK
262
- */
263
- private toModelMessages;
264
- constructor(config: AgentWorkerConfig, restore?: SessionState);
265
- /**
266
- * Check if a tool needs approval for given arguments
267
- */
268
- private checkApproval;
269
- /**
270
- * Build tools with approval wrapping for ToolLoopAgent
271
- */
272
- private buildTools;
273
- /**
274
- * Get or create cached agent, rebuild if tools changed
275
- */
276
- private getAgent;
277
- /**
278
- * Send a message via CLI backend (non-SDK path)
279
- */
280
- private sendViaBackend;
6
+ //#region src/agent/agent-handle.d.ts
7
+ type AgentHandleState = "idle" | "running" | "stopped" | "error";
8
+ declare class AgentHandle implements PersonalContextProvider {
9
+ /** Agent definition (from YAML or API) */
10
+ readonly definition: AgentDefinition;
11
+ /** Absolute path to agent's persistent context directory */
12
+ readonly contextDir: string;
13
+ /**
14
+ * Whether this agent is ephemeral (in-memory only).
15
+ * Ephemeral agents are created via the daemon API (POST /agents) and
16
+ * lost on daemon restart. Config agents are defined in config.yml.
17
+ */
18
+ readonly ephemeral: boolean;
19
+ /** Current agent state */
20
+ state: AgentHandleState;
21
+ /** The agent's execution loop (lazy created on first run/serve) */
22
+ loop: AgentLoop | null;
23
+ /** Conversation log (lazy — created on first access) */
24
+ private _conversationLog?;
25
+ /** Thin thread (lazy — created on first access) */
26
+ private _thinThread?;
27
+ /** Optional logger (injected by registry; absent in standalone CLI) */
28
+ private log?;
29
+ constructor(definition: AgentDefinition, contextDir: string, logger?: Logger, ephemeral?: boolean);
30
+ /** Agent name (convenience accessor) */
31
+ get name(): string;
32
+ /**
33
+ * Get the conversation log (JSONL persistence).
34
+ * Returns null for ephemeral agents (no disk).
35
+ * Lazy — created on first access.
36
+ */
37
+ get conversationLog(): ConversationLog | null;
38
+ /**
39
+ * Get the thin thread (bounded in-memory conversation buffer).
40
+ * Restores from ConversationLog on first access if history exists.
41
+ * Lazy created on first access.
42
+ */
43
+ get thinThread(): ThinThread;
44
+ /**
45
+ * Send a typed instruction to this agent's loop.
46
+ *
47
+ * Convenience method that creates an AgentInstruction and enqueues it.
48
+ * The loop must exist (call ensureAgentLoop first for standalone agents).
49
+ *
50
+ * @throws if no loop is attached
51
+ */
52
+ send(instruction: AgentInstruction): void;
53
+ /**
54
+ * Send a simple message with auto-classified priority.
55
+ *
56
+ * Shorthand for creating an AgentInstruction from a raw message string.
57
+ */
58
+ sendMessage(message: string, options?: {
59
+ priority?: AgentInstruction["priority"];
60
+ source?: AgentInstruction["source"];
61
+ }): void;
281
62
  /**
282
- * Send a message and get the agent's response
63
+ * Ensure the context directory and all subdirectories exist.
64
+ * Called on agent load/creation. Idempotent.
283
65
  */
284
- send(content: string, options?: SendOptions): Promise<AgentResponse>;
66
+ ensureContextDir(): void;
285
67
  /**
286
- * Send a message and stream the response
68
+ * Read all memory entries as key-value records.
69
+ * Memory files are YAML in memory/<key>.yaml.
287
70
  */
288
- sendStream(content: string, options?: SendOptions): AsyncGenerator<string, AgentResponse, unknown>;
71
+ readMemory(): Promise<Record<string, unknown>>;
289
72
  /**
290
- * Add an AI SDK tool
291
- * Only supported for SDK backends (ToolLoopAgent)
73
+ * Write a memory entry. Creates/overwrites memory/<key>.yaml.
292
74
  */
293
- addTool(name: string, t: unknown): void;
75
+ writeMemory(key: string, value: unknown): Promise<void>;
294
76
  /**
295
- * Set approval requirement for a tool
77
+ * Read agent's notes, most recent first.
78
+ * Notes are markdown files in notes/.
296
79
  */
297
- setApproval(name: string, check: ApprovalCheck): void;
80
+ readNotes(limit?: number): Promise<string[]>;
298
81
  /**
299
- * Replace a tool's execute function (for testing)
82
+ * Append a note. Creates notes/<date>-<slug>.md.
300
83
  */
301
- mockTool(name: string, mockFn: (args: Record<string, unknown>) => unknown): void;
84
+ appendNote(content: string, slug?: string): Promise<string>;
302
85
  /**
303
- * Set a static mock response for an existing tool
86
+ * Read active todos from todo/index.md.
87
+ * Returns lines that look like incomplete tasks: "- [ ] ..."
304
88
  */
305
- setMockResponse(name: string, response: unknown): void;
89
+ readTodos(): Promise<string[]>;
306
90
  /**
307
- * Get tool info (names, descriptions, approval status)
91
+ * Write the full todo list. Replaces todo/index.md.
308
92
  */
309
- getTools(): ToolInfo[];
310
- history(): AgentMessage[];
311
- stats(): {
312
- messageCount: number;
313
- usage: TokenUsage;
314
- };
315
- export(): Transcript;
316
- getState(): SessionState;
317
- getPendingApprovals(): PendingApproval[];
318
- approve(approvalId: string): Promise<unknown>;
319
- deny(approvalId: string, reason?: string): void;
320
- clear(): void;
93
+ writeTodos(todos: string[]): Promise<void>;
321
94
  }
322
95
  //#endregion
323
- //#region src/agent/models.d.ts
324
- /**
325
- * Parse model identifier and return the appropriate provider model
326
- *
327
- * Supports three formats:
328
- *
329
- * 1. Provider-only format: provider
330
- * Uses first model from FRONTIER_MODELS via gateway
331
- * Examples: anthropic → anthropic/claude-sonnet-4-5, openai → openai/gpt-5.2
332
- *
333
- * 2. Gateway format: provider/model-name
334
- * Uses Vercel AI Gateway (requires AI_GATEWAY_API_KEY)
335
- * Examples: anthropic/claude-sonnet-4-5, openai/gpt-5.2, deepseek/deepseek-chat
336
- *
337
- * 3. Direct provider format: provider:model-name
338
- * Requires installing the specific @ai-sdk/provider package
339
- * Examples: anthropic:claude-sonnet-4-5, openai:gpt-5.2, deepseek:deepseek-chat
340
- */
341
- declare function createModel(modelId: string): LanguageModel;
342
- /**
343
- * Async version of createModel - supports lazy loading of direct providers
344
- * Use this when you need direct provider access (provider:model format)
345
- */
346
- declare function createModelAsync(modelId: string): Promise<LanguageModel>;
347
- /**
348
- * List of supported providers for direct access
349
- */
350
- declare const SUPPORTED_PROVIDERS: readonly ["anthropic", "openai", "deepseek", "google", "groq", "mistral", "xai"];
351
- type SupportedProvider = (typeof SUPPORTED_PROVIDERS)[number];
352
- /**
353
- * Frontier models for each provider (as of 2026-02)
354
- * Only includes the latest/best models, no legacy versions
355
- *
356
- * Note: Some models may be placeholders for testing or future releases.
357
- * Always verify model availability with the provider before production use.
358
- */
359
- declare const FRONTIER_MODELS: {
360
- readonly anthropic: readonly ["claude-sonnet-4-5", "claude-haiku-4-5", "claude-opus-4-5"];
361
- readonly openai: readonly ["gpt-5.2", "gpt-5.2-codex"];
362
- readonly google: readonly ["gemini-3-pro-preview", "gemini-2.5-flash", "gemini-2.5-pro"];
363
- readonly deepseek: readonly ["deepseek-chat", "deepseek-reasoner"];
364
- readonly groq: readonly ["meta-llama/llama-4-scout-17b-16e-instruct", "deepseek-r1-distill-llama-70b"];
365
- readonly mistral: readonly ["mistral-large-latest", "pixtral-large-latest", "magistral-medium-2506"];
366
- readonly xai: readonly ["grok-4", "grok-4-fast-reasoning"];
367
- };
368
- //#endregion
369
- //#region src/agent/tools/bash.d.ts
370
- /**
371
- * Options for creating bash tools compatible with AgentWorker
372
- */
373
- interface BashToolsOptions extends CreateBashToolOptions {
374
- /**
375
- * Include readFile tool (default: true)
376
- */
377
- includeReadFile?: boolean;
378
- /**
379
- * Include writeFile tool (default: true)
380
- */
381
- includeWriteFile?: boolean;
96
+ //#region src/agent/agent-registry.d.ts
97
+ declare class AgentRegistry {
98
+ /** Loaded agent handles, keyed by name */
99
+ private agents;
100
+ /** Workspace root directory (e.g. ~/.agent-worker/ for global) */
101
+ readonly projectDir: string;
102
+ /** Optional logger (injected by daemon) */
103
+ private log?;
104
+ constructor(projectDir: string, logger?: Logger);
105
+ /**
106
+ * Register a config agent (from config.yml). Creates context dir on disk.
107
+ * Overwrites existing agent with same name (reload semantics).
108
+ */
109
+ registerDefinition(def: AgentDefinition): AgentHandle;
110
+ /**
111
+ * Register an ephemeral agent (from daemon API).
112
+ * Exists only in memory, lost on restart.
113
+ */
114
+ registerEphemeral(def: AgentDefinition): AgentHandle;
115
+ /**
116
+ * Unregister an agent from memory.
117
+ * @returns true if agent existed and was removed.
118
+ */
119
+ delete(name: string): boolean;
120
+ /** Get agent handle by name */
121
+ get(name: string): AgentHandle | undefined;
122
+ /** Check if agent exists */
123
+ has(name: string): boolean;
124
+ /** List all registered agent handles */
125
+ list(): AgentHandle[];
126
+ /** Number of registered agents */
127
+ get size(): number;
128
+ /** Resolve agent's context directory (absolute path) */
129
+ private resolveContextDir;
382
130
  }
383
- /**
384
- * Create bash tools as AI SDK tool() objects for use with AgentWorker
385
- *
386
- * @example
387
- * ```typescript
388
- * const { tools } = await createBashTools({
389
- * files: { 'src/index.ts': 'console.log("hello")' }
390
- * })
391
- *
392
- * const session = new AgentWorker({
393
- * model: 'anthropic/claude-sonnet-4-5',
394
- * system: 'You are a coding assistant.',
395
- * tools
396
- * })
397
- * ```
398
- */
399
- declare function createBashTools(options?: BashToolsOptions): Promise<{
400
- tools: Record<string, unknown>;
401
- toolkit: BashToolkit;
402
- }>;
403
- /**
404
- * Quick helper to create bash tools with a directory
405
- */
406
- declare function createBashToolsFromDirectory(source: string, options?: Omit<BashToolsOptions, "uploadDirectory">): Promise<{
407
- tools: Record<string, unknown>;
408
- toolkit: BashToolkit;
409
- }>;
410
- /**
411
- * Quick helper to create bash tools with inline files
412
- */
413
- declare function createBashToolsFromFiles(files: Record<string, string>, options?: Omit<BashToolsOptions, "files">): Promise<{
414
- tools: Record<string, unknown>;
415
- toolkit: BashToolkit;
416
- }>;
417
131
  //#endregion
418
- //#region src/agent/tools/feedback.d.ts
419
- /**
420
- * Feedback tool lets agents surface workflow improvement needs
421
- *
422
- * When enabled, agents can report what's missing or inconvenient during work:
423
- * a tool they wished they had, a step that felt unnecessarily slow, or a
424
- * capability gap. The purpose is workflow improvement, not bug reporting.
425
- *
426
- * @example
427
- * ```typescript
428
- * const { tool, getFeedback } = createFeedbackTool();
429
- *
430
- * const session = new AgentWorker({
431
- * model: 'anthropic/claude-sonnet-4-5',
432
- * system: FEEDBACK_PROMPT + '\nYou are a coding assistant.',
433
- * tools: { feedback: tool, bash: bashTool },
434
- * });
435
- *
436
- * await session.send('...');
437
- * console.log(getFeedback()); // review what the agent reported
438
- * ```
439
- */
440
- interface FeedbackEntry {
441
- /** ISO timestamp */
442
- timestamp: string;
443
- /** What area this is about — a tool name, workflow step, etc. */
444
- target: string;
445
- /** Category */
446
- type: "missing" | "friction" | "suggestion";
447
- /** What the agent needed or what could be improved */
448
- description: string;
449
- /** Optional: what the agent was trying to do */
450
- context?: string;
451
- }
452
- interface FeedbackToolOptions {
453
- /** Called each time the agent submits feedback */
454
- onFeedback?: (entry: FeedbackEntry) => void;
455
- /** Maximum entries to keep (default: 50) */
456
- maxEntries?: number;
457
- }
458
- interface FeedbackToolResult {
459
- /** AI SDK tool() object — pass to AgentWorker as a tool */
460
- tool: unknown;
461
- /** Retrieve all collected feedback entries */
462
- getFeedback(): FeedbackEntry[];
463
- /** Clear collected feedback */
464
- clearFeedback(): void;
132
+ //#region src/agent/store.d.ts
133
+ interface StateStore {
134
+ /** Load conversation state for an agent. Returns null if no state exists. */
135
+ load(agentId: string): Promise<SessionState | null>;
136
+ /** Save conversation state for an agent. */
137
+ save(agentId: string, state: SessionState): Promise<void>;
138
+ /** Delete conversation state for an agent. */
139
+ delete(agentId: string): Promise<void>;
465
140
  }
466
141
  /**
467
- * Append this to the system prompt when the feedback tool is enabled.
468
- * Tells the agent the tool exists and when to use it.
142
+ * In-memory state store. State is lost when the daemon stops.
143
+ * Suitable for development and single-machine deployments.
469
144
  */
470
- declare const FEEDBACK_PROMPT: string;
471
- declare function createFeedbackTool(options?: FeedbackToolOptions): FeedbackToolResult;
472
- //#endregion
473
- //#region src/backends/stream-json.d.ts
474
- /** Structured callbacks for stream parser output */
475
- interface StreamParserCallbacks {
476
- /** Debug-level messages (kind="debug") */
477
- debugLog: (message: string) => void;
478
- /** Text output from backend (kind="output") — assistant/user messages */
479
- outputLog?: (message: string) => void;
480
- /** Backend native tool call (kind="tool_call", source="backend") */
481
- toolCallLog?: (name: string, args: string) => void;
482
- /** MCP tool names to skip (already logged by MCP server) */
483
- mcpToolNames?: Set<string>;
145
+ declare class MemoryStateStore implements StateStore {
146
+ private states;
147
+ load(agentId: string): Promise<SessionState | null>;
148
+ save(agentId: string, state: SessionState): Promise<void>;
149
+ delete(agentId: string): Promise<void>;
484
150
  }
485
151
  //#endregion
486
- //#region src/backends/claude-code.d.ts
487
- interface ClaudeCodeOptions {
488
- /** Model to use (e.g., 'opus', 'sonnet') */
489
- model?: string;
490
- /** Additional system prompt to append */
491
- appendSystemPrompt?: string;
492
- /** Allowed tools (permission rule syntax) */
493
- allowedTools?: string[];
494
- /** Output format: 'text' | 'json' | 'stream-json' */
495
- outputFormat?: "text" | "json" | "stream-json";
496
- /** Continue most recent conversation */
497
- continue?: boolean;
498
- /** Resume specific session by ID */
499
- resume?: string;
500
- /** Working directory (defaults to workspace if set) */
501
- cwd?: string;
502
- /** Workspace directory for agent isolation */
503
- workspace?: string;
504
- /** Idle timeout in milliseconds — kills process if no output for this duration */
505
- timeout?: number;
506
- /** MCP config file path (for workflow context) */
507
- mcpConfigPath?: string;
508
- /** Stream parser callbacks (structured event output) */
509
- streamCallbacks?: StreamParserCallbacks;
510
- }
511
- declare class ClaudeCodeBackend implements Backend {
512
- readonly type: "claude";
513
- private options;
514
- private currentAbort?;
515
- constructor(options?: ClaudeCodeOptions);
516
- send(message: string, options?: {
517
- system?: string;
518
- }): Promise<BackendResponse>;
519
- isAvailable(): Promise<boolean>;
520
- getInfo(): {
521
- name: string;
522
- version?: string;
523
- model?: string;
524
- };
525
- private buildArgs;
526
- /**
527
- * Abort any running claude process
528
- */
529
- abort(): void;
152
+ //#region src/daemon/serve.d.ts
153
+ interface ServerHandle {
154
+ /** Actual port the server is listening on */
155
+ port: number;
156
+ /** Gracefully close the server */
157
+ close(): Promise<void>;
530
158
  }
531
159
  //#endregion
532
- //#region src/backends/codex.d.ts
533
- interface CodexOptions {
534
- /** Model to use (e.g., 'gpt-5.2-codex') */
535
- model?: string;
536
- /** Working directory (defaults to workspace if set) */
537
- cwd?: string;
538
- /** Workspace directory for agent isolation */
539
- workspace?: string;
540
- /** Resume a previous session */
541
- resume?: string;
542
- /** Idle timeout in milliseconds — kills process if no output for this duration */
543
- timeout?: number;
544
- /** Stream parser callbacks (structured event output) */
545
- streamCallbacks?: StreamParserCallbacks;
546
- }
547
- declare class CodexBackend implements Backend {
548
- readonly type: "codex";
549
- private options;
550
- constructor(options?: CodexOptions);
551
- send(message: string, _options?: {
552
- system?: string;
553
- }): Promise<BackendResponse>;
554
- isAvailable(): Promise<boolean>;
555
- getInfo(): {
556
- name: string;
557
- version?: string;
558
- model?: string;
559
- };
560
- private buildArgs;
561
- }
562
- //#endregion
563
- //#region src/backends/cursor.d.ts
564
- interface CursorOptions {
565
- /** Model to use */
566
- model?: string;
567
- /** Working directory (defaults to workspace if set, otherwise cwd) */
568
- cwd?: string;
569
- /** Workspace directory for agent isolation (contains .cursor/mcp.json) */
570
- workspace?: string;
571
- /** Idle timeout in milliseconds — kills process if no output for this duration */
572
- timeout?: number;
573
- /** Stream parser callbacks (structured event output) */
574
- streamCallbacks?: StreamParserCallbacks;
575
- }
576
- declare class CursorBackend implements Backend {
577
- readonly type: "cursor";
578
- private options;
579
- /**
580
- * Resolved command style:
581
- * - "subcommand": `cursor agent -p ...` (IDE-bundled CLI)
582
- * - "direct": `agent -p ...` (standalone install via cursor.com/install)
583
- * - null: not yet resolved
584
- */
585
- private resolvedStyle;
586
- constructor(options?: CursorOptions);
587
- send(message: string, _options?: {
588
- system?: string;
589
- }): Promise<BackendResponse>;
590
- isAvailable(): Promise<boolean>;
591
- getInfo(): {
592
- name: string;
593
- version?: string;
594
- model?: string;
595
- };
596
- /**
597
- * Resolve which cursor command style is available.
598
- * Tries in order:
599
- * 1. `cursor agent --version` — IDE-bundled CLI (subcommand style)
600
- * 2. `agent --version` — standalone install via cursor.com/install (direct style)
601
- * Result is cached after first resolution.
602
- */
603
- private resolveStyle;
604
- protected buildCommand(message: string): Promise<{
605
- command: string;
606
- args: string[];
607
- }>;
608
- }
609
- //#endregion
610
- //#region src/backends/opencode.d.ts
611
- interface OpenCodeOptions {
612
- /** Model to use in provider/model format (e.g., 'deepseek/deepseek-chat') */
613
- model?: string;
614
- /** Working directory (defaults to workspace if set) */
615
- cwd?: string;
616
- /** Workspace directory for agent isolation */
617
- workspace?: string;
618
- /** Idle timeout in milliseconds — kills process if no output for this duration */
619
- timeout?: number;
620
- /** Stream parser callbacks (structured event output) */
621
- streamCallbacks?: StreamParserCallbacks;
622
- }
160
+ //#region src/daemon/daemon.d.ts
161
+ /** Handle for a running workflow managed by the daemon */
162
+ interface WorkflowHandle {
163
+ /** Workflow name (from YAML name field or filename) */
164
+ name: string;
165
+ /** Workspace instance tag (optional) */
166
+ tag?: string;
167
+ /** Key for lookup: "name:tag" */
168
+ key: string;
169
+ /** Agent names in this workflow */
170
+ agents: string[];
171
+ /** Agent loops for lifecycle management */
172
+ loops: Map<string, AgentLoop>;
173
+ /** Workspace providing shared infrastructure */
174
+ workspace: Workspace;
175
+ /** Shutdown function (stops loops + cleans context) */
176
+ shutdown: () => Promise<void>;
177
+ /** Original workflow file path (for display) */
178
+ workflowPath?: string;
179
+ /** When this workflow was started */
180
+ startedAt: string;
181
+ }
182
+ interface DaemonState {
183
+ /** Agent registry — manages agent handles (definition + loop + state) */
184
+ agents: AgentRegistry;
185
+ /** Default workspace — shared by all standalone agents */
186
+ defaultWorkspace: Workspace | null;
187
+ /** Parsed config from config.yml (workflow format) */
188
+ config: ParsedWorkflow | null;
189
+ /** Running workflows — keyed by "name:tag" */
190
+ workflows: Map<string, WorkflowHandle>;
191
+ /** State store — conversation persistence (pluggable) */
192
+ store: StateStore;
193
+ /** HTTP server handle (optional — missing when app is used without server) */
194
+ server?: ServerHandle;
195
+ port: number;
196
+ host: string;
197
+ startedAt: string;
198
+ }
199
+ declare function startDaemon(config?: {
200
+ port?: number;
201
+ host?: string;
202
+ store?: StateStore;
203
+ }): Promise<void>;
623
204
  //#endregion
624
- //#region src/backends/sdk.d.ts
625
- interface SdkBackendOptions {
626
- /** Model identifier (e.g., 'openai/gpt-5.2' or 'anthropic:claude-sonnet-4-5' or just 'MiniMax-M2.5' with provider) */
627
- model: string;
628
- /** Maximum tokens to generate */
629
- maxTokens?: number;
630
- /** Provider configuration — when set, model is a plain name resolved via the provider */
631
- provider?: string | ProviderConfig;
632
- }
633
- declare class SdkBackend implements Backend {
634
- readonly type: "default";
635
- private modelId;
636
- private model;
637
- private maxTokens;
638
- private provider;
639
- constructor(options: SdkBackendOptions);
640
- send(message: string, options?: {
641
- system?: string;
642
- }): Promise<BackendResponse>;
643
- isAvailable(): Promise<boolean>;
644
- getInfo(): {
645
- name: string;
646
- version?: string;
647
- model?: string;
648
- };
649
- }
205
+ //#region src/daemon/registry.d.ts
206
+ declare const DEFAULT_PORT = 5099;
207
+ interface DaemonInfo {
208
+ pid: number;
209
+ host: string;
210
+ port: number;
211
+ startedAt: string;
212
+ /** Auth token for API access (random per daemon instance) */
213
+ token?: string;
214
+ }
215
+ /** Write daemon.json for client discovery */
216
+ declare function writeDaemonInfo(info: DaemonInfo): void;
217
+ /** Read daemon.json. Returns null if missing or malformed. */
218
+ declare function readDaemonInfo(): DaemonInfo | null;
219
+ /** Remove daemon.json (on shutdown) */
220
+ declare function removeDaemonInfo(): void;
221
+ /** Check if a daemon is already running (daemon.json exists + PID alive) */
222
+ declare function isDaemonRunning(): DaemonInfo | null;
650
223
  //#endregion
651
- //#region src/backends/mock.d.ts
224
+ //#region src/daemon/event-log.d.ts
652
225
  /**
653
- * Mock AI Backend for testing
654
- *
655
- * In single-agent mode, provides a simple echo send().
656
- * In workflow mode, the loop handles MCP tool orchestration
657
- * via the mock runner strategy (loop/mock-runner.ts).
226
+ * Append-only JSONL event log for daemon-level events.
227
+ * Uses synchronous writes — daemon events are infrequent and must not be lost.
658
228
  */
659
- declare class MockAIBackend implements Backend {
660
- private debugLog?;
661
- readonly type: "mock";
662
- constructor(debugLog?: ((message: string) => void) | undefined);
663
- send(message: string, _options?: {
664
- system?: string;
665
- }): Promise<BackendResponse>;
666
- }
667
- /**
668
- * Create a mock AI backend
669
- */
670
- declare function createMockBackend(debugLog?: (msg: string) => void): Backend;
671
- //#endregion
672
- //#region src/backends/index.d.ts
673
- type BackendOptions = {
674
- type: "default";
675
- model?: string;
676
- maxTokens?: number;
677
- provider?: string | ProviderConfig;
678
- } | {
679
- type: "claude";
680
- model?: string;
681
- options?: Omit<ClaudeCodeOptions, "model">;
682
- } | {
683
- type: "codex";
684
- model?: string;
685
- options?: Omit<CodexOptions, "model">;
686
- } | {
687
- type: "cursor";
688
- model?: string;
689
- options?: Omit<CursorOptions, "model">;
690
- } | {
691
- type: "opencode";
692
- model?: string;
693
- options?: Omit<OpenCodeOptions, "model">;
694
- };
695
- /**
696
- * Create a backend instance
697
- * Model names are automatically translated to backend-specific format
698
- * Accepts "sdk" as deprecated alias for "default"
699
- *
700
- * Examples:
701
- * - "sonnet" → cursor: "sonnet-4.5", claude: "sonnet", default: "claude-sonnet-4-5-20250514"
702
- * - "anthropic/claude-sonnet-4-5" → cursor: "sonnet-4.5", claude: "sonnet"
703
- */
704
- declare function createBackend(config: BackendOptions | {
705
- type: "sdk";
706
- model?: string;
707
- maxTokens?: number;
708
- }): Backend;
709
- /**
710
- * Check which backends are available
711
- */
712
- declare function checkBackends(): Promise<Record<BackendType, boolean>>;
713
- /**
714
- * List available backends with info
715
- */
716
- declare function listBackends(): Promise<Array<{
717
- type: BackendType;
718
- available: boolean;
719
- name: string;
720
- }>>;
721
- //#endregion
722
- //#region src/agent/skills/provider.d.ts
723
- interface SkillMetadata {
724
- name: string;
725
- description: string;
726
- path: string;
727
- }
728
- declare class SkillsProvider {
729
- private skills;
730
- /**
731
- * Add a single skill directory
732
- */
733
- addSkill(skillPath: string): Promise<void>;
734
- /**
735
- * Scan a directory and add all valid skills found
736
- */
737
- scanDirectory(dir: string): Promise<void>;
738
- /**
739
- * List all available skills (metadata only)
740
- */
741
- list(): Array<{
742
- name: string;
743
- description: string;
744
- }>;
745
- /**
746
- * View the full SKILL.md content
747
- */
748
- view(skillName: string): Promise<string>;
749
- /**
750
- * Read a file within a skill directory (relative path)
751
- */
752
- readFile(skillName: string, relativePath: string): Promise<string>;
753
- /**
754
- * Parse YAML frontmatter from SKILL.md
755
- */
756
- private parseFrontmatter;
757
- /**
758
- * Resolve tilde and relative paths
759
- */
760
- private resolvePath;
761
- /**
762
- * Synchronous version: Add a single skill directory
763
- */
764
- addSkillSync(skillPath: string): void;
765
- /**
766
- * Synchronous version: Scan a directory and add all valid skills found
767
- */
768
- scanDirectorySync(dir: string): void;
769
- /**
770
- * Synchronous version: Parse YAML frontmatter from SKILL.md
771
- */
772
- private parseFrontmatterSync;
773
- /**
774
- * Add skills from a SkillImporter (async)
775
- * Used for temporary imported skills during session lifecycle
776
- */
777
- addImportedSkills(importer: {
778
- getAllImportedSkillPaths(): string[];
779
- }): Promise<void>;
780
- /**
781
- * Add skills from a SkillImporter (sync)
782
- */
783
- addImportedSkillsSync(importer: {
784
- getAllImportedSkillPaths(): string[];
229
+ declare class DaemonEventLog implements EventSink {
230
+ private filePath;
231
+ constructor(daemonDir: string);
232
+ append(from: string, content: string, options?: {
233
+ kind?: EventKind;
785
234
  }): void;
235
+ /** Read all events (full file read). */
236
+ readAll(): Promise<Message[]>;
237
+ /** Read events from byte offset (incremental sync). */
238
+ readFrom(offset: number): Promise<{
239
+ events: Message[];
240
+ offset: number;
241
+ }>;
786
242
  }
787
243
  //#endregion
788
- //#region src/agent/tools/skills.d.ts
789
- /**
790
- * Create a Skills tool as an AI SDK tool() object
791
- */
792
- declare function createSkillsTool(provider: SkillsProvider): unknown;
793
- //#endregion
794
- //#region src/agent/skills/importer.d.ts
795
- interface ImportedSkill {
244
+ //#region src/agent/config.d.ts
245
+ interface AgentConfig {
246
+ /** Agent name (unique within daemon) */
796
247
  name: string;
797
- source: string;
798
- tempPath: string;
799
- }
800
- /**
801
- * Temporary skill importer for session lifecycle
802
- * Clones Git repos to temp directory and manages imported skills
803
- */
804
- declare class SkillImporter {
805
- private tempDir;
806
- private imported;
807
- constructor(sessionId: string);
808
- /**
809
- * Import skills from a Git repository
810
- */
811
- import(spec: string): Promise<string[]>;
812
- /**
813
- * Import skills from multiple specs
814
- */
815
- importMultiple(specs: string[]): Promise<string[]>;
816
- /**
817
- * Get path for an imported skill
818
- */
819
- getImportedSkillPath(skillName: string): string | null;
820
- /**
821
- * Get all imported skill paths
822
- */
823
- getAllImportedSkillPaths(): string[];
824
- /**
825
- * Get all imported skills metadata
826
- */
827
- getImportedSkills(): ImportedSkill[];
828
- /**
829
- * Get temporary directory path
830
- */
831
- getTempDir(): string;
832
- /**
833
- * Cleanup temporary directory
834
- */
835
- cleanup(): Promise<void>;
836
- /**
837
- * Clone Git repository (shallow clone)
838
- */
839
- private cloneRepo;
840
- /**
841
- * Extract skills from cloned repository
842
- */
843
- private extractSkills;
844
- /**
845
- * Find skills directory in repository
846
- * Tries: skills/, agent-skills/, . (root)
847
- */
848
- private findSkillsDirectory;
849
- /**
850
- * Find all skills in a directory
851
- */
852
- private findAllSkills;
853
- /**
854
- * Execute git command
855
- */
856
- private execGit;
248
+ /** Model identifier (e.g., 'anthropic/claude-sonnet-4-5' or just 'MiniMax-M2.5' when provider is set) */
249
+ model: string;
250
+ /** System prompt */
251
+ system: string;
252
+ /** Backend type */
253
+ backend: BackendType;
254
+ /** Provider configuration — string (built-in) or object (custom endpoint) */
255
+ provider?: string | ProviderConfig;
256
+ /** Workflow this agent belongs to (optional — standalone agents have no workflow) */
257
+ workflow?: string;
258
+ /** Workflow instance tag (optional — standalone agents have no tag) */
259
+ tag?: string;
260
+ /** When this agent was created */
261
+ createdAt: string;
262
+ /** Periodic wakeup schedule */
263
+ schedule?: ScheduleConfig;
857
264
  }
858
265
  //#endregion
859
- //#region src/agent/skills/import-spec.d.ts
860
- type GitProvider = "github" | "gitlab" | "gitee";
861
- interface ImportSpec {
862
- provider: GitProvider;
863
- owner: string;
864
- repo: string;
865
- ref: string;
866
- skills: string[] | "all";
867
- rawSpec: string;
266
+ //#region src/agent/handle.d.ts
267
+ interface WorkerHandle {
268
+ /** Send a message synchronously */
269
+ send(input: string, options?: SendOptions$1): Promise<AgentResponse>;
270
+ /** Send a message with streaming response */
271
+ sendStream(input: string, options?: SendOptions$1): AsyncGenerator<string, AgentResponse>;
272
+ /** Snapshot current conversation state (for persistence) */
273
+ getState(): SessionState;
868
274
  }
869
275
  /**
870
- * Parse import spec: [provider:]owner/repo[@ref]:{skill1,skill2,...}
276
+ * LocalWorker In-process execution via AgentWorker.
871
277
  *
872
- * Examples:
873
- * vercel-labs/agent-skills:react-best-practices
874
- * vercel-labs/agent-skills:{react,web}
875
- * vercel-labs/agent-skills@v1.0.0:react
876
- * github:vercel-labs/agent-skills@main:react
877
- * vercel-labs/agent-skills (imports all)
878
- */
879
- declare function parseImportSpec(spec: string): ImportSpec;
880
- /**
881
- * Build Git URL from import spec
882
- */
883
- declare function buildGitUrl(spec: ImportSpec): string;
884
- /**
885
- * Get display name for import spec
886
- */
887
- declare function getSpecDisplayName(spec: ImportSpec): string;
278
+ * Wraps an AgentWorker instance. State lives in the AgentWorker's memory.
279
+ * This is the default for single-machine deployments.
280
+ */
281
+ declare class LocalWorker implements WorkerHandle {
282
+ private engine;
283
+ constructor(config: AgentConfig, restore?: SessionState);
284
+ send(input: string, options?: SendOptions$1): Promise<AgentResponse>;
285
+ sendStream(input: string, options?: SendOptions$1): AsyncGenerator<string, AgentResponse>;
286
+ getState(): SessionState;
287
+ }
888
288
  //#endregion
889
- export { type AgentMessage, type AgentResponse, AgentWorker, type AgentWorkerConfig, type ApprovalCheck, type Backend, type BackendConfig, type BackendOptions, type BackendResponse, type BackendType, type BashToolkit, type BashToolsOptions, ClaudeCodeBackend, type ClaudeCodeOptions, CodexBackend, type CodexOptions, type CreateBashToolOptions, CursorBackend, type CursorOptions, FEEDBACK_PROMPT, FRONTIER_MODELS, type FeedbackEntry, type FeedbackToolOptions, type FeedbackToolResult, type GitProvider, type ImportSpec, type ImportedSkill, type MessageStatus, MockAIBackend, type PendingApproval, SUPPORTED_PROVIDERS, SdkBackend, type SdkBackendOptions, type SendOptions, type SessionConfig, type SessionState, SkillImporter, type SkillMetadata, SkillsProvider, type StepInfo, type SupportedProvider, type TokenUsage, type ToolCall, type ToolInfo, type Transcript, buildGitUrl, checkBackends, createBackend, createBashTool, createBashTools, createBashToolsFromDirectory, createBashToolsFromFiles, createFeedbackTool, createMockBackend, createModel, createModelAsync, createSkillsTool, getSpecDisplayName, listBackends, parseImportSpec };
289
+ export { type AgentConfig, AgentHandle, type AgentHandleState, AgentRegistry, AgentWorker, type AgentWorkerConfig, type CreateSkillToolOptions, DEFAULT_PORT, DaemonEventLog, type DaemonInfo, type DaemonState, LocalWorker, MemoryStateStore, type SendOptions, SkillImporter, type SkillToolkit, type StateStore, type StepInfo, type WorkerHandle, type WorkflowHandle, createSkillTool, isDaemonRunning, readDaemonInfo, removeDaemonInfo, startDaemon, writeDaemonInfo };