@standardagents/builder 0.41.7 → 0.41.8

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.
@@ -0,0 +1,4522 @@
1
+ import { i as AuthContext, b as ThreadEnv, v as Agent, x as ThreadMetadata, z as ToolResult, M as Message, n as ClientToolRequest, o as ClientToolResponse, V as ProxyStreamReceiver, W as ProxyStreamFrame, p as ClientStreamRequest, X as ProxyStreamTarget, q as ClientStreamResponse, Y as ProxyStreamOpenResult, H as FileRecord, Z as SkillStorageScope, F as FlowState, N as FileStats, K as GrepResult, J as AttachmentRef, U as MessageContent, G as Env, w as ThreadInstance } from './index-ChHAVogf.js';
2
+ import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';
3
+ import { CodeExecutionOptions, CodeExecutionResult, SubagentRegistryEntry, InjectMessageInput, QueueMessageInput, CredentialGrant, SkillMetadata, SkillFileInput, ModelDefinition as ModelDefinition$1, ToolArgs, PromptTextPart, PromptEnvPart, VariableDefinition, SubpromptConfig as SubpromptConfig$1, PromptToolConfig as PromptToolConfig$1, ReasoningConfig, HumanSide as HumanSide$1, SubagentRelationship as SubagentRelationship$1, ParentHookRequirement, LLMProviderInterface, ContentPart, TextPart, ImagePart, FilePart, ThreadState, NamespaceContext, DefinitionLoader } from '@standardagents/spec';
4
+ import { N as NamespacedRegistry } from './types-Dhd0M369.js';
5
+
6
+ /**
7
+ * Global namespace for AgentBuilder types.
8
+ *
9
+ * This namespace provides type-safe references for models, prompts, agents, and tools.
10
+ * Types are automatically populated when you run `pnpm dev` or `pnpm build`,
11
+ * which scans your `agentbuilder/` directories and generates types.
12
+ *
13
+ * The generated types are placed in `.agents/types.d.ts` and augment the
14
+ * StandardAgentSpec namespace from @standardagents/spec.
15
+ *
16
+ * Note: This namespace is provided for backward compatibility. New code should
17
+ * use StandardAgentSpec types directly, which are defined in @standardagents/spec.
18
+ *
19
+ * @deprecated Use StandardAgentSpec namespace from @standardagents/spec instead
20
+ */
21
+ declare global {
22
+ namespace AgentBuilder {
23
+ /**
24
+ * Interface for model type registration.
25
+ * @deprecated Use StandardAgentSpec.ModelRegistry instead
26
+ */
27
+ interface ModelRegistry extends StandardAgentSpec.ModelRegistry {
28
+ }
29
+ /**
30
+ * Interface for prompt type registration.
31
+ * @deprecated Use StandardAgentSpec.PromptRegistry instead
32
+ */
33
+ interface PromptRegistry extends StandardAgentSpec.PromptRegistry {
34
+ }
35
+ /**
36
+ * Interface for agent type registration.
37
+ * @deprecated Use StandardAgentSpec.AgentRegistry instead
38
+ */
39
+ interface AgentRegistry extends StandardAgentSpec.AgentRegistry {
40
+ }
41
+ /**
42
+ * Interface for tool type registration.
43
+ * @deprecated Use StandardAgentSpec.ToolRegistry instead
44
+ */
45
+ interface ToolRegistry extends StandardAgentSpec.ToolRegistry {
46
+ }
47
+ /**
48
+ * Interface for callable type registration (prompts, agents, tools).
49
+ * @deprecated Use StandardAgentSpec.CallableRegistry instead
50
+ */
51
+ interface CallableRegistry extends StandardAgentSpec.CallableRegistry {
52
+ }
53
+ /**
54
+ * Union type of all model names defined in agentbuilder/models/.
55
+ * @deprecated Use StandardAgentSpec.Models instead
56
+ */
57
+ type Models = StandardAgentSpec.Models;
58
+ /**
59
+ * Union type of all prompt names defined in agentbuilder/prompts/.
60
+ * @deprecated Use StandardAgentSpec.Prompts instead
61
+ */
62
+ type Prompts = StandardAgentSpec.Prompts;
63
+ /**
64
+ * Union type of all agent names defined in agentbuilder/agents/.
65
+ * @deprecated Use StandardAgentSpec.Agents instead
66
+ */
67
+ type Agents = StandardAgentSpec.Agents;
68
+ /**
69
+ * Union type of all tool names defined in agentbuilder/tools/.
70
+ * @deprecated Use StandardAgentSpec.Tools instead
71
+ */
72
+ type Tools = StandardAgentSpec.Tools;
73
+ /**
74
+ * Union type of all callable items (prompts, agents, tools) that can be used as tools.
75
+ * @deprecated Use StandardAgentSpec.Callables instead
76
+ */
77
+ type Callables = StandardAgentSpec.Callables;
78
+ /**
79
+ * Interface for hook ID registration.
80
+ * @deprecated Use StandardAgentSpec.HookIdRegistry instead
81
+ */
82
+ interface HookIdRegistry extends StandardAgentSpec.HookIdRegistry {
83
+ }
84
+ /**
85
+ * Union type of all hook IDs defined in agents/hooks/.
86
+ * @deprecated Use StandardAgentSpec.HookIds instead
87
+ */
88
+ type Hooks = StandardAgentSpec.HookIds;
89
+ /**
90
+ * Interface for handler name registration.
91
+ * @deprecated Use StandardAgentSpec.HandlerRegistry instead
92
+ */
93
+ interface HandlerRegistry extends StandardAgentSpec.HandlerRegistry {
94
+ }
95
+ /**
96
+ * Union type of all handler names defined in agents/handlers/.
97
+ * @deprecated Use StandardAgentSpec.Handlers instead
98
+ */
99
+ type Handlers = StandardAgentSpec.Handlers;
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Permissions utility for role-based access control
105
+ *
106
+ * Current behavior:
107
+ * - Admin role can do everything (early return true)
108
+ * - Other roles only get baseline access (own threads)
109
+ *
110
+ * The `can()` function checks arbitrary permission strings.
111
+ * Currently, non-admin users have no explicit permissions,
112
+ * meaning they rely on ownership checks for access.
113
+ */
114
+
115
+ /**
116
+ * Check if a user can access a specific thread
117
+ *
118
+ * @param auth - The authenticated user context
119
+ * @param thread - The thread to check access for (must have user_id)
120
+ * @returns true if the user can access the thread
121
+ */
122
+ declare function canAccessThread(auth: AuthContext, thread: {
123
+ user_id: string | null;
124
+ }): boolean;
125
+
126
+ /** Central API exposure policy shared by the generated Worker router and tests. */
127
+ declare function isHostedInstance(env: unknown): boolean;
128
+ /**
129
+ * Local-only conveniences are enabled by the request destination, not merely
130
+ * by the absence of a deployment flag. This makes an incorrectly configured
131
+ * internet-facing Worker fail closed while preserving localhost and OrbStack.
132
+ */
133
+ declare function isTrustedLocalDevelopmentRequest(request: Request, env: Record<string, unknown> | undefined, trustedDevHosts?: readonly string[]): boolean;
134
+ declare function isPublicApiRoute(routePath: string, request: Request, env: Record<string, unknown> | undefined): boolean;
135
+ /**
136
+ * Reject browser requests initiated by another origin. Requests without
137
+ * browser provenance headers remain available to local CLI/test clients; they
138
+ * still need the normal route credential once bootstrap has completed.
139
+ *
140
+ * `Sec-Fetch-Site: same-origin` is a forbidden header, so a real browser that
141
+ * sends it is attesting same-origin even when a local reverse proxy rewrote
142
+ * `request.url`. Page JavaScript cannot forge that header.
143
+ */
144
+ declare function isSameOriginBrowserRequest(request: Request): boolean;
145
+ /** Instance-global authoring and package-management surfaces are admin-only. */
146
+ declare function isAdminOnlyApiRoute(routePath: string, method?: string): boolean;
147
+
148
+ declare function runtimeCorsHeaders(request: Request, env: Record<string, unknown> | undefined): Record<string, string>;
149
+ declare function applyRuntimeCors(response: Response, request: Request, env: Record<string, unknown> | undefined): Response;
150
+ declare function runtimePreflightResponse(request: Request, env: Record<string, unknown> | undefined): Response;
151
+
152
+ type AlarmQueueStatus = "pending" | "processing" | "completed" | "failed" | "agent_canceled" | "user_canceled";
153
+ type EffectCancelSource = "agent" | "user";
154
+ interface EffectRunRecord {
155
+ id: string;
156
+ name: string;
157
+ args: Record<string, unknown>;
158
+ scheduledAt: number;
159
+ createdAt: number;
160
+ status: AlarmQueueStatus;
161
+ attempts: number;
162
+ error: string | null;
163
+ completedAt: number | null;
164
+ manualRun: boolean;
165
+ manualRunAt: number | null;
166
+ replayedFrom: string | null;
167
+ }
168
+ interface EffectRunListOptions {
169
+ limit?: number;
170
+ offset?: number;
171
+ }
172
+ interface EffectRunListResult {
173
+ effects: EffectRunRecord[];
174
+ total: number;
175
+ upcomingCount: number;
176
+ limit: number;
177
+ offset: number;
178
+ }
179
+ interface EffectRunActionResult {
180
+ action: "ran" | "replayed";
181
+ id: string;
182
+ replayedId?: string;
183
+ }
184
+
185
+ interface RuntimeSafetyStatus {
186
+ state: 'active' | 'quarantined';
187
+ reason: string | null;
188
+ source: string | null;
189
+ trippedAt: number | null;
190
+ resumedAt: number | null;
191
+ forensicHold: boolean;
192
+ lastActionId: string | null;
193
+ observed: Record<string, number>;
194
+ }
195
+ interface RuntimeQuarantineInput {
196
+ actionId: string;
197
+ reason: string;
198
+ source?: string;
199
+ forensicHold?: boolean;
200
+ observed?: Record<string, number>;
201
+ }
202
+
203
+ interface CodeExecutionBridgeRegistration {
204
+ call(functionId: string, encodedArgs: unknown[]): Promise<unknown>;
205
+ }
206
+
207
+ declare const INTERNAL_TOOL_DELIVERY: unique symbol;
208
+ type ThreadEndpointCodeOptions = Pick<CodeExecutionOptions, "language" | "filename" | "execute" | "modules" | "memoryLimitBytes">;
209
+ /**
210
+ * Result of one watchdog assessment (see performWatchdogAssessment). Returned
211
+ * to whichever delivery invoked it — the internal alarm check, the
212
+ * ThreadWatchdog companion probe, or the diagnostics revive endpoint — so the
213
+ * caller can schedule/record without re-deriving thread state.
214
+ */
215
+ interface WatchdogProbeResult {
216
+ /** What the thread looked like, after any recovery action taken. */
217
+ verdict: "healthy" | "observing" | "recovered" | "parked" | "idle";
218
+ /** The recovery action performed (all actions are already done on return). */
219
+ action: "none" | "finalized_resumed" | "finalized_parked" | "finalized_deferred" | "aborted_takeover_resumed";
220
+ executing: boolean;
221
+ incompleteLogs: number;
222
+ queuedMessages: number;
223
+ /** Milliseconds since the last execution heartbeat; null when unknown/∞. */
224
+ silenceMs: number | null;
225
+ ceilingMs: number;
226
+ strikes: number;
227
+ /**
228
+ * True when a live-but-wedged executor was taken over: the zombie turn may
229
+ * still own this DO's alarm invocation, so the caller should force a
230
+ * restart (ThreadWatchdog calls forceRestart()) to free the alarm chain.
231
+ */
232
+ requestRestart: boolean;
233
+ }
234
+ declare class DurableThread<Env extends ThreadEnv = ThreadEnv> extends DurableObject<Env> {
235
+ private migratedToVersion;
236
+ private logSockets;
237
+ private messageSockets;
238
+ private bridgeSockets;
239
+ private bridgeLastSeen;
240
+ private bridgeClientInfo;
241
+ private executionOwnerCache;
242
+ private pendingClientCalls;
243
+ private clientStreams;
244
+ private proxyStreamReceivers;
245
+ private eventProxyStreams;
246
+ private alarmQueue;
247
+ private runtimeSafety;
248
+ private alarmQueueRearmed;
249
+ private currentAbortController;
250
+ private isExecuting;
251
+ /**
252
+ * In-memory waiters parked until the running flow finishes (AB-09): the
253
+ * executeFlow busy-guard awaits this signal instead of re-checking
254
+ * isExecuting every 500ms. Every isExecuting=false transition (execution
255
+ * finallys and the watchdog takeover) notifies. In-memory only — a DO
256
+ * restart drops waiters together with the busy caller.
257
+ */
258
+ private executionIdleWaiters;
259
+ private notifyExecutionIdleWaiters;
260
+ private lastProgressAt;
261
+ private watchdogWedgeStrikes;
262
+ private readonly watchdogIntervalMs;
263
+ private readonly watchdogResumeWindowMs;
264
+ private readonly watchdogMaxResumesPerWindow;
265
+ private codeExecutionBridges;
266
+ constructor(ctx: DurableObjectState, env: Env);
267
+ /**
268
+ * Returns the tools registry for this thread.
269
+ * This method is implemented when you import DurableThread from 'virtual:@standardagents/builder'.
270
+ *
271
+ * @throws Error if not implemented in a subclass
272
+ * @returns Record of tool name to tool loader function
273
+ *
274
+ * @example
275
+ * ```typescript
276
+ * import { DurableThread } from 'virtual:@standardagents/builder'
277
+ *
278
+ * export class Thread extends DurableThread {}
279
+ * ```
280
+ */
281
+ tools(): Record<string, () => Promise<any>>;
282
+ /**
283
+ * Returns the hooks registry for this thread.
284
+ * This method is implemented when you import DurableThread from 'virtual:@standardagents/builder'.
285
+ *
286
+ * @throws Error if not implemented in a subclass
287
+ * @returns Record of hook name to hook loader function
288
+ *
289
+ * @example
290
+ * ```typescript
291
+ * import { DurableThread } from 'virtual:@standardagents/builder'
292
+ *
293
+ * export class Thread extends DurableThread {}
294
+ * ```
295
+ */
296
+ hooks(): Record<string, () => Promise<any>>;
297
+ /**
298
+ * Returns the models registry for lazy-loading model definitions.
299
+ * This method is implemented when you import DurableThread from 'virtual:@standardagents/builder'.
300
+ *
301
+ * @throws Error if not implemented in a subclass
302
+ * @returns Record of model name to model loader function
303
+ */
304
+ models(): Record<string, () => Promise<any>>;
305
+ /**
306
+ * Returns the prompts registry for lazy-loading prompt definitions.
307
+ * This method is implemented when you import DurableThread from 'virtual:@standardagents/builder'.
308
+ *
309
+ * @throws Error if not implemented in a subclass
310
+ * @returns Record of prompt name to prompt loader function
311
+ */
312
+ prompts(): Record<string, () => Promise<any>>;
313
+ /**
314
+ * Returns the agents registry for lazy-loading agent definitions.
315
+ * This method is implemented when you import DurableThread from 'virtual:@standardagents/builder'.
316
+ *
317
+ * @throws Error if not implemented in a subclass
318
+ * @returns Record of agent name to agent loader function
319
+ */
320
+ agents(): Record<string, () => Promise<any>>;
321
+ /**
322
+ * Returns the effects registry for lazy-loading effect definitions.
323
+ * This method is implemented when you import DurableThread from 'virtual:@standardagents/builder'.
324
+ *
325
+ * Effects are scheduled operations that run outside the tool execution context,
326
+ * ideal for delayed notifications, webhooks, and cleanup tasks.
327
+ *
328
+ * @throws Error if not implemented in a subclass
329
+ * @returns Record of effect name to effect loader function
330
+ */
331
+ effects(): Record<string, () => Promise<any>>;
332
+ /**
333
+ * Returns available handler loaders from the agents/handlers/ directory.
334
+ * This method is implemented when you import DurableThread from 'virtual:@standardagents/builder'.
335
+ *
336
+ * Handlers are deterministic code that backs one side of an agent and takes
337
+ * that side's turns in place of a model.
338
+ *
339
+ * @returns Record of handler name to handler loader function
340
+ */
341
+ handlers(): Record<string, () => Promise<any>>;
342
+ /**
343
+ * Returns the namespaced registry for packed agent support.
344
+ * This method is implemented when you import DurableThread from 'virtual:@standardagents/builder'.
345
+ *
346
+ * @throws Error if not implemented in a subclass
347
+ * @returns The namespaced registry with global and packages namespaces
348
+ */
349
+ registry(): any;
350
+ /**
351
+ * Load a model definition by name.
352
+ * Supports both global models and packed models (e.g., "packageId/modelName").
353
+ * For scoped packages, use "@scope/pkg/modelName".
354
+ * For packed context, tries package first then falls back to global.
355
+ */
356
+ loadModel(name: string): Promise<any>;
357
+ /**
358
+ * List available model names.
359
+ */
360
+ getModelNames(): string[];
361
+ /**
362
+ * Load a prompt definition by name.
363
+ * Supports both global prompts (e.g., "my-prompt") and packed prompts (e.g., "packageId/promptName").
364
+ */
365
+ loadPrompt(name: string): Promise<any>;
366
+ /**
367
+ * A prompt whose tools array still carries a 0.1.0 SubagentToolConfig is a
368
+ * LOAD error — there is no compatibility window, and the boot failure is
369
+ * the migration UX. Relationship declarations live on the owning agent
370
+ * side's subagents array.
371
+ */
372
+ static rejectLegacyPromptSubagentTools(promptDef: any, promptName: string): any;
373
+ /**
374
+ * List available prompt names.
375
+ */
376
+ getPromptNames(): string[];
377
+ /**
378
+ * Load an agent definition by name.
379
+ * Supports both global agents (e.g., "my-agent") and packed agents (e.g., "packageId/agentName").
380
+ * For scoped packages, use "@scope/pkg/agentName".
381
+ */
382
+ loadAgent(name: string): Promise<any>;
383
+ /**
384
+ * Convert a raw agent definition (defineAgent) into the runtime `Agent` config
385
+ * FlowEngine expects: maps `sideA/sideB.prompt` → `side_a/b_agent_prompt`,
386
+ * resolves session-tool bindings, and qualifies prompt names for packed
387
+ * agents. The execution entrypoints build this inline; this method is the
388
+ * shared path for code that resolves an agent OUTSIDE a live execution (e.g.
389
+ * `ThreadState.invokeTool()` from a thread endpoint), so the two can't drift
390
+ * (a raw def has no `side_a_agent_prompt`).
391
+ */
392
+ static buildAgentConfig(agentDef: any, agentName: string): Agent;
393
+ /**
394
+ * Load an agent by name AND convert it to the runtime `Agent` config (see
395
+ * `buildAgentConfig`). Used by `ThreadState.invokeTool()` when firing a tool
396
+ * outside an active execution, so the assembled state has a real
397
+ * `side_a_agent_prompt` instead of the raw definition's `sideA.prompt`.
398
+ */
399
+ loadAgentConfig(name: string): Promise<Agent>;
400
+ /**
401
+ * List available agent names.
402
+ */
403
+ getAgentNames(): string[];
404
+ /**
405
+ * Load a handler definition by name.
406
+ * Supports packed handlers via qualified names ("packageId/handlerName").
407
+ */
408
+ loadHandler(name: string): Promise<any>;
409
+ /**
410
+ * List available handler names.
411
+ */
412
+ getHandlerNames(): string[];
413
+ /**
414
+ * Load an effect definition by name.
415
+ */
416
+ loadEffect(name: string): Promise<any>;
417
+ /**
418
+ * List available effect names.
419
+ */
420
+ getEffectNames(): string[];
421
+ /**
422
+ * Load a tool definition by name.
423
+ * Supports both global tools (e.g., "my_tool") and packed tools (e.g., "packageId/toolName").
424
+ */
425
+ loadTool(name: string): Promise<any>;
426
+ /**
427
+ * Get thread metadata from DurableAgentBuilder.
428
+ * Used for creating ThreadState outside of flow execution.
429
+ */
430
+ getThreadMetadata(threadId: string): Promise<ThreadMetadata>;
431
+ /**
432
+ * Execute sandboxed code for a thread endpoint from inside the thread DO.
433
+ *
434
+ * Thread endpoint handlers often start in the top-level Worker with only a
435
+ * Durable Object stub. Code execution must originate here so the dynamic
436
+ * worker can use this DO's env, ctx exports, and bridge registration map.
437
+ */
438
+ executeThreadEndpointCode(threadId: string, source: string, options: ThreadEndpointCodeOptions): Promise<CodeExecutionResult>;
439
+ /**
440
+ * Execute ThreadState.runCode for endpoint handlers that only have a
441
+ * Durable Object stub. The actual Dynamic Worker must be started inside this
442
+ * DurableThread so it has access to env, ctx exports, and bridge callbacks.
443
+ */
444
+ executeThreadStateRunCode(threadId: string, source: string, options?: CodeExecutionOptions, wantsReport?: boolean): Promise<CodeExecutionResult>;
445
+ /**
446
+ * Run `ThreadState.invokeTool()` INSIDE this Durable Object.
447
+ *
448
+ * Thread endpoints hold only a DO stub (no `ctx`/`env`/storage), so they can't
449
+ * build a standalone execution state in the top-level Worker. ThreadStateImpl
450
+ * forwards idle `invokeTool` calls here — where `this` is the real DO — so the
451
+ * assembled state has real storage and `ctx.waitUntil`, letting a non-blocking
452
+ * subagent (e.g. `compaction_agent`) be spawned from an endpoint. Mirrors
453
+ * `executeThreadStateRunCode`.
454
+ */
455
+ executeThreadStateInvokeTool(threadId: string, toolName: string, args: Record<string, unknown>): Promise<ToolResult>;
456
+ /**
457
+ * Read a JSON value from this thread's durable key-value store.
458
+ */
459
+ getValue<T = unknown>(key: string): Promise<T | null>;
460
+ /**
461
+ * Write a JSON value to this thread's durable key-value store.
462
+ *
463
+ * Per the Standard Agents spec, null and undefined delete the key.
464
+ */
465
+ setValue(key: string, value: unknown): Promise<void>;
466
+ listValues(options?: {
467
+ search?: string | null;
468
+ limit?: number;
469
+ offset?: number;
470
+ }): Promise<{
471
+ values: Array<{
472
+ key: string;
473
+ value: unknown;
474
+ serialized: string;
475
+ size: number;
476
+ updatedAt: number;
477
+ parseError?: string;
478
+ }>;
479
+ total: number;
480
+ limit: number;
481
+ offset: number;
482
+ search: string | null;
483
+ }>;
484
+ private assertValidThreadValueKey;
485
+ private escapeThreadValueLike;
486
+ private serializeThreadValue;
487
+ private assertJsonSerializableThreadValue;
488
+ /**
489
+ * Trigger an agent to run on this thread.
490
+ *
491
+ * Queues an agent execution via the alarm queue. The execution
492
+ * runs asynchronously in the background.
493
+ *
494
+ * @param threadId - Thread ID for the execution
495
+ * @param agentName - Name of the agent to run
496
+ */
497
+ runAgent(threadId: string, agentName: string): Promise<void>;
498
+ /**
499
+ * Get the persisted resumable-subagent registry for this thread.
500
+ */
501
+ getChildrenRegistry(_threadId: string): Promise<SubagentRegistryEntry[]>;
502
+ /** In-memory throttle/reentrancy guards for the stale-child reconciler. */
503
+ private lastChildAuditAt;
504
+ private childAuditInFlight;
505
+ /**
506
+ * Lazily heal registry entries stranded at a "working" status. The normal
507
+ * settlement chain lives only in the parent's `waitUntil`; a parent
508
+ * eviction/deploy/kill during a child's run leaves the entry at `running`
509
+ * forever and clients render an eternal spinner. On registry reads, audit
510
+ * old unsettled entries against the child thread's ACTUAL state and settle
511
+ * them — conservatively (see subagent-reconcile.ts): resumable children
512
+ * are never deterministically terminated.
513
+ */
514
+ private reconcileStaleChildren;
515
+ /**
516
+ * Child-side registry settlement: called from the CHILD's own DO whenever
517
+ * a run ends, so the spinner clears even when the parent-held completion
518
+ * chain died with the parent. Only downgrades a live "working" status to
519
+ * idle — never clobbers terminated.
520
+ */
521
+ settleChildRegistryIdle(_threadId: string, reference: string): Promise<void>;
522
+ private setChildrenRegistry;
523
+ upsertChildRegistry(_threadId: string, entry: SubagentRegistryEntry): Promise<void>;
524
+ updateChildRegistryStatus(_threadId: string, reference: string, status: string): Promise<void>;
525
+ /**
526
+ * Nudge live event listeners after a child's registry status changes. The
527
+ * status (`running`/`idle`/`terminated`) lives here in the parent registry,
528
+ * not on the child's thread row, so without this a transition like running →
529
+ * idle would never reach `/api/events`. We re-broadcast a `thread_updated`
530
+ * for the child thread so consumers re-read its status. Best effort.
531
+ */
532
+ private broadcastChildStatusChanged;
533
+ removeChildRegistry(_threadId: string, reference: string): Promise<void>;
534
+ /**
535
+ * Persist the invocation arguments supplied when this subagent thread was
536
+ * created. These are hydrated into prompt-interpolation context on every
537
+ * activation of either side, so they survive for the life of the thread.
538
+ */
539
+ setSubagentArguments(_threadId: string, args: Record<string, unknown>): Promise<void>;
540
+ /**
541
+ * Read the persisted invocation arguments for this subagent thread.
542
+ * Returns an empty object when none were stored.
543
+ */
544
+ getSubagentArguments(_threadId: string): Promise<Record<string, unknown>>;
545
+ private asOptionalString;
546
+ private asOptionalBoolean;
547
+ private getThreadNameFromTags;
548
+ private toSubagentProjection;
549
+ private resolveSubagentMessageProjections;
550
+ /**
551
+ * Build hook resolution context and a genuine at-rest ThreadState.
552
+ * Resolution failures abort insertion so lifecycle hooks cannot be bypassed.
553
+ */
554
+ private buildAtRestHookState;
555
+ /**
556
+ * Inject a top-level message without starting a new execution.
557
+ *
558
+ * This path is used by effects and thread endpoints, which run without a
559
+ * FlowState but still need to write visible messages to the thread.
560
+ */
561
+ injectMessage(threadId: string, message: InjectMessageInput): Promise<Message>;
562
+ /**
563
+ * Queue a message for deferred delivery.
564
+ */
565
+ queueMessage(threadId: string, message: QueueMessageInput): Promise<void>;
566
+ private hasPendingTurnAlarm;
567
+ private ensureQueuedMessageExecution;
568
+ private ensureRootMessageId;
569
+ /**
570
+ * Soft-terminate this thread.
571
+ */
572
+ terminateThread(threadId: string): Promise<{
573
+ success: boolean;
574
+ terminated: number;
575
+ }>;
576
+ /**
577
+ * Schedule an effect for future execution.
578
+ *
579
+ * @param threadId - Thread ID for the effect execution context
580
+ * @param effectName - Name of the effect to schedule
581
+ * @param effectArgs - Arguments to pass to the effect handler
582
+ * @param delayMs - Delay in milliseconds before execution (default: 0)
583
+ * @returns UUID of the scheduled effect
584
+ */
585
+ scheduleEffect(threadId: string, effectName: string, effectArgs: Record<string, unknown>, delayMs?: number, options?: {
586
+ sourceLogId?: string | null;
587
+ }): Promise<string>;
588
+ /**
589
+ * Check whether an effect loader exists in either global or packed registries.
590
+ */
591
+ private effectExists;
592
+ /**
593
+ * Get scheduled effects for this thread.
594
+ *
595
+ * @param name - Optional effect name to filter by
596
+ * @returns Array of scheduled effect records
597
+ */
598
+ getScheduledEffects(name?: string): Promise<Array<{
599
+ id: string;
600
+ name: string;
601
+ args: Record<string, unknown>;
602
+ scheduledAt: number;
603
+ createdAt: number;
604
+ }>>;
605
+ /**
606
+ * List pending and historical effect runs for the AgentBuilder UI.
607
+ */
608
+ listEffectRuns(options?: EffectRunListOptions): Promise<EffectRunListResult>;
609
+ /**
610
+ * Run a pending effect now, or replay a historical effect immediately.
611
+ */
612
+ runEffectNow(effectRunId: string): Promise<EffectRunActionResult>;
613
+ /**
614
+ * Cancel a scheduled effect and keep it in history.
615
+ *
616
+ * @param id - The effect ID returned by scheduleEffect
617
+ * @returns true if the effect was found and canceled, false otherwise
618
+ */
619
+ removeScheduledEffect(id: string, canceledBy?: EffectCancelSource): Promise<boolean>;
620
+ /**
621
+ * Ensures the database schema is up to date.
622
+ * This method is called on the first request to the Durable Object.
623
+ * It checks the schema version and runs any pending migrations.
624
+ *
625
+ * Performance:
626
+ * - Already migrated to latest: ~0.1ms (single SELECT + integer comparison)
627
+ * - Needs migration: Runs once per Durable Object lifetime per schema version
628
+ * - Detects new migrations after code deployment
629
+ */
630
+ private ensureMigrated;
631
+ /**
632
+ * Gets the current schema version from the database.
633
+ * Returns 0 if the metadata table doesn't exist (brand new database).
634
+ */
635
+ private getCurrentVersion;
636
+ /**
637
+ * Runs all pending migrations sequentially.
638
+ * Each migration is run in order, starting from the current version + 1.
639
+ */
640
+ private runMigrations;
641
+ /**
642
+ * Legacy fetch handler for WebSocket upgrades only
643
+ */
644
+ fetch(request: Request): Promise<Response>;
645
+ registerCodeExecutionBridge(runId: string, bridge: CodeExecutionBridgeRegistration): void;
646
+ unregisterCodeExecutionBridge(runId: string): void;
647
+ callCodeExecutionBridge(runId: string, functionId: string, encodedArgs: unknown[]): Promise<unknown>;
648
+ /**
649
+ * Execute thread with initial messages (RPC method)
650
+ * Enqueues the execution to be processed by the alarm handler
651
+ */
652
+ execute(threadId: string, agentId: string, initial_messages?: any[], data?: any): Promise<Response>;
653
+ /**
654
+ * Execute a flow synchronously and return the final top-level message content.
655
+ * Used by blocking subagent tool calls.
656
+ */
657
+ executeBlocking(threadId: string, agentId: string, initial_messages?: any[], data?: any): Promise<{
658
+ status: "success" | "error";
659
+ result?: string;
660
+ error?: string;
661
+ attachments?: unknown[];
662
+ terminal?: boolean;
663
+ }>;
664
+ /** Best-effort: mark this child's entry idle in its parent's registry. */
665
+ private settleOwnRegistryEntry;
666
+ private executeBlockingImpl;
667
+ /**
668
+ * Send a new message to the thread (RPC method)
669
+ * Enqueues the message processing to be handled by the alarm handler
670
+ */
671
+ sendMessage(threadId: string, content: string, role?: string, attachments?: string): Promise<Response>;
672
+ /**
673
+ * Check if execution should be stopped (called by FlowEngine)
674
+ * Reads from SQLite for persistence across hibernation
675
+ */
676
+ shouldStop(): Promise<boolean>;
677
+ /**
678
+ * Returns the termination timestamp (microseconds) or null when active.
679
+ */
680
+ getTerminated(_threadId: string): Promise<number | null>;
681
+ private assertNotTerminated;
682
+ private getLatestTopLevelMessage;
683
+ private getTerminalSessionToolNames;
684
+ private parseAttachmentRefsJson;
685
+ private deleteAttachmentRefsFromJson;
686
+ private cancelQueuedMessage;
687
+ private parseMessageMetadata;
688
+ private extractSubagentIdFromMetadata;
689
+ private getLatestTerminalSessionMessageAfter;
690
+ private inferMimeTypeFromPath;
691
+ private extensionForMimeType;
692
+ private sanitizeFilename;
693
+ private splitFilename;
694
+ private resolveAttachmentMimeType;
695
+ private buildAttachmentTargetPath;
696
+ private copyAttachmentRefsToThread;
697
+ private readAttachmentDataFromSource;
698
+ private arrayBufferToBase64;
699
+ private formatSubagentAttachmentPathSummary;
700
+ private persistParentHandoffStatusMessage;
701
+ private buildMissingTerminalSessionFailure;
702
+ private deliverCompletionToParentIfNeeded;
703
+ private getParentRegistryEntryForChild;
704
+ /**
705
+ * Stop the currently executing thread (RPC method)
706
+ * Simple "off" switch - stops turns, only cleared by user messages
707
+ */
708
+ /**
709
+ * Flip every still-`pending` message to `failed` and broadcast the change to
710
+ * all connected heads. This is THE settle path for any terminal condition
711
+ * that leaves a turn half-open — user stop, lost execution, terminal
712
+ * execution failure, and expired parked forwarded calls — so no head is
713
+ * left rendering a stuck "Working" state. Returns the failure timestamp.
714
+ */
715
+ failPendingMessagesAndBroadcast(): Promise<number>;
716
+ /**
717
+ * A terminal failure ended a turn without a normal assistant reply: settle
718
+ * every pending message and persist a durable `failed` assistant message so
719
+ * all connected heads land on a real, visible end state — never a stuck
720
+ * "Working" spinner. Used by the FlowEngine's terminal catch and the parked
721
+ * forwarded-call TTL.
722
+ */
723
+ settleTerminalFailure(errorMessage: string, threadId?: string): Promise<void>;
724
+ stop(): Promise<Response>;
725
+ /**
726
+ * Continue execution from where it stopped (RPC method)
727
+ * Useful for debugging - continues the FlowEngine with additional steps
728
+ * without adding a new message.
729
+ *
730
+ * @param threadId The thread ID
731
+ * @param side Which side to start from ('a' or 'b'), defaults to 'a'
732
+ */
733
+ continueExecution(threadId: string, side?: 'a' | 'b'): Promise<Response>;
734
+ /**
735
+ * Get message history (RPC method)
736
+ *
737
+ * By default, returns the newest messages (when truncating), but in chronological
738
+ * order (oldest first in the array). This is ideal for chat UIs where messages
739
+ * should be appended and scrolled to the bottom.
740
+ *
741
+ * The offset parameter allows "scrolling up" to view older messages.
742
+ *
743
+ * Example:
744
+ * - getMessages(10, 0) -> newest 10 messages, oldest first in array
745
+ * - getMessages(10, 10) -> next 10 older messages, oldest first in array
746
+ *
747
+ * @param limit Number of messages to return (default: 100)
748
+ * @param offset Number of newest messages to skip (default: 0)
749
+ * @param order Internal query order - "DESC" (default) fetches newest first then reverses
750
+ * @param includeSilent Include silent messages (UI-only messages)
751
+ * @param maxDepth Maximum depth to include (default: 0 for top-level only)
752
+ */
753
+ getMessages(limit?: number, offset?: number, order?: "ASC" | "DESC" | "asc" | "desc", includeSilent?: boolean, maxDepth?: number): Promise<{
754
+ messages: {
755
+ id: string;
756
+ role: string;
757
+ content: string | null;
758
+ name: string | null;
759
+ tool_calls: string | null;
760
+ tool_call_id: string | null;
761
+ tool_status: "success" | "error" | null;
762
+ log_id: string | null;
763
+ created_at: number;
764
+ silent: boolean;
765
+ parent_id: string | null;
766
+ depth: number;
767
+ status: "pending" | "completed" | "failed" | null;
768
+ reasoning_content: string | null;
769
+ reasoning_details: string | null;
770
+ attachments: any;
771
+ metadata: Record<string, unknown> | undefined;
772
+ subagent_id: string | null;
773
+ }[];
774
+ total: number;
775
+ hasMore: boolean;
776
+ }>;
777
+ /**
778
+ * Get specific messages, optionally expanding any requested tool-call message
779
+ * to the full contiguous workblock it belongs to.
780
+ */
781
+ getMessagesByIds(ids: string[], includeSilent?: boolean, maxDepth?: number, includeWorkblocks?: boolean): Promise<{
782
+ messages: {
783
+ id: string;
784
+ role: string;
785
+ content: string | null;
786
+ name: string | null;
787
+ tool_calls: string | null;
788
+ tool_call_id: string | null;
789
+ tool_status: "success" | "error" | null;
790
+ log_id: string | null;
791
+ created_at: number;
792
+ silent: boolean;
793
+ parent_id: string | null;
794
+ depth: number;
795
+ status: "pending" | "completed" | "failed" | null;
796
+ reasoning_content: string | null;
797
+ reasoning_details: string | null;
798
+ attachments: any;
799
+ metadata: Record<string, unknown> | undefined;
800
+ subagent_id: string | null;
801
+ }[];
802
+ total: number;
803
+ hasMore: boolean;
804
+ }>;
805
+ /**
806
+ * Delete a message (RPC method)
807
+ * Also cleans up any attachment files stored on the thread filesystem
808
+ */
809
+ deleteMessage(messageId: string): Promise<{
810
+ success: boolean;
811
+ error?: undefined;
812
+ } | {
813
+ success: boolean;
814
+ error: any;
815
+ }>;
816
+ /**
817
+ * Update a message's content (RPC method)
818
+ */
819
+ updateMessageContent(messageId: string, content: string): Promise<{
820
+ success: boolean;
821
+ error?: undefined;
822
+ } | {
823
+ success: boolean;
824
+ error: any;
825
+ }>;
826
+ /**
827
+ * Seed messages directly into the database (RPC method - for testing)
828
+ * This bypasses the normal message processing flow
829
+ */
830
+ seedMessages(args: {
831
+ messages: Array<{
832
+ id: string;
833
+ role: string;
834
+ content: string;
835
+ created_at: number;
836
+ log_id?: string | null;
837
+ }>;
838
+ }): Promise<{
839
+ success: boolean;
840
+ count: number;
841
+ error?: undefined;
842
+ } | {
843
+ success: boolean;
844
+ error: any;
845
+ count?: undefined;
846
+ }>;
847
+ /**
848
+ * Seed a log directly into the database (RPC method - for testing)
849
+ * This bypasses the normal log creation flow
850
+ */
851
+ seedLog(args: {
852
+ id: string;
853
+ message_id: string;
854
+ provider: string;
855
+ model: string;
856
+ created_at: number;
857
+ is_complete?: boolean;
858
+ prompt_name?: string;
859
+ }): Promise<{
860
+ success: boolean;
861
+ id: string;
862
+ error?: undefined;
863
+ } | {
864
+ success: boolean;
865
+ error: any;
866
+ id?: undefined;
867
+ }>;
868
+ /**
869
+ * Get logs (RPC method)
870
+ */
871
+ getLogs(limit?: number, offset?: number, order?: "ASC" | "DESC"): Promise<{
872
+ logs: {
873
+ id: string;
874
+ kind: string | null;
875
+ message_id: string;
876
+ provider: string;
877
+ actual_provider: string | null;
878
+ standard_agents_router_used: boolean;
879
+ model: string;
880
+ model_name: string | null;
881
+ prompt_name: string | null;
882
+ tools_called: string | null;
883
+ queued_tools: string | null;
884
+ provider_tools: string | null;
885
+ parent_log_id: string | null;
886
+ retry_of_log_id: string | null;
887
+ error: string | null;
888
+ error_type: string | null;
889
+ error_origin: string | null;
890
+ cost_total: number | null;
891
+ input_tokens: number | null;
892
+ cached_tokens: number | null;
893
+ output_tokens: number | null;
894
+ total_tokens: number | null;
895
+ is_complete: boolean;
896
+ created_at: number;
897
+ }[];
898
+ total: number;
899
+ hasMore: boolean;
900
+ }>;
901
+ /**
902
+ * This thread's OWN request-log cost summary (no descendants), aggregated
903
+ * in SQL so subtree cost reporting doesn't page full log rows out of every
904
+ * thread in the tree. Used by GET /api/threads/:id/cost, which merges these
905
+ * across the thread and all of its subagent descendants.
906
+ */
907
+ getCostSummary(): Promise<{
908
+ totalCost: number;
909
+ inputCost: number;
910
+ cachedCost: number;
911
+ outputCost: number;
912
+ routerFeeCost: number;
913
+ requestCount: number;
914
+ messageCount: number;
915
+ byModel: Record<string, {
916
+ totalCost: number;
917
+ inputCost: number;
918
+ cachedCost: number;
919
+ outputCost: number;
920
+ routerFeeCost: number;
921
+ count: number;
922
+ }>;
923
+ }>;
924
+ /**
925
+ * Get specific logs, optionally including all descendant logs.
926
+ */
927
+ getLogsByIds(ids: string[], includeDescendants?: boolean, order?: "ASC" | "DESC"): Promise<{
928
+ logs: {
929
+ id: string;
930
+ kind: string | null;
931
+ message_id: string;
932
+ provider: string;
933
+ actual_provider: string | null;
934
+ standard_agents_router_used: boolean;
935
+ model: string;
936
+ model_name: string | null;
937
+ prompt_name: string | null;
938
+ tools_called: string | null;
939
+ queued_tools: string | null;
940
+ provider_tools: string | null;
941
+ parent_log_id: string | null;
942
+ retry_of_log_id: string | null;
943
+ error: string | null;
944
+ error_type: string | null;
945
+ error_origin: string | null;
946
+ cost_total: number | null;
947
+ is_complete: boolean;
948
+ created_at: number;
949
+ }[];
950
+ total: number;
951
+ hasMore: boolean;
952
+ }>;
953
+ /**
954
+ * Get logs for specific messages, optionally expanding requested messages to
955
+ * the full contiguous workblock they belong to and including descendant logs.
956
+ */
957
+ getLogsByMessageIds(messageIds: string[], includeWorkblocks?: boolean, includeDescendants?: boolean, order?: "ASC" | "DESC"): Promise<{
958
+ logs: {
959
+ id: string;
960
+ kind: string | null;
961
+ message_id: string;
962
+ provider: string;
963
+ actual_provider: string | null;
964
+ standard_agents_router_used: boolean;
965
+ model: string;
966
+ model_name: string | null;
967
+ prompt_name: string | null;
968
+ tools_called: string | null;
969
+ queued_tools: string | null;
970
+ provider_tools: string | null;
971
+ parent_log_id: string | null;
972
+ retry_of_log_id: string | null;
973
+ error: string | null;
974
+ error_type: string | null;
975
+ error_origin: string | null;
976
+ cost_total: number | null;
977
+ is_complete: boolean;
978
+ created_at: number;
979
+ }[];
980
+ total: number;
981
+ hasMore: boolean;
982
+ }>;
983
+ /**
984
+ * Scalar (non-heavy) log-detail fields plus joined source-message scalars
985
+ * and scheduled-effect provenance. The multi-MB TEXT columns are read one
986
+ * at a time via readLogDetailHeavyField so no caller ever holds them all
987
+ * in memory at once.
988
+ */
989
+ private readLogDetailScalars;
990
+ /**
991
+ * Single-column reads for the multi-MB log-detail TEXT columns. Static SQL
992
+ * per field (never interpolated), keyed by the shared heavy-field list the
993
+ * streamed serializer iterates.
994
+ */
995
+ private static readonly LOG_DETAIL_HEAVY_FIELD_SQL;
996
+ private readLogDetailHeavyField;
997
+ /**
998
+ * Get detailed information for a single log (RPC method).
999
+ *
1000
+ * Kept for RPC compatibility; HTTP routes use the streamed
1001
+ * `/internal/logs/:logId/details` fetch transport instead, because an
1002
+ * assembled detail object can approach the 32MiB RPC serialization cap.
1003
+ * `message_history` is no longer returned — it was byte-for-byte
1004
+ * `request_body.messages`; clients derive it from request_body.
1005
+ */
1006
+ getLogDetails(logId: string): Promise<{
1007
+ request_body: string | null;
1008
+ response_body: string | null;
1009
+ tools_schema: string | null;
1010
+ system_prompt: string | null;
1011
+ tool_results: string | null;
1012
+ reasoning_content: string | null;
1013
+ source_message_content: string | null;
1014
+ id: string;
1015
+ kind: string | null;
1016
+ message_id: string;
1017
+ provider: string;
1018
+ actual_provider: string | null;
1019
+ standard_agents_router_used: boolean;
1020
+ model: string;
1021
+ model_name: string | null;
1022
+ endpoint: string | null;
1023
+ request_headers: string | null;
1024
+ response_headers: string | null;
1025
+ status_code: number | null;
1026
+ input_tokens: number | null;
1027
+ cached_tokens: number | null;
1028
+ output_tokens: number | null;
1029
+ reasoning_tokens: number | null;
1030
+ total_tokens: number | null;
1031
+ latency_ms: number | null;
1032
+ time_to_first_token_ms: number | null;
1033
+ generation_ms: number | null;
1034
+ finish_reason: string | null;
1035
+ error: string | null;
1036
+ error_type: string | null;
1037
+ error_origin: string | null;
1038
+ cost_input: number | null;
1039
+ cost_cached: number | null;
1040
+ cost_output: number | null;
1041
+ cost_router_fee: number | null;
1042
+ router_fee_percent: number | null;
1043
+ cost_total: number | null;
1044
+ message_history_length: number | null;
1045
+ tools_available: number | null;
1046
+ prompt_name: string | null;
1047
+ tools_called: string | null;
1048
+ queued_tools: string | null;
1049
+ provider_tools: string | null;
1050
+ parent_log_id: string | null;
1051
+ errors: string | null;
1052
+ retry_of_log_id: string | null;
1053
+ is_complete: boolean;
1054
+ created_at: number;
1055
+ source_message_role: string | null;
1056
+ source_message_created_at: number | null;
1057
+ source_message_metadata: string | null;
1058
+ scheduled_effects: string;
1059
+ } | null>;
1060
+ /**
1061
+ * Streamed transport for log details: same JSON shape as getLogDetails but
1062
+ * served as a fetch Response (no 32MiB RPC cap) whose body is written
1063
+ * field-by-field with backpressure, so the full multi-MB detail object is
1064
+ * never buffered in this DO.
1065
+ */
1066
+ private streamLogDetails;
1067
+ /**
1068
+ * Get thread metadata (RPC method)
1069
+ */
1070
+ getThreadMeta(threadId: string): Promise<Response | {
1071
+ thread: {
1072
+ id: any;
1073
+ agent_id: any;
1074
+ user_id: any;
1075
+ tags: any;
1076
+ parent: any;
1077
+ terminated: any;
1078
+ created_at: any;
1079
+ };
1080
+ agent: {
1081
+ id: any;
1082
+ title: any;
1083
+ description: any;
1084
+ icon: any;
1085
+ side_a_backing: string;
1086
+ side_b_backing: string;
1087
+ side_a_label: any;
1088
+ side_b_label: any;
1089
+ side_a_agent_prompt: string | null;
1090
+ side_b_agent_prompt: string | null;
1091
+ side_a_handler: any;
1092
+ side_b_handler: any;
1093
+ } | null;
1094
+ stats: {
1095
+ message_count: number;
1096
+ log_count: number;
1097
+ };
1098
+ }>;
1099
+ /**
1100
+ * Update thread metadata (RPC method)
1101
+ * Calls the DurableAgentBuilder to update the thread registry
1102
+ */
1103
+ updateThreadMeta(threadId: string, params: {
1104
+ agent_name?: string;
1105
+ user_id?: string | null;
1106
+ tags?: string[] | null;
1107
+ env?: Record<string, string> | null;
1108
+ tenvs?: Record<string, unknown> | null;
1109
+ }): Promise<{
1110
+ success: boolean;
1111
+ thread: {
1112
+ id: any;
1113
+ agent_id: any;
1114
+ user_id: any;
1115
+ tags: any;
1116
+ created_at: any;
1117
+ };
1118
+ error?: undefined;
1119
+ } | {
1120
+ success: boolean;
1121
+ error: any;
1122
+ thread?: undefined;
1123
+ }>;
1124
+ /**
1125
+ * Delete thread data completely (RPC method)
1126
+ * This will permanently delete the Durable Object instance
1127
+ */
1128
+ deleteThread(): Promise<{
1129
+ success: boolean;
1130
+ message: string;
1131
+ }>;
1132
+ /**
1133
+ * Handle WebSocket upgrade for real-time log streaming
1134
+ * Uses Hibernation API to reduce costs during inactivity
1135
+ */
1136
+ private handleLogsWebSocketUpgrade;
1137
+ /**
1138
+ * Handle WebSocket upgrade for real-time message streaming
1139
+ * Uses Hibernation API to reduce costs during inactivity
1140
+ */
1141
+ private handleMessagesWebSocketUpgrade;
1142
+ /**
1143
+ * Handle WebSocket upgrade for the client-tool bridge.
1144
+ *
1145
+ * A connected CLI holds this socket open. Forwarded tools send `tool_request`
1146
+ * frames down it and the client replies with `tool_response` frames, letting
1147
+ * the remotely-running agent execute filesystem/shell operations on the
1148
+ * user's own machine.
1149
+ */
1150
+ private handleBridgeWebSocketUpgrade;
1151
+ /** Parse a raw KV value into an {@link ExecutionOwner}, or null. */
1152
+ private parseExecutionOwner;
1153
+ /** Load (and cache) the thread's persisted execution-owner record. */
1154
+ private getExecutionOwner;
1155
+ /** Owner id from the in-memory mirror only (for sync paths); null when
1156
+ * unloaded or unowned — both degrade to the historical any-socket rule. */
1157
+ private currentExecutionOwnerId;
1158
+ /** Persist + cache the execution-owner record (null releases ownership). */
1159
+ private setExecutionOwner;
1160
+ /** Whether the given client id has an open bridge socket (excluding `except`).
1161
+ * Idle bridge heartbeats are handled by Cloudflare without waking this object,
1162
+ * so timestamp liveness is intentionally enforced only for an in-flight call. */
1163
+ private hasLiveBridgeSocketForClient;
1164
+ /** Tell every other bridge socket that execution ownership moved. */
1165
+ private broadcastOwnerChanged;
1166
+ /** Whether any forwarded call is mid-flight (blocking await or parked). */
1167
+ hasInFlightClientCalls(): Promise<boolean>;
1168
+ /**
1169
+ * Ownership moved away from a dead client: settle everything that was
1170
+ * dispatched to it. In-memory blocking calls fail immediately; parked
1171
+ * durable calls get an error result and the turn resumes — re-sending them
1172
+ * to the NEW owner would silently re-run the operation on a different
1173
+ * machine's filesystem, which is worse than an honest retryable error.
1174
+ */
1175
+ private failStalePendingWork;
1176
+ /**
1177
+ * Forward a tool operation to a connected bridge client and await its result.
1178
+ *
1179
+ * Returns a structured response rather than throwing so forwarded tools can
1180
+ * always produce a normal tool error (no client connected, timeout, or user
1181
+ * denial) for the model to reason about.
1182
+ */
1183
+ callClientTool(request: ClientToolRequest, durability?: {
1184
+ toolCallId: string;
1185
+ side: "a" | "b";
1186
+ }): Promise<ClientToolResponse>;
1187
+ /** Settle a pending forwarded call exactly once, clearing its timers. */
1188
+ private settleClientCall;
1189
+ /** Close and forget a bridge socket we've deemed dead, failing remaining calls. */
1190
+ private markBridgeDead;
1191
+ /**
1192
+ * Return the bridge socket a forwarded call should be dispatched to, pruning
1193
+ * closed ones. Idle clients use Cloudflare's hibernation auto-response, so
1194
+ * their frames deliberately do not update `bridgeLastSeen`. Once a call is
1195
+ * dispatched, the client switches to application-visible pings and the
1196
+ * in-flight liveness timer above detects a half-open connection.
1197
+ *
1198
+ * With an execution owner recorded, only the owner's socket (or, as a
1199
+ * back-compat fallback, an unidentified legacy socket) is eligible; with no
1200
+ * owner, the first live socket wins as it always has.
1201
+ */
1202
+ private getOpenBridgeSocket;
1203
+ /** Resolve an in-flight forwarded tool call from a client `tool_response`. */
1204
+ private resolveClientCall;
1205
+ /**
1206
+ * When the last bridge client that could serve forwarded calls disconnects,
1207
+ * fail any in-flight ones so the agent loop doesn't hang waiting on a client
1208
+ * that is gone. Uses the in-memory owner mirror (sync path); when the mirror
1209
+ * isn't loaded this degrades to the historical any-socket check, and the
1210
+ * per-call liveness interval still catches a dead dispatch target.
1211
+ */
1212
+ private failPendingClientCallsIfNoBridge;
1213
+ /** Whether a bridge client that can execute forwarded calls is connected
1214
+ * right now (used to decide durable park). */
1215
+ hasBridge(): Promise<boolean>;
1216
+ private ensurePendingClientTable;
1217
+ /**
1218
+ * Durably dispatch a forwarded tool call WITHOUT blocking the agent loop.
1219
+ * Persists the request, sends it to the connected client (best effort), and
1220
+ * returns immediately. The client later delivers the result via
1221
+ * {@link deliverClientToolResult}, which resumes execution.
1222
+ */
1223
+ dispatchClientTool(request: ClientToolRequest, toolCallId: string, side: "a" | "b"): Promise<{
1224
+ dispatched: boolean;
1225
+ }>;
1226
+ /**
1227
+ * Send one durable `tool_request` frame to the bridge if a client is
1228
+ * connected — and stamp the pending row with the identity+generation it was
1229
+ * dispatched to, fencing the eventual HTTP delivery to that client. A
1230
+ * legacy (unidentified) executor leaves the row unstamped, keeping the
1231
+ * historical accept-anything delivery for old CLIs.
1232
+ */
1233
+ private sendClientToolRequest;
1234
+ /**
1235
+ * The delivered result of a parked forwarded call, if the client has
1236
+ * already resolved it — lets the approval-park path grace-wait briefly and
1237
+ * return the REAL result inline instead of a "⏳ Awaiting your approval…"
1238
+ * placeholder. Instant auto-accepts (the common case: the client's saved
1239
+ * permission level covers the call) otherwise race the placeholder into
1240
+ * stored history, leaving the model blind to its own tool outcomes.
1241
+ */
1242
+ /**
1243
+ * In-memory waiters parked on a forwarded call's result delivery (AB-09).
1244
+ * `deliverClientToolResult` resolves them so the approval grace-wait reads
1245
+ * delivered state exactly once instead of re-polling it every 150ms.
1246
+ * In-memory only: a DO restart drops waiters along with the caller that
1247
+ * registered them, and the durable park path still resumes the turn.
1248
+ */
1249
+ private deliveredResultWaiters;
1250
+ private notifyDeliveredResultWaiters;
1251
+ /**
1252
+ * Await a parked forwarded call's delivered result: one immediate read,
1253
+ * then a single parked wait resolved by result delivery, bounded by one
1254
+ * hard deadline, then one final read. Replaces the caller-side 150ms
1255
+ * re-poll of {@link getDeliveredClientToolResult}.
1256
+ */
1257
+ awaitDeliveredClientToolResult(toolCallId: string, maxWaitMs: number): Promise<{
1258
+ content: string;
1259
+ toolStatus: string | null;
1260
+ } | null>;
1261
+ getDeliveredClientToolResult(toolCallId: string): Promise<{
1262
+ content: string;
1263
+ toolStatus: string | null;
1264
+ } | null>;
1265
+ /** Still-pending durable forwarded calls (for re-sending after a reconnect). */
1266
+ getPendingClientCalls(): Promise<Array<{
1267
+ toolCallId: string;
1268
+ tool: string;
1269
+ args: Record<string, unknown>;
1270
+ requestPermission: string | null;
1271
+ risk: number | null;
1272
+ }>>;
1273
+ /** Re-send all pending durable requests to a freshly connected bridge socket. */
1274
+ private resendPendingClientCalls;
1275
+ /**
1276
+ * Deliver a client's result for a durable forwarded call: rewrite the parked
1277
+ * "awaiting" placeholder tool-result message to the real result and mark the
1278
+ * call resolved. Returns the side to continue, or null if there is no pending
1279
+ * call (unknown id or already resolved — the delivery is idempotent).
1280
+ */
1281
+ deliverClientToolResult(toolCallId: string, ok: boolean, result?: string, error?: string, deliveredByClientId?: string, deliveredGeneration?: number, deliveryToken?: string, internalAuthorization?: typeof INTERNAL_TOOL_DELIVERY): Promise<{
1282
+ side: "a" | "b";
1283
+ } | null>;
1284
+ /** Default time to wait for the client to accept a stream open. */
1285
+ private static readonly CLIENT_STREAM_OPEN_TIMEOUT_MS;
1286
+ /**
1287
+ * In-memory waiters parked on the owner's bridge socket returning (AB-09).
1288
+ * Resolved by bridge attach and by execution-owner changes; each waiter
1289
+ * re-evaluates against the CURRENT owner on wake. In-memory only: a DO
1290
+ * restart drops waiters with the stream-open call that registered them.
1291
+ */
1292
+ private ownerBridgeWaiters;
1293
+ private notifyOwnerBridgeWaiters;
1294
+ /**
1295
+ * The thread HAS an elected execution owner, but its bridge socket is gone
1296
+ * (daemon restart, network blip, DO handoff). Summon the owning machine
1297
+ * through the per-user hub and wait for a bridge to re-attach instead of
1298
+ * failing the stream open instantly — that instant failure is what ended
1299
+ * Sama One turns with "workspace unavailable" whenever a slow tool/approval
1300
+ * outlived the socket. Threads with NO recorded owner (subagent children)
1301
+ * still fail fast so ancestor walk-up routing stays immediate.
1302
+ *
1303
+ * The wait parks on bridge-attach/owner-change signals under ONE hard
1304
+ * deadline — no re-poll cadence. Each wake re-reads the owner because the
1305
+ * returning daemon may reclaim with a new generation, and the socket must
1306
+ * match the CURRENT owner.
1307
+ */
1308
+ private awaitOwnerBridgeSocket;
1309
+ private parseProxyStreamAttachments;
1310
+ /** Keep live proxy routes on the hibernating bridge socket for restart cleanup. */
1311
+ private updateBridgeProxyAttachment;
1312
+ private deliverProxyStreamFrame;
1313
+ /** Abort live proxy routes restored without their in-memory stream state. */
1314
+ private recoverInterruptedProxyStreams;
1315
+ /** Register the child side before any ancestor opens an owner stream. */
1316
+ createProxyStreamReceiver(onCancel: (error?: string) => void): ProxyStreamReceiver;
1317
+ proxyStreamReceiverExists(receiverId: string): Promise<boolean>;
1318
+ proxyStreamReceive(receiverId: string, frame: ProxyStreamFrame): Promise<boolean>;
1319
+ /** Open a bidirectional byte stream to the connected owner client. */
1320
+ openClientStream(request: ClientStreamRequest, proxyTarget?: ProxyStreamTarget | null): Promise<ClientStreamResponse>;
1321
+ proxyStreamOpen(request: ClientStreamRequest, target: ProxyStreamTarget): Promise<ProxyStreamOpenResult>;
1322
+ proxyStreamWrite(id: string, dataB64: string): Promise<void>;
1323
+ proxyStreamEnd(id: string): Promise<void>;
1324
+ proxyStreamAbort(id: string): Promise<void>;
1325
+ private forgetEventProxyStream;
1326
+ /** Settle and remove a client stream exactly once. */
1327
+ private settleClientStream;
1328
+ /** Abort a stream from the Worker side, telling the client to tear down. */
1329
+ private abortClientStream;
1330
+ /** Handle an incoming stream_* frame from a bridge client. */
1331
+ private handleClientStreamFrame;
1332
+ /** Fail every stream bound to a socket that closed or died. */
1333
+ private failClientStreamsForSocket;
1334
+ /** How long a parked forwarded call waits for a client before failing visibly. */
1335
+ private static readonly CLIENT_PARK_TTL_MS;
1336
+ /**
1337
+ * A forwarded call parked with NO client attached: ask the user's hub to
1338
+ * summon the owning machine's daemon to this thread, and arm the bounded
1339
+ * park TTL that turns an unreachable host into a visible durable failure
1340
+ * instead of a silent hang.
1341
+ */
1342
+ notifyClientWaiting(toolCallId: string, threadId: string, userId: string | null): Promise<void>;
1343
+ /** Ask the user's hub to summon the owning machine's daemon to a thread.
1344
+ * Best-effort: wake failure must never fail the caller's own path. */
1345
+ private requestHubWake;
1346
+ /**
1347
+ * Park TTL expired: if the call is still pending, settle it as a durable,
1348
+ * VISIBLE failure — rewrite the waiting placeholder, mark the pending row
1349
+ * failed, fail any still-pending assistant messages, and persist a durable
1350
+ * failed assistant message so every connected head settles instead of
1351
+ * showing "Working" forever.
1352
+ */
1353
+ private failParkedClientCall;
1354
+ /**
1355
+ * Broadcast a log record to all connected WebSocket clients
1356
+ */
1357
+ private broadcastLog;
1358
+ /**
1359
+ * Broadcast a message record to all connected message WebSocket clients
1360
+ * Filters silent messages based on each socket's includeSilent preference
1361
+ */
1362
+ private broadcastMessage;
1363
+ /**
1364
+ * The FlowEngine's message emit path: broadcast the record, and stamp
1365
+ * message recency when it is the thread's visible terminal assistant reply.
1366
+ *
1367
+ * This is the frame a client's reducer consumes to retire its provisional
1368
+ * draft, so it is the one place where "the user has something new to read"
1369
+ * is known. The stamp deliberately does NOT carry a preview: previews are
1370
+ * row labels and stay keyed to the user's own message, while recency has to
1371
+ * follow the agent's reply.
1372
+ */
1373
+ private emitFlowMessage;
1374
+ private broadcastMessageWithSubagentProjection;
1375
+ /**
1376
+ * Broadcast a content chunk for real-time streaming
1377
+ * Does NOT update database - only broadcasts to connected clients
1378
+ */
1379
+ private broadcastMessageChunk;
1380
+ /**
1381
+ * Broadcast an internal-reasoning chunk for real-time streaming.
1382
+ *
1383
+ * OPT-IN per the spec (`ThreadReasoningChunkEvent`): only sockets that
1384
+ * subscribed with `?reasoning=1` receive it. Like content chunks it does NOT
1385
+ * touch the database — reasoning is ephemeral display output.
1386
+ */
1387
+ private broadcastReasoningChunk;
1388
+ /**
1389
+ * Broadcast a telemetry event to all connected message WebSocket clients
1390
+ * Used for execution status updates (step_started, tool_started, etc.)
1391
+ */
1392
+ private broadcastTelemetry;
1393
+ /**
1394
+ * Broadcast a custom event to all connected message WebSocket clients
1395
+ * Used by tools via emitThreadEvent() to send user-defined events
1396
+ */
1397
+ emitThreadEvent(_threadId: string, type: string, data: unknown): void;
1398
+ private broadcastEvent;
1399
+ /**
1400
+ * WebSocket Hibernation API handler for incoming messages
1401
+ * Called when a message is received on a hibernated WebSocket
1402
+ */
1403
+ webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void>;
1404
+ /**
1405
+ * WebSocket Hibernation API handler for connection close
1406
+ * Called when a WebSocket connection is closed
1407
+ * Note: Do NOT call ws.close() here - the connection is already closed
1408
+ */
1409
+ webSocketClose(ws: WebSocket, _code: number, _reason: string, _wasClean: boolean): Promise<void>;
1410
+ /**
1411
+ * WebSocket Hibernation API handler for errors
1412
+ * Called when a WebSocket encounters an error
1413
+ */
1414
+ webSocketError(ws: WebSocket, error: unknown): Promise<void>;
1415
+ /**
1416
+ * Alarm handler - called by Cloudflare when a scheduled alarm fires
1417
+ * Processes the next item in the alarm queue
1418
+ *
1419
+ * Important: This method must NEVER throw an exception, as that would break
1420
+ * the alarm chain. All errors are caught and logged.
1421
+ */
1422
+ alarm(): Promise<void>;
1423
+ /** Persist a reversible emergency stop without scanning or deleting thread data. */
1424
+ emergencyQuarantine(input: RuntimeQuarantineInput): Promise<RuntimeSafetyStatus>;
1425
+ /** Return the low-cost quarantine status used by Brolly and diagnostics. */
1426
+ getRuntimeSafetyStatus(): Promise<RuntimeSafetyStatus>;
1427
+ /** Resume only through an explicit idempotent action; forensic holds need release. */
1428
+ emergencyResume(input: {
1429
+ actionId: string;
1430
+ reason: string;
1431
+ releaseForensicHold?: boolean;
1432
+ }): Promise<RuntimeSafetyStatus>;
1433
+ /** Heartbeat: called by LLMRequest on each attempt and streamed chunk. */
1434
+ noteExecutionProgress(): void;
1435
+ /**
1436
+ * The per-thread companion watchdog DO (ThreadWatchdog), derived from the
1437
+ * thread id. It exists because this thread's OWN alarm cannot fire while a
1438
+ * queue-dispatched turn runs inside alarm() — the companion delivers the
1439
+ * same check via RPC, which interleaves at await points even mid-turn.
1440
+ * Returns null on deployments whose generated config predates the binding.
1441
+ */
1442
+ private watchdogCompanion;
1443
+ /**
1444
+ * Stamp thread activity on the registry so thread lists can sort by recency
1445
+ * of real work and show which threads are executing right now. Registry
1446
+ * bookkeeping is presentation state: a failure here must never take down the
1447
+ * turn that triggered it.
1448
+ */
1449
+ private recordRegistryActivity;
1450
+ /**
1451
+ * The newest non-empty user message on this thread, for thread-list previews.
1452
+ * Returns null when the thread has none. The Durable Object does not know its
1453
+ * own thread id, so the caller is the one that stamps the registry.
1454
+ */
1455
+ getLatestUserMessagePreview(): Promise<string | null>;
1456
+ /** Arm the standing watchdog for an execution start. One pending row max. */
1457
+ private armExecutionWatchdog;
1458
+ /** Disarm on clean execution end. Completed check rows are noise, not history. */
1459
+ private disarmExecutionWatchdog;
1460
+ /**
1461
+ * The standing check, alarm-queue delivery. Evaluates the thread's state AT
1462
+ * FIRE TIME — it knows nothing about whichever request was in flight when it
1463
+ * was armed. NOTE this delivery path cannot fire while a queue-dispatched
1464
+ * turn runs (the turn owns this DO's single alarm invocation); the
1465
+ * ThreadWatchdog companion delivers the same assessment via watchdogProbe()
1466
+ * in exactly that window.
1467
+ */
1468
+ private watchdogCheck;
1469
+ /**
1470
+ * RPC delivery of the standing check — called by the ThreadWatchdog
1471
+ * companion (and the diagnostics revive endpoint). Runs in a fresh request
1472
+ * context, so it interleaves with a running turn at await points and its
1473
+ * own awaits/timers are alive even when a wedged turn's context is frozen.
1474
+ * Does NOT touch the internal watchdogCheck alarm rows — those belong to
1475
+ * the alarm delivery path.
1476
+ */
1477
+ watchdogProbe(threadId: string): Promise<WatchdogProbeResult>;
1478
+ /**
1479
+ * Reset this Durable Object instance on request. Used by the watchdog
1480
+ * companion after a wedged-executor takeover: the zombie turn may still own
1481
+ * this DO's single alarm invocation, which would block the just-enqueued
1482
+ * recovery alarm forever. Aborting guarantees a fresh instance whose alarm
1483
+ * chain re-arms from persisted queue state on first wake.
1484
+ */
1485
+ forceRestart(reason: string): Promise<void>;
1486
+ /**
1487
+ * Execution-health snapshot for the diagnostics endpoint and `agents diag`.
1488
+ * Exposes the state the 2026-07-08 post-mortem could not see from outside:
1489
+ * the alarm queue (was a turn item pending/processing/failed? was the
1490
+ * watchdog row gone?), the volatile execution flags, and open request logs.
1491
+ * Read-only; safe to call at any time.
1492
+ */
1493
+ getDiagnostics(): Promise<{
1494
+ executing: boolean;
1495
+ lastProgressAt: number | null;
1496
+ silenceMs: number | null;
1497
+ watchdogStrikes: number;
1498
+ watchdogCeilingMs: number;
1499
+ stopped: boolean;
1500
+ runtimeSafety: RuntimeSafetyStatus;
1501
+ incompleteLogs: Array<{
1502
+ id: string;
1503
+ model: string | null;
1504
+ provider: string | null;
1505
+ created_at: number;
1506
+ }>;
1507
+ alarmQueue: Array<{
1508
+ id: string;
1509
+ method: string;
1510
+ status: string;
1511
+ scheduled_at: number;
1512
+ created_at: number;
1513
+ attempts: number;
1514
+ error: string | null;
1515
+ }>;
1516
+ messageQueueCount: number;
1517
+ contextUsage: Record<string, unknown> | null;
1518
+ }>;
1519
+ /**
1520
+ * The shared watchdog decision core. Both deliveries (alarm + companion
1521
+ * probe) evaluate and ACT through this method; the caller only decides what
1522
+ * to do with its own scheduling based on the verdict.
1523
+ */
1524
+ private performWatchdogAssessment;
1525
+ /** Mark logs the dead executor abandoned, and tell connected clients. */
1526
+ private finalizeLostExecutionLogs;
1527
+ /**
1528
+ * A subagent whose execution the watchdog gave up on leaves its parent
1529
+ * waiting forever for a completion message. Deliver the failure the same way
1530
+ * a sessionFail would, so the parent's turn wakes and can route around it.
1531
+ * Explicit-communication children (e.g. the compaction agent) stay quiet by
1532
+ * contract — only the registry status updates for those.
1533
+ */
1534
+ private notifyParentOfLostExecution;
1535
+ /** At most N auto-resumes per rolling window, tracked durably. */
1536
+ private consumeWatchdogResumeBudget;
1537
+ private normalizePlainRecord;
1538
+ private buildExecutionArguments;
1539
+ /**
1540
+ * Internal method: Execute a flow (called by alarm queue)
1541
+ * This is the actual execution logic, separate from the public execute() RPC method
1542
+ */
1543
+ private executeFlow;
1544
+ /**
1545
+ * Internal method: Execute an effect (called by alarm queue)
1546
+ * Effects run outside the tool execution context.
1547
+ */
1548
+ private executeEffect;
1549
+ /**
1550
+ * Internal method: Process a message (called by alarm queue)
1551
+ * This is the actual message processing logic, separate from the public sendMessage() RPC method
1552
+ */
1553
+ private processMessage;
1554
+ /**
1555
+ * Internal method: Continue execution without adding a message (called by alarm queue)
1556
+ * This allows resuming FlowEngine execution from where it stopped.
1557
+ */
1558
+ private doContinueExecution;
1559
+ private getLatestQueuedMessageSide;
1560
+ /**
1561
+ * TEST METHOD: Queue a test operation
1562
+ * Used for testing alarm queue ordering and timing
1563
+ */
1564
+ queueTestOperation(id: string, label: string, expectedOrder: number, delayMs: number): Promise<Response>;
1565
+ /**
1566
+ * TEST METHOD: Get queue state
1567
+ */
1568
+ getQueueState(): Promise<Response>;
1569
+ /**
1570
+ * TEST METHOD: Get test execution logs
1571
+ */
1572
+ getTestLogs(): Promise<Response>;
1573
+ /**
1574
+ * TEST METHOD: Clear test logs
1575
+ */
1576
+ clearTestLogs(): Promise<Response>;
1577
+ /**
1578
+ * TEST METHOD: Insert a malformed message with orphaned tool calls
1579
+ * This allows testing the tool call filtering logic
1580
+ */
1581
+ insertOrphanedToolCall(params: {
1582
+ content?: string;
1583
+ toolCallId: string;
1584
+ toolName: string;
1585
+ toolArgs: string;
1586
+ }): Promise<Response>;
1587
+ /**
1588
+ * TEST METHOD: Execute a test operation
1589
+ * Internal method called by alarm queue
1590
+ */
1591
+ private testOperation;
1592
+ /**
1593
+ * Get file storage helper instance
1594
+ */
1595
+ private getFileStorage;
1596
+ /**
1597
+ * Write a file to storage (RPC method)
1598
+ */
1599
+ writeFile(path: string, data: string, // base64 encoded
1600
+ mimeType: string, options?: {
1601
+ metadata?: Record<string, unknown>;
1602
+ thumbnail?: string;
1603
+ }): Promise<{
1604
+ success: boolean;
1605
+ file: any;
1606
+ error?: undefined;
1607
+ } | {
1608
+ success: boolean;
1609
+ error: any;
1610
+ file?: undefined;
1611
+ }>;
1612
+ /**
1613
+ * Write a text file to storage (RPC method)
1614
+ */
1615
+ writeTextFile(path: string, content: string, mimeType?: string, options?: {
1616
+ metadata?: Record<string, unknown>;
1617
+ }): Promise<{
1618
+ success: boolean;
1619
+ file: any;
1620
+ error?: undefined;
1621
+ } | {
1622
+ success: boolean;
1623
+ error: any;
1624
+ file?: undefined;
1625
+ }>;
1626
+ /**
1627
+ * Process an image using sip (WASM-based image processing)
1628
+ * This runs inside the DO where WASM is properly initialized.
1629
+ *
1630
+ * @param data - base64 encoded image data
1631
+ * @param mimeType - MIME type of the input image
1632
+ * @returns Processed image data, dimensions, and mimeType
1633
+ */
1634
+ processImage(data: string, mimeType: string): Promise<{
1635
+ success: boolean;
1636
+ data?: string;
1637
+ mimeType?: string;
1638
+ width?: number;
1639
+ height?: number;
1640
+ error?: string;
1641
+ }>;
1642
+ /**
1643
+ * Link to an external file (RPC method)
1644
+ */
1645
+ linkFile(path: string, location: string, options?: {
1646
+ mimeType?: string;
1647
+ size?: number;
1648
+ metadata?: Record<string, unknown>;
1649
+ }): Promise<{
1650
+ success: boolean;
1651
+ file: any;
1652
+ error?: undefined;
1653
+ } | {
1654
+ success: boolean;
1655
+ error: any;
1656
+ file?: undefined;
1657
+ }>;
1658
+ /**
1659
+ * Read a file from storage (RPC method)
1660
+ * Returns base64-encoded data
1661
+ */
1662
+ readFile(path: string): Promise<{
1663
+ success: boolean;
1664
+ data: string;
1665
+ error?: undefined;
1666
+ } | {
1667
+ success: boolean;
1668
+ error: any;
1669
+ data?: undefined;
1670
+ }>;
1671
+ /**
1672
+ * Read a text file from storage (RPC method)
1673
+ */
1674
+ readTextFile(path: string): Promise<{
1675
+ success: boolean;
1676
+ content: any;
1677
+ error?: undefined;
1678
+ } | {
1679
+ success: boolean;
1680
+ error: any;
1681
+ content?: undefined;
1682
+ }>;
1683
+ /**
1684
+ * Get file metadata (RPC method)
1685
+ */
1686
+ statFile(path: string): Promise<{
1687
+ success: boolean;
1688
+ file: any;
1689
+ error?: undefined;
1690
+ } | {
1691
+ success: boolean;
1692
+ error: any;
1693
+ file?: undefined;
1694
+ }>;
1695
+ /**
1696
+ * Check if file exists (RPC method)
1697
+ */
1698
+ fileExists(path: string): Promise<{
1699
+ success: boolean;
1700
+ exists: any;
1701
+ error?: undefined;
1702
+ } | {
1703
+ success: boolean;
1704
+ error: any;
1705
+ exists?: undefined;
1706
+ }>;
1707
+ /**
1708
+ * Delete a file (RPC method)
1709
+ */
1710
+ unlinkFile(path: string): Promise<{
1711
+ success: boolean;
1712
+ error?: undefined;
1713
+ } | {
1714
+ success: boolean;
1715
+ error: any;
1716
+ }>;
1717
+ /**
1718
+ * Create a directory (RPC method)
1719
+ */
1720
+ mkdirFile(path: string): Promise<{
1721
+ success: boolean;
1722
+ directory: any;
1723
+ error?: undefined;
1724
+ } | {
1725
+ success: boolean;
1726
+ error: any;
1727
+ directory?: undefined;
1728
+ }>;
1729
+ /**
1730
+ * List directory contents (RPC method)
1731
+ */
1732
+ readdirFile(path: string): Promise<{
1733
+ success: boolean;
1734
+ files: any;
1735
+ error?: undefined;
1736
+ } | {
1737
+ success: boolean;
1738
+ error: any;
1739
+ files?: undefined;
1740
+ }>;
1741
+ /**
1742
+ * Remove empty directory (RPC method)
1743
+ */
1744
+ rmdirFile(path: string): Promise<{
1745
+ success: boolean;
1746
+ error?: undefined;
1747
+ } | {
1748
+ success: boolean;
1749
+ error: any;
1750
+ }>;
1751
+ /**
1752
+ * Move or rename a file or directory (RPC method).
1753
+ * Relocates inline files, chunked files, and whole directory subtrees.
1754
+ */
1755
+ moveFile(sourcePath: string, destinationPath: string): Promise<{
1756
+ success: boolean;
1757
+ file: any;
1758
+ error?: undefined;
1759
+ } | {
1760
+ success: boolean;
1761
+ error: any;
1762
+ file?: undefined;
1763
+ }>;
1764
+ /**
1765
+ * Rename a file or directory in place (RPC method).
1766
+ */
1767
+ renameFile(path: string, newName: string): Promise<{
1768
+ success: boolean;
1769
+ file: any;
1770
+ error?: undefined;
1771
+ } | {
1772
+ success: boolean;
1773
+ error: any;
1774
+ file?: undefined;
1775
+ }>;
1776
+ /**
1777
+ * Get file storage statistics (RPC method)
1778
+ */
1779
+ getFileStats(): Promise<{
1780
+ success: boolean;
1781
+ stats: any;
1782
+ error?: undefined;
1783
+ } | {
1784
+ success: boolean;
1785
+ error: any;
1786
+ stats?: undefined;
1787
+ }>;
1788
+ /**
1789
+ * Get thumbnail for an image (RPC method)
1790
+ * Returns base64-encoded data
1791
+ */
1792
+ getFileThumbnail(path: string): Promise<{
1793
+ success: boolean;
1794
+ data: string;
1795
+ error?: undefined;
1796
+ } | {
1797
+ success: boolean;
1798
+ error: any;
1799
+ data?: undefined;
1800
+ }>;
1801
+ /**
1802
+ * Search file contents using FTS5 (RPC method)
1803
+ */
1804
+ grepFiles(pattern: string, options?: {
1805
+ path?: string;
1806
+ limit?: number;
1807
+ }): Promise<{
1808
+ success: boolean;
1809
+ results: any;
1810
+ error?: undefined;
1811
+ } | {
1812
+ success: boolean;
1813
+ error: any;
1814
+ results?: undefined;
1815
+ }>;
1816
+ /**
1817
+ * Find files by path pattern (RPC method)
1818
+ */
1819
+ findFiles(pattern: string, options?: {
1820
+ type?: "file" | "directory" | "all";
1821
+ limit?: number;
1822
+ }): Promise<{
1823
+ success: boolean;
1824
+ files: any;
1825
+ error?: undefined;
1826
+ } | {
1827
+ success: boolean;
1828
+ error: any;
1829
+ files?: undefined;
1830
+ }>;
1831
+ /**
1832
+ * Start a chunked file upload.
1833
+ * Creates file record with is_chunked=1 and chunk_count=null.
1834
+ * Caller should then use writeFileChunk() to write chunks.
1835
+ */
1836
+ startChunkedUpload(path: string, totalSize: number, mimeType: string, options?: {
1837
+ metadata?: Record<string, unknown>;
1838
+ width?: number;
1839
+ height?: number;
1840
+ }): Promise<{
1841
+ success: boolean;
1842
+ chunkSize?: number;
1843
+ expectedChunks?: number;
1844
+ error?: string;
1845
+ }>;
1846
+ /**
1847
+ * Write a single chunk of a chunked file upload.
1848
+ * @param path - File path
1849
+ * @param chunkIndex - 0-based chunk index
1850
+ * @param data - Base64 encoded chunk data
1851
+ */
1852
+ writeFileChunk(path: string, chunkIndex: number, data: string): Promise<{
1853
+ success: boolean;
1854
+ error?: string;
1855
+ }>;
1856
+ /**
1857
+ * Complete a chunked file upload.
1858
+ * Validates all chunks are present and sets chunk_count.
1859
+ */
1860
+ completeChunkedUpload(path: string, expectedChunks: number, options?: {
1861
+ thumbnail?: string;
1862
+ }): Promise<{
1863
+ success: boolean;
1864
+ file?: FileRecord;
1865
+ error?: string;
1866
+ }>;
1867
+ /**
1868
+ * Read a single chunk of a file.
1869
+ * Use for streaming large files to client.
1870
+ */
1871
+ readFileChunk(path: string, chunkIndex: number): Promise<{
1872
+ success: boolean;
1873
+ data?: string;
1874
+ error?: string;
1875
+ }>;
1876
+ /**
1877
+ * Get file info including chunking metadata.
1878
+ */
1879
+ getFileInfo(path: string): Promise<{
1880
+ success: boolean;
1881
+ file?: FileRecord;
1882
+ error?: string;
1883
+ }>;
1884
+ }
1885
+
1886
+ interface DurableUserHubEnv {
1887
+ /** Secret JSON registry of runtime-managed grants shared by all users. */
1888
+ AGENT_BUILDER_CREDENTIAL_GRANTS?: string;
1889
+ [key: string]: unknown;
1890
+ }
1891
+ interface HubClientInfo {
1892
+ clientId: string | null;
1893
+ clientName: string | null;
1894
+ clientKind: string | null;
1895
+ }
1896
+ declare class DurableUserHub extends DurableObject<DurableUserHubEnv> {
1897
+ /** Persistent client (daemon) sockets, restored across hibernation. */
1898
+ private clientSockets;
1899
+ private clientInfo;
1900
+ private migrated;
1901
+ constructor(ctx: DurableObjectState, env: DurableUserHubEnv);
1902
+ private ensureMigrated;
1903
+ /**
1904
+ * Returns the user endpoints registry for lazy-loading `users/` files.
1905
+ * Keys are endpoint file paths relative to `users/` with the extension
1906
+ * stripped except the method suffix (e.g. `standardcode/lease_acquire.post`).
1907
+ * Implemented when DurableUserHub is imported from
1908
+ * 'virtual:@standardagents/builder'.
1909
+ */
1910
+ userEndpoints(): Record<string, () => Promise<unknown>>;
1911
+ /**
1912
+ * Returns the hooks registry (same registry the thread runtime uses). The
1913
+ * hub filters it to user-scope hook types at dispatch time. Implemented
1914
+ * when DurableUserHub is imported from 'virtual:@standardagents/builder'.
1915
+ */
1916
+ userHooks(): Record<string, () => Promise<unknown>>;
1917
+ /**
1918
+ * Accept the user's persistent client (daemon) WebSocket. The daemon holds
1919
+ * this ONE socket for its whole lifetime; per-thread bridge sockets are
1920
+ * opened separately and only while a thread is active.
1921
+ */
1922
+ fetch(request: Request): Promise<Response>;
1923
+ /** Idle sockets answer heartbeats at the edge without waking the object.
1924
+ * Registered at accept time rather than in the constructor so a hub that
1925
+ * never accepts a socket stays fully evictable (this also keeps
1926
+ * vitest-pool-workers' isolated storage able to pop the DO's frame). */
1927
+ private ensureHeartbeatAutoResponse;
1928
+ /** Sockets attached to the user event stream, restored after hibernation. */
1929
+ private streamSockets;
1930
+ private acceptUserStream;
1931
+ /**
1932
+ * Deliver an event frame to every socket attached to this user's stream.
1933
+ * At-most-once, live-only (spec: Users §4) — no history, no acks.
1934
+ */
1935
+ broadcastUserEvent(userId: string, event: string, data?: unknown): void;
1936
+ /** Per-user execution chain (spec: Users §2.1) — see users/serialize.ts. */
1937
+ private executionChain;
1938
+ private scopeHost;
1939
+ private runUserEndpoint;
1940
+ /**
1941
+ * Fire every definition of a user hook type. Observational and best-effort:
1942
+ * failures are swallowed and dispatch never blocks the triggering
1943
+ * operation. Nested dispatch is suppressed so a `user_value_changed` hook
1944
+ * writing values cannot recurse.
1945
+ */
1946
+ private inUserHookDispatch;
1947
+ private dispatchUserHooks;
1948
+ webSocketClose(ws: WebSocket): Promise<void>;
1949
+ /**
1950
+ * Store or replace a grant. `secret` is write-only from this point on.
1951
+ * Policy (`CredentialGrant` minus the secret) is kept as JSON config.
1952
+ */
1953
+ setGrant(userId: string, grant: CredentialGrant, secret: string): Promise<void>;
1954
+ deleteGrant(userId: string, name: string): Promise<void>;
1955
+ /** Metadata-only listing — never returns secret material. */
1956
+ listGrants(userId: string): Promise<Array<Omit<CredentialGrant, "name"> & {
1957
+ name: string;
1958
+ }>>;
1959
+ /** Perform a privileged fetch with the grant's credential injected. */
1960
+ private grantFetch;
1961
+ private handleGrantFetch;
1962
+ webSocketMessage(ws: WebSocket, _message: string | ArrayBuffer): Promise<void>;
1963
+ webSocketError(ws: WebSocket): Promise<void>;
1964
+ /** Whether a persistent client (daemon) is connected right now. */
1965
+ hasClient(): Promise<boolean>;
1966
+ /**
1967
+ * Signal the connected daemon to attach a bridge to `threadId`. Called by a
1968
+ * cold thread DO that parked a forwarded call with no client attached. The
1969
+ * daemon reacts by opening a per-thread bridge socket, which triggers the
1970
+ * thread's drain-on-attach. Returns whether a daemon was reachable.
1971
+ */
1972
+ requestWake(threadId: string): Promise<{
1973
+ delivered: boolean;
1974
+ }>;
1975
+ getUserValue(userId: string, key: string): Promise<unknown | null>;
1976
+ setUserValue(userId: string, key: string, value: unknown): Promise<void>;
1977
+ listUserValues(userId: string, options?: {
1978
+ prefix?: string | null;
1979
+ limit?: number;
1980
+ offset?: number;
1981
+ }): Promise<{
1982
+ entries: Array<{
1983
+ key: string;
1984
+ value: unknown;
1985
+ updated_at: number;
1986
+ }>;
1987
+ total: number;
1988
+ limit: number;
1989
+ offset: number;
1990
+ }>;
1991
+ }
1992
+
1993
+ type EnvValueType = 'text' | 'secret';
1994
+ /**
1995
+ * Environment type for DurableAgentBuilder.
1996
+ * Users extend this with their own bindings.
1997
+ */
1998
+ interface AgentBuilderEnv {
1999
+ AGENT_BUILDER: DurableObjectNamespace<DurableAgentBuilder>;
2000
+ AGENT_BUILDER_THREAD: DurableObjectNamespace;
2001
+ AGENT_BUILDER_USER_HUB?: DurableObjectNamespace<DurableUserHub>;
2002
+ ENCRYPTION_KEY?: string;
2003
+ }
2004
+ /**
2005
+ * Thread metadata stored in the registry.
2006
+ */
2007
+ interface ThreadRegistryEntry {
2008
+ id: string;
2009
+ agent_name: string;
2010
+ /**
2011
+ * Agent the thread was CREATED on. Never changed by handoffs
2012
+ * (updateThreadAgent only re-points agent_name), so lists can keep a
2013
+ * handed-off conversation visible on its original agent's page.
2014
+ */
2015
+ origin_agent_name?: string | null;
2016
+ user_id: string | null;
2017
+ tags: string[] | null;
2018
+ env: Record<string, string> | null;
2019
+ env_types: Record<string, EnvValueType> | null;
2020
+ /** @deprecated Use env */
2021
+ tenvs: Record<string, unknown> | null;
2022
+ properties: Record<string, unknown> | null;
2023
+ parent: string | null;
2024
+ terminated: number | null;
2025
+ created_at: number;
2026
+ /** Unix seconds of the last message or execution on this thread (or a descendant). */
2027
+ last_activity_at?: number | null;
2028
+ /** True while the thread is executing a flow (stale markers read as false). */
2029
+ executing?: boolean;
2030
+ /** Short excerpt of the most recent user message, for thread-list rows. */
2031
+ last_message_preview?: string | null;
2032
+ /**
2033
+ * Unix seconds of the newest VISIBLE MESSAGE on this thread — the one field
2034
+ * clients key unread indicators on. It moves when a non-empty user (or
2035
+ * operator assistant-role) message arrives, and when a visible terminal
2036
+ * assistant record lands (`isVisibleTerminalAssistantMessage`): terminal
2037
+ * answers, attachment-only replies, and failed rows with visible text — but
2038
+ * never mid-turn tool-calling steps, silent rows, sub-prompt records, or
2039
+ * background execution activity (which move only `last_activity_at`).
2040
+ * Monotonic per thread and never propagated to ancestors.
2041
+ */
2042
+ last_message_at?: number | null;
2043
+ }
2044
+ /**
2045
+ * Safe registry projection carried by system events. Thread env and arbitrary
2046
+ * properties are intentionally excluded: the stream is an invalidation/list
2047
+ * surface, not a second transport for thread configuration or secrets.
2048
+ */
2049
+ type ThreadEventPayload = Pick<ThreadRegistryEntry, 'id' | 'agent_name' | 'origin_agent_name' | 'user_id' | 'tags' | 'parent' | 'terminated' | 'created_at' | 'last_activity_at' | 'executing' | 'last_message_preview' | 'last_message_at'>;
2050
+ interface PendingSubagentAttachmentRef {
2051
+ path: string;
2052
+ name?: string;
2053
+ mimeType?: string;
2054
+ size?: number;
2055
+ width?: number;
2056
+ height?: number;
2057
+ }
2058
+ interface PendingSubagentEnvRequestPayload {
2059
+ blocking: boolean;
2060
+ /** Relationship name (`as` ?? agent) the spawn was requested under. */
2061
+ relationship?: string;
2062
+ /** Which parent side OWNS the relationship ('a' when unrecorded). */
2063
+ owner?: 'a' | 'b';
2064
+ parent_communication: 'implicit' | 'explicit';
2065
+ initial_message_content: string;
2066
+ initial_message_attachments: PendingSubagentAttachmentRef[];
2067
+ initial_arguments?: Record<string, unknown>;
2068
+ initial_agent_name?: string | null;
2069
+ agent_title?: string | null;
2070
+ agent_description?: string | null;
2071
+ spawn_group_id?: string | null;
2072
+ /** Invocation arguments persisted for the life of the child thread. */
2073
+ arguments?: Record<string, unknown>;
2074
+ }
2075
+ interface PendingSubagentEnvRequest {
2076
+ request_id: string;
2077
+ parent_thread_id: string;
2078
+ agent_name: string;
2079
+ registry_agent_name: string;
2080
+ required: string[];
2081
+ missing: string[];
2082
+ payload: PendingSubagentEnvRequestPayload;
2083
+ created_at: number;
2084
+ }
2085
+ /**
2086
+ * Parameters for updating a thread.
2087
+ */
2088
+ interface UpdateThreadParams {
2089
+ agent_name?: string;
2090
+ user_id?: string | null;
2091
+ tags?: string[] | null;
2092
+ env?: Record<string, string> | null;
2093
+ env_types?: Record<string, EnvValueType> | null;
2094
+ /** @deprecated Use env */
2095
+ tenvs?: Record<string, unknown> | null;
2096
+ properties?: Record<string, unknown> | null;
2097
+ parent?: string | null;
2098
+ terminated?: number | null;
2099
+ }
2100
+ /**
2101
+ * User record.
2102
+ */
2103
+ type InstanceRole = 'admin' | 'user' | 'api';
2104
+ interface User {
2105
+ id: string;
2106
+ username: string;
2107
+ password_hash: string;
2108
+ role: InstanceRole;
2109
+ /** Explicit permission grants (e.g. 'logs'); null = legacy default. */
2110
+ permissions?: string[] | null;
2111
+ platform_user_id?: string | null;
2112
+ email?: string | null;
2113
+ display_name?: string | null;
2114
+ avatar_url?: string | null;
2115
+ source?: 'local' | 'standard_agents';
2116
+ replica_active?: number;
2117
+ created_at: number;
2118
+ updated_at: number;
2119
+ }
2120
+ interface PlatformReplicaUser {
2121
+ platform_user_id: string;
2122
+ username?: string | null;
2123
+ email?: string | null;
2124
+ display_name?: string | null;
2125
+ avatar_url?: string | null;
2126
+ role: InstanceRole;
2127
+ permissions?: string[] | null;
2128
+ session_revoked_at?: number | null;
2129
+ }
2130
+ interface PlatformReplicaApiKey {
2131
+ id: string;
2132
+ name?: string | null;
2133
+ key_hash: string;
2134
+ key_prefix: string;
2135
+ last_five?: string | null;
2136
+ user_platform_id?: string | null;
2137
+ scope?: string | null;
2138
+ created_at?: number | null;
2139
+ }
2140
+ interface PlatformReplicaSnapshot {
2141
+ users: PlatformReplicaUser[];
2142
+ api_keys?: PlatformReplicaApiKey[];
2143
+ }
2144
+ interface ScopedEnvEntry {
2145
+ name: string;
2146
+ value: string;
2147
+ type: EnvValueType;
2148
+ created_at: number;
2149
+ updated_at: number;
2150
+ }
2151
+ /**
2152
+ * Provider credentials.
2153
+ */
2154
+ interface Provider$1 {
2155
+ name: string;
2156
+ sdk: string;
2157
+ api_key: string;
2158
+ }
2159
+ /**
2160
+ * Lightweight agent metadata included with real-time thread events.
2161
+ */
2162
+ interface ThreadEventAgent {
2163
+ name: string;
2164
+ title: string;
2165
+ side_a_backing: 'human' | 'prompt' | 'handler';
2166
+ side_b_backing: 'human' | 'prompt' | 'handler';
2167
+ description?: string;
2168
+ icon?: string;
2169
+ }
2170
+ /**
2171
+ * DurableAgentBuilder - The root Durable Object for AgentBuilder.
2172
+ *
2173
+ * This is a singleton DO that stores:
2174
+ * - Thread registry (maps thread IDs to agent names)
2175
+ * - User authentication data
2176
+ * - Provider credentials (API keys for LLM providers)
2177
+ * - Edit lock state for coordinated edits
2178
+ *
2179
+ * ## Usage
2180
+ *
2181
+ * Users must extend this class to provide virtual module access:
2182
+ *
2183
+ * ```typescript
2184
+ * import { DurableAgentBuilder } from '@standardagents/builder/runtime';
2185
+ * import { models } from 'virtual:@standardagents-models';
2186
+ * import { prompts } from 'virtual:@standardagents-prompts';
2187
+ * import { agents } from 'virtual:@standardagents-agents';
2188
+ *
2189
+ * export class AgentBuilder extends DurableAgentBuilder {
2190
+ * models() { return models; }
2191
+ * prompts() { return prompts; }
2192
+ * agents() { return agents; }
2193
+ * }
2194
+ * ```
2195
+ */
2196
+ /**
2197
+ * Event types that can be emitted via WebSocket
2198
+ */
2199
+ type AgentBuilderEvent = {
2200
+ type: 'thread_created';
2201
+ thread: ThreadEventPayload & {
2202
+ agent?: ThreadEventAgent;
2203
+ };
2204
+ } | {
2205
+ type: 'thread_updated';
2206
+ thread: ThreadEventPayload & {
2207
+ agent?: ThreadEventAgent;
2208
+ };
2209
+ } | {
2210
+ type: 'thread_deleted';
2211
+ threadId: string;
2212
+ }
2213
+ /**
2214
+ * Lightweight activity signal. Kept separate from `thread_updated` because it
2215
+ * fires on every execution start/stop: re-broadcasting the whole registry
2216
+ * entry would decrypt thread env on each transition for data that never
2217
+ * changed.
2218
+ */
2219
+ | {
2220
+ type: 'thread_activity';
2221
+ threadId: string;
2222
+ /** Present only when this event actually wrote the field: a message-only
2223
+ * recency stamp omits last_activity_at, and `executing` rides only on a
2224
+ * real transition — clients must leave their current value alone for
2225
+ * absent fields. */
2226
+ last_activity_at?: number;
2227
+ executing?: boolean;
2228
+ last_message_preview?: string | null;
2229
+ last_message_at?: number | null;
2230
+ };
2231
+ /** Sort orders supported by `listThreads`. */
2232
+ type ThreadListSort = 'activity' | 'created' | 'oldest';
2233
+ declare class DurableAgentBuilder<Env extends AgentBuilderEnv = AgentBuilderEnv> extends DurableObject<Env> {
2234
+ private migratedToVersion;
2235
+ private eventSockets;
2236
+ constructor(ctx: DurableObjectState, env: Env);
2237
+ private normalizeEnvRecord;
2238
+ private normalizePlainObject;
2239
+ private hasInitialArguments;
2240
+ private buildSubagentThreadProperties;
2241
+ private buildSubagentInitialArgumentsMessage;
2242
+ private normalizeEnvTypeRecord;
2243
+ private extractEnvTypeRecord;
2244
+ private withEnvTypeRecord;
2245
+ private serializeEnvTypes;
2246
+ private resolveRegistryKey;
2247
+ private extractScopedVariables;
2248
+ private filterScopedInheritedEnv;
2249
+ private filterScopedInheritedEnvTypes;
2250
+ private collectScopedVariablesForAgent;
2251
+ private getScopedVariableNamesForAgent;
2252
+ private getRequiredScopedVariableNamesForAgent;
2253
+ private normalizeScopedVariableList;
2254
+ private normalizePendingAttachments;
2255
+ private sanitizeFilename;
2256
+ private inferMimeTypeFromPath;
2257
+ private extensionForMimeType;
2258
+ private buildAttachmentTargetPath;
2259
+ private formatSubagentAttachmentPathSummary;
2260
+ private formatSubagentTerminalMessage;
2261
+ private copyPendingAttachmentsBetweenThreads;
2262
+ private buildThreadNameTag;
2263
+ private encryptEnvRecord;
2264
+ private decryptEnvRecord;
2265
+ private listActiveDescendantThreadIds;
2266
+ private propagateThreadEnvToDescendants;
2267
+ /**
2268
+ * Returns the tools registry for lazy-loading tool definitions.
2269
+ * Must be overridden in a subclass.
2270
+ */
2271
+ tools(): Record<string, () => Promise<any>>;
2272
+ /**
2273
+ * Returns the hooks registry for lazy-loading hook definitions.
2274
+ * Must be overridden in a subclass.
2275
+ */
2276
+ hooks(): Record<string, () => Promise<any>>;
2277
+ /**
2278
+ * Returns the models registry for lazy-loading model definitions.
2279
+ * Must be overridden in a subclass.
2280
+ */
2281
+ models(): Record<string, () => Promise<any>>;
2282
+ /**
2283
+ * Returns the prompts registry for lazy-loading prompt definitions.
2284
+ * Must be overridden in a subclass.
2285
+ */
2286
+ prompts(): Record<string, () => Promise<any>>;
2287
+ /**
2288
+ * Returns the agents registry for lazy-loading agent definitions.
2289
+ * Must be overridden in a subclass.
2290
+ */
2291
+ agents(): Record<string, () => Promise<any>>;
2292
+ /**
2293
+ * Returns the namespaced registry for packed agent support.
2294
+ * Must be overridden in a subclass.
2295
+ */
2296
+ registry(): any;
2297
+ private ensureMigrated;
2298
+ private getCurrentVersion;
2299
+ private runMigrations;
2300
+ /**
2301
+ * Create a new thread and add it to the registry.
2302
+ */
2303
+ createThread(params: {
2304
+ agent_name: string;
2305
+ user_id?: string;
2306
+ tags?: string[];
2307
+ env?: Record<string, string>;
2308
+ env_types?: Record<string, EnvValueType>;
2309
+ /** @deprecated Use env */
2310
+ tenvs?: Record<string, unknown>;
2311
+ properties?: Record<string, unknown>;
2312
+ parent?: string;
2313
+ }): Promise<ThreadRegistryEntry>;
2314
+ /**
2315
+ * Spawn `immediate` subagent relationships at THREAD CREATION, before any
2316
+ * side takes a turn — required even when the owning side is a handler, or
2317
+ * when the first inbound message arrives instantly. Spawns run through the
2318
+ * normal `subagent_create` machinery (registry, scoped env, hidden,
2319
+ * maxInstances) via the standalone invokeTool path. A relationship whose
2320
+ * child demands invocation arguments this path cannot synthesize fails
2321
+ * softly here; the FlowEngine immediate runner bootstraps it with an
2322
+ * internal model call before the owning side's first turn.
2323
+ */
2324
+ private spawnImmediateSubagents;
2325
+ private runAfterThreadCreatedHook;
2326
+ /**
2327
+ * Get a thread by ID.
2328
+ */
2329
+ getThread(id: string): Promise<ThreadRegistryEntry | null>;
2330
+ /**
2331
+ * All descendant threads of a root thread (children, grandchildren, …),
2332
+ * excluding the root itself. Used for subtree cost reporting: a thread's
2333
+ * displayed cost is its own plus every subagent thread it spawned,
2334
+ * recursively. Ordered parents-before-children (breadth by creation time).
2335
+ */
2336
+ getDescendantThreads(rootId: string): Promise<Array<{
2337
+ id: string;
2338
+ agent_name: string;
2339
+ parent: string | null;
2340
+ tags: string[] | null;
2341
+ terminated: number | null;
2342
+ created_at: number;
2343
+ }>>;
2344
+ /**
2345
+ * List threads with optional filtering.
2346
+ * Note: tenvs are not decrypted in list operations for performance.
2347
+ * Use getThread() to retrieve a thread with decrypted tenvs.
2348
+ */
2349
+ listThreads(params?: {
2350
+ agent_name?: string;
2351
+ user_id?: string;
2352
+ search?: string;
2353
+ startDate?: number;
2354
+ endDate?: number;
2355
+ limit?: number;
2356
+ offset?: number;
2357
+ include_children?: boolean;
2358
+ /** Default `activity`: most recently worked-on threads first. */
2359
+ sort?: ThreadListSort;
2360
+ /** `true` → only threads currently executing; `false` → only idle ones. */
2361
+ executing?: boolean;
2362
+ /** `false` hides terminated threads; `true` shows only terminated ones. */
2363
+ terminated?: boolean;
2364
+ }): Promise<{
2365
+ threads: ThreadRegistryEntry[];
2366
+ total: number;
2367
+ }>;
2368
+ /**
2369
+ * Distinct owners of threads visible to the caller, with counts, so a thread
2370
+ * list can offer an "owner" filter without exposing the admin-only user
2371
+ * directory (which is unavailable on hosted instances).
2372
+ */
2373
+ listThreadOwners(params?: {
2374
+ user_id?: string;
2375
+ }): Promise<Array<{
2376
+ user_id: string | null;
2377
+ username: string | null;
2378
+ display_name: string | null;
2379
+ email: string | null;
2380
+ thread_count: number;
2381
+ }>>;
2382
+ /**
2383
+ * Record that a thread did work: stamp `last_activity_at` and flip the
2384
+ * executing marker. Activity bubbles up the parent chain so a root thread
2385
+ * sorts by the freshest work anywhere in its subagent tree — otherwise a
2386
+ * long-running subagent would let its parent sink down an activity-sorted
2387
+ * list.
2388
+ */
2389
+ recordThreadActivity(threadId: string, options?: {
2390
+ executing?: boolean;
2391
+ messagePreview?: string | null;
2392
+ messageAt?: number;
2393
+ }): Promise<void>;
2394
+ /**
2395
+ * Fill in previews for threads that predate preview tracking. Callers read
2396
+ * each thread's newest user message and stamp the results here in one batch.
2397
+ *
2398
+ * A thread with no user message is stamped with an empty string rather than
2399
+ * left NULL: NULL means "not looked at yet", so without the sentinel an
2400
+ * empty thread would be re-read on every list request forever.
2401
+ */
2402
+ backfillThreadPreviews(entries: Array<{
2403
+ id: string;
2404
+ preview: string | null;
2405
+ }>): Promise<void>;
2406
+ /**
2407
+ * Delete a thread from the registry.
2408
+ */
2409
+ deleteThread(id: string): Promise<boolean>;
2410
+ /**
2411
+ * Delete all singleton AgentBuilder storage for platform-owned teardown.
2412
+ * Used when the hosting platform expires a preview branch deployment after
2413
+ * all thread Durable Objects have already been wiped.
2414
+ */
2415
+ deleteAllStorage(): Promise<{
2416
+ success: boolean;
2417
+ message: string;
2418
+ }>;
2419
+ /**
2420
+ * Get a thread tree (root + all descendants) in child-first order.
2421
+ *
2422
+ * Child-first ordering allows callers to perform destructive operations
2423
+ * (like deletes) without leaving child rows referencing a deleted parent.
2424
+ */
2425
+ getThreadTreeIds(rootThreadId: string): Promise<string[]>;
2426
+ /**
2427
+ * Update a thread's agent_name (used during agent handoff).
2428
+ * origin_agent_name is deliberately untouched — it pins the thread to the
2429
+ * agent page it started on. Broadcasts thread_updated so connected clients
2430
+ * re-render the row immediately instead of on the next activity tick
2431
+ * (which is when handed-off threads used to silently vanish mid-watch).
2432
+ */
2433
+ updateThreadAgent(id: string, agent_name: string): Promise<boolean>;
2434
+ /**
2435
+ * Update a thread's metadata.
2436
+ */
2437
+ updateThread(id: string, params: UpdateThreadParams): Promise<ThreadRegistryEntry | null>;
2438
+ private getEncryptionKey;
2439
+ private encryptEnvValue;
2440
+ private decryptEnvValue;
2441
+ private listScopedEnv;
2442
+ private listScopedEnvEntries;
2443
+ private getScopedEnvTypeRecord;
2444
+ private replaceScopedEnv;
2445
+ private patchScopedEnv;
2446
+ getInstanceEnv(): Promise<Record<string, string>>;
2447
+ getInstanceEnvTypes(): Promise<Record<string, EnvValueType>>;
2448
+ getInstanceEnvEntries(): Promise<ScopedEnvEntry[]>;
2449
+ setInstanceEnv(env: Record<string, string>, envTypes?: Record<string, EnvValueType> | null): Promise<void>;
2450
+ patchInstanceEnv(params: {
2451
+ env_patch?: Record<string, unknown> | null;
2452
+ env_type_patch?: Record<string, unknown> | null;
2453
+ env_delete?: string[] | null;
2454
+ }): Promise<void>;
2455
+ getUserEnv(userId: string): Promise<Record<string, string>>;
2456
+ getUserEnvTypes(userId: string): Promise<Record<string, EnvValueType>>;
2457
+ getUserEnvEntries(userId: string): Promise<ScopedEnvEntry[]>;
2458
+ setUserEnv(userId: string, env: Record<string, string>, envTypes?: Record<string, EnvValueType> | null): Promise<void>;
2459
+ patchUserEnv(userId: string, params: {
2460
+ env_patch?: Record<string, unknown> | null;
2461
+ env_type_patch?: Record<string, unknown> | null;
2462
+ env_delete?: string[] | null;
2463
+ }): Promise<void>;
2464
+ private assertValidUserValueKey;
2465
+ private assertValidUserValueUserId;
2466
+ /**
2467
+ * The per-user hub is the sharded home for account-wide KV. When the binding
2468
+ * exists, the singleton delegates so the global object is no longer a
2469
+ * per-user bottleneck; without it (pre-hub deploys, unit tests) it keeps the
2470
+ * local `user_values` table.
2471
+ */
2472
+ private userHub;
2473
+ /** Read one JSON value from a user's account-wide key-value store. */
2474
+ getUserValue(userId: string, key: string): Promise<unknown | null>;
2475
+ /** Write one JSON value to a user's account-wide store; null/undefined deletes. */
2476
+ setUserValue(userId: string, key: string, value: unknown): Promise<void>;
2477
+ /** List a user's account-wide values, optionally filtered by key prefix. */
2478
+ listUserValues(userId: string, options?: {
2479
+ prefix?: string | null;
2480
+ limit?: number;
2481
+ offset?: number;
2482
+ }): Promise<{
2483
+ entries: Array<{
2484
+ key: string;
2485
+ value: unknown;
2486
+ updated_at: number;
2487
+ }>;
2488
+ total: number;
2489
+ limit: number;
2490
+ offset: number;
2491
+ }>;
2492
+ getMissingRequiredScopedSubagentEnv(params: {
2493
+ parent_thread_id: string;
2494
+ agent_name: string;
2495
+ provided_env?: Record<string, string> | null;
2496
+ }): Promise<string[]>;
2497
+ createPendingSubagentEnvRequest(params: {
2498
+ parent_thread_id: string;
2499
+ agent_name: string;
2500
+ registry_agent_name: string;
2501
+ required_variables: string[];
2502
+ missing_variables: string[];
2503
+ payload: PendingSubagentEnvRequestPayload;
2504
+ }): Promise<PendingSubagentEnvRequest>;
2505
+ getPendingSubagentEnvRequest(parentThreadId: string, requestId: string): Promise<PendingSubagentEnvRequest | null>;
2506
+ private clearPendingSubagentEnvRequest;
2507
+ completePendingSubagentEnvRequest(params: {
2508
+ parent_thread_id: string;
2509
+ request_id: string;
2510
+ env: Record<string, string>;
2511
+ }): Promise<{
2512
+ request_id: string;
2513
+ child_thread_id: string;
2514
+ status: 'success';
2515
+ }>;
2516
+ resolveThreadEnv(params: {
2517
+ threadId: string;
2518
+ property: string;
2519
+ promptName?: string;
2520
+ }): Promise<string | null>;
2521
+ resolveThreadEnvType(params: {
2522
+ threadId: string;
2523
+ property: string;
2524
+ promptName?: string;
2525
+ }): Promise<EnvValueType>;
2526
+ private toThreadEventPayload;
2527
+ /**
2528
+ * Load a model definition by name.
2529
+ */
2530
+ loadModel(name: string): Promise<any>;
2531
+ /**
2532
+ * List available model names.
2533
+ */
2534
+ getModelNames(): string[];
2535
+ /**
2536
+ * Load a prompt definition by name.
2537
+ */
2538
+ loadPrompt(name: string): Promise<any>;
2539
+ /**
2540
+ * List available prompt names.
2541
+ */
2542
+ getPromptNames(): string[];
2543
+ /**
2544
+ * Load an agent definition by name.
2545
+ * Supports both global agents (e.g., "my-agent") and packed agents (e.g., "packageId/agentName").
2546
+ * For scoped packages, use "@scope/pkg/agentName".
2547
+ */
2548
+ loadAgent(name: string): Promise<any>;
2549
+ /**
2550
+ * List available agent names.
2551
+ */
2552
+ getAgentNames(): string[];
2553
+ /**
2554
+ * Get a provider's credentials.
2555
+ */
2556
+ getProvider(name: string): Promise<Provider$1 | null>;
2557
+ /**
2558
+ * Set a provider's credentials.
2559
+ */
2560
+ setProvider(provider: Provider$1): Promise<void>;
2561
+ /**
2562
+ * List all providers.
2563
+ */
2564
+ listProviders(): Promise<Provider$1[]>;
2565
+ /**
2566
+ * Delete a provider.
2567
+ */
2568
+ deleteProvider(name: string): Promise<boolean>;
2569
+ private normalizeReplicaUsername;
2570
+ private availableReplicaUsername;
2571
+ private userFromRow;
2572
+ /**
2573
+ * Get a user by username.
2574
+ */
2575
+ getUserByUsername(username: string): Promise<User | null>;
2576
+ /**
2577
+ * Get a user by ID.
2578
+ */
2579
+ getUserById(id: string): Promise<User | null>;
2580
+ /**
2581
+ * Create a new user.
2582
+ */
2583
+ createUser(params: {
2584
+ username: string;
2585
+ password_hash: string;
2586
+ role?: InstanceRole;
2587
+ permissions?: string[] | null;
2588
+ platform_user_id?: string | null;
2589
+ email?: string | null;
2590
+ display_name?: string | null;
2591
+ avatar_url?: string | null;
2592
+ source?: 'local' | 'standard_agents';
2593
+ }): Promise<User>;
2594
+ /**
2595
+ * Check if any users exist (for first-time setup).
2596
+ */
2597
+ hasUsers(): Promise<boolean>;
2598
+ /**
2599
+ * List all users (excludes password hash).
2600
+ */
2601
+ listUsers(): Promise<Array<{
2602
+ id: string;
2603
+ username: string;
2604
+ role: InstanceRole;
2605
+ platform_user_id: string | null;
2606
+ email: string | null;
2607
+ display_name: string | null;
2608
+ avatar_url: string | null;
2609
+ source: 'local' | 'standard_agents';
2610
+ replica_active: number;
2611
+ created_at: number;
2612
+ updated_at: number;
2613
+ }>>;
2614
+ /**
2615
+ * Update a user.
2616
+ */
2617
+ updateUser(id: string, params: {
2618
+ username?: string;
2619
+ password_hash?: string;
2620
+ role?: InstanceRole;
2621
+ permissions?: string[] | null;
2622
+ platform_user_id?: string | null;
2623
+ email?: string | null;
2624
+ display_name?: string | null;
2625
+ avatar_url?: string | null;
2626
+ source?: 'local' | 'standard_agents';
2627
+ replica_active?: number;
2628
+ }): Promise<User | null>;
2629
+ /**
2630
+ * Delete a user.
2631
+ */
2632
+ deleteUser(id: string): Promise<boolean>;
2633
+ /**
2634
+ * Upsert a platform-replicated identity and return the local user row.
2635
+ */
2636
+ upsertPlatformReplicaUser(replica: PlatformReplicaUser): Promise<User>;
2637
+ /**
2638
+ * Apply a full platform read-replica snapshot for this instance.
2639
+ */
2640
+ applyPlatformReplicaSnapshot(snapshot: PlatformReplicaSnapshot): Promise<{
2641
+ users: number;
2642
+ api_keys: number;
2643
+ }>;
2644
+ getUserByPlatformUserId(platformUserId: string): Promise<User | null>;
2645
+ private getFirstReplicaAdminUser;
2646
+ private upsertPlatformReplicaApiKey;
2647
+ /**
2648
+ * Create a new session.
2649
+ */
2650
+ createSession(params: {
2651
+ user_id: string;
2652
+ token_hash: string;
2653
+ expires_at: number;
2654
+ }): Promise<string>;
2655
+ /**
2656
+ * Validate a session token.
2657
+ */
2658
+ validateSession(tokenHash: string): Promise<{
2659
+ user_id: string;
2660
+ expires_at: number;
2661
+ } | null>;
2662
+ /**
2663
+ * Delete expired sessions.
2664
+ */
2665
+ cleanupSessions(): Promise<number>;
2666
+ /**
2667
+ * Delete a session.
2668
+ */
2669
+ deleteSession(tokenHash: string): Promise<void>;
2670
+ /** Register a short-lived super-admin token so it can be revoked alone. */
2671
+ createSuperAdminSession(params: {
2672
+ token_hash: string;
2673
+ expires_at: number;
2674
+ }): Promise<void>;
2675
+ /** A valid signature is insufficient: the session must still be registered. */
2676
+ validateSuperAdminSession(tokenHash: string): Promise<boolean>;
2677
+ /** Revoke only the presented super-admin session; no key rotation required. */
2678
+ deleteSuperAdminSession(tokenHash: string): Promise<void>;
2679
+ /** Register a path-bound bearer ticket for one WebSocket handshake. */
2680
+ createWebSocketTicket(params: {
2681
+ ticket_hash: string;
2682
+ pathname: string;
2683
+ auth_json: string;
2684
+ expires_at: number;
2685
+ }): Promise<void>;
2686
+ /**
2687
+ * Atomically consume a WebSocket ticket. Deleting before validating its path
2688
+ * means even a mistaken or malicious first presentation burns the bearer.
2689
+ */
2690
+ consumeWebSocketTicket(params: {
2691
+ ticket_hash: string;
2692
+ pathname: string;
2693
+ }): Promise<string | null>;
2694
+ /** Atomically accept an unexpired platform handoff identifier once. */
2695
+ consumePlatformHandoffJti(params: {
2696
+ jti: string;
2697
+ expires_at: number;
2698
+ }): Promise<boolean>;
2699
+ /**
2700
+ * Atomically consume one attempt from a fixed-window authentication bucket.
2701
+ * The singleton Durable Object serializes calls, preventing parallel bypass.
2702
+ */
2703
+ consumeAuthRateLimit(params: {
2704
+ key: string;
2705
+ limit: number;
2706
+ window_seconds: number;
2707
+ }): Promise<{
2708
+ allowed: boolean;
2709
+ retry_after: number;
2710
+ remaining: number;
2711
+ }>;
2712
+ /**
2713
+ * Create an API key.
2714
+ */
2715
+ createApiKey(params: {
2716
+ name: string;
2717
+ key_hash: string;
2718
+ key_prefix: string;
2719
+ last_five: string;
2720
+ user_id: string;
2721
+ }): Promise<string>;
2722
+ /**
2723
+ * Validate an API key.
2724
+ */
2725
+ validateApiKey(keyHash: string): Promise<{
2726
+ user_id: string;
2727
+ id: string;
2728
+ } | null>;
2729
+ /**
2730
+ * List API keys for a user.
2731
+ */
2732
+ listApiKeys(userId: string): Promise<Array<{
2733
+ id: string;
2734
+ name: string;
2735
+ key_prefix: string;
2736
+ last_five: string;
2737
+ source: 'local' | 'standard_agents';
2738
+ created_at: number;
2739
+ last_used_at: number | null;
2740
+ }>>;
2741
+ /**
2742
+ * Delete an API key.
2743
+ */
2744
+ deleteApiKey(id: string, userId: string): Promise<boolean>;
2745
+ /**
2746
+ * Link an OAuth account to a user.
2747
+ */
2748
+ linkOAuthAccount(params: {
2749
+ user_id: string;
2750
+ provider: 'github' | 'google';
2751
+ provider_user_id: string;
2752
+ provider_username?: string;
2753
+ }): Promise<void>;
2754
+ /**
2755
+ * Find user by OAuth account.
2756
+ */
2757
+ findUserByOAuth(provider: 'github' | 'google', providerUserId: string): Promise<User | null>;
2758
+ /**
2759
+ * Acquire edit lock for coordinated edits.
2760
+ */
2761
+ acquireEditLock(params: {
2762
+ locked_by: string;
2763
+ lock_reason: string;
2764
+ }): Promise<boolean>;
2765
+ /**
2766
+ * Release edit lock.
2767
+ */
2768
+ releaseEditLock(lockedBy: string): Promise<boolean>;
2769
+ /**
2770
+ * Get current lock state.
2771
+ */
2772
+ getEditLockState(): Promise<{
2773
+ locked: boolean;
2774
+ locked_by: string | null;
2775
+ locked_at: number | null;
2776
+ lock_reason: string | null;
2777
+ pending_changes: string | null;
2778
+ }>;
2779
+ /**
2780
+ * Store pending changes for commit.
2781
+ */
2782
+ setPendingChanges(changes: string): Promise<void>;
2783
+ /**
2784
+ * Get the Durable Object stub for a thread.
2785
+ */
2786
+ getThreadStub(threadId: string): DurableObjectStub;
2787
+ /**
2788
+ * Handle fetch requests - used for WebSocket upgrades
2789
+ */
2790
+ fetch(request: Request): Promise<Response>;
2791
+ /**
2792
+ * Handle WebSocket upgrade for events channel
2793
+ * Uses Hibernation API to reduce costs during inactivity
2794
+ */
2795
+ private handleEventsWebSocketUpgrade;
2796
+ /**
2797
+ * Re-broadcast a `thread_updated` for a single thread to all event listeners.
2798
+ *
2799
+ * Subagent running/idle status lives in the *parent's* child registry, not on
2800
+ * the thread row, so a status change (e.g. running → idle) normally produces
2801
+ * no thread-registry event. The child-registry writer calls this so live
2802
+ * listeners (the CLI subagent indicator) re-read `/api/threads/:id/subagents`
2803
+ * and reflect the new status without polling.
2804
+ */
2805
+ broadcastThreadUpdated(threadId: string): Promise<void>;
2806
+ /**
2807
+ * Broadcast an event only to its owner or an explicitly all-scoped admin.
2808
+ */
2809
+ private broadcastEvent;
2810
+ /** Resolve a thread owner without decrypting its env or loading the row. */
2811
+ private getThreadOwnerId;
2812
+ /**
2813
+ * WebSocket Hibernation API handler for incoming messages
2814
+ * Called when a message is received on a hibernated WebSocket
2815
+ */
2816
+ webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void>;
2817
+ /**
2818
+ * WebSocket Hibernation API handler for connection close
2819
+ * Called when a WebSocket connection is closed
2820
+ */
2821
+ webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean): Promise<void>;
2822
+ /**
2823
+ * WebSocket Hibernation API handler for errors
2824
+ * Called when a WebSocket encounters an error
2825
+ */
2826
+ webSocketError(ws: WebSocket, error: unknown): Promise<void>;
2827
+ /** Installed skills, metadata only (no file contents). */
2828
+ listSkills(scope: SkillStorageScope, options?: {
2829
+ includeDisabled?: boolean;
2830
+ }): Promise<SkillMetadata[]>;
2831
+ /** One skill's metadata (null when not installed). */
2832
+ getSkill(scope: SkillStorageScope, name: string): Promise<SkillMetadata | null>;
2833
+ /** One bundled file's text (null when the skill or file is missing). */
2834
+ getSkillFile(scope: SkillStorageScope, name: string, path: string): Promise<string | null>;
2835
+ /**
2836
+ * Install (or replace) a skill from its file set. Validates the payload and
2837
+ * the root SKILL.md frontmatter; the skill's identity always comes from
2838
+ * that frontmatter. Throws SkillValidationError with an actionable message
2839
+ * on any standard violation.
2840
+ */
2841
+ upsertSkill(scope: SkillStorageScope, files: SkillFileInput[]): Promise<SkillMetadata>;
2842
+ /** Enable/disable an installed skill. Returns false when not installed. */
2843
+ setSkillEnabled(scope: SkillStorageScope, name: string, enabled: boolean): Promise<boolean>;
2844
+ private sweepDeviceLogins;
2845
+ startDeviceLogin(codeHash: string): Promise<void>;
2846
+ /** Poll a device login. An approved row returns its token exactly once. */
2847
+ pollDeviceLogin(codeHash: string): Promise<{
2848
+ status: string;
2849
+ token?: string;
2850
+ } | null>;
2851
+ /** Deny a pending device login without creating a user or API key. */
2852
+ denyDeviceLogin(codeHash: string): Promise<boolean>;
2853
+ /** Approve a pending device login: mint a personal API key for the user and
2854
+ * park its plaintext for the single claim. A retry by the same user remains
2855
+ * successful after the row is approved or claimed, without minting another
2856
+ * key. Returns false for unknown, expired, denied, or differently-owned
2857
+ * logins. */
2858
+ approveDeviceLogin(params: {
2859
+ code_hash: string;
2860
+ user_id: string;
2861
+ token: string;
2862
+ token_hash: string;
2863
+ key_prefix: string;
2864
+ last_five: string;
2865
+ key_name: string;
2866
+ }): Promise<boolean>;
2867
+ /** Uninstall a skill and its files. Returns false when not installed. */
2868
+ deleteSkill(scope: SkillStorageScope, name: string): Promise<boolean>;
2869
+ }
2870
+
2871
+ interface CodeExecutionBridgeProps {
2872
+ threadId?: string;
2873
+ runId?: string;
2874
+ }
2875
+ declare class CodeExecutionBridge extends WorkerEntrypoint<ThreadEnv, CodeExecutionBridgeProps> {
2876
+ call(threadId: string, runId: string, functionId: string, encodedArgs: unknown[]): Promise<unknown>;
2877
+ }
2878
+
2879
+ /**
2880
+ * ThreadWatchdog — a per-thread companion Durable Object whose only job is to
2881
+ * deliver liveness checks INTO a DurableThread on a schedule the thread cannot
2882
+ * starve.
2883
+ *
2884
+ * Why this exists (2026-07-08 incident, api.standardcode.ai): every normal
2885
+ * turn is dispatched through the thread's own AlarmQueue and runs INSIDE its
2886
+ * alarm() handler. Cloudflare serializes alarm invocations per object and the
2887
+ * queue only re-arms the storage alarm after the current item finishes — so
2888
+ * while a turn runs, the thread's own standing `watchdogCheck` alarm rows are
2889
+ * inert. When a provider request wedged (zero bytes for 18+ minutes, in-flight
2890
+ * stall-guard timers frozen with the turn's context), nothing could fire: the
2891
+ * thread sat "working" forever, and the user's UI polling kept the instance
2892
+ * resident, which is exactly what prevented fresh-instance wake recovery.
2893
+ * A manual RPC delivery of the same check recovered the thread in one call —
2894
+ * the LOGIC was sound, the DELIVERY was starved. This object is that delivery.
2895
+ *
2896
+ * Design rules:
2897
+ * - The alarm handler stays tiny: one probe RPC + reschedule. It must never
2898
+ * run long work, so it can never starve itself the way thread turns do.
2899
+ * - Reschedule-first: the next alarm is set before the probe runs, so a crash
2900
+ * mid-probe never kills the chain.
2901
+ * - Parent-child lifecycle is explicit (Cloudflare has no cascade): the
2902
+ * companion is created lazily by the thread's execution start (`arm`),
2903
+ * stands itself down when the thread probes clean, and is destroyed by
2904
+ * `DurableThread.deleteThread()`/`terminateThread()`. Standing down keeps
2905
+ * the check-in history (the UI reads it) but drops the alarm — a DO with no
2906
+ * alarm and no traffic hibernates at zero cost.
2907
+ * - Probe timeouts are counted, not fatal: a thread DO whose input gate is
2908
+ * permanently blocked cannot be revived at the application layer, so after
2909
+ * MAX_UNREACHABLE consecutive timeouts the companion logs loudly and stands
2910
+ * down instead of ticking forever.
2911
+ */
2912
+ /** One recorded check-in, newest first in storage. */
2913
+ interface WatchdogCheckin {
2914
+ at: number;
2915
+ /** Thread verdict, or 'unreachable' when the probe itself failed/timed out. */
2916
+ verdict: "healthy" | "observing" | "recovered" | "parked" | "idle" | "unreachable";
2917
+ /** What the probe did, for the UI's determination column. */
2918
+ action: string;
2919
+ executing: boolean | null;
2920
+ incompleteLogs: number | null;
2921
+ silenceMs: number | null;
2922
+ probeMs: number;
2923
+ error?: string;
2924
+ }
2925
+ interface ThreadWatchdogState {
2926
+ armed: boolean;
2927
+ threadId: string | null;
2928
+ armedAt: number | null;
2929
+ history: WatchdogCheckin[];
2930
+ }
2931
+ interface ThreadWatchdogEnv {
2932
+ AGENT_BUILDER_THREAD: {
2933
+ idFromName(name: string): unknown;
2934
+ get(id: unknown): unknown;
2935
+ };
2936
+ [key: string]: unknown;
2937
+ }
2938
+ declare class ThreadWatchdog extends DurableObject<ThreadWatchdogEnv> {
2939
+ /**
2940
+ * Arm (or re-arm) the standing check for a thread execution. Idempotent —
2941
+ * called at every execution start. Resets the unreachable counter because a
2942
+ * fresh arm proves the thread is answering RPCs right now.
2943
+ */
2944
+ arm(threadId: string): Promise<void>;
2945
+ /**
2946
+ * Hint that the thread believes its execution ended cleanly. The companion
2947
+ * does NOT trust this (a bogus "clean end" was one of the incident's failure
2948
+ * modes) — it just moves the next check close so a genuinely clean thread
2949
+ * stands down in seconds instead of a full cadence.
2950
+ */
2951
+ disarmHint(): Promise<void>;
2952
+ /** Diagnostics view for the thread inspector UI and the diag CLI. */
2953
+ getState(): Promise<ThreadWatchdogState>;
2954
+ /**
2955
+ * Explicit cascade from the parent thread (delete/terminate). Cloudflare
2956
+ * has no automatic parent-child cleanup — this IS the cleanup.
2957
+ */
2958
+ destroy(): Promise<void>;
2959
+ alarm(): Promise<void>;
2960
+ private getThreadStub;
2961
+ private probeThread;
2962
+ private recordCheckin;
2963
+ }
2964
+
2965
+ /**
2966
+ * Model definition module for AgentBuilder.
2967
+ *
2968
+ * This module re-exports model types from @standardagents/spec and provides
2969
+ * a builder-specific version of ModelDefinition that supports the generated
2970
+ * AgentBuilder.Models type for fallback references.
2971
+ *
2972
+ * @module
2973
+ */
2974
+
2975
+ /**
2976
+ * Model definition configuration with AgentBuilder-specific fallback typing.
2977
+ *
2978
+ * Extends the base ModelDefinition from @standardagents/spec to support
2979
+ * the generated AgentBuilder.Models type for type-safe fallback references.
2980
+ *
2981
+ * @template N - The model name as a string literal type for type inference
2982
+ */
2983
+ interface ModelDefinition<N extends string = string> extends Omit<ModelDefinition$1<N>, 'fallbacks'> {
2984
+ /**
2985
+ * Fallback models to try if this model fails.
2986
+ * Referenced by model name (must be defined in agents/models/).
2987
+ * Tried in order after primary model exhausts retries.
2988
+ *
2989
+ * @example ['gpt-4', 'gpt-3.5-turbo']
2990
+ */
2991
+ fallbacks?: AgentBuilder.Models[];
2992
+ }
2993
+
2994
+ /**
2995
+ * Prompt definition module for AgentBuilder.
2996
+ *
2997
+ * This module re-exports prompt types from @standardagents/spec and provides
2998
+ * builder-specific versions that use the generated AgentBuilder namespace types.
2999
+ *
3000
+ * @module
3001
+ */
3002
+
3003
+ /**
3004
+ * A prompt inclusion part with type-safe autocomplete.
3005
+ * Uses AgentBuilder.Prompts for type-safe prompt name references.
3006
+ */
3007
+ interface PromptIncludePart {
3008
+ type: 'include';
3009
+ /** The name of the prompt to include (type-safe with autocomplete) */
3010
+ prompt: AgentBuilder.Prompts;
3011
+ }
3012
+ /**
3013
+ * A single part of a structured prompt.
3014
+ */
3015
+ type PromptPart = PromptTextPart | PromptIncludePart | PromptEnvPart;
3016
+ /**
3017
+ * Prompt content can be a string or structured array with type-safe includes.
3018
+ */
3019
+ type PromptContent = string | PromptPart[];
3020
+ /**
3021
+ * Sub-prompt configuration with type-safe name references.
3022
+ */
3023
+ interface SubpromptConfig<T extends string = AgentBuilder.Callables> extends Omit<SubpromptConfig$1<T>, 'name'> {
3024
+ /** Name of the sub-prompt (type-safe with autocomplete) */
3025
+ name: T;
3026
+ }
3027
+ /**
3028
+ * Prompt tool configuration with static tenvs/options.
3029
+ */
3030
+ interface PromptToolConfig<T extends string = AgentBuilder.Callables> extends Omit<PromptToolConfig$1, 'name'> {
3031
+ /** Name of the callable tool/agent (type-safe with autocomplete). */
3032
+ name: T;
3033
+ /** Environment values scoped to this tool invocation. */
3034
+ env?: Record<string, string>;
3035
+ /** @deprecated Use env */
3036
+ tenvs?: Record<string, unknown>;
3037
+ }
3038
+ /**
3039
+ * @deprecated Removed in 0.2.0 — subagent relationships are no longer
3040
+ * declared in a prompt's `tools` array. Declare them on the owning side's
3041
+ * `subagents` array instead (see `SubagentRelationship`). The owning side's
3042
+ * prompt automatically receives the lifecycle tools (`subagents`,
3043
+ * `subagent_create`, `subagent_message`).
3044
+ */
3045
+ type SubagentToolConfig<T extends string = string> = never;
3046
+ /**
3047
+ * @deprecated Use SubpromptConfig instead
3048
+ */
3049
+ type ToolConfig<T extends string = AgentBuilder.Callables> = SubpromptConfig<T>;
3050
+
3051
+ /**
3052
+ * Prompt definition configuration with AgentBuilder-specific typing.
3053
+ *
3054
+ * Provides type-safe references to models, tools, and agents via the
3055
+ * generated AgentBuilder namespace.
3056
+ *
3057
+ * @template N - The prompt name as a string literal type
3058
+ * @template S - The Zod schema type for requiredSchema (inferred automatically)
3059
+ */
3060
+ interface PromptDefinition<N extends string = string, S extends ToolArgs = ToolArgs> {
3061
+ /** Unique name for this prompt. */
3062
+ name: N;
3063
+ /** Description shown when this prompt is exposed as a tool. */
3064
+ toolDescription: string;
3065
+ /** The system prompt content with type-safe includes. */
3066
+ prompt: PromptContent;
3067
+ /** Model to use (type-safe with autocomplete). */
3068
+ model: AgentBuilder.Models;
3069
+ /**
3070
+ * @deprecated All prompts are now automatically exposed as tools.
3071
+ */
3072
+ exposeAsTool?: boolean;
3073
+ /** Include full chat history in the LLM context. @default false */
3074
+ includeChat?: boolean;
3075
+ /** Include results from past tool calls. @default false */
3076
+ includePastTools?: boolean;
3077
+ /** Allow parallel execution of multiple tool calls. @default false */
3078
+ parallelToolCalls?: boolean;
3079
+ /** Tool calling strategy. @default 'auto' */
3080
+ toolChoice?: 'auto' | 'none' | 'required';
3081
+ /** Zod schema for validating inputs when called as a tool. */
3082
+ requiredSchema?: S;
3083
+ /** Variable declarations for this prompt. */
3084
+ variables?: VariableDefinition[];
3085
+ /**
3086
+ * Tools available to this prompt (type-safe with autocomplete). To enable
3087
+ * handoffs, include exposed agent names. Subagent relationships are NOT
3088
+ * declared here — they live on the owning side's `subagents` array, and
3089
+ * the runtime injects the lifecycle tools automatically. Handlers may
3090
+ * never appear in this array.
3091
+ */
3092
+ tools?: (AgentBuilder.Callables | SubpromptConfig | PromptToolConfig)[];
3093
+ /** Prompt-level environment values. */
3094
+ env?: Record<string, string>;
3095
+ /** @deprecated Use env */
3096
+ tenvs?: Record<string, unknown>;
3097
+ /** Reasoning configuration for extended thinking models. */
3098
+ reasoning?: ReasoningConfig;
3099
+ /** Number of recent messages to keep actual images for. @default 10 */
3100
+ recentImageThreshold?: number;
3101
+ /** Hook IDs to run when this prompt is active. Falls back to agent-level hooks if not set. */
3102
+ hooks?: AgentBuilder.Hooks[];
3103
+ }
3104
+
3105
+ /**
3106
+ * Agent definition module for AgentBuilder.
3107
+ *
3108
+ * This module re-exports agent types from @standardagents/spec and provides
3109
+ * builder-specific versions that use the generated AgentBuilder namespace types.
3110
+ *
3111
+ * An agent has exactly two sides; each side is backed by exactly one of
3112
+ * `human`, `prompt`, or `handler`. There is no agent "type".
3113
+ *
3114
+ * @module
3115
+ */
3116
+
3117
+ /**
3118
+ * Session lifecycle tool configuration with type-safe autocomplete.
3119
+ * Object form only — the bare-string binding was removed in 0.2.0.
3120
+ */
3121
+ interface SessionToolConfig {
3122
+ /**
3123
+ * Tool name for this lifecycle binding.
3124
+ */
3125
+ readonly name: AgentBuilder.Callables;
3126
+ /**
3127
+ * Optional tool-argument property used as message text.
3128
+ */
3129
+ readonly messageProperty?: string;
3130
+ /**
3131
+ * Optional tool-argument property containing attachment path(s).
3132
+ */
3133
+ readonly attachmentsProperty?: string;
3134
+ }
3135
+ /**
3136
+ * Session lifecycle binding.
3137
+ * Object form only — use `{ name: 'tool_name' }` in place of `'tool_name'`.
3138
+ */
3139
+ type SessionToolBinding = SessionToolConfig;
3140
+ /**
3141
+ * A side-owned subagent relationship with type-safe agent references.
3142
+ * See the spec `SubagentRelationship` for full semantics.
3143
+ */
3144
+ interface SubagentRelationship extends Omit<SubagentRelationship$1, 'agent' | 'initUserMessageProperty' | 'initAttachmentsProperty' | 'initAgentNameProperty'> {
3145
+ /**
3146
+ * Which agent definition to instantiate (type-safe with autocomplete).
3147
+ * Must reference an agent with `exposeAsTool: true`.
3148
+ */
3149
+ readonly agent: AgentBuilder.Agents;
3150
+ /**
3151
+ * Property from `subagent_create` arguments used as the initial user
3152
+ * message when spawning an instance.
3153
+ */
3154
+ readonly initUserMessageProperty?: string;
3155
+ /**
3156
+ * Property from `subagent_create` arguments containing attachment path(s)
3157
+ * to include with the initial message.
3158
+ */
3159
+ readonly initAttachmentsProperty?: string;
3160
+ /**
3161
+ * Property from `subagent_create` arguments used as a human-readable name
3162
+ * for each spawned instance.
3163
+ */
3164
+ readonly initAgentNameProperty?: string;
3165
+ }
3166
+ /**
3167
+ * A side backed by a human: a person takes this side's turns. The runtime
3168
+ * parks execution awaiting inbound input on this side's perspective.
3169
+ */
3170
+ type HumanSide = HumanSide$1;
3171
+ /**
3172
+ * A side backed by a prompt: a model takes this side's turns
3173
+ * (type-safe with autocomplete).
3174
+ */
3175
+ interface PromptSide {
3176
+ /**
3177
+ * The prompt to use for this side.
3178
+ * Must reference a prompt defined in agents/prompts/.
3179
+ */
3180
+ readonly prompt: AgentBuilder.Prompts;
3181
+ /** Custom label for this side of the conversation. */
3182
+ readonly label?: string;
3183
+ /**
3184
+ * Subagent relationships OWNED by this side. The side's prompt
3185
+ * automatically receives the lifecycle tools (`subagents`,
3186
+ * `subagent_create`, `subagent_message`) for the side's non-hidden
3187
+ * relationships; inbound child traffic lands on this side's perspective.
3188
+ */
3189
+ readonly subagents?: readonly SubagentRelationship[];
3190
+ /**
3191
+ * Stop this side's turn when it returns a text response (no tool calls).
3192
+ * @default true
3193
+ */
3194
+ readonly stopOnResponse?: boolean;
3195
+ /**
3196
+ * Stop this side's turn when a specific tool is called (type-safe with
3197
+ * autocomplete). Requires stopToolResponseProperty to extract the result.
3198
+ */
3199
+ readonly stopTool?: AgentBuilder.Callables;
3200
+ /**
3201
+ * Property to extract from the stop tool's result.
3202
+ * Required when stopTool is set.
3203
+ */
3204
+ readonly stopToolResponseProperty?: string;
3205
+ /**
3206
+ * Maximum steps for this side before forcing a stop.
3207
+ * A step is one complete LLM request/response cycle.
3208
+ */
3209
+ readonly maxSteps?: number;
3210
+ /**
3211
+ * Tool that ends the entire session when called. Ending a session never
3212
+ * terminates the thread.
3213
+ */
3214
+ readonly sessionStop?: SessionToolBinding;
3215
+ /**
3216
+ * Tool that fails the entire session when called. Failing a session never
3217
+ * terminates the thread.
3218
+ */
3219
+ readonly sessionFail?: SessionToolBinding;
3220
+ /**
3221
+ * Tool that publishes status updates to the parent thread when this agent
3222
+ * runs as a subagent.
3223
+ */
3224
+ readonly sessionStatus?: SessionToolBinding;
3225
+ /**
3226
+ * Enable manual stop condition handling via hooks.
3227
+ * Builder-specific feature for custom stop logic.
3228
+ * @default false
3229
+ */
3230
+ readonly manualStopCondition?: boolean;
3231
+ readonly human?: never;
3232
+ readonly handler?: never;
3233
+ }
3234
+ /**
3235
+ * A side backed by a handler: deterministic code takes this side's turns
3236
+ * (type-safe with autocomplete). A handler turn has no steps to cap and no
3237
+ * session bindings — handlers end sessions via `state.stopSession()`.
3238
+ */
3239
+ interface HandlerSide {
3240
+ /**
3241
+ * The handler that takes this side's turns.
3242
+ * Must reference a handler defined in agents/handlers/.
3243
+ */
3244
+ readonly handler: AgentBuilder.Handlers;
3245
+ /** Custom label for this side of the conversation. */
3246
+ readonly label?: string;
3247
+ /**
3248
+ * Subagent relationships OWNED by this side. Handlers need no tool grant;
3249
+ * they reach children through `ThreadState`.
3250
+ */
3251
+ readonly subagents?: readonly SubagentRelationship[];
3252
+ readonly human?: never;
3253
+ readonly prompt?: never;
3254
+ readonly stopOnResponse?: never;
3255
+ readonly stopTool?: never;
3256
+ readonly stopToolResponseProperty?: never;
3257
+ readonly maxSteps?: never;
3258
+ readonly sessionStop?: never;
3259
+ readonly sessionFail?: never;
3260
+ readonly sessionStatus?: never;
3261
+ readonly manualStopCondition?: never;
3262
+ }
3263
+ /**
3264
+ * Configuration for one side of an agent conversation — exactly one backing:
3265
+ * `human`, `prompt`, or `handler`. Both sides human is reserved and rejected.
3266
+ */
3267
+ type SideConfig = HumanSide | PromptSide | HandlerSide;
3268
+ /**
3269
+ * Agent definition configuration with AgentBuilder-specific typing.
3270
+ *
3271
+ * Provides type-safe references to prompts, handlers, and agents via the
3272
+ * generated AgentBuilder namespace.
3273
+ *
3274
+ * @template N - The agent name as a string literal type
3275
+ *
3276
+ * @example
3277
+ * ```typescript
3278
+ * import { defineAgent } from '@standardagents/builder';
3279
+ *
3280
+ * export default defineAgent({
3281
+ * name: 'support_agent',
3282
+ * sideA: {
3283
+ * label: 'Support',
3284
+ * prompt: 'customer_support',
3285
+ * stopOnResponse: true,
3286
+ * },
3287
+ * sideB: { human: true },
3288
+ * });
3289
+ * ```
3290
+ */
3291
+ interface AgentDefinition<N extends string = string> {
3292
+ /** Unique name for this agent. */
3293
+ readonly name: N;
3294
+ /**
3295
+ * Human-readable title for the agent.
3296
+ * @deprecated Use name instead. Title will be removed in a future version.
3297
+ */
3298
+ readonly title?: string;
3299
+ /**
3300
+ * @deprecated Removed in 0.2.0 — there is no agent "type". Delete this
3301
+ * field and declare both sides explicitly: `type: 'ai_human'` becomes
3302
+ * `sideB: { human: true }`; `type: 'dual_ai'` is two prompt-backed sides.
3303
+ */
3304
+ readonly type?: never;
3305
+ /**
3306
+ * Maximum total exchanges across both sides before the runtime ends the
3307
+ * session. Optional on every side combination; exchange counting is
3308
+ * uniform across backings. Reaching the cap ends the session, never the
3309
+ * thread.
3310
+ */
3311
+ readonly maxSessionTurns?: number;
3312
+ /** Configuration for side A (type-safe with autocomplete). */
3313
+ readonly sideA: SideConfig;
3314
+ /** Configuration for side B (type-safe with autocomplete). */
3315
+ readonly sideB: SideConfig;
3316
+ /**
3317
+ * Expose this agent as a tool for other prompts.
3318
+ * Enables handoffs and subagent composition.
3319
+ * @default false
3320
+ */
3321
+ readonly exposeAsTool?: boolean;
3322
+ /**
3323
+ * Whether this agent is a PRIMARY, user-facing entry point.
3324
+ * Set false on internal handoff targets (e.g. domain-gearbox variants) so
3325
+ * UIs keep them out of top-level agent lists while they stay fully
3326
+ * addressable for handoffs and thread resumption.
3327
+ * @default true
3328
+ */
3329
+ readonly primary?: boolean;
3330
+ /** Description shown when agent is used as a tool. */
3331
+ readonly toolDescription?: string;
3332
+ /**
3333
+ * Thread-scoped hooks this child requires on every direct parent side that
3334
+ * declares a relationship targeting it. Legal on any exposed agent.
3335
+ */
3336
+ readonly parentHooks?: readonly ParentHookRequirement[];
3337
+ /**
3338
+ * Environment values provided by this agent.
3339
+ */
3340
+ readonly env?: Readonly<Record<string, string>>;
3341
+ /**
3342
+ * @deprecated Use env
3343
+ */
3344
+ readonly tenvs?: Readonly<Record<string, unknown>>;
3345
+ /** Brief description of what this agent does. */
3346
+ readonly description?: string;
3347
+ /** Icon URL or absolute path for the agent. */
3348
+ readonly icon?: string;
3349
+ /**
3350
+ * npm package name for this agent when packed.
3351
+ * Preserved through unpack → edit → pack cycles.
3352
+ */
3353
+ readonly packageName?: string;
3354
+ /**
3355
+ * Package version (semver format).
3356
+ * Preserved through unpack → edit → pack cycles.
3357
+ */
3358
+ readonly version?: string;
3359
+ /**
3360
+ * Package author/copyright holder.
3361
+ * Preserved through unpack → edit → pack cycles.
3362
+ */
3363
+ readonly author?: string;
3364
+ /**
3365
+ * License identifier (SPDX format).
3366
+ * Preserved through unpack → edit → pack cycles.
3367
+ */
3368
+ readonly license?: string;
3369
+ }
3370
+
3371
+ /**
3372
+ * Options for injecting a message
3373
+ */
3374
+ interface InjectMessageOptions {
3375
+ /** The message content */
3376
+ content: string;
3377
+ /** The message role */
3378
+ role: "system" | "user" | "assistant" | "tool";
3379
+ /** Optional message ID. If not provided, a UUID will be generated */
3380
+ id?: string;
3381
+ /** Optional message to insert before. If not provided, message is appended to the end */
3382
+ beforeMessageId?: string;
3383
+ /** Optional tool call ID (for role="tool" only) */
3384
+ toolCallId?: string;
3385
+ /** Optional name field */
3386
+ name?: string;
3387
+ /** Whether this message is silent (not shown in UI). Default: false */
3388
+ silent?: boolean;
3389
+ /** Optional structured metadata */
3390
+ metadata?: Record<string, unknown>;
3391
+ /** Force message to be top-level (depth 0) even when called from sub-prompts. Default: false */
3392
+ forceTopLevel?: boolean;
3393
+ /** Force a specific side to play the next turn after injecting the message */
3394
+ forceTurn?: "side_a" | "side_b";
3395
+ }
3396
+ /**
3397
+ * Queue a new tool call to be executed in the current flow
3398
+ *
3399
+ * This adds a tool call to the execution queue without immediately executing it.
3400
+ * The tool will be executed as part of the normal flow processing.
3401
+ *
3402
+ * If the current tool has a `uses` list defined, the toolName must be in that list.
3403
+ * This enforces namespace isolation for packed agents.
3404
+ *
3405
+ * @param flow - The current FlowState
3406
+ * @param toolName - The name of the tool to call
3407
+ * @param args - The arguments to pass to the tool
3408
+ * @throws Error if toolName is not in the current tool's uses list (when defined)
3409
+ *
3410
+ * @example
3411
+ * ```typescript
3412
+ * import { queueTool } from '@standardagents/builder';
3413
+ *
3414
+ * queueTool(flow, "search_user", { email: "user@example.com" });
3415
+ * ```
3416
+ */
3417
+ declare function queueTool(flow: FlowState, toolName: string, args?: Record<string, unknown>): void;
3418
+ /**
3419
+ * Inject a message into the thread without triggering execution
3420
+ *
3421
+ * This allows you to add messages to the conversation history programmatically.
3422
+ * The message is persisted to storage but does not cause the agent to execute.
3423
+ *
3424
+ * By default, messages are appended to the end of the conversation.
3425
+ * You can optionally insert a message before another message by providing beforeMessageId.
3426
+ *
3427
+ * @param flow - The current FlowState
3428
+ * @param options - Message options
3429
+ *
3430
+ * @example
3431
+ * ```typescript
3432
+ * import { injectMessage } from '@standardagents/builder';
3433
+ *
3434
+ * // Append a system message
3435
+ * await injectMessage(flow, {
3436
+ * role: "system",
3437
+ * content: "Context has been updated"
3438
+ * });
3439
+ *
3440
+ * // Insert a user message before a specific message
3441
+ * await injectMessage(flow, {
3442
+ * role: "user",
3443
+ * content: "Additional context",
3444
+ * beforeMessageId: "msg-123"
3445
+ * });
3446
+ *
3447
+ * // Inject a message and force a specific side to play next
3448
+ * await injectMessage(flow, {
3449
+ * role: "system",
3450
+ * content: "New instructions for the AI",
3451
+ * forceTurn: "side_a" // Force side_a to respond to this message
3452
+ * });
3453
+ * ```
3454
+ */
3455
+ declare function injectMessage(flow: FlowState, options: InjectMessageOptions): Promise<Message>;
3456
+ /**
3457
+ * Get messages from the thread history
3458
+ *
3459
+ * Retrieves message history from the thread's SQLite storage.
3460
+ * Messages are ordered by creation time (oldest first by default).
3461
+ *
3462
+ * @param flow - The current FlowState
3463
+ * @param limit - Maximum number of messages to retrieve (default: 100)
3464
+ * @param offset - Number of messages to skip (default: 0)
3465
+ * @param order - Sort order: "asc" (oldest first) or "desc" (newest first) (default: "asc")
3466
+ * @returns Array of messages
3467
+ *
3468
+ * @example
3469
+ * ```typescript
3470
+ * import { getMessages } from '@standardagents/builder';
3471
+ *
3472
+ * // Get last 10 messages
3473
+ * const messages = await getMessages(flow, 10);
3474
+ *
3475
+ * // Get 10 messages, skipping the first 20
3476
+ * const messages = await getMessages(flow, 10, 20);
3477
+ *
3478
+ * // Get newest 10 messages
3479
+ * const messages = await getMessages(flow, 10, 0, "desc");
3480
+ * ```
3481
+ */
3482
+ declare function getMessages(flow: FlowState, limit?: number, offset?: number, order?: "asc" | "desc"): Promise<Message[]>;
3483
+ /**
3484
+ * Reload message history from storage
3485
+ *
3486
+ * Re-loads the complete message history from the thread's SQLite storage.
3487
+ * This is useful when you need to refresh the message history after making
3488
+ * changes (e.g., injecting messages).
3489
+ *
3490
+ * @param flow - The current FlowState
3491
+ * @returns Array of messages (reloaded from storage)
3492
+ *
3493
+ * @example
3494
+ * ```typescript
3495
+ * import { injectMessage, reloadHistory } from '@standardagents/builder';
3496
+ *
3497
+ * // Reload history after injecting a silent message
3498
+ * await injectMessage(flow, { role: "system", content: "...", silent: true });
3499
+ * flow.messageHistory = await reloadHistory(flow);
3500
+ * ```
3501
+ */
3502
+ declare function reloadHistory(state: FlowState): Promise<Message[]>;
3503
+ /**
3504
+ * Emit a custom event to WebSocket clients via the stream
3505
+ *
3506
+ * Sends a custom event to all connected WebSocket clients on the stream channel.
3507
+ * This allows backend code to push arbitrary data to the frontend
3508
+ * outside of the standard message events.
3509
+ *
3510
+ * @param flow - The current FlowState
3511
+ * @param type - The event type name (e.g., "progress", "notification")
3512
+ * @param data - The event payload (any serializable data)
3513
+ *
3514
+ * @example
3515
+ * ```typescript
3516
+ * import { emitThreadEvent } from '@standardagents/builder';
3517
+ *
3518
+ * // Emit a progress update
3519
+ * emitThreadEvent(flow, "progress", { step: 3, total: 10, message: "Processing data..." });
3520
+ *
3521
+ * // Emit a custom notification
3522
+ * emitThreadEvent(flow, "notification", { level: "info", message: "User authenticated" });
3523
+ *
3524
+ * // Emit metadata
3525
+ * emitThreadEvent(flow, "metadata", { userId: "123", sessionId: "abc" });
3526
+ * ```
3527
+ */
3528
+ declare function emitThreadEvent(flow: FlowState, type: string, data: unknown): void;
3529
+ /**
3530
+ * Force a specific side to play the next turn
3531
+ *
3532
+ * This queues the specified side to play next without interrupting the current turn.
3533
+ * The forced turn only takes effect at the END of the current turn execution.
3534
+ *
3535
+ * If the tool queue is currently being processed (sequence.isHandling is true),
3536
+ * the forced turn is deferred until all queued tools complete. This allows patterns like:
3537
+ *
3538
+ * ```typescript
3539
+ * import { queueTool, forceTurn } from '@standardagents/builder';
3540
+ *
3541
+ * queueTool(flow, 'myTool', {});
3542
+ * forceTurn(flow, 'side_a');
3543
+ * // myTool executes first, THEN the turn switches to side_a
3544
+ * ```
3545
+ *
3546
+ * @param flow - The current FlowState
3547
+ * @param side - Which side should play next ('side_a' or 'side_b')
3548
+ *
3549
+ * @example
3550
+ * ```typescript
3551
+ * import { forceTurn } from '@standardagents/builder';
3552
+ *
3553
+ * // Force current side to continue (override stop condition)
3554
+ * // If side_a is playing and would stop, this forces it to play at least 1 more turn
3555
+ * forceTurn(flow, 'side_a');
3556
+ *
3557
+ * // Force switch to other side
3558
+ * // If side_a is playing, this forces side_b to play next turn
3559
+ * forceTurn(flow, 'side_b');
3560
+ *
3561
+ * // Forcing a HUMAN-backed side parks execution: the thread stops and waits
3562
+ * // for that side's next inbound message instead of taking a runtime turn.
3563
+ * forceTurn(flow, 'side_b'); // side B human-backed → parks awaiting input
3564
+ * ```
3565
+ */
3566
+ declare function forceTurn(flow: FlowState, side: 'side_a' | 'side_b'): void;
3567
+ /**
3568
+ * Thread context from defineThreadEndpoint
3569
+ */
3570
+ interface ThreadContext {
3571
+ instance: {
3572
+ updateThreadMeta: (threadId: string, params: {
3573
+ agent_name?: string;
3574
+ user_id?: string | null;
3575
+ tags?: string[] | null;
3576
+ }) => Promise<{
3577
+ success: boolean;
3578
+ error?: string;
3579
+ thread?: {
3580
+ id: string;
3581
+ agent_id: string;
3582
+ user_id: string | null;
3583
+ tags: string[];
3584
+ created_at: number;
3585
+ };
3586
+ }>;
3587
+ };
3588
+ metadata: {
3589
+ id: string;
3590
+ agent_name: string;
3591
+ user_id: string | null;
3592
+ tags: string[] | null;
3593
+ created_at: number;
3594
+ };
3595
+ }
3596
+ /**
3597
+ * Update a thread's metadata in the DurableAgentBuilder registry
3598
+ *
3599
+ * This allows updating the agent_name, user_id, and tags for an existing thread.
3600
+ * Uses the thread instance from defineThreadEndpoint context.
3601
+ *
3602
+ * @param thread - The thread context from defineThreadEndpoint ({ instance, metadata })
3603
+ * @param params - The fields to update (agent_name, user_id, tags)
3604
+ * @returns The updated thread info, or null if update failed
3605
+ *
3606
+ * @example
3607
+ * ```typescript
3608
+ * import { defineThreadEndpoint, updateThread } from '@standardagents/builder';
3609
+ *
3610
+ * export default defineThreadEndpoint(async (req, thread) => {
3611
+ * // Update thread's user_id
3612
+ * await updateThread(thread, { user_id: 'user-123' });
3613
+ *
3614
+ * // Update thread's tags
3615
+ * await updateThread(thread, { tags: ['support', 'urgent'] });
3616
+ *
3617
+ * // Update multiple fields
3618
+ * const result = await updateThread(thread, {
3619
+ * agent_name: 'new-agent',
3620
+ * user_id: 'user-456',
3621
+ * tags: ['sales']
3622
+ * });
3623
+ *
3624
+ * return Response.json(result);
3625
+ * });
3626
+ * ```
3627
+ */
3628
+ declare function updateThread(thread: ThreadContext, params: {
3629
+ agent_name?: string;
3630
+ user_id?: string | null;
3631
+ tags?: string[] | null;
3632
+ }): Promise<{
3633
+ id: string;
3634
+ agent_id: string;
3635
+ user_id: string | null;
3636
+ tags: string[];
3637
+ created_at: number;
3638
+ } | null>;
3639
+ /**
3640
+ * Write a file to thread storage
3641
+ *
3642
+ * @param flow - The current FlowState
3643
+ * @param path - File path (e.g., "/images/photo.jpg")
3644
+ * @param data - File data as ArrayBuffer or string
3645
+ * @param mimeType - MIME type of the file
3646
+ * @param options - Optional metadata and thumbnail
3647
+ * @returns The created file record
3648
+ *
3649
+ * @example
3650
+ * ```typescript
3651
+ * import { writeFile } from '@standardagents/builder';
3652
+ *
3653
+ * // Write binary file
3654
+ * const imageData = new Uint8Array([...]);
3655
+ * await writeFile(flow, "/images/photo.jpg", imageData.buffer, "image/jpeg");
3656
+ *
3657
+ * // Write text file
3658
+ * await writeFile(flow, "/docs/readme.md", "# Hello", "text/markdown");
3659
+ * ```
3660
+ */
3661
+ declare function writeFile(flow: FlowState, path: string, data: ArrayBuffer | string, mimeType: string, options?: {
3662
+ metadata?: Record<string, unknown>;
3663
+ thumbnail?: ArrayBuffer;
3664
+ }): Promise<FileRecord>;
3665
+ /**
3666
+ * Write an image file with optional thumbnail
3667
+ *
3668
+ * @param flow - The current FlowState
3669
+ * @param path - File path
3670
+ * @param data - Image data as ArrayBuffer
3671
+ * @param mimeType - Image MIME type
3672
+ * @param options - Image metadata (width, height) and optional thumbnail
3673
+ * @returns The created file record
3674
+ *
3675
+ * @example
3676
+ * ```typescript
3677
+ * import { writeImage } from '@standardagents/builder';
3678
+ *
3679
+ * await writeImage(flow, "/images/photo.jpg", imageBuffer, "image/jpeg", {
3680
+ * metadata: { width: 1024, height: 768 },
3681
+ * thumbnail: thumbnailBuffer
3682
+ * });
3683
+ * ```
3684
+ */
3685
+ declare function writeImage(flow: FlowState, path: string, data: ArrayBuffer, mimeType: string, options?: {
3686
+ metadata?: {
3687
+ width: number;
3688
+ height: number;
3689
+ [key: string]: unknown;
3690
+ };
3691
+ thumbnail?: ArrayBuffer;
3692
+ }): Promise<FileRecord>;
3693
+ /**
3694
+ * Link to an external file (URL, S3, R2)
3695
+ *
3696
+ * Creates a file entry pointing to an external location without storing the data locally.
3697
+ *
3698
+ * @param flow - The current FlowState
3699
+ * @param path - File path in thread storage
3700
+ * @param location - External location (https://, s3://, r2://)
3701
+ * @param options - Optional MIME type, size, and metadata
3702
+ * @returns The created file record
3703
+ *
3704
+ * @example
3705
+ * ```typescript
3706
+ * import { linkFile } from '@standardagents/builder';
3707
+ *
3708
+ * // Link to a URL
3709
+ * await linkFile(flow, "/images/hero.jpg", "https://cdn.example.com/hero.jpg");
3710
+ *
3711
+ * // Link to S3
3712
+ * await linkFile(flow, "/data/large.csv", "s3://mybucket/data/large.csv", {
3713
+ * mimeType: "text/csv",
3714
+ * size: 10 * 1024 * 1024 * 1024 // 10GB
3715
+ * });
3716
+ * ```
3717
+ */
3718
+ declare function linkFile(flow: FlowState, path: string, location: string, options?: {
3719
+ mimeType?: string;
3720
+ size?: number;
3721
+ metadata?: Record<string, unknown>;
3722
+ }): Promise<FileRecord>;
3723
+ /**
3724
+ * Read a file from thread storage
3725
+ *
3726
+ * @param flow - The current FlowState
3727
+ * @param path - File path
3728
+ * @returns File data as ArrayBuffer, or null if not found/external
3729
+ *
3730
+ * @example
3731
+ * ```typescript
3732
+ * import { readFile } from '@standardagents/builder';
3733
+ *
3734
+ * const data = await readFile(flow, "/images/photo.jpg");
3735
+ * if (data) {
3736
+ * // Process binary data
3737
+ * }
3738
+ * ```
3739
+ */
3740
+ declare function readFile(flow: FlowState, path: string): Promise<ArrayBuffer | null>;
3741
+ /**
3742
+ * Get file metadata
3743
+ *
3744
+ * @param flow - The current FlowState
3745
+ * @param path - File path
3746
+ * @returns File record or null if not found
3747
+ *
3748
+ * @example
3749
+ * ```typescript
3750
+ * import { stat } from '@standardagents/builder';
3751
+ *
3752
+ * const file = await stat(flow, "/images/photo.jpg");
3753
+ * if (file) {
3754
+ * console.log(`Size: ${file.size}, Type: ${file.mimeType}`);
3755
+ * }
3756
+ * ```
3757
+ */
3758
+ declare function stat(flow: FlowState, path: string): Promise<FileRecord | null>;
3759
+ /**
3760
+ * Check if file or directory exists
3761
+ *
3762
+ * @param flow - The current FlowState
3763
+ * @param path - File path
3764
+ * @returns true if exists, false otherwise
3765
+ *
3766
+ * @example
3767
+ * ```typescript
3768
+ * import { exists } from '@standardagents/builder';
3769
+ *
3770
+ * if (await exists(flow, "/config.json")) {
3771
+ * // File exists
3772
+ * }
3773
+ * ```
3774
+ */
3775
+ declare function exists(flow: FlowState, path: string): Promise<boolean>;
3776
+ /**
3777
+ * Delete a file
3778
+ *
3779
+ * @param flow - The current FlowState
3780
+ * @param path - File path
3781
+ *
3782
+ * @example
3783
+ * ```typescript
3784
+ * import { unlink } from '@standardagents/builder';
3785
+ *
3786
+ * await unlink(flow, "/temp/draft.txt");
3787
+ * ```
3788
+ */
3789
+ declare function unlink(flow: FlowState, path: string): Promise<void>;
3790
+ /**
3791
+ * Create a directory
3792
+ *
3793
+ * @param flow - The current FlowState
3794
+ * @param path - Directory path
3795
+ * @returns The created directory record
3796
+ *
3797
+ * @example
3798
+ * ```typescript
3799
+ * import { mkdir } from '@standardagents/builder';
3800
+ *
3801
+ * await mkdir(flow, "/uploads/2024");
3802
+ * ```
3803
+ */
3804
+ declare function mkdir(flow: FlowState, path: string): Promise<FileRecord>;
3805
+ /**
3806
+ * List directory contents
3807
+ *
3808
+ * @param flow - The current FlowState
3809
+ * @param path - Directory path
3810
+ * @returns Array of file records in the directory
3811
+ *
3812
+ * @example
3813
+ * ```typescript
3814
+ * import { readdir } from '@standardagents/builder';
3815
+ *
3816
+ * const files = await readdir(flow, "/images");
3817
+ * for (const file of files) {
3818
+ * console.log(file.name, file.size);
3819
+ * }
3820
+ * ```
3821
+ */
3822
+ declare function readdir(flow: FlowState, path: string): Promise<FileRecord[]>;
3823
+ /**
3824
+ * Remove an empty directory
3825
+ *
3826
+ * @param flow - The current FlowState
3827
+ * @param path - Directory path
3828
+ *
3829
+ * @example
3830
+ * ```typescript
3831
+ * import { rmdir } from '@standardagents/builder';
3832
+ *
3833
+ * await rmdir(flow, "/temp");
3834
+ * ```
3835
+ */
3836
+ declare function rmdir(flow: FlowState, path: string): Promise<void>;
3837
+ /**
3838
+ * Move or rename a file or directory to a new path.
3839
+ *
3840
+ * Works for files (inline or chunked) and directories (the whole subtree is
3841
+ * relocated). The destination must not already exist.
3842
+ *
3843
+ * @param flow - The current FlowState
3844
+ * @param sourcePath - Existing file or directory path
3845
+ * @param destinationPath - New path
3846
+ * @returns The moved file record at its new path
3847
+ *
3848
+ * @example
3849
+ * ```typescript
3850
+ * import { move } from '@standardagents/builder';
3851
+ *
3852
+ * await move(flow, "/drafts/post.md", "/published/post.md");
3853
+ * await move(flow, "/tmp/work", "/archive/2024/work");
3854
+ * ```
3855
+ */
3856
+ declare function move(flow: FlowState, sourcePath: string, destinationPath: string): Promise<FileRecord>;
3857
+ /**
3858
+ * Rename a file or directory in place, keeping it in the same directory.
3859
+ *
3860
+ * @param flow - The current FlowState
3861
+ * @param path - Existing file or directory path
3862
+ * @param newName - New name (must not contain path separators)
3863
+ * @returns The renamed file record at its new path
3864
+ *
3865
+ * @example
3866
+ * ```typescript
3867
+ * import { rename } from '@standardagents/builder';
3868
+ *
3869
+ * await rename(flow, "/notes/draft.txt", "final.txt");
3870
+ * ```
3871
+ */
3872
+ declare function rename(flow: FlowState, path: string, newName: string): Promise<FileRecord>;
3873
+ /**
3874
+ * Get file storage statistics
3875
+ *
3876
+ * @param flow - The current FlowState
3877
+ * @returns Storage statistics (total size and file count)
3878
+ *
3879
+ * @example
3880
+ * ```typescript
3881
+ * import { getFileStats } from '@standardagents/builder';
3882
+ *
3883
+ * const stats = await getFileStats(flow);
3884
+ * console.log(`Total: ${stats.totalSize} bytes, Files: ${stats.fileCount}`);
3885
+ * ```
3886
+ */
3887
+ declare function getFileStats(flow: FlowState): Promise<FileStats>;
3888
+ /**
3889
+ * Get thumbnail for an image file
3890
+ *
3891
+ * @param flow - The current FlowState
3892
+ * @param path - Image file path
3893
+ * @returns Thumbnail data as ArrayBuffer, or null if not found
3894
+ *
3895
+ * @example
3896
+ * ```typescript
3897
+ * import { getThumbnail } from '@standardagents/builder';
3898
+ *
3899
+ * const thumb = await getThumbnail(flow, "/images/photo.jpg");
3900
+ * ```
3901
+ */
3902
+ declare function getThumbnail(flow: FlowState, path: string): Promise<ArrayBuffer | null>;
3903
+ /**
3904
+ * Read a text file as string
3905
+ *
3906
+ * @param flow - The current FlowState
3907
+ * @param path - File path
3908
+ * @returns File content as string, or null if not found
3909
+ *
3910
+ * @example
3911
+ * ```typescript
3912
+ * import { cat } from '@standardagents/builder';
3913
+ *
3914
+ * const content = await cat(flow, "/docs/readme.md");
3915
+ * ```
3916
+ */
3917
+ declare function cat(flow: FlowState, path: string): Promise<string | null>;
3918
+ /**
3919
+ * Read first N lines of a text file
3920
+ *
3921
+ * @param flow - The current FlowState
3922
+ * @param path - File path
3923
+ * @param lines - Number of lines to read (default: 10)
3924
+ * @returns First N lines as string, or null if not found
3925
+ *
3926
+ * @example
3927
+ * ```typescript
3928
+ * import { head } from '@standardagents/builder';
3929
+ *
3930
+ * const firstLines = await head(flow, "/logs/app.log", 20);
3931
+ * ```
3932
+ */
3933
+ declare function head(flow: FlowState, path: string, lines?: number): Promise<string | null>;
3934
+ /**
3935
+ * Read last N lines of a text file
3936
+ *
3937
+ * @param flow - The current FlowState
3938
+ * @param path - File path
3939
+ * @param lines - Number of lines to read (default: 10)
3940
+ * @returns Last N lines as string, or null if not found
3941
+ *
3942
+ * @example
3943
+ * ```typescript
3944
+ * import { tail } from '@standardagents/builder';
3945
+ *
3946
+ * const lastLines = await tail(flow, "/logs/app.log", 50);
3947
+ * ```
3948
+ */
3949
+ declare function tail(flow: FlowState, path: string, lines?: number): Promise<string | null>;
3950
+ /**
3951
+ * Search text file contents using FTS5 full-text search
3952
+ *
3953
+ * @param flow - The current FlowState
3954
+ * @param pattern - Search pattern (FTS5 syntax)
3955
+ * @param options - Search options
3956
+ * @returns Array of matching results with snippets
3957
+ *
3958
+ * @example
3959
+ * ```typescript
3960
+ * import { grep } from '@standardagents/builder';
3961
+ *
3962
+ * // Search all files
3963
+ * const results = await grep(flow, "error");
3964
+ *
3965
+ * // Search in specific directory
3966
+ * const results = await grep(flow, "TODO", { path: "/src" });
3967
+ * ```
3968
+ */
3969
+ declare function grep(flow: FlowState, pattern: string, options?: {
3970
+ path?: string;
3971
+ limit?: number;
3972
+ }): Promise<GrepResult[]>;
3973
+ /**
3974
+ * Find files by path pattern
3975
+ *
3976
+ * @param flow - The current FlowState
3977
+ * @param pattern - Glob-like pattern (e.g., "*.md", "/docs/subdir/*.txt")
3978
+ * @param options - Find options
3979
+ * @returns Array of matching file records
3980
+ *
3981
+ * @example
3982
+ * ```typescript
3983
+ * import { find } from '@standardagents/builder';
3984
+ *
3985
+ * // Find all markdown files
3986
+ * const mdFiles = await find(flow, "*.md");
3987
+ *
3988
+ * // Find all files in docs
3989
+ * const docFiles = await find(flow, "/docs/*", { type: "file" });
3990
+ * ```
3991
+ */
3992
+ declare function find(flow: FlowState, pattern: string, options?: {
3993
+ type?: "file" | "directory" | "all";
3994
+ limit?: number;
3995
+ }): Promise<FileRecord[]>;
3996
+
3997
+ /**
3998
+ * Options for broadcasting custom data
3999
+ */
4000
+ interface BroadcastOptions {
4001
+ /** The type of the broadcast message */
4002
+ type: string;
4003
+ /** The value/payload of the broadcast message */
4004
+ value: unknown;
4005
+ }
4006
+ /**
4007
+ * FlowState SDK - Utility methods for working with FlowState
4008
+ *
4009
+ * These methods extend the FlowState object with helpful utilities for:
4010
+ * - Queuing tool calls
4011
+ * - Injecting messages
4012
+ * - Retrieving message history
4013
+ * - Broadcasting custom data via WebSocket
4014
+ */
4015
+ declare class FlowStateSdk {
4016
+ /**
4017
+ * Queue a new tool call to be executed in the current flow
4018
+ *
4019
+ * This adds a tool call to the execution queue without immediately executing it.
4020
+ * The tool will be executed as part of the normal flow processing.
4021
+ *
4022
+ * @param flow - The current FlowState
4023
+ * @param toolName - The name of the tool to call (autocompletes from available tools)
4024
+ * @param args - The arguments to pass to the tool
4025
+ *
4026
+ * @example
4027
+ * ```typescript
4028
+ * FlowStateSdk.queueTool(flow, "search_user", { email: "user@example.com" });
4029
+ * ```
4030
+ */
4031
+ static queueTool(flow: FlowState, toolName: StandardAgentSpec.Callables, args?: Record<string, unknown>): void;
4032
+ /**
4033
+ * Inject a message into the thread without triggering execution
4034
+ *
4035
+ * This allows you to add messages to the conversation history programmatically.
4036
+ * The message is persisted to storage but does not cause the agent to execute.
4037
+ *
4038
+ * By default, messages are appended to the end of the conversation.
4039
+ * You can optionally insert a message before another message by providing beforeMessageId.
4040
+ *
4041
+ * @param flow - The current FlowState
4042
+ * @param options - Message options
4043
+ *
4044
+ * @example
4045
+ * ```typescript
4046
+ * // Append a system message
4047
+ * await FlowStateSdk.injectMessage(flow, {
4048
+ * role: "system",
4049
+ * content: "Context has been updated"
4050
+ * });
4051
+ *
4052
+ * // Insert a user message before a specific message
4053
+ * await FlowStateSdk.injectMessage(flow, {
4054
+ * role: "user",
4055
+ * content: "Additional context",
4056
+ * beforeMessageId: "msg-123"
4057
+ * });
4058
+ *
4059
+ * // Inject a message and force a specific side to play next
4060
+ * await FlowStateSdk.injectMessage(flow, {
4061
+ * role: "system",
4062
+ * content: "New instructions for the AI",
4063
+ * forceTurn: "side_a" // Force side_a to respond to this message
4064
+ * });
4065
+ * ```
4066
+ */
4067
+ static injectMessage(flow: FlowState, options: InjectMessageOptions): Promise<Message>;
4068
+ /**
4069
+ * Get messages from the thread history
4070
+ *
4071
+ * Retrieves message history from the thread's SQLite storage.
4072
+ * Messages are ordered by creation time (oldest first by default).
4073
+ *
4074
+ * @param flow - The current FlowState
4075
+ * @param limit - Maximum number of messages to retrieve (default: 100)
4076
+ * @param offset - Number of messages to skip (default: 0)
4077
+ * @param order - Sort order: "asc" (oldest first) or "desc" (newest first) (default: "asc")
4078
+ * @returns Array of messages
4079
+ *
4080
+ * @example
4081
+ * ```typescript
4082
+ * // Get last 10 messages
4083
+ * const messages = await FlowStateSdk.getMessages(flow, 10);
4084
+ *
4085
+ * // Get 10 messages, skipping the first 20
4086
+ * const messages = await FlowStateSdk.getMessages(flow, 10, 20);
4087
+ *
4088
+ * // Get newest 10 messages
4089
+ * const messages = await FlowStateSdk.getMessages(flow, 10, 0, "desc");
4090
+ * ```
4091
+ */
4092
+ static getMessages(flow: FlowState, limit?: number, offset?: number, order?: "asc" | "desc"): Promise<Message[]>;
4093
+ /**
4094
+ * Reload message history from storage
4095
+ *
4096
+ * Re-loads the complete message history from the thread's SQLite storage.
4097
+ * This is useful when you need to refresh the message history after making
4098
+ * changes (e.g., injecting messages).
4099
+ *
4100
+ * @param flow - The current FlowState
4101
+ * @returns Array of messages (reloaded from storage)
4102
+ *
4103
+ * @example
4104
+ * ```typescript
4105
+ * // Reload history after injecting a silent message
4106
+ * await FlowStateSdk.injectMessage(flow, { role: "system", content: "...", silent: true });
4107
+ * flow.messageHistory = await FlowStateSdk.reloadHistory(flow);
4108
+ * ```
4109
+ */
4110
+ static reloadHistory(state: FlowState): Promise<Message[]>;
4111
+ /**
4112
+ * Broadcast custom data to WebSocket clients
4113
+ *
4114
+ * Sends a custom message to all connected WebSocket clients.
4115
+ * This allows backend code to push arbitrary data to the frontend
4116
+ * outside of the standard telemetry events.
4117
+ *
4118
+ * The message is sent with the structure: { type: string, value: unknown }
4119
+ *
4120
+ * @param flow - The current FlowState
4121
+ * @param options - Broadcast options
4122
+ *
4123
+ * @example
4124
+ * ```typescript
4125
+ * // Broadcast a progress update
4126
+ * FlowStateSdk.broadcast(flow, {
4127
+ * type: "progress",
4128
+ * value: { step: 3, total: 10, message: "Processing data..." }
4129
+ * });
4130
+ *
4131
+ * // Broadcast a custom notification
4132
+ * FlowStateSdk.broadcast(flow, {
4133
+ * type: "notification",
4134
+ * value: { level: "info", message: "User authenticated successfully" }
4135
+ * });
4136
+ *
4137
+ * // Broadcast metadata
4138
+ * FlowStateSdk.broadcast(flow, {
4139
+ * type: "metadata",
4140
+ * value: { userId: "123", sessionId: "abc", timestamp: Date.now() }
4141
+ * });
4142
+ * ```
4143
+ */
4144
+ static broadcast(flow: FlowState, options: BroadcastOptions): void;
4145
+ /**
4146
+ * Force a specific side to play the next turn
4147
+ *
4148
+ * This queues the specified side to play next without interrupting the current turn.
4149
+ * The forced turn only takes effect at the END of the current turn execution.
4150
+ *
4151
+ * If the tool queue is currently being processed (sequence.isHandling is true),
4152
+ * the forced turn is deferred until all queued tools complete. This allows patterns like:
4153
+ *
4154
+ * ```typescript
4155
+ * FlowStateSdk.queueTool(flow, 'myTool', {});
4156
+ * FlowStateSdk.forceTurn(flow, 'side_a');
4157
+ * // myTool executes first, THEN the turn switches to side_a
4158
+ * ```
4159
+ *
4160
+ * @param flow - The current FlowState
4161
+ * @param side - Which side should play next ('side_a' or 'side_b')
4162
+ *
4163
+ * @example
4164
+ * ```typescript
4165
+ * // Force current side to continue (override stop condition)
4166
+ * // If side_a is playing and would stop, this forces it to play at least 1 more turn
4167
+ * FlowStateSdk.forceTurn(flow, 'side_a');
4168
+ *
4169
+ * // Force switch to other side
4170
+ * // If side_a is playing, this forces side_b to play next turn
4171
+ * FlowStateSdk.forceTurn(flow, 'side_b');
4172
+ *
4173
+ * // Forcing a HUMAN-backed side parks execution: the thread stops and
4174
+ * // waits for that side's next inbound message instead of taking a turn.
4175
+ * FlowStateSdk.forceTurn(flow, 'side_b'); // side B human-backed → parks
4176
+ * ```
4177
+ */
4178
+ static forceTurn(flow: FlowState, side: 'side_a' | 'side_b'): void;
4179
+ }
4180
+ /**
4181
+ * Convenience methods added to FlowState (optional - can be used via static methods above)
4182
+ *
4183
+ * These are helper methods that can be added to FlowState instances for convenience.
4184
+ * They delegate to the static methods above.
4185
+ */
4186
+ interface FlowStateWithSdk extends FlowState {
4187
+ queueTool: (toolName: StandardAgentSpec.Callables, args?: Record<string, unknown>) => void;
4188
+ injectMessage: (options: InjectMessageOptions) => Promise<Message>;
4189
+ getMessages: (limit?: number, offset?: number, order?: "asc" | "desc") => Promise<Message[]>;
4190
+ reloadHistory: () => Promise<Message[]>;
4191
+ broadcast: (options: BroadcastOptions) => void;
4192
+ forceTurn: (side: 'side_a' | 'side_b') => void;
4193
+ }
4194
+ /**
4195
+ * Enhance a FlowState object with SDK methods
4196
+ *
4197
+ * This adds convenience methods to a FlowState instance that delegate to
4198
+ * the static FlowStateSdk methods.
4199
+ *
4200
+ * @param flow - The FlowState to enhance
4201
+ * @returns The enhanced FlowState with SDK methods
4202
+ *
4203
+ * @example
4204
+ * ```typescript
4205
+ * const enhancedFlow = enhanceFlowState(flow);
4206
+ *
4207
+ * // Now you can use methods directly on the flow object
4208
+ * enhancedFlow.queueTool("search_user", { email: "user@example.com" });
4209
+ * await enhancedFlow.injectMessage({ role: "system", content: "Context updated" });
4210
+ * const messages = await enhancedFlow.getMessages(10);
4211
+ * flow.messageHistory = await enhancedFlow.reloadHistory();
4212
+ * enhancedFlow.broadcast({ type: "progress", value: { step: 1 } });
4213
+ * enhancedFlow.forceTurn('side_b'); // Force side_b to play next turn
4214
+ * ```
4215
+ */
4216
+ declare function enhanceFlowState(flow: FlowState): FlowStateWithSdk;
4217
+
4218
+ /**
4219
+ * Context Management for Image Attachments
4220
+ *
4221
+ * Handles auto-summarization of old images to reduce context window usage
4222
+ * while preserving the semantic meaning of image content.
4223
+ */
4224
+
4225
+ /**
4226
+ * Configuration for image context management
4227
+ */
4228
+ interface ImageContextConfig {
4229
+ /** Number of recent messages to keep images for (default: 10) */
4230
+ recentMessageThreshold: number;
4231
+ /** System prompt for generating image descriptions */
4232
+ descriptionPrompt: string;
4233
+ }
4234
+ /**
4235
+ * Check if a message has image attachments that could be summarized
4236
+ */
4237
+ declare function hasImageAttachments(message: Message): boolean;
4238
+ /**
4239
+ * Get image attachments from a message that don't have descriptions yet
4240
+ */
4241
+ declare function getUnsummarizedImageAttachments(message: Message): AttachmentRef[];
4242
+ /**
4243
+ * Determine which messages should have their images replaced with descriptions.
4244
+ * Returns indices of messages that are old enough to be summarized.
4245
+ */
4246
+ declare function getMessagesToSummarize(messages: Message[], config?: ImageContextConfig): number[];
4247
+ /**
4248
+ * Build text representation for an image attachment (used when image is too old)
4249
+ */
4250
+ declare function buildImageDescription(attachment: AttachmentRef): string;
4251
+ /**
4252
+ * Transform message content to replace old images with text descriptions.
4253
+ * This modifies the content array for LLM context building.
4254
+ */
4255
+ declare function replaceImagesWithDescriptions(content: MessageContent, attachments: AttachmentRef[]): MessageContent;
4256
+ /**
4257
+ * Process message history to optimize context window usage.
4258
+ * Old images are replaced with their text descriptions.
4259
+ *
4260
+ * @param messages - Full message history
4261
+ * @param config - Context management configuration
4262
+ * @returns Processed messages with old images replaced by descriptions
4263
+ */
4264
+ declare function optimizeImageContext(messages: Message[], config?: ImageContextConfig): Message[];
4265
+ /**
4266
+ * Generate a description for an image using a vision model.
4267
+ * This should be called when storing new messages with images.
4268
+ *
4269
+ * Note: This function is a placeholder for the actual LLM call.
4270
+ * The actual implementation would need to make an API call to a vision model.
4271
+ *
4272
+ * @param imageBase64 - Base64-encoded image data
4273
+ * @param mimeType - MIME type of the image
4274
+ * @param state - Flow state for LLM access
4275
+ * @returns Generated description
4276
+ */
4277
+ declare function generateImageDescription(_imageBase64: string, _mimeType: string, _state: FlowState): Promise<string | null>;
4278
+
4279
+ /** @public Alias for LLMProviderInterface */
4280
+ type Provider = LLMProviderInterface;
4281
+ /** @public Alias for ContentPart */
4282
+ type ProviderContentPart = ContentPart;
4283
+ /** @public Alias for TextPart */
4284
+ type ProviderTextPart = TextPart;
4285
+ /** @public Alias for ImagePart */
4286
+ type ProviderImagePart = ImagePart;
4287
+ /** @public Alias for FilePart */
4288
+ type ProviderFilePart = FilePart;
4289
+
4290
+ /**
4291
+ * Function that can intercept provider creation.
4292
+ * Returns a provider to override the default, or null to fall through.
4293
+ */
4294
+ type ProviderOverrideFn = (modelName: string, modelDef: ModelDefinition$1<string>, env: Env) => LLMProviderInterface | null;
4295
+ interface ProviderLookupResult {
4296
+ provider: LLMProviderInterface;
4297
+ modelName: string;
4298
+ modelDef: ModelDefinition$1<string>;
4299
+ /** True when requests route through the Standard Agents platform (hosted routing or a registered override). */
4300
+ viaPlatform: boolean;
4301
+ /**
4302
+ * Platform origin serving the passthrough proxy when built-in hosted routing
4303
+ * is active. Lets request logging look up the router-fee percent observed on
4304
+ * this origin's proxied responses.
4305
+ */
4306
+ platformProxyOrigin?: string;
4307
+ }
4308
+ /**
4309
+ * Provider registry implementation
4310
+ *
4311
+ * Models must use ProviderFactory functions imported from provider packages
4312
+ * (e.g., @standardagents/openai, @standardagents/openrouter).
4313
+ *
4314
+ * Loads model configs from TypeScript virtual modules and
4315
+ * provider API keys from environment variables.
4316
+ */
4317
+ declare class ProviderRegistryImpl {
4318
+ private providerCache;
4319
+ /** Why the last thread-scoped resolution did (not) contribute user env,
4320
+ * keyed by the env object handed back — surfaced in missing-variable
4321
+ * errors so a silent user-env failure is diagnosable from the log. */
4322
+ private scopeDiagnostics;
4323
+ private providerOverrideFn;
4324
+ private providerOverrideRevision;
4325
+ setProviderOverride(fn: ProviderOverrideFn | null): void;
4326
+ /**
4327
+ * The env a provider resolves against for a given execution, scoped to the
4328
+ * THREAD rather than just the instance: thread env overrides win, then the
4329
+ * thread OWNER's user env, then instance/Worker env. This is what makes
4330
+ * per-user BYOK providers work — a credential a user installs in their own
4331
+ * account env (e.g. an OAuth token a companion service rotates) is honored
4332
+ * for that user's threads no matter which authorized actor plays the turn.
4333
+ *
4334
+ * Best-effort by design: a missing user id (super-admin/local threads) or
4335
+ * an older AgentBuilder DO without user-env storage simply contributes
4336
+ * nothing, leaving instance-env behavior untouched.
4337
+ */
4338
+ buildThreadScopedEnv(state: {
4339
+ env: Env;
4340
+ thread: {
4341
+ metadata?: {
4342
+ user_id?: string | null;
4343
+ parent?: string | null;
4344
+ env?: Record<string, unknown> | null;
4345
+ tenvs?: Record<string, unknown> | null;
4346
+ };
4347
+ };
4348
+ }): Promise<Env>;
4349
+ /**
4350
+ * Get provider for a model.
4351
+ *
4352
+ * Models must use ProviderFactory functions (imported from provider packages).
4353
+ *
4354
+ * @param modelName - The model name (from TypeScript config)
4355
+ * @param env - Environment bindings
4356
+ * @param thread - Thread instance for loading model from virtual modules
4357
+ * @returns Provider and model definition
4358
+ */
4359
+ getProvider(modelName: string, env: Env, thread?: ThreadInstance, getState?: () => Promise<ThreadState>): Promise<ProviderLookupResult>;
4360
+ private buildResult;
4361
+ private cacheAndReturn;
4362
+ private getProviderFingerprint;
4363
+ /**
4364
+ * Get API key for a provider from environment variables.
4365
+ */
4366
+ private getApiKeyForProvider;
4367
+ /**
4368
+ * Clear the provider cache
4369
+ * Useful for testing or when configurations change
4370
+ */
4371
+ clearCache(): void;
4372
+ }
4373
+ /**
4374
+ * Singleton instance
4375
+ */
4376
+ declare const ProviderRegistry: ProviderRegistryImpl;
4377
+
4378
+ /**
4379
+ * Namespace-scoped resolution for the packing system.
4380
+ *
4381
+ * This module provides functions to resolve items (tools, prompts, models, agents)
4382
+ * within the correct namespace context, enforcing isolation between packed and
4383
+ * unpacked code.
4384
+ *
4385
+ * @module
4386
+ */
4387
+
4388
+ /**
4389
+ * Error thrown when an item cannot be resolved in the current namespace.
4390
+ */
4391
+ declare class NamespaceResolutionError extends Error {
4392
+ readonly itemType: 'tool' | 'prompt' | 'model' | 'agent' | 'hook';
4393
+ readonly itemName: string;
4394
+ readonly namespace: NamespaceContext;
4395
+ constructor(itemType: 'tool' | 'prompt' | 'model' | 'agent' | 'hook', itemName: string, namespace: NamespaceContext, message: string);
4396
+ }
4397
+ /**
4398
+ * Parse a potentially qualified name into package ID and short name.
4399
+ *
4400
+ * For scoped npm packages (starting with @), the format is @scope/pkg-name/item-name
4401
+ * where @scope/pkg-name is the package and item-name is the short name.
4402
+ *
4403
+ * For non-scoped packages, the format is pkg-name/item-name.
4404
+ *
4405
+ * @param name - The name to parse (e.g., 'tool', 'pkg/tool', or '@scope/pkg/tool')
4406
+ * @returns Tuple of [packageId, shortName] where packageId is null for unqualified names
4407
+ */
4408
+ declare function parseQualifiedName(name: string): [string | null, string];
4409
+ /**
4410
+ * Create a qualified name from package ID and short name.
4411
+ */
4412
+ declare function qualifyName(packageId: string, shortName: string): string;
4413
+ /**
4414
+ * Get the short name (strip any package qualification).
4415
+ */
4416
+ declare function getShortName(name: string): string;
4417
+ /**
4418
+ * Resolve a tool by name within a namespace context.
4419
+ *
4420
+ * Resolution rules:
4421
+ * - Qualified names (pkg:tool) → resolve cross-package entry point
4422
+ * - Unqualified names in packed context → resolve from own package
4423
+ * - Unqualified names in global context → resolve from global namespace
4424
+ *
4425
+ * @param registry - The namespaced registry
4426
+ * @param name - Tool name (can be qualified with packageId:toolName)
4427
+ * @param namespace - Current namespace context
4428
+ * @returns Loader function for the tool definition
4429
+ * @throws NamespaceResolutionError if tool cannot be found or accessed
4430
+ */
4431
+ declare function resolveTool(registry: NamespacedRegistry, name: string, namespace: NamespaceContext): DefinitionLoader<unknown>;
4432
+ /**
4433
+ * Resolve a prompt by name within a namespace context.
4434
+ *
4435
+ * @param registry - The namespaced registry
4436
+ * @param name - Prompt name (can be qualified)
4437
+ * @param namespace - Current namespace context
4438
+ * @returns Loader function for the prompt definition
4439
+ */
4440
+ declare function resolvePrompt(registry: NamespacedRegistry, name: string, namespace: NamespaceContext): DefinitionLoader<unknown>;
4441
+ /**
4442
+ * Resolve a model by name within a namespace context.
4443
+ *
4444
+ * Models are special: packed agents include their model definitions,
4445
+ * but the host must provide API keys.
4446
+ *
4447
+ * @param registry - The namespaced registry
4448
+ * @param name - Model name
4449
+ * @param namespace - Current namespace context
4450
+ * @returns Loader function for the model definition
4451
+ */
4452
+ declare function resolveModel(registry: NamespacedRegistry, name: string, namespace: NamespaceContext): DefinitionLoader<unknown>;
4453
+ /**
4454
+ * Resolve an agent by name within a namespace context.
4455
+ *
4456
+ * Resolution rules:
4457
+ * - Qualified names (pkg:agent) → resolve cross-package entry point
4458
+ * - Unqualified in packed → resolve from own package
4459
+ * - Unqualified in global → resolve from global + entry points
4460
+ *
4461
+ * @param registry - The namespaced registry
4462
+ * @param name - Agent name (can be qualified)
4463
+ * @param namespace - Current namespace context
4464
+ * @returns Loader function for the agent definition
4465
+ */
4466
+ declare function resolveAgent(registry: NamespacedRegistry, name: string, namespace: NamespaceContext): DefinitionLoader<unknown>;
4467
+ /**
4468
+ * Resolve a hook by name within a namespace context.
4469
+ *
4470
+ * Hooks follow similar rules to tools but are keyed by hook type.
4471
+ *
4472
+ * @param registry - The namespaced registry
4473
+ * @param name - Hook name (file name, e.g., 'filter_messages')
4474
+ * @param namespace - Current namespace context
4475
+ * @returns Loader function for the hook implementation
4476
+ */
4477
+ declare function resolveHook(registry: NamespacedRegistry, name: string, namespace: NamespaceContext): DefinitionLoader<unknown> | null;
4478
+ /**
4479
+ * Get all tool names visible in a namespace context.
4480
+ *
4481
+ * @param registry - The namespaced registry
4482
+ * @param namespace - Current namespace context
4483
+ * @returns Array of visible tool names (short names)
4484
+ */
4485
+ declare function getVisibleToolNames(registry: NamespacedRegistry, namespace: NamespaceContext): string[];
4486
+ /**
4487
+ * Get all agent names visible in a namespace context.
4488
+ *
4489
+ * @param registry - The namespaced registry
4490
+ * @param namespace - Current namespace context
4491
+ * @returns Array of visible agent names (may include qualified names for cross-package)
4492
+ */
4493
+ declare function getVisibleAgentNames(registry: NamespacedRegistry, namespace: NamespaceContext): string[];
4494
+ /**
4495
+ * Get all prompt names visible in a namespace context.
4496
+ */
4497
+ declare function getVisiblePromptNames(registry: NamespacedRegistry, namespace: NamespaceContext): string[];
4498
+ /**
4499
+ * Get all model names visible in a namespace context.
4500
+ */
4501
+ declare function getVisibleModelNames(registry: NamespacedRegistry, namespace: NamespaceContext): string[];
4502
+ /**
4503
+ * Create a namespace context for an agent definition.
4504
+ *
4505
+ * @param agentDef - Agent definition (may have __package field)
4506
+ * @returns Appropriate namespace context
4507
+ */
4508
+ declare function createNamespaceContext(agentDef: {
4509
+ __package?: {
4510
+ packageId: string;
4511
+ };
4512
+ } | undefined): NamespaceContext;
4513
+ /**
4514
+ * Check if a name is qualified (contains package prefix).
4515
+ *
4516
+ * For scoped packages (@scope/name), there must be at least two slashes
4517
+ * to be considered qualified (e.g., @scope/pkg/item).
4518
+ * For non-scoped packages, a single slash qualifies it (e.g., pkg/item).
4519
+ */
4520
+ declare function isQualifiedName(name: string): boolean;
4521
+
4522
+ export { stat as $, type AgentDefinition as A, type SessionToolBinding as B, CodeExecutionBridge as C, DurableThread as D, type HumanSide as E, type PromptSide as F, type HandlerSide as G, type HubClientInfo as H, type SideConfig as I, type SubagentRelationship as J, queueTool as K, injectMessage as L, type ModelDefinition as M, getMessages as N, reloadHistory as O, type Provider$1 as P, emitThreadEvent as Q, forceTurn as R, type SubpromptConfig as S, ThreadWatchdog as T, type UpdateThreadParams as U, updateThread as V, type WatchdogProbeResult as W, writeFile as X, writeImage as Y, linkFile as Z, readFile as _, isTrustedLocalDevelopmentRequest as a, exists as a0, unlink as a1, mkdir as a2, readdir as a3, rmdir as a4, move as a5, rename as a6, getFileStats as a7, getThumbnail as a8, cat as a9, resolveTool as aA, resolvePrompt as aB, resolveModel as aC, resolveAgent as aD, resolveHook as aE, getVisibleToolNames as aF, getVisibleAgentNames as aG, getVisiblePromptNames as aH, getVisibleModelNames as aI, createNamespaceContext as aJ, isQualifiedName as aK, NamespaceResolutionError as aL, head as aa, tail as ab, grep as ac, find as ad, type InjectMessageOptions as ae, FlowStateSdk as af, enhanceFlowState as ag, type BroadcastOptions as ah, type FlowStateWithSdk as ai, hasImageAttachments as aj, getUnsummarizedImageAttachments as ak, getMessagesToSummarize as al, buildImageDescription as am, replaceImagesWithDescriptions as an, optimizeImageContext as ao, generateImageDescription as ap, type ImageContextConfig as aq, ProviderRegistry as ar, type Provider as as, type ProviderContentPart as at, type ProviderTextPart as au, type ProviderImagePart as av, type ProviderFilePart as aw, parseQualifiedName as ax, qualifyName as ay, getShortName as az, isPublicApiRoute as b, canAccessThread as c, isAdminOnlyApiRoute as d, isSameOriginBrowserRequest as e, applyRuntimeCors as f, runtimePreflightResponse as g, DurableAgentBuilder as h, isHostedInstance as i, type ThreadWatchdogState as j, type WatchdogCheckin as k, DurableUserHub as l, type AgentBuilderEnv as m, type AgentBuilderEvent as n, type ThreadEventPayload as o, type ThreadRegistryEntry as p, type User as q, runtimeCorsHeaders as r, type PromptDefinition as s, type PromptToolConfig as t, type SubagentToolConfig as u, type ToolConfig as v, type PromptContent as w, type PromptPart as x, type PromptIncludePart as y, type SessionToolConfig as z };