@standardagents/builder 0.15.3 → 0.17.0-next.a4b7340

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 (38) hide show
  1. package/dist/built-in-routes.js +362 -281
  2. package/dist/built-in-routes.js.map +1 -1
  3. package/dist/client/ApiKeysView.js +1 -1
  4. package/dist/client/CenteredContentView.js +1 -1
  5. package/dist/client/CompositionView.js +1 -1
  6. package/dist/client/ConfirmDialog.vue_vue_type_script_setup_true_lang.js +1 -1
  7. package/dist/client/CopyButton.vue_vue_type_script_setup_true_lang.js +1 -1
  8. package/dist/client/DataTable.vue_vue_type_script_setup_true_lang.js +1 -1
  9. package/dist/client/JsonViewer.js +1 -1
  10. package/dist/client/LoginView.js +1 -1
  11. package/dist/client/Modal.vue_vue_type_script_setup_true_lang.js +1 -1
  12. package/dist/client/ModelModal.vue_vue_type_script_setup_true_lang.js +1 -1
  13. package/dist/client/ModelsView.js +1 -1
  14. package/dist/client/PromptEditView.js +1 -1
  15. package/dist/client/PromptModal.js +1 -1
  16. package/dist/client/PromptsView.js +1 -1
  17. package/dist/client/ProvidersView.js +2 -2
  18. package/dist/client/ThreadInspectorPane.vue_vue_type_script_setup_true_lang.js +1 -1
  19. package/dist/client/ToolsView.js +1 -1
  20. package/dist/client/UsersView.js +1 -1
  21. package/dist/client/VariablesView.js +1 -1
  22. package/dist/client/assets/index.css +1 -1
  23. package/dist/client/index.js +3 -3
  24. package/dist/{discovery-DVviz3By.d.ts → discovery-DiMJWisl.d.ts} +1 -1
  25. package/dist/{index-BwqQtJ4r.d.ts → index-EaxysUHv.d.ts} +2 -5
  26. package/dist/index.d.ts +116 -3402
  27. package/dist/index.js +190 -324
  28. package/dist/index.js.map +1 -1
  29. package/dist/packing.d.ts +3 -3
  30. package/dist/plugin.d.ts +5 -4
  31. package/dist/plugin.js +143 -78
  32. package/dist/plugin.js.map +1 -1
  33. package/dist/runtime.d.ts +3124 -0
  34. package/dist/runtime.js +21218 -0
  35. package/dist/runtime.js.map +1 -0
  36. package/dist/test.d.ts +2 -2
  37. package/dist/{types-DH3Egc5l.d.ts → types-Bpe7IANZ.d.ts} +1 -1
  38. package/package.json +10 -9
@@ -0,0 +1,3124 @@
1
+ import { e as ThreadEnv, h as ThreadMetadata, M as Message, l as FileRecord, F as FlowState, n as FileStats, G as GrepResult, m as AttachmentRef, r as MessageContent, E as Env, g as ThreadInstance } from './index-EaxysUHv.js';
2
+ export { A as Agent, f as BuilderThreadEndpointHandler, B as Controller, a as ControllerContext, j as FlowResult, p as ImageContentPart, I as ImageMetadata, L as LLMResponse, q as MultimodalContent, R as RequestContext, S as StorageBackend, k as TelemetryEvent, o as TextContentPart, b as ThreadEndpointContext, T as ToolCall, i as ToolResult, c as createThreadEndpointHandler, d as defineController } from './index-EaxysUHv.js';
3
+ import { CodeExecutionOptions, CodeExecutionResult, SubagentRegistryEntry, InjectMessageInput, QueueMessageInput, ModelDefinition as ModelDefinition$1, ToolArgs, PromptTextPart, PromptEnvPart, VariableDefinition, SubpromptConfig as SubpromptConfig$1, PromptToolConfig as PromptToolConfig$1, SubagentToolConfig as SubagentToolConfig$1, ReasoningConfig, SideConfig as SideConfig$1, LLMProviderInterface, ContentPart, TextPart, ImagePart, FilePart, NamespaceContext, DefinitionLoader } from '@standardagents/spec';
4
+ export { AgentType, DefinitionLoader, GlobalNamespaceContext, HookSignatures, ImageContent, ModelCapabilities, ModelProvider, NamespaceContext, PackageSignature, PackedExports, PackedMeta, PackedMetadata, PackedNamespaceContext, PromptInput, PromptTextPart, ProviderAssistantMessage, ProviderError, ProviderErrorCode, ProviderFactory, ProviderFactoryConfig, ProviderFinishReason, ProviderGeneratedImage, ProviderMessage, ProviderMessageContent, ModelCapabilities as ProviderModelCapabilities, ProviderReasoningDetail, ProviderRequest, ProviderResponse, ProviderStreamChunk, ProviderSystemMessage, ProviderTool, ProviderToolCallPart, ProviderToolMessage, ProviderToolResultContent, ProviderUsage, ProviderUserMessage, ReasoningConfig, StructuredPrompt, TextContent, Tool, ToolArgs, ToolArgsNode, ToolArgsRawShape, ToolContent, belongsToPackage, defineAgent, defineHook, defineModel, definePrompt, defineTool, isPacked, isVisibleInNamespace, mapReasoningLevel } from '@standardagents/spec';
5
+ import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';
6
+ import { N as NamespacedRegistry } from './types-Bpe7IANZ.js';
7
+ import '@cloudflare/workers-types';
8
+ import 'zod';
9
+
10
+ /**
11
+ * Global namespace for AgentBuilder types.
12
+ *
13
+ * This namespace provides type-safe references for models, prompts, agents, and tools.
14
+ * Types are automatically populated when you run `pnpm dev` or `pnpm build`,
15
+ * which scans your `agentbuilder/` directories and generates types.
16
+ *
17
+ * The generated types are placed in `.agents/types.d.ts` and augment the
18
+ * StandardAgentSpec namespace from @standardagents/spec.
19
+ *
20
+ * Note: This namespace is provided for backward compatibility. New code should
21
+ * use StandardAgentSpec types directly, which are defined in @standardagents/spec.
22
+ *
23
+ * @deprecated Use StandardAgentSpec namespace from @standardagents/spec instead
24
+ */
25
+ declare global {
26
+ namespace AgentBuilder {
27
+ /**
28
+ * Interface for model type registration.
29
+ * @deprecated Use StandardAgentSpec.ModelRegistry instead
30
+ */
31
+ interface ModelRegistry extends StandardAgentSpec.ModelRegistry {
32
+ }
33
+ /**
34
+ * Interface for prompt type registration.
35
+ * @deprecated Use StandardAgentSpec.PromptRegistry instead
36
+ */
37
+ interface PromptRegistry extends StandardAgentSpec.PromptRegistry {
38
+ }
39
+ /**
40
+ * Interface for agent type registration.
41
+ * @deprecated Use StandardAgentSpec.AgentRegistry instead
42
+ */
43
+ interface AgentRegistry extends StandardAgentSpec.AgentRegistry {
44
+ }
45
+ /**
46
+ * Interface for tool type registration.
47
+ * @deprecated Use StandardAgentSpec.ToolRegistry instead
48
+ */
49
+ interface ToolRegistry extends StandardAgentSpec.ToolRegistry {
50
+ }
51
+ /**
52
+ * Interface for callable type registration (prompts, agents, tools).
53
+ * @deprecated Use StandardAgentSpec.CallableRegistry instead
54
+ */
55
+ interface CallableRegistry extends StandardAgentSpec.CallableRegistry {
56
+ }
57
+ /**
58
+ * Union type of all model names defined in agentbuilder/models/.
59
+ * @deprecated Use StandardAgentSpec.Models instead
60
+ */
61
+ type Models = StandardAgentSpec.Models;
62
+ /**
63
+ * Union type of all prompt names defined in agentbuilder/prompts/.
64
+ * @deprecated Use StandardAgentSpec.Prompts instead
65
+ */
66
+ type Prompts = StandardAgentSpec.Prompts;
67
+ /**
68
+ * Union type of all agent names defined in agentbuilder/agents/.
69
+ * @deprecated Use StandardAgentSpec.Agents instead
70
+ */
71
+ type Agents = StandardAgentSpec.Agents;
72
+ /**
73
+ * Union type of all tool names defined in agentbuilder/tools/.
74
+ * @deprecated Use StandardAgentSpec.Tools instead
75
+ */
76
+ type Tools = StandardAgentSpec.Tools;
77
+ /**
78
+ * Union type of all callable items (prompts, agents, tools) that can be used as tools.
79
+ * @deprecated Use StandardAgentSpec.Callables instead
80
+ */
81
+ type Callables = StandardAgentSpec.Callables;
82
+ /**
83
+ * Interface for hook ID registration.
84
+ * @deprecated Use StandardAgentSpec.HookIdRegistry instead
85
+ */
86
+ interface HookIdRegistry extends StandardAgentSpec.HookIdRegistry {
87
+ }
88
+ /**
89
+ * Union type of all hook IDs defined in agents/hooks/.
90
+ * @deprecated Use StandardAgentSpec.HookIds instead
91
+ */
92
+ type Hooks = StandardAgentSpec.HookIds;
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Authentication middleware for protecting API routes
98
+ *
99
+ * Supports multiple authentication types:
100
+ * - Super admin token (signed with ENCRYPTION_KEY)
101
+ * - User session token (validated against DurableAgentBuilder)
102
+ * - API key (validated against DurableAgentBuilder)
103
+ */
104
+ interface AuthUser {
105
+ id: string;
106
+ username: string;
107
+ role: string;
108
+ }
109
+ interface AuthContext {
110
+ user: AuthUser;
111
+ authType: 'super_admin' | 'session' | 'api_key';
112
+ }
113
+ /**
114
+ * Authenticate a request using various token types
115
+ */
116
+ declare function authenticate(request: Request, env: any): Promise<AuthContext | null>;
117
+ /**
118
+ * Middleware to require authentication
119
+ * Returns 401 if not authenticated
120
+ */
121
+ declare function requireAuth(request: Request, env: any): Promise<AuthContext | Response>;
122
+ /**
123
+ * Middleware to require admin role
124
+ * Returns 401 if not authenticated, 403 if not admin
125
+ */
126
+ declare function requireAdmin(request: Request, env: any): Promise<AuthContext | Response>;
127
+
128
+ type AlarmQueueStatus = "pending" | "processing" | "completed" | "failed" | "agent_canceled" | "user_canceled";
129
+ type EffectCancelSource = "agent" | "user";
130
+ interface EffectRunRecord {
131
+ id: string;
132
+ name: string;
133
+ args: Record<string, unknown>;
134
+ scheduledAt: number;
135
+ createdAt: number;
136
+ status: AlarmQueueStatus;
137
+ attempts: number;
138
+ error: string | null;
139
+ completedAt: number | null;
140
+ manualRun: boolean;
141
+ manualRunAt: number | null;
142
+ replayedFrom: string | null;
143
+ }
144
+ interface EffectRunListOptions {
145
+ limit?: number;
146
+ offset?: number;
147
+ }
148
+ interface EffectRunListResult {
149
+ effects: EffectRunRecord[];
150
+ total: number;
151
+ upcomingCount: number;
152
+ limit: number;
153
+ offset: number;
154
+ }
155
+ interface EffectRunActionResult {
156
+ action: "ran" | "replayed";
157
+ id: string;
158
+ replayedId?: string;
159
+ }
160
+
161
+ interface CodeExecutionBridgeRegistration {
162
+ call(functionId: string, encodedArgs: unknown[]): Promise<unknown>;
163
+ }
164
+
165
+ type ThreadEndpointCodeOptions = Pick<CodeExecutionOptions, "language" | "filename" | "execute" | "modules" | "memoryLimitBytes">;
166
+ declare class DurableThread<Env extends ThreadEnv = ThreadEnv> extends DurableObject<Env> {
167
+ private migratedToVersion;
168
+ private logSockets;
169
+ private messageSockets;
170
+ private alarmQueue;
171
+ private alarmQueueRearmed;
172
+ private currentAbortController;
173
+ private isExecuting;
174
+ private codeExecutionBridges;
175
+ constructor(ctx: DurableObjectState, env: Env);
176
+ /**
177
+ * Returns the tools registry for this thread.
178
+ * This method is implemented when you import DurableThread from 'virtual:@standardagents/builder'.
179
+ *
180
+ * @throws Error if not implemented in a subclass
181
+ * @returns Record of tool name to tool loader function
182
+ *
183
+ * @example
184
+ * ```typescript
185
+ * import { DurableThread } from 'virtual:@standardagents/builder'
186
+ *
187
+ * export class Thread extends DurableThread {}
188
+ * ```
189
+ */
190
+ tools(): Record<string, () => Promise<any>>;
191
+ /**
192
+ * Returns the hooks registry for this thread.
193
+ * This method is implemented when you import DurableThread from 'virtual:@standardagents/builder'.
194
+ *
195
+ * @throws Error if not implemented in a subclass
196
+ * @returns Record of hook name to hook loader function
197
+ *
198
+ * @example
199
+ * ```typescript
200
+ * import { DurableThread } from 'virtual:@standardagents/builder'
201
+ *
202
+ * export class Thread extends DurableThread {}
203
+ * ```
204
+ */
205
+ hooks(): Record<string, () => Promise<any>>;
206
+ /**
207
+ * Returns the models registry for lazy-loading model definitions.
208
+ * This method is implemented when you import DurableThread from 'virtual:@standardagents/builder'.
209
+ *
210
+ * @throws Error if not implemented in a subclass
211
+ * @returns Record of model name to model loader function
212
+ */
213
+ models(): Record<string, () => Promise<any>>;
214
+ /**
215
+ * Returns the prompts registry for lazy-loading prompt definitions.
216
+ * This method is implemented when you import DurableThread from 'virtual:@standardagents/builder'.
217
+ *
218
+ * @throws Error if not implemented in a subclass
219
+ * @returns Record of prompt name to prompt loader function
220
+ */
221
+ prompts(): Record<string, () => Promise<any>>;
222
+ /**
223
+ * Returns the agents registry for lazy-loading agent definitions.
224
+ * This method is implemented when you import DurableThread from 'virtual:@standardagents/builder'.
225
+ *
226
+ * @throws Error if not implemented in a subclass
227
+ * @returns Record of agent name to agent loader function
228
+ */
229
+ agents(): Record<string, () => Promise<any>>;
230
+ /**
231
+ * Returns the effects registry for lazy-loading effect definitions.
232
+ * This method is implemented when you import DurableThread from 'virtual:@standardagents/builder'.
233
+ *
234
+ * Effects are scheduled operations that run outside the tool execution context,
235
+ * ideal for delayed notifications, webhooks, and cleanup tasks.
236
+ *
237
+ * @throws Error if not implemented in a subclass
238
+ * @returns Record of effect name to effect loader function
239
+ */
240
+ effects(): Record<string, () => Promise<any>>;
241
+ /**
242
+ * Returns the namespaced registry for packed agent support.
243
+ * This method is implemented when you import DurableThread from 'virtual:@standardagents/builder'.
244
+ *
245
+ * @throws Error if not implemented in a subclass
246
+ * @returns The namespaced registry with global and packages namespaces
247
+ */
248
+ registry(): any;
249
+ /**
250
+ * Load a model definition by name.
251
+ * Supports both global models and packed models (e.g., "packageId/modelName").
252
+ * For scoped packages, use "@scope/pkg/modelName".
253
+ * For packed context, tries package first then falls back to global.
254
+ */
255
+ loadModel(name: string): Promise<any>;
256
+ /**
257
+ * List available model names.
258
+ */
259
+ getModelNames(): string[];
260
+ /**
261
+ * Load a prompt definition by name.
262
+ * Supports both global prompts (e.g., "my-prompt") and packed prompts (e.g., "packageId/promptName").
263
+ */
264
+ loadPrompt(name: string): Promise<any>;
265
+ /**
266
+ * List available prompt names.
267
+ */
268
+ getPromptNames(): string[];
269
+ /**
270
+ * Load an agent definition by name.
271
+ * Supports both global agents (e.g., "my-agent") and packed agents (e.g., "packageId/agentName").
272
+ * For scoped packages, use "@scope/pkg/agentName".
273
+ */
274
+ loadAgent(name: string): Promise<any>;
275
+ /**
276
+ * List available agent names.
277
+ */
278
+ getAgentNames(): string[];
279
+ /**
280
+ * Load an effect definition by name.
281
+ */
282
+ loadEffect(name: string): Promise<any>;
283
+ /**
284
+ * List available effect names.
285
+ */
286
+ getEffectNames(): string[];
287
+ /**
288
+ * Load a tool definition by name.
289
+ * Supports both global tools (e.g., "my_tool") and packed tools (e.g., "packageId/toolName").
290
+ */
291
+ loadTool(name: string): Promise<any>;
292
+ /**
293
+ * Get thread metadata from DurableAgentBuilder.
294
+ * Used for creating ThreadState outside of flow execution.
295
+ */
296
+ getThreadMetadata(threadId: string): Promise<ThreadMetadata>;
297
+ /**
298
+ * Execute sandboxed code for a thread endpoint from inside the thread DO.
299
+ *
300
+ * Thread endpoint handlers often start in the top-level Worker with only a
301
+ * Durable Object stub. Code execution must originate here so the dynamic
302
+ * worker can use this DO's env, ctx exports, and bridge registration map.
303
+ */
304
+ executeThreadEndpointCode(threadId: string, source: string, options: ThreadEndpointCodeOptions): Promise<CodeExecutionResult>;
305
+ /**
306
+ * Execute ThreadState.runCode for endpoint handlers that only have a
307
+ * Durable Object stub. The actual Dynamic Worker must be started inside this
308
+ * DurableThread so it has access to env, ctx exports, and bridge callbacks.
309
+ */
310
+ executeThreadStateRunCode(threadId: string, source: string, options?: CodeExecutionOptions, wantsReport?: boolean): Promise<CodeExecutionResult>;
311
+ /**
312
+ * Read a JSON value from this thread's durable key-value store.
313
+ */
314
+ getValue<T = unknown>(key: string): Promise<T | null>;
315
+ /**
316
+ * Write a JSON value to this thread's durable key-value store.
317
+ *
318
+ * Per the Standard Agents spec, null and undefined delete the key.
319
+ */
320
+ setValue(key: string, value: unknown): Promise<void>;
321
+ listValues(options?: {
322
+ search?: string | null;
323
+ limit?: number;
324
+ offset?: number;
325
+ }): Promise<{
326
+ values: Array<{
327
+ key: string;
328
+ value: unknown;
329
+ serialized: string;
330
+ size: number;
331
+ updatedAt: number;
332
+ parseError?: string;
333
+ }>;
334
+ total: number;
335
+ limit: number;
336
+ offset: number;
337
+ search: string | null;
338
+ }>;
339
+ private assertValidThreadValueKey;
340
+ private escapeThreadValueLike;
341
+ private serializeThreadValue;
342
+ private assertJsonSerializableThreadValue;
343
+ /**
344
+ * Trigger an agent to run on this thread.
345
+ *
346
+ * Queues an agent execution via the alarm queue. The execution
347
+ * runs asynchronously in the background.
348
+ *
349
+ * @param threadId - Thread ID for the execution
350
+ * @param agentName - Name of the agent to run
351
+ */
352
+ runAgent(threadId: string, agentName: string): Promise<void>;
353
+ /**
354
+ * Get the persisted resumable-subagent registry for this thread.
355
+ */
356
+ getChildrenRegistry(_threadId: string): Promise<SubagentRegistryEntry[]>;
357
+ private setChildrenRegistry;
358
+ upsertChildRegistry(_threadId: string, entry: SubagentRegistryEntry): Promise<void>;
359
+ updateChildRegistryStatus(_threadId: string, reference: string, status: string): Promise<void>;
360
+ removeChildRegistry(_threadId: string, reference: string): Promise<void>;
361
+ private asOptionalString;
362
+ private asOptionalBoolean;
363
+ private getThreadNameFromTags;
364
+ private toSubagentProjection;
365
+ private resolveSubagentMessageProjections;
366
+ /**
367
+ * Inject a top-level message without starting a new execution.
368
+ *
369
+ * This path is used by effects and thread endpoints, which run without a
370
+ * FlowState but still need to write visible messages to the thread.
371
+ */
372
+ injectMessage(threadId: string, message: InjectMessageInput): Promise<Message>;
373
+ /**
374
+ * Queue a message for deferred delivery.
375
+ */
376
+ queueMessage(threadId: string, message: QueueMessageInput): Promise<void>;
377
+ private hasPendingTurnAlarm;
378
+ private ensureQueuedMessageExecution;
379
+ private ensureRootMessageId;
380
+ /**
381
+ * Soft-terminate this thread.
382
+ */
383
+ terminateThread(threadId: string): Promise<{
384
+ success: boolean;
385
+ terminated: number;
386
+ }>;
387
+ /**
388
+ * Schedule an effect for future execution.
389
+ *
390
+ * @param threadId - Thread ID for the effect execution context
391
+ * @param effectName - Name of the effect to schedule
392
+ * @param effectArgs - Arguments to pass to the effect handler
393
+ * @param delayMs - Delay in milliseconds before execution (default: 0)
394
+ * @returns UUID of the scheduled effect
395
+ */
396
+ scheduleEffect(threadId: string, effectName: string, effectArgs: Record<string, unknown>, delayMs?: number, options?: {
397
+ sourceLogId?: string | null;
398
+ }): Promise<string>;
399
+ /**
400
+ * Check whether an effect loader exists in either global or packed registries.
401
+ */
402
+ private effectExists;
403
+ /**
404
+ * Get scheduled effects for this thread.
405
+ *
406
+ * @param name - Optional effect name to filter by
407
+ * @returns Array of scheduled effect records
408
+ */
409
+ getScheduledEffects(name?: string): Promise<Array<{
410
+ id: string;
411
+ name: string;
412
+ args: Record<string, unknown>;
413
+ scheduledAt: number;
414
+ createdAt: number;
415
+ }>>;
416
+ /**
417
+ * List pending and historical effect runs for the AgentBuilder UI.
418
+ */
419
+ listEffectRuns(options?: EffectRunListOptions): Promise<EffectRunListResult>;
420
+ /**
421
+ * Run a pending effect now, or replay a historical effect immediately.
422
+ */
423
+ runEffectNow(effectRunId: string): Promise<EffectRunActionResult>;
424
+ /**
425
+ * Cancel a scheduled effect and keep it in history.
426
+ *
427
+ * @param id - The effect ID returned by scheduleEffect
428
+ * @returns true if the effect was found and canceled, false otherwise
429
+ */
430
+ removeScheduledEffect(id: string, canceledBy?: EffectCancelSource): Promise<boolean>;
431
+ /**
432
+ * Ensures the database schema is up to date.
433
+ * This method is called on the first request to the Durable Object.
434
+ * It checks the schema version and runs any pending migrations.
435
+ *
436
+ * Performance:
437
+ * - Already migrated to latest: ~0.1ms (single SELECT + integer comparison)
438
+ * - Needs migration: Runs once per Durable Object lifetime per schema version
439
+ * - Detects new migrations after code deployment
440
+ */
441
+ private ensureMigrated;
442
+ /**
443
+ * Gets the current schema version from the database.
444
+ * Returns 0 if the metadata table doesn't exist (brand new database).
445
+ */
446
+ private getCurrentVersion;
447
+ /**
448
+ * Runs all pending migrations sequentially.
449
+ * Each migration is run in order, starting from the current version + 1.
450
+ */
451
+ private runMigrations;
452
+ /**
453
+ * Legacy fetch handler for WebSocket upgrades only
454
+ */
455
+ fetch(request: Request): Promise<Response>;
456
+ registerCodeExecutionBridge(runId: string, bridge: CodeExecutionBridgeRegistration): void;
457
+ unregisterCodeExecutionBridge(runId: string): void;
458
+ callCodeExecutionBridge(runId: string, functionId: string, encodedArgs: unknown[]): Promise<unknown>;
459
+ /**
460
+ * Execute thread with initial messages (RPC method)
461
+ * Enqueues the execution to be processed by the alarm handler
462
+ */
463
+ execute(threadId: string, agentId: string, initial_messages?: any[], data?: any): Promise<Response>;
464
+ /**
465
+ * Execute a flow synchronously and return the final top-level message content.
466
+ * Used by blocking subagent tool calls.
467
+ */
468
+ executeBlocking(threadId: string, agentId: string, initial_messages?: any[], data?: any): Promise<{
469
+ status: "success" | "error";
470
+ result?: string;
471
+ error?: string;
472
+ attachments?: unknown[];
473
+ terminal?: boolean;
474
+ }>;
475
+ /**
476
+ * Send a new message to the thread (RPC method)
477
+ * Enqueues the message processing to be handled by the alarm handler
478
+ */
479
+ sendMessage(threadId: string, content: string, role?: string, attachments?: string): Promise<Response>;
480
+ /**
481
+ * Check if execution should be stopped (called by FlowEngine)
482
+ * Reads from SQLite for persistence across hibernation
483
+ */
484
+ shouldStop(): Promise<boolean>;
485
+ /**
486
+ * Returns the termination timestamp (microseconds) or null when active.
487
+ */
488
+ getTerminated(_threadId: string): Promise<number | null>;
489
+ private assertNotTerminated;
490
+ private getLatestTopLevelMessage;
491
+ private getTerminalSessionToolNames;
492
+ private parseAttachmentRefsJson;
493
+ private deleteAttachmentRefsFromJson;
494
+ private cancelQueuedMessage;
495
+ private parseMessageMetadata;
496
+ private extractSubagentIdFromMetadata;
497
+ private getLatestTerminalSessionMessageAfter;
498
+ private inferMimeTypeFromPath;
499
+ private extensionForMimeType;
500
+ private sanitizeFilename;
501
+ private splitFilename;
502
+ private resolveAttachmentMimeType;
503
+ private buildAttachmentTargetPath;
504
+ private copyAttachmentRefsToThread;
505
+ private readAttachmentDataFromSource;
506
+ private arrayBufferToBase64;
507
+ private formatSubagentAttachmentPathSummary;
508
+ private persistParentHandoffStatusMessage;
509
+ private buildMissingTerminalSessionFailure;
510
+ private deliverCompletionToParentIfNeeded;
511
+ private getParentCommunicationModeForChild;
512
+ /**
513
+ * Stop the currently executing thread (RPC method)
514
+ * Simple "off" switch - stops turns, only cleared by user messages
515
+ */
516
+ stop(): Promise<Response>;
517
+ /**
518
+ * Continue execution from where it stopped (RPC method)
519
+ * Useful for debugging - continues the FlowEngine with additional steps
520
+ * without adding a new message.
521
+ *
522
+ * @param threadId The thread ID
523
+ * @param side Which side to start from ('a' or 'b'), defaults to 'a'
524
+ */
525
+ continueExecution(threadId: string, side?: 'a' | 'b'): Promise<Response>;
526
+ /**
527
+ * Get message history (RPC method)
528
+ *
529
+ * By default, returns the newest messages (when truncating), but in chronological
530
+ * order (oldest first in the array). This is ideal for chat UIs where messages
531
+ * should be appended and scrolled to the bottom.
532
+ *
533
+ * The offset parameter allows "scrolling up" to view older messages.
534
+ *
535
+ * Example:
536
+ * - getMessages(10, 0) -> newest 10 messages, oldest first in array
537
+ * - getMessages(10, 10) -> next 10 older messages, oldest first in array
538
+ *
539
+ * @param limit Number of messages to return (default: 100)
540
+ * @param offset Number of newest messages to skip (default: 0)
541
+ * @param order Internal query order - "DESC" (default) fetches newest first then reverses
542
+ * @param includeSilent Include silent messages (UI-only messages)
543
+ * @param maxDepth Maximum depth to include (default: 0 for top-level only)
544
+ */
545
+ getMessages(limit?: number, offset?: number, order?: "ASC" | "DESC", includeSilent?: boolean, maxDepth?: number): Promise<{
546
+ messages: {
547
+ id: string;
548
+ role: string;
549
+ content: string | null;
550
+ name: string | null;
551
+ tool_calls: string | null;
552
+ tool_call_id: string | null;
553
+ tool_status: "success" | "error" | null;
554
+ log_id: string | null;
555
+ created_at: number;
556
+ silent: boolean;
557
+ parent_id: string | null;
558
+ depth: number;
559
+ status: "pending" | "completed" | "failed" | null;
560
+ reasoning_content: string | null;
561
+ reasoning_details: string | null;
562
+ attachments: any;
563
+ metadata: Record<string, unknown> | undefined;
564
+ subagent_id: string | null;
565
+ }[];
566
+ total: number;
567
+ hasMore: boolean;
568
+ }>;
569
+ /**
570
+ * Get specific messages, optionally expanding any requested tool-call message
571
+ * to the full contiguous workblock it belongs to.
572
+ */
573
+ getMessagesByIds(ids: string[], includeSilent?: boolean, maxDepth?: number, includeWorkblocks?: boolean): Promise<{
574
+ messages: {
575
+ id: string;
576
+ role: string;
577
+ content: string | null;
578
+ name: string | null;
579
+ tool_calls: string | null;
580
+ tool_call_id: string | null;
581
+ tool_status: "success" | "error" | null;
582
+ log_id: string | null;
583
+ created_at: number;
584
+ silent: boolean;
585
+ parent_id: string | null;
586
+ depth: number;
587
+ status: "pending" | "completed" | "failed" | null;
588
+ reasoning_content: string | null;
589
+ reasoning_details: string | null;
590
+ attachments: any;
591
+ metadata: Record<string, unknown> | undefined;
592
+ subagent_id: string | null;
593
+ }[];
594
+ total: number;
595
+ hasMore: boolean;
596
+ }>;
597
+ /**
598
+ * Delete a message (RPC method)
599
+ * Also cleans up any attachment files stored on the thread filesystem
600
+ */
601
+ deleteMessage(messageId: string): Promise<{
602
+ success: boolean;
603
+ error?: undefined;
604
+ } | {
605
+ success: boolean;
606
+ error: any;
607
+ }>;
608
+ /**
609
+ * Update a message's content (RPC method)
610
+ */
611
+ updateMessageContent(messageId: string, content: string): Promise<{
612
+ success: boolean;
613
+ error?: undefined;
614
+ } | {
615
+ success: boolean;
616
+ error: any;
617
+ }>;
618
+ /**
619
+ * Seed messages directly into the database (RPC method - for testing)
620
+ * This bypasses the normal message processing flow
621
+ */
622
+ seedMessages(args: {
623
+ messages: Array<{
624
+ id: string;
625
+ role: string;
626
+ content: string;
627
+ created_at: number;
628
+ log_id?: string | null;
629
+ }>;
630
+ }): Promise<{
631
+ success: boolean;
632
+ count: number;
633
+ error?: undefined;
634
+ } | {
635
+ success: boolean;
636
+ error: any;
637
+ count?: undefined;
638
+ }>;
639
+ /**
640
+ * Seed a log directly into the database (RPC method - for testing)
641
+ * This bypasses the normal log creation flow
642
+ */
643
+ seedLog(args: {
644
+ id: string;
645
+ message_id: string;
646
+ provider: string;
647
+ model: string;
648
+ created_at: number;
649
+ is_complete?: boolean;
650
+ prompt_name?: string;
651
+ }): Promise<{
652
+ success: boolean;
653
+ id: string;
654
+ error?: undefined;
655
+ } | {
656
+ success: boolean;
657
+ error: any;
658
+ id?: undefined;
659
+ }>;
660
+ /**
661
+ * Get logs (RPC method)
662
+ */
663
+ getLogs(limit?: number, offset?: number, order?: "ASC" | "DESC"): Promise<{
664
+ logs: {
665
+ id: string;
666
+ message_id: string;
667
+ provider: string;
668
+ actual_provider: string | null;
669
+ standard_agents_router_used: boolean;
670
+ model: string;
671
+ model_name: string | null;
672
+ prompt_name: string | null;
673
+ tools_called: string | null;
674
+ queued_tools: string | null;
675
+ provider_tools: string | null;
676
+ parent_log_id: string | null;
677
+ retry_of_log_id: string | null;
678
+ error: string | null;
679
+ cost_total: number | null;
680
+ is_complete: boolean;
681
+ created_at: number;
682
+ request_body: string | null;
683
+ }[];
684
+ total: number;
685
+ hasMore: boolean;
686
+ }>;
687
+ /**
688
+ * Get specific logs, optionally including all descendant logs.
689
+ */
690
+ getLogsByIds(ids: string[], includeDescendants?: boolean, order?: "ASC" | "DESC"): Promise<{
691
+ logs: {
692
+ id: string;
693
+ message_id: string;
694
+ provider: string;
695
+ actual_provider: string | null;
696
+ model: string;
697
+ model_name: string | null;
698
+ prompt_name: string | null;
699
+ tools_called: string | null;
700
+ queued_tools: string | null;
701
+ provider_tools: string | null;
702
+ parent_log_id: string | null;
703
+ retry_of_log_id: string | null;
704
+ error: string | null;
705
+ cost_total: number | null;
706
+ is_complete: boolean;
707
+ created_at: number;
708
+ request_body: string | null;
709
+ }[];
710
+ total: number;
711
+ hasMore: boolean;
712
+ }>;
713
+ /**
714
+ * Get logs for specific messages, optionally expanding requested messages to
715
+ * the full contiguous workblock they belong to and including descendant logs.
716
+ */
717
+ getLogsByMessageIds(messageIds: string[], includeWorkblocks?: boolean, includeDescendants?: boolean, order?: "ASC" | "DESC"): Promise<{
718
+ logs: {
719
+ id: string;
720
+ message_id: string;
721
+ provider: string;
722
+ actual_provider: string | null;
723
+ model: string;
724
+ model_name: string | null;
725
+ prompt_name: string | null;
726
+ tools_called: string | null;
727
+ queued_tools: string | null;
728
+ provider_tools: string | null;
729
+ parent_log_id: string | null;
730
+ retry_of_log_id: string | null;
731
+ error: string | null;
732
+ cost_total: number | null;
733
+ is_complete: boolean;
734
+ created_at: number;
735
+ request_body: string | null;
736
+ }[];
737
+ total: number;
738
+ hasMore: boolean;
739
+ }>;
740
+ /**
741
+ * Get detailed information for a single log (RPC method)
742
+ * This includes all fields including large ones like request/response bodies
743
+ */
744
+ getLogDetails(logId: string): Promise<{
745
+ id: string;
746
+ message_id: string;
747
+ provider: string;
748
+ actual_provider: string | null;
749
+ standard_agents_router_used: boolean;
750
+ model: string;
751
+ model_name: string | null;
752
+ endpoint: string | null;
753
+ request_body: string | null;
754
+ request_headers: string | null;
755
+ response_body: string | null;
756
+ response_headers: string | null;
757
+ status_code: number | null;
758
+ reasoning_content: string | null;
759
+ input_tokens: number | null;
760
+ cached_tokens: number | null;
761
+ output_tokens: number | null;
762
+ reasoning_tokens: number | null;
763
+ total_tokens: number | null;
764
+ latency_ms: number | null;
765
+ time_to_first_token_ms: number | null;
766
+ finish_reason: string | null;
767
+ error: string | null;
768
+ error_type: string | null;
769
+ cost_input: number | null;
770
+ cost_output: number | null;
771
+ cost_total: number | null;
772
+ message_history_length: number | null;
773
+ tools_available: number | null;
774
+ prompt_name: string | null;
775
+ tools_called: string | null;
776
+ queued_tools: string | null;
777
+ provider_tools: string | null;
778
+ parent_log_id: string | null;
779
+ tools_schema: string | null;
780
+ message_history: string | null;
781
+ system_prompt: string | null;
782
+ errors: string | null;
783
+ retry_of_log_id: string | null;
784
+ tool_results: string | null;
785
+ is_complete: boolean;
786
+ created_at: number;
787
+ source_message_role: string | null;
788
+ source_message_content: string | null;
789
+ source_message_created_at: number | null;
790
+ source_message_metadata: string | null;
791
+ scheduled_effects: string;
792
+ } | null>;
793
+ /**
794
+ * Get thread metadata (RPC method)
795
+ */
796
+ getThreadMeta(threadId: string): Promise<Response | {
797
+ thread: {
798
+ id: any;
799
+ agent_id: any;
800
+ user_id: any;
801
+ tags: any;
802
+ parent: any;
803
+ terminated: any;
804
+ created_at: any;
805
+ };
806
+ agent: {
807
+ id: any;
808
+ title: any;
809
+ type: any;
810
+ description: any;
811
+ icon: any;
812
+ side_a_label: any;
813
+ side_b_label: any;
814
+ side_a_agent_prompt: string | null;
815
+ side_b_agent_prompt: string | null;
816
+ } | null;
817
+ stats: {
818
+ message_count: number;
819
+ log_count: number;
820
+ };
821
+ }>;
822
+ /**
823
+ * Update thread metadata (RPC method)
824
+ * Calls the DurableAgentBuilder to update the thread registry
825
+ */
826
+ updateThreadMeta(threadId: string, params: {
827
+ agent_name?: string;
828
+ user_id?: string | null;
829
+ tags?: string[] | null;
830
+ env?: Record<string, string> | null;
831
+ tenvs?: Record<string, unknown> | null;
832
+ }): Promise<{
833
+ success: boolean;
834
+ thread: {
835
+ id: any;
836
+ agent_id: any;
837
+ user_id: any;
838
+ tags: any;
839
+ created_at: any;
840
+ };
841
+ error?: undefined;
842
+ } | {
843
+ success: boolean;
844
+ error: any;
845
+ thread?: undefined;
846
+ }>;
847
+ /**
848
+ * Delete thread data completely (RPC method)
849
+ * This will permanently delete the Durable Object instance
850
+ */
851
+ deleteThread(): Promise<{
852
+ success: boolean;
853
+ message: string;
854
+ }>;
855
+ /**
856
+ * Handle WebSocket upgrade for real-time log streaming
857
+ * Uses Hibernation API to reduce costs during inactivity
858
+ */
859
+ private handleLogsWebSocketUpgrade;
860
+ /**
861
+ * Handle WebSocket upgrade for real-time message streaming
862
+ * Uses Hibernation API to reduce costs during inactivity
863
+ */
864
+ private handleMessagesWebSocketUpgrade;
865
+ /**
866
+ * Broadcast a log record to all connected WebSocket clients
867
+ */
868
+ private broadcastLog;
869
+ /**
870
+ * Broadcast a message record to all connected message WebSocket clients
871
+ * Filters silent messages based on each socket's includeSilent preference
872
+ */
873
+ private broadcastMessage;
874
+ private broadcastMessageWithSubagentProjection;
875
+ /**
876
+ * Broadcast a content chunk for real-time streaming
877
+ * Does NOT update database - only broadcasts to connected clients
878
+ */
879
+ private broadcastMessageChunk;
880
+ /**
881
+ * Broadcast a telemetry event to all connected message WebSocket clients
882
+ * Used for execution status updates (step_started, tool_started, etc.)
883
+ */
884
+ private broadcastTelemetry;
885
+ /**
886
+ * Broadcast a custom event to all connected message WebSocket clients
887
+ * Used by tools via emitThreadEvent() to send user-defined events
888
+ */
889
+ private broadcastEvent;
890
+ /**
891
+ * WebSocket Hibernation API handler for incoming messages
892
+ * Called when a message is received on a hibernated WebSocket
893
+ */
894
+ webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void>;
895
+ /**
896
+ * WebSocket Hibernation API handler for connection close
897
+ * Called when a WebSocket connection is closed
898
+ * Note: Do NOT call ws.close() here - the connection is already closed
899
+ */
900
+ webSocketClose(ws: WebSocket, _code: number, _reason: string, _wasClean: boolean): Promise<void>;
901
+ /**
902
+ * WebSocket Hibernation API handler for errors
903
+ * Called when a WebSocket encounters an error
904
+ */
905
+ webSocketError(ws: WebSocket, error: unknown): Promise<void>;
906
+ /**
907
+ * Alarm handler - called by Cloudflare when a scheduled alarm fires
908
+ * Processes the next item in the alarm queue
909
+ *
910
+ * Important: This method must NEVER throw an exception, as that would break
911
+ * the alarm chain. All errors are caught and logged.
912
+ */
913
+ alarm(): Promise<void>;
914
+ /**
915
+ * Internal method: Execute a flow (called by alarm queue)
916
+ * This is the actual execution logic, separate from the public execute() RPC method
917
+ */
918
+ private executeFlow;
919
+ /**
920
+ * Internal method: Execute an effect (called by alarm queue)
921
+ * Effects run outside the tool execution context.
922
+ */
923
+ private executeEffect;
924
+ /**
925
+ * Internal method: Process a message (called by alarm queue)
926
+ * This is the actual message processing logic, separate from the public sendMessage() RPC method
927
+ */
928
+ private processMessage;
929
+ /**
930
+ * Internal method: Continue execution without adding a message (called by alarm queue)
931
+ * This allows resuming FlowEngine execution from where it stopped.
932
+ */
933
+ private doContinueExecution;
934
+ private getLatestQueuedMessageSide;
935
+ /**
936
+ * TEST METHOD: Queue a test operation
937
+ * Used for testing alarm queue ordering and timing
938
+ */
939
+ queueTestOperation(id: string, label: string, expectedOrder: number, delayMs: number): Promise<Response>;
940
+ /**
941
+ * TEST METHOD: Get queue state
942
+ */
943
+ getQueueState(): Promise<Response>;
944
+ /**
945
+ * TEST METHOD: Get test execution logs
946
+ */
947
+ getTestLogs(): Promise<Response>;
948
+ /**
949
+ * TEST METHOD: Clear test logs
950
+ */
951
+ clearTestLogs(): Promise<Response>;
952
+ /**
953
+ * TEST METHOD: Insert a malformed message with orphaned tool calls
954
+ * This allows testing the tool call filtering logic
955
+ */
956
+ insertOrphanedToolCall(params: {
957
+ content?: string;
958
+ toolCallId: string;
959
+ toolName: string;
960
+ toolArgs: string;
961
+ }): Promise<Response>;
962
+ /**
963
+ * TEST METHOD: Execute a test operation
964
+ * Internal method called by alarm queue
965
+ */
966
+ private testOperation;
967
+ /**
968
+ * Get file storage helper instance
969
+ */
970
+ private getFileStorage;
971
+ /**
972
+ * Write a file to storage (RPC method)
973
+ */
974
+ writeFile(path: string, data: string, // base64 encoded
975
+ mimeType: string, options?: {
976
+ metadata?: Record<string, unknown>;
977
+ thumbnail?: string;
978
+ }): Promise<{
979
+ success: boolean;
980
+ file: any;
981
+ error?: undefined;
982
+ } | {
983
+ success: boolean;
984
+ error: any;
985
+ file?: undefined;
986
+ }>;
987
+ /**
988
+ * Write a text file to storage (RPC method)
989
+ */
990
+ writeTextFile(path: string, content: string, mimeType?: string, options?: {
991
+ metadata?: Record<string, unknown>;
992
+ }): Promise<{
993
+ success: boolean;
994
+ file: any;
995
+ error?: undefined;
996
+ } | {
997
+ success: boolean;
998
+ error: any;
999
+ file?: undefined;
1000
+ }>;
1001
+ /**
1002
+ * Process an image using sip (WASM-based image processing)
1003
+ * This runs inside the DO where WASM is properly initialized.
1004
+ *
1005
+ * @param data - base64 encoded image data
1006
+ * @param mimeType - MIME type of the input image
1007
+ * @returns Processed image data, dimensions, and mimeType
1008
+ */
1009
+ processImage(data: string, mimeType: string): Promise<{
1010
+ success: boolean;
1011
+ data?: string;
1012
+ mimeType?: string;
1013
+ width?: number;
1014
+ height?: number;
1015
+ error?: string;
1016
+ }>;
1017
+ /**
1018
+ * Link to an external file (RPC method)
1019
+ */
1020
+ linkFile(path: string, location: string, options?: {
1021
+ mimeType?: string;
1022
+ size?: number;
1023
+ metadata?: Record<string, unknown>;
1024
+ }): Promise<{
1025
+ success: boolean;
1026
+ file: any;
1027
+ error?: undefined;
1028
+ } | {
1029
+ success: boolean;
1030
+ error: any;
1031
+ file?: undefined;
1032
+ }>;
1033
+ /**
1034
+ * Read a file from storage (RPC method)
1035
+ * Returns base64-encoded data
1036
+ */
1037
+ readFile(path: string): Promise<{
1038
+ success: boolean;
1039
+ data: string;
1040
+ error?: undefined;
1041
+ } | {
1042
+ success: boolean;
1043
+ error: any;
1044
+ data?: undefined;
1045
+ }>;
1046
+ /**
1047
+ * Read a text file from storage (RPC method)
1048
+ */
1049
+ readTextFile(path: string): Promise<{
1050
+ success: boolean;
1051
+ content: any;
1052
+ error?: undefined;
1053
+ } | {
1054
+ success: boolean;
1055
+ error: any;
1056
+ content?: undefined;
1057
+ }>;
1058
+ /**
1059
+ * Get file metadata (RPC method)
1060
+ */
1061
+ statFile(path: string): Promise<{
1062
+ success: boolean;
1063
+ file: any;
1064
+ error?: undefined;
1065
+ } | {
1066
+ success: boolean;
1067
+ error: any;
1068
+ file?: undefined;
1069
+ }>;
1070
+ /**
1071
+ * Check if file exists (RPC method)
1072
+ */
1073
+ fileExists(path: string): Promise<{
1074
+ success: boolean;
1075
+ exists: any;
1076
+ error?: undefined;
1077
+ } | {
1078
+ success: boolean;
1079
+ error: any;
1080
+ exists?: undefined;
1081
+ }>;
1082
+ /**
1083
+ * Delete a file (RPC method)
1084
+ */
1085
+ unlinkFile(path: string): Promise<{
1086
+ success: boolean;
1087
+ error?: undefined;
1088
+ } | {
1089
+ success: boolean;
1090
+ error: any;
1091
+ }>;
1092
+ /**
1093
+ * Create a directory (RPC method)
1094
+ */
1095
+ mkdirFile(path: string): Promise<{
1096
+ success: boolean;
1097
+ directory: any;
1098
+ error?: undefined;
1099
+ } | {
1100
+ success: boolean;
1101
+ error: any;
1102
+ directory?: undefined;
1103
+ }>;
1104
+ /**
1105
+ * List directory contents (RPC method)
1106
+ */
1107
+ readdirFile(path: string): Promise<{
1108
+ success: boolean;
1109
+ files: any;
1110
+ error?: undefined;
1111
+ } | {
1112
+ success: boolean;
1113
+ error: any;
1114
+ files?: undefined;
1115
+ }>;
1116
+ /**
1117
+ * Remove empty directory (RPC method)
1118
+ */
1119
+ rmdirFile(path: string): Promise<{
1120
+ success: boolean;
1121
+ error?: undefined;
1122
+ } | {
1123
+ success: boolean;
1124
+ error: any;
1125
+ }>;
1126
+ /**
1127
+ * Get file storage statistics (RPC method)
1128
+ */
1129
+ getFileStats(): Promise<{
1130
+ success: boolean;
1131
+ stats: any;
1132
+ error?: undefined;
1133
+ } | {
1134
+ success: boolean;
1135
+ error: any;
1136
+ stats?: undefined;
1137
+ }>;
1138
+ /**
1139
+ * Get thumbnail for an image (RPC method)
1140
+ * Returns base64-encoded data
1141
+ */
1142
+ getFileThumbnail(path: string): Promise<{
1143
+ success: boolean;
1144
+ data: string;
1145
+ error?: undefined;
1146
+ } | {
1147
+ success: boolean;
1148
+ error: any;
1149
+ data?: undefined;
1150
+ }>;
1151
+ /**
1152
+ * Search file contents using FTS5 (RPC method)
1153
+ */
1154
+ grepFiles(pattern: string, options?: {
1155
+ path?: string;
1156
+ limit?: number;
1157
+ }): Promise<{
1158
+ success: boolean;
1159
+ results: any;
1160
+ error?: undefined;
1161
+ } | {
1162
+ success: boolean;
1163
+ error: any;
1164
+ results?: undefined;
1165
+ }>;
1166
+ /**
1167
+ * Find files by path pattern (RPC method)
1168
+ */
1169
+ findFiles(pattern: string, options?: {
1170
+ type?: "file" | "directory" | "all";
1171
+ limit?: number;
1172
+ }): Promise<{
1173
+ success: boolean;
1174
+ files: any;
1175
+ error?: undefined;
1176
+ } | {
1177
+ success: boolean;
1178
+ error: any;
1179
+ files?: undefined;
1180
+ }>;
1181
+ /**
1182
+ * Start a chunked file upload.
1183
+ * Creates file record with is_chunked=1 and chunk_count=null.
1184
+ * Caller should then use writeFileChunk() to write chunks.
1185
+ */
1186
+ startChunkedUpload(path: string, totalSize: number, mimeType: string, options?: {
1187
+ metadata?: Record<string, unknown>;
1188
+ width?: number;
1189
+ height?: number;
1190
+ }): Promise<{
1191
+ success: boolean;
1192
+ chunkSize?: number;
1193
+ expectedChunks?: number;
1194
+ error?: string;
1195
+ }>;
1196
+ /**
1197
+ * Write a single chunk of a chunked file upload.
1198
+ * @param path - File path
1199
+ * @param chunkIndex - 0-based chunk index
1200
+ * @param data - Base64 encoded chunk data
1201
+ */
1202
+ writeFileChunk(path: string, chunkIndex: number, data: string): Promise<{
1203
+ success: boolean;
1204
+ error?: string;
1205
+ }>;
1206
+ /**
1207
+ * Complete a chunked file upload.
1208
+ * Validates all chunks are present and sets chunk_count.
1209
+ */
1210
+ completeChunkedUpload(path: string, expectedChunks: number, options?: {
1211
+ thumbnail?: string;
1212
+ }): Promise<{
1213
+ success: boolean;
1214
+ file?: FileRecord;
1215
+ error?: string;
1216
+ }>;
1217
+ /**
1218
+ * Read a single chunk of a file.
1219
+ * Use for streaming large files to client.
1220
+ */
1221
+ readFileChunk(path: string, chunkIndex: number): Promise<{
1222
+ success: boolean;
1223
+ data?: string;
1224
+ error?: string;
1225
+ }>;
1226
+ /**
1227
+ * Get file info including chunking metadata.
1228
+ */
1229
+ getFileInfo(path: string): Promise<{
1230
+ success: boolean;
1231
+ file?: FileRecord;
1232
+ error?: string;
1233
+ }>;
1234
+ }
1235
+
1236
+ type EnvValueType = 'text' | 'secret';
1237
+ /**
1238
+ * Environment type for DurableAgentBuilder.
1239
+ * Users extend this with their own bindings.
1240
+ */
1241
+ interface AgentBuilderEnv {
1242
+ AGENT_BUILDER: DurableObjectNamespace<DurableAgentBuilder>;
1243
+ AGENT_BUILDER_THREAD: DurableObjectNamespace;
1244
+ ENCRYPTION_KEY?: string;
1245
+ }
1246
+ /**
1247
+ * Thread metadata stored in the registry.
1248
+ */
1249
+ interface ThreadRegistryEntry {
1250
+ id: string;
1251
+ agent_name: string;
1252
+ user_id: string | null;
1253
+ tags: string[] | null;
1254
+ env: Record<string, string> | null;
1255
+ env_types: Record<string, EnvValueType> | null;
1256
+ /** @deprecated Use env */
1257
+ tenvs: Record<string, unknown> | null;
1258
+ properties: Record<string, unknown> | null;
1259
+ parent: string | null;
1260
+ terminated: number | null;
1261
+ created_at: number;
1262
+ }
1263
+ interface PendingSubagentAttachmentRef {
1264
+ path: string;
1265
+ name?: string;
1266
+ mimeType?: string;
1267
+ size?: number;
1268
+ width?: number;
1269
+ height?: number;
1270
+ }
1271
+ interface PendingSubagentEnvRequestPayload {
1272
+ blocking: boolean;
1273
+ resumable: boolean;
1274
+ receives_messages: 'side_a' | 'side_b';
1275
+ parent_communication: 'implicit' | 'explicit';
1276
+ initial_message_content: string;
1277
+ initial_message_attachments: PendingSubagentAttachmentRef[];
1278
+ initial_agent_name?: string | null;
1279
+ agent_title?: string | null;
1280
+ agent_description?: string | null;
1281
+ spawn_group_id?: string | null;
1282
+ }
1283
+ interface PendingSubagentEnvRequest {
1284
+ request_id: string;
1285
+ parent_thread_id: string;
1286
+ agent_name: string;
1287
+ registry_agent_name: string;
1288
+ required: string[];
1289
+ missing: string[];
1290
+ payload: PendingSubagentEnvRequestPayload;
1291
+ created_at: number;
1292
+ }
1293
+ /**
1294
+ * Parameters for updating a thread.
1295
+ */
1296
+ interface UpdateThreadParams {
1297
+ agent_name?: string;
1298
+ user_id?: string | null;
1299
+ tags?: string[] | null;
1300
+ env?: Record<string, string> | null;
1301
+ env_types?: Record<string, EnvValueType> | null;
1302
+ /** @deprecated Use env */
1303
+ tenvs?: Record<string, unknown> | null;
1304
+ properties?: Record<string, unknown> | null;
1305
+ parent?: string | null;
1306
+ terminated?: number | null;
1307
+ }
1308
+ /**
1309
+ * User record.
1310
+ */
1311
+ interface User {
1312
+ id: string;
1313
+ username: string;
1314
+ password_hash: string;
1315
+ role: 'admin';
1316
+ created_at: number;
1317
+ updated_at: number;
1318
+ }
1319
+ interface ScopedEnvEntry {
1320
+ name: string;
1321
+ value: string;
1322
+ type: EnvValueType;
1323
+ created_at: number;
1324
+ updated_at: number;
1325
+ }
1326
+ /**
1327
+ * Provider credentials.
1328
+ */
1329
+ interface Provider$1 {
1330
+ name: string;
1331
+ sdk: string;
1332
+ api_key: string;
1333
+ }
1334
+ declare class DurableAgentBuilder<Env extends AgentBuilderEnv = AgentBuilderEnv> extends DurableObject<Env> {
1335
+ private migratedToVersion;
1336
+ private eventSockets;
1337
+ constructor(ctx: DurableObjectState, env: Env);
1338
+ private normalizeEnvRecord;
1339
+ private normalizeEnvTypeRecord;
1340
+ private extractEnvTypeRecord;
1341
+ private withEnvTypeRecord;
1342
+ private serializeEnvTypes;
1343
+ private resolveRegistryKey;
1344
+ private extractScopedVariables;
1345
+ private filterScopedInheritedEnv;
1346
+ private filterScopedInheritedEnvTypes;
1347
+ private collectScopedVariablesForAgent;
1348
+ private getScopedVariableNamesForAgent;
1349
+ private getRequiredScopedVariableNamesForAgent;
1350
+ private normalizeScopedVariableList;
1351
+ private normalizePendingAttachments;
1352
+ private sanitizeFilename;
1353
+ private inferMimeTypeFromPath;
1354
+ private extensionForMimeType;
1355
+ private buildAttachmentTargetPath;
1356
+ private formatSubagentAttachmentPathSummary;
1357
+ private formatSubagentTerminalMessage;
1358
+ private copyPendingAttachmentsBetweenThreads;
1359
+ private buildThreadNameTag;
1360
+ private encryptEnvRecord;
1361
+ private decryptEnvRecord;
1362
+ private listActiveDescendantThreadIds;
1363
+ private propagateThreadEnvToDescendants;
1364
+ /**
1365
+ * Returns the tools registry for lazy-loading tool definitions.
1366
+ * Must be overridden in a subclass.
1367
+ */
1368
+ tools(): Record<string, () => Promise<any>>;
1369
+ /**
1370
+ * Returns the hooks registry for lazy-loading hook definitions.
1371
+ * Must be overridden in a subclass.
1372
+ */
1373
+ hooks(): Record<string, () => Promise<any>>;
1374
+ /**
1375
+ * Returns the models registry for lazy-loading model definitions.
1376
+ * Must be overridden in a subclass.
1377
+ */
1378
+ models(): Record<string, () => Promise<any>>;
1379
+ /**
1380
+ * Returns the prompts registry for lazy-loading prompt definitions.
1381
+ * Must be overridden in a subclass.
1382
+ */
1383
+ prompts(): Record<string, () => Promise<any>>;
1384
+ /**
1385
+ * Returns the agents registry for lazy-loading agent definitions.
1386
+ * Must be overridden in a subclass.
1387
+ */
1388
+ agents(): Record<string, () => Promise<any>>;
1389
+ /**
1390
+ * Returns the namespaced registry for packed agent support.
1391
+ * Must be overridden in a subclass.
1392
+ */
1393
+ registry(): any;
1394
+ private ensureMigrated;
1395
+ private getCurrentVersion;
1396
+ private runMigrations;
1397
+ /**
1398
+ * Create a new thread and add it to the registry.
1399
+ */
1400
+ createThread(params: {
1401
+ agent_name: string;
1402
+ user_id?: string;
1403
+ tags?: string[];
1404
+ env?: Record<string, string>;
1405
+ env_types?: Record<string, EnvValueType>;
1406
+ /** @deprecated Use env */
1407
+ tenvs?: Record<string, unknown>;
1408
+ properties?: Record<string, unknown>;
1409
+ parent?: string;
1410
+ }): Promise<ThreadRegistryEntry>;
1411
+ private runAfterThreadCreatedHook;
1412
+ /**
1413
+ * Get a thread by ID.
1414
+ */
1415
+ getThread(id: string): Promise<ThreadRegistryEntry | null>;
1416
+ /**
1417
+ * List threads with optional filtering.
1418
+ * Note: tenvs are not decrypted in list operations for performance.
1419
+ * Use getThread() to retrieve a thread with decrypted tenvs.
1420
+ */
1421
+ listThreads(params?: {
1422
+ agent_name?: string;
1423
+ user_id?: string;
1424
+ search?: string;
1425
+ startDate?: number;
1426
+ endDate?: number;
1427
+ limit?: number;
1428
+ offset?: number;
1429
+ include_children?: boolean;
1430
+ }): Promise<{
1431
+ threads: ThreadRegistryEntry[];
1432
+ total: number;
1433
+ }>;
1434
+ /**
1435
+ * Delete a thread from the registry.
1436
+ */
1437
+ deleteThread(id: string): Promise<boolean>;
1438
+ /**
1439
+ * Get a thread tree (root + all descendants) in child-first order.
1440
+ *
1441
+ * Child-first ordering allows callers to perform destructive operations
1442
+ * (like deletes) without leaving child rows referencing a deleted parent.
1443
+ */
1444
+ getThreadTreeIds(rootThreadId: string): Promise<string[]>;
1445
+ /**
1446
+ * Update a thread's agent_name (used during agent handoff).
1447
+ */
1448
+ updateThreadAgent(id: string, agent_name: string): Promise<boolean>;
1449
+ /**
1450
+ * Update a thread's metadata.
1451
+ */
1452
+ updateThread(id: string, params: UpdateThreadParams): Promise<ThreadRegistryEntry | null>;
1453
+ private getEncryptionKey;
1454
+ private encryptEnvValue;
1455
+ private decryptEnvValue;
1456
+ private listScopedEnv;
1457
+ private listScopedEnvEntries;
1458
+ private getScopedEnvTypeRecord;
1459
+ private replaceScopedEnv;
1460
+ private patchScopedEnv;
1461
+ getInstanceEnv(): Promise<Record<string, string>>;
1462
+ getInstanceEnvTypes(): Promise<Record<string, EnvValueType>>;
1463
+ getInstanceEnvEntries(): Promise<ScopedEnvEntry[]>;
1464
+ setInstanceEnv(env: Record<string, string>, envTypes?: Record<string, EnvValueType> | null): Promise<void>;
1465
+ patchInstanceEnv(params: {
1466
+ env_patch?: Record<string, unknown> | null;
1467
+ env_type_patch?: Record<string, unknown> | null;
1468
+ env_delete?: string[] | null;
1469
+ }): Promise<void>;
1470
+ getUserEnv(userId: string): Promise<Record<string, string>>;
1471
+ getUserEnvTypes(userId: string): Promise<Record<string, EnvValueType>>;
1472
+ getUserEnvEntries(userId: string): Promise<ScopedEnvEntry[]>;
1473
+ setUserEnv(userId: string, env: Record<string, string>, envTypes?: Record<string, EnvValueType> | null): Promise<void>;
1474
+ patchUserEnv(userId: string, params: {
1475
+ env_patch?: Record<string, unknown> | null;
1476
+ env_type_patch?: Record<string, unknown> | null;
1477
+ env_delete?: string[] | null;
1478
+ }): Promise<void>;
1479
+ getMissingRequiredScopedSubagentEnv(params: {
1480
+ parent_thread_id: string;
1481
+ agent_name: string;
1482
+ provided_env?: Record<string, string> | null;
1483
+ }): Promise<string[]>;
1484
+ createPendingSubagentEnvRequest(params: {
1485
+ parent_thread_id: string;
1486
+ agent_name: string;
1487
+ registry_agent_name: string;
1488
+ required_variables: string[];
1489
+ missing_variables: string[];
1490
+ payload: PendingSubagentEnvRequestPayload;
1491
+ }): Promise<PendingSubagentEnvRequest>;
1492
+ getPendingSubagentEnvRequest(parentThreadId: string, requestId: string): Promise<PendingSubagentEnvRequest | null>;
1493
+ private clearPendingSubagentEnvRequest;
1494
+ completePendingSubagentEnvRequest(params: {
1495
+ parent_thread_id: string;
1496
+ request_id: string;
1497
+ env: Record<string, string>;
1498
+ }): Promise<{
1499
+ request_id: string;
1500
+ child_thread_id: string;
1501
+ status: 'success';
1502
+ }>;
1503
+ resolveThreadEnv(params: {
1504
+ threadId: string;
1505
+ property: string;
1506
+ promptName?: string;
1507
+ }): Promise<string | null>;
1508
+ resolveThreadEnvType(params: {
1509
+ threadId: string;
1510
+ property: string;
1511
+ promptName?: string;
1512
+ }): Promise<EnvValueType>;
1513
+ private toThreadEventPayload;
1514
+ /**
1515
+ * Load a model definition by name.
1516
+ */
1517
+ loadModel(name: string): Promise<any>;
1518
+ /**
1519
+ * List available model names.
1520
+ */
1521
+ getModelNames(): string[];
1522
+ /**
1523
+ * Load a prompt definition by name.
1524
+ */
1525
+ loadPrompt(name: string): Promise<any>;
1526
+ /**
1527
+ * List available prompt names.
1528
+ */
1529
+ getPromptNames(): string[];
1530
+ /**
1531
+ * Load an agent definition by name.
1532
+ * Supports both global agents (e.g., "my-agent") and packed agents (e.g., "packageId/agentName").
1533
+ * For scoped packages, use "@scope/pkg/agentName".
1534
+ */
1535
+ loadAgent(name: string): Promise<any>;
1536
+ /**
1537
+ * List available agent names.
1538
+ */
1539
+ getAgentNames(): string[];
1540
+ /**
1541
+ * Get a provider's credentials.
1542
+ */
1543
+ getProvider(name: string): Promise<Provider$1 | null>;
1544
+ /**
1545
+ * Set a provider's credentials.
1546
+ */
1547
+ setProvider(provider: Provider$1): Promise<void>;
1548
+ /**
1549
+ * List all providers.
1550
+ */
1551
+ listProviders(): Promise<Provider$1[]>;
1552
+ /**
1553
+ * Delete a provider.
1554
+ */
1555
+ deleteProvider(name: string): Promise<boolean>;
1556
+ /**
1557
+ * Get a user by username.
1558
+ */
1559
+ getUserByUsername(username: string): Promise<User | null>;
1560
+ /**
1561
+ * Get a user by ID.
1562
+ */
1563
+ getUserById(id: string): Promise<User | null>;
1564
+ /**
1565
+ * Create a new user.
1566
+ */
1567
+ createUser(params: {
1568
+ username: string;
1569
+ password_hash: string;
1570
+ role?: 'admin';
1571
+ }): Promise<User>;
1572
+ /**
1573
+ * Check if any users exist (for first-time setup).
1574
+ */
1575
+ hasUsers(): Promise<boolean>;
1576
+ /**
1577
+ * List all users (excludes password hash).
1578
+ */
1579
+ listUsers(): Promise<Array<{
1580
+ id: string;
1581
+ username: string;
1582
+ role: 'admin';
1583
+ created_at: number;
1584
+ updated_at: number;
1585
+ }>>;
1586
+ /**
1587
+ * Update a user.
1588
+ */
1589
+ updateUser(id: string, params: {
1590
+ username?: string;
1591
+ password_hash?: string;
1592
+ role?: 'admin';
1593
+ }): Promise<User | null>;
1594
+ /**
1595
+ * Delete a user.
1596
+ */
1597
+ deleteUser(id: string): Promise<boolean>;
1598
+ /**
1599
+ * Create a new session.
1600
+ */
1601
+ createSession(params: {
1602
+ user_id: string;
1603
+ token_hash: string;
1604
+ expires_at: number;
1605
+ }): Promise<string>;
1606
+ /**
1607
+ * Validate a session token.
1608
+ */
1609
+ validateSession(tokenHash: string): Promise<{
1610
+ user_id: string;
1611
+ expires_at: number;
1612
+ } | null>;
1613
+ /**
1614
+ * Delete expired sessions.
1615
+ */
1616
+ cleanupSessions(): Promise<number>;
1617
+ /**
1618
+ * Delete a session.
1619
+ */
1620
+ deleteSession(tokenHash: string): Promise<void>;
1621
+ /**
1622
+ * Create an API key.
1623
+ */
1624
+ createApiKey(params: {
1625
+ name: string;
1626
+ key_hash: string;
1627
+ key_prefix: string;
1628
+ last_five: string;
1629
+ user_id: string;
1630
+ }): Promise<string>;
1631
+ /**
1632
+ * Validate an API key.
1633
+ */
1634
+ validateApiKey(keyHash: string): Promise<{
1635
+ user_id: string;
1636
+ id: string;
1637
+ } | null>;
1638
+ /**
1639
+ * List API keys for a user.
1640
+ */
1641
+ listApiKeys(userId: string): Promise<Array<{
1642
+ id: string;
1643
+ name: string;
1644
+ key_prefix: string;
1645
+ last_five: string;
1646
+ created_at: number;
1647
+ last_used_at: number | null;
1648
+ }>>;
1649
+ /**
1650
+ * Delete an API key.
1651
+ */
1652
+ deleteApiKey(id: string, userId: string): Promise<boolean>;
1653
+ /**
1654
+ * Link an OAuth account to a user.
1655
+ */
1656
+ linkOAuthAccount(params: {
1657
+ user_id: string;
1658
+ provider: 'github' | 'google';
1659
+ provider_user_id: string;
1660
+ provider_username?: string;
1661
+ }): Promise<void>;
1662
+ /**
1663
+ * Find user by OAuth account.
1664
+ */
1665
+ findUserByOAuth(provider: 'github' | 'google', providerUserId: string): Promise<User | null>;
1666
+ /**
1667
+ * Acquire edit lock for coordinated edits.
1668
+ */
1669
+ acquireEditLock(params: {
1670
+ locked_by: string;
1671
+ lock_reason: string;
1672
+ }): Promise<boolean>;
1673
+ /**
1674
+ * Release edit lock.
1675
+ */
1676
+ releaseEditLock(lockedBy: string): Promise<boolean>;
1677
+ /**
1678
+ * Get current lock state.
1679
+ */
1680
+ getEditLockState(): Promise<{
1681
+ locked: boolean;
1682
+ locked_by: string | null;
1683
+ locked_at: number | null;
1684
+ lock_reason: string | null;
1685
+ pending_changes: string | null;
1686
+ }>;
1687
+ /**
1688
+ * Store pending changes for commit.
1689
+ */
1690
+ setPendingChanges(changes: string): Promise<void>;
1691
+ /**
1692
+ * Get the Durable Object stub for a thread.
1693
+ */
1694
+ getThreadStub(threadId: string): DurableObjectStub;
1695
+ /**
1696
+ * Handle fetch requests - used for WebSocket upgrades
1697
+ */
1698
+ fetch(request: Request): Promise<Response>;
1699
+ /**
1700
+ * Handle WebSocket upgrade for events channel
1701
+ * Uses Hibernation API to reduce costs during inactivity
1702
+ */
1703
+ private handleEventsWebSocketUpgrade;
1704
+ /**
1705
+ * Broadcast an event to all connected WebSocket clients
1706
+ */
1707
+ private broadcastEvent;
1708
+ /**
1709
+ * WebSocket Hibernation API handler for incoming messages
1710
+ * Called when a message is received on a hibernated WebSocket
1711
+ */
1712
+ webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void>;
1713
+ /**
1714
+ * WebSocket Hibernation API handler for connection close
1715
+ * Called when a WebSocket connection is closed
1716
+ */
1717
+ webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean): Promise<void>;
1718
+ /**
1719
+ * WebSocket Hibernation API handler for errors
1720
+ * Called when a WebSocket encounters an error
1721
+ */
1722
+ webSocketError(ws: WebSocket, error: unknown): Promise<void>;
1723
+ }
1724
+
1725
+ interface CodeExecutionBridgeProps {
1726
+ threadId?: string;
1727
+ runId?: string;
1728
+ }
1729
+ declare class CodeExecutionBridge extends WorkerEntrypoint<ThreadEnv, CodeExecutionBridgeProps> {
1730
+ call(threadId: string, runId: string, functionId: string, encodedArgs: unknown[]): Promise<unknown>;
1731
+ }
1732
+
1733
+ /**
1734
+ * Model definition module for AgentBuilder.
1735
+ *
1736
+ * This module re-exports model types from @standardagents/spec and provides
1737
+ * a builder-specific version of ModelDefinition that supports the generated
1738
+ * AgentBuilder.Models type for fallback references.
1739
+ *
1740
+ * @module
1741
+ */
1742
+
1743
+ /**
1744
+ * Model definition configuration with AgentBuilder-specific fallback typing.
1745
+ *
1746
+ * Extends the base ModelDefinition from @standardagents/spec to support
1747
+ * the generated AgentBuilder.Models type for type-safe fallback references.
1748
+ *
1749
+ * @template N - The model name as a string literal type for type inference
1750
+ */
1751
+ interface ModelDefinition<N extends string = string> extends Omit<ModelDefinition$1<N>, 'fallbacks'> {
1752
+ /**
1753
+ * Fallback models to try if this model fails.
1754
+ * Referenced by model name (must be defined in agents/models/).
1755
+ * Tried in order after primary model exhausts retries.
1756
+ *
1757
+ * @example ['gpt-4', 'gpt-3.5-turbo']
1758
+ */
1759
+ fallbacks?: AgentBuilder.Models[];
1760
+ }
1761
+
1762
+ /**
1763
+ * Prompt definition module for AgentBuilder.
1764
+ *
1765
+ * This module re-exports prompt types from @standardagents/spec and provides
1766
+ * builder-specific versions that use the generated AgentBuilder namespace types.
1767
+ *
1768
+ * @module
1769
+ */
1770
+
1771
+ /**
1772
+ * A prompt inclusion part with type-safe autocomplete.
1773
+ * Uses AgentBuilder.Prompts for type-safe prompt name references.
1774
+ */
1775
+ interface PromptIncludePart {
1776
+ type: 'include';
1777
+ /** The name of the prompt to include (type-safe with autocomplete) */
1778
+ prompt: AgentBuilder.Prompts;
1779
+ }
1780
+ /**
1781
+ * A single part of a structured prompt.
1782
+ */
1783
+ type PromptPart = PromptTextPart | PromptIncludePart | PromptEnvPart;
1784
+ /**
1785
+ * Prompt content can be a string or structured array with type-safe includes.
1786
+ */
1787
+ type PromptContent = string | PromptPart[];
1788
+ /**
1789
+ * Sub-prompt configuration with type-safe name references.
1790
+ */
1791
+ interface SubpromptConfig<T extends string = AgentBuilder.Callables> extends Omit<SubpromptConfig$1<T>, 'name'> {
1792
+ /** Name of the sub-prompt (type-safe with autocomplete) */
1793
+ name: T;
1794
+ }
1795
+ /**
1796
+ * Prompt tool configuration with static tenvs/options.
1797
+ */
1798
+ interface PromptToolConfig<T extends string = AgentBuilder.Callables> extends Omit<PromptToolConfig$1, 'name'> {
1799
+ /** Name of the callable tool/agent (type-safe with autocomplete). */
1800
+ name: T;
1801
+ /** Environment values scoped to this tool invocation. */
1802
+ env?: Record<string, string>;
1803
+ /** @deprecated Use env */
1804
+ tenvs?: Record<string, unknown>;
1805
+ }
1806
+ /**
1807
+ * Subagent tool configuration with type-safe name references.
1808
+ */
1809
+ interface SubagentToolConfig<T extends string = AgentBuilder.Callables> extends Omit<SubagentToolConfig$1<T>, 'name'> {
1810
+ /** Name of the callable dual_ai agent (type-safe with autocomplete). */
1811
+ name: T;
1812
+ }
1813
+ /**
1814
+ * @deprecated Use SubpromptConfig instead
1815
+ */
1816
+ type ToolConfig<T extends string = AgentBuilder.Callables> = SubpromptConfig<T>;
1817
+
1818
+ /**
1819
+ * Prompt definition configuration with AgentBuilder-specific typing.
1820
+ *
1821
+ * Provides type-safe references to models, tools, and agents via the
1822
+ * generated AgentBuilder namespace.
1823
+ *
1824
+ * @template N - The prompt name as a string literal type
1825
+ * @template S - The Zod schema type for requiredSchema (inferred automatically)
1826
+ */
1827
+ interface PromptDefinition<N extends string = string, S extends ToolArgs = ToolArgs> {
1828
+ /** Unique name for this prompt. */
1829
+ name: N;
1830
+ /** Description shown when this prompt is exposed as a tool. */
1831
+ toolDescription: string;
1832
+ /** The system prompt content with type-safe includes. */
1833
+ prompt: PromptContent;
1834
+ /** Model to use (type-safe with autocomplete). */
1835
+ model: AgentBuilder.Models;
1836
+ /**
1837
+ * @deprecated All prompts are now automatically exposed as tools.
1838
+ */
1839
+ exposeAsTool?: boolean;
1840
+ /** Include full chat history in the LLM context. @default false */
1841
+ includeChat?: boolean;
1842
+ /** Include results from past tool calls. @default false */
1843
+ includePastTools?: boolean;
1844
+ /** Allow parallel execution of multiple tool calls. @default false */
1845
+ parallelToolCalls?: boolean;
1846
+ /** Tool calling strategy. @default 'auto' */
1847
+ toolChoice?: 'auto' | 'none' | 'required';
1848
+ /** Zod schema for validating inputs when called as a tool. */
1849
+ requiredSchema?: S;
1850
+ /** Variable declarations for this prompt. */
1851
+ variables?: VariableDefinition[];
1852
+ /** Tools available to this prompt (type-safe with autocomplete). To enable handoffs, include ai_human agent names. */
1853
+ tools?: (AgentBuilder.Callables | SubpromptConfig | PromptToolConfig | SubagentToolConfig)[];
1854
+ /** Prompt-level environment values. */
1855
+ env?: Record<string, string>;
1856
+ /** @deprecated Use env */
1857
+ tenvs?: Record<string, unknown>;
1858
+ /** Reasoning configuration for extended thinking models. */
1859
+ reasoning?: ReasoningConfig;
1860
+ /** Number of recent messages to keep actual images for. @default 10 */
1861
+ recentImageThreshold?: number;
1862
+ /** Hook IDs to run when this prompt is active. Falls back to agent-level hooks if not set. */
1863
+ hooks?: AgentBuilder.Hooks[];
1864
+ }
1865
+
1866
+ /**
1867
+ * Agent definition module for AgentBuilder.
1868
+ *
1869
+ * This module re-exports agent types from @standardagents/spec and provides
1870
+ * builder-specific versions that use the generated AgentBuilder namespace types.
1871
+ *
1872
+ * @module
1873
+ */
1874
+
1875
+ /**
1876
+ * Side configuration with type-safe autocomplete.
1877
+ * Uses AgentBuilder.Prompts and AgentBuilder.Callables for type-safe references.
1878
+ */
1879
+ interface SessionToolConfig {
1880
+ /**
1881
+ * Tool name for this lifecycle binding.
1882
+ */
1883
+ name: AgentBuilder.Callables;
1884
+ /**
1885
+ * Optional tool-argument property used as message text.
1886
+ */
1887
+ messageProperty?: string;
1888
+ /**
1889
+ * Optional tool-argument property containing attachment path(s).
1890
+ */
1891
+ attachmentsProperty?: string;
1892
+ }
1893
+ /**
1894
+ * Session lifecycle binding (string shorthand or explicit object form).
1895
+ */
1896
+ type SessionToolBinding = AgentBuilder.Callables | SessionToolConfig;
1897
+ interface SideConfig extends Omit<SideConfig$1, 'prompt' | 'stopTool' | 'sessionStop' | 'sessionFail' | 'sessionStatus'> {
1898
+ /**
1899
+ * The prompt to use for this side (type-safe with autocomplete).
1900
+ * Must reference a prompt defined in agents/prompts/.
1901
+ */
1902
+ prompt: AgentBuilder.Prompts;
1903
+ /**
1904
+ * Stop this side's turn when a specific tool is called (type-safe with autocomplete).
1905
+ * Overrides stopOnResponse when the named tool is invoked.
1906
+ * Requires stopToolResponseProperty to extract the result.
1907
+ */
1908
+ stopTool?: AgentBuilder.Callables;
1909
+ /**
1910
+ * Tool that ends the entire session when called.
1911
+ * Supports shorthand string or explicit message/attachment mapping object.
1912
+ */
1913
+ sessionStop?: SessionToolBinding;
1914
+ /**
1915
+ * Tool that fails the entire session when called.
1916
+ * Supports shorthand string or explicit message/attachment mapping object.
1917
+ */
1918
+ sessionFail?: SessionToolBinding;
1919
+ /**
1920
+ * Tool that publishes status updates to the parent thread when used as a subagent.
1921
+ * Supports shorthand string or explicit message/attachment mapping object.
1922
+ */
1923
+ sessionStatus?: SessionToolBinding;
1924
+ /**
1925
+ * Enable manual stop condition handling via hooks.
1926
+ * Builder-specific feature for custom stop logic.
1927
+ * @default false
1928
+ */
1929
+ manualStopCondition?: boolean;
1930
+ }
1931
+ /**
1932
+ * Agent definition configuration with AgentBuilder-specific typing.
1933
+ *
1934
+ * Provides type-safe references to prompts and tools via the
1935
+ * generated AgentBuilder namespace.
1936
+ *
1937
+ * @template N - The agent name as a string literal type
1938
+ *
1939
+ * @example
1940
+ * ```typescript
1941
+ * import { defineAgent } from '@standardagents/builder';
1942
+ *
1943
+ * export default defineAgent({
1944
+ * name: 'support_agent',
1945
+ * title: 'Customer Support Agent',
1946
+ * type: 'ai_human',
1947
+ * sideA: {
1948
+ * label: 'Support',
1949
+ * prompt: 'customer_support',
1950
+ * stopOnResponse: true,
1951
+ * },
1952
+ * });
1953
+ * ```
1954
+ */
1955
+ interface AgentDefinition<N extends string = string> {
1956
+ /** Unique name for this agent. */
1957
+ name: N;
1958
+ /**
1959
+ * Human-readable title for the agent.
1960
+ * @deprecated Use name instead. Title will be removed in a future version.
1961
+ */
1962
+ title?: string;
1963
+ /**
1964
+ * Agent conversation type.
1965
+ * - `ai_human`: AI conversing with a human user (default)
1966
+ * - `dual_ai`: Two AI participants conversing
1967
+ * @default 'ai_human'
1968
+ */
1969
+ type?: 'ai_human' | 'dual_ai';
1970
+ /**
1971
+ * Maximum total turns across both sides.
1972
+ * Only applies to `dual_ai` agents.
1973
+ */
1974
+ maxSessionTurns?: number;
1975
+ /** Configuration for Side A (type-safe with autocomplete). */
1976
+ sideA: SideConfig;
1977
+ /** Configuration for Side B (type-safe with autocomplete). */
1978
+ sideB?: SideConfig;
1979
+ /**
1980
+ * Expose this agent as a tool for other prompts.
1981
+ * @default false
1982
+ */
1983
+ exposeAsTool?: boolean;
1984
+ /** Description shown when agent is used as a tool. */
1985
+ toolDescription?: string;
1986
+ /**
1987
+ * Environment values provided by this agent.
1988
+ */
1989
+ env?: Record<string, string>;
1990
+ /**
1991
+ * @deprecated Use env
1992
+ */
1993
+ tenvs?: Record<string, unknown>;
1994
+ /** Brief description of what this agent does. */
1995
+ description?: string;
1996
+ /** Icon URL or absolute path for the agent. */
1997
+ icon?: string;
1998
+ /**
1999
+ * npm package name for this agent when packed.
2000
+ * Preserved through unpack → edit → pack cycles.
2001
+ */
2002
+ packageName?: string;
2003
+ /**
2004
+ * Package version (semver format).
2005
+ * Preserved through unpack → edit → pack cycles.
2006
+ */
2007
+ version?: string;
2008
+ /**
2009
+ * Package author/copyright holder.
2010
+ * Preserved through unpack → edit → pack cycles.
2011
+ */
2012
+ author?: string;
2013
+ /**
2014
+ * License identifier (SPDX format).
2015
+ * Preserved through unpack → edit → pack cycles.
2016
+ */
2017
+ license?: string;
2018
+ }
2019
+
2020
+ /**
2021
+ * Options for injecting a message
2022
+ */
2023
+ interface InjectMessageOptions$1 {
2024
+ /** The message content */
2025
+ content: string;
2026
+ /** The message role */
2027
+ role: "system" | "user" | "assistant" | "tool";
2028
+ /** Optional message ID. If not provided, a UUID will be generated */
2029
+ id?: string;
2030
+ /** Optional message to insert before. If not provided, message is appended to the end */
2031
+ beforeMessageId?: string;
2032
+ /** Optional tool call ID (for role="tool" only) */
2033
+ toolCallId?: string;
2034
+ /** Optional name field */
2035
+ name?: string;
2036
+ /** Whether this message is silent (hidden from LLM, visible in UI only). Default: false */
2037
+ silent?: boolean;
2038
+ /** Optional structured metadata */
2039
+ metadata?: Record<string, unknown>;
2040
+ /** Force message to be top-level (depth 0) even when called from sub-prompts. Default: false */
2041
+ forceTopLevel?: boolean;
2042
+ /** Force a specific side to play the next turn after injecting the message */
2043
+ forceTurn?: "side_a" | "side_b";
2044
+ }
2045
+ /**
2046
+ * Queue a new tool call to be executed in the current flow
2047
+ *
2048
+ * This adds a tool call to the execution queue without immediately executing it.
2049
+ * The tool will be executed as part of the normal flow processing.
2050
+ *
2051
+ * If the current tool has a `uses` list defined, the toolName must be in that list.
2052
+ * This enforces namespace isolation for packed agents.
2053
+ *
2054
+ * @param flow - The current FlowState
2055
+ * @param toolName - The name of the tool to call
2056
+ * @param args - The arguments to pass to the tool
2057
+ * @throws Error if toolName is not in the current tool's uses list (when defined)
2058
+ *
2059
+ * @example
2060
+ * ```typescript
2061
+ * import { queueTool } from '@standardagents/builder';
2062
+ *
2063
+ * queueTool(flow, "search_user", { email: "user@example.com" });
2064
+ * ```
2065
+ */
2066
+ declare function queueTool(flow: FlowState, toolName: string, args?: Record<string, unknown>): void;
2067
+ /**
2068
+ * Inject a message into the thread without triggering execution
2069
+ *
2070
+ * This allows you to add messages to the conversation history programmatically.
2071
+ * The message is persisted to storage but does not cause the agent to execute.
2072
+ *
2073
+ * By default, messages are appended to the end of the conversation.
2074
+ * You can optionally insert a message before another message by providing beforeMessageId.
2075
+ *
2076
+ * @param flow - The current FlowState
2077
+ * @param options - Message options
2078
+ *
2079
+ * @example
2080
+ * ```typescript
2081
+ * import { injectMessage } from '@standardagents/builder';
2082
+ *
2083
+ * // Append a system message
2084
+ * await injectMessage(flow, {
2085
+ * role: "system",
2086
+ * content: "Context has been updated"
2087
+ * });
2088
+ *
2089
+ * // Insert a user message before a specific message
2090
+ * await injectMessage(flow, {
2091
+ * role: "user",
2092
+ * content: "Additional context",
2093
+ * beforeMessageId: "msg-123"
2094
+ * });
2095
+ *
2096
+ * // Inject a message and force a specific side to play next
2097
+ * await injectMessage(flow, {
2098
+ * role: "system",
2099
+ * content: "New instructions for the AI",
2100
+ * forceTurn: "side_a" // Force side_a to respond to this message
2101
+ * });
2102
+ * ```
2103
+ */
2104
+ declare function injectMessage(flow: FlowState, options: InjectMessageOptions$1): Promise<Message>;
2105
+ /**
2106
+ * Get messages from the thread history
2107
+ *
2108
+ * Retrieves message history from the thread's SQLite storage.
2109
+ * Messages are ordered by creation time (oldest first by default).
2110
+ *
2111
+ * @param flow - The current FlowState
2112
+ * @param limit - Maximum number of messages to retrieve (default: 100)
2113
+ * @param offset - Number of messages to skip (default: 0)
2114
+ * @param order - Sort order: "asc" (oldest first) or "desc" (newest first) (default: "asc")
2115
+ * @returns Array of messages
2116
+ *
2117
+ * @example
2118
+ * ```typescript
2119
+ * import { getMessages } from '@standardagents/builder';
2120
+ *
2121
+ * // Get last 10 messages
2122
+ * const messages = await getMessages(flow, 10);
2123
+ *
2124
+ * // Get 10 messages, skipping the first 20
2125
+ * const messages = await getMessages(flow, 10, 20);
2126
+ *
2127
+ * // Get newest 10 messages
2128
+ * const messages = await getMessages(flow, 10, 0, "desc");
2129
+ * ```
2130
+ */
2131
+ declare function getMessages(flow: FlowState, limit?: number, offset?: number, order?: "asc" | "desc"): Promise<Message[]>;
2132
+ /**
2133
+ * Reload message history from storage
2134
+ *
2135
+ * Re-loads the complete message history from the thread's SQLite storage,
2136
+ * applying any filter_messages hooks. This is useful when you need to refresh
2137
+ * the message history after making changes (e.g., injecting silent messages).
2138
+ *
2139
+ * @param flow - The current FlowState
2140
+ * @returns Array of messages (reloaded from storage)
2141
+ *
2142
+ * @example
2143
+ * ```typescript
2144
+ * import { injectMessage, reloadHistory } from '@standardagents/builder';
2145
+ *
2146
+ * // Reload history after injecting a silent message
2147
+ * await injectMessage(flow, { role: "system", content: "...", silent: true });
2148
+ * flow.messageHistory = await reloadHistory(flow);
2149
+ * ```
2150
+ */
2151
+ declare function reloadHistory(state: FlowState): Promise<Message[]>;
2152
+ /**
2153
+ * Emit a custom event to WebSocket clients via the stream
2154
+ *
2155
+ * Sends a custom event to all connected WebSocket clients on the stream channel.
2156
+ * This allows backend code to push arbitrary data to the frontend
2157
+ * outside of the standard message events.
2158
+ *
2159
+ * @param flow - The current FlowState
2160
+ * @param type - The event type name (e.g., "progress", "notification")
2161
+ * @param data - The event payload (any serializable data)
2162
+ *
2163
+ * @example
2164
+ * ```typescript
2165
+ * import { emitThreadEvent } from '@standardagents/builder';
2166
+ *
2167
+ * // Emit a progress update
2168
+ * emitThreadEvent(flow, "progress", { step: 3, total: 10, message: "Processing data..." });
2169
+ *
2170
+ * // Emit a custom notification
2171
+ * emitThreadEvent(flow, "notification", { level: "info", message: "User authenticated" });
2172
+ *
2173
+ * // Emit metadata
2174
+ * emitThreadEvent(flow, "metadata", { userId: "123", sessionId: "abc" });
2175
+ * ```
2176
+ */
2177
+ declare function emitThreadEvent(flow: FlowState, type: string, data: unknown): void;
2178
+ /**
2179
+ * Force a specific side to play the next turn
2180
+ *
2181
+ * This queues the specified side to play next without interrupting the current turn.
2182
+ * The forced turn only takes effect at the END of the current turn execution.
2183
+ *
2184
+ * If the tool queue is currently being processed (sequence.isHandling is true),
2185
+ * the forced turn is deferred until all queued tools complete. This allows patterns like:
2186
+ *
2187
+ * ```typescript
2188
+ * import { queueTool, forceTurn } from '@standardagents/builder';
2189
+ *
2190
+ * queueTool(flow, 'myTool', {});
2191
+ * forceTurn(flow, 'side_a');
2192
+ * // myTool executes first, THEN the turn switches to side_a
2193
+ * ```
2194
+ *
2195
+ * @param flow - The current FlowState
2196
+ * @param side - Which side should play next ('side_a' or 'side_b')
2197
+ *
2198
+ * @example
2199
+ * ```typescript
2200
+ * import { forceTurn } from '@standardagents/builder';
2201
+ *
2202
+ * // Force current side to continue (override stop condition)
2203
+ * // If side_a is playing and would stop, this forces it to play at least 1 more turn
2204
+ * forceTurn(flow, 'side_a');
2205
+ *
2206
+ * // Force switch to other side
2207
+ * // If side_a is playing, this forces side_b to play next turn
2208
+ * forceTurn(flow, 'side_b');
2209
+ *
2210
+ * // Force human turn in ai_human agent (execution stops and waits for user input)
2211
+ * if (flow.agentConfig.type === 'ai_human') {
2212
+ * forceTurn(flow, 'side_b'); // Stops execution, awaits user input
2213
+ * }
2214
+ * ```
2215
+ */
2216
+ declare function forceTurn(flow: FlowState, side: 'side_a' | 'side_b'): void;
2217
+ /**
2218
+ * Thread context from defineThreadEndpoint
2219
+ */
2220
+ interface ThreadContext {
2221
+ instance: {
2222
+ updateThreadMeta: (threadId: string, params: {
2223
+ agent_name?: string;
2224
+ user_id?: string | null;
2225
+ tags?: string[] | null;
2226
+ }) => Promise<{
2227
+ success: boolean;
2228
+ error?: string;
2229
+ thread?: {
2230
+ id: string;
2231
+ agent_id: string;
2232
+ user_id: string | null;
2233
+ tags: string[];
2234
+ created_at: number;
2235
+ };
2236
+ }>;
2237
+ };
2238
+ metadata: {
2239
+ id: string;
2240
+ agent_name: string;
2241
+ user_id: string | null;
2242
+ tags: string[] | null;
2243
+ created_at: number;
2244
+ };
2245
+ }
2246
+ /**
2247
+ * Update a thread's metadata in the DurableAgentBuilder registry
2248
+ *
2249
+ * This allows updating the agent_name, user_id, and tags for an existing thread.
2250
+ * Uses the thread instance from defineThreadEndpoint context.
2251
+ *
2252
+ * @param thread - The thread context from defineThreadEndpoint ({ instance, metadata })
2253
+ * @param params - The fields to update (agent_name, user_id, tags)
2254
+ * @returns The updated thread info, or null if update failed
2255
+ *
2256
+ * @example
2257
+ * ```typescript
2258
+ * import { defineThreadEndpoint, updateThread } from '@standardagents/builder';
2259
+ *
2260
+ * export default defineThreadEndpoint(async (req, thread) => {
2261
+ * // Update thread's user_id
2262
+ * await updateThread(thread, { user_id: 'user-123' });
2263
+ *
2264
+ * // Update thread's tags
2265
+ * await updateThread(thread, { tags: ['support', 'urgent'] });
2266
+ *
2267
+ * // Update multiple fields
2268
+ * const result = await updateThread(thread, {
2269
+ * agent_name: 'new-agent',
2270
+ * user_id: 'user-456',
2271
+ * tags: ['sales']
2272
+ * });
2273
+ *
2274
+ * return Response.json(result);
2275
+ * });
2276
+ * ```
2277
+ */
2278
+ declare function updateThread(thread: ThreadContext, params: {
2279
+ agent_name?: string;
2280
+ user_id?: string | null;
2281
+ tags?: string[] | null;
2282
+ }): Promise<{
2283
+ id: string;
2284
+ agent_id: string;
2285
+ user_id: string | null;
2286
+ tags: string[];
2287
+ created_at: number;
2288
+ } | null>;
2289
+ /**
2290
+ * Write a file to thread storage
2291
+ *
2292
+ * @param flow - The current FlowState
2293
+ * @param path - File path (e.g., "/images/photo.jpg")
2294
+ * @param data - File data as ArrayBuffer or string
2295
+ * @param mimeType - MIME type of the file
2296
+ * @param options - Optional metadata and thumbnail
2297
+ * @returns The created file record
2298
+ *
2299
+ * @example
2300
+ * ```typescript
2301
+ * import { writeFile } from '@standardagents/builder';
2302
+ *
2303
+ * // Write binary file
2304
+ * const imageData = new Uint8Array([...]);
2305
+ * await writeFile(flow, "/images/photo.jpg", imageData.buffer, "image/jpeg");
2306
+ *
2307
+ * // Write text file
2308
+ * await writeFile(flow, "/docs/readme.md", "# Hello", "text/markdown");
2309
+ * ```
2310
+ */
2311
+ declare function writeFile(flow: FlowState, path: string, data: ArrayBuffer | string, mimeType: string, options?: {
2312
+ metadata?: Record<string, unknown>;
2313
+ thumbnail?: ArrayBuffer;
2314
+ }): Promise<FileRecord>;
2315
+ /**
2316
+ * Write an image file with optional thumbnail
2317
+ *
2318
+ * @param flow - The current FlowState
2319
+ * @param path - File path
2320
+ * @param data - Image data as ArrayBuffer
2321
+ * @param mimeType - Image MIME type
2322
+ * @param options - Image metadata (width, height) and optional thumbnail
2323
+ * @returns The created file record
2324
+ *
2325
+ * @example
2326
+ * ```typescript
2327
+ * import { writeImage } from '@standardagents/builder';
2328
+ *
2329
+ * await writeImage(flow, "/images/photo.jpg", imageBuffer, "image/jpeg", {
2330
+ * metadata: { width: 1024, height: 768 },
2331
+ * thumbnail: thumbnailBuffer
2332
+ * });
2333
+ * ```
2334
+ */
2335
+ declare function writeImage(flow: FlowState, path: string, data: ArrayBuffer, mimeType: string, options?: {
2336
+ metadata?: {
2337
+ width: number;
2338
+ height: number;
2339
+ [key: string]: unknown;
2340
+ };
2341
+ thumbnail?: ArrayBuffer;
2342
+ }): Promise<FileRecord>;
2343
+ /**
2344
+ * Link to an external file (URL, S3, R2)
2345
+ *
2346
+ * Creates a file entry pointing to an external location without storing the data locally.
2347
+ *
2348
+ * @param flow - The current FlowState
2349
+ * @param path - File path in thread storage
2350
+ * @param location - External location (https://, s3://, r2://)
2351
+ * @param options - Optional MIME type, size, and metadata
2352
+ * @returns The created file record
2353
+ *
2354
+ * @example
2355
+ * ```typescript
2356
+ * import { linkFile } from '@standardagents/builder';
2357
+ *
2358
+ * // Link to a URL
2359
+ * await linkFile(flow, "/images/hero.jpg", "https://cdn.example.com/hero.jpg");
2360
+ *
2361
+ * // Link to S3
2362
+ * await linkFile(flow, "/data/large.csv", "s3://mybucket/data/large.csv", {
2363
+ * mimeType: "text/csv",
2364
+ * size: 10 * 1024 * 1024 * 1024 // 10GB
2365
+ * });
2366
+ * ```
2367
+ */
2368
+ declare function linkFile(flow: FlowState, path: string, location: string, options?: {
2369
+ mimeType?: string;
2370
+ size?: number;
2371
+ metadata?: Record<string, unknown>;
2372
+ }): Promise<FileRecord>;
2373
+ /**
2374
+ * Read a file from thread storage
2375
+ *
2376
+ * @param flow - The current FlowState
2377
+ * @param path - File path
2378
+ * @returns File data as ArrayBuffer, or null if not found/external
2379
+ *
2380
+ * @example
2381
+ * ```typescript
2382
+ * import { readFile } from '@standardagents/builder';
2383
+ *
2384
+ * const data = await readFile(flow, "/images/photo.jpg");
2385
+ * if (data) {
2386
+ * // Process binary data
2387
+ * }
2388
+ * ```
2389
+ */
2390
+ declare function readFile(flow: FlowState, path: string): Promise<ArrayBuffer | null>;
2391
+ /**
2392
+ * Get file metadata
2393
+ *
2394
+ * @param flow - The current FlowState
2395
+ * @param path - File path
2396
+ * @returns File record or null if not found
2397
+ *
2398
+ * @example
2399
+ * ```typescript
2400
+ * import { stat } from '@standardagents/builder';
2401
+ *
2402
+ * const file = await stat(flow, "/images/photo.jpg");
2403
+ * if (file) {
2404
+ * console.log(`Size: ${file.size}, Type: ${file.mimeType}`);
2405
+ * }
2406
+ * ```
2407
+ */
2408
+ declare function stat(flow: FlowState, path: string): Promise<FileRecord | null>;
2409
+ /**
2410
+ * Check if file or directory exists
2411
+ *
2412
+ * @param flow - The current FlowState
2413
+ * @param path - File path
2414
+ * @returns true if exists, false otherwise
2415
+ *
2416
+ * @example
2417
+ * ```typescript
2418
+ * import { exists } from '@standardagents/builder';
2419
+ *
2420
+ * if (await exists(flow, "/config.json")) {
2421
+ * // File exists
2422
+ * }
2423
+ * ```
2424
+ */
2425
+ declare function exists(flow: FlowState, path: string): Promise<boolean>;
2426
+ /**
2427
+ * Delete a file
2428
+ *
2429
+ * @param flow - The current FlowState
2430
+ * @param path - File path
2431
+ *
2432
+ * @example
2433
+ * ```typescript
2434
+ * import { unlink } from '@standardagents/builder';
2435
+ *
2436
+ * await unlink(flow, "/temp/draft.txt");
2437
+ * ```
2438
+ */
2439
+ declare function unlink(flow: FlowState, path: string): Promise<void>;
2440
+ /**
2441
+ * Create a directory
2442
+ *
2443
+ * @param flow - The current FlowState
2444
+ * @param path - Directory path
2445
+ * @returns The created directory record
2446
+ *
2447
+ * @example
2448
+ * ```typescript
2449
+ * import { mkdir } from '@standardagents/builder';
2450
+ *
2451
+ * await mkdir(flow, "/uploads/2024");
2452
+ * ```
2453
+ */
2454
+ declare function mkdir(flow: FlowState, path: string): Promise<FileRecord>;
2455
+ /**
2456
+ * List directory contents
2457
+ *
2458
+ * @param flow - The current FlowState
2459
+ * @param path - Directory path
2460
+ * @returns Array of file records in the directory
2461
+ *
2462
+ * @example
2463
+ * ```typescript
2464
+ * import { readdir } from '@standardagents/builder';
2465
+ *
2466
+ * const files = await readdir(flow, "/images");
2467
+ * for (const file of files) {
2468
+ * console.log(file.name, file.size);
2469
+ * }
2470
+ * ```
2471
+ */
2472
+ declare function readdir(flow: FlowState, path: string): Promise<FileRecord[]>;
2473
+ /**
2474
+ * Remove an empty directory
2475
+ *
2476
+ * @param flow - The current FlowState
2477
+ * @param path - Directory path
2478
+ *
2479
+ * @example
2480
+ * ```typescript
2481
+ * import { rmdir } from '@standardagents/builder';
2482
+ *
2483
+ * await rmdir(flow, "/temp");
2484
+ * ```
2485
+ */
2486
+ declare function rmdir(flow: FlowState, path: string): Promise<void>;
2487
+ /**
2488
+ * Get file storage statistics
2489
+ *
2490
+ * @param flow - The current FlowState
2491
+ * @returns Storage statistics (total size and file count)
2492
+ *
2493
+ * @example
2494
+ * ```typescript
2495
+ * import { getFileStats } from '@standardagents/builder';
2496
+ *
2497
+ * const stats = await getFileStats(flow);
2498
+ * console.log(`Total: ${stats.totalSize} bytes, Files: ${stats.fileCount}`);
2499
+ * ```
2500
+ */
2501
+ declare function getFileStats(flow: FlowState): Promise<FileStats>;
2502
+ /**
2503
+ * Get thumbnail for an image file
2504
+ *
2505
+ * @param flow - The current FlowState
2506
+ * @param path - Image file path
2507
+ * @returns Thumbnail data as ArrayBuffer, or null if not found
2508
+ *
2509
+ * @example
2510
+ * ```typescript
2511
+ * import { getThumbnail } from '@standardagents/builder';
2512
+ *
2513
+ * const thumb = await getThumbnail(flow, "/images/photo.jpg");
2514
+ * ```
2515
+ */
2516
+ declare function getThumbnail(flow: FlowState, path: string): Promise<ArrayBuffer | null>;
2517
+ /**
2518
+ * Read a text file as string
2519
+ *
2520
+ * @param flow - The current FlowState
2521
+ * @param path - File path
2522
+ * @returns File content as string, or null if not found
2523
+ *
2524
+ * @example
2525
+ * ```typescript
2526
+ * import { cat } from '@standardagents/builder';
2527
+ *
2528
+ * const content = await cat(flow, "/docs/readme.md");
2529
+ * ```
2530
+ */
2531
+ declare function cat(flow: FlowState, path: string): Promise<string | null>;
2532
+ /**
2533
+ * Read first N lines of a text file
2534
+ *
2535
+ * @param flow - The current FlowState
2536
+ * @param path - File path
2537
+ * @param lines - Number of lines to read (default: 10)
2538
+ * @returns First N lines as string, or null if not found
2539
+ *
2540
+ * @example
2541
+ * ```typescript
2542
+ * import { head } from '@standardagents/builder';
2543
+ *
2544
+ * const firstLines = await head(flow, "/logs/app.log", 20);
2545
+ * ```
2546
+ */
2547
+ declare function head(flow: FlowState, path: string, lines?: number): Promise<string | null>;
2548
+ /**
2549
+ * Read last N lines of a text file
2550
+ *
2551
+ * @param flow - The current FlowState
2552
+ * @param path - File path
2553
+ * @param lines - Number of lines to read (default: 10)
2554
+ * @returns Last N lines as string, or null if not found
2555
+ *
2556
+ * @example
2557
+ * ```typescript
2558
+ * import { tail } from '@standardagents/builder';
2559
+ *
2560
+ * const lastLines = await tail(flow, "/logs/app.log", 50);
2561
+ * ```
2562
+ */
2563
+ declare function tail(flow: FlowState, path: string, lines?: number): Promise<string | null>;
2564
+ /**
2565
+ * Search text file contents using FTS5 full-text search
2566
+ *
2567
+ * @param flow - The current FlowState
2568
+ * @param pattern - Search pattern (FTS5 syntax)
2569
+ * @param options - Search options
2570
+ * @returns Array of matching results with snippets
2571
+ *
2572
+ * @example
2573
+ * ```typescript
2574
+ * import { grep } from '@standardagents/builder';
2575
+ *
2576
+ * // Search all files
2577
+ * const results = await grep(flow, "error");
2578
+ *
2579
+ * // Search in specific directory
2580
+ * const results = await grep(flow, "TODO", { path: "/src" });
2581
+ * ```
2582
+ */
2583
+ declare function grep(flow: FlowState, pattern: string, options?: {
2584
+ path?: string;
2585
+ limit?: number;
2586
+ }): Promise<GrepResult[]>;
2587
+ /**
2588
+ * Find files by path pattern
2589
+ *
2590
+ * @param flow - The current FlowState
2591
+ * @param pattern - Glob-like pattern (e.g., "*.md", "/docs/subdir/*.txt")
2592
+ * @param options - Find options
2593
+ * @returns Array of matching file records
2594
+ *
2595
+ * @example
2596
+ * ```typescript
2597
+ * import { find } from '@standardagents/builder';
2598
+ *
2599
+ * // Find all markdown files
2600
+ * const mdFiles = await find(flow, "*.md");
2601
+ *
2602
+ * // Find all files in docs
2603
+ * const docFiles = await find(flow, "/docs/*", { type: "file" });
2604
+ * ```
2605
+ */
2606
+ declare function find(flow: FlowState, pattern: string, options?: {
2607
+ type?: "file" | "directory" | "all";
2608
+ limit?: number;
2609
+ }): Promise<FileRecord[]>;
2610
+
2611
+ /**
2612
+ * Options for injecting a message
2613
+ */
2614
+ interface InjectMessageOptions {
2615
+ /** The message content */
2616
+ content: string;
2617
+ /** The message role */
2618
+ role: "system" | "user" | "assistant" | "tool";
2619
+ /** Optional message ID. If not provided, a UUID will be generated */
2620
+ id?: string;
2621
+ /** Optional message to insert before. If not provided, message is appended to the end */
2622
+ beforeMessageId?: string;
2623
+ /** Optional tool call ID (for role="tool" only) */
2624
+ toolCallId?: string;
2625
+ /** Optional name field */
2626
+ name?: string;
2627
+ /** Whether this message is silent (hidden from LLM, visible in UI only). Default: false */
2628
+ silent?: boolean;
2629
+ /** Force message to be top-level (depth 0) even when called from sub-prompts. Default: false */
2630
+ forceTopLevel?: boolean;
2631
+ /** Force a specific side to play the next turn after injecting the message */
2632
+ forceTurn?: "side_a" | "side_b";
2633
+ }
2634
+ /**
2635
+ * Options for broadcasting custom data
2636
+ */
2637
+ interface BroadcastOptions {
2638
+ /** The type of the broadcast message */
2639
+ type: string;
2640
+ /** The value/payload of the broadcast message */
2641
+ value: unknown;
2642
+ }
2643
+ /**
2644
+ * FlowState SDK - Utility methods for working with FlowState
2645
+ *
2646
+ * These methods extend the FlowState object with helpful utilities for:
2647
+ * - Queuing tool calls
2648
+ * - Injecting messages
2649
+ * - Retrieving message history
2650
+ * - Broadcasting custom data via WebSocket
2651
+ */
2652
+ declare class FlowStateSdk {
2653
+ /**
2654
+ * Queue a new tool call to be executed in the current flow
2655
+ *
2656
+ * This adds a tool call to the execution queue without immediately executing it.
2657
+ * The tool will be executed as part of the normal flow processing.
2658
+ *
2659
+ * @param flow - The current FlowState
2660
+ * @param toolName - The name of the tool to call (autocompletes from available tools)
2661
+ * @param args - The arguments to pass to the tool
2662
+ *
2663
+ * @example
2664
+ * ```typescript
2665
+ * FlowStateSdk.queueTool(flow, "search_user", { email: "user@example.com" });
2666
+ * ```
2667
+ */
2668
+ static queueTool(flow: FlowState, toolName: StandardAgentSpec.Callables, args?: Record<string, unknown>): void;
2669
+ /**
2670
+ * Inject a message into the thread without triggering execution
2671
+ *
2672
+ * This allows you to add messages to the conversation history programmatically.
2673
+ * The message is persisted to storage but does not cause the agent to execute.
2674
+ *
2675
+ * By default, messages are appended to the end of the conversation.
2676
+ * You can optionally insert a message before another message by providing beforeMessageId.
2677
+ *
2678
+ * @param flow - The current FlowState
2679
+ * @param options - Message options
2680
+ *
2681
+ * @example
2682
+ * ```typescript
2683
+ * // Append a system message
2684
+ * await FlowStateSdk.injectMessage(flow, {
2685
+ * role: "system",
2686
+ * content: "Context has been updated"
2687
+ * });
2688
+ *
2689
+ * // Insert a user message before a specific message
2690
+ * await FlowStateSdk.injectMessage(flow, {
2691
+ * role: "user",
2692
+ * content: "Additional context",
2693
+ * beforeMessageId: "msg-123"
2694
+ * });
2695
+ *
2696
+ * // Inject a message and force a specific side to play next
2697
+ * await FlowStateSdk.injectMessage(flow, {
2698
+ * role: "system",
2699
+ * content: "New instructions for the AI",
2700
+ * forceTurn: "side_a" // Force side_a to respond to this message
2701
+ * });
2702
+ * ```
2703
+ */
2704
+ static injectMessage(flow: FlowState, options: InjectMessageOptions): Promise<Message>;
2705
+ /**
2706
+ * Get messages from the thread history
2707
+ *
2708
+ * Retrieves message history from the thread's SQLite storage.
2709
+ * Messages are ordered by creation time (oldest first by default).
2710
+ *
2711
+ * @param flow - The current FlowState
2712
+ * @param limit - Maximum number of messages to retrieve (default: 100)
2713
+ * @param offset - Number of messages to skip (default: 0)
2714
+ * @param order - Sort order: "asc" (oldest first) or "desc" (newest first) (default: "asc")
2715
+ * @returns Array of messages
2716
+ *
2717
+ * @example
2718
+ * ```typescript
2719
+ * // Get last 10 messages
2720
+ * const messages = await FlowStateSdk.getMessages(flow, 10);
2721
+ *
2722
+ * // Get 10 messages, skipping the first 20
2723
+ * const messages = await FlowStateSdk.getMessages(flow, 10, 20);
2724
+ *
2725
+ * // Get newest 10 messages
2726
+ * const messages = await FlowStateSdk.getMessages(flow, 10, 0, "desc");
2727
+ * ```
2728
+ */
2729
+ static getMessages(flow: FlowState, limit?: number, offset?: number, order?: "asc" | "desc"): Promise<Message[]>;
2730
+ /**
2731
+ * Reload message history from storage
2732
+ *
2733
+ * Re-loads the complete message history from the thread's SQLite storage,
2734
+ * applying any filter_messages hooks. This is useful when you need to refresh
2735
+ * the message history after making changes (e.g., injecting silent messages).
2736
+ *
2737
+ * @param flow - The current FlowState
2738
+ * @returns Array of messages (reloaded from storage)
2739
+ *
2740
+ * @example
2741
+ * ```typescript
2742
+ * // Reload history after injecting a silent message
2743
+ * await FlowStateSdk.injectMessage(flow, { role: "system", content: "...", silent: true });
2744
+ * flow.messageHistory = await FlowStateSdk.reloadHistory(flow);
2745
+ * ```
2746
+ */
2747
+ static reloadHistory(state: FlowState): Promise<Message[]>;
2748
+ /**
2749
+ * Broadcast custom data to WebSocket clients
2750
+ *
2751
+ * Sends a custom message to all connected WebSocket clients.
2752
+ * This allows backend code to push arbitrary data to the frontend
2753
+ * outside of the standard telemetry events.
2754
+ *
2755
+ * The message is sent with the structure: { type: string, value: unknown }
2756
+ *
2757
+ * @param flow - The current FlowState
2758
+ * @param options - Broadcast options
2759
+ *
2760
+ * @example
2761
+ * ```typescript
2762
+ * // Broadcast a progress update
2763
+ * FlowStateSdk.broadcast(flow, {
2764
+ * type: "progress",
2765
+ * value: { step: 3, total: 10, message: "Processing data..." }
2766
+ * });
2767
+ *
2768
+ * // Broadcast a custom notification
2769
+ * FlowStateSdk.broadcast(flow, {
2770
+ * type: "notification",
2771
+ * value: { level: "info", message: "User authenticated successfully" }
2772
+ * });
2773
+ *
2774
+ * // Broadcast metadata
2775
+ * FlowStateSdk.broadcast(flow, {
2776
+ * type: "metadata",
2777
+ * value: { userId: "123", sessionId: "abc", timestamp: Date.now() }
2778
+ * });
2779
+ * ```
2780
+ */
2781
+ static broadcast(flow: FlowState, options: BroadcastOptions): void;
2782
+ /**
2783
+ * Force a specific side to play the next turn
2784
+ *
2785
+ * This queues the specified side to play next without interrupting the current turn.
2786
+ * The forced turn only takes effect at the END of the current turn execution.
2787
+ *
2788
+ * If the tool queue is currently being processed (sequence.isHandling is true),
2789
+ * the forced turn is deferred until all queued tools complete. This allows patterns like:
2790
+ *
2791
+ * ```typescript
2792
+ * FlowStateSdk.queueTool(flow, 'myTool', {});
2793
+ * FlowStateSdk.forceTurn(flow, 'side_a');
2794
+ * // myTool executes first, THEN the turn switches to side_a
2795
+ * ```
2796
+ *
2797
+ * @param flow - The current FlowState
2798
+ * @param side - Which side should play next ('side_a' or 'side_b')
2799
+ *
2800
+ * @example
2801
+ * ```typescript
2802
+ * // Force current side to continue (override stop condition)
2803
+ * // If side_a is playing and would stop, this forces it to play at least 1 more turn
2804
+ * FlowStateSdk.forceTurn(flow, 'side_a');
2805
+ *
2806
+ * // Force switch to other side
2807
+ * // If side_a is playing, this forces side_b to play next turn
2808
+ * FlowStateSdk.forceTurn(flow, 'side_b');
2809
+ *
2810
+ * // Force human turn in ai_human agent (execution stops and waits for user input)
2811
+ * if (flow.agentConfig.type === 'ai_human') {
2812
+ * FlowStateSdk.forceTurn(flow, 'side_b'); // Stops execution, awaits user input
2813
+ * }
2814
+ * ```
2815
+ */
2816
+ static forceTurn(flow: FlowState, side: 'side_a' | 'side_b'): void;
2817
+ }
2818
+ /**
2819
+ * Convenience methods added to FlowState (optional - can be used via static methods above)
2820
+ *
2821
+ * These are helper methods that can be added to FlowState instances for convenience.
2822
+ * They delegate to the static methods above.
2823
+ */
2824
+ interface FlowStateWithSdk extends FlowState {
2825
+ queueTool: (toolName: StandardAgentSpec.Callables, args?: Record<string, unknown>) => void;
2826
+ injectMessage: (options: InjectMessageOptions) => Promise<Message>;
2827
+ getMessages: (limit?: number, offset?: number, order?: "asc" | "desc") => Promise<Message[]>;
2828
+ reloadHistory: () => Promise<Message[]>;
2829
+ broadcast: (options: BroadcastOptions) => void;
2830
+ forceTurn: (side: 'side_a' | 'side_b') => void;
2831
+ }
2832
+ /**
2833
+ * Enhance a FlowState object with SDK methods
2834
+ *
2835
+ * This adds convenience methods to a FlowState instance that delegate to
2836
+ * the static FlowStateSdk methods.
2837
+ *
2838
+ * @param flow - The FlowState to enhance
2839
+ * @returns The enhanced FlowState with SDK methods
2840
+ *
2841
+ * @example
2842
+ * ```typescript
2843
+ * const enhancedFlow = enhanceFlowState(flow);
2844
+ *
2845
+ * // Now you can use methods directly on the flow object
2846
+ * enhancedFlow.queueTool("search_user", { email: "user@example.com" });
2847
+ * await enhancedFlow.injectMessage({ role: "system", content: "Context updated" });
2848
+ * const messages = await enhancedFlow.getMessages(10);
2849
+ * flow.messageHistory = await enhancedFlow.reloadHistory();
2850
+ * enhancedFlow.broadcast({ type: "progress", value: { step: 1 } });
2851
+ * enhancedFlow.forceTurn('side_b'); // Force side_b to play next turn
2852
+ * ```
2853
+ */
2854
+ declare function enhanceFlowState(flow: FlowState): FlowStateWithSdk;
2855
+
2856
+ /**
2857
+ * Context Management for Image Attachments
2858
+ *
2859
+ * Handles auto-summarization of old images to reduce context window usage
2860
+ * while preserving the semantic meaning of image content.
2861
+ */
2862
+
2863
+ /**
2864
+ * Configuration for image context management
2865
+ */
2866
+ interface ImageContextConfig {
2867
+ /** Number of recent messages to keep images for (default: 10) */
2868
+ recentMessageThreshold: number;
2869
+ /** System prompt for generating image descriptions */
2870
+ descriptionPrompt: string;
2871
+ }
2872
+ /**
2873
+ * Check if a message has image attachments that could be summarized
2874
+ */
2875
+ declare function hasImageAttachments(message: Message): boolean;
2876
+ /**
2877
+ * Get image attachments from a message that don't have descriptions yet
2878
+ */
2879
+ declare function getUnsummarizedImageAttachments(message: Message): AttachmentRef[];
2880
+ /**
2881
+ * Determine which messages should have their images replaced with descriptions.
2882
+ * Returns indices of messages that are old enough to be summarized.
2883
+ */
2884
+ declare function getMessagesToSummarize(messages: Message[], config?: ImageContextConfig): number[];
2885
+ /**
2886
+ * Build text representation for an image attachment (used when image is too old)
2887
+ */
2888
+ declare function buildImageDescription(attachment: AttachmentRef): string;
2889
+ /**
2890
+ * Transform message content to replace old images with text descriptions.
2891
+ * This modifies the content array for LLM context building.
2892
+ */
2893
+ declare function replaceImagesWithDescriptions(content: MessageContent, attachments: AttachmentRef[]): MessageContent;
2894
+ /**
2895
+ * Process message history to optimize context window usage.
2896
+ * Old images are replaced with their text descriptions.
2897
+ *
2898
+ * @param messages - Full message history
2899
+ * @param config - Context management configuration
2900
+ * @returns Processed messages with old images replaced by descriptions
2901
+ */
2902
+ declare function optimizeImageContext(messages: Message[], config?: ImageContextConfig): Message[];
2903
+ /**
2904
+ * Generate a description for an image using a vision model.
2905
+ * This should be called when storing new messages with images.
2906
+ *
2907
+ * Note: This function is a placeholder for the actual LLM call.
2908
+ * The actual implementation would need to make an API call to a vision model.
2909
+ *
2910
+ * @param imageBase64 - Base64-encoded image data
2911
+ * @param mimeType - MIME type of the image
2912
+ * @param state - Flow state for LLM access
2913
+ * @returns Generated description
2914
+ */
2915
+ declare function generateImageDescription(_imageBase64: string, _mimeType: string, _state: FlowState): Promise<string | null>;
2916
+
2917
+ /** @public Alias for LLMProviderInterface */
2918
+ type Provider = LLMProviderInterface;
2919
+ /** @public Alias for ContentPart */
2920
+ type ProviderContentPart = ContentPart;
2921
+ /** @public Alias for TextPart */
2922
+ type ProviderTextPart = TextPart;
2923
+ /** @public Alias for ImagePart */
2924
+ type ProviderImagePart = ImagePart;
2925
+ /** @public Alias for FilePart */
2926
+ type ProviderFilePart = FilePart;
2927
+
2928
+ /**
2929
+ * Function that can intercept provider creation.
2930
+ * Returns a provider to override the default, or null to fall through.
2931
+ */
2932
+ type ProviderOverrideFn = (modelName: string, modelDef: ModelDefinition$1<string>, env: Env) => LLMProviderInterface | null;
2933
+ /**
2934
+ * Provider registry implementation
2935
+ *
2936
+ * Models must use ProviderFactory functions imported from provider packages
2937
+ * (e.g., @standardagents/openai, @standardagents/openrouter).
2938
+ *
2939
+ * Loads model configs from TypeScript virtual modules and
2940
+ * provider API keys from environment variables.
2941
+ */
2942
+ declare class ProviderRegistryImpl {
2943
+ private providerCache;
2944
+ private providerOverrideFn;
2945
+ private providerOverrideRevision;
2946
+ setProviderOverride(fn: ProviderOverrideFn | null): void;
2947
+ /**
2948
+ * Get provider for a model.
2949
+ *
2950
+ * Models must use ProviderFactory functions (imported from provider packages).
2951
+ *
2952
+ * @param modelName - The model name (from TypeScript config)
2953
+ * @param env - Environment bindings
2954
+ * @param thread - Thread instance for loading model from virtual modules
2955
+ * @returns Provider and model definition
2956
+ */
2957
+ getProvider(modelName: string, env: Env, thread?: ThreadInstance): Promise<{
2958
+ provider: LLMProviderInterface;
2959
+ modelName: string;
2960
+ modelDef: ModelDefinition$1<string>;
2961
+ }>;
2962
+ private buildResult;
2963
+ private cacheAndReturn;
2964
+ private getProviderFingerprint;
2965
+ /**
2966
+ * Get API key for a provider from environment variables.
2967
+ */
2968
+ private getApiKeyForProvider;
2969
+ /**
2970
+ * Clear the provider cache
2971
+ * Useful for testing or when configurations change
2972
+ */
2973
+ clearCache(): void;
2974
+ }
2975
+ /**
2976
+ * Singleton instance
2977
+ */
2978
+ declare const ProviderRegistry: ProviderRegistryImpl;
2979
+
2980
+ /**
2981
+ * Namespace-scoped resolution for the packing system.
2982
+ *
2983
+ * This module provides functions to resolve items (tools, prompts, models, agents)
2984
+ * within the correct namespace context, enforcing isolation between packed and
2985
+ * unpacked code.
2986
+ *
2987
+ * @module
2988
+ */
2989
+
2990
+ /**
2991
+ * Error thrown when an item cannot be resolved in the current namespace.
2992
+ */
2993
+ declare class NamespaceResolutionError extends Error {
2994
+ readonly itemType: 'tool' | 'prompt' | 'model' | 'agent' | 'hook';
2995
+ readonly itemName: string;
2996
+ readonly namespace: NamespaceContext;
2997
+ constructor(itemType: 'tool' | 'prompt' | 'model' | 'agent' | 'hook', itemName: string, namespace: NamespaceContext, message: string);
2998
+ }
2999
+ /**
3000
+ * Parse a potentially qualified name into package ID and short name.
3001
+ *
3002
+ * For scoped npm packages (starting with @), the format is @scope/pkg-name/item-name
3003
+ * where @scope/pkg-name is the package and item-name is the short name.
3004
+ *
3005
+ * For non-scoped packages, the format is pkg-name/item-name.
3006
+ *
3007
+ * @param name - The name to parse (e.g., 'tool', 'pkg/tool', or '@scope/pkg/tool')
3008
+ * @returns Tuple of [packageId, shortName] where packageId is null for unqualified names
3009
+ */
3010
+ declare function parseQualifiedName(name: string): [string | null, string];
3011
+ /**
3012
+ * Create a qualified name from package ID and short name.
3013
+ */
3014
+ declare function qualifyName(packageId: string, shortName: string): string;
3015
+ /**
3016
+ * Get the short name (strip any package qualification).
3017
+ */
3018
+ declare function getShortName(name: string): string;
3019
+ /**
3020
+ * Resolve a tool by name within a namespace context.
3021
+ *
3022
+ * Resolution rules:
3023
+ * - Qualified names (pkg:tool) → resolve cross-package entry point
3024
+ * - Unqualified names in packed context → resolve from own package
3025
+ * - Unqualified names in global context → resolve from global namespace
3026
+ *
3027
+ * @param registry - The namespaced registry
3028
+ * @param name - Tool name (can be qualified with packageId:toolName)
3029
+ * @param namespace - Current namespace context
3030
+ * @returns Loader function for the tool definition
3031
+ * @throws NamespaceResolutionError if tool cannot be found or accessed
3032
+ */
3033
+ declare function resolveTool(registry: NamespacedRegistry, name: string, namespace: NamespaceContext): DefinitionLoader<unknown>;
3034
+ /**
3035
+ * Resolve a prompt by name within a namespace context.
3036
+ *
3037
+ * @param registry - The namespaced registry
3038
+ * @param name - Prompt name (can be qualified)
3039
+ * @param namespace - Current namespace context
3040
+ * @returns Loader function for the prompt definition
3041
+ */
3042
+ declare function resolvePrompt(registry: NamespacedRegistry, name: string, namespace: NamespaceContext): DefinitionLoader<unknown>;
3043
+ /**
3044
+ * Resolve a model by name within a namespace context.
3045
+ *
3046
+ * Models are special: packed agents include their model definitions,
3047
+ * but the host must provide API keys.
3048
+ *
3049
+ * @param registry - The namespaced registry
3050
+ * @param name - Model name
3051
+ * @param namespace - Current namespace context
3052
+ * @returns Loader function for the model definition
3053
+ */
3054
+ declare function resolveModel(registry: NamespacedRegistry, name: string, namespace: NamespaceContext): DefinitionLoader<unknown>;
3055
+ /**
3056
+ * Resolve an agent by name within a namespace context.
3057
+ *
3058
+ * Resolution rules:
3059
+ * - Qualified names (pkg:agent) → resolve cross-package entry point
3060
+ * - Unqualified in packed → resolve from own package
3061
+ * - Unqualified in global → resolve from global + entry points
3062
+ *
3063
+ * @param registry - The namespaced registry
3064
+ * @param name - Agent name (can be qualified)
3065
+ * @param namespace - Current namespace context
3066
+ * @returns Loader function for the agent definition
3067
+ */
3068
+ declare function resolveAgent(registry: NamespacedRegistry, name: string, namespace: NamespaceContext): DefinitionLoader<unknown>;
3069
+ /**
3070
+ * Resolve a hook by name within a namespace context.
3071
+ *
3072
+ * Hooks follow similar rules to tools but are keyed by hook type.
3073
+ *
3074
+ * @param registry - The namespaced registry
3075
+ * @param name - Hook name (file name, e.g., 'filter_messages')
3076
+ * @param namespace - Current namespace context
3077
+ * @returns Loader function for the hook implementation
3078
+ */
3079
+ declare function resolveHook(registry: NamespacedRegistry, name: string, namespace: NamespaceContext): DefinitionLoader<unknown> | null;
3080
+ /**
3081
+ * Get all tool names visible in a namespace context.
3082
+ *
3083
+ * @param registry - The namespaced registry
3084
+ * @param namespace - Current namespace context
3085
+ * @returns Array of visible tool names (short names)
3086
+ */
3087
+ declare function getVisibleToolNames(registry: NamespacedRegistry, namespace: NamespaceContext): string[];
3088
+ /**
3089
+ * Get all agent names visible in a namespace context.
3090
+ *
3091
+ * @param registry - The namespaced registry
3092
+ * @param namespace - Current namespace context
3093
+ * @returns Array of visible agent names (may include qualified names for cross-package)
3094
+ */
3095
+ declare function getVisibleAgentNames(registry: NamespacedRegistry, namespace: NamespaceContext): string[];
3096
+ /**
3097
+ * Get all prompt names visible in a namespace context.
3098
+ */
3099
+ declare function getVisiblePromptNames(registry: NamespacedRegistry, namespace: NamespaceContext): string[];
3100
+ /**
3101
+ * Get all model names visible in a namespace context.
3102
+ */
3103
+ declare function getVisibleModelNames(registry: NamespacedRegistry, namespace: NamespaceContext): string[];
3104
+ /**
3105
+ * Create a namespace context for an agent definition.
3106
+ *
3107
+ * @param agentDef - Agent definition (may have __package field)
3108
+ * @returns Appropriate namespace context
3109
+ */
3110
+ declare function createNamespaceContext(agentDef: {
3111
+ __package?: {
3112
+ packageId: string;
3113
+ };
3114
+ } | undefined): NamespaceContext;
3115
+ /**
3116
+ * Check if a name is qualified (contains package prefix).
3117
+ *
3118
+ * For scoped packages (@scope/name), there must be at least two slashes
3119
+ * to be considered qualified (e.g., @scope/pkg/item).
3120
+ * For non-scoped packages, a single slash qualifies it (e.g., pkg/item).
3121
+ */
3122
+ declare function isQualifiedName(name: string): boolean;
3123
+
3124
+ export { type AgentBuilderEnv, type AgentDefinition, AttachmentRef, type AuthContext, type AuthUser, type BroadcastOptions, CodeExecutionBridge, DurableAgentBuilder, DurableThread, Env, FileRecord, FileStats, FlowState, FlowStateSdk, type FlowStateWithSdk, GrepResult, type ImageContextConfig, type InjectMessageOptions$1 as InjectMessageOptions, type Provider as LLMProviderInterface, Message, MessageContent, type ModelDefinition, NamespaceResolutionError, NamespacedRegistry, type PromptContent, type PromptDefinition, type PromptIncludePart, type PromptPart, type PromptToolConfig, type Provider$1 as Provider, type ProviderContentPart, type ProviderFilePart, type ProviderImagePart, ProviderRegistry, type ProviderTextPart, type SessionToolBinding, type SessionToolConfig, type SideConfig, type SubagentToolConfig, type SubpromptConfig, ThreadEnv, ThreadInstance, ThreadMetadata, type ThreadRegistryEntry, type ToolConfig, type UpdateThreadParams, type User, authenticate, buildImageDescription, cat, createNamespaceContext, emitThreadEvent, enhanceFlowState, exists, find, forceTurn, generateImageDescription, getFileStats, getMessages, getMessagesToSummarize, getShortName, getThumbnail, getUnsummarizedImageAttachments, getVisibleAgentNames, getVisibleModelNames, getVisiblePromptNames, getVisibleToolNames, grep, hasImageAttachments, head, injectMessage, isQualifiedName, linkFile, mkdir, optimizeImageContext, parseQualifiedName, qualifyName, queueTool, readFile, readdir, reloadHistory, replaceImagesWithDescriptions, requireAdmin, requireAuth, resolveAgent, resolveHook, resolveModel, resolvePrompt, resolveTool, rmdir, stat, tail, unlink, updateThread, writeFile, writeImage };