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