@cuylabs/agent-core 0.8.0 → 0.10.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.
Files changed (127) hide show
  1. package/README.md +33 -17
  2. package/dist/chunk-2O4MCSQS.js +780 -0
  3. package/dist/chunk-2TTOLHBT.js +198 -0
  4. package/dist/chunk-5FMSGQVX.js +281 -0
  5. package/dist/chunk-5NVVNXPQ.js +288 -0
  6. package/dist/{chunk-CAA7FHIH.js → chunk-6HZBHFOL.js} +3 -103
  7. package/dist/chunk-CJI7PVS2.js +58 -0
  8. package/dist/{chunk-N6HWIEEA.js → chunk-CMYN2RCB.js} +278 -61
  9. package/dist/chunk-FII65CN7.js +117 -0
  10. package/dist/{chunk-IVUJDISU.js → chunk-GFTW23FV.js} +5 -14
  11. package/dist/chunk-I6PKJ7XQ.js +292 -0
  12. package/dist/{chunk-BDBZ3SLK.js → chunk-ICZ66572.js} +48 -4
  13. package/dist/chunk-KYLPMBHD.js +316 -0
  14. package/dist/chunk-MXAP4UG6.js +2956 -0
  15. package/dist/{chunk-RZITT45F.js → chunk-N3VX7FEE.js} +39 -6
  16. package/dist/{chunk-YSLSEQ6B.js → chunk-NDZWXCBZ.js} +218 -95
  17. package/dist/{chunk-P6YF7USR.js → chunk-Q742PSH3.js} +23 -38
  18. package/dist/chunk-QAL3OMI3.js +943 -0
  19. package/dist/{chunk-RFEKJKTO.js → chunk-RN6WZEUF.js} +330 -280
  20. package/dist/{chunk-ZXAKHMWH.js → chunk-ROTGCYDW.js} +22 -84
  21. package/dist/chunk-SPBFQXOT.js +0 -0
  22. package/dist/{chunk-LRHOS4ZN.js → chunk-SPILYYDF.js} +3 -2
  23. package/dist/chunk-SSFBF3US.js +602 -0
  24. package/dist/chunk-SZ2XBPTW.js +8 -0
  25. package/dist/chunk-T4UIX5D7.js +115 -0
  26. package/dist/chunk-TIHPYVAJ.js +102 -0
  27. package/dist/{chunk-YUUJK53A.js → chunk-TOTDGK3P.js} +1 -1
  28. package/dist/chunk-V4RFNEET.js +563 -0
  29. package/dist/chunk-VOUEJSW6.js +0 -0
  30. package/dist/{chunk-4BDA7DQY.js → chunk-WBPOZ7CL.js} +673 -273
  31. package/dist/chunk-X4VN4GIJ.js +185 -0
  32. package/dist/dispatch/index.d.ts +93 -0
  33. package/dist/dispatch/index.js +37 -0
  34. package/dist/events/index.d.ts +93 -0
  35. package/dist/events/index.js +6 -0
  36. package/dist/{runtime → execution}/index.d.ts +120 -34
  37. package/dist/{runtime → execution}/index.js +18 -13
  38. package/dist/index-BCqEGzBj.d.ts +251 -0
  39. package/dist/index.d.ts +490 -122
  40. package/dist/index.js +2104 -615
  41. package/dist/{errors → inference/errors}/index.d.ts +2 -2
  42. package/dist/{errors → inference/errors}/index.js +1 -1
  43. package/dist/inference/index.d.ts +16 -23
  44. package/dist/inference/index.js +45 -16
  45. package/dist/instance-BqV2D5pc.d.ts +5723 -0
  46. package/dist/logger/index.d.ts +50 -0
  47. package/dist/logger/index.js +11 -0
  48. package/dist/mcp/index.d.ts +5 -9
  49. package/dist/mcp/index.js +2 -3
  50. package/dist/middleware/index.d.ts +10 -149
  51. package/dist/middleware/index.js +11 -3
  52. package/dist/model-messages-B4nK9D1-.d.ts +13 -0
  53. package/dist/models/index.d.ts +23 -18
  54. package/dist/models/index.js +48 -11
  55. package/dist/models/reasoning/index.d.ts +4 -0
  56. package/dist/{reasoning → models/reasoning}/index.js +3 -3
  57. package/dist/plugin/index.d.ts +458 -0
  58. package/dist/plugin/index.js +32 -0
  59. package/dist/profiles/index.d.ts +55 -0
  60. package/dist/profiles/index.js +30 -0
  61. package/dist/prompt/index.d.ts +8 -12
  62. package/dist/prompt/index.js +3 -2
  63. package/dist/safety/index.d.ts +109 -14
  64. package/dist/safety/index.js +59 -3
  65. package/dist/sandbox/index.d.ts +81 -0
  66. package/dist/sandbox/index.js +1 -0
  67. package/dist/skill/index.d.ts +10 -8
  68. package/dist/skill/index.js +3 -3
  69. package/dist/storage/index.d.ts +12 -4
  70. package/dist/storage/index.js +1 -1
  71. package/dist/subagents/index.d.ts +177 -0
  72. package/dist/subagents/index.js +78 -0
  73. package/dist/team/index.d.ts +544 -0
  74. package/dist/team/index.js +41 -0
  75. package/dist/tool/host/index.d.ts +41 -0
  76. package/dist/tool/host/index.js +10 -0
  77. package/dist/tool/index.d.ts +125 -21
  78. package/dist/tool/index.js +20 -13
  79. package/dist/{types-VQgymC1N.d.ts → types-Bj_J8u_W.d.ts} +44 -64
  80. package/dist/{types-CHiPh8U2.d.ts → types-C_LCeYNg.d.ts} +7 -7
  81. package/dist/types-RSCv7nQ4.d.ts +59 -0
  82. package/package.json +58 -53
  83. package/dist/builder-UpOWQMW3.d.ts +0 -34
  84. package/dist/chunk-7MUFEN4K.js +0 -559
  85. package/dist/chunk-7VKQ4WPB.js +0 -73
  86. package/dist/chunk-BFM2YHNM.js +0 -222
  87. package/dist/chunk-DWYX7ASF.js +0 -26
  88. package/dist/chunk-KUVSERLJ.js +0 -50
  89. package/dist/chunk-N7P4PN3O.js +0 -84
  90. package/dist/chunk-SDSBEQXG.js +0 -157
  91. package/dist/chunk-SQU2AJHO.js +0 -305
  92. package/dist/chunk-VBWWUHWI.js +0 -724
  93. package/dist/chunk-VEKUXUVF.js +0 -41
  94. package/dist/chunk-VNQBHPCT.js +0 -398
  95. package/dist/chunk-WWYYNWEW.js +0 -259
  96. package/dist/context/index.d.ts +0 -259
  97. package/dist/context/index.js +0 -26
  98. package/dist/events-CE72w8W4.d.ts +0 -149
  99. package/dist/host/index.d.ts +0 -45
  100. package/dist/host/index.js +0 -8
  101. package/dist/index-CWSchSql.d.ts +0 -1058
  102. package/dist/messages-BYWGn8TY.d.ts +0 -110
  103. package/dist/presets/index.d.ts +0 -53
  104. package/dist/presets/index.js +0 -28
  105. package/dist/reasoning/index.d.ts +0 -116
  106. package/dist/registry-DwYqsQkX.d.ts +0 -164
  107. package/dist/runner-e2YRcUoX.d.ts +0 -786
  108. package/dist/scope/index.d.ts +0 -10
  109. package/dist/scope/index.js +0 -14
  110. package/dist/session-manager-B_CWGTsl.d.ts +0 -274
  111. package/dist/signal/index.d.ts +0 -28
  112. package/dist/signal/index.js +0 -6
  113. package/dist/sub-agent/index.d.ts +0 -23
  114. package/dist/sub-agent/index.js +0 -15
  115. package/dist/tool-BHbyUAy3.d.ts +0 -150
  116. package/dist/tool-DLXAR9Ce.d.ts +0 -145
  117. package/dist/tracker-DClqYqTj.d.ts +0 -96
  118. package/dist/tracking/index.d.ts +0 -111
  119. package/dist/tracking/index.js +0 -20
  120. package/dist/types-BfNpU8NS.d.ts +0 -270
  121. package/dist/types-BnpEOYV-.d.ts +0 -50
  122. package/dist/types-CQL-SvTn.d.ts +0 -29
  123. package/dist/types-CWm-7rvB.d.ts +0 -55
  124. package/dist/types-KKDrdU9Y.d.ts +0 -325
  125. package/dist/types-QA4WhEfz.d.ts +0 -138
  126. package/dist/types-QKHHQLLq.d.ts +0 -336
  127. package/dist/types-YuWV4ag7.d.ts +0 -72
@@ -1,1058 +0,0 @@
1
- import { LanguageModel } from 'ai';
2
- import { P as Preset } from './types-BnpEOYV-.js';
3
- import { T as Tool } from './tool-BHbyUAy3.js';
4
- import { A as AgentMiddleware, d as StreamProvider, P as PromptConfig, M as MiddlewareRunner } from './runner-e2YRcUoX.js';
5
- import { S as SessionManager, f as SessionContext, i as SessionInfo } from './session-manager-B_CWGTsl.js';
6
- import { T as ToolHost } from './types-CHiPh8U2.js';
7
- import { T as TokenUsage, M as Message } from './messages-BYWGn8TY.js';
8
- import { A as AgentEvent } from './events-CE72w8W4.js';
9
- import { R as ReasoningLevel } from './types-CQaXbRsS.js';
10
- import { a as MCPManager } from './types-VQgymC1N.js';
11
- import { A as AgentSignal } from './types-YuWV4ag7.js';
12
- import { U as UndoResult, T as TurnChangeTracker } from './tracker-DClqYqTj.js';
13
- import { P as PromptBuilder } from './builder-UpOWQMW3.js';
14
- import { P as PendingIntervention, g as InterventionController } from './types-KKDrdU9Y.js';
15
- import { s as DoomLoopHandler, o as AgentTurnStepRuntimeConfig } from './types-QKHHQLLq.js';
16
-
17
- /**
18
- * Tools whose outputs should never be pruned automatically.
19
- */
20
- declare const PRUNE_PROTECTED_TOOLS: readonly ["skill"];
21
- /**
22
- * Configuration for automatic context compaction.
23
- */
24
- interface CompactionConfig {
25
- /**
26
- * Enable automatic compaction when context overflows.
27
- * Default: true
28
- */
29
- auto?: boolean;
30
- /**
31
- * Enable pruning of old tool outputs before summarization.
32
- * Default: true
33
- */
34
- prune?: boolean;
35
- /**
36
- * Protect this many recent tokens from pruning.
37
- * Default: 40,000
38
- */
39
- protectedTokens?: number;
40
- /**
41
- * Minimum tokens to trigger pruning.
42
- * Default: 20,000
43
- */
44
- pruneMinimum?: number;
45
- /**
46
- * Custom summarization prompt for compaction.
47
- */
48
- summaryPrompt?: string;
49
- /**
50
- * Model to use for summarization. Defaults to the agent model.
51
- */
52
- summaryModel?: LanguageModel;
53
- /**
54
- * Auto-continue after compaction with a continuation prompt.
55
- * Default: true
56
- */
57
- autoContinue?: boolean;
58
- }
59
-
60
- /**
61
- * Tracing configuration for `createAgent({ tracing })`.
62
- *
63
- * When provided, the agent auto-creates the OTel middleware and AI SDK
64
- * telemetry settings, so callers do not need to wire them separately.
65
- */
66
- interface TracingConfig {
67
- /** Agent description — recorded as `gen_ai.agent.description`. */
68
- agentDescription?: string;
69
- /** Record tool arguments and LLM prompts in spans. Defaults to `true`. */
70
- recordInputs?: boolean;
71
- /** Record tool results and LLM responses in spans. Defaults to `true`. */
72
- recordOutputs?: boolean;
73
- /** Emit `execute_tool` spans from our middleware. Defaults to `true`. */
74
- emitToolSpans?: boolean;
75
- /** TTL in ms for orphaned spans. Defaults to 5 minutes. */
76
- spanTimeoutMs?: number;
77
- /**
78
- * An OTel `SpanProcessor` used to auto-create and register a tracer provider.
79
- */
80
- spanProcessor?: unknown;
81
- /**
82
- * OTel service name for the auto-created provider resource.
83
- * Defaults to the agent `name`.
84
- */
85
- serviceName?: string;
86
- }
87
-
88
- /**
89
- * Public configuration surface for `createAgent()`.
90
- */
91
- interface AgentConfig {
92
- /**
93
- * Agent name — used as identity in spans, workflow names, and logs.
94
- * Defaults to `"agent"`.
95
- */
96
- name?: string;
97
- /** Vercel AI SDK model instance */
98
- model: LanguageModel;
99
- /** Flat system prompt */
100
- systemPrompt?: string;
101
- /** Working directory */
102
- cwd?: string;
103
- /**
104
- * Execution environment for tools.
105
- */
106
- host?: ToolHost;
107
- /** Temperature (0-1) */
108
- temperature?: number;
109
- /** Top-p sampling */
110
- topP?: number;
111
- /** Max output tokens */
112
- maxOutputTokens?: number;
113
- /** Maximum steps (tool call iterations) */
114
- maxSteps?: number;
115
- /** Reasoning/thinking level for supported models */
116
- reasoningLevel?: ReasoningLevel;
117
- /** Require approval for dangerous operations */
118
- requireApproval?: boolean;
119
- /**
120
- * Handler for doom-loop detection.
121
- */
122
- onDoomLoop?: DoomLoopHandler;
123
- /**
124
- * Strictly enforce doom-loop detection when no custom handler is provided.
125
- * Default: true
126
- */
127
- enforceDoomLoop?: boolean;
128
- /**
129
- * Number of identical tool calls before triggering doom-loop handling.
130
- * Default: 3
131
- */
132
- doomLoopThreshold?: number;
133
- /**
134
- * Automatic context compaction settings.
135
- */
136
- compaction?: CompactionConfig;
137
- /**
138
- * Middleware for the agent lifecycle.
139
- */
140
- middleware?: AgentMiddleware[];
141
- /**
142
- * Context window size in tokens for overflow detection.
143
- * Defaults to 128,000.
144
- */
145
- contextWindow?: number;
146
- /**
147
- * Custom stream provider for specialized models.
148
- */
149
- streamProvider?: StreamProvider;
150
- /**
151
- * MCP manager for external tool servers.
152
- */
153
- mcp?: MCPManager;
154
- /**
155
- * Layered prompt pipeline configuration.
156
- */
157
- prompt?: PromptConfig;
158
- /**
159
- * Simplest way to enable tracing.
160
- */
161
- tracing?: TracingConfig;
162
- /**
163
- * Event signal for multi-consumer dispatch.
164
- *
165
- * Every event yielded by `chat()` is also emitted here, enabling
166
- * passive observers (SSE routes, TUI renderers, plugins) to
167
- * subscribe without consuming the primary generator.
168
- *
169
- * Defaults to an in-process `LocalSignal`. A distributed runtime
170
- * can supply its own implementation to bridge events externally.
171
- */
172
- signal?: AgentSignal;
173
- }
174
-
175
- interface AgentForkOptions {
176
- name?: string;
177
- systemPrompt?: string;
178
- prompt?: PromptConfig;
179
- model?: LanguageModel;
180
- temperature?: number;
181
- tools?: Tool.AnyInfo[];
182
- maxSteps?: number;
183
- reasoningLevel?: ReasoningLevel;
184
- preset?: Preset;
185
- middleware?: AgentMiddleware[];
186
- additionalMiddleware?: AgentMiddleware[];
187
- }
188
-
189
- type AgentConstructionOptions = AgentConfig & {
190
- tools?: Tool.AnyInfo[];
191
- sessionManager?: SessionManager;
192
- };
193
-
194
- /**
195
- * Create an agent instance
196
- */
197
- declare function createAgent(config: AgentConstructionOptions): Agent;
198
- /**
199
- * Embeddable AI agent with tool support.
200
- *
201
- * The `Agent` class is the main entry-point for consumers. It manages:
202
- * - **Sessions** — persistent conversation history
203
- * - **Streaming** — real-time event generation via `chat()`
204
- * - **Tools** — registry + execution context
205
- * - **Context management** — overflow detection & auto-compaction
206
- * - **Reasoning** — configurable thinking levels per model
207
- * - **Sub-agents** — `fork()` / `run()` for parallel or specialised tasks
208
- *
209
- * @example
210
- * ```typescript
211
- * import { createAgent } from "@cuylabs/agent-core";
212
- * import { anthropic } from "@ai-sdk/anthropic";
213
- *
214
- * const agent = createAgent({
215
- * model: anthropic("claude-sonnet-4-20250514"),
216
- * cwd: "/path/to/project",
217
- * });
218
- *
219
- * // Streaming
220
- * for await (const event of agent.chat("session-1", "List all TypeScript files")) {
221
- * if (event.type === "text-delta") process.stdout.write(event.text);
222
- * }
223
- *
224
- * // Non-streaming (convenience)
225
- * const result = await agent.send("session-1", "Fix the bug in utils.ts");
226
- * console.log(result.response);
227
- * ```
228
- */
229
- declare class Agent {
230
- private config;
231
- private tools;
232
- private sessions;
233
- private loadedSessions;
234
- private state;
235
- /** Context manager for overflow detection and compaction */
236
- private contextManager;
237
- /** Tools that user said "remember" for doom loop (don't ask again) */
238
- private rememberedDoomLoopTools;
239
- /** Turn change tracker for file modification tracking */
240
- private turnTracker;
241
- /** Counter for turn IDs */
242
- private turnCounter;
243
- /** MCP manager for external tool servers */
244
- private mcpManager?;
245
- /** Whether MCP has been connected (lazy init) */
246
- private mcpConnected;
247
- /** Whether skill tools have been resolved (lazy init) */
248
- private skillToolsResolved;
249
- /** Cached MCP tools (refreshed on connect) */
250
- private mcpToolsCache?;
251
- /** Prompt pipeline builder (when using layered prompt mode) */
252
- private promptBuilder?;
253
- /** Intervention controller for mid-turn message injection */
254
- private interventionCtrl;
255
- /** Execution environment for tool operations */
256
- private host;
257
- /** Middleware runner for lifecycle hooks */
258
- private middlewareRunner;
259
- /** AI SDK telemetry settings (auto-created from `tracing` config) */
260
- private telemetrySettings?;
261
- /** Tracing shutdown function (from `tracing` config auto-setup) */
262
- private tracingShutdown?;
263
- /** Multi-consumer event dispatch */
264
- private readonly _signal;
265
- constructor(config: AgentConstructionOptions);
266
- /**
267
- * Event signal — subscribe to events without consuming the generator.
268
- *
269
- * Every event yielded by `chat()` is also dispatched here, allowing
270
- * multiple passive observers (SSE routes, TUI, plugins) to listen
271
- * concurrently.
272
- */
273
- get signal(): AgentSignal;
274
- /** Agent name (identity for spans, Dapr workflows, etc.) */
275
- get name(): string;
276
- /** Working directory for file operations */
277
- get cwd(): string;
278
- /** Current model */
279
- get model(): LanguageModel;
280
- /** System prompt */
281
- get systemPrompt(): string;
282
- /** Is currently streaming */
283
- get isStreaming(): boolean;
284
- /** Current reasoning level */
285
- get reasoningLevel(): ReasoningLevel;
286
- /**
287
- * Set reasoning level
288
- * Will be clamped to available levels for the current model
289
- */
290
- setReasoningLevel(level: ReasoningLevel): void;
291
- /**
292
- * Get available reasoning levels for the current model
293
- */
294
- getAvailableReasoningLevels(): ReasoningLevel[];
295
- /**
296
- * Check if current model supports reasoning
297
- */
298
- supportsReasoning(): boolean;
299
- /**
300
- * Ensure skill tools are registered when `prompt.skills` is configured.
301
- * Lazy initialization — resolves the registry and adds tools on first use.
302
- */
303
- private ensureSkillTools;
304
- /**
305
- * Ensure MCP is connected and return tools
306
- * Lazy initialization - only connects on first use
307
- */
308
- private ensureMCPConnected;
309
- /**
310
- * Repair session history by synthesising missing tool-result messages.
311
- *
312
- * When a tool `execute()` throws, the AI SDK emits `tool-error` instead
313
- * of `tool-result`. If the error event wasn't persisted (e.g. because
314
- * the fix above wasn't in place), subsequent turns will fail with
315
- * `MissingToolResultsError`. This method detects orphaned tool-call IDs
316
- * and adds placeholder `tool` messages so the history is valid again.
317
- */
318
- private repairOrphanedToolCalls;
319
- /**
320
- * Convert internal {@link Message} array to Vercel AI SDK {@link ModelMessage} format.
321
- *
322
- * Handles the role-specific mappings:
323
- * - `user` / `system` → pass-through
324
- * - `assistant` with tool calls → `ToolCallPart[]` content
325
- * - `tool` → `tool-result` content part
326
- */
327
- private toModelMessages;
328
- /**
329
- * Stream a chat response.
330
- *
331
- * Sends a user message and yields real-time {@link AgentEvent}s as the
332
- * model responds, calls tools, and finishes. Conversation state is
333
- * persisted to the session automatically.
334
- *
335
- * @param sessionId - Session identifier for conversation history
336
- * @param message - User message to send
337
- * @param options - Abort signal, system prompt override, and approval handler
338
- * @yields {AgentEvent} Events as they occur during processing
339
- */
340
- chat(sessionId: string, message: string, options?: {
341
- abort?: AbortSignal;
342
- system?: string;
343
- }): AsyncGenerator<AgentEvent>;
344
- /**
345
- * Ensure a session is loaded or created
346
- */
347
- private ensureSession;
348
- /**
349
- * Send a message and wait for the complete response (non-streaming).
350
- *
351
- * This is a convenience wrapper around {@link chat} that buffers all
352
- * events internally and returns the final response, usage, and tool
353
- * call results. Prefer `chat()` when you need real-time streaming.
354
- *
355
- * @param sessionId - Session identifier
356
- * @param message - User message
357
- * @param options - Abort signal and optional system prompt override
358
- */
359
- send(sessionId: string, message: string, options?: {
360
- abort?: AbortSignal;
361
- system?: string;
362
- }): Promise<{
363
- response: string;
364
- usage: TokenUsage;
365
- toolCalls: Array<{
366
- name: string;
367
- result: unknown;
368
- }>;
369
- }>;
370
- /** Add a tool at runtime */
371
- addTool(tool: Tool.Info): void;
372
- /** Remove a tool by ID */
373
- removeTool(toolId: string): boolean;
374
- /** Get all tool IDs */
375
- getToolIds(): string[];
376
- /** Get all tools */
377
- getTools(): Tool.AnyInfo[];
378
- /** Check if a tool exists */
379
- hasTool(toolId: string): boolean;
380
- /** Get session manager */
381
- getSessionManager(): SessionManager;
382
- /** Get current session context */
383
- getSessionContext(): SessionContext;
384
- /** Get messages from current session */
385
- getMessages(): Message[];
386
- /** Delete a session */
387
- deleteSession(sessionId: string): Promise<boolean>;
388
- /** List all sessions */
389
- listSessions(): Promise<SessionInfo[]>;
390
- /** Branch from current point */
391
- branch(summary?: string): Promise<string>;
392
- /**
393
- * Get context window statistics.
394
- *
395
- * Useful for UI to display context utilization like:
396
- * - Progress bar showing how full the context is
397
- * - Warning when approaching limit
398
- * - Info about when compaction will trigger
399
- *
400
- * @example
401
- * ```typescript
402
- * const stats = agent.getContextStats();
403
- * console.log(`Context: ${stats.utilizationPercent}% used`);
404
- * if (stats.shouldPrune) {
405
- * console.log('Context will be compacted soon');
406
- * }
407
- * ```
408
- */
409
- getContextStats(): {
410
- tokens: number;
411
- limit: number;
412
- available: number;
413
- utilizationPercent: number;
414
- isOverflowing: boolean;
415
- shouldPrune: boolean;
416
- };
417
- /**
418
- * Manually trigger context compaction.
419
- *
420
- * Usually auto-compaction handles this, but you can trigger it manually
421
- * if needed (e.g., before a long operation).
422
- *
423
- * @returns Pruning result with details about what was removed/summarized
424
- */
425
- compactContext(): Promise<{
426
- removedCount: number;
427
- tokensRemoved: number;
428
- summarized: boolean;
429
- summary?: string;
430
- }>;
431
- /**
432
- * Clear remembered doom loop tools.
433
- *
434
- * When a user says "remember" for a doom loop, that tool is added
435
- * to a set that skips future doom loop checks. Call this to reset.
436
- */
437
- clearRememberedDoomLoopTools(): void;
438
- /**
439
- * Inject a message at the next step boundary of a running turn.
440
- *
441
- * This is the primary redirection mechanism. When the agent is
442
- * streaming a multi-step response (calling tools, reasoning, etc.),
443
- * this injects a user message before the next LLM call. The LLM
444
- * sees the intervention and can adjust its behavior.
445
- *
446
- * Uses Vercel AI SDK v6's `prepareStep` hook — no polling, no
447
- * custom loop code. The SDK handles the injection naturally.
448
- *
449
- * Safe to call from any async context (UI event handlers, WebSocket
450
- * callbacks, timers, etc.) while `chat()` is running.
451
- *
452
- * If called when no turn is active, the message will be picked up
453
- * by the first step of the next `chat()` call.
454
- *
455
- * @param message - The user message to inject mid-turn
456
- * @returns Intervention ID for tracking
457
- *
458
- * @example
459
- * ```typescript
460
- * // Start a streaming turn
461
- * const stream = agent.chat("session-1", "refactor the auth module");
462
- *
463
- * // From a UI handler (another async context):
464
- * agent.intervene("stop, focus only on JWT validation in auth.ts");
465
- *
466
- * // The stream will yield an intervention-applied event
467
- * for await (const event of stream) {
468
- * if (event.type === "intervention-applied") {
469
- * console.log(`Redirected: ${event.message}`);
470
- * }
471
- * }
472
- * ```
473
- */
474
- intervene(message: string): string;
475
- /**
476
- * Queue a message for after the current turn completes.
477
- *
478
- * Unlike `intervene()`, this does **not** interrupt the current turn.
479
- * The message is held and available via `drainQueuedNext()` after
480
- * `chat()` finishes. The consumer decides whether to send it as a
481
- * new turn.
482
- *
483
- * @param message - The message to queue
484
- * @returns Intervention ID for tracking
485
- *
486
- * @example
487
- * ```typescript
488
- * agent.queueNext("now run the test suite");
489
- *
490
- * for await (const event of agent.chat("s1", "fix the bug")) {
491
- * // ... handle events
492
- * }
493
- *
494
- * // After turn completes, check for queued messages
495
- * if (agent.hasQueuedNext()) {
496
- * const next = agent.drainQueuedNext();
497
- * for (const item of next) {
498
- * // Send as a new turn
499
- * for await (const ev of agent.chat("s1", item.message)) { ... }
500
- * }
501
- * }
502
- * ```
503
- */
504
- queueNext(message: string): string;
505
- /** Whether there are deferred messages queued for after the turn */
506
- hasQueuedNext(): boolean;
507
- /** Drain and return all deferred messages (clears the queue) */
508
- drainQueuedNext(): PendingIntervention[];
509
- /**
510
- * Get the raw intervention controller for advanced use cases.
511
- *
512
- * Use this when you need fine-grained control over the intervention
513
- * lifecycle (e.g., checking pending count, clearing queues, setting
514
- * custom `onApplied` callbacks).
515
- *
516
- * @internal
517
- */
518
- getInterventionController(): InterventionController;
519
- /**
520
- * Get the unified diff for all file changes in the current/last turn.
521
- *
522
- * @example
523
- * ```typescript
524
- * const diff = await agent.getTurnDiff();
525
- * if (diff) {
526
- * console.log('Changes this turn:\n', diff);
527
- * }
528
- * ```
529
- */
530
- getTurnDiff(): Promise<string | null>;
531
- /**
532
- * Get list of files being tracked in the current turn.
533
- */
534
- getTrackedFiles(): string[];
535
- /**
536
- * Undo all file changes from the current turn.
537
- * Restores files to their state before the turn started.
538
- *
539
- * @example
540
- * ```typescript
541
- * const result = await agent.undoTurn();
542
- * console.log(`Restored ${result.restored.length} files`);
543
- * if (result.failed.length > 0) {
544
- * console.log('Failed to restore:', result.failed);
545
- * }
546
- * ```
547
- */
548
- undoTurn(): Promise<UndoResult>;
549
- /**
550
- * Undo changes to specific files only.
551
- *
552
- * @param files - Array of file paths to restore (relative to cwd)
553
- */
554
- undoFiles(files: string[]): Promise<UndoResult>;
555
- /**
556
- * Check if currently tracking a turn.
557
- */
558
- isTrackingTurn(): boolean;
559
- /**
560
- * Get access to the raw turn tracker for advanced use cases.
561
- *
562
- * @internal
563
- */
564
- getTurnTracker(): TurnChangeTracker;
565
- /**
566
- * Update system prompt.
567
- *
568
- * If the agent is using the prompt pipeline, calling this switches
569
- * to flat string mode (disabling the pipeline). To modify the pipeline
570
- * instead, use `getPromptBuilder()`.
571
- */
572
- setSystemPrompt(prompt: string): void;
573
- /** Update working directory */
574
- setCwd(cwd: string): void;
575
- /** Update model */
576
- setModel(model: LanguageModel): void;
577
- /**
578
- * Get the prompt builder (when using pipeline mode).
579
- * Returns undefined if using flat string mode.
580
- *
581
- * Use this to add/remove sections, clear caches, or inspect
582
- * the prompt composition without switching to flat mode.
583
- *
584
- * @example
585
- * ```typescript
586
- * const builder = agent.getPromptBuilder();
587
- * if (builder) {
588
- * builder.addSection({
589
- * id: "task-context",
590
- * label: "Task Context",
591
- * content: "Focus on fixing authentication bugs.",
592
- * priority: 60,
593
- * });
594
- * }
595
- * ```
596
- */
597
- getPromptBuilder(): PromptBuilder | undefined;
598
- /**
599
- * Check if the agent is using the prompt pipeline.
600
- */
601
- isUsingPromptPipeline(): boolean;
602
- /**
603
- * Build the effective system prompts for a turn.
604
- *
605
- * This mirrors the prompt resolution path used by `chat()` so external host
606
- * runtimes can start durable turns without duplicating prompt assembly.
607
- */
608
- buildSystemPrompts(sessionId: string, override?: string): Promise<string[]>;
609
- /**
610
- * Return the runtime configuration required by the extracted turn-step
611
- * helpers.
612
- */
613
- getTurnRuntimeConfig(): AgentTurnStepRuntimeConfig;
614
- /**
615
- * Get the configured tool host.
616
- */
617
- getHost(): ToolHost;
618
- /**
619
- * Get the configured middleware runner.
620
- *
621
- * The runner is immutable after construction, so it is safe to reuse in
622
- * durable activity helpers that need the same middleware stack.
623
- */
624
- getMiddlewareRunner(): MiddlewareRunner;
625
- /**
626
- * Fork this agent to create a sub-agent with modified configuration.
627
- *
628
- * Sub-agents share the same session manager but can have different:
629
- * - System prompts (specialized for tasks)
630
- * - Tools (restricted subset)
631
- * - Models (cheaper/faster for simple tasks)
632
- * - Reasoning levels
633
- *
634
- * @example
635
- * ```typescript
636
- * // Create an exploration sub-agent with read-only tools
637
- * const explorer = agent.fork({
638
- * name: "explore",
639
- * systemPrompt: "You explore codebases. Only use read and search tools.",
640
- * tools: [readTool, grepTool, globTool],
641
- * });
642
- *
643
- * // Run the sub-agent
644
- * const result = await explorer.run({
645
- * parentSessionId: "main-session",
646
- * message: "Find all API endpoints",
647
- * });
648
- * ```
649
- */
650
- fork(options?: AgentForkOptions): Agent;
651
- /**
652
- * Create a sub-agent with a preset configuration.
653
- *
654
- * Convenience method that applies a preset and returns a forked agent.
655
- *
656
- * @example
657
- * ```typescript
658
- * import { Presets } from "@cuylabs/agent-core";
659
- *
660
- * // Create an exploration sub-agent
661
- * const explorer = agent.withPreset(Presets.explore);
662
- * const result = await explorer.run({
663
- * message: "Find all API routes in this project",
664
- * });
665
- *
666
- * // Create a careful review sub-agent
667
- * const reviewer = agent.withPreset(Presets.review);
668
- * const review = await reviewer.run({
669
- * message: "Review src/auth.ts for security issues",
670
- * });
671
- * ```
672
- */
673
- withPreset(preset: Preset): Agent;
674
- /**
675
- * Run a task in an isolated sub-agent session.
676
- *
677
- * Creates a new session linked to the parent, runs the task to completion,
678
- * and returns the result. The sub-agent session is preserved for inspection.
679
- *
680
- * @example
681
- * ```typescript
682
- * const result = await agent.run({
683
- * parentSessionId: "main-session",
684
- * message: "Review this code for security issues",
685
- * title: "Security Review",
686
- * });
687
- *
688
- * console.log(result.response);
689
- * console.log(`Sub-agent session: ${result.sessionId}`);
690
- * ```
691
- */
692
- run(options: {
693
- /** Parent session ID (for linking) */
694
- parentSessionId?: string;
695
- /** The task/message to execute */
696
- message: string;
697
- /** Title for the sub-agent session */
698
- title?: string;
699
- /** Abort signal */
700
- abort?: AbortSignal;
701
- }): Promise<{
702
- /** Final response text */
703
- response: string;
704
- /** Sub-agent session ID */
705
- sessionId: string;
706
- /** Token usage */
707
- usage: TokenUsage;
708
- /** Tool calls made */
709
- toolCalls: Array<{
710
- name: string;
711
- result: unknown;
712
- }>;
713
- }>;
714
- /**
715
- * Get the MCP manager (if configured)
716
- */
717
- getMCP(): MCPManager | undefined;
718
- /**
719
- * Check if MCP is configured
720
- */
721
- hasMCP(): boolean;
722
- /**
723
- * Reconnect to MCP servers
724
- *
725
- * Use this after network issues or when server availability changes.
726
- * Clears tool cache and reconnects all servers.
727
- */
728
- reconnectMCP(): Promise<void>;
729
- /**
730
- * Close the agent and clean up resources
731
- *
732
- * Flushes and shuts down the tracing provider (when `tracing` was configured),
733
- * closes MCP connections if configured.
734
- * After calling close(), the agent should not be used.
735
- */
736
- close(): Promise<void>;
737
- }
738
-
739
- /**
740
- * Sub-Agent Types
741
- *
742
- * Type definitions for the sub-agent system: profiles, lifecycle status,
743
- * handles, and configuration.
744
- *
745
- * Following PowerShell verb-noun naming (Invoke-Agent, Get-Agent, Stop-Agent).
746
- *
747
- * Designed for agent-core's composable library architecture.
748
- *
749
- * Key design decisions:
750
- *
751
- * 1. **Library-first**: Unlike CLI-embedded tools, these
752
- * are importable building blocks. The consumer creates them with
753
- * `createSubAgentTools(parent)` and opts in — nothing auto-registered.
754
- *
755
- * 2. **Agent profiles over role configs**: Instead of TOML files or markdown
756
- * agents, we use composable `AgentProfile` objects that wrap existing
757
- * `Preset` + extra metadata the LLM can read.
758
- *
759
- * 3. **Progressive lifecycle**: Start with synchronous `invoke_agent` (simplest),
760
- * add `wait_agent`/`close_agent` only when async profiles exist.
761
- *
762
- * 4. **Depth safety**: Hard limit on nesting with configurable max depth.
763
- *
764
- * @packageDocumentation
765
- */
766
-
767
- /**
768
- * An agent profile defines a specialized sub-agent personality.
769
- *
770
- * Profiles combine a `Preset` (tool filtering, temperature, etc.) with
771
- * LLM-facing metadata (name, description, examples) so the model knows
772
- * when and how to delegate.
773
- *
774
- * Profiles define specialized sub-agent personalities with roles
775
- * like explorer, worker, planner, and reviewer.
776
- *
777
- * @example
778
- * ```typescript
779
- * const explorer: AgentProfile = {
780
- * name: "explorer",
781
- * description: "Fast, read-only codebase exploration. Use when you need to find files, search code, or understand project structure.",
782
- * preset: Presets.explore,
783
- * maxSteps: 30,
784
- * };
785
- * ```
786
- */
787
- interface AgentProfile {
788
- /** Unique identifier used in tool calls (lowercase, no spaces) */
789
- name: string;
790
- /**
791
- * When to use this sub-agent — written for the LLM to consume.
792
- *
793
- * This is the most important field. The parent LLM reads this to decide
794
- * whether to delegate. Include clear trigger phrases.
795
- */
796
- description: string;
797
- /**
798
- * Preset to apply (tool filtering, temperature, system prompt, etc.).
799
- * If omitted, inherits the parent agent's configuration.
800
- */
801
- preset?: Preset;
802
- /**
803
- * Override system prompt for this profile.
804
- * Takes precedence over preset's systemPrompt.
805
- * Use `{basePrompt}` to include the parent's system prompt.
806
- */
807
- systemPrompt?: string;
808
- /**
809
- * Override model for this profile.
810
- * Useful for using cheaper/faster models for simple tasks.
811
- */
812
- model?: LanguageModel;
813
- /** Max steps for this sub-agent (default: parent's maxSteps) */
814
- maxSteps?: number;
815
- /**
816
- * Additional middleware appended to the parent's middleware stack.
817
- * Useful for adding logging or guardrails specific to this profile.
818
- */
819
- additionalMiddleware?: AgentMiddleware[];
820
- /**
821
- * Additional tools beyond what the preset allows.
822
- * These are merged with the preset-filtered tools.
823
- */
824
- additionalTools?: Tool.AnyInfo[];
825
- /**
826
- * Whether this sub-agent can itself spawn further sub-agents.
827
- * When false, the `invoke_agent` tool is removed from the child.
828
- *
829
- * @default false — sub-agents cannot nest by default (safe default)
830
- */
831
- canSpawn?: boolean;
832
- }
833
- /**
834
- * Lifecycle status of a running or completed sub-agent.
835
- *
836
- * Simplified lifecycle for the fire-and-forget-with-optional-wait model.
837
- */
838
- type SubAgentStatus = {
839
- state: "running";
840
- } | {
841
- state: "completed";
842
- response: string;
843
- usage: SubAgentUsage;
844
- } | {
845
- state: "errored";
846
- error: string;
847
- } | {
848
- state: "cancelled";
849
- };
850
- /**
851
- * Token usage tracking for a sub-agent run.
852
- */
853
- interface SubAgentUsage {
854
- inputTokens: number;
855
- outputTokens: number;
856
- totalTokens: number;
857
- }
858
- /**
859
- * A handle to a running or completed sub-agent.
860
- *
861
- * Returned by async invocations. Allows the parent to wait for completion,
862
- * check status, or cancel.
863
- */
864
- interface SubAgentHandle {
865
- /** Unique ID for this sub-agent invocation */
866
- id: string;
867
- /** Human-readable name (from profile or auto-generated) */
868
- name: string;
869
- /** Session ID of the child agent's session */
870
- sessionId: string;
871
- /** Current status */
872
- status: SubAgentStatus;
873
- /** The promise that resolves when the sub-agent completes */
874
- promise: Promise<SubAgentCompletedResult>;
875
- /** Abort controller to cancel this sub-agent */
876
- abort: AbortController;
877
- }
878
- /**
879
- * The final result of a completed sub-agent.
880
- */
881
- interface SubAgentCompletedResult {
882
- /** Final response text */
883
- response: string;
884
- /** Session ID (for audit/inspection) */
885
- sessionId: string;
886
- /** Token usage */
887
- usage: SubAgentUsage;
888
- /** Tool calls the sub-agent made */
889
- toolCalls: Array<{
890
- name: string;
891
- result: unknown;
892
- }>;
893
- }
894
- /**
895
- * Configuration for `createSubAgentTools()`.
896
- *
897
- * Controls which profiles are available, concurrency limits,
898
- * depth limits, and whether async mode is enabled.
899
- */
900
- interface SubAgentToolConfig {
901
- /**
902
- * Available sub-agent profiles.
903
- * Each profile defines a specialized persona the LLM can invoke.
904
- * At least one profile is required.
905
- */
906
- profiles: AgentProfile[];
907
- /**
908
- * Maximum concurrent sub-agents (across all profiles).
909
- * @default 6
910
- */
911
- maxConcurrent?: number;
912
- /**
913
- * Maximum nesting depth for recursive sub-agent spawning.
914
- * Depth 0 = no spawning, 1 = one level of sub-agents, etc.
915
- *
916
- * When a sub-agent reaches the depth limit, the `invoke_agent`
917
- * tool is automatically removed from its tool set.
918
- *
919
- * @default 2
920
- */
921
- maxDepth?: number;
922
- /**
923
- * Current depth (internal — incremented when creating child tools).
924
- * Users should not set this directly.
925
- *
926
- * @internal
927
- */
928
- currentDepth?: number;
929
- /**
930
- * Enable async mode with `wait_agent` and `close_agent` tools.
931
- *
932
- * When false (default), `invoke_agent` blocks until the sub-agent
933
- * completes and returns the result directly — simpler but sequential.
934
- *
935
- * When true, `invoke_agent` returns immediately with an agent ID,
936
- * and the LLM must call `wait_agent` to collect results. This enables
937
- * parallel sub-agent execution.
938
- *
939
- * @default false
940
- */
941
- async?: boolean;
942
- /**
943
- * Title prefix for sub-agent sessions.
944
- * @default "Sub-agent"
945
- */
946
- sessionTitlePrefix?: string;
947
- }
948
- /** Default maximum concurrent sub-agents */
949
- declare const DEFAULT_MAX_CONCURRENT = 6;
950
- /** Default maximum nesting depth */
951
- declare const DEFAULT_MAX_SPAWN_DEPTH = 2;
952
- /** Default session title prefix */
953
- declare const DEFAULT_SESSION_TITLE_PREFIX = "Sub-agent";
954
-
955
- /**
956
- * Sub-Agent Tracker — in-memory state for active sub-agents
957
- *
958
- * Manages the lifecycle of running sub-agents: slots, handles,
959
- * concurrency limits, and depth enforcement.
960
- *
961
- * Handles spawn slot reservation and depth checking, designed for
962
- * single-process TypeScript/async usage.
963
- *
964
- * @packageDocumentation
965
- */
966
-
967
- /**
968
- * Tracks active sub-agent handles and enforces concurrency/depth limits.
969
- *
970
- * One tracker is created per `createSubAgentTools()` call and shared
971
- * across all sub-agent tool instances for that parent agent.
972
- */
973
- declare class SubAgentTracker {
974
- /** Active sub-agent handles by ID */
975
- private readonly handles;
976
- /** Maximum concurrent sub-agents */
977
- readonly maxConcurrent: number;
978
- /** Maximum nesting depth */
979
- readonly maxDepth: number;
980
- /** Current depth in the spawn hierarchy */
981
- readonly currentDepth: number;
982
- constructor(config?: Partial<SubAgentToolConfig>);
983
- /** Number of currently active (running) sub-agents */
984
- get activeCount(): number;
985
- /** Total tracked handles (including completed) */
986
- get totalCount(): number;
987
- /**
988
- * Check if a new sub-agent can be spawned.
989
- * Returns an error message if not, undefined if OK.
990
- */
991
- canSpawn(): string | undefined;
992
- /** Whether the current depth allows further spawning */
993
- get canNest(): boolean;
994
- /** Register a new sub-agent handle */
995
- register(handle: SubAgentHandle): void;
996
- /** Get a handle by ID */
997
- get(id: string): SubAgentHandle | undefined;
998
- /** Update a handle's status */
999
- updateStatus(id: string, status: SubAgentStatus): void;
1000
- /** Get all handles */
1001
- list(): SubAgentHandle[];
1002
- /** Get all running handles */
1003
- running(): SubAgentHandle[];
1004
- /** Get all completed handles */
1005
- completed(): SubAgentHandle[];
1006
- /**
1007
- * Cancel a running sub-agent.
1008
- * Signals the abort controller and updates status.
1009
- */
1010
- cancel(id: string): boolean;
1011
- /**
1012
- * Cancel all running sub-agents.
1013
- */
1014
- cancelAll(): void;
1015
- /**
1016
- * Wait for a specific sub-agent to complete.
1017
- * Returns the result or throws if not found.
1018
- */
1019
- wait(id: string, timeoutMs?: number): Promise<SubAgentCompletedResult>;
1020
- /**
1021
- * Wait for any one of the given sub-agents to complete.
1022
- * Returns the first result.
1023
- */
1024
- waitAny(ids: string[], timeoutMs?: number): Promise<{
1025
- id: string;
1026
- result: SubAgentCompletedResult;
1027
- } | {
1028
- timedOut: true;
1029
- }>;
1030
- /**
1031
- * Create a child tracker configuration for a nested sub-agent.
1032
- * Increments the depth counter.
1033
- */
1034
- childConfig(): Partial<SubAgentToolConfig>;
1035
- }
1036
-
1037
- /**
1038
- * Sub-Agent Tools — LLM-callable tools for delegating work to specialized agents
1039
- *
1040
- * Provides three tools:
1041
- * - `invoke_agent` — spawn a sub-agent for a focused task
1042
- * - `wait_agent` — collect async sub-agent results
1043
- * - `close_agent` — cancel a running async sub-agent
1044
- *
1045
- * @packageDocumentation
1046
- */
1047
-
1048
- /**
1049
- * Create the sub-agent tools for an agent.
1050
- *
1051
- * Returns an array of tools that the LLM can call to delegate tasks:
1052
- * - `invoke_agent` — always included
1053
- * - `wait_agent` — only in async mode
1054
- * - `close_agent` — only in async mode
1055
- */
1056
- declare function createSubAgentTools(parent: Agent, config: SubAgentToolConfig): Tool.AnyInfo[];
1057
-
1058
- export { type AgentConfig as A, type CompactionConfig as C, DEFAULT_MAX_CONCURRENT as D, PRUNE_PROTECTED_TOOLS as P, type SubAgentCompletedResult as S, type TracingConfig as T, Agent as a, type AgentProfile as b, DEFAULT_MAX_SPAWN_DEPTH as c, DEFAULT_SESSION_TITLE_PREFIX as d, type SubAgentHandle as e, type SubAgentStatus as f, type SubAgentToolConfig as g, SubAgentTracker as h, type SubAgentUsage as i, createAgent as j, createSubAgentTools as k };