noumen 0.1.0 → 0.2.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 (118) hide show
  1. package/README.md +767 -51
  2. package/dist/a2a/index.d.ts +148 -0
  3. package/dist/a2a/index.js +579 -0
  4. package/dist/a2a/index.js.map +1 -0
  5. package/dist/acp/index.d.ts +129 -0
  6. package/dist/acp/index.js +498 -0
  7. package/dist/acp/index.js.map +1 -0
  8. package/dist/agent-BrkbZyOT.d.ts +1028 -0
  9. package/dist/cache-DVqaCX8v.d.ts +38 -0
  10. package/dist/chunk-2ZTGQLYK.js +356 -0
  11. package/dist/chunk-2ZTGQLYK.js.map +1 -0
  12. package/dist/chunk-42PHHZUA.js +132 -0
  13. package/dist/chunk-42PHHZUA.js.map +1 -0
  14. package/dist/chunk-4SQA2UCV.js +26 -0
  15. package/dist/chunk-4SQA2UCV.js.map +1 -0
  16. package/dist/chunk-5GEX6ZSB.js +179 -0
  17. package/dist/chunk-5GEX6ZSB.js.map +1 -0
  18. package/dist/chunk-7ZMN7XJE.js +94 -0
  19. package/dist/chunk-7ZMN7XJE.js.map +1 -0
  20. package/dist/chunk-AMYIJSAZ.js +57 -0
  21. package/dist/chunk-AMYIJSAZ.js.map +1 -0
  22. package/dist/chunk-BGG2E6JD.js +10 -0
  23. package/dist/chunk-BGG2E6JD.js.map +1 -0
  24. package/dist/chunk-BZSFUEWM.js +43 -0
  25. package/dist/chunk-BZSFUEWM.js.map +1 -0
  26. package/dist/chunk-CPFHEPW4.js +139 -0
  27. package/dist/chunk-CPFHEPW4.js.map +1 -0
  28. package/dist/chunk-D43BWEZA.js +346 -0
  29. package/dist/chunk-D43BWEZA.js.map +1 -0
  30. package/dist/chunk-DGUM43GV.js +11 -0
  31. package/dist/chunk-DGUM43GV.js.map +1 -0
  32. package/dist/chunk-JACGEMTF.js +43 -0
  33. package/dist/chunk-JACGEMTF.js.map +1 -0
  34. package/dist/chunk-JX7CLUCV.js +21 -0
  35. package/dist/chunk-JX7CLUCV.js.map +1 -0
  36. package/dist/chunk-KXDB56YW.js +39 -0
  37. package/dist/chunk-KXDB56YW.js.map +1 -0
  38. package/dist/chunk-KY6ZPWHO.js +112 -0
  39. package/dist/chunk-KY6ZPWHO.js.map +1 -0
  40. package/dist/chunk-NBDFQYUZ.js +7992 -0
  41. package/dist/chunk-NBDFQYUZ.js.map +1 -0
  42. package/dist/chunk-OGXNFXFA.js +196 -0
  43. package/dist/chunk-OGXNFXFA.js.map +1 -0
  44. package/dist/chunk-QTJ7VTJY.js +1994 -0
  45. package/dist/chunk-QTJ7VTJY.js.map +1 -0
  46. package/dist/chunk-UVSSQBDY.js +192 -0
  47. package/dist/chunk-UVSSQBDY.js.map +1 -0
  48. package/dist/chunk-Y45R3PQL.js +684 -0
  49. package/dist/chunk-Y45R3PQL.js.map +1 -0
  50. package/dist/cli/index.d.ts +1 -0
  51. package/dist/cli/index.js +868 -0
  52. package/dist/cli/index.js.map +1 -0
  53. package/dist/client/index.d.ts +64 -0
  54. package/dist/client/index.js +409 -0
  55. package/dist/client/index.js.map +1 -0
  56. package/dist/client-CRRO2376.js +10 -0
  57. package/dist/client-CRRO2376.js.map +1 -0
  58. package/dist/headless-Q7XHHZIW.js +143 -0
  59. package/dist/headless-Q7XHHZIW.js.map +1 -0
  60. package/dist/history-snip-64GYP4ZL.js +12 -0
  61. package/dist/history-snip-64GYP4ZL.js.map +1 -0
  62. package/dist/index.d.ts +1305 -418
  63. package/dist/index.js +384 -1757
  64. package/dist/index.js.map +1 -1
  65. package/dist/jsonrpc/index.d.ts +54 -0
  66. package/dist/jsonrpc/index.js +34 -0
  67. package/dist/jsonrpc/index.js.map +1 -0
  68. package/dist/lsp/index.d.ts +36 -0
  69. package/dist/lsp/index.js +16 -0
  70. package/dist/lsp/index.js.map +1 -0
  71. package/dist/lsp-PS3BWIHC.js +8 -0
  72. package/dist/lsp-PS3BWIHC.js.map +1 -0
  73. package/dist/manager-DLXK63XC.js +8 -0
  74. package/dist/manager-DLXK63XC.js.map +1 -0
  75. package/dist/mcp/index.d.ts +111 -0
  76. package/dist/mcp/index.js +104 -0
  77. package/dist/mcp/index.js.map +1 -0
  78. package/dist/mcp-auth-AEI2R4ZC.js +9 -0
  79. package/dist/mcp-auth-AEI2R4ZC.js.map +1 -0
  80. package/dist/ollama-YNXAYP3R.js +18 -0
  81. package/dist/ollama-YNXAYP3R.js.map +1 -0
  82. package/dist/provider-factory-34MSWJZ3.js +20 -0
  83. package/dist/provider-factory-34MSWJZ3.js.map +1 -0
  84. package/dist/providers/anthropic.d.ts +19 -0
  85. package/dist/providers/anthropic.js +33 -0
  86. package/dist/providers/anthropic.js.map +1 -0
  87. package/dist/providers/bedrock.d.ts +39 -0
  88. package/dist/providers/bedrock.js +54 -0
  89. package/dist/providers/bedrock.js.map +1 -0
  90. package/dist/providers/gemini.d.ts +16 -0
  91. package/dist/providers/gemini.js +224 -0
  92. package/dist/providers/gemini.js.map +1 -0
  93. package/dist/providers/openai.d.ts +18 -0
  94. package/dist/providers/openai.js +8 -0
  95. package/dist/providers/openai.js.map +1 -0
  96. package/dist/providers/openrouter.d.ts +16 -0
  97. package/dist/providers/openrouter.js +23 -0
  98. package/dist/providers/openrouter.js.map +1 -0
  99. package/dist/providers/vertex.d.ts +40 -0
  100. package/dist/providers/vertex.js +64 -0
  101. package/dist/providers/vertex.js.map +1 -0
  102. package/dist/render-GRN4ZSSW.js +14 -0
  103. package/dist/render-GRN4ZSSW.js.map +1 -0
  104. package/dist/resolve-XM52G7YE.js +14 -0
  105. package/dist/resolve-XM52G7YE.js.map +1 -0
  106. package/dist/server/index.d.ts +128 -0
  107. package/dist/server/index.js +626 -0
  108. package/dist/server/index.js.map +1 -0
  109. package/dist/server-Cg1yWGaV.d.ts +96 -0
  110. package/dist/spinner-OJNR6NFO.js +8 -0
  111. package/dist/spinner-OJNR6NFO.js.map +1 -0
  112. package/dist/types-2kTLUCnD.d.ts +107 -0
  113. package/dist/types-3c88cRKH.d.ts +547 -0
  114. package/dist/types-CwKKucOF.d.ts +620 -0
  115. package/dist/types-DwdzmXfs.d.ts +107 -0
  116. package/dist/types-NIyVwQ4h.d.ts +109 -0
  117. package/dist/types-QwfylltH.d.ts +71 -0
  118. package/package.json +134 -6
package/dist/index.d.ts CHANGED
@@ -1,376 +1,82 @@
1
- type UUID = string & {
2
- readonly __brand: unique symbol;
3
- };
4
-
5
- interface ToolCallContent {
6
- id: string;
7
- type: "function";
8
- function: {
9
- name: string;
10
- arguments: string;
11
- };
12
- }
13
- interface UserMessage {
14
- role: "user";
15
- content: string;
16
- }
17
- interface AssistantMessage {
18
- role: "assistant";
19
- content: string | null;
20
- tool_calls?: ToolCallContent[];
21
- }
22
- interface ToolResultMessage {
23
- role: "tool";
24
- tool_call_id: string;
25
- content: string;
26
- }
27
- interface SystemMessage {
28
- role: "system";
29
- content: string;
30
- }
31
- type ChatMessage = UserMessage | AssistantMessage | ToolResultMessage | SystemMessage;
32
- interface SerializedMessage {
33
- uuid: UUID;
34
- parentUuid: UUID | null;
35
- sessionId: string;
36
- timestamp: string;
37
- message: ChatMessage;
38
- }
39
- interface MessageEntry {
40
- type: "message";
41
- uuid: UUID;
42
- parentUuid: UUID | null;
43
- sessionId: string;
44
- timestamp: string;
45
- message: ChatMessage;
46
- }
47
- interface CompactBoundaryEntry {
48
- type: "compact-boundary";
49
- uuid: UUID;
50
- sessionId: string;
51
- timestamp: string;
52
- }
53
- interface SummaryEntry {
54
- type: "summary";
55
- uuid: UUID;
56
- parentUuid: UUID | null;
57
- sessionId: string;
58
- timestamp: string;
59
- message: ChatMessage;
60
- }
61
- interface CustomTitleEntry {
62
- type: "custom-title";
63
- sessionId: string;
64
- title: string;
65
- timestamp: string;
66
- }
67
- interface MetadataEntry {
68
- type: "metadata";
69
- sessionId: string;
70
- timestamp: string;
71
- key: string;
72
- value: unknown;
73
- }
74
- type Entry = MessageEntry | CompactBoundaryEntry | SummaryEntry | CustomTitleEntry | MetadataEntry;
75
- interface SessionInfo {
76
- sessionId: string;
77
- createdAt: string;
78
- lastMessageAt: string;
79
- title?: string;
80
- messageCount: number;
81
- }
82
- interface ToolResult$1 {
83
- content: string;
84
- isError?: boolean;
85
- }
86
- type StreamEvent = {
87
- type: "text_delta";
88
- text: string;
89
- } | {
90
- type: "tool_use_start";
91
- toolName: string;
92
- toolUseId: string;
93
- } | {
94
- type: "tool_use_delta";
95
- input: string;
96
- } | {
97
- type: "tool_result";
98
- toolUseId: string;
99
- toolName: string;
100
- result: ToolResult$1;
101
- } | {
102
- type: "message_complete";
103
- message: AssistantMessage;
104
- } | {
105
- type: "compact_start";
106
- } | {
107
- type: "compact_complete";
108
- } | {
109
- type: "error";
110
- error: Error;
111
- };
112
- interface RunOptions {
113
- signal?: AbortSignal;
114
- }
115
-
116
- interface ToolParameterProperty$1 {
117
- type: string;
118
- description?: string;
119
- enum?: string[];
120
- default?: unknown;
121
- minimum?: number;
122
- maximum?: number;
123
- }
124
- interface ToolDefinition {
125
- type: "function";
126
- function: {
127
- name: string;
128
- description: string;
129
- parameters: {
130
- type: "object";
131
- properties: Record<string, ToolParameterProperty$1>;
132
- required?: string[];
133
- };
134
- };
135
- }
136
- interface ChatStreamDelta {
137
- role?: "assistant";
138
- content?: string | null;
139
- tool_calls?: Array<{
140
- index: number;
141
- id?: string;
142
- type?: "function";
143
- function?: {
144
- name?: string;
145
- arguments?: string;
146
- };
147
- }>;
148
- }
149
- interface ChatStreamChoice {
150
- index: number;
151
- delta: ChatStreamDelta;
152
- finish_reason: string | null;
153
- }
154
- interface ChatStreamChunk {
155
- id: string;
156
- choices: ChatStreamChoice[];
157
- model: string;
158
- usage?: {
159
- prompt_tokens: number;
160
- completion_tokens: number;
161
- total_tokens: number;
162
- };
163
- }
164
- interface ChatCompletionUsage {
165
- prompt_tokens: number;
166
- completion_tokens: number;
167
- total_tokens: number;
168
- }
169
- interface ChatParams {
170
- model: string;
171
- messages: ChatMessage[];
172
- tools?: ToolDefinition[];
173
- max_tokens?: number;
174
- system?: string;
175
- temperature?: number;
176
- }
177
- interface AIProvider {
178
- chat(params: ChatParams): AsyncIterable<ChatStreamChunk>;
179
- }
180
-
181
- interface FileEntry {
182
- name: string;
183
- path: string;
184
- isDirectory: boolean;
185
- isFile: boolean;
186
- size?: number;
187
- }
188
- interface FileStat {
189
- size: number;
190
- isDirectory: boolean;
191
- isFile: boolean;
192
- createdAt?: Date;
193
- modifiedAt?: Date;
194
- }
195
- interface ReadOptions {
196
- encoding?: BufferEncoding;
197
- }
198
- interface VirtualFs {
199
- readFile(path: string, opts?: ReadOptions): Promise<string>;
200
- writeFile(path: string, content: string): Promise<void>;
201
- appendFile(path: string, content: string): Promise<void>;
202
- deleteFile(path: string, opts?: {
203
- recursive?: boolean;
204
- }): Promise<void>;
205
- mkdir(path: string, opts?: {
206
- recursive?: boolean;
207
- }): Promise<void>;
208
- readdir(path: string, opts?: {
209
- recursive?: boolean;
210
- }): Promise<FileEntry[]>;
211
- exists(path: string): Promise<boolean>;
212
- stat(path: string): Promise<FileStat>;
213
- }
214
-
215
- interface ExecOptions {
216
- timeout?: number;
217
- cwd?: string;
218
- env?: Record<string, string>;
219
- }
220
- interface CommandResult {
221
- exitCode: number;
222
- stdout: string;
223
- stderr: string;
224
- }
225
- interface VirtualComputer {
226
- executeCommand(command: string, opts?: ExecOptions): Promise<CommandResult>;
227
- }
228
-
229
- interface SkillDefinition {
230
- name: string;
231
- content: string;
232
- path?: string;
233
- description?: string;
234
- /** Glob patterns for files this skill applies to */
235
- globs?: string[];
236
- }
237
-
238
- interface AutoCompactConfig {
239
- enabled: boolean;
240
- /** Token threshold at which to trigger compaction */
241
- threshold: number;
242
- }
243
- declare function createAutoCompactConfig(opts?: {
244
- enabled?: boolean;
245
- threshold?: number;
246
- }): AutoCompactConfig;
247
- declare function shouldAutoCompact(messages: ChatMessage[], config: AutoCompactConfig): boolean;
1
+ import { S as Sandbox, A as Agent, D as DockerContainer, E as E2BSandboxInstance, a as SkillDefinition, T as ThreadConfig, b as SessionStorage, C as ContextFile, P as ProjectContextConfig, c as ContextScope, R as RetryConfig, d as RetryContext, e as RetryEngineOptions, f as Span, g as SpanAttributeValue, h as SpanStatusCode, i as Tracer, j as SpanOptions, k as StoredCostState } from './agent-BrkbZyOT.js';
2
+ export { l as AgentOptions, m as AutoCompactConfig, n as AutoCompactTrackingState, B as BudgetState, o as CLEARED_PLACEHOLDER, p as COMPACTABLE_TOOLS, q as ContentReplacementState, r as CostTracker, s as DEFAULT_MODELS, t as DEFAULT_RETRY_CONFIG, u as DiagnoseCheckResult, v as DiagnoseResult, w as DockerComputer, x as DockerComputerOptions, y as DockerSandbox, z as DockerSandboxOptions, F as E2BComputer, G as E2BComputerOptions, H as E2BSandbox, I as E2BSandboxOptions, L as LocalSandbox, J as LocalSandboxOptions, M as MicrocompactConfig, K as MicrocompactResult, N as ProviderName, O as ReactiveCompactConfig, Q as ReactiveCompactResult, U as ResolveProviderOptions, V as RetryEvent, W as RunCallbacks, X as RunResult, Y as SUPPORTED_PROVIDERS, Z as SandboxConfig, _ as SandboxedLocalComputer, $ as SandboxedLocalComputerOptions, a0 as SnipConfig, a1 as SnipResult, a2 as SpritesSandbox, a3 as SpritesSandboxOptions, a4 as Thread, a5 as ThreadOptions, a6 as ToolResultBudgetConfig, a7 as ToolResultBudgetResult, a8 as ToolResultReplacementRecord, a9 as ToolResultSpillResult, aa as ToolResultStorageConfig, ab as TracingConfig, ac as UnsandboxedLocal, ad as UnsandboxedLocalOptions, ae as WebSearchConfig, af as WebSearchResult, ag as applyPersistedReplacements, ah as applySnipRemovals, ai as canAutoCompact, aj as createAutoCompactConfig, ak as createAutoCompactTracking, al as createBudgetState, am as createContentReplacementState, an as createWebSearchTool, ao as detectProvider, ap as enforceToolResultBudget, aq as enforceToolResultStorageBudget, ar as microcompactMessages, as as persistToolResult, at as projectSnippedView, au as reconstructContentReplacementState, av as recordAutoCompactFailure, aw as recordAutoCompactSuccess, ax as resolveProvider, ay as shouldAutoCompact, az as snipMessagesByUuids, aA as tryReactiveCompact, aB as webSearchToolPlaceholder } from './agent-BrkbZyOT.js';
3
+ import { A as AIProvider, T as ToolDefinition, o as ToolCallContent, S as StreamEvent, e as ContentPart, b as ChatMessage, k as ChatCompletionUsage, M as ModelPricing, h as UsageRecord, a as ChatStreamChunk, p as MemoryProvider, q as MemoryEntry, l as ThinkingConfig, r as AssistantMessage, s as ToolResultMessage, d as FileCheckpointSnapshot, t as ToolResultOverflowEntry, f as ContentReplacementRecord, J as JsonSchemaOutputFormat } from './types-3c88cRKH.js';
4
+ export { C as ChatParams, u as ChatStreamChoice, v as ChatStreamDelta, w as ChatStreamError, c as CheckpointConfig, x as CompactBoundaryEntry, y as ContentReplacementEntry, i as CostSummary, z as CustomTitleEntry, D as DiffStats, E as Entry, B as FileCheckpointBackup, G as FileCheckpointEntry, F as FileCheckpointState, I as ImageContent, H as ImageUrlContent, K as JsonObjectOutputFormat, m as MemoryConfig, L as MemoryType, N as MessageEntry, P as MetadataEntry, j as ModelUsageSummary, O as OutputFormat, R as RunOptions, Q as SerializedMessage, g as SessionInfo, V as SnipBoundaryEntry, W as SummaryEntry, X as SystemMessage, Y as TextContent, Z as ToolDefParameterProperty, n as ToolResult, _ as UserMessage, $ as createCheckpointState } from './types-3c88cRKH.js';
5
+ import { H as HookDefinition, V as VirtualFs, R as ReadOptions, F as FileEntry, i as FileStat, j as VirtualComputer, E as ExecOptions, C as CommandResult, T as Tool, h as ToolContext, g as ToolResult, o as HookEvent, p as HookInput, P as PostToolUseFailureHookInput, q as PostToolUseFailureHookOutput, r as PostToolUseHookInput, s as PostToolUseHookOutput, t as PreToolUseHookInput, u as PreToolUseHookOutput } from './types-CwKKucOF.js';
6
+ export { m as FileCheckpointManager, v as FileState, w as FileStateCache, n as FileStateCacheConfig, x as FileWriteHookInput, y as HookOutput, J as JsonSchemaType, b as LspDiagnostic, c as LspLocation, d as LspOperation, L as LspServerConfig, a as LspServerState, f as LspSymbol, M as MemoryUpdateHookInput, z as ModelSwitchHookInput, N as NotificationHookInput, A as PermissionDeniedHookInput, B as PermissionRequestHookInput, G as RetryAttemptHookInput, I as SafeParseResult, K as SessionEndHookInput, O as SessionStartHookInput, S as SubagentConfig, k as SubagentRun, Q as SubagentStartHookInput, U as SubagentStopHookInput, W as Task, X as TaskCreateInput, Y as TaskStatus, l as TaskStore, Z as TaskUpdateInput, _ as ToolParameters, $ as ZodLikeSchema, a0 as formatZodValidationError, a1 as registerZodToJsonSchema, a2 as zodToJsonSchema } from './types-CwKKucOF.js';
7
+ import { M as McpServerConfig } from './types-2kTLUCnD.js';
8
+ export { b as McpConfig, c as McpConnection, d as McpHttpServerConfig, e as McpOAuthConfig, f as McpSseServerConfig, g as McpStdioServerConfig, h as McpToolInfo, i as McpWebSocketServerConfig, a as OAuthProviderOptions, O as OAuthTokenData, T as TokenStorage } from './types-2kTLUCnD.js';
9
+ export { OpenAIProviderOptions } from './providers/openai.js';
10
+ export { AnthropicProviderOptions } from './providers/anthropic.js';
11
+ export { GeminiProviderOptions } from './providers/gemini.js';
12
+ export { OpenRouterProviderOptions } from './providers/openrouter.js';
13
+ export { BedrockAnthropicProviderOptions } from './providers/bedrock.js';
14
+ export { VertexAnthropicProviderOptions } from './providers/vertex.js';
15
+ import { c as PermissionHandler, e as PermissionContext, f as PermissionBehavior, g as PermissionRule, A as AutoModeConfig, h as PermissionDecision, i as PermissionUpdate } from './types-DwdzmXfs.js';
16
+ export { D as DenialTrackingConfig, j as PermissionAllowResult, k as PermissionAskResult, d as PermissionConfig, l as PermissionDenyResult, a as PermissionMode, m as PermissionPassthroughResult, n as PermissionRequest, P as PermissionResponse, b as PermissionResult, o as PermissionRuleSource, R as RULE_SOURCE_PRECEDENCE } from './types-DwdzmXfs.js';
17
+ export { a as McpClientManagerOptions, b as McpServerOptions, c as buildMcpToolName, g as getMcpPrefix, n as normalizeNameForMCP, p as parseMcpToolName } from './server-Cg1yWGaV.js';
18
+ export { C as CacheControlConfig, a as CacheScope, g as getMessageCacheBreakpointIndex, s as sortToolDefinitionsForCache } from './cache-DVqaCX8v.js';
19
+ export { JsonRpcErrorObject, JsonRpcMessage, JsonRpcNotification, JsonRpcRequest, JsonRpcResponse } from './jsonrpc/index.js';
20
+ export { b as AcpCapabilities, c as AcpInitializeParams, d as AcpInitializeResult, A as AcpTransport } from './types-QwfylltH.js';
21
+ export { e as A2AArtifact, M as A2AMessage, P as A2APart, b as A2ATask, g as A2ATaskStatus, a as AgentCard, A as AgentSkill } from './types-NIyVwQ4h.js';
22
+ export { OAuthClientInformation, OAuthClientInformationFull, OAuthClientInformationMixed, OAuthClientMetadata, OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';
23
+ export { OAuthClientProvider, OAuthDiscoveryState } from '@modelcontextprotocol/sdk/client/auth.js';
24
+ import '@modelcontextprotocol/sdk/client/index.js';
248
25
 
249
- interface ThreadOptions {
250
- sessionId?: string;
251
- resume?: boolean;
26
+ interface PresetOptions {
27
+ /** The AI provider instance (e.g. `new OpenAIProvider({ apiKey })`) */
28
+ provider: AIProvider;
29
+ /** Working directory for the sandbox. Defaults to `process.cwd()`. */
252
30
  cwd?: string;
31
+ /** Model name override. Each preset has a sensible default. */
253
32
  model?: string;
254
- }
255
- interface ThreadConfig {
256
- aiProvider: AIProvider;
257
- fs: VirtualFs;
258
- computer: VirtualComputer;
259
- sessionDir: string;
260
- skills?: SkillDefinition[];
33
+ /** Custom sandbox. Defaults to `UnsandboxedLocal({ cwd })`. */
34
+ sandbox?: Sandbox;
35
+ /** Extra hooks to attach. */
36
+ hooks?: HookDefinition[];
37
+ /** MCP servers to connect to during `init()`. */
38
+ mcpServers?: Record<string, McpServerConfig>;
39
+ /** Custom system prompt prepended to the built-in prompt. */
261
40
  systemPrompt?: string;
262
- model?: string;
263
- maxTokens?: number;
264
- autoCompact?: AutoCompactConfig;
265
- }
266
- declare class Thread {
267
- readonly sessionId: string;
268
- private config;
269
- private storage;
270
- private toolRegistry;
271
- private messages;
272
- private loaded;
273
- private abortController;
274
- private cwd;
275
- private model;
276
- constructor(config: ThreadConfig, opts?: ThreadOptions);
277
- run(prompt: string, opts?: RunOptions): AsyncGenerator<StreamEvent, void, unknown>;
278
- getMessages(): Promise<ChatMessage[]>;
279
- compact(opts?: {
280
- instructions?: string;
281
- }): Promise<void>;
282
- abort(): void;
283
- }
284
-
285
- interface CodeOptions {
286
- aiProvider: AIProvider;
287
- virtualFs: VirtualFs;
288
- virtualComputer: VirtualComputer;
289
- options?: {
290
- sessionDir?: string;
291
- skills?: SkillDefinition[];
292
- skillsPaths?: string[];
293
- systemPrompt?: string;
294
- model?: string;
295
- maxTokens?: number;
296
- autoCompact?: boolean;
297
- autoCompactThreshold?: number;
298
- cwd?: string;
299
- };
300
- }
301
- declare class Code {
302
- private aiProvider;
303
- private fs;
304
- private computer;
305
- private sessionDir;
306
- private skills;
307
- private skillsPaths;
308
- private systemPrompt?;
309
- private model?;
310
- private maxTokens?;
311
- private autoCompactEnabled;
312
- private autoCompactThreshold?;
313
- private cwd;
314
- private storage;
315
- private resolvedSkills;
316
- constructor(opts: CodeOptions);
317
- private getSkills;
318
- createThread(opts?: ThreadOptions): Thread;
319
- listSessions(): Promise<SessionInfo[]>;
320
- /**
321
- * Pre-resolve skills from paths. Call this once after construction if using
322
- * skillsPaths, so that createThread() has skills available synchronously.
323
- */
324
- init(): Promise<void>;
325
- }
326
-
327
- interface OpenAIProviderOptions {
328
- apiKey: string;
329
- baseURL?: string;
330
- model?: string;
331
- }
332
- declare class OpenAIProvider implements AIProvider {
333
- private client;
334
- private defaultModel;
335
- constructor(opts: OpenAIProviderOptions);
336
- chat(params: ChatParams): AsyncIterable<ChatStreamChunk>;
337
- private buildMessages;
338
41
  }
42
+ /**
43
+ * Full-featured coding agent with subagents, tasks, plan mode, auto-compact,
44
+ * retry, cost tracking, and project context enabled out of the box.
45
+ */
46
+ declare function codingAgent(opts: PresetOptions): Agent;
47
+ /**
48
+ * Read-only planning agent — can explore the codebase but cannot make changes.
49
+ * Useful for architecture analysis, code review prep, or scoping work.
50
+ */
51
+ declare function planningAgent(opts: PresetOptions): Agent;
52
+ /**
53
+ * Code review agent — read-only with web search enabled for looking up
54
+ * documentation, best practices, and security advisories.
55
+ */
56
+ declare function reviewAgent(opts: PresetOptions): Agent;
339
57
 
340
- interface AnthropicProviderOptions {
341
- apiKey: string;
58
+ interface OllamaProviderOptions {
59
+ /** Ollama server URL. Defaults to http://localhost:11434/v1. */
342
60
  baseURL?: string;
343
61
  model?: string;
344
62
  }
345
- declare class AnthropicProvider implements AIProvider {
346
- private client;
347
- private defaultModel;
348
- constructor(opts: AnthropicProviderOptions);
349
- chat(params: ChatParams): AsyncIterable<ChatStreamChunk>;
350
- private makeChunk;
351
- private convertMessages;
352
- }
353
-
354
- interface GeminiProviderOptions {
355
- apiKey: string;
356
- model?: string;
357
- }
358
- declare class GeminiProvider implements AIProvider {
359
- private client;
360
- private defaultModel;
361
- constructor(opts: GeminiProviderOptions);
362
- chat(params: ChatParams): AsyncIterable<ChatStreamChunk>;
363
- private convertMessages;
364
- }
365
63
 
366
64
  interface LocalFsOptions {
367
65
  basePath?: string;
368
66
  }
67
+ /**
68
+ * Unsandboxed VirtualFs backed by `node:fs/promises` on the host machine.
69
+ * Paths resolve relative to `basePath`. Suitable for local development and
70
+ * trusted environments. For production or untrusted agents, use a sandboxed
71
+ * implementation like `SpritesFs` (remote container) or a custom
72
+ * Docker/E2B adapter instead.
73
+ */
369
74
  declare class LocalFs implements VirtualFs {
370
75
  private basePath;
371
76
  constructor(opts?: LocalFsOptions);
372
77
  private resolve;
373
78
  readFile(filePath: string, opts?: ReadOptions): Promise<string>;
79
+ readFileBytes(filePath: string, maxBytes?: number): Promise<Buffer>;
374
80
  writeFile(filePath: string, content: string): Promise<void>;
375
81
  appendFile(filePath: string, content: string): Promise<void>;
376
82
  deleteFile(filePath: string, opts?: {
@@ -390,6 +96,13 @@ interface LocalComputerOptions {
390
96
  defaultCwd?: string;
391
97
  defaultTimeout?: number;
392
98
  }
99
+ /**
100
+ * Unsandboxed VirtualComputer that runs commands directly on the host via
101
+ * `node:child_process`. Suitable for local development and trusted
102
+ * environments. For production or untrusted agents, use a sandboxed
103
+ * implementation like `SpritesComputer` (remote container) or a custom
104
+ * Docker/E2B adapter instead.
105
+ */
393
106
  declare class LocalComputer implements VirtualComputer {
394
107
  private defaultCwd;
395
108
  private defaultTimeout;
@@ -407,6 +120,13 @@ interface SpritesFsOptions {
407
120
  /** Working directory inside the sprite (default: /home/sprite) */
408
121
  workingDir?: string;
409
122
  }
123
+ /**
124
+ * Sandboxed VirtualFs backed by a remote sprites.dev container. All file
125
+ * operations are executed over the sprites.dev HTTP API — the agent has no
126
+ * access to the host filesystem. This is the recommended VirtualFs for
127
+ * production deployments and untrusted agents. See `LocalFs` for an
128
+ * unsandboxed local alternative.
129
+ */
410
130
  declare class SpritesFs implements VirtualFs {
411
131
  private token;
412
132
  private spriteName;
@@ -417,6 +137,7 @@ declare class SpritesFs implements VirtualFs {
417
137
  private resolvePath;
418
138
  private headers;
419
139
  readFile(filePath: string, _opts?: ReadOptions): Promise<string>;
140
+ readFileBytes(filePath: string, maxBytes?: number): Promise<Buffer>;
420
141
  writeFile(filePath: string, content: string): Promise<void>;
421
142
  appendFile(filePath: string, content: string): Promise<void>;
422
143
  deleteFile(filePath: string, opts?: {
@@ -443,12 +164,16 @@ interface SpritesComputerOptions {
443
164
  workingDir?: string;
444
165
  }
445
166
  /**
446
- * Executes commands inside a sprites.dev container via the exec REST endpoint.
167
+ * Sandboxed VirtualComputer that executes commands inside a remote
168
+ * sprites.dev container. All shell execution is fully isolated — the agent
169
+ * has no access to the host machine's processes, filesystem, or network.
170
+ *
171
+ * This is the recommended VirtualComputer for production deployments and
172
+ * untrusted agents. See `LocalComputer` for an unsandboxed local alternative.
447
173
  *
448
- * Uses the non-interactive exec mode: POST a command and get back
449
- * stdout/stderr/exit_code. For more complex use cases (streaming, TTY),
450
- * the WebSocket exec endpoint would be used, but for tool-call purposes
451
- * the REST endpoint is sufficient.
174
+ * Uses the non-interactive exec REST endpoint (POST command, receive
175
+ * stdout/stderr/exit_code). The WebSocket exec endpoint can be used for
176
+ * streaming/TTY use cases, but REST is sufficient for tool calls.
452
177
  */
453
178
  declare class SpritesComputer implements VirtualComputer {
454
179
  private token;
@@ -461,44 +186,105 @@ declare class SpritesComputer implements VirtualComputer {
461
186
  private shellEscape;
462
187
  }
463
188
 
464
- interface ToolResult {
465
- content: string;
466
- isError?: boolean;
467
- }
468
- interface ToolContext {
469
- fs: VirtualFs;
470
- computer: VirtualComputer;
471
- cwd: string;
472
- }
473
- interface ToolParameterProperty {
474
- type: string;
475
- description?: string;
476
- enum?: string[];
477
- default?: unknown;
478
- minimum?: number;
479
- maximum?: number;
480
- }
481
- interface ToolParameters {
482
- type: "object";
483
- properties: Record<string, ToolParameterProperty>;
484
- required?: string[];
485
- }
486
- interface Tool {
487
- name: string;
488
- description: string;
489
- parameters: ToolParameters;
490
- call(args: Record<string, unknown>, ctx: ToolContext): Promise<ToolResult>;
189
+ interface DockerFsOptions {
190
+ /** A dockerode Container instance for the target container. */
191
+ container: DockerContainer;
192
+ /** Working directory for relative path resolution (default: /). */
193
+ workingDir?: string;
194
+ }
195
+ /**
196
+ * VirtualFs backed by file operations inside a Docker container.
197
+ *
198
+ * Uses `container.exec()` to run filesystem commands (cat, tee, rm, mkdir,
199
+ * stat, etc.) inside the container. File writes use exec + tee to avoid
200
+ * tar archive overhead for text content.
201
+ *
202
+ * Requires `dockerode` as an optional peer dependency.
203
+ * The user is responsible for container lifecycle.
204
+ */
205
+ declare class DockerFs implements VirtualFs {
206
+ private container;
207
+ private workingDir;
208
+ constructor(opts: DockerFsOptions);
209
+ private resolvePath;
210
+ private exec;
211
+ readFile(path: string, _opts?: ReadOptions): Promise<string>;
212
+ readFileBytes(path: string, maxBytes?: number): Promise<Buffer>;
213
+ writeFile(path: string, content: string): Promise<void>;
214
+ appendFile(path: string, content: string): Promise<void>;
215
+ deleteFile(path: string, opts?: {
216
+ recursive?: boolean;
217
+ }): Promise<void>;
218
+ mkdir(path: string, opts?: {
219
+ recursive?: boolean;
220
+ }): Promise<void>;
221
+ readdir(path: string, _opts?: {
222
+ recursive?: boolean;
223
+ }): Promise<FileEntry[]>;
224
+ exists(path: string): Promise<boolean>;
225
+ stat(path: string): Promise<FileStat>;
226
+ }
227
+
228
+ interface E2BFsOptions {
229
+ /** An E2B Sandbox instance created via `Sandbox.create()`. */
230
+ sandbox: E2BSandboxInstance;
231
+ /** Working directory for relative path resolution. */
232
+ workingDir?: string;
233
+ }
234
+ /**
235
+ * VirtualFs backed by the E2B cloud sandbox filesystem.
236
+ *
237
+ * Requires `e2b` as an optional peer dependency.
238
+ * The user is responsible for sandbox lifecycle (create, close).
239
+ */
240
+ declare class E2BFs implements VirtualFs {
241
+ private sandbox;
242
+ private workingDir;
243
+ constructor(opts: E2BFsOptions);
244
+ private resolvePath;
245
+ readFile(path: string, _opts?: ReadOptions): Promise<string>;
246
+ readFileBytes(path: string, maxBytes?: number): Promise<Buffer>;
247
+ writeFile(path: string, content: string): Promise<void>;
248
+ appendFile(path: string, content: string): Promise<void>;
249
+ deleteFile(path: string, _opts?: {
250
+ recursive?: boolean;
251
+ }): Promise<void>;
252
+ mkdir(path: string, _opts?: {
253
+ recursive?: boolean;
254
+ }): Promise<void>;
255
+ readdir(path: string, _opts?: {
256
+ recursive?: boolean;
257
+ }): Promise<FileEntry[]>;
258
+ exists(path: string): Promise<boolean>;
259
+ stat(path: string): Promise<FileStat>;
491
260
  }
492
261
 
262
+ /**
263
+ * Resolve a tool flag that can be a static boolean or a function of the input.
264
+ * Returns `defaultValue` when the flag is `undefined`.
265
+ */
266
+ declare function resolveToolFlag(flag: boolean | ((args: Record<string, unknown>) => boolean) | undefined, args: Record<string, unknown>, defaultValue?: boolean): boolean;
493
267
  declare class ToolRegistry {
494
268
  private tools;
269
+ private _discoveredTools;
270
+ private _toolSearchEnabled;
495
271
  constructor(additionalTools?: Tool[]);
272
+ enableToolSearch(): void;
273
+ register(tool: Tool): void;
496
274
  get(name: string): Tool | undefined;
497
- execute(name: string, args: Record<string, unknown>, ctx: ToolContext): Promise<{
498
- content: string;
499
- isError?: boolean;
500
- }>;
275
+ execute(name: string, args: Record<string, unknown>, ctx: ToolContext): Promise<ToolResult>;
501
276
  toToolDefinitions(): ToolDefinition[];
277
+ /**
278
+ * Get tool definitions filtered by tool search. Eager tools (always sent)
279
+ * plus any deferred tools the model has discovered via ToolSearch.
280
+ * Falls back to all tools when tool search is not enabled.
281
+ */
282
+ getActiveToolDefinitions(): ToolDefinition[];
283
+ getEagerTools(): Tool[];
284
+ getDeferredTools(): Tool[];
285
+ getToolsByNames(names: string[]): Tool[];
286
+ markDiscovered(names: string[]): void;
287
+ get discoveredTools(): ReadonlySet<string>;
502
288
  listTools(): Tool[];
503
289
  }
504
290
 
@@ -510,42 +296,1143 @@ declare const editFileTool: Tool;
510
296
 
511
297
  declare const bashTool: Tool;
512
298
 
299
+ /**
300
+ * Edit utilities: fuzzy matching and quote normalization.
301
+ *
302
+ * When the model produces an `old_string` with smart/curly quotes that
303
+ * don't literally match the file (or vice versa), these helpers find the
304
+ * actual on-disk string and rewrite the replacement to preserve the file's
305
+ * quote style.
306
+ */
307
+ /**
308
+ * Replace curly/smart quotes with their ASCII equivalents.
309
+ */
310
+ declare function normalizeQuotes(str: string): string;
311
+ /**
312
+ * Find the actual substring in `fileContent` that matches `searchString`,
313
+ * allowing for quote-normalization differences.
314
+ *
315
+ * Returns the literal bytes from the file that match (which may contain
316
+ * curly quotes even though `searchString` used straight quotes), or null
317
+ * if no match is found even after normalization.
318
+ */
319
+ declare function findActualString(fileContent: string, searchString: string): string | null;
320
+ /**
321
+ * Count occurrences of `needle` in `haystack` using the same fuzzy matching
322
+ * as `findActualString` — normalizes quotes before counting.
323
+ */
324
+ declare function countOccurrences(haystack: string, needle: string): number;
325
+ /**
326
+ * When the file uses curly quotes but the model provided straight quotes
327
+ * (or vice versa), rewrite `newString` to match the file's quote style.
328
+ *
329
+ * If `oldString === actualOldString`, no normalization happened and the
330
+ * replacement is returned unchanged.
331
+ */
332
+ declare function preserveQuoteStyle(oldString: string, actualOldString: string, newString: string): string;
333
+ /**
334
+ * Strip trailing whitespace (spaces/tabs) from each line, preserving
335
+ * the line-ending style (CRLF, LF, CR).
336
+ */
337
+ declare function stripTrailingWhitespace(str: string): string;
338
+
513
339
  declare const globTool: Tool;
514
340
 
515
341
  declare const grepTool: Tool;
516
342
 
517
343
  /**
518
- * Load skill definitions from SKILL.md files found at the given paths on the VirtualFs.
519
- * Each path can be a directory (scanned for SKILL.md files) or a direct file.
344
+ * Create a Skill tool that lets the model invoke skills by name.
345
+ * Skill content is expanded inline with $ARGUMENTS substitution.
520
346
  */
521
- declare function loadSkills(fs: VirtualFs, paths: string[]): Promise<SkillDefinition[]>;
347
+ declare function createSkillTool(getSkills: () => SkillDefinition[]): Tool;
522
348
 
523
- declare class SessionStorage {
524
- private fs;
525
- private sessionDir;
526
- constructor(fs: VirtualFs, sessionDir: string);
527
- private getTranscriptPath;
528
- ensureDir(): Promise<void>;
529
- appendEntry(sessionId: string, entry: Entry): Promise<void>;
530
- appendMessage(sessionId: string, message: ChatMessage, parentUuid?: UUID | null): Promise<UUID>;
531
- appendCompactBoundary(sessionId: string): Promise<UUID>;
532
- appendSummary(sessionId: string, summaryMessage: ChatMessage, parentUuid?: UUID | null): Promise<UUID>;
533
- loadMessages(sessionId: string): Promise<ChatMessage[]>;
534
- loadAllEntries(sessionId: string): Promise<Entry[]>;
535
- sessionExists(sessionId: string): Promise<boolean>;
536
- listSessions(): Promise<SessionInfo[]>;
349
+ declare const agentTool: Tool;
350
+
351
+ declare const webFetchTool: Tool;
352
+
353
+ declare const notebookEditTool: Tool;
354
+
355
+ type UserInputHandler = (question: string) => Promise<string>;
356
+ declare const askUserTool: Tool;
357
+
358
+ declare const TOOL_SEARCH_NAME = "ToolSearch";
359
+ /**
360
+ * Check if a tool should be deferred (requires ToolSearch to load).
361
+ *
362
+ * A tool is deferred if:
363
+ * - It has `shouldDefer: true`
364
+ * - It's an MCP tool (has `mcpInfo`) and doesn't have `alwaysLoad: true`
365
+ *
366
+ * A tool is never deferred if it has `alwaysLoad: true`, or if it IS
367
+ * the ToolSearch tool itself.
368
+ */
369
+ declare function isDeferredTool(tool: Tool): boolean;
370
+ /**
371
+ * Format a single deferred tool as a one-line reference for the system prompt.
372
+ */
373
+ declare function formatDeferredToolLine(tool: Tool): string;
374
+ /**
375
+ * Keyword search over tool names and descriptions.
376
+ */
377
+ declare function searchToolsWithKeywords(query: string, deferredTools: Tool[], allTools: Tool[], maxResults: number): string[];
378
+ /**
379
+ * Extended Tool interface with deferral properties.
380
+ */
381
+ interface ToolWithDeferral extends Tool {
382
+ shouldDefer?: boolean;
383
+ alwaysLoad?: boolean;
537
384
  }
385
+ /**
386
+ * Create the ToolSearch tool. Requires access to the tool registry for
387
+ * looking up deferred tools and their schemas.
388
+ */
389
+ declare function createToolSearchTool(getDeferredTools: () => Tool[], getAllTools: () => Tool[], getToolsByNames: (names: string[]) => Tool[], onDiscovered: (names: string[]) => void): Tool;
538
390
 
539
- interface CompactOptions {
540
- customInstructions?: string;
391
+ interface ToolCallExecResult {
392
+ toolCall: ToolCallContent;
393
+ parsedArgs: Record<string, unknown>;
394
+ result: ToolResult;
395
+ /** When true, the result came from a permission denial — not actual tool execution */
396
+ permissionDenied?: boolean;
541
397
  }
542
- declare function compactConversation(aiProvider: AIProvider, model: string, messages: ChatMessage[], storage: SessionStorage, sessionId: string, opts?: CompactOptions): Promise<ChatMessage[]>;
398
+ type ToolCallExecutor = (toolCall: ToolCallContent, parsedArgs: Record<string, unknown>) => Promise<ToolCallExecResult>;
399
+ interface Batch {
400
+ isConcurrencySafe: boolean;
401
+ items: Array<{
402
+ toolCall: ToolCallContent;
403
+ parsedArgs: Record<string, unknown>;
404
+ }>;
405
+ }
406
+ /**
407
+ * Partition tool calls into batches: consecutive concurrency-safe tools
408
+ * are grouped together; each non-safe tool gets its own batch.
409
+ */
410
+ declare function partitionToolCalls(toolCalls: ToolCallContent[], getTool: (name: string) => Tool | undefined): Batch[];
411
+ /**
412
+ * Execute tool calls with optimal concurrency: safe tools run in parallel,
413
+ * unsafe tools run one at a time.
414
+ */
415
+ declare function runToolsBatched(toolCalls: ToolCallContent[], getTool: (name: string) => Tool | undefined, executor: ToolCallExecutor, concurrencyCap?: number): AsyncGenerator<ToolCallExecResult, void>;
543
416
 
544
- declare function buildSystemPrompt(opts: {
545
- customPrompt?: string;
546
- skills?: SkillDefinition[];
547
- tools?: Tool[];
548
- date?: string;
549
- }): string;
417
+ interface StreamingExecResult {
418
+ toolCall: ToolCallContent;
419
+ parsedArgs: Record<string, unknown>;
420
+ result: ToolResult;
421
+ permissionDenied?: boolean;
422
+ preventContinuation?: boolean;
423
+ events: StreamEvent[];
424
+ }
425
+ type StreamingToolExecutorFn = (toolCall: ToolCallContent, parsedArgs: Record<string, unknown>) => Promise<{
426
+ result: ToolResult;
427
+ permissionDenied?: boolean;
428
+ preventContinuation?: boolean;
429
+ events: StreamEvent[];
430
+ }>;
431
+ /**
432
+ * Executes tools as they arrive during model streaming.
433
+ * Concurrency-safe tools run in parallel; unsafe tools wait for all prior
434
+ * executions to finish before starting.
435
+ */
436
+ declare class StreamingToolExecutor {
437
+ private readonly getTool;
438
+ private readonly executeFn;
439
+ private tools;
440
+ private progressResolve?;
441
+ constructor(getTool: (name: string) => Tool | undefined, executeFn: StreamingToolExecutorFn);
442
+ addTool(toolCall: ToolCallContent, parsedArgs: Record<string, unknown>): void;
443
+ private canExecute;
444
+ private processQueue;
445
+ private executeTool;
446
+ /**
447
+ * Synchronously yield any completed results (called during streaming).
448
+ * Preserves declaration order: stops before a non-safe executing tool.
449
+ */
450
+ getCompletedResults(): Generator<StreamingExecResult, void>;
451
+ /**
452
+ * Async drain: waits for all in-flight tools then yields remaining results.
453
+ */
454
+ getRemainingResults(): AsyncGenerator<StreamingExecResult, void>;
455
+ private hasUnfinished;
456
+ private hasExecuting;
457
+ private hasCompleted;
458
+ }
459
+
460
+ interface CommandClassification {
461
+ /** True when every sub-command in the pipeline is read-only. */
462
+ isReadOnly: boolean;
463
+ /** True when any sub-command matches a destructive pattern. */
464
+ isDestructive: boolean;
465
+ /** Human-readable explanation of the classification. */
466
+ reason?: string;
467
+ }
468
+ interface ShellSafetyConfig {
469
+ /** Extra commands to treat as read-only (merged with built-in list). */
470
+ extraReadOnlyCommands?: string[];
471
+ /** Extra regex patterns to treat as destructive. */
472
+ extraDestructivePatterns?: RegExp[];
473
+ }
474
+
475
+ /**
476
+ * Shell command safety classification.
477
+ *
478
+ * Classifies bash commands as read-only or potentially destructive so the
479
+ * permission pipeline can make informed decisions without explicit per-command
480
+ * rules.
481
+ */
482
+
483
+ declare function extractCommandName(command: string): string;
484
+ /**
485
+ * Classify a shell command (potentially compound with pipes/chains).
486
+ *
487
+ * - A compound command is read-only only if ALL sub-commands are read-only.
488
+ * - A compound command is destructive if ANY sub-command is destructive.
489
+ */
490
+ declare function classifyCommand(command: string, config?: ShellSafetyConfig): CommandClassification;
491
+
492
+ /**
493
+ * Git-specific safety checks.
494
+ *
495
+ * Detects bare repositories, git-internal path writes, and other
496
+ * attack vectors (e.g. hook injection via .git/hooks/). Adapted from
497
+ * claude-code's gitSafety.ts and git.ts.
498
+ */
499
+ /**
500
+ * Returns true if `path` targets a file inside `.git/` internals.
501
+ * Used to detect attempts to write hooks, alter config, etc.
502
+ */
503
+ declare function isGitInternalPath(path: string): boolean;
504
+ /**
505
+ * Heuristic: does `dirEntries` (a list of filenames/dirnames in a
506
+ * directory) look like a bare git repository?
507
+ *
508
+ * Returns true when all three markers (HEAD, objects/, refs/) are
509
+ * present *and* there is no `.git` entry (which would indicate a
510
+ * normal working tree).
511
+ */
512
+ declare function looksLikeBareRepo(dirEntries: string[]): boolean;
513
+ /**
514
+ * Check if a shell command targets git-internal paths for writes.
515
+ * Scans for redirect operators (`>`, `>>`, `tee`) whose target is
516
+ * inside `.git/`.
517
+ */
518
+ declare function commandWritesGitInternals(command: string): boolean;
519
+
520
+ /**
521
+ * Git operation tracking.
522
+ *
523
+ * Parses shell command + output to detect high-level git operations
524
+ * (commits, pushes, PR creation, merges, rebases). Adapted from
525
+ * claude-code's gitOperationTracking.ts.
526
+ */
527
+ type GitOperationType = "commit" | "push" | "pr_create" | "merge" | "rebase";
528
+ interface GitOperationEvent {
529
+ type: GitOperationType;
530
+ details: string;
531
+ }
532
+ /**
533
+ * Detect git operations from a command string and its stdout output.
534
+ * Returns an array of events (most commands produce 0 or 1).
535
+ * Only detects on success — caller should check exit code first.
536
+ */
537
+ declare function detectGitOperations(command: string, stdout: string): GitOperationEvent[];
538
+ /**
539
+ * Check if command output indicates a git index.lock error.
540
+ * This commonly occurs when another git process is running.
541
+ */
542
+ declare function hasGitIndexLockError(output: string): boolean;
543
+
544
+ declare const taskCreateTool: Tool;
545
+
546
+ declare const taskListTool: Tool;
547
+
548
+ declare const taskGetTool: Tool;
549
+
550
+ declare const taskUpdateTool: Tool;
551
+
552
+ declare const enterPlanModeTool: Tool;
553
+ declare const exitPlanModeTool: Tool;
554
+
555
+ declare const enterWorktreeTool: Tool;
556
+ declare const exitWorktreeTool: Tool;
557
+
558
+ interface WorktreeInfo {
559
+ path: string;
560
+ branch: string;
561
+ head?: string;
562
+ }
563
+ /**
564
+ * Find the git root directory from a given cwd.
565
+ */
566
+ declare function findGitRoot(computer: VirtualComputer, cwd: string): Promise<string | null>;
567
+ /**
568
+ * Create a git worktree at the given path with the given branch name.
569
+ */
570
+ declare function createWorktree(computer: VirtualComputer, repoRoot: string, worktreePath: string, branchName: string, baseBranch?: string): Promise<{
571
+ success: boolean;
572
+ error?: string;
573
+ }>;
574
+ /**
575
+ * Remove a git worktree.
576
+ */
577
+ declare function removeWorktree(computer: VirtualComputer, repoRoot: string, worktreePath: string, branchName?: string): Promise<{
578
+ success: boolean;
579
+ error?: string;
580
+ }>;
581
+ /**
582
+ * List existing git worktrees.
583
+ */
584
+ declare function listWorktrees(computer: VirtualComputer, cwd: string): Promise<WorktreeInfo[]>;
585
+ /**
586
+ * Check if a worktree has uncommitted changes or unpushed commits.
587
+ */
588
+ declare function getWorktreeChanges(computer: VirtualComputer, worktreePath: string): Promise<{
589
+ hasChanges: boolean;
590
+ uncommittedFiles: number;
591
+ unpushedCommits: number;
592
+ }>;
593
+ /**
594
+ * Sanitize a name for use as a worktree slug/branch name.
595
+ */
596
+ declare function sanitizeWorktreeSlug(name: string): string;
597
+
598
+ type SwarmMemberStatus = "pending" | "running" | "completed" | "failed" | "killed";
599
+ interface SwarmMemberConfig {
600
+ name: string;
601
+ prompt: string;
602
+ systemPrompt?: string;
603
+ allowedTools?: string[];
604
+ model?: string;
605
+ }
606
+ interface SwarmMember {
607
+ id: string;
608
+ name: string;
609
+ status: SwarmMemberStatus;
610
+ sessionId?: string;
611
+ result?: string;
612
+ error?: Error;
613
+ }
614
+ interface SwarmMessage {
615
+ from: string;
616
+ to: string;
617
+ content: string;
618
+ timestamp: string;
619
+ }
620
+ interface SwarmConfig {
621
+ /** Maximum number of concurrent members (default: 4). */
622
+ maxConcurrent?: number;
623
+ /**
624
+ * When a swarm member hits an 'ask' permission, forward to this handler.
625
+ * If not set, members use bypassPermissions mode.
626
+ */
627
+ permissionHandler?: PermissionHandler;
628
+ }
629
+ interface SwarmStatus {
630
+ members: SwarmMember[];
631
+ messages: SwarmMessage[];
632
+ }
633
+ interface SwarmEvents {
634
+ type: "swarm_member_start" | "swarm_member_complete" | "swarm_member_failed" | "swarm_message";
635
+ memberId: string;
636
+ memberName: string;
637
+ content?: string;
638
+ error?: Error;
639
+ }
640
+
641
+ /**
642
+ * Backend interface for executing swarm members.
643
+ * The in-process backend runs Thread instances concurrently.
644
+ * Custom backends can spawn external processes, containers, etc.
645
+ */
646
+ interface SwarmBackend {
647
+ spawn(config: SwarmMemberConfig, member: SwarmMember): AsyncGenerator<StreamEvent, string, unknown>;
648
+ kill(memberId: string): Promise<void>;
649
+ }
650
+
651
+ /**
652
+ * In-memory message queue for communication between swarm members.
653
+ */
654
+ declare class Mailbox {
655
+ private messages;
656
+ private listeners;
657
+ /**
658
+ * Send a message from one member to another.
659
+ */
660
+ send(from: string, to: string, content: string): void;
661
+ /**
662
+ * Broadcast a message to all members except the sender.
663
+ */
664
+ broadcast(from: string, content: string, memberNames: string[]): void;
665
+ /**
666
+ * Get all messages sent to a specific member.
667
+ */
668
+ getMessagesFor(memberName: string): SwarmMessage[];
669
+ /**
670
+ * Get all unread messages for a member since the last check.
671
+ */
672
+ getNewMessagesFor(memberName: string, since: string): SwarmMessage[];
673
+ /**
674
+ * Register a listener for incoming messages to a member.
675
+ */
676
+ onMessage(memberName: string, handler: (msg: SwarmMessage) => void): () => void;
677
+ /**
678
+ * Get all messages in the mailbox.
679
+ */
680
+ getAllMessages(): SwarmMessage[];
681
+ }
682
+
683
+ /**
684
+ * Orchestrates multiple agent threads running in parallel.
685
+ */
686
+ declare class SwarmManager {
687
+ private members;
688
+ private backend;
689
+ private mailbox;
690
+ private config;
691
+ private runningTasks;
692
+ private eventHandlers;
693
+ constructor(backend: SwarmBackend, config?: SwarmConfig);
694
+ /**
695
+ * Register a handler for swarm lifecycle events.
696
+ */
697
+ onEvent(handler: (event: SwarmEvents) => void): () => void;
698
+ private emit;
699
+ /**
700
+ * Spawn a new swarm member. Returns the member ID.
701
+ */
702
+ spawn(config: SwarmMemberConfig): Promise<string>;
703
+ private runMember;
704
+ /**
705
+ * Spawn multiple members concurrently. Returns their IDs.
706
+ */
707
+ spawnAll(configs: SwarmMemberConfig[]): Promise<string[]>;
708
+ /**
709
+ * Send a message between swarm members.
710
+ */
711
+ sendMessage(from: string, to: string, content: string): void;
712
+ /**
713
+ * Kill a running member.
714
+ */
715
+ kill(memberId: string): Promise<void>;
716
+ /**
717
+ * Wait for all running members to complete.
718
+ */
719
+ waitForAll(): Promise<void>;
720
+ /**
721
+ * Get current swarm status.
722
+ */
723
+ getStatus(): SwarmStatus;
724
+ /**
725
+ * Get a specific member.
726
+ */
727
+ getMember(id: string): SwarmMember | undefined;
728
+ /**
729
+ * Get the mailbox for direct access.
730
+ */
731
+ getMailbox(): Mailbox;
732
+ private getMemberName;
733
+ private waitForSlot;
734
+ }
735
+
736
+ /**
737
+ * In-process backend: runs each swarm member as a concurrent Thread.
738
+ */
739
+ declare class InProcessBackend implements SwarmBackend {
740
+ private threadConfig;
741
+ private abortControllers;
742
+ constructor(threadConfig: Omit<ThreadConfig, "systemPrompt" | "model">);
743
+ spawn(config: SwarmMemberConfig, member: SwarmMember): AsyncGenerator<StreamEvent, string, unknown>;
744
+ kill(memberId: string): Promise<void>;
745
+ }
746
+
747
+ /**
748
+ * Normalize content to a uniform ContentPart[] representation.
749
+ * Strings are wrapped as a single TextContent block.
750
+ */
751
+ declare function normalizeContent(content: string | ContentPart[]): ContentPart[];
752
+ /**
753
+ * Extract the text representation of content. Image blocks are omitted;
754
+ * only text parts are concatenated.
755
+ */
756
+ declare function contentToString(content: string | ContentPart[]): string;
757
+ /**
758
+ * Returns true if the content contains at least one image block.
759
+ */
760
+ declare function hasImageContent(content: string | ContentPart[]): boolean;
761
+ /**
762
+ * Strip image blocks from content, replacing them with a text placeholder.
763
+ * Returns a plain string when the result contains only text.
764
+ */
765
+ declare function stripImageContent(content: string | ContentPart[], placeholder?: string): string | ContentPart[];
766
+
767
+ /**
768
+ * Run multiple async generators concurrently up to a concurrency cap,
769
+ * yielding values as they become available. Generators beyond the cap
770
+ * are started as earlier ones finish.
771
+ */
772
+ declare function all<A>(generators: AsyncGenerator<A, void>[], concurrencyCap?: number): AsyncGenerator<A, void>;
773
+
774
+ /**
775
+ * Load skill definitions from SKILL.md files found at the given paths on the VirtualFs.
776
+ * Each path can be a directory (scanned for SKILL.md files) or a direct file.
777
+ */
778
+ declare function loadSkills(fs: VirtualFs, paths: string[]): Promise<SkillDefinition[]>;
779
+
780
+ interface FrontmatterData {
781
+ "allowed-tools"?: string | string[] | null;
782
+ description?: string | null;
783
+ paths?: string | string[] | null;
784
+ context?: "inline" | "fork" | null;
785
+ "argument-hint"?: string | null;
786
+ [key: string]: unknown;
787
+ }
788
+ interface ParsedFrontmatter {
789
+ frontmatter: FrontmatterData;
790
+ body: string;
791
+ }
792
+ /**
793
+ * Parse YAML frontmatter from markdown content.
794
+ * Returns the parsed frontmatter fields and the body after the closing ---.
795
+ * If no frontmatter is found, returns empty frontmatter and the full content as body.
796
+ */
797
+ declare function parseFrontmatter(content: string): ParsedFrontmatter;
798
+ /**
799
+ * Parse the allowed-tools field from frontmatter.
800
+ * Accepts a string (comma/space separated), string[], or null/undefined.
801
+ */
802
+ declare function parseAllowedTools(value: string | string[] | null | undefined): string[];
803
+ /**
804
+ * Parse the paths field from frontmatter into glob patterns.
805
+ */
806
+ declare function parsePaths(value: string | string[] | null | undefined): string[];
807
+
808
+ /**
809
+ * Check which skills should be activated based on file paths the agent touched.
810
+ * Skills with `globs` are conditional -- they only activate when a matching file is touched.
811
+ * Skills without `globs` are always active.
812
+ *
813
+ * Returns the names of newly-activated conditional skills.
814
+ */
815
+ declare function activateSkillsForPaths(allSkills: SkillDefinition[], filePaths: string[], cwd: string, alreadyActivated: Set<string>): string[];
816
+ /**
817
+ * Get all currently active skills: unconditional ones + activated conditional ones.
818
+ */
819
+ declare function getActiveSkills(allSkills: SkillDefinition[], activatedNames: Set<string>): SkillDefinition[];
820
+
821
+ interface CompactOptions {
822
+ customInstructions?: string;
823
+ /** Number of recent messages to keep uncompacted (default: 0 = summarize all). */
824
+ tailMessagesToKeep?: number;
825
+ /** Strip binary/image content from messages before sending to the summarizer. */
826
+ stripBinaryContent?: boolean;
827
+ /** Abort signal — if fired, the partial summary is discarded instead of persisted. */
828
+ signal?: AbortSignal;
829
+ }
830
+ declare function compactConversation(provider: AIProvider, model: string, messages: ChatMessage[], storage: SessionStorage, sessionId: string, opts?: CompactOptions): Promise<ChatMessage[]>;
831
+ /**
832
+ * Estimate the token savings from a potential compaction.
833
+ */
834
+ declare function estimateCompactionSavings(messages: ChatMessage[], tailMessagesToKeep: number): {
835
+ currentTokens: number;
836
+ estimatedAfter: number;
837
+ };
838
+
839
+ /**
840
+ * Model context window sizes and effective window calculations.
841
+ */
842
+ /**
843
+ * Register custom context window sizes for models not in the built-in table.
844
+ */
845
+ declare function registerContextWindows(windows: Record<string, number>): void;
846
+ /**
847
+ * Get the context window size for a model. Checks custom overrides first,
848
+ * then built-in table, then prefix-matches, then falls back to default.
849
+ */
850
+ declare function getContextWindowForModel(model: string): number;
851
+ /**
852
+ * Effective context window = total window minus space reserved for the
853
+ * model's output during a compaction/summary request.
854
+ */
855
+ declare function getEffectiveContextWindow(model: string, maxOutputTokens?: number): number;
856
+ /**
857
+ * Auto-compact threshold: effective window minus a buffer to ensure we
858
+ * compact before we're at the hard limit.
859
+ */
860
+ declare function getAutoCompactThreshold(model: string, maxOutputTokens?: number): number;
861
+
862
+ /**
863
+ * Rough token estimation: ~4 chars per token for English text.
864
+ */
865
+ declare function estimateTokens(text: string): number;
866
+ /**
867
+ * Estimate tokens across an array of messages (pure estimation, no API anchor).
868
+ */
869
+ declare function estimateMessagesTokens(messages: Array<{
870
+ role: string;
871
+ content: string | unknown;
872
+ }>): number;
873
+ /**
874
+ * Usage-grounded token counting. Uses the last API response's prompt_tokens
875
+ * as an anchor and only estimates delta messages added since.
876
+ *
877
+ * If no usage anchor is available, falls back to pure estimation.
878
+ */
879
+ declare function tokenCountWithEstimation(messages: ChatMessage[], lastUsage?: ChatCompletionUsage, anchorMessageIndex?: number): number;
880
+ /**
881
+ * Group messages into API-round groups. A new group starts when an
882
+ * assistant message follows a tool result (i.e. each model response
883
+ * round). This gives finer-grained groups than splitting on user
884
+ * messages, enabling PTL recovery in agentic sessions with many
885
+ * tool-use rounds under a single user prompt.
886
+ */
887
+ declare function groupMessagesByTurn(messages: ChatMessage[]): ChatMessage[][];
888
+ /**
889
+ * Drop the oldest turn groups until estimated tokens drop below `targetTokens`.
890
+ * Returns the trimmed message list. Used for prompt-too-long recovery.
891
+ */
892
+ declare function truncateHeadForPTLRetry(messages: ChatMessage[], targetTokens: number): ChatMessage[];
893
+
894
+ declare function buildSystemPrompt(opts: {
895
+ customPrompt?: string;
896
+ skills?: SkillDefinition[];
897
+ tools?: Tool[];
898
+ date?: string;
899
+ projectContext?: string;
900
+ memorySection?: string;
901
+ deferredTools?: {
902
+ name: string;
903
+ description: string;
904
+ }[];
905
+ }): string;
906
+
907
+ /**
908
+ * Load project context files from the hierarchical NOUMEN.md / CLAUDE.md
909
+ * convention. Returns files ordered lowest-to-highest priority:
910
+ * managed -> user -> project (root first, cwd last) -> local.
911
+ */
912
+ declare function loadProjectContext(fs: VirtualFs, config: ProjectContextConfig): Promise<ContextFile[]>;
913
+ /**
914
+ * Filter context files to only those whose globs match at least one
915
+ * of the given file paths. Files without globs (unconditional) always pass.
916
+ */
917
+ declare function filterActiveContextFiles(files: ContextFile[], touchedPaths: string[], cwd: string): ContextFile[];
918
+ /**
919
+ * Check which conditional context files are newly activated by the given
920
+ * touched paths. Returns the paths of newly activated files.
921
+ */
922
+ declare function activateContextForPaths(allFiles: ContextFile[], touchedPaths: string[], cwd: string, alreadyActivated: Set<string>): string[];
923
+
924
+ /**
925
+ * Format loaded context files into a system prompt section.
926
+ *
927
+ * Files are rendered in array order (lowest to highest priority).
928
+ * Included sub-files are inlined immediately after their parent.
929
+ */
930
+ declare function buildProjectContextSection(files: ContextFile[], filter?: ContextScope[]): string;
931
+
932
+ /**
933
+ * Check whether a tool name matches a rule's `toolName` field.
934
+ *
935
+ * Supports:
936
+ * - Exact match: `"Bash"` matches `"Bash"`
937
+ * - MCP server-level wildcard: rule `"mcp__myserver"` matches any tool
938
+ * on that server (e.g. `"mcp__myserver__sometool"`)
939
+ */
940
+ declare function toolMatchesRule(toolName: string, rule: PermissionRule, mcpInfo?: {
941
+ serverName: string;
942
+ toolName: string;
943
+ }): boolean;
944
+ /**
945
+ * Match a content string against a rule's `ruleContent`.
946
+ *
947
+ * Three match modes (following claude-code's bash/filesystem patterns):
948
+ * - **exact**: `ruleContent === content`
949
+ * - **prefix**: `ruleContent` ends with `:*` → prefix match
950
+ * - **glob**: `ruleContent` contains `*` or `**` → simple glob match
951
+ */
952
+ declare function contentMatchesRule(content: string, ruleContent: string): boolean;
953
+ /**
954
+ * Minimal glob matching for file-path rules.
955
+ *
956
+ * Supports `*` (any non-separator chars) and `**` (any chars including `/`).
957
+ * Anchored: the entire string must match.
958
+ */
959
+ declare function matchSimpleGlob(pattern: string, value: string): boolean;
960
+ /**
961
+ * Return all rules in `context` that match the given tool and behavior,
962
+ * optionally filtered by content.
963
+ */
964
+ declare function getMatchingRules(context: PermissionContext, toolName: string, behavior: PermissionBehavior, content?: string, mcpInfo?: {
965
+ serverName: string;
966
+ toolName: string;
967
+ }): PermissionRule[];
968
+ /**
969
+ * Check whether a file path falls within any of the configured working directories.
970
+ */
971
+ declare function isPathInWorkingDirectories(filePath: string, workingDirectories: string[]): boolean;
972
+
973
+ /**
974
+ * Resolve the permission decision for a tool invocation.
975
+ *
976
+ * Pipeline mirrors claude-code's `hasPermissionsToUseToolInner`:
977
+ * 1. Deny rules for the whole tool
978
+ * 2. Ask rules for the whole tool
979
+ * 3. Tool's own `checkPermissions` (if defined)
980
+ * 4. Mode-based bypass / enforcement
981
+ * 5. Content-specific allow rules
982
+ * 6. Fallback: passthrough → ask
983
+ */
984
+ interface ResolvePermissionOptions {
985
+ provider?: AIProvider;
986
+ model?: string;
987
+ recentMessages?: ChatMessage[];
988
+ autoModeConfig?: AutoModeConfig;
989
+ signal?: AbortSignal;
990
+ }
991
+ declare function resolvePermission(tool: Tool, input: Record<string, unknown>, ctx: ToolContext, permCtx: PermissionContext, opts?: ResolvePermissionOptions): Promise<PermissionDecision>;
992
+
993
+ /**
994
+ * Apply a permission update to an in-memory context.
995
+ * Returns the mutated context (same reference).
996
+ */
997
+ declare function applyPermissionUpdate(ctx: PermissionContext, update: PermissionUpdate): PermissionContext;
998
+ /**
999
+ * Apply multiple permission updates in order.
1000
+ */
1001
+ declare function applyPermissionUpdates(ctx: PermissionContext, updates: PermissionUpdate[]): PermissionContext;
1002
+
1003
+ interface DenialLimits {
1004
+ maxConsecutive: number;
1005
+ maxTotal: number;
1006
+ }
1007
+ interface DenialState {
1008
+ consecutiveDenials: number;
1009
+ totalDenials: number;
1010
+ }
1011
+ /**
1012
+ * Tracks permission denials and determines when limits are exceeded.
1013
+ * When limits are hit, the system should fall back to prompting or abort.
1014
+ */
1015
+ declare class DenialTracker {
1016
+ private state;
1017
+ private limits;
1018
+ constructor(limits?: Partial<DenialLimits>);
1019
+ recordDenial(): void;
1020
+ recordSuccess(): void;
1021
+ shouldFallback(): boolean;
1022
+ getState(): Readonly<DenialState>;
1023
+ reset(): void;
1024
+ }
1025
+
1026
+ interface ClassifierResult {
1027
+ shouldBlock: boolean;
1028
+ reason: string;
1029
+ }
1030
+ /**
1031
+ * Run a side-query to classify whether a tool call should be auto-approved.
1032
+ */
1033
+ declare function classifyPermission(toolName: string, args: Record<string, unknown>, recentMessages: ChatMessage[], provider: AIProvider, opts?: {
1034
+ classifierPrompt?: string;
1035
+ classifierModel?: string;
1036
+ model?: string;
1037
+ signal?: AbortSignal;
1038
+ }): Promise<ClassifierResult>;
1039
+
1040
+ /**
1041
+ * Default pricing table for common models. Keys are matched as substrings
1042
+ * against the model ID so versioned model strings (e.g. `claude-sonnet-4`)
1043
+ * resolve correctly.
1044
+ */
1045
+ declare const DEFAULT_PRICING: Record<string, ModelPricing>;
1046
+ /**
1047
+ * Find pricing for a model by checking if the model string contains any
1048
+ * known pricing key as a substring. More specific keys (longer) are
1049
+ * checked first to ensure e.g. "gpt-4o-mini" matches before "gpt-4o".
1050
+ */
1051
+ declare function findModelPricing(model: string, pricing: Record<string, ModelPricing>): ModelPricing | null;
1052
+ /**
1053
+ * Calculate USD cost for a usage record using the given pricing table.
1054
+ * Returns 0 if the model is not found in the pricing table and logs a
1055
+ * one-time warning per unknown model.
1056
+ */
1057
+ declare function calculateCost(model: string, usage: UsageRecord, pricing?: Record<string, ModelPricing>): number;
1058
+
1059
+ /**
1060
+ * Provider-agnostic error classification for retry decisions.
1061
+ * Extracts status codes and retry hints from common SDK error shapes
1062
+ * without depending on any specific provider's types.
1063
+ */
1064
+ interface ClassifiedError {
1065
+ originalError: unknown;
1066
+ message: string;
1067
+ status?: number;
1068
+ retryAfter?: string;
1069
+ isOverloaded: boolean;
1070
+ isContextOverflow: boolean;
1071
+ contextOverflowData?: {
1072
+ inputTokens: number;
1073
+ maxTokens: number;
1074
+ contextLimit: number;
1075
+ };
1076
+ }
1077
+ /**
1078
+ * Classify an unknown error into retry-relevant metadata.
1079
+ * Works across OpenAI, Anthropic, and Gemini SDK error shapes by
1080
+ * duck-typing common properties (`.status`, `.headers`, `.message`).
1081
+ */
1082
+ declare function classifyError(error: unknown): ClassifiedError;
1083
+ declare function isRetryable(classified: ClassifiedError, config: RetryConfig): boolean;
1084
+
1085
+ /**
1086
+ * Compute retry delay with exponential backoff and jitter.
1087
+ * If a Retry-After header value is provided (seconds), it takes precedence.
1088
+ * Ported from claude-code's getRetryDelay with the same formula.
1089
+ */
1090
+ declare function getRetryDelay(attempt: number, retryAfterHeader?: string | null, maxDelayMs?: number): number;
1091
+
1092
+ declare class CannotRetryError extends Error {
1093
+ readonly originalError: unknown;
1094
+ readonly retryContext: RetryContext;
1095
+ constructor(originalError: unknown, retryContext: RetryContext);
1096
+ }
1097
+ declare class FallbackTriggeredError extends Error {
1098
+ readonly originalModel: string;
1099
+ readonly fallbackModel: string;
1100
+ constructor(originalModel: string, fallbackModel: string);
1101
+ }
1102
+ /**
1103
+ * Retry engine that wraps a stream-creating operation.
1104
+ * Yields retry_attempt events while waiting, then returns the stream on success.
1105
+ *
1106
+ * The operation receives a RetryContext that may include a maxTokensOverride
1107
+ * (after context overflow) or a different model (after fallback).
1108
+ */
1109
+ declare function withRetry(operation: (ctx: RetryContext) => AsyncIterable<ChatStreamChunk>, options: RetryEngineOptions): AsyncGenerator<StreamEvent, AsyncIterable<ChatStreamChunk>>;
1110
+
1111
+ /**
1112
+ * Run pre-tool-use hooks. Returns a merged output where later hooks override
1113
+ * earlier ones. A 'deny' decision from any hook short-circuits.
1114
+ */
1115
+ declare function runPreToolUseHooks(hooks: HookDefinition[], input: PreToolUseHookInput): Promise<PreToolUseHookOutput>;
1116
+ /**
1117
+ * Run post-tool-use hooks. Returns merged output.
1118
+ */
1119
+ declare function runPostToolUseHooks(hooks: HookDefinition[], input: PostToolUseHookInput): Promise<PostToolUseHookOutput>;
1120
+ /**
1121
+ * Run post-tool-use-failure hooks. Same shape as post-tool-use hooks but
1122
+ * triggers on the PostToolUseFailure event, fired only when `isError` is true.
1123
+ */
1124
+ declare function runPostToolUseFailureHooks(hooks: HookDefinition[], input: PostToolUseFailureHookInput): Promise<PostToolUseFailureHookOutput>;
1125
+ /**
1126
+ * Run notification hooks concurrently (fire-and-forget, no return value).
1127
+ */
1128
+ declare function runNotificationHooks(hooks: HookDefinition[], event: HookEvent, input: HookInput): Promise<void>;
1129
+
1130
+ declare class NoopSpan implements Span {
1131
+ readonly name: string;
1132
+ constructor(name: string);
1133
+ setAttribute(_key: string, _value: SpanAttributeValue): void;
1134
+ addEvent(_name: string, _attributes?: Record<string, SpanAttributeValue>): void;
1135
+ setStatus(_code: SpanStatusCode, _message?: string): void;
1136
+ end(): void;
1137
+ }
1138
+ declare class NoopTracer implements Tracer {
1139
+ startSpan(name: string, _options?: SpanOptions): Span;
1140
+ }
1141
+
1142
+ /**
1143
+ * Adapter that bridges noumen's `Tracer` interface to an OpenTelemetry
1144
+ * `TracerProvider`. The `@opentelemetry/api` package is loaded lazily via
1145
+ * dynamic `import()` so it remains an optional peer dependency.
1146
+ *
1147
+ * Call `OTelTracer.create()` (async factory) to obtain an instance.
1148
+ * If `@opentelemetry/api` is not installed, the factory returns a `NoopTracer`.
1149
+ */
1150
+ declare class OTelTracer implements Tracer {
1151
+ private otelTracer;
1152
+ private api;
1153
+ private constructor();
1154
+ /**
1155
+ * Create an `OTelTracer`. Falls back to `NoopTracer` if
1156
+ * `@opentelemetry/api` is not available at runtime.
1157
+ */
1158
+ static create(serviceName?: string, version?: string): Promise<Tracer>;
1159
+ startSpan(name: string, options?: SpanOptions): Span;
1160
+ }
1161
+
1162
+ interface IndexTruncation {
1163
+ content: string;
1164
+ lineCount: number;
1165
+ byteCount: number;
1166
+ wasLineTruncated: boolean;
1167
+ wasByteTruncated: boolean;
1168
+ }
1169
+ declare function truncateIndex(raw: string, maxLines?: number, maxBytes?: number): IndexTruncation;
1170
+ /**
1171
+ * Default `MemoryProvider` that stores memories as individual `.md` files
1172
+ * with YAML frontmatter, plus a `MEMORY.md` index. All I/O goes through
1173
+ * `VirtualFs` so it works with any sandbox backend.
1174
+ */
1175
+ declare class FileMemoryProvider implements MemoryProvider {
1176
+ private fs;
1177
+ private dir;
1178
+ private maxIndexLines;
1179
+ constructor(fs: VirtualFs, memoryDir: string, maxIndexLines?: number);
1180
+ private indexPath;
1181
+ private ensureDir;
1182
+ loadIndex(): Promise<string>;
1183
+ loadEntry(path: string): Promise<MemoryEntry | null>;
1184
+ saveEntry(entry: MemoryEntry): Promise<void>;
1185
+ removeEntry(path: string): Promise<void>;
1186
+ listEntries(): Promise<MemoryEntry[]>;
1187
+ search(query: string): Promise<MemoryEntry[]>;
1188
+ private rebuildIndex;
1189
+ }
1190
+
1191
+ /**
1192
+ * Prompt helpers for the memory system.
1193
+ *
1194
+ * `buildMemorySystemPromptSection` generates the instruction block injected
1195
+ * into the system prompt that teaches the model about the four-type memory
1196
+ * taxonomy and how to read/write memories.
1197
+ *
1198
+ * `buildExtractionPrompt` generates the user message sent to the LLM when
1199
+ * auto-extracting memories from a completed conversation turn.
1200
+ *
1201
+ * Both are adapted from claude-code's memdir/memoryTypes prompt helpers,
1202
+ * stripped of analytics, team memory, and Anthropic-specific concerns.
1203
+ */
1204
+ /**
1205
+ * Build the system-prompt section that teaches the model about its persistent
1206
+ * memory directory.
1207
+ *
1208
+ * @param indexContent - The current contents of MEMORY.md (may be empty).
1209
+ * @param memoryDir - Absolute path to the memory directory.
1210
+ */
1211
+ declare function buildMemorySystemPromptSection(indexContent: string, memoryDir: string): string;
1212
+ /**
1213
+ * Build the prompt sent to the LLM to extract durable memories from a
1214
+ * conversation. The response should be a JSON object with a `memories` array.
1215
+ */
1216
+ declare function buildExtractionPrompt(conversationSummary: string, existingIndex: string): string;
1217
+
1218
+ interface ExtractMemoriesResult {
1219
+ created: MemoryEntry[];
1220
+ updated: MemoryEntry[];
1221
+ deleted: string[];
1222
+ }
1223
+ /**
1224
+ * Extract durable memories from a conversation by making a single
1225
+ * structured-output LLM call. Applies the returned actions to the
1226
+ * `MemoryProvider` and returns a summary of changes.
1227
+ */
1228
+ declare function extractMemories(llmProvider: AIProvider, model: string, messages: ChatMessage[], provider: MemoryProvider): Promise<ExtractMemoriesResult>;
1229
+
1230
+ /**
1231
+ * Cache-safe parameters for subagent prompt cache sharing.
1232
+ *
1233
+ * When a subagent (fork) shares the same system prompt, model, tools, and
1234
+ * thinking config as its parent, both can share the same prompt cache
1235
+ * prefix. CacheSafeParams captures these values so the child thread can
1236
+ * inherit them and avoid cache breaks.
1237
+ */
1238
+
1239
+ interface CacheSafeParams {
1240
+ systemPrompt: string;
1241
+ model: string;
1242
+ tools: ToolDefinition[];
1243
+ thinking?: ThinkingConfig;
1244
+ }
1245
+ declare function saveCacheSafeParams(params: CacheSafeParams | null, sessionId?: string): void;
1246
+ declare function getLastCacheSafeParams(sessionId?: string): CacheSafeParams | null;
1247
+ declare function createCacheSafeParams(opts: {
1248
+ systemPrompt: string;
1249
+ model: string;
1250
+ tools: ToolDefinition[];
1251
+ thinking?: ThinkingConfig;
1252
+ }): CacheSafeParams;
1253
+
1254
+ /**
1255
+ * Conversation recovery and message sanitization.
1256
+ *
1257
+ * Cleans up persisted messages before resuming a session so the API
1258
+ * receives a structurally valid conversation. Handles crashes, streaming
1259
+ * interruptions, orphaned tool calls, and whitespace-only messages.
1260
+ */
1261
+
1262
+ type TurnInterruption = {
1263
+ kind: "none";
1264
+ } | {
1265
+ kind: "interrupted_tool";
1266
+ } | {
1267
+ kind: "interrupted_prompt";
1268
+ };
1269
+ interface SanitizeResult {
1270
+ messages: ChatMessage[];
1271
+ interruption: TurnInterruption;
1272
+ /** Number of messages removed by each filter (for diagnostics). */
1273
+ removals: {
1274
+ unresolvedToolUses: number;
1275
+ whitespaceOnly: number;
1276
+ orphanedThinking: number;
1277
+ };
1278
+ }
1279
+ /**
1280
+ * Drop assistant messages where *every* tool_call has no matching tool
1281
+ * result message. Keeps assistants that have at least one resolved call
1282
+ * or no tool_calls at all.
1283
+ */
1284
+ declare function filterUnresolvedToolUses(messages: ChatMessage[]): {
1285
+ messages: ChatMessage[];
1286
+ removed: number;
1287
+ };
1288
+ /**
1289
+ * Drop assistant messages that are whitespace-only text with no
1290
+ * tool_calls (API-invalid). After removal, merge consecutive user
1291
+ * messages to restore role alternation.
1292
+ */
1293
+ declare function filterWhitespaceOnlyAssistantMessages(messages: ChatMessage[]): {
1294
+ messages: ChatMessage[];
1295
+ removed: number;
1296
+ };
1297
+ /**
1298
+ * Drop assistant messages that contain only thinking content (no
1299
+ * real text and no tool_calls). These are artifacts of streaming
1300
+ * interruptions where a thinking block was streamed but the model
1301
+ * never produced a real response.
1302
+ *
1303
+ * In noumen's format, thinking content appears as `content: null`
1304
+ * with no tool_calls (the thinking deltas were streamed separately).
1305
+ * We detect these as assistants with null/empty content and no calls.
1306
+ */
1307
+ declare function filterOrphanedThinkingMessages(messages: ChatMessage[]): {
1308
+ messages: ChatMessage[];
1309
+ removed: number;
1310
+ };
1311
+ /**
1312
+ * Detect whether the conversation was interrupted mid-turn.
1313
+ *
1314
+ * Walks backward from the end skipping system messages to find the
1315
+ * last significant message. Returns `interrupted_tool` when the last
1316
+ * message is a tool result (agent got results but model never replied),
1317
+ * `interrupted_prompt` when the last message is a user prompt (model
1318
+ * never started), or `none` otherwise.
1319
+ */
1320
+ declare function detectTurnInterruption(messages: ChatMessage[]): TurnInterruption;
1321
+ /**
1322
+ * Run the full sanitization pipeline on a set of persisted messages.
1323
+ *
1324
+ * Order matters:
1325
+ * 1. Remove unresolved tool uses (structural — fixes orphan tool_calls)
1326
+ * 2. Remove orphaned thinking messages (streaming artifacts)
1327
+ * 3. Remove whitespace-only assistants (API validity)
1328
+ * 4. Detect turn interruption (must happen last, on clean messages)
1329
+ */
1330
+ declare function sanitizeForResume(messages: ChatMessage[]): SanitizeResult;
1331
+ /**
1332
+ * Generate synthetic tool result messages for tool_calls in an
1333
+ * assistant message that have no matching result yet. Used to
1334
+ * prevent orphaned tool_calls from corrupting the conversation
1335
+ * when streaming is interrupted or provider errors occur.
1336
+ */
1337
+ declare function generateMissingToolResults(assistantMsg: AssistantMessage, existingResults: ChatMessage[], reason: string): ToolResultMessage[];
1338
+
1339
+ /**
1340
+ * Session resume / restore.
1341
+ *
1342
+ * Parses a persisted JSONL session and extracts everything needed to
1343
+ * reconstruct thread state: messages (respecting compact boundaries),
1344
+ * file checkpoint snapshots, metadata, and tool result overflow entries.
1345
+ */
1346
+
1347
+ interface ResumePayload {
1348
+ messages: ChatMessage[];
1349
+ checkpointSnapshots: FileCheckpointSnapshot[];
1350
+ metadata: Record<string, unknown>;
1351
+ costState?: StoredCostState;
1352
+ overflowEntries: ToolResultOverflowEntry[];
1353
+ /** Persisted content replacement records for disk-spilled tool results. */
1354
+ contentReplacements: ContentReplacementRecord[];
1355
+ /** Detected turn interruption state after sanitization. */
1356
+ interruption: TurnInterruption;
1357
+ /** Number of messages removed per sanitization filter. */
1358
+ recoveryRemovals: {
1359
+ unresolvedToolUses: number;
1360
+ whitespaceOnly: number;
1361
+ orphanedThinking: number;
1362
+ };
1363
+ }
1364
+ /**
1365
+ * Restore a session from its persisted JSONL transcript.
1366
+ *
1367
+ * Returns everything needed to reconstruct Thread state:
1368
+ * - Messages after the last compact boundary
1369
+ * - File checkpoint snapshot chain
1370
+ * - Session metadata (title, custom keys)
1371
+ * - Tool result overflow entries
1372
+ */
1373
+ declare function restoreSession(storage: SessionStorage, sessionId: string): Promise<ResumePayload>;
1374
+
1375
+ declare const STRUCTURED_OUTPUT_TOOL_NAME = "StructuredOutput";
1376
+ /**
1377
+ * Creates a synthetic tool whose input schema matches the user's desired
1378
+ * output schema. When the model calls this tool, the agent loop treats it
1379
+ * as the final structured response and terminates.
1380
+ *
1381
+ * This is the "final_response" pattern: the model reasons freely (using
1382
+ * tools), and signals completion by calling StructuredOutput with data
1383
+ * that conforms to the schema.
1384
+ */
1385
+ declare function createStructuredOutputTool(format: JsonSchemaOutputFormat): Tool;
1386
+
1387
+ /**
1388
+ * Image resize / compress pipeline.
1389
+ *
1390
+ * Ported from claude-code's imageResizer.ts. Uses `sharp` (optional peer
1391
+ * dependency) for dimension caps, iterative quality reduction, and API
1392
+ * base64 size guards. Gracefully degrades when sharp is not installed.
1393
+ */
1394
+ /** Maximum base64-encoded image size (API enforced by most providers). */
1395
+ declare const API_IMAGE_MAX_BASE64_SIZE: number;
1396
+ declare const IMAGE_MAX_WIDTH = 8000;
1397
+ declare const IMAGE_MAX_HEIGHT = 8000;
1398
+ interface ImageDimensions {
1399
+ width: number;
1400
+ height: number;
1401
+ }
1402
+ interface ResizedImage {
1403
+ buffer: Buffer;
1404
+ mediaType: string;
1405
+ dimensions?: ImageDimensions;
1406
+ }
1407
+ interface CompressedImageResult {
1408
+ base64: string;
1409
+ mediaType: string;
1410
+ }
1411
+ /**
1412
+ * Resize and downsample an image buffer if it exceeds dimension or size
1413
+ * limits. Returns the (possibly unchanged) buffer with mediaType info.
1414
+ */
1415
+ declare function maybeResizeAndDownsampleImageBuffer(imageBuffer: Buffer, originalSize: number, ext: string): Promise<ResizedImage>;
1416
+ /**
1417
+ * Decode base64 image block, resize, re-encode.
1418
+ */
1419
+ declare function maybeResizeAndDownsampleImageBlock(imageBlock: {
1420
+ data: string;
1421
+ media_type: string;
1422
+ }): Promise<{
1423
+ data: string;
1424
+ media_type: string;
1425
+ dimensions?: ImageDimensions;
1426
+ }>;
1427
+ /**
1428
+ * Compress an image to fit within a token budget.
1429
+ * Token formula: tokens ≈ base64_chars × 0.125
1430
+ */
1431
+ declare function compressImageBufferWithTokenLimit(imageBuffer: Buffer, maxTokens: number, originalMediaType?: string): Promise<CompressedImageResult>;
1432
+ declare const IMAGE_EXTENSIONS: Set<string>;
1433
+ /**
1434
+ * Create dimension metadata text for the model (helps with coordinate reasoning).
1435
+ */
1436
+ declare function createImageMetadataText(dims: ImageDimensions): string;
550
1437
 
551
- export { type AIProvider, AnthropicProvider, type AnthropicProviderOptions, type AssistantMessage, type AutoCompactConfig, type ChatCompletionUsage, type ChatMessage, type ChatParams, type ChatStreamChoice, type ChatStreamChunk, type ChatStreamDelta, Code, type CodeOptions, type CommandResult, type CompactBoundaryEntry, type CustomTitleEntry, type Entry, type ExecOptions, type FileEntry, type FileStat, GeminiProvider, type GeminiProviderOptions, LocalComputer, type LocalComputerOptions, LocalFs, type LocalFsOptions, type MessageEntry, type MetadataEntry, OpenAIProvider, type OpenAIProviderOptions, type ReadOptions, type RunOptions, type SerializedMessage, type SessionInfo, type SkillDefinition, SpritesComputer, type SpritesComputerOptions, SpritesFs, type SpritesFsOptions, type StreamEvent, type SummaryEntry, type SystemMessage, Thread, type ThreadConfig, type ThreadOptions, type Tool, type ToolCallContent, type ToolResult as ToolCallResult, type ToolContext, type ToolParameterProperty$1 as ToolDefParameterProperty, type ToolDefinition, type ToolParameters, ToolRegistry, type ToolResult$1 as ToolResult, type ToolResultMessage, type UserMessage, type VirtualComputer, type VirtualFs, bashTool, buildSystemPrompt, compactConversation, createAutoCompactConfig, editFileTool, globTool, grepTool, loadSkills, readFileTool, shouldAutoCompact, writeFileTool };
1438
+ export { AIProvider, API_IMAGE_MAX_BASE64_SIZE, Agent, AssistantMessage, AutoModeConfig, type CacheSafeParams, CannotRetryError, ChatCompletionUsage, ChatMessage, ChatStreamChunk, type ClassifiedError, type ClassifierResult, type CommandClassification, CommandResult, type CompactOptions, type CompressedImageResult, ContentPart, ContentReplacementRecord, ContextFile, ContextScope, DEFAULT_PRICING, type DenialLimits, type DenialState, DenialTracker, DockerContainer, DockerFs, type DockerFsOptions, E2BFs, type E2BFsOptions, E2BSandboxInstance, ExecOptions, type ExtractMemoriesResult, FallbackTriggeredError, FileCheckpointSnapshot, FileEntry, FileMemoryProvider, FileStat, type FrontmatterData, type GitOperationEvent, type GitOperationType, HookDefinition, HookEvent, HookInput, IMAGE_EXTENSIONS, IMAGE_MAX_HEIGHT, IMAGE_MAX_WIDTH, type ImageDimensions, InProcessBackend, type IndexTruncation, JsonSchemaOutputFormat, LocalComputer, type LocalComputerOptions, LocalFs, type LocalFsOptions, Mailbox, McpServerConfig, MemoryEntry, MemoryProvider, ModelPricing, NoopSpan, NoopTracer, OTelTracer, type OllamaProviderOptions, type ParsedFrontmatter, PermissionBehavior, PermissionContext, PermissionDecision, PermissionHandler, PermissionRule, PermissionUpdate, PostToolUseFailureHookInput, PostToolUseFailureHookOutput, PostToolUseHookInput, PostToolUseHookOutput, PreToolUseHookInput, PreToolUseHookOutput, type PresetOptions, ProjectContextConfig, ReadOptions, type ResizedImage, type ResolvePermissionOptions, type ResumePayload, RetryConfig, RetryContext, RetryEngineOptions, STRUCTURED_OUTPUT_TOOL_NAME, Sandbox, type SanitizeResult, type ShellSafetyConfig, SkillDefinition, Span, SpanAttributeValue, SpanOptions, SpanStatusCode, SpritesComputer, type SpritesComputerOptions, SpritesFs, type SpritesFsOptions, StoredCostState, StreamEvent, type StreamingExecResult, StreamingToolExecutor, type StreamingToolExecutorFn, type SwarmBackend, type SwarmConfig, type SwarmEvents, SwarmManager, type SwarmMember, type SwarmMemberConfig, type SwarmMemberStatus, type SwarmMessage, type SwarmStatus, TOOL_SEARCH_NAME, ThinkingConfig, ThreadConfig, Tool, ToolCallContent, type ToolCallExecResult, type ToolCallExecutor, ToolResult as ToolCallResult, ToolContext, ToolDefinition, ToolRegistry, ToolResultMessage, ToolResultOverflowEntry, type ToolWithDeferral, Tracer, type TurnInterruption, UsageRecord, type UserInputHandler, VirtualComputer, VirtualFs, type WorktreeInfo, activateContextForPaths, activateSkillsForPaths, agentTool, all, applyPermissionUpdate, applyPermissionUpdates, askUserTool, bashTool, buildExtractionPrompt, buildMemorySystemPromptSection, buildProjectContextSection, buildSystemPrompt, calculateCost, classifyCommand, classifyError, classifyPermission, codingAgent, commandWritesGitInternals, compactConversation, compressImageBufferWithTokenLimit, contentMatchesRule, contentToString, countOccurrences, createCacheSafeParams, createImageMetadataText, createSkillTool, createStructuredOutputTool, createToolSearchTool, createWorktree, detectGitOperations, detectTurnInterruption, editFileTool, enterPlanModeTool, enterWorktreeTool, estimateCompactionSavings, estimateMessagesTokens, estimateTokens, exitPlanModeTool, exitWorktreeTool, extractCommandName, extractMemories, filterActiveContextFiles, filterOrphanedThinkingMessages, filterUnresolvedToolUses, filterWhitespaceOnlyAssistantMessages, findActualString, findGitRoot, findModelPricing, formatDeferredToolLine, generateMissingToolResults, getActiveSkills, getAutoCompactThreshold, getContextWindowForModel, getEffectiveContextWindow, getLastCacheSafeParams, getMatchingRules, getRetryDelay, getWorktreeChanges, globTool, grepTool, groupMessagesByTurn, hasGitIndexLockError, hasImageContent, isDeferredTool, isGitInternalPath, isPathInWorkingDirectories, isRetryable, listWorktrees, loadProjectContext, loadSkills, looksLikeBareRepo, matchSimpleGlob, maybeResizeAndDownsampleImageBlock, maybeResizeAndDownsampleImageBuffer, normalizeContent, normalizeQuotes, notebookEditTool, parseAllowedTools, parseFrontmatter, parsePaths, partitionToolCalls, planningAgent, preserveQuoteStyle, readFileTool, registerContextWindows, removeWorktree, resolvePermission, resolveToolFlag, restoreSession, reviewAgent, runNotificationHooks, runPostToolUseFailureHooks, runPostToolUseHooks, runPreToolUseHooks, runToolsBatched, sanitizeForResume, sanitizeWorktreeSlug, saveCacheSafeParams, searchToolsWithKeywords, stripImageContent, stripTrailingWhitespace, taskCreateTool, taskGetTool, taskListTool, taskUpdateTool, tokenCountWithEstimation, toolMatchesRule, truncateHeadForPTLRetry, truncateIndex, webFetchTool, withRetry, writeFileTool };