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