@deepagents/experimental 6.0.0 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/coding-agent-reminders/index.ts", "../src/coding-agent-reminders/evaluate.ts", "../src/coding-agent-reminders/io.ts", "../src/coding-agent-reminders/predicates/classifier.ts", "../src/coding-agent-reminders/predicates/combinators.ts", "../src/coding-agent-reminders/context.ts", "../src/coding-agent-reminders/predicates/content.ts", "../src/coding-agent-reminders/predicates/count.ts", "../src/coding-agent-reminders/predicates/environment.ts", "../src/coding-agent-reminders/predicates/event.ts", "../src/coding-agent-reminders/predicates/tool.ts", "../src/zukhruf/index.ts", "../src/zukhruf/agent.ts", "../src/zukhruf/control-plane/agent-path.ts", "../src/zukhruf/control-plane/agent-thread.ts", "../src/zukhruf/runtime/agent-runtime.ts", "../src/zukhruf/control-plane/agent-control-plane.ts", "../src/zukhruf/mailbox/types.ts", "../src/zukhruf/control-plane/agent-declaration-registry.ts", "../src/zukhruf/control-plane/agent-directory.ts", "../src/zukhruf/control-plane/agent-history-forker.ts", "../src/zukhruf/control-plane/agent-status-projector.ts", "../src/zukhruf/control-plane/agent-turn-id.ts", "../src/zukhruf/mailbox/coordinator.ts", "../src/zukhruf/multi-agent-v2-config.ts", "../src/zukhruf/runtime/agent-turn-executor.ts", "../src/zukhruf/collaboration/interrupt-agent.ts", "../src/zukhruf/collaboration/list-agents.ts", "../src/zukhruf/collaboration/message-tools.ts", "../src/zukhruf/collaboration/spawn-agent.ts", "../src/zukhruf/control-plane/fork-turns.ts", "../src/zukhruf/collaboration/wait-agent.ts", "../src/zukhruf/collaboration/collaboration-tools.ts", "../src/zukhruf/runtime/approval-controller.ts", "../src/zukhruf/runtime/approval-job-id.ts", "../src/zukhruf/instructions.ts", "../src/zukhruf/mailbox/sqlite.store.ts", "../src/zukhruf/mailbox/store.ts", "../src/zukhruf/queue/pg-boss.turn-queue.ts", "../src/zukhruf/queue/turn-queue.ts", "../src/zukhruf/render-turn.ts", "../src/zukhruf/sandbox/define.ts", "../src/zukhruf/tool.ts"],
4
- "sourcesContent": ["export * from './evaluate.ts';\nexport * from './io.ts';\nexport * from './predicates/index.ts';\nexport * from './types.ts';\n", "import type {\n ClaudeHookInput,\n ClaudeHookOutput,\n GuardRule,\n HookEventName,\n ReminderHookConfig,\n ReminderRule,\n} from './types.ts';\n\nexport async function evaluateReminderHook(\n input: ClaudeHookInput,\n config: ReminderHookConfig,\n): Promise<ClaudeHookOutput | undefined> {\n const guardMatch =\n input.hook_event_name === 'PreToolUse'\n ? await firstMatchingGuard(input, config.guards)\n : undefined;\n if (guardMatch) {\n return {\n hookSpecificOutput: {\n hookEventName: input.hook_event_name,\n permissionDecision: 'deny',\n permissionDecisionReason:\n guardMatch.errorReason ?? resolveGuardReason(guardMatch.rule, input),\n },\n };\n }\n\n if (\n input.stop_hook_active === true &&\n (input.hook_event_name === 'Stop' ||\n input.hook_event_name === 'SubagentStop')\n ) {\n return undefined;\n }\n\n const reminders = await matchingReminders(input, config.reminders);\n if (reminders.length === 0) return undefined;\n\n return {\n hookSpecificOutput: {\n hookEventName: input.hook_event_name,\n additionalContext: reminders.join('\\n\\n'),\n },\n };\n}\n\nasync function firstMatchingGuard(\n input: ClaudeHookInput,\n guards: GuardRule[],\n): Promise<{ rule: GuardRule; errorReason?: string } | undefined> {\n for (const rule of guards) {\n try {\n if (await rule.when(input)) return { rule };\n } catch (error) {\n console.error(`Guard \"${rule.id}\" predicate failed`, error);\n return {\n rule,\n errorReason: `Guard \"${rule.id}\" failed to evaluate; denying by default.`,\n };\n }\n }\n return undefined;\n}\n\nasync function matchingReminders(\n input: ClaudeHookInput,\n reminders: ReminderRule[],\n): Promise<string[]> {\n const matched: string[] = [];\n for (const rule of reminders) {\n if (!rule.events.includes(input.hook_event_name as HookEventName)) continue;\n try {\n if (!(await rule.when(input))) continue;\n matched.push(\n `[${rule.target}:${rule.id}]\\n${resolveText(rule.message, input)}`,\n );\n } catch (error) {\n console.error(`Reminder \"${rule.id}\" evaluation failed`, error);\n }\n }\n return matched;\n}\n\nfunction resolveText(\n value: string | ((ctx: ClaudeHookInput) => string),\n input: ClaudeHookInput,\n): string {\n return typeof value === 'function' ? value(input) : value;\n}\n\nfunction resolveGuardReason(rule: GuardRule, input: ClaudeHookInput): string {\n try {\n return resolveText(rule.deny, input);\n } catch (error) {\n console.error(`Guard \"${rule.id}\" denial message failed`, error);\n return `Guard \"${rule.id}\" matched but its denial message failed; denying by default.`;\n }\n}\n", "import type { ClaudeHookOutput } from './types.ts';\n\nexport async function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(Buffer.from(chunk));\n }\n return Buffer.concat(chunks).toString('utf8');\n}\n\nexport function writeOutput(output: ClaudeHookOutput): void {\n process.stdout.write(`${JSON.stringify(output)}\\n`);\n}\n", "import { Corpus } from 'tiny-tfidf';\n\nimport type {\n ClassifierMatch,\n ClassifierOptions,\n IClassifier,\n} from '../types.ts';\n\nexport class BM25Classifier<\n T extends { name: string; description: string },\n> implements IClassifier<T> {\n #corpus: Corpus;\n #itemsByName: Map<string, T>;\n\n constructor(items: T[]) {\n const names = items.map((item) => item.name);\n const texts = items.map((item) => `${item.name} ${item.description}`);\n this.#corpus = new Corpus(names, texts);\n this.#itemsByName = new Map(items.map((item) => [item.name, item]));\n }\n\n match(query: string, options?: ClassifierOptions): ClassifierMatch<T>[] {\n const topN = options?.topN ?? 5;\n const threshold = options?.threshold ?? 0;\n\n return this.#corpus\n .getResultsForQuery(query)\n .filter(([, score]: [string, number]) => score > threshold)\n .slice(0, topN)\n .map(([name, score]: [string, number]) => {\n const item = this.#itemsByName.get(name);\n if (!item) return null;\n return { item, score };\n })\n .filter((match): match is ClassifierMatch<T> => match !== null);\n }\n}\n", "import type { AsyncHookPredicate, HookPredicate } from '../types.ts';\n\nexport const always: HookPredicate = () => true;\n\nexport const and =\n (...predicates: HookPredicate[]): AsyncHookPredicate =>\n async (ctx) => {\n for (const predicate of predicates) {\n if (!(await predicate(ctx))) return false;\n }\n return true;\n };\n\nexport const or =\n (...predicates: HookPredicate[]): AsyncHookPredicate =>\n async (ctx) => {\n for (const predicate of predicates) {\n if (await predicate(ctx)) return true;\n }\n return false;\n };\n\nexport const not =\n (predicate: HookPredicate): AsyncHookPredicate =>\n async (ctx) =>\n !(await predicate(ctx));\n", "import type { ClaudeHookInput, ToolCallState, ToolNameSpec } from './types.ts';\n\nexport type NormalizedToolCall = {\n name: string;\n state: ToolCallState;\n input?: unknown;\n output?: unknown;\n errorText?: string;\n};\n\nexport function contentText(ctx: ClaudeHookInput): string {\n return [ctx.prompt, ctx.command_name, ctx.command_args]\n .filter((value): value is string => typeof value === 'string')\n .join(' ');\n}\n\nexport function bashCommand(ctx: ClaudeHookInput): string {\n if (ctx.tool_name !== 'Bash') return '';\n const command = ctx.tool_input?.command;\n return typeof command === 'string' ? command : '';\n}\n\nexport function outputText(ctx: ClaudeHookInput): string {\n if (ctx.hook_event_name === 'PostToolBatch' && ctx.tool_calls) {\n return ctx.tool_calls\n .map((call) => textOf(call.tool_response))\n .filter(Boolean)\n .join('\\n');\n }\n const output = ctx.tool_output ?? ctx.tool_response;\n return textOf(output);\n}\n\nexport function textOf(value: unknown): string {\n if (typeof value === 'string') return value;\n if (value === undefined) return '';\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nexport function toolCallsOf(ctx: ClaudeHookInput): NormalizedToolCall[] {\n if (ctx.hook_event_name === 'PostToolBatch' && ctx.tool_calls) {\n return ctx.tool_calls.map((call) => ({\n name: call.tool_name,\n state: 'output-available',\n input: call.tool_input,\n output: call.tool_response,\n }));\n }\n\n const calls: NormalizedToolCall[] = [];\n const toolName = ctx.tool_name;\n if (typeof toolName === 'string') {\n calls.push({\n name: toolName,\n state: stateOf(ctx.hook_event_name),\n input: ctx.tool_input,\n output: ctx.tool_output ?? ctx.tool_response,\n errorText: errorTextOf(ctx),\n });\n }\n return calls;\n}\n\nexport function matchesName(spec: ToolNameSpec, name: string): boolean {\n return typeof spec === 'function' ? spec(name) : spec === name;\n}\n\nfunction stateOf(eventName: string): ToolCallState {\n if (eventName === 'PostToolUseFailure') return 'output-error';\n if (eventName === 'PostToolUse') return 'output-available';\n return 'input-available';\n}\n\nfunction errorTextOf(ctx: ClaudeHookInput): string {\n const error =\n ctx.tool_error ??\n ctx.error ??\n ctx.reason ??\n ctx.tool_output ??\n ctx.tool_response;\n return textOf(error);\n}\n", "import { contentText } from '../context.ts';\nimport type {\n ClassifierOptions,\n ContentMatchesOptions,\n HookPredicate,\n IClassifier,\n} from '../types.ts';\nimport { BM25Classifier } from './classifier.ts';\n\nexport function contentMatches(\n topics: string[],\n options?: ContentMatchesOptions,\n): HookPredicate {\n const classifier = new BM25Classifier(\n topics.map((topic, index) => ({\n name: `t${index}`,\n description: topic,\n })),\n );\n return (ctx) =>\n classifier.match(contentText(ctx), {\n threshold: options?.threshold,\n }).length > 0;\n}\n\nexport function classifies<T>(\n classifier: IClassifier<T>,\n options?: ClassifierOptions,\n): HookPredicate {\n return (ctx) => classifier.match(contentText(ctx), options).length > 0;\n}\n\nexport function contentIncludes(keywords: string[]): HookPredicate {\n const lower = keywords.map((keyword) => keyword.toLowerCase());\n return (ctx) => {\n const text = contentText(ctx).toLowerCase();\n return lower.some((keyword) => text.includes(keyword));\n };\n}\n\nexport const contentPattern =\n (pattern: RegExp): HookPredicate =>\n (ctx) => {\n pattern.lastIndex = 0;\n return pattern.test(contentText(ctx));\n };\n\nexport const promptMatches = contentPattern;\n", "import type { CountSpec } from '../types.ts';\n\nexport function assertCountSpec(spec: CountSpec): void {\n const hasEq = spec.eq !== undefined;\n const hasRange = spec.gte !== undefined || spec.lte !== undefined;\n if (!hasEq && !hasRange) {\n throw new Error('CountSpec must include at least one of gte/lte/eq');\n }\n if (hasEq && hasRange) {\n throw new Error('CountSpec.eq cannot be combined with gte/lte');\n }\n}\n\nexport function checkCount(count: number, spec: CountSpec): boolean {\n if (spec.eq !== undefined) return count === spec.eq;\n if (spec.gte !== undefined && count < spec.gte) return false;\n if (spec.lte !== undefined && count > spec.lte) return false;\n return true;\n}\n", "import type { HookPredicate } from '../types.ts';\n\nexport const envFlag =\n (name: string): HookPredicate =>\n () =>\n process.env[name] === '1' || process.env[name] === 'true';\n", "import type { HookEventName, HookPredicate } from '../types.ts';\n\nexport const eventIs =\n (...events: HookEventName[]): HookPredicate =>\n (ctx) =>\n events.includes(ctx.hook_event_name as HookEventName);\n", "import {\n bashCommand,\n matchesName,\n outputText,\n textOf,\n toolCallsOf,\n} from '../context.ts';\nimport type {\n CountSpec,\n HookPredicate,\n ToolCallOptions,\n ToolNameSpec,\n} from '../types.ts';\nimport { assertCountSpec, checkCount } from './count.ts';\n\nexport const toolIs =\n (name: string): HookPredicate =>\n (ctx) =>\n ctx.tool_name === name;\n\nexport const bashCommandMatches =\n (pattern: RegExp): HookPredicate =>\n (ctx) => {\n pattern.lastIndex = 0;\n return pattern.test(bashCommand(ctx));\n };\n\nexport function toolCall(options: ToolCallOptions): HookPredicate {\n return (ctx) => {\n return toolCallsOf(ctx).some((call) => {\n if (options.state && call.state !== options.state) return false;\n if (options.name !== undefined && !matchesName(options.name, call.name)) {\n return false;\n }\n if (options.input && !options.input(call.input)) return false;\n if (options.output) {\n if (call.state !== 'output-available') return false;\n if (!options.output(call.output)) return false;\n }\n if (options.errorText) {\n if (call.state !== 'output-error') return false;\n if (!options.errorText(call.errorText ?? '')) return false;\n }\n return true;\n });\n };\n}\n\nexport function toolCalled(name: ToolNameSpec): HookPredicate {\n return toolCall({ name });\n}\n\nexport function toolFailed(name: ToolNameSpec): HookPredicate {\n return toolCall({ name, state: 'output-error' });\n}\n\nexport function anyToolCalled(): HookPredicate {\n return (ctx) => toolCallsOf(ctx).length > 0;\n}\n\nexport function toolCallCount(\n name: ToolNameSpec,\n spec: CountSpec,\n): HookPredicate {\n assertCountSpec(spec);\n return (ctx) =>\n checkCount(\n toolCallsOf(ctx).filter((call) => matchesName(name, call.name)).length,\n spec,\n );\n}\n\nexport const outputMatches =\n (pattern: RegExp): HookPredicate =>\n (ctx) => {\n pattern.lastIndex = 0;\n return pattern.test(outputText(ctx));\n };\n\nexport const toolOutputMatches = (pattern: RegExp): HookPredicate =>\n toolCall({\n output: (output) => {\n pattern.lastIndex = 0;\n return pattern.test(textOf(output));\n },\n });\n", "export * from './agent.ts';\nexport * from './control-plane/agent-path.ts';\nexport * from './control-plane/agent-thread.ts';\nexport type { TurnInput } from './control-plane/agent-control-plane.ts';\nexport * from './runtime/agent-runtime.ts';\nexport type { MultiAgentV2HostConfig } from './multi-agent-v2-config.ts';\nexport * from './instructions.ts';\nexport * from './mailbox/sqlite.store.ts';\nexport * from './mailbox/store.ts';\nexport * from './mailbox/types.ts';\nexport * from './queue/pg-boss.turn-queue.ts';\nexport * from './queue/turn-queue.ts';\nexport * from './render-turn.ts';\nexport * from './sandbox/define.ts';\nexport * from './tool.ts';\n", "import type { generateText } from 'ai';\n\nimport type {\n AgentModel,\n AgentSandbox,\n ContextFragment,\n} from '@deepagents/context';\n\nimport type { ZukhrufToolSet } from './tool.ts';\n\n/**\n * Sandboxes are per-chat: the factory receives the conversation identity so\n * the backend can be named by `chatId` and re-attached across turns, workers,\n * and restarts (the container engine is the registry \u2014 no in-memory state).\n */\nexport interface SandboxContext {\n chatId: string;\n userId: string;\n}\n\nexport interface AgentDeclaration {\n /**\n * Stable declaration identity persisted in conversation metadata.\n * It must be unique in one declaration graph and must not be renamed while\n * conversations created from that graph still exist.\n */\n name: string;\n model: AgentModel;\n sandbox: (context: SandboxContext) => Promise<AgentSandbox>;\n instructions: ContextFragment[];\n tools?: ZukhrufToolSet;\n subagents?: AgentDeclaration[];\n telemetry?: Parameters<typeof generateText>[0]['telemetry'];\n}\n\nexport interface DefinedAgentDeclaration extends AgentDeclaration {\n tools: ZukhrufToolSet;\n subagents: AgentDeclaration[];\n}\n\nexport function defineAgent(\n declaration: AgentDeclaration,\n): DefinedAgentDeclaration {\n return {\n name: declaration.name,\n model: declaration.model,\n sandbox: declaration.sandbox,\n instructions: declaration.instructions,\n tools: declaration.tools ?? {},\n subagents: declaration.subagents ?? [],\n telemetry: declaration.telemetry,\n };\n}\n", "/** Canonical model-facing address for one agent in a Zukhruf tree. */\nexport class AgentPath {\n readonly #value: string;\n\n private constructor(value: string) {\n this.#value = value;\n }\n\n static root(): AgentPath {\n return new AgentPath('/root');\n }\n\n static parse(value: string): AgentPath {\n const path = value.trim();\n if (path !== '/root' && !path.startsWith('/root/')) {\n throw new Error(`agent path \"${value}\" must start at /root`);\n }\n\n const segments = path.slice(1).split('/');\n if (\n segments.some(\n (segment) =>\n segment.length === 0 ||\n segment !== segment.trim() ||\n segment === '.' ||\n segment === '..',\n )\n ) {\n throw new Error(`agent path \"${value}\" contains an invalid segment`);\n }\n return new AgentPath(path);\n }\n\n /** Relative targets name descendants; absolute targets keep their canonical path. */\n resolve(target: string): AgentPath {\n const requested = target.trim();\n if (!requested) throw new Error('agent path cannot be empty');\n return AgentPath.parse(\n requested.startsWith('/') ? requested : `${this.#value}/${requested}`,\n );\n }\n\n contains(candidate: AgentPath): boolean {\n return (\n this.equals(candidate) || candidate.#value.startsWith(`${this.#value}/`)\n );\n }\n\n equals(other: AgentPath): boolean {\n return this.#value === other.#value;\n }\n\n get isRoot(): boolean {\n return this.#value === '/root';\n }\n\n get parent(): AgentPath | null {\n if (this.isRoot) return null;\n return AgentPath.parse(this.#value.slice(0, this.#value.lastIndexOf('/')));\n }\n\n toString(): string {\n return this.#value;\n }\n}\n", "import type { ConversationId } from '../mailbox/types.ts';\nimport { AgentPath } from './agent-path.ts';\n\nexport interface AgentThreadOptions {\n conversation: ConversationId;\n treeId: string;\n path: AgentPath;\n parentChatId: string | null;\n declarationName: string;\n lastTurnId?: string;\n}\n\n/** Durable identity and persisted metadata for one agent instance. */\nexport class AgentThread {\n readonly conversation: ConversationId;\n readonly treeId: string;\n readonly path: AgentPath;\n readonly parentChatId: string | null;\n readonly declarationName: string;\n readonly lastTurnId?: string;\n\n constructor(options: AgentThreadOptions) {\n AgentThread.#assertTopology(options);\n this.conversation = options.conversation;\n this.treeId = options.treeId;\n this.path = options.path;\n this.parentChatId = options.parentChatId;\n this.declarationName = options.declarationName;\n this.lastTurnId = options.lastTurnId;\n }\n\n static root(\n conversation: ConversationId,\n declarationName: string,\n ): AgentThread {\n return new AgentThread({\n conversation,\n treeId: conversation.chatId,\n path: AgentPath.root(),\n parentChatId: null,\n declarationName,\n });\n }\n\n static metadataFilter(treeId: string): { key: string; value: string } {\n return { key: 'zukhrufTreeId', value: treeId };\n }\n\n static hasReservedMetadata(\n metadata: Record<string, unknown> | undefined,\n ): boolean {\n return Boolean(\n metadata &&\n (Object.hasOwn(metadata, 'zukhrufTreeId') ||\n Object.hasOwn(metadata, 'zukhruf')),\n );\n }\n\n static fromMetadata(\n conversation: ConversationId,\n metadata: Record<string, unknown> | undefined,\n ): AgentThread | undefined {\n const treeId = metadata?.zukhrufTreeId;\n const zukhruf = metadata?.zukhruf;\n if (typeof treeId !== 'string' || !AgentThread.#isRecord(zukhruf)) {\n return undefined;\n }\n\n const { path, parentChatId, declarationName, lastTurnId } = zukhruf;\n if (\n typeof path !== 'string' ||\n (parentChatId !== null && typeof parentChatId !== 'string') ||\n typeof declarationName !== 'string' ||\n (lastTurnId !== undefined && typeof lastTurnId !== 'string')\n ) {\n return undefined;\n }\n\n let parsedPath: AgentPath;\n try {\n parsedPath = AgentPath.parse(path);\n } catch {\n return undefined;\n }\n if (parsedPath.toString() !== path) return undefined;\n\n try {\n return new AgentThread({\n conversation,\n treeId,\n path: parsedPath,\n parentChatId,\n declarationName,\n ...(lastTurnId === undefined ? {} : { lastTurnId }),\n });\n } catch {\n return undefined;\n }\n }\n\n withLatestTurn(lastTurnId: string): AgentThread {\n return new AgentThread({\n conversation: this.conversation,\n treeId: this.treeId,\n path: this.path,\n parentChatId: this.parentChatId,\n declarationName: this.declarationName,\n lastTurnId,\n });\n }\n\n toMetadata(\n metadata: Record<string, unknown> | undefined,\n ): Record<string, unknown> {\n const existing = AgentThread.#isRecord(metadata?.zukhruf)\n ? metadata.zukhruf\n : {};\n return {\n ...metadata,\n zukhrufTreeId: this.treeId,\n zukhruf: {\n ...existing,\n path: this.path.toString(),\n parentChatId: this.parentChatId,\n declarationName: this.declarationName,\n ...(this.lastTurnId === undefined\n ? {}\n : { lastTurnId: this.lastTurnId }),\n },\n };\n }\n\n static #isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n }\n\n static #assertTopology(options: AgentThreadOptions): void {\n if (options.path.isRoot) {\n if (options.treeId !== options.conversation.chatId) {\n throw new Error('root agent thread treeId must match its chatId');\n }\n if (options.parentChatId !== null) {\n throw new Error('root agent thread cannot have a parent');\n }\n return;\n }\n if (options.parentChatId === null) {\n throw new Error('child agent thread requires a parent');\n }\n if (options.parentChatId === options.conversation.chatId) {\n throw new Error('child agent thread cannot parent itself');\n }\n }\n}\n", "import {\n ContextEngine,\n type ContextStore,\n type StreamManager,\n} from '@deepagents/context';\n\nimport type { AgentDeclaration } from '../agent.ts';\nimport {\n AgentControlPlane,\n type TurnInput,\n} from '../control-plane/agent-control-plane.ts';\nimport { AgentDeclarationRegistry } from '../control-plane/agent-declaration-registry.ts';\nimport { AgentDirectory } from '../control-plane/agent-directory.ts';\nimport { AgentHistoryForker } from '../control-plane/agent-history-forker.ts';\nimport { AgentStatusProjector } from '../control-plane/agent-status-projector.ts';\nimport { AgentTurnId } from '../control-plane/agent-turn-id.ts';\nimport { MailboxCoordinator } from '../mailbox/coordinator.ts';\nimport type { MailboxStore } from '../mailbox/store.ts';\nimport type {\n ConversationId,\n InterAgentCommunication,\n MessageDeliveryMode,\n} from '../mailbox/types.ts';\nimport {\n type MultiAgentV2HostConfig,\n resolveMultiAgentV2HostConfig,\n} from '../multi-agent-v2-config.ts';\nimport type { TurnQueue, TurnRef } from '../queue/turn-queue.ts';\nimport { AgentTurnExecutor } from './agent-turn-executor.ts';\nimport { ApprovalController } from './approval-controller.ts';\n\nexport interface AgentRuntimeOptions {\n store: ContextStore;\n /** Borrowed stream subsystem; the caller owns its store, change source, and lifecycle. */\n streams: StreamManager;\n queue: TurnQueue;\n /** Durable pending inter-agent input. Distinct from the TurnQueue scheduler. */\n mailboxStore: MailboxStore;\n /** Codex MultiAgentV2-compatible host guidance and tool configuration. */\n multiAgentV2?: MultiAgentV2HostConfig;\n}\n\nexport interface AgentRuntimeWorkOptions {\n concurrency?: number;\n}\n\n/** Reconnect and cancellation view over one durable conversation. */\nexport class AgentObservation {\n readonly engine: ContextEngine;\n readonly #conversation: ConversationId;\n readonly #store: ContextStore;\n readonly #streams: StreamManager;\n\n constructor(\n conversation: ConversationId,\n store: ContextStore,\n streams: StreamManager,\n ) {\n this.engine = new ContextEngine({\n store,\n chatId: conversation.chatId,\n userId: conversation.userId,\n });\n this.#conversation = conversation;\n this.#store = store;\n this.#streams = streams;\n }\n\n async resume() {\n const id = await this.#headStreamId();\n if (!id) return null;\n AgentTurnId.assertOwner(this.#conversation, id);\n const status = await this.#streams.store.getStreamStatus(id);\n return status ? this.#streams.watch(id) : null;\n }\n\n async cancel(streamId?: string): Promise<void> {\n const chat = await this.#store.getChat(this.#conversation.chatId);\n if (chat && chat.userId !== this.#conversation.userId) {\n throw new Error(\n `chat \"${this.#conversation.chatId}\" belongs to user \"${chat.userId}\", not \"${this.#conversation.userId}\"`,\n );\n }\n const id = streamId ?? (await this.#headStreamId());\n if (!id) return;\n AgentTurnId.assertOwner(this.#conversation, id);\n const status = await this.#streams.store.getStreamStatus(id);\n if (status === 'queued' || status === 'running') {\n await this.#streams.cancel(id);\n }\n }\n\n async #headStreamId(): Promise<string | undefined> {\n const head = await this.engine.headMessage();\n return head?.name === 'assistant' ? head.id : undefined;\n }\n}\n\n/** Thin host-facing composition and lifecycle fa\u00E7ade for a Zukhruf agent tree. */\nexport class AgentRuntime {\n readonly #store: ContextStore;\n readonly #queue: TurnQueue;\n readonly #streams: StreamManager;\n readonly #mailbox: MailboxCoordinator;\n readonly #directory: AgentDirectory;\n readonly #controlPlane: AgentControlPlane;\n readonly #approvals: ApprovalController;\n readonly #executor: AgentTurnExecutor;\n\n constructor(root: AgentDeclaration, options: AgentRuntimeOptions) {\n const multiAgentV2 = resolveMultiAgentV2HostConfig(options.multiAgentV2);\n const declarations = new AgentDeclarationRegistry(root);\n const directory = new AgentDirectory(options.store);\n const streams = options.streams;\n const mailbox = new MailboxCoordinator({\n store: options.mailboxStore,\n queue: options.queue,\n streams,\n });\n const approvals = new ApprovalController({\n store: options.store,\n queue: options.queue,\n });\n const statusProjector = new AgentStatusProjector({\n store: options.store,\n streams,\n queue: options.queue,\n mailbox,\n directory,\n approvals,\n });\n const historyForker = new AgentHistoryForker(options.store);\n const controlPlane = new AgentControlPlane({\n root,\n streams,\n queue: options.queue,\n mailbox,\n declarations,\n directory,\n statusProjector,\n historyForker,\n });\n\n this.#store = options.store;\n this.#queue = options.queue;\n this.#streams = streams;\n this.#mailbox = mailbox;\n this.#directory = directory;\n this.#controlPlane = controlPlane;\n this.#approvals = approvals;\n this.#executor = new AgentTurnExecutor({\n store: options.store,\n streams,\n controlPlane,\n mailbox,\n approvals,\n multiAgentV2,\n });\n }\n\n async enqueue(conversation: ConversationId, turn: TurnInput) {\n const streamId = await this.#controlPlane.enqueue(conversation, turn);\n return { id: streamId, stream: this.#streams.watch(streamId) };\n }\n\n async deliver(\n communication: InterAgentCommunication,\n mode: MessageDeliveryMode,\n ): Promise<void> {\n await this.#directory.assertOwnerIfExists(communication.recipient);\n await this.#mailbox.deliver(communication, mode);\n }\n\n approve(conversation: ConversationId, input: { toolCallId: string }) {\n return this.#approvals.approve(conversation, input);\n }\n\n deny(\n conversation: ConversationId,\n input: { toolCallId: string; reason?: string },\n ) {\n return this.#approvals.deny(conversation, input);\n }\n\n observe(conversation: ConversationId): AgentObservation {\n return new AgentObservation(conversation, this.#store, this.#streams);\n }\n\n work(options?: AgentRuntimeWorkOptions): Promise<AsyncDisposable> {\n return this.#queue.consume(this.#executor.execute.bind(this.#executor), {\n concurrency: options?.concurrency,\n onOrphaned: this.#onOrphaned.bind(this),\n });\n }\n\n async #onOrphaned(turn: TurnRef, error: string): Promise<void> {\n try {\n let stream = await this.#streams.store.getStream(turn.streamId);\n const firstReconciliation =\n stream?.status === 'queued' || stream?.status === 'running';\n if (firstReconciliation) {\n await this.#streams.store.updateStreamStatus(turn.streamId, 'failed', {\n error,\n });\n stream = await this.#streams.store.getStream(turn.streamId);\n }\n let declaration: AgentDeclaration | undefined;\n if (\n (turn.kind === 'approval' ||\n (turn.kind === 'continuation' && turn.recovery !== 'idempotent')) &&\n stream?.status === 'failed'\n ) {\n try {\n ({ declaration } = await this.#controlPlane.resolve(turn));\n } catch {\n // Default terminal reconciliation below remains the safe fallback.\n }\n }\n if (\n declaration !== undefined &&\n (await this.#approvals.retryIdempotentContinuation(\n turn,\n turn.streamId,\n declaration.tools ?? {},\n ))\n ) {\n return;\n }\n if (\n (turn.kind === 'approval' || turn.kind === 'continuation') &&\n stream?.status === 'completed' &&\n (await this.#approvals.recoverUnstartedContinuation(\n turn,\n turn.streamId,\n ))\n ) {\n return;\n }\n stream = await this.#streams.store.getStream(turn.streamId);\n if (\n (turn.kind === 'approval' || turn.kind === 'continuation') &&\n (stream?.status === 'completed' ||\n stream?.status === 'failed' ||\n stream?.status === 'cancelled')\n ) {\n await this.#approvals.reconcileTerminalContinuation(\n turn,\n turn.streamId,\n stream.status,\n stream.error ?? error,\n );\n }\n const { thread } = await this.#controlPlane.resolve(turn);\n if (\n thread.lastTurnId === undefined ||\n thread.lastTurnId === turn.streamId\n ) {\n await this.#controlPlane.recordLatestTurnIfCurrent(\n turn,\n turn.streamId,\n thread.lastTurnId,\n );\n }\n await this.#controlPlane.projectTerminal(turn, thread);\n } finally {\n try {\n if (turn.kind === 'approval' || turn.kind === 'continuation') {\n await this.#queue.resumeParked(turn.chatId);\n }\n } finally {\n await this.#mailbox.endTurn(turn);\n }\n }\n }\n}\n", "import { v5 as uuidv5 } from 'uuid';\n\nimport type { StreamManager } from '@deepagents/context';\n\nimport type { AgentDeclaration } from '../agent.ts';\nimport type { MailboxCoordinator } from '../mailbox/coordinator.ts';\nimport type { ConversationId, MessageDeliveryMode } from '../mailbox/types.ts';\nimport {\n MessageDeliveryMode as DeliveryMode,\n InterAgentCommunicationType,\n createInterAgentCommunication,\n} from '../mailbox/types.ts';\nimport type { TurnQueue, TurnRef } from '../queue/turn-queue.ts';\nimport { AgentDeclarationRegistry } from './agent-declaration-registry.ts';\nimport { AgentDirectory } from './agent-directory.ts';\nimport { AgentHistoryForker } from './agent-history-forker.ts';\nimport {\n type AgentStatusProjector,\n type ListedAgent,\n} from './agent-status-projector.ts';\nimport type { AgentThread } from './agent-thread.ts';\nimport { AgentTurnId } from './agent-turn-id.ts';\nimport type { ForkTurns } from './fork-turns.ts';\n\nexport interface AgentControlPlaneOptions {\n root: AgentDeclaration;\n streams: StreamManager;\n queue: TurnQueue;\n mailbox: MailboxCoordinator;\n declarations: AgentDeclarationRegistry;\n directory: AgentDirectory;\n statusProjector: AgentStatusProjector;\n historyForker: AgentHistoryForker;\n}\n\nexport interface AgentActor {\n turn: TurnRef;\n thread: AgentThread;\n declaration: AgentDeclaration;\n}\n\nexport interface TurnInput {\n /** Caller-supplied idempotency key; enqueue returns its scoped durable id. */\n id: string;\n input: string;\n}\n\nexport interface SpawnAgentInput {\n agentType: string;\n taskName: string;\n message: string;\n forkTurns: ForkTurns;\n}\n\nexport interface SpawnAgentOutput {\n task_name: string;\n}\n\nexport type {\n ListedAgent,\n ListedAgentStatus,\n} from './agent-status-projector.ts';\n\n/** Application-level coordination for one declared agent tree. */\nexport class AgentControlPlane {\n readonly #root: AgentDeclaration;\n readonly #streams: StreamManager;\n readonly #queue: TurnQueue;\n readonly #mailbox: MailboxCoordinator;\n readonly #declarations: AgentDeclarationRegistry;\n readonly #directory: AgentDirectory;\n readonly #statusProjector: AgentStatusProjector;\n readonly #historyForker: AgentHistoryForker;\n\n constructor(options: AgentControlPlaneOptions) {\n this.#root = options.root;\n this.#streams = options.streams;\n this.#queue = options.queue;\n this.#mailbox = options.mailbox;\n this.#declarations = options.declarations;\n this.#directory = options.directory;\n this.#statusProjector = options.statusProjector;\n this.#historyForker = options.historyForker;\n }\n\n async resolve(conversation: ConversationId): Promise<{\n declaration: AgentDeclaration;\n thread: AgentThread;\n }> {\n const thread = await this.#directory.loadOrCreateRoot(\n conversation,\n this.#root.name,\n );\n const declaration = this.#declarations.get(thread.declarationName);\n if (!declaration) {\n throw new Error(\n `AgentControlPlane.resolve: unknown agent declaration \"${thread.declarationName}\"`,\n );\n }\n return { declaration, thread };\n }\n\n async enqueue(\n conversation: ConversationId,\n turn: TurnInput,\n ): Promise<string> {\n if (!turn.id.trim()) {\n throw new Error(\n 'enqueue: turn id is required \u2014 it names the ask, making retries idempotent',\n );\n }\n await this.#directory.assertOwnerIfExists(conversation);\n const streamId = AgentTurnId.fromRequest(conversation, turn.id).toString();\n await this.#streams.register(streamId);\n await this.#queue.push({\n kind: 'ask',\n streamId,\n chatId: conversation.chatId,\n userId: conversation.userId,\n input: turn.input,\n });\n return streamId;\n }\n\n recordLatestTurn(\n conversation: ConversationId,\n streamId: string,\n ): Promise<AgentThread> {\n return this.#directory.recordLatestTurn(conversation, streamId);\n }\n\n recordLatestTurnIfCurrent(\n conversation: ConversationId,\n streamId: string,\n expectedLastTurnId: string | undefined,\n ): Promise<AgentThread | undefined> {\n return this.#directory.recordLatestTurnIfCurrent(\n conversation,\n streamId,\n expectedLastTurnId,\n );\n }\n\n async spawn(\n actor: AgentActor,\n input: SpawnAgentInput,\n ): Promise<SpawnAgentOutput> {\n const childDeclaration = (actor.declaration.subagents ?? []).find(\n (subagent) => subagent.name === input.agentType,\n );\n if (!childDeclaration) {\n throw new Error(\n `spawn_agent: agent type \"${input.agentType}\" is not a subagent of \"${actor.declaration.name}\"`,\n );\n }\n\n let child: AgentThread;\n try {\n child = await this.#directory.createChild({\n parent: actor.thread,\n taskName: input.taskName,\n declarationName: childDeclaration.name,\n });\n } catch (error) {\n if (error instanceof Error && error.message.startsWith('agent path ')) {\n throw new Error(`spawn_agent: ${error.message}`);\n }\n throw error;\n }\n\n const childPath = child.path.toString();\n const requestId = AgentControlPlane.#initialTurnId(\n child.conversation.chatId,\n );\n const streamId = AgentTurnId.fromRequest(\n child.conversation,\n requestId,\n ).toString();\n const status = await this.#streams.store.getStreamStatus(streamId);\n if (\n status === 'completed' ||\n status === 'failed' ||\n status === 'cancelled'\n ) {\n throw new Error(\n `spawn_agent: agent path \"${childPath}\" already finished with status \"${status}\"`,\n );\n }\n await this.#historyForker.fork(actor.thread, child, input.forkTurns);\n await this.enqueue(child.conversation, {\n id: requestId,\n input: input.message,\n });\n return { task_name: childPath };\n }\n\n async sendMessage(\n actor: AgentActor,\n input: { target: string; message: string },\n ): Promise<{ target: string }> {\n return this.#deliverAgentMessage(actor, input, {\n type: InterAgentCommunicationType.Message,\n mode: DeliveryMode.QueueOnly,\n rejectRoot: false,\n });\n }\n\n async followupTask(\n actor: AgentActor,\n input: { target: string; message: string },\n ): Promise<{ target: string }> {\n return this.#deliverAgentMessage(actor, input, {\n type: InterAgentCommunicationType.NewTask,\n mode: DeliveryMode.TriggerTurn,\n rejectRoot: true,\n });\n }\n\n async listAgents(\n actor: AgentActor,\n pathPrefix?: string,\n ): Promise<{ agents: ListedAgent[] }> {\n const prefix = pathPrefix\n ? actor.thread.path.resolve(pathPrefix)\n : undefined;\n const threads = await this.#directory.listTree(actor.thread);\n const agents = await Promise.all(\n threads.flatMap((thread) => {\n if (prefix && !prefix.contains(thread.path)) return [];\n return [this.#statusProjector.projectListedAgent(actor.turn, thread)];\n }),\n );\n agents.sort((left, right) =>\n left.agent_name.localeCompare(right.agent_name),\n );\n return { agents };\n }\n\n async interruptAgent(\n actor: AgentActor,\n input: { target: string },\n ): Promise<{ previous_status: ListedAgent['agent_status'] }> {\n const target = await this.#directory.find(actor.thread, input.target);\n if (!target) return { previous_status: 'not_found' };\n if (target.path.isRoot) {\n throw new Error('interrupt_agent: the root agent cannot be interrupted');\n }\n if (target.path.equals(actor.thread.path)) {\n throw new Error('interrupt_agent: an agent cannot interrupt itself');\n }\n\n const previous = await this.#statusProjector.projectListedAgent(\n actor.turn,\n target,\n );\n const currentTurn = await this.#queue.getCurrentTurn(target.conversation);\n if (currentTurn) {\n const interruptedThread =\n (await this.#directory.recordLatestTurnIfCurrent(\n target.conversation,\n currentTurn.streamId,\n target.lastTurnId,\n )) ?? target;\n // Stream state is the durable execution authority. Transition it before\n // aborting scheduler delivery so a racing worker observes cancellation,\n // never an orphaned failure.\n await this.#streams.cancel(currentTurn.streamId);\n // Terminal mail has a deterministic id, so retrying this projection is\n // idempotent. Project before destructive queue cleanup: if mailbox\n // delivery fails, the still-discoverable scheduler receipt lets a later\n // interrupt_agent call retry instead of losing FINAL_ANSWER forever.\n await this.#statusProjector.projectTerminal(\n currentTurn,\n interruptedThread,\n );\n await this.#queue.cancel(currentTurn.streamId);\n }\n return { previous_status: previous.agent_status };\n }\n\n waitForMailbox(\n actor: AgentActor,\n options: { timeoutMs: number; signal?: AbortSignal },\n ): Promise<boolean> {\n return this.#mailbox.waitForPending(actor.thread.conversation, options);\n }\n\n async projectTerminal(turn: TurnRef, thread: AgentThread): Promise<void> {\n await this.#statusProjector.projectTerminal(turn, thread);\n }\n\n async #deliverAgentMessage(\n actor: AgentActor,\n input: { target: string; message: string },\n options: {\n type: InterAgentCommunicationType;\n mode: MessageDeliveryMode;\n rejectRoot: boolean;\n },\n ): Promise<{ target: string }> {\n const target = await this.#directory.resolve(actor.thread, input.target);\n if (options.rejectRoot && target.path.isRoot) {\n throw new Error(\n 'followup_task: the root agent cannot receive a follow-up',\n );\n }\n await this.#mailbox.deliver(\n createInterAgentCommunication({\n type: options.type,\n author: actor.thread.conversation,\n recipient: target.conversation,\n content: input.message,\n metadata: {\n authorPath: actor.thread.path.toString(),\n recipientPath: target.path.toString(),\n },\n }),\n options.mode,\n );\n return { target: target.path.toString() };\n }\n\n static #initialTurnId(chatId: string): string {\n return uuidv5(`urn:deepagents:zukhruf:initial-turn:${chatId}`, uuidv5.URL);\n }\n}\n", "import { randomUUID } from 'node:crypto';\n\n/** Durable thread identity; AgentPath is its model-facing address. */\nexport interface ConversationId {\n chatId: string;\n userId: string;\n}\n\nexport const MessageDeliveryMode = {\n QueueOnly: 'queue-only',\n TriggerTurn: 'trigger-turn',\n} as const;\n\nexport type MessageDeliveryMode =\n (typeof MessageDeliveryMode)[keyof typeof MessageDeliveryMode];\n\nexport const InterAgentCommunicationType = {\n Message: 'MESSAGE',\n NewTask: 'NEW_TASK',\n FinalAnswer: 'FINAL_ANSWER',\n} as const;\n\nexport type InterAgentCommunicationType =\n (typeof InterAgentCommunicationType)[keyof typeof InterAgentCommunicationType];\n\n/** A model-visible message sent from one independent agent thread to another. */\nexport interface InterAgentCommunication {\n id: string;\n type: InterAgentCommunicationType;\n author: ConversationId;\n recipient: ConversationId;\n otherRecipients: ConversationId[];\n content: string;\n metadata?: Record<string, unknown>;\n triggerTurn: boolean;\n}\n\nexport type NewInterAgentCommunication = Omit<\n InterAgentCommunication,\n 'id' | 'otherRecipients' | 'triggerTurn' | 'type'\n> & {\n id?: string;\n otherRecipients?: ConversationId[];\n type?: InterAgentCommunicationType;\n};\n\nexport function createInterAgentCommunication(\n communication: NewInterAgentCommunication,\n): InterAgentCommunication {\n const value: InterAgentCommunication = {\n ...communication,\n id: communication.id ?? randomUUID(),\n type: communication.type ?? InterAgentCommunicationType.Message,\n otherRecipients: communication.otherRecipients ?? [],\n triggerTurn: false,\n };\n assertCommunication(value);\n return value;\n}\n\nexport function assertCommunication(\n communication: InterAgentCommunication,\n): void {\n if (!communication.id.trim()) {\n throw new Error('inter-agent communication id cannot be empty');\n }\n if (\n !Object.values(InterAgentCommunicationType).includes(communication.type)\n ) {\n throw new Error('inter-agent communication type is invalid');\n }\n assertConversationId(communication.author, 'author');\n assertConversationId(communication.recipient, 'recipient');\n for (const recipient of communication.otherRecipients) {\n assertConversationId(recipient, 'other recipient');\n }\n if (!communication.content.trim()) {\n throw new Error('inter-agent communication content cannot be empty');\n }\n}\n\nfunction assertConversationId(value: ConversationId, label: string): void {\n if (!value.chatId.trim() || !value.userId.trim()) {\n throw new Error(\n `inter-agent communication ${label} requires chatId and userId`,\n );\n }\n}\n", "import type { AgentDeclaration } from '../agent.ts';\n\n/** Immutable declaration lookup compiled once for one agent runtime. */\nexport class AgentDeclarationRegistry {\n readonly root: AgentDeclaration;\n\n readonly #declarations = new Map<string, AgentDeclaration>();\n\n constructor(root: AgentDeclaration) {\n this.root = root;\n this.#register(root, new Set());\n }\n\n get(name: string): AgentDeclaration | undefined {\n return this.#declarations.get(name);\n }\n\n #register(\n declaration: AgentDeclaration,\n visited: Set<AgentDeclaration>,\n ): void {\n if (visited.has(declaration)) return;\n visited.add(declaration);\n\n if (!declaration.name.trim()) {\n throw new Error('AgentRuntime: agent declaration name cannot be empty');\n }\n if (declaration.name !== declaration.name.trim()) {\n throw new Error(\n `AgentRuntime: agent declaration name \"${declaration.name}\" must not contain surrounding whitespace`,\n );\n }\n\n const existing = this.#declarations.get(declaration.name);\n if (existing && existing !== declaration) {\n throw new Error(\n `AgentRuntime: duplicate agent declaration name \"${declaration.name}\"`,\n );\n }\n this.#declarations.set(declaration.name, declaration);\n\n for (const subagent of declaration.subagents ?? []) {\n this.#register(subagent, visited);\n }\n }\n}\n", "import { v5 as uuidv5 } from 'uuid';\n\nimport type { ContextStore } from '@deepagents/context';\n\nimport type { ConversationId } from '../mailbox/types.ts';\nimport { AgentThread } from './agent-thread.ts';\n\n/** ContextStore-backed directory of durable agent instances. */\nexport class AgentDirectory {\n readonly #store: ContextStore;\n\n constructor(store: ContextStore) {\n this.#store = store;\n }\n\n async assertOwnerIfExists(conversation: ConversationId): Promise<void> {\n const chat = await this.#store.getChat(conversation.chatId);\n if (!chat) return;\n this.#assertOwner(conversation, chat.userId);\n const thread = this.#threadFromMetadata(conversation, chat.metadata);\n if (thread) await this.#assertValidParent(thread);\n }\n\n async load(conversation: ConversationId): Promise<AgentThread | undefined> {\n const chat = await this.#store.getChat(conversation.chatId);\n if (chat) this.#assertOwner(conversation, chat.userId);\n if (!chat) return undefined;\n const thread = this.#threadFromMetadata(conversation, chat.metadata);\n if (thread) await this.#assertValidParent(thread);\n return thread;\n }\n\n async loadOrCreateRoot(\n conversation: ConversationId,\n declarationName: string,\n ): Promise<AgentThread> {\n await this.#store.upsertChat({\n id: conversation.chatId,\n userId: conversation.userId,\n });\n let thread!: AgentThread;\n let adopted = false;\n await this.#store.updateChat(conversation.chatId, (chat) => {\n this.#assertOwner(conversation, chat.userId);\n const existing = this.#threadFromMetadata(conversation, chat.metadata);\n if (existing) {\n thread = existing;\n adopted = true;\n return undefined;\n }\n thread = AgentThread.root(conversation, declarationName);\n adopted = false;\n return { metadata: thread.toMetadata(chat.metadata) };\n });\n if (adopted) {\n await this.#assertValidParent(thread);\n }\n return thread;\n }\n\n async recordLatestTurn(\n conversation: ConversationId,\n streamId: string,\n ): Promise<AgentThread> {\n return this.#updateLatestTurn(conversation, streamId);\n }\n\n async recordLatestTurnIfCurrent(\n conversation: ConversationId,\n streamId: string,\n expectedLastTurnId: string | undefined,\n ): Promise<AgentThread | undefined> {\n return this.#updateLatestTurn(conversation, streamId, expectedLastTurnId);\n }\n\n async listTree(thread: AgentThread): Promise<AgentThread[]> {\n const chats = await this.#store.listChats({\n userId: thread.conversation.userId,\n metadata: AgentThread.metadataFilter(thread.treeId),\n });\n return Promise.all(\n chats.map(async (chat) => {\n const conversation = { chatId: chat.id, userId: chat.userId };\n const member = this.#threadFromMetadata(conversation, chat.metadata);\n if (!member) {\n throw new Error(\n `AgentDirectory.listTree: chat \"${chat.id}\" is missing Zukhruf metadata`,\n );\n }\n await this.#assertValidParent(member);\n return member;\n }),\n );\n }\n\n async resolve(thread: AgentThread, target: string): Promise<AgentThread> {\n const path = thread.path.resolve(target);\n const match = await this.find(thread, target);\n if (match) return match;\n throw new Error(`agent path \"${path}\" does not exist in this tree`);\n }\n\n async find(\n thread: AgentThread,\n target: string,\n ): Promise<AgentThread | undefined> {\n const path = thread.path.resolve(target);\n return (await this.listTree(thread)).find((candidate) =>\n candidate.path.equals(path),\n );\n }\n\n async createChild(options: {\n parent: AgentThread;\n taskName: string;\n declarationName: string;\n }): Promise<AgentThread> {\n const path = options.parent.path.resolve(options.taskName);\n const pathString = path.toString();\n const conversation = {\n chatId: AgentDirectory.#childChatId(\n options.parent.conversation.userId,\n options.parent.treeId,\n pathString,\n ),\n userId: options.parent.conversation.userId,\n };\n const occupied = (await this.listTree(options.parent)).find((thread) =>\n thread.path.equals(path),\n );\n if (occupied && occupied.conversation.chatId !== conversation.chatId) {\n throw new Error(`agent path \"${pathString}\" already exists`);\n }\n\n const child = new AgentThread({\n conversation,\n treeId: options.parent.treeId,\n path,\n parentChatId: options.parent.conversation.chatId,\n declarationName: options.declarationName,\n });\n const storedChat = await this.#store.upsertChat({\n id: conversation.chatId,\n userId: conversation.userId,\n metadata: child.toMetadata(undefined),\n });\n const stored = AgentThread.fromMetadata(\n { chatId: storedChat.id, userId: storedChat.userId },\n storedChat.metadata,\n );\n if (\n storedChat.userId !== conversation.userId ||\n stored?.treeId !== child.treeId ||\n !stored.path.equals(child.path) ||\n stored.parentChatId !== child.parentChatId ||\n stored.declarationName !== child.declarationName\n ) {\n throw new Error(`agent path \"${pathString}\" already exists`);\n }\n return stored;\n }\n\n static #childChatId(userId: string, treeId: string, path: string): string {\n return uuidv5(\n `urn:deepagents:zukhruf:agent:${JSON.stringify([userId, treeId, path])}`,\n uuidv5.URL,\n );\n }\n\n #assertOwner(conversation: ConversationId, storedUserId: string): void {\n if (storedUserId === conversation.userId) return;\n throw new Error(\n `chat \"${conversation.chatId}\" belongs to user \"${storedUserId}\", not \"${conversation.userId}\"`,\n );\n }\n\n #threadFromMetadata(\n conversation: ConversationId,\n metadata: Record<string, unknown> | undefined,\n ): AgentThread | undefined {\n const thread = AgentThread.fromMetadata(conversation, metadata);\n if (!thread && AgentThread.hasReservedMetadata(metadata)) {\n throw new Error(\n `invalid Zukhruf metadata for chat \"${conversation.chatId}\"`,\n );\n }\n return thread;\n }\n\n async #assertValidParent(thread: AgentThread): Promise<void> {\n if (thread.path.isRoot) return;\n const parentChatId = thread.parentChatId;\n if (!parentChatId) {\n throw new Error(\n `invalid Zukhruf parent for chat \"${thread.conversation.chatId}\"`,\n );\n }\n const parentChat = await this.#store.getChat(parentChatId);\n if (!parentChat || parentChat.userId !== thread.conversation.userId) {\n throw new Error(\n `invalid Zukhruf parent for chat \"${thread.conversation.chatId}\"`,\n );\n }\n const parent = this.#threadFromMetadata(\n { chatId: parentChat.id, userId: parentChat.userId },\n parentChat.metadata,\n );\n const expectedPath = thread.path.parent;\n if (\n !parent ||\n !expectedPath ||\n parent.treeId !== thread.treeId ||\n !parent.path.equals(expectedPath)\n ) {\n throw new Error(\n `invalid Zukhruf parent for chat \"${thread.conversation.chatId}\"`,\n );\n }\n }\n\n async #updateLatestTurn(\n conversation: ConversationId,\n streamId: string,\n expectedLastTurnId?: string,\n ): Promise<AgentThread>;\n async #updateLatestTurn(\n conversation: ConversationId,\n streamId: string,\n expectedLastTurnId: string | undefined,\n ): Promise<AgentThread | undefined>;\n async #updateLatestTurn(\n conversation: ConversationId,\n streamId: string,\n ...expected: [string | undefined] | []\n ): Promise<AgentThread | undefined> {\n let result: AgentThread | undefined;\n await this.#store.updateChat(conversation.chatId, (chat) => {\n this.#assertOwner(conversation, chat.userId);\n const thread = this.#threadFromMetadata(conversation, chat.metadata);\n if (!thread) {\n throw new Error(\n `AgentDirectory.recordLatestTurn: missing agent metadata for chat \"${conversation.chatId}\"`,\n );\n }\n if (expected.length > 0 && thread.lastTurnId !== expected[0]) {\n result = undefined;\n return undefined;\n }\n if (thread.lastTurnId === streamId) {\n result = thread;\n return undefined;\n }\n result = thread.withLatestTurn(streamId);\n return { metadata: result.toMetadata(chat.metadata) };\n });\n return result;\n }\n}\n", "import { type UIMessage, validateUIMessages } from 'ai';\nimport { v5 as uuidv5 } from 'uuid';\n\nimport {\n type ContextStore,\n type MessageData,\n isSyntheticReminderMessage,\n} from '@deepagents/context';\n\nimport type { AgentThread } from './agent-thread.ts';\nimport type { ForkTurns } from './fork-turns.ts';\n\ninterface HistoryForkRecord {\n forkTurns: ForkTurns;\n parentChatId: string;\n parentHeadMessageId: string | null;\n sourceMessageIds?: string[];\n}\n\ninterface SourceMessage {\n stored: MessageData;\n message: UIMessage;\n}\n\n/** Copies a stable, filtered parent-history snapshot into a new child chat. */\nexport class AgentHistoryForker {\n readonly #store: ContextStore;\n\n constructor(store: ContextStore) {\n this.#store = store;\n }\n\n async fork(\n parent: AgentThread,\n child: AgentThread,\n forkTurns: ForkTurns,\n ): Promise<void> {\n const record = await this.#claim(parent, child, forkTurns);\n if (record.forkTurns === 'none' || record.parentHeadMessageId === null) {\n return;\n }\n\n const selected = await this.#selectedMessages(parent, child, record);\n if (selected.length === 0) return;\n\n const cloned = this.#cloneMessages(child, selected);\n const expectedIds = cloned.map((message) => message.id);\n const branch = await this.#store.getActiveBranch(child.conversation.chatId);\n if (!branch) {\n throw new Error(\n `spawn_agent: child chat \"${child.conversation.chatId}\" has no active branch`,\n );\n }\n if (branch.headMessageId !== null) {\n if (await this.#hasForkedPrefix(child, expectedIds)) return;\n throw new Error(\n `spawn_agent: cannot apply parent history after child \"${child.path}\" has started`,\n );\n }\n\n const head = cloned.at(-1);\n if (!head) return;\n await this.#store.addMessages(cloned);\n const committed = await this.#store.updateBranchHead(\n branch.id,\n head.id,\n null,\n );\n if (!committed && !(await this.#hasForkedPrefix(child, expectedIds))) {\n throw new Error(\n `spawn_agent: child \"${child.path}\" started before parent history was applied`,\n );\n }\n if (!(await this.#hasForkedPrefix(child, expectedIds))) {\n throw new Error(\n `spawn_agent: failed to persist parent history for child \"${child.path}\"`,\n );\n }\n }\n\n async #claim(\n parent: AgentThread,\n child: AgentThread,\n forkTurns: ForkTurns,\n ): Promise<HistoryForkRecord> {\n const parentBranch = await this.#store.getActiveBranch(\n parent.conversation.chatId,\n );\n if (!parentBranch) {\n throw new Error(\n `spawn_agent: parent chat \"${parent.conversation.chatId}\" has no active branch`,\n );\n }\n const proposed: HistoryForkRecord = {\n forkTurns,\n parentChatId: parent.conversation.chatId,\n parentHeadMessageId:\n forkTurns === 'none' ? null : parentBranch.headMessageId,\n };\n let claimed: HistoryForkRecord | undefined;\n\n await this.#store.updateChat(child.conversation.chatId, (chat) => {\n const metadata = chat.metadata;\n const zukhruf = metadata?.zukhruf;\n if (!isRecord(zukhruf)) {\n throw new Error(\n `spawn_agent: child chat \"${child.conversation.chatId}\" is missing Zukhruf metadata`,\n );\n }\n\n if (zukhruf.historyFork !== undefined) {\n claimed = parseHistoryForkRecord(zukhruf.historyFork);\n if (\n claimed.parentChatId !== proposed.parentChatId ||\n claimed.forkTurns !== proposed.forkTurns\n ) {\n throw new Error(\n `spawn_agent: agent path \"${child.path}\" already exists with a different fork_turns setting`,\n );\n }\n return undefined;\n }\n\n claimed = proposed;\n return {\n metadata: {\n ...metadata,\n zukhruf: { ...zukhruf, historyFork: proposed },\n },\n };\n });\n\n if (!claimed) {\n throw new Error(\n `spawn_agent: failed to claim history for child \"${child.path}\"`,\n );\n }\n return claimed;\n }\n\n async #sourceMessages(\n parent: AgentThread,\n record: HistoryForkRecord,\n ): Promise<SourceMessage[]> {\n const headId = record.parentHeadMessageId;\n if (headId === null) return [];\n\n const chain = await this.#store.getMessageChain(headId);\n if (chain.at(-1)?.id !== headId) {\n throw new Error(\n `spawn_agent: parent history head \"${headId}\" is unavailable`,\n );\n }\n if (\n chain.some((message) => message.chatId !== parent.conversation.chatId)\n ) {\n throw new Error('spawn_agent: parent history crosses chat boundaries');\n }\n\n const materialized = chain.filter(\n (message) => !isEmptyAssistantPlaceholder(message.data),\n );\n const messages = await validateUIMessages({\n messages: materialized.map((message) => message.data),\n });\n return materialized.map((stored, index) => {\n const message = messages[index];\n if (message.id !== stored.id) {\n throw new Error(\n `spawn_agent: stored message \"${stored.id}\" has a mismatched payload id`,\n );\n }\n return { stored, message };\n });\n }\n\n async #selectedMessages(\n parent: AgentThread,\n child: AgentThread,\n record: HistoryForkRecord,\n ): Promise<SourceMessage[]> {\n if (record.forkTurns === 'none') return [];\n if (record.sourceMessageIds !== undefined) {\n return this.#messagesById(parent, record.sourceMessageIds);\n }\n\n const source = await this.#sourceMessages(parent, record);\n const selected = this.#select(source, record.forkTurns)\n .map((entry) => this.#keepHistoryMessage(entry))\n .filter((entry): entry is SourceMessage => entry !== undefined);\n const sourceMessageIds = await this.#claimSelection(\n child,\n selected.map(({ stored }) => stored.id),\n );\n return arraysEqual(\n sourceMessageIds,\n selected.map(({ stored }) => stored.id),\n )\n ? selected\n : this.#messagesById(parent, sourceMessageIds);\n }\n\n async #messagesById(\n parent: AgentThread,\n sourceMessageIds: string[],\n ): Promise<SourceMessage[]> {\n const storedMessages = await Promise.all(\n sourceMessageIds.map((id) => this.#store.getMessage(id)),\n );\n if (\n storedMessages.some(\n (message) =>\n message === undefined ||\n message.chatId !== parent.conversation.chatId,\n )\n ) {\n throw new Error(\n 'spawn_agent: persisted parent-history snapshot is unavailable',\n );\n }\n const stored = storedMessages as MessageData[];\n const messages = await validateUIMessages({\n messages: stored.map((message) => message.data),\n });\n return stored.map((messageData, index) => {\n const source = this.#keepHistoryMessage({\n stored: messageData,\n message: messages[index],\n });\n if (!source || source.message.id !== messageData.id) {\n throw new Error(\n `spawn_agent: persisted parent-history message \"${messageData.id}\" changed shape`,\n );\n }\n return source;\n });\n }\n\n async #claimSelection(\n child: AgentThread,\n proposedIds: string[],\n ): Promise<string[]> {\n let sourceMessageIds: string[] | undefined;\n await this.#store.updateChat(child.conversation.chatId, (chat) => {\n const metadata = chat.metadata;\n const zukhruf = metadata?.zukhruf;\n if (!isRecord(zukhruf)) {\n throw new Error(\n `spawn_agent: child chat \"${child.conversation.chatId}\" is missing Zukhruf metadata`,\n );\n }\n const record = parseHistoryForkRecord(zukhruf.historyFork);\n if (record.sourceMessageIds !== undefined) {\n sourceMessageIds = record.sourceMessageIds;\n return undefined;\n }\n\n sourceMessageIds = proposedIds;\n return {\n metadata: {\n ...metadata,\n zukhruf: {\n ...zukhruf,\n historyFork: { ...record, sourceMessageIds: proposedIds },\n },\n },\n };\n });\n if (!sourceMessageIds) {\n throw new Error(\n `spawn_agent: failed to claim parent-history messages for child \"${child.path}\"`,\n );\n }\n return sourceMessageIds;\n }\n\n #select(source: SourceMessage[], forkTurns: Exclude<ForkTurns, 'none'>) {\n if (forkTurns === 'all') return source;\n\n const boundaries = source.flatMap((entry, index) =>\n isForkTurnBoundary(entry.message) ? [index] : [],\n );\n const start = boundaries.at(-forkTurns) ?? boundaries[0];\n return start === undefined ? [] : source.slice(start);\n }\n\n #keepHistoryMessage(entry: SourceMessage): SourceMessage | undefined {\n const { message } = entry;\n if (message.role === 'user') {\n if (\n isSyntheticReminderMessage(message) ||\n interAgentCommunication(message) !== undefined\n ) {\n return undefined;\n }\n return entry;\n }\n if (message.role !== 'assistant') return undefined;\n\n const finalStepStart = message.parts.findLastIndex(\n (part) => part.type === 'step-start',\n );\n const parts = message.parts\n .slice(finalStepStart + 1)\n .filter((part) =>\n ['text', 'file', 'source-url', 'source-document'].includes(part.type),\n );\n return parts.length === 0\n ? undefined\n : { ...entry, message: { ...message, parts } };\n }\n\n #cloneMessages(child: AgentThread, selected: SourceMessage[]): MessageData[] {\n let parentId: string | null = null;\n return selected.map(({ stored, message }) => {\n const id = uuidv5(\n `urn:deepagents:zukhruf:forked-message:${JSON.stringify([\n child.conversation.chatId,\n stored.id,\n ])}`,\n uuidv5.URL,\n );\n const clone: MessageData = {\n id,\n chatId: child.conversation.chatId,\n parentId,\n name: message.role,\n type: 'message',\n data: { ...message, id },\n createdAt: stored.createdAt,\n };\n parentId = id;\n return clone;\n });\n }\n\n async #hasForkedPrefix(\n child: AgentThread,\n expectedIds: string[],\n ): Promise<boolean> {\n const branch = await this.#store.getActiveBranch(child.conversation.chatId);\n if (!branch?.headMessageId) return false;\n const chain = await this.#store.getMessageChain(branch.headMessageId);\n return expectedIds.every(\n (id, index) =>\n chain[index]?.id === id &&\n chain[index]?.chatId === child.conversation.chatId,\n );\n }\n}\n\nfunction isForkTurnBoundary(message: UIMessage): boolean {\n if (message.role !== 'user' || isSyntheticReminderMessage(message)) {\n return false;\n }\n return interAgentCommunication(message)?.triggerTurn ?? true;\n}\n\nfunction interAgentCommunication(\n message: UIMessage,\n): { triggerTurn: boolean } | undefined {\n if (!isRecord(message.metadata)) return undefined;\n if (!Object.hasOwn(message.metadata, 'interAgentCommunication')) {\n return undefined;\n }\n const communication = message.metadata.interAgentCommunication;\n if (\n !isRecord(communication) ||\n typeof communication.triggerTurn !== 'boolean'\n ) {\n throw new Error(\n `spawn_agent: message \"${message.id}\" has invalid inter-agent metadata`,\n );\n }\n return { triggerTurn: communication.triggerTurn };\n}\n\nfunction parseHistoryForkRecord(value: unknown): HistoryForkRecord {\n if (!isRecord(value)) {\n throw new Error('spawn_agent: invalid persisted history-fork metadata');\n }\n const { forkTurns, parentChatId, parentHeadMessageId, sourceMessageIds } =\n value;\n if (\n !isForkTurns(forkTurns) ||\n typeof parentChatId !== 'string' ||\n !parentChatId.trim() ||\n (parentHeadMessageId !== null &&\n (typeof parentHeadMessageId !== 'string' ||\n parentHeadMessageId.length === 0)) ||\n (sourceMessageIds !== undefined &&\n (!Array.isArray(sourceMessageIds) ||\n !sourceMessageIds.every(\n (id): id is string => typeof id === 'string' && id.trim().length > 0,\n ) ||\n new Set(sourceMessageIds).size !== sourceMessageIds.length))\n ) {\n throw new Error('spawn_agent: invalid persisted history-fork metadata');\n }\n return {\n forkTurns,\n parentChatId,\n parentHeadMessageId,\n ...(sourceMessageIds === undefined ? {} : { sourceMessageIds }),\n };\n}\n\nfunction isForkTurns(value: unknown): value is ForkTurns {\n return (\n value === 'none' ||\n value === 'all' ||\n (typeof value === 'number' && Number.isSafeInteger(value) && value > 0)\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isEmptyAssistantPlaceholder(value: unknown): boolean {\n return (\n isRecord(value) &&\n typeof value.id === 'string' &&\n value.role === 'assistant' &&\n Array.isArray(value.parts) &&\n value.parts.length === 0\n );\n}\n\nfunction arraysEqual(left: string[], right: string[]): boolean {\n return (\n left.length === right.length &&\n left.every((value, index) => value === right[index])\n );\n}\n", "import { type UIMessage, isTextUIPart } from 'ai';\nimport { z } from 'zod';\n\nimport {\n ContextEngine,\n type ContextStore,\n type StreamManager,\n type StreamStatus,\n} from '@deepagents/context';\n\nimport type { MailboxCoordinator } from '../mailbox/coordinator.ts';\nimport {\n InterAgentCommunicationType,\n MessageDeliveryMode,\n createInterAgentCommunication,\n} from '../mailbox/types.ts';\nimport type { TurnQueue, TurnRef } from '../queue/turn-queue.ts';\nimport type { ApprovalController } from '../runtime/approval-controller.ts';\nimport type { AgentDirectory } from './agent-directory.ts';\nimport type { AgentThread } from './agent-thread.ts';\n\nexport const listedAgentStatusSchema = z.union([\n z.enum(['pending_init', 'running', 'interrupted', 'shutdown', 'not_found']),\n z.object({ completed: z.string().nullable() }).strict(),\n z.object({ errored: z.string() }).strict(),\n]);\n\nexport type ListedAgentStatus = z.infer<typeof listedAgentStatusSchema>;\n\nexport const listedAgentSchema = z\n .object({\n agent_name: z.string(),\n agent_status: listedAgentStatusSchema,\n })\n .strict();\n\nexport type ListedAgent = z.infer<typeof listedAgentSchema>;\n\nexport interface AgentStatusProjectorOptions {\n store: ContextStore;\n streams: StreamManager;\n queue: TurnQueue;\n mailbox: MailboxCoordinator;\n directory: AgentDirectory;\n approvals: ApprovalController;\n}\n\n/** Projects durable execution state into agent-facing status and terminal mail. */\nexport class AgentStatusProjector {\n readonly #store: ContextStore;\n readonly #streams: StreamManager;\n readonly #queue: TurnQueue;\n readonly #mailbox: MailboxCoordinator;\n readonly #directory: AgentDirectory;\n readonly #approvals: ApprovalController;\n\n constructor(options: AgentStatusProjectorOptions) {\n this.#store = options.store;\n this.#streams = options.streams;\n this.#queue = options.queue;\n this.#mailbox = options.mailbox;\n this.#directory = options.directory;\n this.#approvals = options.approvals;\n }\n\n async projectListedAgent(\n currentTurn: TurnRef,\n thread: AgentThread,\n ): Promise<ListedAgent> {\n const messages = await this.#messages(thread);\n const head = messages.at(-1);\n const streamId =\n thread.lastTurnId ?? (head?.role === 'assistant' ? head.id : undefined);\n const stream = streamId\n ? await this.#streams.store.getStream(streamId)\n : undefined;\n const scheduledTurn = await this.#queue.getCurrentTurn(thread.conversation);\n const scheduledStream = scheduledTurn\n ? await this.#streams.store.getStream(scheduledTurn.streamId)\n : undefined;\n let status = AgentStatusProjector.#listedStatus(\n stream?.status,\n stream?.error,\n head,\n );\n if (stream?.status === 'completed' && this.#approvals.isPaused(head)) {\n status = 'running';\n }\n if (\n thread.conversation.chatId === currentTurn.chatId ||\n (thread.lastTurnId !== undefined &&\n scheduledTurn?.streamId !== thread.lastTurnId &&\n (scheduledStream?.status === 'queued' ||\n scheduledStream?.status === 'running'))\n ) {\n status = 'running';\n }\n\n return {\n agent_name: thread.path.toString(),\n agent_status: status,\n };\n }\n\n async projectTerminal(turn: TurnRef, thread: AgentThread): Promise<void> {\n if (thread.parentChatId === null) return;\n const stream = await this.#streams.store.getStream(turn.streamId);\n if (\n !stream ||\n (stream.status !== 'completed' &&\n stream.status !== 'failed' &&\n stream.status !== 'cancelled')\n ) {\n return;\n }\n\n const message = (await this.#messages(thread)).find(\n (candidate) =>\n candidate.role === 'assistant' && candidate.id === turn.streamId,\n );\n if (stream.status === 'completed' && this.#approvals.isPaused(message)) {\n return;\n }\n const text =\n message?.role === 'assistant'\n ? AgentStatusProjector.#messageText(message)\n : '';\n let content = text || 'Agent completed without a text response.';\n if (stream.status === 'failed') {\n content = `Agent failed: ${stream.error || 'unknown error'}`;\n } else if (stream.status === 'cancelled') {\n content = 'Agent was interrupted.';\n }\n const parent = await this.#directory.load({\n chatId: thread.parentChatId,\n userId: thread.conversation.userId,\n });\n\n await this.#mailbox.deliver(\n createInterAgentCommunication({\n id: `zukhruf:child-terminal:${turn.streamId}`,\n type: InterAgentCommunicationType.FinalAnswer,\n author: thread.conversation,\n recipient: {\n chatId: thread.parentChatId,\n userId: thread.conversation.userId,\n },\n content,\n metadata: {\n authorPath: thread.path.toString(),\n recipientPath: parent?.path.toString() ?? thread.parentChatId,\n streamId: turn.streamId,\n status: stream.status,\n },\n }),\n MessageDeliveryMode.QueueOnly,\n );\n }\n\n async #messages(thread: AgentThread): Promise<UIMessage[]> {\n const engine = new ContextEngine({\n store: this.#store,\n chatId: thread.conversation.chatId,\n userId: thread.conversation.userId,\n });\n return engine.getMessages();\n }\n\n static #listedStatus(\n status: StreamStatus | undefined,\n error: string | null | undefined,\n head: UIMessage | undefined,\n ): ListedAgentStatus {\n switch (status) {\n case 'running':\n return 'running';\n case 'completed':\n return {\n completed:\n head?.role === 'assistant'\n ? AgentStatusProjector.#messageText(head) || null\n : null,\n };\n case 'failed':\n return { errored: error || 'Agent turn failed.' };\n case 'cancelled':\n return 'interrupted';\n case 'queued':\n case undefined:\n return 'pending_init';\n }\n }\n\n static #messageText(message: UIMessage): string {\n return message.parts\n .filter(isTextUIPart)\n .map((part) => part.text)\n .join('\\n')\n .trim();\n }\n}\n", "import { v5 as uuidv5 } from 'uuid';\n\nimport type { ConversationId } from '../mailbox/types.ts';\n\n/** Conversation-scoped durable identity for one caller-supplied turn key. */\nexport class AgentTurnId {\n static readonly #prefix = 'zukhruf-turn';\n readonly #value: string;\n\n private constructor(value: string) {\n this.#value = value;\n }\n\n static fromRequest(\n conversation: ConversationId,\n requestId: string,\n ): AgentTurnId {\n if (!requestId.trim()) {\n throw new Error('turn id cannot be empty');\n }\n const scope = conversationNamespace(conversation);\n return new AgentTurnId(\n `${AgentTurnId.#prefix}:${scope}:${uuidv5(requestId, scope)}`,\n );\n }\n\n static random(conversation: ConversationId): AgentTurnId {\n return AgentTurnId.fromRequest(conversation, crypto.randomUUID());\n }\n\n static assertOwner(conversation: ConversationId, streamId: string): void {\n const expectedPrefix = `${AgentTurnId.#prefix}:${conversationNamespace(conversation)}:`;\n if (!streamId.startsWith(expectedPrefix)) {\n throw new Error(\n `stream \"${streamId}\" does not belong to conversation \"${conversation.chatId}\"`,\n );\n }\n }\n\n toString(): string {\n return this.#value;\n }\n}\n\nexport function conversationNamespace(conversation: ConversationId): string {\n if (!conversation.chatId.trim() || !conversation.userId.trim()) {\n throw new Error('conversation requires non-empty chatId and userId');\n }\n return uuidv5(\n JSON.stringify([conversation.userId, conversation.chatId]),\n uuidv5.URL,\n );\n}\n", "import { setTimeout as delay } from 'node:timers/promises';\n\nimport type { StreamManager } from '@deepagents/context';\n\nimport { AgentTurnId } from '../control-plane/agent-turn-id.ts';\nimport type { TurnQueue, TurnRef } from '../queue/turn-queue.ts';\nimport type { MailboxStore } from './store.ts';\nimport {\n type ConversationId,\n MessageDeliveryMode as DeliveryMode,\n type InterAgentCommunication,\n InterAgentCommunicationType,\n type MessageDeliveryMode,\n assertCommunication,\n} from './types.ts';\n\nexport interface MailboxCoordinatorOptions {\n store: MailboxStore;\n queue: Pick<TurnQueue, 'push'>;\n streams: StreamManager;\n}\n\nconst WAIT_POLL_INTERVAL_MS = 50;\n\n/** Owns durable mail delivery and the serialized turns that wake recipients. */\nexport class MailboxCoordinator {\n readonly #store: MailboxStore;\n readonly #queue: Pick<TurnQueue, 'push'>;\n readonly #streams: StreamManager;\n readonly #wakeRequests = new Map<string, Promise<void>>();\n\n constructor(options: MailboxCoordinatorOptions) {\n this.#store = options.store;\n this.#queue = options.queue;\n this.#streams = options.streams;\n }\n\n async deliver(\n communication: InterAgentCommunication,\n mode: MessageDeliveryMode,\n ): Promise<void> {\n const delivered = {\n ...communication,\n type:\n mode === DeliveryMode.TriggerTurn\n ? InterAgentCommunicationType.NewTask\n : communication.type,\n triggerTurn: mode === DeliveryMode.TriggerTurn,\n };\n assertCommunication(delivered);\n\n const { recipientActive } = await this.#store.enqueue(delivered);\n if (delivered.triggerTurn || recipientActive) {\n // Queue-only mail sent during an active turn gets a serialized fallback\n // in case sampling has already crossed its final safe drain boundary.\n await this.#scheduleWake(delivered.recipient);\n }\n }\n\n beginTurn(turn: TurnRef): Promise<void> {\n return this.#store.beginTurn(turn, turn.streamId);\n }\n\n async endTurn(\n turn: TurnRef,\n options: { parked?: boolean } = {},\n ): Promise<void> {\n const { hasPending, turnEnded } = await this.#store.endTurn(\n turn,\n turn.streamId,\n );\n if (turnEnded && hasPending && !options.parked) {\n await this.#scheduleWake(turn);\n }\n }\n\n drainLeadingQueueOnly(\n recipient: ConversationId,\n ): Promise<InterAgentCommunication[]> {\n return this.#store.drainLeadingQueueOnly(recipient);\n }\n\n drain(recipient: ConversationId): Promise<InterAgentCommunication[]> {\n return this.#store.drain(recipient);\n }\n\n async waitForPending(\n recipient: ConversationId,\n options: { timeoutMs: number; signal?: AbortSignal },\n ): Promise<boolean> {\n const deadline = Date.now() + options.timeoutMs;\n while (true) {\n options.signal?.throwIfAborted();\n if (await this.#store.hasPending(recipient)) return true;\n const remaining = deadline - Date.now();\n if (remaining <= 0) return false;\n await delay(Math.min(WAIT_POLL_INTERVAL_MS, remaining), undefined, {\n signal: options.signal,\n });\n }\n }\n\n #scheduleWake(target: ConversationId): Promise<void> {\n const key = this.#conversationKey(target);\n const existing = this.#wakeRequests.get(key);\n if (existing) return existing;\n\n // This map coalesces only concurrent requests in this process. A fulfilled\n // request is removed because another process may consume the wake.\n const request = (async () => {\n const wakeId = AgentTurnId.random(target).toString();\n await this.#streams.register(wakeId);\n try {\n await this.#queue.push({\n kind: 'mailbox',\n streamId: wakeId,\n chatId: target.chatId,\n userId: target.userId,\n } satisfies TurnRef);\n } catch (error) {\n await this.#streams.store.updateStreamStatus(wakeId, 'failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n })();\n this.#wakeRequests.set(key, request);\n\n const clearRequest = () => {\n if (this.#wakeRequests.get(key) === request) {\n this.#wakeRequests.delete(key);\n }\n };\n void request.then(clearRequest, clearRequest);\n return request;\n }\n\n #conversationKey(conversation: ConversationId): string {\n return JSON.stringify([conversation.chatId, conversation.userId]);\n }\n}\n", "const DEFAULT_MIN_WAIT_TIMEOUT_MS = 10_000;\nconst DEFAULT_WAIT_TIMEOUT_MS = 30_000;\nconst DEFAULT_MAX_WAIT_TIMEOUT_MS = 3_600_000;\n\nconst RESERVED_TOOL_NAMESPACES = new Set([\n 'api_tool',\n 'browser',\n 'computer',\n 'container',\n 'file_search',\n 'functions',\n 'image_gen',\n 'multi_tool_use',\n 'python',\n 'python_user_visible',\n 'submodel_delegator',\n 'terminal',\n 'tool_search',\n 'web',\n]);\n\n/** Host-level controls matching Codex MultiAgentV2 configuration. */\nexport interface MultiAgentV2HostConfig {\n minWaitTimeoutMs?: number;\n defaultWaitTimeoutMs?: number;\n maxWaitTimeoutMs?: number;\n /** Additional guidance appended to the spawn_agent tool description. */\n usageHintText?: string;\n /** Complete root guidance override. An empty string disables the hint. */\n rootAgentUsageHintText?: string;\n /** Complete child guidance override. An empty string disables the hint. */\n subagentUsageHintText?: string;\n /** Native OpenAI Responses namespace for the six collaboration tools. */\n toolNamespace?: string;\n /**\n * Keeps collaboration tools on the direct model surface instead of a nested\n * code-mode executor. Defaults to true. Zukhruf currently rejects false\n * because it has no nested code-mode executor in which to expose the tools.\n */\n nonCodeModeOnly?: boolean;\n}\n\nexport interface ResolvedMultiAgentV2HostConfig {\n minWaitTimeoutMs: number;\n defaultWaitTimeoutMs: number;\n maxWaitTimeoutMs: number;\n usageHintText?: string;\n rootAgentUsageHintText?: string;\n subagentUsageHintText?: string;\n toolNamespace?: string;\n nonCodeModeOnly: boolean;\n}\n\nexport function resolveMultiAgentV2HostConfig(\n input: MultiAgentV2HostConfig = {},\n): ResolvedMultiAgentV2HostConfig {\n const minWaitTimeoutMs =\n input.minWaitTimeoutMs ?? DEFAULT_MIN_WAIT_TIMEOUT_MS;\n const defaultWaitTimeoutMs =\n input.defaultWaitTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;\n const maxWaitTimeoutMs =\n input.maxWaitTimeoutMs ?? DEFAULT_MAX_WAIT_TIMEOUT_MS;\n assertTimeout('minWaitTimeoutMs', minWaitTimeoutMs);\n assertTimeout('defaultWaitTimeoutMs', defaultWaitTimeoutMs);\n assertTimeout('maxWaitTimeoutMs', maxWaitTimeoutMs);\n if (minWaitTimeoutMs > maxWaitTimeoutMs) {\n throw new Error(\n 'AgentRuntime: multiAgentV2.minWaitTimeoutMs must be at most maxWaitTimeoutMs',\n );\n }\n if (defaultWaitTimeoutMs < minWaitTimeoutMs) {\n throw new Error(\n 'AgentRuntime: multiAgentV2.defaultWaitTimeoutMs must be at least minWaitTimeoutMs',\n );\n }\n if (defaultWaitTimeoutMs > maxWaitTimeoutMs) {\n throw new Error(\n 'AgentRuntime: multiAgentV2.defaultWaitTimeoutMs must be at most maxWaitTimeoutMs',\n );\n }\n\n const toolNamespace = input.toolNamespace;\n if (\n toolNamespace !== undefined &&\n (toolNamespace.length === 0 || toolNamespace.trim() !== toolNamespace)\n ) {\n throw new Error(\n 'AgentRuntime: multiAgentV2.toolNamespace cannot be empty or padded',\n );\n }\n if (toolNamespace !== undefined) validateToolNamespace(toolNamespace);\n\n const nonCodeModeOnly = input.nonCodeModeOnly ?? true;\n if (!nonCodeModeOnly) {\n throw new Error(\n 'AgentRuntime: multiAgentV2.nonCodeModeOnly=false requires a nested code-mode executor, which Zukhruf does not provide',\n );\n }\n const tool = (name: string) =>\n toolNamespace === undefined ? name : `${toolNamespace}.${name}`;\n const collaborationTools = [\n 'spawn_agent',\n 'send_message',\n 'followup_task',\n 'wait_agent',\n 'interrupt_agent',\n 'list_agents',\n ]\n .map((name) => `\\`${tool(name)}\\``)\n .join(', ');\n const shared = `Call ${collaborationTools} directly. They are intentionally unavailable inside nested code execution.\n\nAll agents share the same workspace, current working directory, and filesystem.`;\n\n return {\n minWaitTimeoutMs,\n defaultWaitTimeoutMs,\n maxWaitTimeoutMs,\n usageHintText: nonEmptyText(input.usageHintText),\n rootAgentUsageHintText:\n input.rootAgentUsageHintText === undefined\n ? defaultRootUsageHint(tool, shared)\n : nonEmptyText(input.rootAgentUsageHintText),\n subagentUsageHintText:\n input.subagentUsageHintText === undefined\n ? defaultSubagentUsageHint(tool, shared)\n : nonEmptyText(input.subagentUsageHintText),\n toolNamespace,\n nonCodeModeOnly,\n };\n}\n\nfunction assertTimeout(name: string, value: number): void {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(\n `AgentRuntime: multiAgentV2.${name} must be a non-negative safe integer`,\n );\n }\n}\n\nfunction validateToolNamespace(namespace: string): void {\n if (\n namespace.length > 64 ||\n !/^[a-zA-Z0-9_-]+$/.test(namespace) ||\n namespace === 'mcp' ||\n namespace.startsWith('mcp__') ||\n RESERVED_TOOL_NAMESPACES.has(namespace)\n ) {\n throw new Error(\n `AgentRuntime: multiAgentV2.toolNamespace \"${namespace}\" is a reserved tool namespace or invalid`,\n );\n }\n}\n\nfunction nonEmptyText(value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n return value.length === 0 ? undefined : value;\n}\n\nfunction defaultRootUsageHint(\n tool: (name: string) => string,\n shared: string,\n): string {\n return `You are \\`/root\\`, the primary agent in a team of agents collaborating to fulfill the user's goals.\n\nAt the start of your turn, you are the active agent. You can spawn sub-agents to handle subtasks, and those agents can recursively spawn their own declared sub-agents. All agents are equally capable and receive the tools declared for their agent type.\n\nUse \\`${tool('spawn_agent')}\\` to create an agent, \\`${tool('followup_task')}\\` to assign a new task and trigger a turn, and \\`${tool('send_message')}\\` to queue a message without triggering a turn. Use \\`fork_turns\\` to control how much parent history the child receives.\n\nChild messages arrive as \\`MESSAGE\\` or \\`FINAL_ANSWER\\` mailbox envelopes with their task name, sender, and payload preserved.\n\n${shared}`;\n}\n\nfunction defaultSubagentUsageHint(\n tool: (name: string) => string,\n shared: string,\n): string {\n return `You are an agent in a team collaborating to complete a task.\n\nYou can spawn declared sub-agents recursively. All agents are equally capable and receive the tools declared for their agent type. Use \\`${tool('spawn_agent')}\\` to create one, \\`${tool('followup_task')}\\` to assign a new task and trigger a turn, and \\`${tool('send_message')}\\` to queue a message for another agent.\n\nYour final response is delivered automatically to your parent agent. Mailbox messages arrive as \\`NEW_TASK\\`, \\`MESSAGE\\`, or \\`FINAL_ANSWER\\` envelopes with their task name, sender, and payload preserved.\n\n${shared}`;\n}\n", "import type { UIMessage } from 'ai';\n\nimport {\n ContextEngine,\n type ContextStore,\n type StreamManager,\n agent,\n assistant,\n chat,\n role,\n user,\n} from '@deepagents/context';\n\nimport type { AgentToolContext } from '../collaboration/agent-tool-context.ts';\nimport { createCollaborationTools } from '../collaboration/collaboration-tools.ts';\nimport type { AgentControlPlane } from '../control-plane/agent-control-plane.ts';\nimport type { MailboxCoordinator } from '../mailbox/coordinator.ts';\nimport type {\n ConversationId,\n InterAgentCommunication,\n} from '../mailbox/types.ts';\nimport type { ResolvedMultiAgentV2HostConfig } from '../multi-agent-v2-config.ts';\nimport type { ConsumeContext, TurnRef } from '../queue/turn-queue.ts';\nimport type { ApprovalController } from './approval-controller.ts';\n\nexport interface AgentTurnExecutorOptions {\n store: ContextStore;\n streams: StreamManager;\n controlPlane: AgentControlPlane;\n mailbox: MailboxCoordinator;\n approvals: ApprovalController;\n multiAgentV2: ResolvedMultiAgentV2HostConfig;\n}\n\ninterface SamplingMailboxState {\n firstRequest: boolean;\n}\n\n/** Executes one queued turn without owning host lifecycle or agent routing. */\nexport class AgentTurnExecutor {\n readonly #store: ContextStore;\n readonly #streams: StreamManager;\n readonly #controlPlane: AgentControlPlane;\n readonly #mailbox: MailboxCoordinator;\n readonly #approvals: ApprovalController;\n readonly #multiAgentV2: ResolvedMultiAgentV2HostConfig;\n readonly #collaborationTools: ReturnType<typeof createCollaborationTools>;\n\n constructor(options: AgentTurnExecutorOptions) {\n this.#store = options.store;\n this.#streams = options.streams;\n this.#controlPlane = options.controlPlane;\n this.#mailbox = options.mailbox;\n this.#approvals = options.approvals;\n this.#multiAgentV2 = options.multiAgentV2;\n this.#collaborationTools = createCollaborationTools(options.multiAgentV2);\n }\n\n async execute(turn: TurnRef, context: ConsumeContext): Promise<void> {\n if (turn.kind === 'approval') {\n if (!(await this.#approvals.applyDecision(turn))) return;\n await this.#reopen(turn.streamId);\n return this.execute(\n {\n kind: 'continuation',\n streamId: turn.streamId,\n chatId: turn.chatId,\n userId: turn.userId,\n },\n context,\n );\n }\n if (turn.kind === 'continuation' && turn.recovery !== undefined) {\n await this.#reopen(turn.streamId);\n }\n if (await this.#projectSkippedTerminalTurn(turn)) return;\n\n let parked = false;\n await this.#mailbox.beginTurn(turn);\n try {\n await this.#executeTurn(turn, {\n ...context,\n park: async () => {\n parked = true;\n await context.park();\n },\n });\n } finally {\n await this.#mailbox.endTurn(turn, { parked });\n }\n }\n\n async #executeTurn(\n turn: TurnRef,\n { signal, park }: ConsumeContext,\n ): Promise<void> {\n if (await this.#projectSkippedTerminalTurn(turn)) return;\n\n const { declaration, thread } = await this.#controlPlane.resolve(turn);\n const usageHint = thread.path.isRoot\n ? this.#multiAgentV2.rootAgentUsageHintText\n : this.#multiAgentV2.subagentUsageHintText;\n const engine = this.#engineFor(turn).set(\n ...declaration.instructions,\n ...(usageHint === undefined ? [] : [role(usageHint)]),\n );\n\n if (turn.kind === 'ask' || turn.kind === 'mailbox') {\n const head = (await engine.getMessages()).at(-1);\n if (this.#approvals.isPaused(head)) {\n await park();\n return;\n }\n }\n\n let communications: InterAgentCommunication[] = [];\n if (turn.kind === 'ask') {\n communications = await this.#mailbox.drainLeadingQueueOnly(turn);\n } else if (turn.kind === 'mailbox') {\n communications = await this.#mailbox.drain(turn);\n }\n\n if (turn.kind === 'mailbox' && communications.length === 0) {\n // Duplicate wakes are harmless scheduling receipts once mail is gone.\n await this.#streams.store.updateStreamStatus(turn.streamId, 'completed');\n return;\n }\n\n await this.#controlPlane.recordLatestTurn(turn, turn.streamId);\n await this.#prepareChain(turn, engine, communications);\n\n const sandbox = await declaration.sandbox({\n chatId: turn.chatId,\n userId: turn.userId,\n });\n if (await this.#projectSkippedTerminalTurn(turn)) return;\n if (!(await this.#streams.claim(turn.streamId))) {\n await this.#projectSkippedTerminalTurn(turn);\n return;\n }\n const mailboxState: SamplingMailboxState = { firstRequest: true };\n const ai = agent<AgentToolContext>({\n name: declaration.name,\n model: declaration.model,\n sandbox,\n context: engine,\n tools: {\n ...declaration.tools,\n ...this.#collaborationTools,\n },\n telemetry: declaration.telemetry,\n prepareStepInput: () => this.#prepareStepInput(turn, mailboxState),\n });\n\n const abort = new AbortController();\n const onWorkerAbort = () => abort.abort();\n signal.addEventListener('abort', onWorkerAbort, { once: true });\n try {\n const setupCancellation = this.#streams.monitorCancellation(\n turn.streamId,\n () => abort.abort(),\n );\n let stream: Awaited<ReturnType<typeof chat>>;\n try {\n stream = await chat(ai, {\n abortSignal: abort.signal,\n contextVariables: {\n controlPlane: this.#controlPlane,\n actor: { turn, thread, declaration },\n },\n });\n } finally {\n await setupCancellation[Symbol.asyncDispose]();\n }\n await this.#streams.persist(stream, turn.streamId, {\n preclaimed: true,\n onCancelDetected: () => abort.abort(),\n });\n if (turn.kind === 'continuation') {\n await this.#reconcileTerminalContinuation(turn);\n }\n await this.#controlPlane.projectTerminal(turn, thread);\n } finally {\n signal.removeEventListener('abort', onWorkerAbort);\n }\n }\n\n async #projectSkippedTerminalTurn(turn: TurnRef): Promise<boolean> {\n const status = await this.#streams.store.getStreamStatus(turn.streamId);\n if (status === 'queued' || status === 'running') return false;\n if (status === undefined || turn.kind === 'mailbox') return true;\n\n if (turn.kind === 'continuation') {\n await this.#reconcileTerminalContinuation(turn);\n }\n\n const { thread } = await this.#controlPlane.resolve(turn);\n if (\n thread.lastTurnId === undefined ||\n thread.lastTurnId === turn.streamId\n ) {\n await this.#controlPlane.recordLatestTurnIfCurrent(\n turn,\n turn.streamId,\n thread.lastTurnId,\n );\n }\n await this.#controlPlane.projectTerminal(turn, thread);\n return true;\n }\n\n async #reconcileTerminalContinuation(turn: TurnRef): Promise<void> {\n const stream = await this.#streams.store.getStream(turn.streamId);\n if (\n stream?.status !== 'completed' &&\n stream?.status !== 'failed' &&\n stream?.status !== 'cancelled'\n ) {\n return;\n }\n await this.#approvals.reconcileTerminalContinuation(\n turn,\n turn.streamId,\n stream.status,\n stream.error,\n );\n }\n\n async #reopen(streamId: string): Promise<void> {\n const status = await this.#streams.store.getStreamStatus(streamId);\n if (status === 'queued' || status === 'running') return;\n await this.#streams.reopen(streamId);\n }\n\n async #prepareChain(\n turn: TurnRef,\n engine: ContextEngine,\n communications: InterAgentCommunication[],\n ): Promise<void> {\n if (turn.kind === 'ask') {\n engine.set(\n ...communications.map((communication) =>\n user(this.#mailboxInputMessage(communication)),\n ),\n user(turn.input),\n assistant({ id: turn.streamId, role: 'assistant', parts: [] }),\n );\n await engine.save({ branch: true });\n } else if (turn.kind === 'mailbox') {\n engine.set(\n ...communications.map((communication) =>\n user(this.#mailboxInputMessage(communication)),\n ),\n assistant({ id: turn.streamId, role: 'assistant', parts: [] }),\n );\n await engine.save({ branch: true });\n }\n }\n\n async #prepareStepInput(\n turn: TurnRef,\n state: SamplingMailboxState,\n ): Promise<Array<UIMessage & { role: 'user' }> | undefined> {\n const communications =\n turn.kind === 'ask' && state.firstRequest\n ? await this.#mailbox.drainLeadingQueueOnly(turn)\n : await this.#mailbox.drain(turn);\n state.firstRequest = false;\n return communications.length === 0\n ? undefined\n : communications.map((communication) =>\n this.#mailboxInputMessage(communication),\n );\n }\n\n #engineFor({ chatId, userId }: ConversationId): ContextEngine {\n return new ContextEngine({ store: this.#store, chatId, userId });\n }\n\n #mailboxInputMessage(\n communication: InterAgentCommunication,\n ): UIMessage & { role: 'user' } {\n return {\n id: crypto.randomUUID(),\n role: 'user',\n parts: [\n {\n type: 'text',\n text: this.#renderInterAgentCommunication(communication),\n },\n ],\n metadata: { interAgentCommunication: communication },\n };\n }\n\n #renderInterAgentCommunication(\n communication: InterAgentCommunication,\n ): string {\n const recipientPath = communication.metadata?.recipientPath;\n const authorPath = communication.metadata?.authorPath;\n const taskName =\n typeof recipientPath === 'string'\n ? recipientPath\n : communication.recipient.chatId;\n const sender =\n typeof authorPath === 'string' ? authorPath : communication.author.chatId;\n return `Message Type: ${communication.type}\\nTask name: ${taskName}\\nSender: ${sender}\\nPayload:\\n${communication.content}`;\n }\n}\n", "import { tool } from 'ai';\nimport { z } from 'zod';\n\nimport {\n type ListedAgentStatus,\n listedAgentStatusSchema,\n} from '../control-plane/agent-status-projector.ts';\nimport type { AgentToolContext } from './agent-tool-context.ts';\n\nconst interruptAgentInputSchema = z.object({\n target: z\n .string()\n .trim()\n .min(1)\n .describe(\n 'The canonical /root/... path, or a descendant-relative target name.',\n ),\n});\n\ntype InterruptAgentInput = z.infer<typeof interruptAgentInputSchema>;\n\nconst interruptAgentOutputSchema = z\n .object({ previous_status: listedAgentStatusSchema })\n .strict();\n\nexport const interruptAgentTool = tool<\n InterruptAgentInput,\n { previous_status: ListedAgentStatus },\n AgentToolContext\n>({\n description:\n \"Interrupt an agent's current turn, if any, and return its previous status. The agent remains available for messages and follow-up tasks.\",\n inputSchema: interruptAgentInputSchema,\n outputSchema: interruptAgentOutputSchema,\n execute: async (input, { context }) =>\n context.controlPlane.interruptAgent(context.actor, input),\n});\n", "import { tool } from 'ai';\nimport { z } from 'zod';\n\nimport {\n type ListedAgent,\n listedAgentSchema,\n} from '../control-plane/agent-status-projector.ts';\nimport type { AgentToolContext } from './agent-tool-context.ts';\n\nconst listAgentsInputSchema = z.object({\n path_prefix: z\n .string()\n .trim()\n .min(1)\n .describe(\n 'Task-path prefix without a trailing slash. Omit to list the whole tree.',\n )\n .optional(),\n});\n\ntype ListAgentsInput = z.infer<typeof listAgentsInputSchema>;\n\nconst listAgentsOutputSchema = z\n .object({ agents: z.array(listedAgentSchema) })\n .strict();\n\nexport const listAgentsTool = tool<\n ListAgentsInput,\n { agents: ListedAgent[] },\n AgentToolContext\n>({\n description:\n 'List live agents in the current root thread tree. Optionally filter by task-path prefix.',\n inputSchema: listAgentsInputSchema,\n outputSchema: listAgentsOutputSchema,\n execute: async ({ path_prefix }, { context }) =>\n context.controlPlane.listAgents(context.actor, path_prefix),\n});\n", "import { tool } from 'ai';\nimport { z } from 'zod';\n\nimport type { AgentToolContext } from './agent-tool-context.ts';\n\nconst agentMessageInputSchema = z.object({\n target: z\n .string()\n .trim()\n .min(1)\n .describe(\n 'The canonical /root/... path, or a descendant-relative target name.',\n ),\n message: z.string().trim().min(1).describe('The message or follow-up task.'),\n});\n\ntype AgentMessageInput = z.infer<typeof agentMessageInputSchema>;\ntype AgentMessageOutput = string;\n\nexport const sendMessageTool = tool<\n AgentMessageInput,\n AgentMessageOutput,\n AgentToolContext\n>({\n description:\n 'Queue a message for another agent. Address siblings with their canonical /root/... path.',\n inputSchema: agentMessageInputSchema,\n execute: async (input, { context }) => {\n await context.controlPlane.sendMessage(context.actor, input);\n return '';\n },\n});\n\nexport const followupTaskTool = tool<\n AgentMessageInput,\n AgentMessageOutput,\n AgentToolContext\n>({\n description:\n 'Send a follow-up task to an existing non-root agent and wake its thread.',\n inputSchema: agentMessageInputSchema,\n execute: async (input, { context }) => {\n await context.controlPlane.followupTask(context.actor, input);\n return '';\n },\n});\n", "import { tool } from 'ai';\nimport { z } from 'zod';\n\nimport { forkTurnsError, parseForkTurns } from '../control-plane/fork-turns.ts';\nimport type { AgentToolContext } from './agent-tool-context.ts';\n\nconst spawnAgentInputSchema = z.object({\n agent_type: z\n .string()\n .trim()\n .min(1)\n .describe('The name of one available subagent declaration.'),\n task_name: z\n .string()\n .trim()\n .min(1)\n .refine(\n (value) => value !== '.' && value !== '..' && !value.includes('/'),\n 'task_name must be one non-empty path segment',\n )\n .describe('One path segment naming this independent agent task.'),\n message: z\n .string()\n .refine((value) => value.trim().length > 0, 'message cannot be empty')\n .describe('The initial task for the spawned agent.'),\n fork_turns: z\n .string()\n .trim()\n .default('all')\n .refine((value) => parseForkTurns(value) !== undefined, forkTurnsError)\n .describe(\n 'Optional number of parent turns to fork. Defaults to `all`. Use `none`, `all`, or a positive integer string such as `3`.',\n ),\n});\n\ntype SpawnAgentInput = z.infer<typeof spawnAgentInputSchema>;\n\nconst spawnAgentOutputSchema = z.object({ task_name: z.string() }).strict();\n\nexport function createSpawnAgentTool(options?: { usageHintText?: string }) {\n return tool<SpawnAgentInput, { task_name: string }, AgentToolContext>({\n description: ({ context }) => {\n const available = (context.actor.declaration.subagents ?? [])\n .map((subagent) => subagent.name)\n .join(', ');\n return [\n `Spawn an independent subagent. Available agent types: ${available || 'none'}.`,\n options?.usageHintText,\n ]\n .filter(Boolean)\n .join(' ');\n },\n inputSchema: spawnAgentInputSchema,\n outputSchema: spawnAgentOutputSchema,\n execute: async (\n { agent_type, task_name, message, fork_turns },\n { context },\n ) => {\n const forkTurns = parseForkTurns(fork_turns);\n if (forkTurns === undefined) throw new Error(forkTurnsError);\n return context.controlPlane.spawn(context.actor, {\n agentType: agent_type,\n taskName: task_name,\n message,\n forkTurns,\n });\n },\n });\n}\n", "export type ForkTurns = 'none' | 'all' | number;\n\nexport const forkTurnsError =\n 'fork_turns must be `none`, `all`, or a positive integer string';\n\nexport function parseForkTurns(value: string): ForkTurns | undefined {\n const normalized = value.trim().toLowerCase();\n if (normalized === 'none' || normalized === 'all') return normalized;\n if (!/^\\d+$/.test(normalized)) return undefined;\n\n const turns = Number(normalized);\n return Number.isSafeInteger(turns) && turns > 0 ? turns : undefined;\n}\n", "import { tool } from 'ai';\nimport { z } from 'zod';\n\nimport type { AgentToolContext } from './agent-tool-context.ts';\n\nconst waitAgentOutputSchema = z\n .object({ message: z.string(), timed_out: z.boolean() })\n .strict();\n\nexport function createWaitAgentTool(options: {\n minTimeoutMs: number;\n defaultTimeoutMs: number;\n maxTimeoutMs: number;\n}) {\n const waitAgentInputSchema = z.object({\n timeout_ms: z\n .number()\n .int()\n .min(options.minTimeoutMs)\n .max(options.maxTimeoutMs)\n .optional()\n .describe('Maximum time to wait in milliseconds.'),\n });\n type WaitAgentInput = z.infer<typeof waitAgentInputSchema>;\n\n return tool<\n WaitAgentInput,\n { message: string; timed_out: boolean },\n AgentToolContext\n >({\n description:\n 'Wait for pending mail addressed to this agent without consuming it.',\n inputSchema: waitAgentInputSchema,\n outputSchema: waitAgentOutputSchema,\n execute: async ({ timeout_ms }, { abortSignal, context }) => {\n const received = await context.controlPlane.waitForMailbox(\n context.actor,\n {\n timeoutMs: timeout_ms ?? options.defaultTimeoutMs,\n signal: abortSignal,\n },\n );\n return received\n ? { message: 'Wait completed.', timed_out: false }\n : { message: 'Wait timed out.', timed_out: true };\n },\n });\n}\n", "import type { Tool, ToolSet } from 'ai';\n\nimport type { ResolvedMultiAgentV2HostConfig } from '../multi-agent-v2-config.ts';\nimport { interruptAgentTool } from './interrupt-agent.ts';\nimport { listAgentsTool } from './list-agents.ts';\nimport { followupTaskTool, sendMessageTool } from './message-tools.ts';\nimport { createSpawnAgentTool } from './spawn-agent.ts';\nimport { createWaitAgentTool } from './wait-agent.ts';\n\nconst NAMESPACE_DESCRIPTION = 'Tools for spawning and managing sub-agents.';\n\nexport function createCollaborationTools(\n config: ResolvedMultiAgentV2HostConfig,\n): ToolSet {\n const tools: ToolSet = {\n spawn_agent: createSpawnAgentTool({\n usageHintText: config.usageHintText,\n }),\n send_message: sendMessageTool,\n followup_task: followupTaskTool,\n list_agents: listAgentsTool,\n wait_agent: createWaitAgentTool({\n minTimeoutMs: config.minWaitTimeoutMs,\n defaultTimeoutMs: config.defaultWaitTimeoutMs,\n maxTimeoutMs: config.maxWaitTimeoutMs,\n }),\n interrupt_agent: interruptAgentTool,\n };\n\n return Object.fromEntries(\n Object.entries(tools).map(([name, collaborationTool]) => [\n name,\n configureTool(collaborationTool, config),\n ]),\n );\n}\n\nfunction configureTool(\n collaborationTool: Tool,\n config: ResolvedMultiAgentV2HostConfig,\n): Tool {\n const openai = collaborationTool.providerOptions?.openai;\n return {\n ...collaborationTool,\n providerOptions: {\n ...collaborationTool.providerOptions,\n ...(config.toolNamespace === undefined\n ? {}\n : {\n openai: {\n ...(typeof openai === 'object' && openai !== null ? openai : {}),\n namespace: {\n name: config.toolNamespace,\n description: NAMESPACE_DESCRIPTION,\n },\n },\n }),\n },\n metadata: {\n ...collaborationTool.metadata,\n zukhruf: {\n kind: 'collaboration',\n codeModeExposure: 'direct-model-only',\n },\n },\n };\n}\n", "import {\n type DynamicToolUIPart,\n type ToolUIPart,\n type UIMessage,\n getToolName,\n isToolUIPart,\n} from 'ai';\n\nimport {\n ContextEngine,\n type ContextStore,\n assistant,\n} from '@deepagents/context';\n\nimport type { ConversationId } from '../mailbox/types.ts';\nimport type {\n ApprovalTurnRef,\n TurnQueue,\n TurnRef,\n} from '../queue/turn-queue.ts';\nimport type { ZukhrufToolSet } from '../tool.ts';\nimport { approvalJobId } from './approval-job-id.ts';\n\nexport interface ApprovalControllerOptions {\n store: ContextStore;\n queue: TurnQueue;\n}\n\ntype ApprovalToolPart = DynamicToolUIPart | ToolUIPart;\n\n/** Durable approval-response and continuation state machine. */\nexport class ApprovalController {\n static readonly #settledToolStates = new Set([\n 'output-available',\n 'output-error',\n 'output-denied',\n ]);\n\n readonly #store: ContextStore;\n readonly #queue: TurnQueue;\n\n constructor(options: ApprovalControllerOptions) {\n this.#store = options.store;\n this.#queue = options.queue;\n }\n\n isPaused(message: UIMessage | undefined): boolean {\n return (\n message?.role === 'assistant' &&\n this.#pendingToolPart(message) !== undefined\n );\n }\n\n approve(conversation: ConversationId, input: { toolCallId: string }) {\n return this.#respond('approve', conversation, input.toolCallId, {\n approved: true,\n });\n }\n\n deny(\n conversation: ConversationId,\n input: { toolCallId: string; reason?: string },\n ) {\n return this.#respond('deny', conversation, input.toolCallId, {\n approved: false,\n reason: input.reason,\n });\n }\n\n async settleDeniedApprovals(\n conversation: ConversationId,\n streamId: string,\n ): Promise<void> {\n const engine = this.#engineFor(conversation);\n const head = (await engine.getMessages()).at(-1);\n if (head?.role !== 'assistant' || head.id !== streamId) return;\n const hasDenied = head.parts.some(\n (part) =>\n isToolUIPart(part) &&\n part.state === 'approval-responded' &&\n part.approval.approved === false,\n );\n if (!hasDenied) return;\n\n const updated: UIMessage = {\n ...head,\n parts: head.parts.map((part) => {\n if (\n !isToolUIPart(part) ||\n part.state !== 'approval-responded' ||\n part.approval.approved !== false\n ) {\n return part;\n }\n const settled: ApprovalToolPart = {\n ...part,\n state: 'output-denied',\n approval: { ...part.approval, approved: false },\n };\n return settled;\n }),\n };\n await engine.continue(assistant(updated));\n }\n\n async settleFailedApprovals(\n conversation: ConversationId,\n streamId: string,\n error: string,\n ): Promise<void> {\n const engine = this.#engineFor(conversation);\n const head = (await engine.getMessages()).at(-1);\n if (head?.role !== 'assistant' || head.id !== streamId) return;\n const hasResponded = head.parts.some(\n (part) => isToolUIPart(part) && part.state === 'approval-responded',\n );\n if (!hasResponded) return;\n\n const updated: UIMessage = {\n ...head,\n parts: head.parts.map((part) => {\n if (!isToolUIPart(part) || part.state !== 'approval-responded') {\n return part;\n }\n if (part.approval.approved === false) {\n const denied: ApprovalToolPart = {\n ...part,\n state: 'output-denied',\n approval: { ...part.approval, approved: false },\n };\n return denied;\n }\n const failed: ApprovalToolPart = {\n ...part,\n state: 'output-error',\n errorText: error,\n approval: { ...part.approval, approved: true },\n };\n return failed;\n }),\n };\n await engine.continue(assistant(updated));\n }\n\n async reconcileTerminalContinuation(\n conversation: ConversationId,\n streamId: string,\n status: 'completed' | 'failed' | 'cancelled',\n error?: string | null,\n ): Promise<void> {\n if (status === 'completed') {\n await this.settleDeniedApprovals(conversation, streamId);\n } else {\n await this.settleFailedApprovals(\n conversation,\n streamId,\n error ?? `approval continuation ${status}`,\n );\n }\n await this.#queue.resumeParked(conversation.chatId);\n }\n\n async retryIdempotentContinuation(\n conversation: ConversationId,\n streamId: string,\n tools: ZukhrufToolSet,\n ): Promise<boolean> {\n const head = (await this.#engineFor(conversation).getMessages()).at(-1);\n if (head?.role !== 'assistant' || head.id !== streamId) return false;\n const approved = head.parts.filter(\n (part): part is ApprovalToolPart =>\n isToolUIPart(part) &&\n part.state === 'approval-responded' &&\n part.approval.approved === true,\n );\n const retryable =\n approved.length > 0 &&\n approved.every((part) => {\n const tool = tools[getToolName(part)];\n return (\n tool?.recovery === 'idempotent' && typeof tool.execute === 'function'\n );\n });\n if (!retryable) return false;\n\n await this.#queue.push({\n kind: 'continuation',\n streamId,\n chatId: conversation.chatId,\n userId: conversation.userId,\n recovery: 'idempotent',\n });\n return true;\n }\n\n async applyDecision(turn: ApprovalTurnRef): Promise<boolean> {\n const engine = this.#engineFor(turn);\n const head = (await engine.getMessages()).at(-1);\n if (head?.role !== 'assistant' || head.id !== turn.streamId) return false;\n\n const part = this.#findToolPart(head, turn.toolCallId);\n if (part?.approval?.id !== turn.approvalId) return false;\n if (part.approval.approved !== undefined) return false;\n if (part.state !== 'approval-requested') return false;\n\n const responded: ApprovalToolPart = {\n ...part,\n state: 'approval-responded',\n approval: { ...part.approval, ...turn.decision },\n };\n const updated: UIMessage = {\n ...head,\n parts: head.parts.map((candidate) =>\n candidate === part ? responded : candidate,\n ),\n };\n await engine.continue(assistant(updated));\n return !this.#hasUnansweredApprovals(updated);\n }\n\n async recoverUnstartedContinuation(\n turn: TurnRef,\n streamId: string,\n ): Promise<boolean> {\n if (turn.kind === 'approval') await this.applyDecision(turn);\n const head = (await this.#engineFor(turn).getMessages()).at(-1);\n if (\n head?.role !== 'assistant' ||\n head.id !== streamId ||\n this.#hasUnansweredApprovals(head) ||\n !head.parts.some(\n (part) => isToolUIPart(part) && part.state === 'approval-responded',\n )\n ) {\n return false;\n }\n\n await this.#queue.push({\n kind: 'continuation',\n streamId,\n chatId: turn.chatId,\n userId: turn.userId,\n recovery: 'handoff',\n });\n return true;\n }\n\n async #respond(\n operation: 'approve' | 'deny',\n conversation: ConversationId,\n toolCallId: string,\n approval: { approved: true } | { approved: false; reason?: string },\n ) {\n const head = (await this.#engineFor(conversation).getMessages()).at(-1);\n if (head?.role !== 'assistant') {\n throw new Error(\n `ApprovalController.${operation}: no paused turn \u2014 the chain head is not an assistant message`,\n );\n }\n const part = this.#findToolPart(head, toolCallId);\n if (!part) {\n throw new Error(\n `ApprovalController.${operation}: no tool call \"${toolCallId}\" on the paused turn`,\n );\n }\n if (!part.approval) {\n throw new Error(\n `ApprovalController.${operation}: tool call \"${toolCallId}\" is not awaiting approval`,\n );\n }\n const jobId = approvalJobId(conversation, part.approval.id);\n if (part.approval.approved !== undefined) {\n if (part.approval.approved !== approval.approved) {\n throw new Error(\n `ApprovalController.${operation}: approval already answered with a different decision`,\n );\n }\n return { id: head.id, jobId, status: 'already-applied' as const };\n }\n if (part.state !== 'approval-requested') {\n throw new Error(\n `ApprovalController.${operation}: tool call \"${toolCallId}\" is not awaiting approval`,\n );\n }\n\n const result = await this.#queue.push({\n kind: 'approval',\n streamId: head.id,\n chatId: conversation.chatId,\n userId: conversation.userId,\n toolCallId,\n approvalId: part.approval.id,\n decision: approval,\n });\n return {\n id: head.id,\n jobId,\n status: result.inserted\n ? ('queued' as const)\n : ('already-queued' as const),\n };\n }\n\n #pendingToolPart(message: UIMessage) {\n return message.parts.find(\n (part) =>\n isToolUIPart(part) &&\n !ApprovalController.#settledToolStates.has(part.state),\n );\n }\n\n #hasUnansweredApprovals(message: UIMessage): boolean {\n return message.parts.some(\n (part) => isToolUIPart(part) && part.state === 'approval-requested',\n );\n }\n\n #findToolPart(\n message: UIMessage,\n toolCallId: string,\n ): ApprovalToolPart | undefined {\n return message.parts.find(\n (part): part is ApprovalToolPart =>\n isToolUIPart(part) && part.toolCallId === toolCallId,\n );\n }\n\n #engineFor({ chatId, userId }: ConversationId): ContextEngine {\n return new ContextEngine({ store: this.#store, chatId, userId });\n }\n}\n", "import { v5 as uuidv5 } from 'uuid';\n\nimport { conversationNamespace } from '../control-plane/agent-turn-id.ts';\nimport type { ConversationId } from '../mailbox/types.ts';\n\nexport function approvalJobId(\n conversation: ConversationId,\n approvalId: string,\n): string {\n return uuidv5(`approval:${approvalId}`, conversationNamespace(conversation));\n}\n", "import type { ContextFragment } from '@deepagents/context';\n\nexport function defineInstructions(...fragments: ContextFragment[]) {\n return fragments;\n}\n", "import { DatabaseSync } from 'node:sqlite';\n\nimport {\n type MailboxEndTurnResult,\n type MailboxEnqueueResult,\n MailboxStore,\n} from './store.ts';\nimport {\n type ConversationId,\n type InterAgentCommunication,\n InterAgentCommunicationType,\n} from './types.ts';\n\nconst DDL = `\n PRAGMA journal_mode = WAL;\n PRAGMA synchronous = NORMAL;\n\n CREATE TABLE IF NOT EXISTS zukhruf_mailbox_items (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n recipient_chat_id TEXT NOT NULL,\n recipient_user_id TEXT NOT NULL,\n communication TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS zukhruf_mailbox_activity (\n recipient_chat_id TEXT NOT NULL,\n recipient_user_id TEXT NOT NULL,\n turn_id TEXT NOT NULL,\n PRIMARY KEY (recipient_chat_id, recipient_user_id)\n );\n\n CREATE TABLE IF NOT EXISTS zukhruf_mailbox_consumed_terminal_ids (\n communication_id TEXT PRIMARY KEY\n );\n\n CREATE INDEX IF NOT EXISTS zukhruf_mailbox_recipient_sequence\n ON zukhruf_mailbox_items (\n recipient_chat_id,\n recipient_user_id,\n sequence\n );\n\n CREATE UNIQUE INDEX IF NOT EXISTS zukhruf_mailbox_communication_id\n ON zukhruf_mailbox_items (\n json_extract(communication, '$.id')\n );\n`;\n\nconst BUSY_TIMEOUT_MS = 5_000;\n\n/** SQLite-backed mailbox for durable cross-process delivery. */\nexport class SqliteMailboxStore extends MailboxStore implements Disposable {\n #database: DatabaseSync;\n #closed = false;\n\n constructor(path: string) {\n super();\n this.#database = new DatabaseSync(path, { timeout: BUSY_TIMEOUT_MS });\n this.#database.exec(DDL);\n }\n\n override async beginTurn(\n recipient: ConversationId,\n turnId: string,\n ): Promise<void> {\n this.#transaction(() => {\n this.#database\n .prepare(\n `INSERT INTO zukhruf_mailbox_activity (\n recipient_chat_id,\n recipient_user_id,\n turn_id\n ) VALUES (?, ?, ?)\n ON CONFLICT (recipient_chat_id, recipient_user_id)\n DO UPDATE SET turn_id = excluded.turn_id`,\n )\n .run(recipient.chatId, recipient.userId, turnId);\n });\n }\n\n override async enqueue(\n communication: InterAgentCommunication,\n ): Promise<MailboxEnqueueResult> {\n return this.#transaction(() => {\n const consumedTerminal =\n communication.type === InterAgentCommunicationType.FinalAnswer &&\n this.#hasConsumedTerminal(communication.id);\n if (!consumedTerminal) {\n this.#database\n .prepare(\n `INSERT OR IGNORE INTO zukhruf_mailbox_items (\n recipient_chat_id,\n recipient_user_id,\n communication\n ) VALUES (?, ?, ?)`,\n )\n .run(\n communication.recipient.chatId,\n communication.recipient.userId,\n JSON.stringify(communication),\n );\n }\n return {\n recipientActive: this.#isTurnActive(communication.recipient),\n };\n });\n }\n\n override async endTurn(\n recipient: ConversationId,\n turnId: string,\n ): Promise<MailboxEndTurnResult> {\n return this.#transaction(() => {\n const result = this.#database\n .prepare(\n `DELETE FROM zukhruf_mailbox_activity\n WHERE recipient_chat_id = ?\n AND recipient_user_id = ?\n AND turn_id = ?`,\n )\n .run(recipient.chatId, recipient.userId, turnId);\n return {\n hasPending: this.#hasPending(recipient),\n turnEnded: result.changes > 0,\n };\n });\n }\n\n override async hasPending(recipient: ConversationId): Promise<boolean> {\n return this.#hasPending(recipient);\n }\n\n #hasPending(recipient: ConversationId): boolean {\n const row = this.#database\n .prepare(\n `SELECT 1\n FROM zukhruf_mailbox_items\n WHERE recipient_chat_id = ?\n AND recipient_user_id = ?\n LIMIT 1`,\n )\n .get(recipient.chatId, recipient.userId);\n return row !== undefined;\n }\n\n #isTurnActive(recipient: ConversationId): boolean {\n const row = this.#database\n .prepare(\n `SELECT 1\n FROM zukhruf_mailbox_activity\n WHERE recipient_chat_id = ?\n AND recipient_user_id = ?\n LIMIT 1`,\n )\n .get(recipient.chatId, recipient.userId);\n return row !== undefined;\n }\n\n #hasConsumedTerminal(communicationId: string): boolean {\n const row = this.#database\n .prepare(\n `SELECT 1\n FROM zukhruf_mailbox_consumed_terminal_ids\n WHERE communication_id = ?\n LIMIT 1`,\n )\n .get(communicationId);\n return row !== undefined;\n }\n\n override async drain(\n recipient: ConversationId,\n ): Promise<InterAgentCommunication[]> {\n return this.#drain(recipient, false);\n }\n\n override async drainLeadingQueueOnly(\n recipient: ConversationId,\n ): Promise<InterAgentCommunication[]> {\n return this.#drain(recipient, true);\n }\n\n #drain(\n recipient: ConversationId,\n leadingQueueOnly: boolean,\n ): InterAgentCommunication[] {\n return this.#transaction(() => {\n const rows = this.#database\n .prepare(\n `SELECT sequence, communication\n FROM zukhruf_mailbox_items\n WHERE recipient_chat_id = ?\n AND recipient_user_id = ?\n ORDER BY sequence`,\n )\n .all(recipient.chatId, recipient.userId) as Array<{\n sequence: number;\n communication: string;\n }>;\n const items = rows.map((row) => ({\n sequence: row.sequence,\n communication: JSON.parse(row.communication) as InterAgentCommunication,\n }));\n const firstTrigger = leadingQueueOnly\n ? items.findIndex(({ communication }) => communication.triggerTurn)\n : -1;\n const consumed =\n firstTrigger === -1 ? items : items.slice(0, firstTrigger);\n const lastConsumed = consumed.at(-1);\n if (lastConsumed) {\n // Only terminal IDs get durable tombstones. Ordinary random-ID mail\n // does not need permanent dedup state after FIFO consumption.\n const tombstone = this.#database.prepare(\n `INSERT OR IGNORE\n INTO zukhruf_mailbox_consumed_terminal_ids (communication_id)\n VALUES (?)`,\n );\n for (const { communication } of consumed) {\n if (communication.type === InterAgentCommunicationType.FinalAnswer) {\n tombstone.run(communication.id);\n }\n }\n this.#database\n .prepare(\n `DELETE FROM zukhruf_mailbox_items\n WHERE recipient_chat_id = ?\n AND recipient_user_id = ?\n AND sequence <= ?`,\n )\n .run(recipient.chatId, recipient.userId, lastConsumed.sequence);\n }\n return consumed.map(({ communication }) => communication);\n });\n }\n\n #transaction<T>(operation: () => T): T {\n this.#database.exec('BEGIN IMMEDIATE');\n try {\n const result = operation();\n this.#database.exec('COMMIT');\n return result;\n } catch (error) {\n try {\n this.#database.exec('ROLLBACK');\n } catch {\n // Preserve the operation error when SQLite already ended the transaction.\n }\n throw error;\n }\n }\n\n close(): void {\n if (this.#closed) return;\n this.#closed = true;\n this.#database.close();\n }\n\n [Symbol.dispose](): void {\n this.close();\n }\n}\n", "import type { ConversationId, InterAgentCommunication } from './types.ts';\n\nexport interface MailboxEnqueueResult {\n recipientActive: boolean;\n}\n\nexport interface MailboxEndTurnResult {\n hasPending: boolean;\n turnEnded: boolean;\n}\n\n/** Durable pending-mail storage. This is deliberately not an execution queue. */\nexport abstract class MailboxStore {\n abstract beginTurn(recipient: ConversationId, turnId: string): Promise<void>;\n\n abstract enqueue(\n communication: InterAgentCommunication,\n ): Promise<MailboxEnqueueResult>;\n\n abstract endTurn(\n recipient: ConversationId,\n turnId: string,\n ): Promise<MailboxEndTurnResult>;\n\n abstract hasPending(recipient: ConversationId): Promise<boolean>;\n\n /** Consumes the contiguous queue-only prefix, stopping before the first trigger. */\n abstract drainLeadingQueueOnly(\n recipient: ConversationId,\n ): Promise<InterAgentCommunication[]>;\n\n /** Draining is consumption: removes and returns all pending mail in FIFO order. */\n abstract drain(recipient: ConversationId): Promise<InterAgentCommunication[]>;\n}\n", "import type { JobWithMetadata, PgBoss } from 'pg-boss';\nimport { v7 as uuidv7 } from 'uuid';\n\nimport { approvalJobId } from '../runtime/approval-job-id.ts';\nimport {\n type ConsumeContext,\n type ConsumeOptions,\n type TurnActivity,\n type TurnPushResult,\n TurnQueue,\n type TurnRef,\n} from './turn-queue.ts';\n\nexport interface PgBossTurnQueueOptions {\n queue?: string;\n /** Required for custom DB adapters; must match the PgBoss schema. */\n schema?: string;\n /** Hard cap on one turn attempt; the job fails past this. */\n expireInSeconds?: number;\n /** Dead-worker detection window; must be >= 10 (pg-boss constraint). */\n heartbeatSeconds?: number;\n pollingIntervalSeconds?: number;\n}\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n\n/**\n * TurnQueue on pg-boss.\n *\n * - `key_strict_fifo` policy with `singletonKey = chatId` gives the per-chat\n * serialization contract structurally: one active turn per chat and strict\n * push order.\n * - `group.id = chatId` with global `groupConcurrency: 1` excludes an active\n * chat before pg-boss selects the next job, so its queued successor cannot\n * block ready turns from other chats.\n * - `retryLimit: 0` \u2014 a crashed turn is never silently re-run (its bash\n * already executed). It dead-letters instead.\n * - A failed job blocks its chat's key until acknowledged; the dead-letter\n * consumer is that acknowledgement: it reports the orphan via\n * `onOrphaned`, then deletes the source job, unblocking the chat.\n * - `deleteAfterSeconds: 0` \u2014 pg-boss never deletes a terminal job on a\n * wall-clock timer. That is what makes a parked (cancelled) turn durable: it\n * awaits its approval for as long as it takes, with no retention deadline.\n * Cleanup is commit-driven instead \u2014 `consume` deletes a job the moment its\n * turn runs and commits to the chain \u2014 so completed jobs don't accumulate.\n * (`retentionSeconds`, which governs still-`created` jobs, can't be 0; its\n * default 14d is never approached because a queued turn only waits behind one\n * running turn.)\n * - Interrupting an active turn aborts the adapter-local handler but leaves its\n * pg-boss row `active` until that handler exits. Cancelling the row itself\n * would surrender the strict-FIFO key early and let the successor overlap.\n * Cross-process handler abort comes from the runtime's durable stream\n * cancellation; this queue remains the scheduler-ordering authority.\n *\n * The `PgBoss` instance is borrowed: the caller `start()`s and `stop()`s it.\n */\nexport class PgBossTurnQueue extends TurnQueue {\n #boss: PgBoss;\n #queue: string;\n #schema: string;\n #schemaConfigurationError?: string;\n #table?: string;\n #expireInSeconds: number;\n #cancelIntentTtlMs: number;\n #heartbeatSeconds: number;\n #pollingIntervalSeconds: number;\n #active = new Map<string, Set<AbortController>>();\n #cancelIntents = new Map<string, number>();\n #cancelIntentExpiryTimer?: ReturnType<typeof globalThis.setTimeout>;\n\n constructor(boss: PgBoss, options: PgBossTurnQueueOptions = {}) {\n super();\n this.#boss = boss;\n this.#queue = options.queue ?? 'zukhruf-turns';\n const configuredSchema = (boss.getDb() as { config?: { schema?: unknown } })\n .config?.schema;\n const bossSchema =\n typeof configuredSchema === 'string' ? configuredSchema : undefined;\n this.#schema = options.schema ?? bossSchema ?? 'pgboss';\n if (options.schema === undefined && bossSchema === undefined) {\n this.#schemaConfigurationError =\n 'PgBossTurnQueue cannot read the schema from a custom PgBoss database adapter; pass the PgBoss schema in options.schema';\n } else if (\n options.schema !== undefined &&\n bossSchema !== undefined &&\n options.schema !== bossSchema\n ) {\n this.#schemaConfigurationError = `PgBossTurnQueue schema \"${options.schema}\" does not match the PgBoss schema \"${bossSchema}\"`;\n }\n this.#expireInSeconds = options.expireInSeconds ?? 3600;\n this.#cancelIntentTtlMs = this.#expireInSeconds * 1_000;\n if (\n !Number.isFinite(this.#expireInSeconds) ||\n this.#expireInSeconds <= 0 ||\n !Number.isSafeInteger(this.#cancelIntentTtlMs) ||\n this.#cancelIntentTtlMs > Number.MAX_SAFE_INTEGER - Date.now()\n ) {\n throw new Error(\n 'PgBossTurnQueue expireInSeconds must be a finite positive duration',\n );\n }\n this.#heartbeatSeconds = options.heartbeatSeconds ?? 30;\n this.#pollingIntervalSeconds = options.pollingIntervalSeconds ?? 1;\n }\n\n get queue(): string {\n return this.#queue;\n }\n\n get deadLetterQueue(): string {\n return `${this.#queue}-dead`;\n }\n\n async initialize(): Promise<void> {\n if (this.#schemaConfigurationError) {\n throw new Error(this.#schemaConfigurationError);\n }\n if (!(await this.#boss.getQueue(this.deadLetterQueue))) {\n await this.#boss.createQueue(this.deadLetterQueue);\n }\n let queue = await this.#boss.getQueue(this.#queue);\n if (!queue) {\n await this.#boss.createQueue(this.#queue, {\n policy: 'key_strict_fifo',\n retryLimit: 0,\n expireInSeconds: this.#expireInSeconds,\n heartbeatSeconds: this.#heartbeatSeconds,\n deleteAfterSeconds: 0,\n deadLetter: this.deadLetterQueue,\n });\n queue = await this.#boss.getQueue(this.#queue);\n }\n if (!queue) throw new Error(`Queue \"${this.#queue}\" was not initialized`);\n this.#table = queue.table;\n try {\n const catalog = await this.#boss.getDb().executeSql(\n `SELECT table_name AS \"table\"\n FROM ${PgBossTurnQueue.#quoteIdentifier(this.#schema)}.\"queue\"\n WHERE name = $1`,\n [this.#queue],\n );\n if (\n catalog.rows.length !== 1 ||\n (catalog.rows[0] as { table?: unknown }).table !== this.#table\n ) {\n throw new Error('queue catalog does not match');\n }\n await this.#boss\n .getDb()\n .executeSql(`SELECT 1 FROM ${this.#relation()} WHERE false`);\n } catch (cause) {\n throw new Error(\n `PgBossTurnQueue schema \"${this.#schema}\" does not match the PgBoss queue; pass the PgBoss schema in options.schema`,\n { cause },\n );\n }\n }\n\n async push(turn: TurnRef): Promise<TurnPushResult> {\n // pg-boss fetches `ORDER BY priority desc, created_on, id`. A monotonic\n // UUIDv7 job id makes the id tiebreak follow push order, so FIFO survives\n // created_on timestamp ties (millisecond-resolution clocks like PGlite).\n // Non-approval pushes create new jobs for at-least-once delivery. Approval\n // pushes use the persisted approval id, so pg-boss's id uniqueness makes\n // concurrent commands converge on the first inserted decision.\n // Approval and recovery jobs outrank waiting turns: revived parked jobs\n // keep their original (older) created_on, so priority is what puts the\n // command/recovery first.\n const jobId =\n turn.kind === 'approval'\n ? approvalJobId(turn, turn.approvalId)\n : uuidv7();\n const inserted = await this.#boss.send(this.#queue, turn, {\n id: jobId,\n singletonKey: turn.chatId,\n group: { id: turn.chatId },\n priority:\n turn.kind === 'approval' || turn.kind === 'continuation' ? 1 : 0,\n });\n if (inserted === null && turn.kind !== 'approval') {\n throw new Error(`PgBossTurnQueue job id collision: ${jobId}`);\n }\n return { jobId, inserted: inserted !== null };\n }\n\n override async getTurnActivity(\n conversation: Pick<TurnRef, 'chatId' | 'userId'>,\n ): Promise<TurnActivity> {\n const jobs = await this.#boss.findJobs<TurnRef>(this.#queue, {\n key: conversation.chatId,\n });\n const conversationJobs = jobs.filter(\n (job) =>\n job.data.userId === conversation.userId &&\n (job.state === 'created' ||\n job.state === 'retry' ||\n job.state === 'active'),\n );\n if (conversationJobs.some((job) => job.state === 'active')) {\n return 'running';\n }\n return conversationJobs.length > 0 ? 'queued' : 'idle';\n }\n\n override async getCurrentTurn(\n conversation: Pick<TurnRef, 'chatId' | 'userId'>,\n ): Promise<TurnRef | undefined> {\n const jobs = await this.#boss.findJobs<TurnRef>(this.#queue, {\n key: conversation.chatId,\n });\n return jobs\n .filter(\n (job) =>\n job.data.userId === conversation.userId &&\n (job.state === 'active' ||\n job.state === 'created' ||\n job.state === 'retry'),\n )\n .sort(PgBossTurnQueue.#interruptOrder)[0]?.data;\n }\n\n override async cancel(streamId: string): Promise<void> {\n this.#rememberCancelIntent(streamId);\n this.#abortLocal(streamId);\n const jobs = await this.#boss.findJobs<TurnRef>(this.#queue, {\n data: { streamId },\n });\n // An active row must retain the strict-FIFO key until its handler exits.\n // Delete only rows that are still queued at mutation time: a worker may\n // claim one after findJobs() returns, and pg-boss's public cancel/delete\n // methods do not provide the state predicate needed to close that race.\n // Remote active handlers are stopped by the runtime's durable stream\n // cancellation; their normal handler exit performs commit-driven GC.\n const queued = jobs\n .filter((job) => job.state === 'created' || job.state === 'retry')\n .map((job) => job.id);\n if (queued.length > 0) await this.#deleteIfStillQueued(queued);\n\n // Close the inverse race too: a local worker can claim after the first\n // controller scan but before the state-conditional delete.\n this.#abortLocal(streamId);\n const remaining = await this.#boss.findJobs<TurnRef>(this.#queue, {\n data: { streamId },\n });\n if (!remaining.some((job) => job.state === 'active')) {\n this.#forgetCancelIntent(streamId);\n }\n }\n\n async consume(\n handler: (turn: TurnRef, context: ConsumeContext) => Promise<void>,\n options: ConsumeOptions,\n ): Promise<AsyncDisposable> {\n const turnWorkerId = await this.#boss.work<TurnRef>(\n this.#queue,\n {\n localConcurrency: options.concurrency ?? 1,\n groupConcurrency: 1,\n pollingIntervalSeconds: this.#pollingIntervalSeconds,\n },\n async ([job]) => {\n let parked = false;\n const localAbort = new AbortController();\n const active = this.#active.get(job.data.streamId) ?? new Set();\n active.add(localAbort);\n this.#active.set(job.data.streamId, active);\n if (this.#hasCancelIntent(job.data.streamId)) localAbort.abort();\n try {\n await handler(job.data, {\n signal: AbortSignal.any([job.signal, localAbort.signal]),\n // Parking = self-cancel: a cancelled job stops blocking the chat's\n // key and is revived (original created_on, so original order) by\n // resumeParked(). The worker's completion of a cancelled job is a\n // clean no-op (probe-verified).\n park: async () => {\n parked = true;\n await this.#boss.cancel(this.#queue, job.id);\n },\n });\n } finally {\n active.delete(localAbort);\n if (active.size === 0) {\n this.#active.delete(job.data.streamId);\n this.#forgetCancelIntent(job.data.streamId);\n }\n }\n // Commit-driven GC. A handler that returns without parking has run its\n // turn to a terminal stream and committed to the chain (the permanent\n // record) \u2014 the job is spent, so delete it now instead of leaning on a\n // wall-clock timer (`deleteAfterSeconds: 0` disables that). Deleting an\n // active job from inside its own handler is safe: pg-boss's subsequent\n // completion finds no row and no-ops (probe-verified, zero errors). A\n // parked turn is skipped \u2014 it must stay `cancelled` for resumeParked to\n // revive it. A throwing handler is skipped too \u2014 the throw propagates to\n // pg-boss and the turn dead-letters.\n if (!parked) {\n await this.#boss.deleteJob(this.#queue, job.id);\n }\n },\n );\n\n const deadWorkerId = await this.#boss.work(\n this.deadLetterQueue,\n {\n includeMetadata: true,\n pollingIntervalSeconds: this.#pollingIntervalSeconds,\n },\n async ([job]: JobWithMetadata<TurnRef>[]) => {\n try {\n await options.onOrphaned(\n job.data,\n PgBossTurnQueue.#orphanError(job.output),\n );\n } finally {\n // The failed source job owns the strict-FIFO key. Reconciliation may\n // retry through this DLQ job, but it must never retain that key and\n // wedge every later turn in the conversation.\n if (job.sourceId) {\n await this.#boss.deleteJob(this.#queue, job.sourceId);\n }\n }\n },\n );\n\n return {\n [Symbol.asyncDispose]: async () => {\n await this.#boss.offWork(this.#queue, { id: turnWorkerId });\n await this.#boss.offWork(this.deadLetterQueue, { id: deadWorkerId });\n },\n };\n }\n\n async resumeParked(chatId: string): Promise<void> {\n // Revives every cancelled job for the chat. A revived USER-cancelled\n // turn is harmless \u2014 the consumer's terminal-stream check skips it \u2014\n // so no parked-vs-cancelled bookkeeping is needed here.\n const jobs = await this.#boss.findJobs(this.#queue, { key: chatId });\n const parked = jobs\n .filter((job) => job.state === 'cancelled')\n .map((job) => job.id);\n if (parked.length > 0) {\n await this.#boss.resume(this.#queue, parked);\n }\n }\n\n #abortLocal(streamId: string): void {\n for (const controller of this.#active.get(streamId) ?? []) {\n controller.abort();\n }\n }\n\n #rememberCancelIntent(streamId: string): void {\n this.#pruneCancelIntents();\n this.#cancelIntents.set(streamId, Date.now() + this.#cancelIntentTtlMs);\n this.#scheduleCancelIntentExpiry();\n }\n\n #hasCancelIntent(streamId: string): boolean {\n this.#pruneCancelIntents();\n return this.#cancelIntents.has(streamId);\n }\n\n #pruneCancelIntents(): void {\n const now = Date.now();\n for (const [streamId, expiresAt] of this.#cancelIntents) {\n if (expiresAt <= now) this.#cancelIntents.delete(streamId);\n }\n this.#scheduleCancelIntentExpiry();\n }\n\n #forgetCancelIntent(streamId: string): void {\n this.#cancelIntents.delete(streamId);\n this.#scheduleCancelIntentExpiry();\n }\n\n #scheduleCancelIntentExpiry(): void {\n if (this.#cancelIntentExpiryTimer !== undefined) {\n globalThis.clearTimeout(this.#cancelIntentExpiryTimer);\n this.#cancelIntentExpiryTimer = undefined;\n }\n let nextExpiry = Number.POSITIVE_INFINITY;\n for (const expiresAt of this.#cancelIntents.values()) {\n nextExpiry = Math.min(nextExpiry, expiresAt);\n }\n if (!Number.isFinite(nextExpiry)) return;\n\n const timer = globalThis.setTimeout(\n () => {\n if (this.#cancelIntentExpiryTimer !== timer) return;\n this.#cancelIntentExpiryTimer = undefined;\n this.#pruneCancelIntents();\n },\n Math.min(MAX_TIMEOUT_MS, Math.max(1, nextExpiry - Date.now())),\n );\n this.#cancelIntentExpiryTimer = timer;\n (timer as { unref?: () => void }).unref?.();\n }\n\n async #deleteIfStillQueued(ids: string[]): Promise<void> {\n if (!this.#table) {\n throw new Error('PgBossTurnQueue.initialize() must run before cancel()');\n }\n await this.#boss.getDb().executeSql(\n `DELETE FROM ${this.#relation()}\n WHERE name = $1\n AND id = ANY($2::uuid[])\n AND state IN ('created', 'retry')`,\n [this.#queue, ids],\n );\n }\n\n #relation(): string {\n if (!this.#table) {\n throw new Error(\n 'PgBossTurnQueue.initialize() must resolve its job table',\n );\n }\n return `${PgBossTurnQueue.#quoteIdentifier(this.#schema)}.${PgBossTurnQueue.#quoteIdentifier(this.#table)}`;\n }\n\n static #quoteIdentifier(identifier: string): string {\n return `\"${identifier.replaceAll('\"', '\"\"')}\"`;\n }\n\n static #orphanError(output: object | null | undefined): string {\n if (output && 'message' in output && typeof output.message === 'string') {\n return output.message;\n }\n return output ? JSON.stringify(output) : 'turn orphaned';\n }\n\n static #interruptOrder(\n left: JobWithMetadata<TurnRef>,\n right: JobWithMetadata<TurnRef>,\n ): number {\n if (left.state === 'active' && right.state !== 'active') return -1;\n if (left.state !== 'active' && right.state === 'active') return 1;\n if (left.priority !== right.priority) return right.priority - left.priority;\n const created = left.createdOn.getTime() - right.createdOn.getTime();\n return created || left.id.localeCompare(right.id);\n }\n}\n", "export type TurnRef = {\n streamId: string;\n chatId: string;\n userId: string;\n} & (\n | {\n kind: 'ask';\n /**\n * The user message, carried by the queue until the turn executes. It\n * enters the context chain only when the turn RUNS \u2014 enqueue-time\n * persistence would let a queued turn's message leak into the running\n * turn's prompt (and `chat()` streams into the chain head, which must\n * be THIS turn's placeholder).\n */\n input: string;\n }\n | {\n /**\n * Recovery-only re-execution of an existing stream. Normal approval\n * responses resume directly inside their approval job.\n */\n kind: 'continuation';\n recovery?: 'handoff' | 'idempotent';\n }\n | {\n kind: 'approval';\n toolCallId: string;\n approvalId: string;\n decision: { approved: true } | { approved: false; reason?: string };\n }\n | {\n /**\n * A mailbox wake-up. The communication payload remains in MailboxStore;\n * TurnQueue carries only the execution request and addressing.\n */\n kind: 'mailbox';\n }\n);\n\nexport interface TurnPushResult {\n jobId: string;\n inserted: boolean;\n}\n\nexport type ApprovalTurnRef = Extract<TurnRef, { kind: 'approval' }>;\n\nexport interface ConsumeContext {\n signal: AbortSignal;\n /**\n * Park the turn being handled: it settles WITHOUT executing and is not\n * delivered again until `resumeParked(chatId)`. Used by the queue-behind\n * gate \u2014 turns arriving while their chat awaits a tool approval.\n */\n park: () => Promise<void>;\n}\n\nexport interface ConsumeOptions {\n /** Max turns processed concurrently by this consumer (across chats). */\n concurrency?: number;\n /**\n * Fires for a turn whose handler crashed or whose worker died mid-turn.\n * After it resolves, the turn's chat is unblocked and its next queued\n * turn becomes eligible.\n */\n onOrphaned: (turn: TurnRef, error: string) => Promise<void>;\n}\n\nexport type TurnActivity = 'idle' | 'queued' | 'running';\n\n/**\n * Durable holding pen for pending turns.\n *\n * Contract every implementation must honor:\n * - `push` is durable: a pushed turn survives process death until consumed.\n * - Delivery is AT-LEAST-ONCE: a pushed non-approval turn is delivered until settled, and\n * duplicate pushes of the same `streamId` may each be delivered. Consumers\n * MUST be idempotent on `streamId` (the zukhruf runtime skips turns whose\n * stream row is terminal \u2014 a check that, unlike queue-side dedup, never\n * expires with job retention).\n * - Approval pushes use their persisted approval id as a deterministic job\n * identity. The first decision inserts; later decisions for that approval\n * report the existing job instead of adding a row.\n * - Per chat, at most ONE handler invocation is active at a time, and turns\n * run in the order they were pushed (strict FIFO per `chatId`) \u2014 this\n * covers duplicates too: they can never run concurrently or out of order.\n * - Turns from different chats may run concurrently.\n * - `getTurnActivity` distinguishes queued from active scheduler work for\n * status inspection; adapters must not silently fall back to stale history.\n * - `getCurrentTurn` returns the active turn, or otherwise the oldest eligible\n * queued turn, for exact interruption. `cancel` removes queued copies of that\n * exact stream and signals an adapter-local active handler, but an active turn\n * retains FIFO ownership until its handler exits. Cross-process handler abort\n * is the runtime stream-control layer's responsibility.\n * - A handler that throws (or a worker that dies mid-turn) does not retry:\n * the turn surfaces once through `onOrphaned`, then the chat unblocks.\n * - Mailbox payloads NEVER live here. A `{kind: 'mailbox'}` item is only a\n * durable wake request; the target MailboxStore remains the pending-input\n * authority.\n * - A parked turn (`context.park()`) is not delivered again until\n * `resumeParked(chatId)`; revived turns keep their original FIFO order,\n * and approval/recovery turns pushed for the chat outrank them.\n *\n * On platforms with native per-conversation serialization (e.g. Durable\n * Objects) this port is absorbed by the host rather than implemented.\n */\nexport abstract class TurnQueue {\n abstract push(turn: TurnRef): Promise<TurnPushResult>;\n\n /** Whether this conversation currently has queued or active scheduler work. */\n abstract getTurnActivity(\n conversation: Pick<TurnRef, 'chatId' | 'userId'>,\n ): Promise<TurnActivity>;\n\n /** Active turn, or the oldest eligible queued turn, for a conversation. */\n abstract getCurrentTurn(\n conversation: Pick<TurnRef, 'chatId' | 'userId'>,\n ): Promise<TurnRef | undefined>;\n\n /** Cancel queued copies and request local active cancellation by stream id. */\n abstract cancel(streamId: string): Promise<void>;\n\n abstract consume(\n handler: (turn: TurnRef, context: ConsumeContext) => Promise<void>,\n options: ConsumeOptions,\n ): Promise<AsyncDisposable>;\n\n abstract resumeParked(chatId: string): Promise<void>;\n}\n", "import type { UIMessageChunk } from 'ai';\nimport { styleText } from 'node:util';\n\nconst dim = (text: string) => styleText('dim', text);\nconst red = (text: string) => styleText('red', text);\n\nfunction oneLine(value: unknown, max = 88): string {\n const text = String(value ?? '')\n .replaceAll(/\\s+/g, ' ')\n .trim();\n return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;\n}\n\nfunction describeToolCall(toolName: string, input: unknown): string {\n const args = (input ?? {}) as Record<string, unknown>;\n switch (toolName) {\n case 'spawn_agent':\n return `\u21C4 spawn ${args.agent_type} \"${args.task_name}\" \u2014 ${args.message}`;\n case 'send_message':\n return `\u21C4 mail ${args.target} \u2014 ${args.message}`;\n case 'followup_task':\n return `\u21C4 follow-up ${args.target} \u2014 ${args.message}`;\n case 'list_agents':\n return '\u21C4 list agents';\n default:\n return `\u00B7 ${toolName}`;\n }\n}\n\n/**\n * Render one turn stream as a conversation: assistant text streams raw, each\n * tool call becomes a single dim line, and failures become a single red line.\n * Reasoning shows up only as one dim ellipsis so silence never looks like a\n * hang. Everything else in the chunk vocabulary is deliberately dropped.\n */\nexport async function renderTurn(\n stream: ReadableStream<UIMessageChunk>,\n): Promise<void> {\n const toolNames = new Map<string, string>();\n let midText = false;\n let thinkingShown = false;\n const breakText = () => {\n if (midText) process.stdout.write('\\n');\n midText = false;\n };\n\n for await (const chunk of stream) {\n switch (chunk.type) {\n case 'reasoning-start':\n if (!thinkingShown) {\n console.log(dim('\u2026'));\n thinkingShown = true;\n }\n break;\n case 'text-delta':\n process.stdout.write(chunk.delta);\n midText = true;\n break;\n case 'text-end':\n breakText();\n break;\n case 'tool-input-available':\n toolNames.set(chunk.toolCallId, chunk.toolName);\n breakText();\n console.log(dim(describeToolCall(chunk.toolName, chunk.input)));\n break;\n case 'tool-output-error':\n breakText();\n console.log(\n red(\n `\u2717 ${toolNames.get(chunk.toolCallId) ?? 'tool'}: ${oneLine(chunk.errorText)}`,\n ),\n );\n break;\n case 'error':\n breakText();\n console.log(red(`\u2717 ${oneLine(chunk.errorText)}`));\n break;\n case 'abort':\n breakText();\n console.log(dim('\u00B7 turn aborted'));\n break;\n }\n }\n breakText();\n}\n", "import {\n type AgentSandbox,\n type DisposableSandbox,\n createBashTool,\n} from '@deepagents/context';\n\nimport type { SandboxContext } from '../agent.ts';\n\ntype WrapOptions = Omit<Parameters<typeof createBashTool>[0], 'sandbox'>;\n\nexport function defineSandbox(\n createBackend: (context: SandboxContext) => Promise<DisposableSandbox>,\n options?: WrapOptions,\n): (context: SandboxContext) => Promise<AgentSandbox> {\n return async (context) =>\n createBashTool({ sandbox: await createBackend(context), ...options });\n}\n", "import { type Tool, type ToolExecuteFunction, type ToolSet, tool } from 'ai';\n\nexport type ToolRecovery = 'idempotent';\n\nexport type ZukhrufTool<\n INPUT,\n OUTPUT,\n CONTEXT extends Record<string, unknown>,\n> = Tool<INPUT, OUTPUT, CONTEXT> & {\n /** Allows one automatic replay after a worker crash. */\n recovery?: ToolRecovery;\n};\n\nexport type ZukhrufToolSet = ToolSet &\n Record<string, { recovery?: ToolRecovery }>;\n\nexport function defineTool<\n INPUT,\n OUTPUT,\n CONTEXT extends Record<string, unknown>,\n>(\n definition: ZukhrufTool<INPUT, OUTPUT, CONTEXT> & {\n execute: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;\n },\n): ZukhrufTool<INPUT, OUTPUT, CONTEXT> & {\n execute: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;\n};\nexport function defineTool<\n INPUT,\n OUTPUT,\n CONTEXT extends Record<string, unknown>,\n>(\n definition: ZukhrufTool<INPUT, OUTPUT, CONTEXT>,\n): ZukhrufTool<INPUT, OUTPUT, CONTEXT>;\nexport function defineTool<INPUT, CONTEXT extends Record<string, unknown>>(\n definition: ZukhrufTool<INPUT, never, CONTEXT>,\n): ZukhrufTool<INPUT, never, CONTEXT>;\nexport function defineTool<OUTPUT, CONTEXT extends Record<string, unknown>>(\n definition: ZukhrufTool<never, OUTPUT, CONTEXT>,\n): ZukhrufTool<never, OUTPUT, CONTEXT>;\nexport function defineTool<CONTEXT extends Record<string, unknown>>(\n definition: ZukhrufTool<never, never, CONTEXT>,\n): ZukhrufTool<never, never, CONTEXT>;\nexport function defineTool(definition: unknown): unknown {\n return tool(definition as Tool);\n}\n"],
5
- "mappings": ";;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSA,eAAsB,qBACpB,OACA,QACuC;AACvC,QAAM,aACJ,MAAM,oBAAoB,eACtB,MAAM,mBAAmB,OAAO,OAAO,MAAM,IAC7C;AACN,MAAI,YAAY;AACd,WAAO;AAAA,MACL,oBAAoB;AAAA,QAClB,eAAe,MAAM;AAAA,QACrB,oBA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,YACZ,eAAe,EAAE,SAAS,MAAM,cAAc,OAAO,GAAG,GAAG,QAAQ,CAAC;AACxE;;;AChBA,SAA4D,QAAAC,aAAY;AA2CjE,SAAS,WAAW,YAA8B;AACvD,SAAOA,MAAK,UAAkB;AAChC;",
6
- "names": ["ContextEngine", "uuidv5", "chat", "uuidv5", "chat", "uuidv5", "uuidv5", "tool", "ContextEngine", "z", "z", "tool", "z", "z", "tool", "tool", "z", "tool", "z", "z", "tool", "tool", "z", "ContextEngine", "ContextEngine", "assistant", "uuidv5", "uuidv5", "assistant", "tool", "ContextEngine", "ContextEngine", "chat", "tool"]
3
+ "sources": ["../src/coding-agent-reminders/index.ts", "../src/coding-agent-reminders/evaluate.ts", "../src/coding-agent-reminders/io.ts", "../src/coding-agent-reminders/predicates/classifier.ts", "../src/coding-agent-reminders/predicates/combinators.ts", "../src/coding-agent-reminders/context.ts", "../src/coding-agent-reminders/predicates/content.ts", "../src/coding-agent-reminders/predicates/count.ts", "../src/coding-agent-reminders/predicates/environment.ts", "../src/coding-agent-reminders/predicates/event.ts", "../src/coding-agent-reminders/predicates/tool.ts", "../src/zukhruf/index.ts", "../src/zukhruf/agent.ts", "../src/zukhruf/control-plane/agent-path.ts", "../src/zukhruf/control-plane/agent-thread.ts", "../src/zukhruf/runtime/agent-runtime.ts", "../src/zukhruf/control-plane/agent-control-plane.ts", "../src/zukhruf/mailbox/types.ts", "../src/zukhruf/control-plane/agent-declaration-registry.ts", "../src/zukhruf/control-plane/agent-directory.ts", "../src/zukhruf/control-plane/agent-history-forker.ts", "../src/zukhruf/control-plane/agent-status-projector.ts", "../src/zukhruf/control-plane/agent-turn-id.ts", "../src/zukhruf/mailbox/coordinator.ts", "../src/zukhruf/multi-agent-v2-config.ts", "../src/zukhruf/runtime/agent-turn-executor.ts", "../src/zukhruf/collaboration/interrupt-agent.ts", "../src/zukhruf/collaboration/list-agents.ts", "../src/zukhruf/collaboration/message-tools.ts", "../src/zukhruf/collaboration/spawn-agent.ts", "../src/zukhruf/control-plane/fork-turns.ts", "../src/zukhruf/collaboration/wait-agent.ts", "../src/zukhruf/collaboration/collaboration-tools.ts", "../src/zukhruf/runtime/agent-skills.ts", "../src/zukhruf/runtime/approval-controller.ts", "../src/zukhruf/runtime/approval-job-id.ts", "../src/zukhruf/instructions.ts", "../src/zukhruf/mailbox/sqlite.store.ts", "../src/zukhruf/mailbox/store.ts", "../src/zukhruf/queue/pg-boss.turn-queue.ts", "../src/zukhruf/queue/turn-queue.ts", "../src/zukhruf/render-turn.ts", "../src/zukhruf/sandbox/define.ts", "../src/zukhruf/tool.ts"],
4
+ "sourcesContent": ["export * from './evaluate.ts';\nexport * from './io.ts';\nexport * from './predicates/index.ts';\nexport * from './types.ts';\n", "import type {\n ClaudeHookInput,\n ClaudeHookOutput,\n GuardRule,\n HookEventName,\n ReminderHookConfig,\n ReminderRule,\n} from './types.ts';\n\nexport async function evaluateReminderHook(\n input: ClaudeHookInput,\n config: ReminderHookConfig,\n): Promise<ClaudeHookOutput | undefined> {\n const guardMatch =\n input.hook_event_name === 'PreToolUse'\n ? await firstMatchingGuard(input, config.guards)\n : undefined;\n if (guardMatch) {\n return {\n hookSpecificOutput: {\n hookEventName: input.hook_event_name,\n permissionDecision: 'deny',\n permissionDecisionReason:\n guardMatch.errorReason ?? resolveGuardReason(guardMatch.rule, input),\n },\n };\n }\n\n if (\n input.stop_hook_active === true &&\n (input.hook_event_name === 'Stop' ||\n input.hook_event_name === 'SubagentStop')\n ) {\n return undefined;\n }\n\n const reminders = await matchingReminders(input, config.reminders);\n if (reminders.length === 0) return undefined;\n\n return {\n hookSpecificOutput: {\n hookEventName: input.hook_event_name,\n additionalContext: reminders.join('\\n\\n'),\n },\n };\n}\n\nasync function firstMatchingGuard(\n input: ClaudeHookInput,\n guards: GuardRule[],\n): Promise<{ rule: GuardRule; errorReason?: string } | undefined> {\n for (const rule of guards) {\n try {\n if (await rule.when(input)) return { rule };\n } catch (error) {\n console.error(`Guard \"${rule.id}\" predicate failed`, error);\n return {\n rule,\n errorReason: `Guard \"${rule.id}\" failed to evaluate; denying by default.`,\n };\n }\n }\n return undefined;\n}\n\nasync function matchingReminders(\n input: ClaudeHookInput,\n reminders: ReminderRule[],\n): Promise<string[]> {\n const matched: string[] = [];\n for (const rule of reminders) {\n if (!rule.events.includes(input.hook_event_name as HookEventName)) continue;\n try {\n if (!(await rule.when(input))) continue;\n matched.push(\n `[${rule.target}:${rule.id}]\\n${resolveText(rule.message, input)}`,\n );\n } catch (error) {\n console.error(`Reminder \"${rule.id}\" evaluation failed`, error);\n }\n }\n return matched;\n}\n\nfunction resolveText(\n value: string | ((ctx: ClaudeHookInput) => string),\n input: ClaudeHookInput,\n): string {\n return typeof value === 'function' ? value(input) : value;\n}\n\nfunction resolveGuardReason(rule: GuardRule, input: ClaudeHookInput): string {\n try {\n return resolveText(rule.deny, input);\n } catch (error) {\n console.error(`Guard \"${rule.id}\" denial message failed`, error);\n return `Guard \"${rule.id}\" matched but its denial message failed; denying by default.`;\n }\n}\n", "import type { ClaudeHookOutput } from './types.ts';\n\nexport async function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(Buffer.from(chunk));\n }\n return Buffer.concat(chunks).toString('utf8');\n}\n\nexport function writeOutput(output: ClaudeHookOutput): void {\n process.stdout.write(`${JSON.stringify(output)}\\n`);\n}\n", "import { Corpus } from 'tiny-tfidf';\n\nimport type {\n ClassifierMatch,\n ClassifierOptions,\n IClassifier,\n} from '../types.ts';\n\nexport class BM25Classifier<\n T extends { name: string; description: string },\n> implements IClassifier<T> {\n #corpus: Corpus;\n #itemsByName: Map<string, T>;\n\n constructor(items: T[]) {\n const names = items.map((item) => item.name);\n const texts = items.map((item) => `${item.name} ${item.description}`);\n this.#corpus = new Corpus(names, texts);\n this.#itemsByName = new Map(items.map((item) => [item.name, item]));\n }\n\n match(query: string, options?: ClassifierOptions): ClassifierMatch<T>[] {\n const topN = options?.topN ?? 5;\n const threshold = options?.threshold ?? 0;\n\n return this.#corpus\n .getResultsForQuery(query)\n .filter(([, score]: [string, number]) => score > threshold)\n .slice(0, topN)\n .map(([name, score]: [string, number]) => {\n const item = this.#itemsByName.get(name);\n if (!item) return null;\n return { item, score };\n })\n .filter((match): match is ClassifierMatch<T> => match !== null);\n }\n}\n", "import type { AsyncHookPredicate, HookPredicate } from '../types.ts';\n\nexport const always: HookPredicate = () => true;\n\nexport const and =\n (...predicates: HookPredicate[]): AsyncHookPredicate =>\n async (ctx) => {\n for (const predicate of predicates) {\n if (!(await predicate(ctx))) return false;\n }\n return true;\n };\n\nexport const or =\n (...predicates: HookPredicate[]): AsyncHookPredicate =>\n async (ctx) => {\n for (const predicate of predicates) {\n if (await predicate(ctx)) return true;\n }\n return false;\n };\n\nexport const not =\n (predicate: HookPredicate): AsyncHookPredicate =>\n async (ctx) =>\n !(await predicate(ctx));\n", "import type { ClaudeHookInput, ToolCallState, ToolNameSpec } from './types.ts';\n\nexport type NormalizedToolCall = {\n name: string;\n state: ToolCallState;\n input?: unknown;\n output?: unknown;\n errorText?: string;\n};\n\nexport function contentText(ctx: ClaudeHookInput): string {\n return [ctx.prompt, ctx.command_name, ctx.command_args]\n .filter((value): value is string => typeof value === 'string')\n .join(' ');\n}\n\nexport function bashCommand(ctx: ClaudeHookInput): string {\n if (ctx.tool_name !== 'Bash') return '';\n const command = ctx.tool_input?.command;\n return typeof command === 'string' ? command : '';\n}\n\nexport function outputText(ctx: ClaudeHookInput): string {\n if (ctx.hook_event_name === 'PostToolBatch' && ctx.tool_calls) {\n return ctx.tool_calls\n .map((call) => textOf(call.tool_response))\n .filter(Boolean)\n .join('\\n');\n }\n const output = ctx.tool_output ?? ctx.tool_response;\n return textOf(output);\n}\n\nexport function textOf(value: unknown): string {\n if (typeof value === 'string') return value;\n if (value === undefined) return '';\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nexport function toolCallsOf(ctx: ClaudeHookInput): NormalizedToolCall[] {\n if (ctx.hook_event_name === 'PostToolBatch' && ctx.tool_calls) {\n return ctx.tool_calls.map((call) => ({\n name: call.tool_name,\n state: 'output-available',\n input: call.tool_input,\n output: call.tool_response,\n }));\n }\n\n const calls: NormalizedToolCall[] = [];\n const toolName = ctx.tool_name;\n if (typeof toolName === 'string') {\n calls.push({\n name: toolName,\n state: stateOf(ctx.hook_event_name),\n input: ctx.tool_input,\n output: ctx.tool_output ?? ctx.tool_response,\n errorText: errorTextOf(ctx),\n });\n }\n return calls;\n}\n\nexport function matchesName(spec: ToolNameSpec, name: string): boolean {\n return typeof spec === 'function' ? spec(name) : spec === name;\n}\n\nfunction stateOf(eventName: string): ToolCallState {\n if (eventName === 'PostToolUseFailure') return 'output-error';\n if (eventName === 'PostToolUse') return 'output-available';\n return 'input-available';\n}\n\nfunction errorTextOf(ctx: ClaudeHookInput): string {\n const error =\n ctx.tool_error ??\n ctx.error ??\n ctx.reason ??\n ctx.tool_output ??\n ctx.tool_response;\n return textOf(error);\n}\n", "import { contentText } from '../context.ts';\nimport type {\n ClassifierOptions,\n ContentMatchesOptions,\n HookPredicate,\n IClassifier,\n} from '../types.ts';\nimport { BM25Classifier } from './classifier.ts';\n\nexport function contentMatches(\n topics: string[],\n options?: ContentMatchesOptions,\n): HookPredicate {\n const classifier = new BM25Classifier(\n topics.map((topic, index) => ({\n name: `t${index}`,\n description: topic,\n })),\n );\n return (ctx) =>\n classifier.match(contentText(ctx), {\n threshold: options?.threshold,\n }).length > 0;\n}\n\nexport function classifies<T>(\n classifier: IClassifier<T>,\n options?: ClassifierOptions,\n): HookPredicate {\n return (ctx) => classifier.match(contentText(ctx), options).length > 0;\n}\n\nexport function contentIncludes(keywords: string[]): HookPredicate {\n const lower = keywords.map((keyword) => keyword.toLowerCase());\n return (ctx) => {\n const text = contentText(ctx).toLowerCase();\n return lower.some((keyword) => text.includes(keyword));\n };\n}\n\nexport const contentPattern =\n (pattern: RegExp): HookPredicate =>\n (ctx) => {\n pattern.lastIndex = 0;\n return pattern.test(contentText(ctx));\n };\n\nexport const promptMatches = contentPattern;\n", "import type { CountSpec } from '../types.ts';\n\nexport function assertCountSpec(spec: CountSpec): void {\n const hasEq = spec.eq !== undefined;\n const hasRange = spec.gte !== undefined || spec.lte !== undefined;\n if (!hasEq && !hasRange) {\n throw new Error('CountSpec must include at least one of gte/lte/eq');\n }\n if (hasEq && hasRange) {\n throw new Error('CountSpec.eq cannot be combined with gte/lte');\n }\n}\n\nexport function checkCount(count: number, spec: CountSpec): boolean {\n if (spec.eq !== undefined) return count === spec.eq;\n if (spec.gte !== undefined && count < spec.gte) return false;\n if (spec.lte !== undefined && count > spec.lte) return false;\n return true;\n}\n", "import type { HookPredicate } from '../types.ts';\n\nexport const envFlag =\n (name: string): HookPredicate =>\n () =>\n process.env[name] === '1' || process.env[name] === 'true';\n", "import type { HookEventName, HookPredicate } from '../types.ts';\n\nexport const eventIs =\n (...events: HookEventName[]): HookPredicate =>\n (ctx) =>\n events.includes(ctx.hook_event_name as HookEventName);\n", "import {\n bashCommand,\n matchesName,\n outputText,\n textOf,\n toolCallsOf,\n} from '../context.ts';\nimport type {\n CountSpec,\n HookPredicate,\n ToolCallOptions,\n ToolNameSpec,\n} from '../types.ts';\nimport { assertCountSpec, checkCount } from './count.ts';\n\nexport const toolIs =\n (name: string): HookPredicate =>\n (ctx) =>\n ctx.tool_name === name;\n\nexport const bashCommandMatches =\n (pattern: RegExp): HookPredicate =>\n (ctx) => {\n pattern.lastIndex = 0;\n return pattern.test(bashCommand(ctx));\n };\n\nexport function toolCall(options: ToolCallOptions): HookPredicate {\n return (ctx) => {\n return toolCallsOf(ctx).some((call) => {\n if (options.state && call.state !== options.state) return false;\n if (options.name !== undefined && !matchesName(options.name, call.name)) {\n return false;\n }\n if (options.input && !options.input(call.input)) return false;\n if (options.output) {\n if (call.state !== 'output-available') return false;\n if (!options.output(call.output)) return false;\n }\n if (options.errorText) {\n if (call.state !== 'output-error') return false;\n if (!options.errorText(call.errorText ?? '')) return false;\n }\n return true;\n });\n };\n}\n\nexport function toolCalled(name: ToolNameSpec): HookPredicate {\n return toolCall({ name });\n}\n\nexport function toolFailed(name: ToolNameSpec): HookPredicate {\n return toolCall({ name, state: 'output-error' });\n}\n\nexport function anyToolCalled(): HookPredicate {\n return (ctx) => toolCallsOf(ctx).length > 0;\n}\n\nexport function toolCallCount(\n name: ToolNameSpec,\n spec: CountSpec,\n): HookPredicate {\n assertCountSpec(spec);\n return (ctx) =>\n checkCount(\n toolCallsOf(ctx).filter((call) => matchesName(name, call.name)).length,\n spec,\n );\n}\n\nexport const outputMatches =\n (pattern: RegExp): HookPredicate =>\n (ctx) => {\n pattern.lastIndex = 0;\n return pattern.test(outputText(ctx));\n };\n\nexport const toolOutputMatches = (pattern: RegExp): HookPredicate =>\n toolCall({\n output: (output) => {\n pattern.lastIndex = 0;\n return pattern.test(textOf(output));\n },\n });\n", "export * from './agent.ts';\nexport * from './control-plane/agent-path.ts';\nexport * from './control-plane/agent-thread.ts';\nexport type { TurnInput } from './control-plane/agent-control-plane.ts';\nexport * from './runtime/agent-runtime.ts';\nexport type { MultiAgentV2HostConfig } from './multi-agent-v2-config.ts';\nexport * from './instructions.ts';\nexport * from './mailbox/sqlite.store.ts';\nexport * from './mailbox/store.ts';\nexport * from './mailbox/types.ts';\nexport * from './queue/pg-boss.turn-queue.ts';\nexport * from './queue/turn-queue.ts';\nexport * from './render-turn.ts';\nexport * from './sandbox/define.ts';\nexport * from './tool.ts';\n", "import type { generateText } from 'ai';\n\nimport type {\n AgentModel,\n AgentSandbox,\n ContextFragment,\n} from '@deepagents/context';\n\nimport type { ZukhrufToolSet } from './tool.ts';\n\n/**\n * Sandboxes are per-chat: the factory receives the conversation identity so\n * the backend can be named by `chatId` and re-attached across turns, workers,\n * and restarts (the container engine is the registry \u2014 no in-memory state).\n */\nexport interface SandboxContext {\n chatId: string;\n userId: string;\n}\n\nexport type ZukhrufSandbox = AgentSandbox & {\n /** Absolute directory containing this conversation's files and skills. Omit to disable discovery. */\n readonly workingDirectory?: string;\n};\n\nexport interface AgentDeclaration {\n /**\n * Stable declaration identity persisted in conversation metadata.\n * It must be unique in one declaration graph and must not be renamed while\n * conversations created from that graph still exist.\n */\n name: string;\n model: AgentModel;\n sandbox: (context: SandboxContext) => Promise<ZukhrufSandbox>;\n instructions: ContextFragment[];\n tools?: ZukhrufToolSet;\n subagents?: AgentDeclaration[];\n telemetry?: Parameters<typeof generateText>[0]['telemetry'];\n}\n\nexport interface DefinedAgentDeclaration extends AgentDeclaration {\n tools: ZukhrufToolSet;\n subagents: AgentDeclaration[];\n}\n\nexport function defineAgent(\n declaration: AgentDeclaration,\n): DefinedAgentDeclaration {\n return {\n name: declaration.name,\n model: declaration.model,\n sandbox: declaration.sandbox,\n instructions: declaration.instructions,\n tools: declaration.tools ?? {},\n subagents: declaration.subagents ?? [],\n telemetry: declaration.telemetry,\n };\n}\n", "/** Canonical model-facing address for one agent in a Zukhruf tree. */\nexport class AgentPath {\n readonly #value: string;\n\n private constructor(value: string) {\n this.#value = value;\n }\n\n static root(): AgentPath {\n return new AgentPath('/root');\n }\n\n static parse(value: string): AgentPath {\n const path = value.trim();\n if (path !== '/root' && !path.startsWith('/root/')) {\n throw new Error(`agent path \"${value}\" must start at /root`);\n }\n\n const segments = path.slice(1).split('/');\n if (\n segments.some(\n (segment) =>\n segment.length === 0 ||\n segment !== segment.trim() ||\n segment === '.' ||\n segment === '..',\n )\n ) {\n throw new Error(`agent path \"${value}\" contains an invalid segment`);\n }\n return new AgentPath(path);\n }\n\n /** Relative targets name descendants; absolute targets keep their canonical path. */\n resolve(target: string): AgentPath {\n const requested = target.trim();\n if (!requested) throw new Error('agent path cannot be empty');\n return AgentPath.parse(\n requested.startsWith('/') ? requested : `${this.#value}/${requested}`,\n );\n }\n\n contains(candidate: AgentPath): boolean {\n return (\n this.equals(candidate) || candidate.#value.startsWith(`${this.#value}/`)\n );\n }\n\n equals(other: AgentPath): boolean {\n return this.#value === other.#value;\n }\n\n get isRoot(): boolean {\n return this.#value === '/root';\n }\n\n get parent(): AgentPath | null {\n if (this.isRoot) return null;\n return AgentPath.parse(this.#value.slice(0, this.#value.lastIndexOf('/')));\n }\n\n toString(): string {\n return this.#value;\n }\n}\n", "import type { ConversationId } from '../mailbox/types.ts';\nimport { AgentPath } from './agent-path.ts';\n\nexport interface AgentThreadOptions {\n conversation: ConversationId;\n treeId: string;\n path: AgentPath;\n parentChatId: string | null;\n declarationName: string;\n lastTurnId?: string;\n}\n\n/** Durable identity and persisted metadata for one agent instance. */\nexport class AgentThread {\n readonly conversation: ConversationId;\n readonly treeId: string;\n readonly path: AgentPath;\n readonly parentChatId: string | null;\n readonly declarationName: string;\n readonly lastTurnId?: string;\n\n constructor(options: AgentThreadOptions) {\n AgentThread.#assertTopology(options);\n this.conversation = options.conversation;\n this.treeId = options.treeId;\n this.path = options.path;\n this.parentChatId = options.parentChatId;\n this.declarationName = options.declarationName;\n this.lastTurnId = options.lastTurnId;\n }\n\n static root(\n conversation: ConversationId,\n declarationName: string,\n ): AgentThread {\n return new AgentThread({\n conversation,\n treeId: conversation.chatId,\n path: AgentPath.root(),\n parentChatId: null,\n declarationName,\n });\n }\n\n static metadataFilter(treeId: string): { key: string; value: string } {\n return { key: 'zukhrufTreeId', value: treeId };\n }\n\n static hasReservedMetadata(\n metadata: Record<string, unknown> | undefined,\n ): boolean {\n return Boolean(\n metadata &&\n (Object.hasOwn(metadata, 'zukhrufTreeId') ||\n Object.hasOwn(metadata, 'zukhruf')),\n );\n }\n\n static fromMetadata(\n conversation: ConversationId,\n metadata: Record<string, unknown> | undefined,\n ): AgentThread | undefined {\n const treeId = metadata?.zukhrufTreeId;\n const zukhruf = metadata?.zukhruf;\n if (typeof treeId !== 'string' || !AgentThread.#isRecord(zukhruf)) {\n return undefined;\n }\n\n const { path, parentChatId, declarationName, lastTurnId } = zukhruf;\n if (\n typeof path !== 'string' ||\n (parentChatId !== null && typeof parentChatId !== 'string') ||\n typeof declarationName !== 'string' ||\n (lastTurnId !== undefined && typeof lastTurnId !== 'string')\n ) {\n return undefined;\n }\n\n let parsedPath: AgentPath;\n try {\n parsedPath = AgentPath.parse(path);\n } catch {\n return undefined;\n }\n if (parsedPath.toString() !== path) return undefined;\n\n try {\n return new AgentThread({\n conversation,\n treeId,\n path: parsedPath,\n parentChatId,\n declarationName,\n ...(lastTurnId === undefined ? {} : { lastTurnId }),\n });\n } catch {\n return undefined;\n }\n }\n\n withLatestTurn(lastTurnId: string): AgentThread {\n return new AgentThread({\n conversation: this.conversation,\n treeId: this.treeId,\n path: this.path,\n parentChatId: this.parentChatId,\n declarationName: this.declarationName,\n lastTurnId,\n });\n }\n\n toMetadata(\n metadata: Record<string, unknown> | undefined,\n ): Record<string, unknown> {\n const existing = AgentThread.#isRecord(metadata?.zukhruf)\n ? metadata.zukhruf\n : {};\n return {\n ...metadata,\n zukhrufTreeId: this.treeId,\n zukhruf: {\n ...existing,\n path: this.path.toString(),\n parentChatId: this.parentChatId,\n declarationName: this.declarationName,\n ...(this.lastTurnId === undefined\n ? {}\n : { lastTurnId: this.lastTurnId }),\n },\n };\n }\n\n static #isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n }\n\n static #assertTopology(options: AgentThreadOptions): void {\n if (options.path.isRoot) {\n if (options.treeId !== options.conversation.chatId) {\n throw new Error('root agent thread treeId must match its chatId');\n }\n if (options.parentChatId !== null) {\n throw new Error('root agent thread cannot have a parent');\n }\n return;\n }\n if (options.parentChatId === null) {\n throw new Error('child agent thread requires a parent');\n }\n if (options.parentChatId === options.conversation.chatId) {\n throw new Error('child agent thread cannot parent itself');\n }\n }\n}\n", "import {\n ContextEngine,\n type ContextStore,\n type StreamManager,\n} from '@deepagents/context';\n\nimport type { AgentDeclaration } from '../agent.ts';\nimport {\n AgentControlPlane,\n type TurnInput,\n} from '../control-plane/agent-control-plane.ts';\nimport { AgentDeclarationRegistry } from '../control-plane/agent-declaration-registry.ts';\nimport { AgentDirectory } from '../control-plane/agent-directory.ts';\nimport { AgentHistoryForker } from '../control-plane/agent-history-forker.ts';\nimport { AgentStatusProjector } from '../control-plane/agent-status-projector.ts';\nimport { AgentTurnId } from '../control-plane/agent-turn-id.ts';\nimport { MailboxCoordinator } from '../mailbox/coordinator.ts';\nimport type { MailboxStore } from '../mailbox/store.ts';\nimport type {\n ConversationId,\n InterAgentCommunication,\n MessageDeliveryMode,\n} from '../mailbox/types.ts';\nimport {\n type MultiAgentV2HostConfig,\n resolveMultiAgentV2HostConfig,\n} from '../multi-agent-v2-config.ts';\nimport type { TurnQueue, TurnRef } from '../queue/turn-queue.ts';\nimport { AgentTurnExecutor } from './agent-turn-executor.ts';\nimport { ApprovalController } from './approval-controller.ts';\n\nexport interface AgentRuntimeOptions {\n store: ContextStore;\n /** Borrowed stream subsystem; the caller owns its store, change source, and lifecycle. */\n streams: StreamManager;\n queue: TurnQueue;\n /** Durable pending inter-agent input. Distinct from the TurnQueue scheduler. */\n mailboxStore: MailboxStore;\n /** Codex MultiAgentV2-compatible host guidance and tool configuration. */\n multiAgentV2?: MultiAgentV2HostConfig;\n}\n\nexport interface AgentRuntimeWorkOptions {\n concurrency?: number;\n}\n\n/** Reconnect and cancellation view over one durable conversation. */\nexport class AgentObservation {\n readonly engine: ContextEngine;\n readonly #conversation: ConversationId;\n readonly #store: ContextStore;\n readonly #streams: StreamManager;\n readonly #queue: TurnQueue;\n\n constructor(\n conversation: ConversationId,\n store: ContextStore,\n streams: StreamManager,\n queue: TurnQueue,\n ) {\n this.engine = new ContextEngine({\n store,\n chatId: conversation.chatId,\n userId: conversation.userId,\n });\n this.#conversation = conversation;\n this.#store = store;\n this.#streams = streams;\n this.#queue = queue;\n }\n\n async resume() {\n const id = await this.#headStreamId();\n if (!id) return null;\n AgentTurnId.assertOwner(this.#conversation, id);\n const status = await this.#streams.store.getStreamStatus(id);\n return status ? this.#streams.watch(id) : null;\n }\n\n async cancel(streamId?: string): Promise<void> {\n const chat = await this.#store.getChat(this.#conversation.chatId);\n if (chat && chat.userId !== this.#conversation.userId) {\n throw new Error(\n `chat \"${this.#conversation.chatId}\" belongs to user \"${chat.userId}\", not \"${this.#conversation.userId}\"`,\n );\n }\n const id = streamId ?? (await this.#headStreamId());\n if (!id) return;\n AgentTurnId.assertOwner(this.#conversation, id);\n const status = await this.#streams.store.getStreamStatus(id);\n if (status === 'queued' || status === 'running' || status === 'cancelled') {\n await this.#streams.cancel(id);\n await this.#queue.cancel(id);\n }\n }\n\n async #headStreamId(): Promise<string | undefined> {\n const head = await this.engine.headMessage();\n return head?.name === 'assistant' ? head.id : undefined;\n }\n}\n\n/** Thin host-facing composition and lifecycle fa\u00E7ade for a Zukhruf agent tree. */\nexport class AgentRuntime {\n readonly #store: ContextStore;\n readonly #queue: TurnQueue;\n readonly #streams: StreamManager;\n readonly #mailbox: MailboxCoordinator;\n readonly #directory: AgentDirectory;\n readonly #controlPlane: AgentControlPlane;\n readonly #approvals: ApprovalController;\n readonly #executor: AgentTurnExecutor;\n\n constructor(root: AgentDeclaration, options: AgentRuntimeOptions) {\n const multiAgentV2 = resolveMultiAgentV2HostConfig(options.multiAgentV2);\n const declarations = new AgentDeclarationRegistry(root);\n const directory = new AgentDirectory(options.store);\n const streams = options.streams;\n const mailbox = new MailboxCoordinator({\n store: options.mailboxStore,\n queue: options.queue,\n streams,\n });\n const approvals = new ApprovalController({\n store: options.store,\n queue: options.queue,\n });\n const statusProjector = new AgentStatusProjector({\n store: options.store,\n streams,\n queue: options.queue,\n mailbox,\n directory,\n approvals,\n });\n const historyForker = new AgentHistoryForker(options.store);\n const controlPlane = new AgentControlPlane({\n root,\n streams,\n queue: options.queue,\n mailbox,\n declarations,\n directory,\n statusProjector,\n historyForker,\n });\n\n this.#store = options.store;\n this.#queue = options.queue;\n this.#streams = streams;\n this.#mailbox = mailbox;\n this.#directory = directory;\n this.#controlPlane = controlPlane;\n this.#approvals = approvals;\n this.#executor = new AgentTurnExecutor({\n store: options.store,\n streams,\n controlPlane,\n mailbox,\n approvals,\n multiAgentV2,\n });\n }\n\n async enqueue(conversation: ConversationId, turn: TurnInput) {\n const streamId = await this.#controlPlane.enqueue(conversation, turn);\n return { id: streamId, stream: this.#streams.watch(streamId) };\n }\n\n async deliver(\n communication: InterAgentCommunication,\n mode: MessageDeliveryMode,\n ): Promise<void> {\n await this.#directory.assertOwnerIfExists(communication.recipient);\n await this.#mailbox.deliver(communication, mode);\n }\n\n approve(conversation: ConversationId, input: { toolCallId: string }) {\n return this.#approvals.approve(conversation, input);\n }\n\n deny(\n conversation: ConversationId,\n input: { toolCallId: string; reason?: string },\n ) {\n return this.#approvals.deny(conversation, input);\n }\n\n observe(conversation: ConversationId): AgentObservation {\n return new AgentObservation(\n conversation,\n this.#store,\n this.#streams,\n this.#queue,\n );\n }\n\n work(options?: AgentRuntimeWorkOptions): Promise<AsyncDisposable> {\n return this.#queue.consume(this.#executor.execute.bind(this.#executor), {\n concurrency: options?.concurrency,\n onOrphaned: this.#onOrphaned.bind(this),\n });\n }\n\n async #onOrphaned(turn: TurnRef, error: string): Promise<void> {\n try {\n let stream = await this.#streams.store.getStream(turn.streamId);\n const firstReconciliation =\n stream?.status === 'queued' || stream?.status === 'running';\n if (firstReconciliation) {\n await this.#streams.store.updateStreamStatus(turn.streamId, 'failed', {\n error,\n });\n stream = await this.#streams.store.getStream(turn.streamId);\n }\n let declaration: AgentDeclaration | undefined;\n if (\n (turn.kind === 'approval' ||\n (turn.kind === 'continuation' && turn.recovery !== 'idempotent')) &&\n stream?.status === 'failed'\n ) {\n try {\n ({ declaration } = await this.#controlPlane.resolve(turn));\n } catch {\n // Default terminal reconciliation below remains the safe fallback.\n }\n }\n if (\n declaration !== undefined &&\n (await this.#approvals.retryIdempotentContinuation(\n turn,\n turn.streamId,\n declaration.tools ?? {},\n ))\n ) {\n return;\n }\n if (\n (turn.kind === 'approval' || turn.kind === 'continuation') &&\n stream?.status === 'completed' &&\n (await this.#approvals.recoverUnstartedContinuation(\n turn,\n turn.streamId,\n ))\n ) {\n return;\n }\n stream = await this.#streams.store.getStream(turn.streamId);\n if (\n (turn.kind === 'approval' || turn.kind === 'continuation') &&\n (stream?.status === 'completed' ||\n stream?.status === 'failed' ||\n stream?.status === 'cancelled')\n ) {\n await this.#approvals.reconcileTerminalContinuation(\n turn,\n turn.streamId,\n stream.status,\n stream.error ?? error,\n );\n }\n const { thread } = await this.#controlPlane.resolve(turn);\n if (\n thread.lastTurnId === undefined ||\n thread.lastTurnId === turn.streamId\n ) {\n await this.#controlPlane.recordLatestTurnIfCurrent(\n turn,\n turn.streamId,\n thread.lastTurnId,\n );\n }\n await this.#controlPlane.projectTerminal(turn, thread);\n } finally {\n try {\n if (turn.kind === 'approval' || turn.kind === 'continuation') {\n await this.#queue.resumeParked(turn.chatId);\n }\n } finally {\n await this.#mailbox.endTurn(turn);\n }\n }\n }\n}\n", "import { v5 as uuidv5 } from 'uuid';\n\nimport type { StreamManager } from '@deepagents/context';\n\nimport type { AgentDeclaration } from '../agent.ts';\nimport type { MailboxCoordinator } from '../mailbox/coordinator.ts';\nimport type { ConversationId, MessageDeliveryMode } from '../mailbox/types.ts';\nimport {\n MessageDeliveryMode as DeliveryMode,\n InterAgentCommunicationType,\n createInterAgentCommunication,\n} from '../mailbox/types.ts';\nimport type { TurnQueue, TurnRef } from '../queue/turn-queue.ts';\nimport { AgentDeclarationRegistry } from './agent-declaration-registry.ts';\nimport { AgentDirectory } from './agent-directory.ts';\nimport { AgentHistoryForker } from './agent-history-forker.ts';\nimport {\n type AgentStatusProjector,\n type ListedAgent,\n} from './agent-status-projector.ts';\nimport type { AgentThread } from './agent-thread.ts';\nimport { AgentTurnId } from './agent-turn-id.ts';\nimport type { ForkTurns } from './fork-turns.ts';\n\nexport interface AgentControlPlaneOptions {\n root: AgentDeclaration;\n streams: StreamManager;\n queue: TurnQueue;\n mailbox: MailboxCoordinator;\n declarations: AgentDeclarationRegistry;\n directory: AgentDirectory;\n statusProjector: AgentStatusProjector;\n historyForker: AgentHistoryForker;\n}\n\nexport interface AgentActor {\n turn: TurnRef;\n thread: AgentThread;\n declaration: AgentDeclaration;\n}\n\nexport interface TurnInput {\n /** Caller-supplied idempotency key; enqueue returns its scoped durable id. */\n id: string;\n input: string;\n}\n\nexport interface SpawnAgentInput {\n agentType: string;\n taskName: string;\n message: string;\n forkTurns: ForkTurns;\n}\n\nexport interface SpawnAgentOutput {\n task_name: string;\n}\n\nexport type {\n ListedAgent,\n ListedAgentStatus,\n} from './agent-status-projector.ts';\n\n/** Application-level coordination for one declared agent tree. */\nexport class AgentControlPlane {\n readonly #root: AgentDeclaration;\n readonly #streams: StreamManager;\n readonly #queue: TurnQueue;\n readonly #mailbox: MailboxCoordinator;\n readonly #declarations: AgentDeclarationRegistry;\n readonly #directory: AgentDirectory;\n readonly #statusProjector: AgentStatusProjector;\n readonly #historyForker: AgentHistoryForker;\n\n constructor(options: AgentControlPlaneOptions) {\n this.#root = options.root;\n this.#streams = options.streams;\n this.#queue = options.queue;\n this.#mailbox = options.mailbox;\n this.#declarations = options.declarations;\n this.#directory = options.directory;\n this.#statusProjector = options.statusProjector;\n this.#historyForker = options.historyForker;\n }\n\n async resolve(conversation: ConversationId): Promise<{\n declaration: AgentDeclaration;\n thread: AgentThread;\n }> {\n const thread = await this.#directory.loadOrCreateRoot(\n conversation,\n this.#root.name,\n );\n const declaration = this.#declarations.get(thread.declarationName);\n if (!declaration) {\n throw new Error(\n `AgentControlPlane.resolve: unknown agent declaration \"${thread.declarationName}\"`,\n );\n }\n return { declaration, thread };\n }\n\n async enqueue(\n conversation: ConversationId,\n turn: TurnInput,\n ): Promise<string> {\n if (!turn.id.trim()) {\n throw new Error(\n 'enqueue: turn id is required \u2014 it names the ask, making retries idempotent',\n );\n }\n await this.#directory.assertOwnerIfExists(conversation);\n const streamId = AgentTurnId.fromRequest(conversation, turn.id).toString();\n await this.#streams.register(streamId);\n await this.#queue.push({\n kind: 'ask',\n streamId,\n chatId: conversation.chatId,\n userId: conversation.userId,\n input: turn.input,\n });\n return streamId;\n }\n\n recordLatestTurn(\n conversation: ConversationId,\n streamId: string,\n ): Promise<AgentThread> {\n return this.#directory.recordLatestTurn(conversation, streamId);\n }\n\n recordLatestTurnIfCurrent(\n conversation: ConversationId,\n streamId: string,\n expectedLastTurnId: string | undefined,\n ): Promise<AgentThread | undefined> {\n return this.#directory.recordLatestTurnIfCurrent(\n conversation,\n streamId,\n expectedLastTurnId,\n );\n }\n\n async spawn(\n actor: AgentActor,\n input: SpawnAgentInput,\n ): Promise<SpawnAgentOutput> {\n const childDeclaration = (actor.declaration.subagents ?? []).find(\n (subagent) => subagent.name === input.agentType,\n );\n if (!childDeclaration) {\n throw new Error(\n `spawn_agent: agent type \"${input.agentType}\" is not a subagent of \"${actor.declaration.name}\"`,\n );\n }\n\n let child: AgentThread;\n try {\n child = await this.#directory.createChild({\n parent: actor.thread,\n taskName: input.taskName,\n declarationName: childDeclaration.name,\n });\n } catch (error) {\n if (error instanceof Error && error.message.startsWith('agent path ')) {\n throw new Error(`spawn_agent: ${error.message}`);\n }\n throw error;\n }\n\n const childPath = child.path.toString();\n const requestId = AgentControlPlane.#initialTurnId(\n child.conversation.chatId,\n );\n const streamId = AgentTurnId.fromRequest(\n child.conversation,\n requestId,\n ).toString();\n const status = await this.#streams.store.getStreamStatus(streamId);\n if (\n status === 'completed' ||\n status === 'failed' ||\n status === 'cancelled'\n ) {\n throw new Error(\n `spawn_agent: agent path \"${childPath}\" already finished with status \"${status}\"`,\n );\n }\n await this.#historyForker.fork(actor.thread, child, input.forkTurns);\n await this.enqueue(child.conversation, {\n id: requestId,\n input: input.message,\n });\n return { task_name: childPath };\n }\n\n async sendMessage(\n actor: AgentActor,\n input: { target: string; message: string },\n ): Promise<{ target: string }> {\n return this.#deliverAgentMessage(actor, input, {\n type: InterAgentCommunicationType.Message,\n mode: DeliveryMode.QueueOnly,\n rejectRoot: false,\n });\n }\n\n async followupTask(\n actor: AgentActor,\n input: { target: string; message: string },\n ): Promise<{ target: string }> {\n return this.#deliverAgentMessage(actor, input, {\n type: InterAgentCommunicationType.NewTask,\n mode: DeliveryMode.TriggerTurn,\n rejectRoot: true,\n });\n }\n\n async listAgents(\n actor: AgentActor,\n pathPrefix?: string,\n ): Promise<{ agents: ListedAgent[] }> {\n const prefix = pathPrefix\n ? actor.thread.path.resolve(pathPrefix)\n : undefined;\n const threads = await this.#directory.listTree(actor.thread);\n const agents = await Promise.all(\n threads.flatMap((thread) => {\n if (prefix && !prefix.contains(thread.path)) return [];\n return [this.#statusProjector.projectListedAgent(actor.turn, thread)];\n }),\n );\n agents.sort((left, right) =>\n left.agent_name.localeCompare(right.agent_name),\n );\n return { agents };\n }\n\n async interruptAgent(\n actor: AgentActor,\n input: { target: string },\n ): Promise<{ previous_status: ListedAgent['agent_status'] }> {\n const target = await this.#directory.find(actor.thread, input.target);\n if (!target) return { previous_status: 'not_found' };\n if (target.path.isRoot) {\n throw new Error('interrupt_agent: the root agent cannot be interrupted');\n }\n if (target.path.equals(actor.thread.path)) {\n throw new Error('interrupt_agent: an agent cannot interrupt itself');\n }\n\n const previous = await this.#statusProjector.projectListedAgent(\n actor.turn,\n target,\n );\n const currentTurn = await this.#queue.getCurrentTurn(target.conversation);\n if (currentTurn) {\n const interruptedThread =\n (await this.#directory.recordLatestTurnIfCurrent(\n target.conversation,\n currentTurn.streamId,\n target.lastTurnId,\n )) ?? target;\n // Stream state is the durable execution authority. Transition it before\n // aborting scheduler delivery so a racing worker observes cancellation,\n // never an orphaned failure.\n await this.#streams.cancel(currentTurn.streamId);\n // Terminal mail has a deterministic id, so retrying this projection is\n // idempotent. Project before destructive queue cleanup: if mailbox\n // delivery fails, the still-discoverable scheduler receipt lets a later\n // interrupt_agent call retry instead of losing FINAL_ANSWER forever.\n await this.#statusProjector.projectTerminal(\n currentTurn,\n interruptedThread,\n );\n await this.#queue.cancel(currentTurn.streamId);\n }\n return { previous_status: previous.agent_status };\n }\n\n waitForMailbox(\n actor: AgentActor,\n options: { timeoutMs: number; signal?: AbortSignal },\n ): Promise<boolean> {\n return this.#mailbox.waitForPending(actor.thread.conversation, options);\n }\n\n async projectTerminal(turn: TurnRef, thread: AgentThread): Promise<void> {\n await this.#statusProjector.projectTerminal(turn, thread);\n }\n\n async #deliverAgentMessage(\n actor: AgentActor,\n input: { target: string; message: string },\n options: {\n type: InterAgentCommunicationType;\n mode: MessageDeliveryMode;\n rejectRoot: boolean;\n },\n ): Promise<{ target: string }> {\n const target = await this.#directory.resolve(actor.thread, input.target);\n if (options.rejectRoot && target.path.isRoot) {\n throw new Error(\n 'followup_task: the root agent cannot receive a follow-up',\n );\n }\n await this.#mailbox.deliver(\n createInterAgentCommunication({\n type: options.type,\n author: actor.thread.conversation,\n recipient: target.conversation,\n content: input.message,\n metadata: {\n authorPath: actor.thread.path.toString(),\n recipientPath: target.path.toString(),\n },\n }),\n options.mode,\n );\n return { target: target.path.toString() };\n }\n\n static #initialTurnId(chatId: string): string {\n return uuidv5(`urn:deepagents:zukhruf:initial-turn:${chatId}`, uuidv5.URL);\n }\n}\n", "import { randomUUID } from 'node:crypto';\n\n/** Durable thread identity; AgentPath is its model-facing address. */\nexport interface ConversationId {\n chatId: string;\n userId: string;\n}\n\nexport const MessageDeliveryMode = {\n QueueOnly: 'queue-only',\n TriggerTurn: 'trigger-turn',\n} as const;\n\nexport type MessageDeliveryMode =\n (typeof MessageDeliveryMode)[keyof typeof MessageDeliveryMode];\n\nexport const InterAgentCommunicationType = {\n Message: 'MESSAGE',\n NewTask: 'NEW_TASK',\n FinalAnswer: 'FINAL_ANSWER',\n} as const;\n\nexport type InterAgentCommunicationType =\n (typeof InterAgentCommunicationType)[keyof typeof InterAgentCommunicationType];\n\n/** A model-visible message sent from one independent agent thread to another. */\nexport interface InterAgentCommunication {\n id: string;\n type: InterAgentCommunicationType;\n author: ConversationId;\n recipient: ConversationId;\n otherRecipients: ConversationId[];\n content: string;\n metadata?: Record<string, unknown>;\n triggerTurn: boolean;\n}\n\nexport type NewInterAgentCommunication = Omit<\n InterAgentCommunication,\n 'id' | 'otherRecipients' | 'triggerTurn' | 'type'\n> & {\n id?: string;\n otherRecipients?: ConversationId[];\n type?: InterAgentCommunicationType;\n};\n\nexport function createInterAgentCommunication(\n communication: NewInterAgentCommunication,\n): InterAgentCommunication {\n const value: InterAgentCommunication = {\n ...communication,\n id: communication.id ?? randomUUID(),\n type: communication.type ?? InterAgentCommunicationType.Message,\n otherRecipients: communication.otherRecipients ?? [],\n triggerTurn: false,\n };\n assertCommunication(value);\n return value;\n}\n\nexport function assertCommunication(\n communication: InterAgentCommunication,\n): void {\n if (!communication.id.trim()) {\n throw new Error('inter-agent communication id cannot be empty');\n }\n if (\n !Object.values(InterAgentCommunicationType).includes(communication.type)\n ) {\n throw new Error('inter-agent communication type is invalid');\n }\n assertConversationId(communication.author, 'author');\n assertConversationId(communication.recipient, 'recipient');\n for (const recipient of communication.otherRecipients) {\n assertConversationId(recipient, 'other recipient');\n }\n if (!communication.content.trim()) {\n throw new Error('inter-agent communication content cannot be empty');\n }\n}\n\nfunction assertConversationId(value: ConversationId, label: string): void {\n if (!value.chatId.trim() || !value.userId.trim()) {\n throw new Error(\n `inter-agent communication ${label} requires chatId and userId`,\n );\n }\n}\n", "import type { AgentDeclaration } from '../agent.ts';\n\n/** Immutable declaration lookup compiled once for one agent runtime. */\nexport class AgentDeclarationRegistry {\n readonly root: AgentDeclaration;\n\n readonly #declarations = new Map<string, AgentDeclaration>();\n\n constructor(root: AgentDeclaration) {\n this.root = root;\n this.#register(root, new Set());\n }\n\n get(name: string): AgentDeclaration | undefined {\n return this.#declarations.get(name);\n }\n\n #register(\n declaration: AgentDeclaration,\n visited: Set<AgentDeclaration>,\n ): void {\n if (visited.has(declaration)) return;\n visited.add(declaration);\n\n if (!declaration.name.trim()) {\n throw new Error('AgentRuntime: agent declaration name cannot be empty');\n }\n if (declaration.name !== declaration.name.trim()) {\n throw new Error(\n `AgentRuntime: agent declaration name \"${declaration.name}\" must not contain surrounding whitespace`,\n );\n }\n\n const existing = this.#declarations.get(declaration.name);\n if (existing && existing !== declaration) {\n throw new Error(\n `AgentRuntime: duplicate agent declaration name \"${declaration.name}\"`,\n );\n }\n this.#declarations.set(declaration.name, declaration);\n\n for (const subagent of declaration.subagents ?? []) {\n this.#register(subagent, visited);\n }\n }\n}\n", "import { v5 as uuidv5 } from 'uuid';\n\nimport type { ContextStore } from '@deepagents/context';\n\nimport type { ConversationId } from '../mailbox/types.ts';\nimport { AgentThread } from './agent-thread.ts';\n\n/** ContextStore-backed directory of durable agent instances. */\nexport class AgentDirectory {\n readonly #store: ContextStore;\n\n constructor(store: ContextStore) {\n this.#store = store;\n }\n\n async assertOwnerIfExists(conversation: ConversationId): Promise<void> {\n const chat = await this.#store.getChat(conversation.chatId);\n if (!chat) return;\n this.#assertOwner(conversation, chat.userId);\n const thread = this.#threadFromMetadata(conversation, chat.metadata);\n if (thread) await this.#assertValidParent(thread);\n }\n\n async load(conversation: ConversationId): Promise<AgentThread | undefined> {\n const chat = await this.#store.getChat(conversation.chatId);\n if (chat) this.#assertOwner(conversation, chat.userId);\n if (!chat) return undefined;\n const thread = this.#threadFromMetadata(conversation, chat.metadata);\n if (thread) await this.#assertValidParent(thread);\n return thread;\n }\n\n async loadOrCreateRoot(\n conversation: ConversationId,\n declarationName: string,\n ): Promise<AgentThread> {\n await this.#store.upsertChat({\n id: conversation.chatId,\n userId: conversation.userId,\n });\n let thread!: AgentThread;\n let adopted = false;\n await this.#store.updateChat(conversation.chatId, (chat) => {\n this.#assertOwner(conversation, chat.userId);\n const existing = this.#threadFromMetadata(conversation, chat.metadata);\n if (existing) {\n thread = existing;\n adopted = true;\n return undefined;\n }\n thread = AgentThread.root(conversation, declarationName);\n adopted = false;\n return { metadata: thread.toMetadata(chat.metadata) };\n });\n if (adopted) {\n await this.#assertValidParent(thread);\n }\n return thread;\n }\n\n async recordLatestTurn(\n conversation: ConversationId,\n streamId: string,\n ): Promise<AgentThread> {\n return this.#updateLatestTurn(conversation, streamId);\n }\n\n async recordLatestTurnIfCurrent(\n conversation: ConversationId,\n streamId: string,\n expectedLastTurnId: string | undefined,\n ): Promise<AgentThread | undefined> {\n return this.#updateLatestTurn(conversation, streamId, expectedLastTurnId);\n }\n\n async listTree(thread: AgentThread): Promise<AgentThread[]> {\n const chats = await this.#store.listChats({\n userId: thread.conversation.userId,\n metadata: AgentThread.metadataFilter(thread.treeId),\n });\n return Promise.all(\n chats.map(async (chat) => {\n const conversation = { chatId: chat.id, userId: chat.userId };\n const member = this.#threadFromMetadata(conversation, chat.metadata);\n if (!member) {\n throw new Error(\n `AgentDirectory.listTree: chat \"${chat.id}\" is missing Zukhruf metadata`,\n );\n }\n await this.#assertValidParent(member);\n return member;\n }),\n );\n }\n\n async resolve(thread: AgentThread, target: string): Promise<AgentThread> {\n const path = thread.path.resolve(target);\n const match = await this.find(thread, target);\n if (match) return match;\n throw new Error(`agent path \"${path}\" does not exist in this tree`);\n }\n\n async find(\n thread: AgentThread,\n target: string,\n ): Promise<AgentThread | undefined> {\n const path = thread.path.resolve(target);\n return (await this.listTree(thread)).find((candidate) =>\n candidate.path.equals(path),\n );\n }\n\n async createChild(options: {\n parent: AgentThread;\n taskName: string;\n declarationName: string;\n }): Promise<AgentThread> {\n const path = options.parent.path.resolve(options.taskName);\n const pathString = path.toString();\n const conversation = {\n chatId: AgentDirectory.#childChatId(\n options.parent.conversation.userId,\n options.parent.treeId,\n pathString,\n ),\n userId: options.parent.conversation.userId,\n };\n const occupied = (await this.listTree(options.parent)).find((thread) =>\n thread.path.equals(path),\n );\n if (occupied && occupied.conversation.chatId !== conversation.chatId) {\n throw new Error(`agent path \"${pathString}\" already exists`);\n }\n\n const child = new AgentThread({\n conversation,\n treeId: options.parent.treeId,\n path,\n parentChatId: options.parent.conversation.chatId,\n declarationName: options.declarationName,\n });\n const storedChat = await this.#store.upsertChat({\n id: conversation.chatId,\n userId: conversation.userId,\n metadata: child.toMetadata(undefined),\n });\n const stored = AgentThread.fromMetadata(\n { chatId: storedChat.id, userId: storedChat.userId },\n storedChat.metadata,\n );\n if (\n storedChat.userId !== conversation.userId ||\n stored?.treeId !== child.treeId ||\n !stored.path.equals(child.path) ||\n stored.parentChatId !== child.parentChatId ||\n stored.declarationName !== child.declarationName\n ) {\n throw new Error(`agent path \"${pathString}\" already exists`);\n }\n return stored;\n }\n\n static #childChatId(userId: string, treeId: string, path: string): string {\n return uuidv5(\n `urn:deepagents:zukhruf:agent:${JSON.stringify([userId, treeId, path])}`,\n uuidv5.URL,\n );\n }\n\n #assertOwner(conversation: ConversationId, storedUserId: string): void {\n if (storedUserId === conversation.userId) return;\n throw new Error(\n `chat \"${conversation.chatId}\" belongs to user \"${storedUserId}\", not \"${conversation.userId}\"`,\n );\n }\n\n #threadFromMetadata(\n conversation: ConversationId,\n metadata: Record<string, unknown> | undefined,\n ): AgentThread | undefined {\n const thread = AgentThread.fromMetadata(conversation, metadata);\n if (!thread && AgentThread.hasReservedMetadata(metadata)) {\n throw new Error(\n `invalid Zukhruf metadata for chat \"${conversation.chatId}\"`,\n );\n }\n return thread;\n }\n\n async #assertValidParent(thread: AgentThread): Promise<void> {\n if (thread.path.isRoot) return;\n const parentChatId = thread.parentChatId;\n if (!parentChatId) {\n throw new Error(\n `invalid Zukhruf parent for chat \"${thread.conversation.chatId}\"`,\n );\n }\n const parentChat = await this.#store.getChat(parentChatId);\n if (!parentChat || parentChat.userId !== thread.conversation.userId) {\n throw new Error(\n `invalid Zukhruf parent for chat \"${thread.conversation.chatId}\"`,\n );\n }\n const parent = this.#threadFromMetadata(\n { chatId: parentChat.id, userId: parentChat.userId },\n parentChat.metadata,\n );\n const expectedPath = thread.path.parent;\n if (\n !parent ||\n !expectedPath ||\n parent.treeId !== thread.treeId ||\n !parent.path.equals(expectedPath)\n ) {\n throw new Error(\n `invalid Zukhruf parent for chat \"${thread.conversation.chatId}\"`,\n );\n }\n }\n\n async #updateLatestTurn(\n conversation: ConversationId,\n streamId: string,\n expectedLastTurnId?: string,\n ): Promise<AgentThread>;\n async #updateLatestTurn(\n conversation: ConversationId,\n streamId: string,\n expectedLastTurnId: string | undefined,\n ): Promise<AgentThread | undefined>;\n async #updateLatestTurn(\n conversation: ConversationId,\n streamId: string,\n ...expected: [string | undefined] | []\n ): Promise<AgentThread | undefined> {\n let result: AgentThread | undefined;\n await this.#store.updateChat(conversation.chatId, (chat) => {\n this.#assertOwner(conversation, chat.userId);\n const thread = this.#threadFromMetadata(conversation, chat.metadata);\n if (!thread) {\n throw new Error(\n `AgentDirectory.recordLatestTurn: missing agent metadata for chat \"${conversation.chatId}\"`,\n );\n }\n if (expected.length > 0 && thread.lastTurnId !== expected[0]) {\n result = undefined;\n return undefined;\n }\n if (thread.lastTurnId === streamId) {\n result = thread;\n return undefined;\n }\n result = thread.withLatestTurn(streamId);\n return { metadata: result.toMetadata(chat.metadata) };\n });\n return result;\n }\n}\n", "import { type UIMessage, validateUIMessages } from 'ai';\nimport { v5 as uuidv5 } from 'uuid';\n\nimport {\n type ContextStore,\n type MessageData,\n isSyntheticReminderMessage,\n} from '@deepagents/context';\n\nimport type { AgentThread } from './agent-thread.ts';\nimport type { ForkTurns } from './fork-turns.ts';\n\ninterface HistoryForkRecord {\n forkTurns: ForkTurns;\n parentChatId: string;\n parentHeadMessageId: string | null;\n sourceMessageIds?: string[];\n}\n\ninterface SourceMessage {\n stored: MessageData;\n message: UIMessage;\n}\n\n/** Copies a stable, filtered parent-history snapshot into a new child chat. */\nexport class AgentHistoryForker {\n readonly #store: ContextStore;\n\n constructor(store: ContextStore) {\n this.#store = store;\n }\n\n async fork(\n parent: AgentThread,\n child: AgentThread,\n forkTurns: ForkTurns,\n ): Promise<void> {\n const record = await this.#claim(parent, child, forkTurns);\n if (record.forkTurns === 'none' || record.parentHeadMessageId === null) {\n return;\n }\n\n const selected = await this.#selectedMessages(parent, child, record);\n if (selected.length === 0) return;\n\n const cloned = this.#cloneMessages(child, selected);\n const expectedIds = cloned.map((message) => message.id);\n const branch = await this.#store.getActiveBranch(child.conversation.chatId);\n if (!branch) {\n throw new Error(\n `spawn_agent: child chat \"${child.conversation.chatId}\" has no active branch`,\n );\n }\n if (branch.headMessageId !== null) {\n if (await this.#hasForkedPrefix(child, expectedIds)) return;\n throw new Error(\n `spawn_agent: cannot apply parent history after child \"${child.path}\" has started`,\n );\n }\n\n const head = cloned.at(-1);\n if (!head) return;\n await this.#store.addMessages(cloned);\n const committed = await this.#store.updateBranchHead(\n branch.id,\n head.id,\n null,\n );\n if (!committed && !(await this.#hasForkedPrefix(child, expectedIds))) {\n throw new Error(\n `spawn_agent: child \"${child.path}\" started before parent history was applied`,\n );\n }\n if (!(await this.#hasForkedPrefix(child, expectedIds))) {\n throw new Error(\n `spawn_agent: failed to persist parent history for child \"${child.path}\"`,\n );\n }\n }\n\n async #claim(\n parent: AgentThread,\n child: AgentThread,\n forkTurns: ForkTurns,\n ): Promise<HistoryForkRecord> {\n const parentBranch = await this.#store.getActiveBranch(\n parent.conversation.chatId,\n );\n if (!parentBranch) {\n throw new Error(\n `spawn_agent: parent chat \"${parent.conversation.chatId}\" has no active branch`,\n );\n }\n const proposed: HistoryForkRecord = {\n forkTurns,\n parentChatId: parent.conversation.chatId,\n parentHeadMessageId:\n forkTurns === 'none' ? null : parentBranch.headMessageId,\n };\n let claimed: HistoryForkRecord | undefined;\n\n await this.#store.updateChat(child.conversation.chatId, (chat) => {\n const metadata = chat.metadata;\n const zukhruf = metadata?.zukhruf;\n if (!isRecord(zukhruf)) {\n throw new Error(\n `spawn_agent: child chat \"${child.conversation.chatId}\" is missing Zukhruf metadata`,\n );\n }\n\n if (zukhruf.historyFork !== undefined) {\n claimed = parseHistoryForkRecord(zukhruf.historyFork);\n if (\n claimed.parentChatId !== proposed.parentChatId ||\n claimed.forkTurns !== proposed.forkTurns\n ) {\n throw new Error(\n `spawn_agent: agent path \"${child.path}\" already exists with a different fork_turns setting`,\n );\n }\n return undefined;\n }\n\n claimed = proposed;\n return {\n metadata: {\n ...metadata,\n zukhruf: { ...zukhruf, historyFork: proposed },\n },\n };\n });\n\n if (!claimed) {\n throw new Error(\n `spawn_agent: failed to claim history for child \"${child.path}\"`,\n );\n }\n return claimed;\n }\n\n async #sourceMessages(\n parent: AgentThread,\n record: HistoryForkRecord,\n ): Promise<SourceMessage[]> {\n const headId = record.parentHeadMessageId;\n if (headId === null) return [];\n\n const chain = await this.#store.getMessageChain(headId);\n if (chain.at(-1)?.id !== headId) {\n throw new Error(\n `spawn_agent: parent history head \"${headId}\" is unavailable`,\n );\n }\n if (\n chain.some((message) => message.chatId !== parent.conversation.chatId)\n ) {\n throw new Error('spawn_agent: parent history crosses chat boundaries');\n }\n\n const materialized = chain.filter(\n (message) => !isEmptyAssistantPlaceholder(message.data),\n );\n const messages = await validateUIMessages({\n messages: materialized.map((message) => message.data),\n });\n return materialized.map((stored, index) => {\n const message = messages[index];\n if (message.id !== stored.id) {\n throw new Error(\n `spawn_agent: stored message \"${stored.id}\" has a mismatched payload id`,\n );\n }\n return { stored, message };\n });\n }\n\n async #selectedMessages(\n parent: AgentThread,\n child: AgentThread,\n record: HistoryForkRecord,\n ): Promise<SourceMessage[]> {\n if (record.forkTurns === 'none') return [];\n if (record.sourceMessageIds !== undefined) {\n return this.#messagesById(parent, record.sourceMessageIds);\n }\n\n const source = await this.#sourceMessages(parent, record);\n const selected = this.#select(source, record.forkTurns)\n .map((entry) => this.#keepHistoryMessage(entry))\n .filter((entry): entry is SourceMessage => entry !== undefined);\n const sourceMessageIds = await this.#claimSelection(\n child,\n selected.map(({ stored }) => stored.id),\n );\n return arraysEqual(\n sourceMessageIds,\n selected.map(({ stored }) => stored.id),\n )\n ? selected\n : this.#messagesById(parent, sourceMessageIds);\n }\n\n async #messagesById(\n parent: AgentThread,\n sourceMessageIds: string[],\n ): Promise<SourceMessage[]> {\n const storedMessages = await Promise.all(\n sourceMessageIds.map((id) => this.#store.getMessage(id)),\n );\n if (\n storedMessages.some(\n (message) =>\n message === undefined ||\n message.chatId !== parent.conversation.chatId,\n )\n ) {\n throw new Error(\n 'spawn_agent: persisted parent-history snapshot is unavailable',\n );\n }\n const stored = storedMessages as MessageData[];\n const messages = await validateUIMessages({\n messages: stored.map((message) => message.data),\n });\n return stored.map((messageData, index) => {\n const source = this.#keepHistoryMessage({\n stored: messageData,\n message: messages[index],\n });\n if (!source || source.message.id !== messageData.id) {\n throw new Error(\n `spawn_agent: persisted parent-history message \"${messageData.id}\" changed shape`,\n );\n }\n return source;\n });\n }\n\n async #claimSelection(\n child: AgentThread,\n proposedIds: string[],\n ): Promise<string[]> {\n let sourceMessageIds: string[] | undefined;\n await this.#store.updateChat(child.conversation.chatId, (chat) => {\n const metadata = chat.metadata;\n const zukhruf = metadata?.zukhruf;\n if (!isRecord(zukhruf)) {\n throw new Error(\n `spawn_agent: child chat \"${child.conversation.chatId}\" is missing Zukhruf metadata`,\n );\n }\n const record = parseHistoryForkRecord(zukhruf.historyFork);\n if (record.sourceMessageIds !== undefined) {\n sourceMessageIds = record.sourceMessageIds;\n return undefined;\n }\n\n sourceMessageIds = proposedIds;\n return {\n metadata: {\n ...metadata,\n zukhruf: {\n ...zukhruf,\n historyFork: { ...record, sourceMessageIds: proposedIds },\n },\n },\n };\n });\n if (!sourceMessageIds) {\n throw new Error(\n `spawn_agent: failed to claim parent-history messages for child \"${child.path}\"`,\n );\n }\n return sourceMessageIds;\n }\n\n #select(source: SourceMessage[], forkTurns: Exclude<ForkTurns, 'none'>) {\n if (forkTurns === 'all') return source;\n\n const boundaries = source.flatMap((entry, index) =>\n isForkTurnBoundary(entry.message) ? [index] : [],\n );\n const start = boundaries.at(-forkTurns) ?? boundaries[0];\n return start === undefined ? [] : source.slice(start);\n }\n\n #keepHistoryMessage(entry: SourceMessage): SourceMessage | undefined {\n const { message } = entry;\n if (message.role === 'user') {\n if (\n isSyntheticReminderMessage(message) ||\n interAgentCommunication(message) !== undefined\n ) {\n return undefined;\n }\n return entry;\n }\n if (message.role !== 'assistant') return undefined;\n\n const finalStepStart = message.parts.findLastIndex(\n (part) => part.type === 'step-start',\n );\n const parts = message.parts\n .slice(finalStepStart + 1)\n .filter((part) =>\n ['text', 'file', 'source-url', 'source-document'].includes(part.type),\n );\n return parts.length === 0\n ? undefined\n : { ...entry, message: { ...message, parts } };\n }\n\n #cloneMessages(child: AgentThread, selected: SourceMessage[]): MessageData[] {\n let parentId: string | null = null;\n return selected.map(({ stored, message }) => {\n const id = uuidv5(\n `urn:deepagents:zukhruf:forked-message:${JSON.stringify([\n child.conversation.chatId,\n stored.id,\n ])}`,\n uuidv5.URL,\n );\n const clone: MessageData = {\n id,\n chatId: child.conversation.chatId,\n parentId,\n name: message.role,\n type: 'message',\n data: { ...message, id },\n createdAt: stored.createdAt,\n };\n parentId = id;\n return clone;\n });\n }\n\n async #hasForkedPrefix(\n child: AgentThread,\n expectedIds: string[],\n ): Promise<boolean> {\n const branch = await this.#store.getActiveBranch(child.conversation.chatId);\n if (!branch?.headMessageId) return false;\n const chain = await this.#store.getMessageChain(branch.headMessageId);\n return expectedIds.every(\n (id, index) =>\n chain[index]?.id === id &&\n chain[index]?.chatId === child.conversation.chatId,\n );\n }\n}\n\nfunction isForkTurnBoundary(message: UIMessage): boolean {\n if (message.role !== 'user' || isSyntheticReminderMessage(message)) {\n return false;\n }\n return interAgentCommunication(message)?.triggerTurn ?? true;\n}\n\nfunction interAgentCommunication(\n message: UIMessage,\n): { triggerTurn: boolean } | undefined {\n if (!isRecord(message.metadata)) return undefined;\n if (!Object.hasOwn(message.metadata, 'interAgentCommunication')) {\n return undefined;\n }\n const communication = message.metadata.interAgentCommunication;\n if (\n !isRecord(communication) ||\n typeof communication.triggerTurn !== 'boolean'\n ) {\n throw new Error(\n `spawn_agent: message \"${message.id}\" has invalid inter-agent metadata`,\n );\n }\n return { triggerTurn: communication.triggerTurn };\n}\n\nfunction parseHistoryForkRecord(value: unknown): HistoryForkRecord {\n if (!isRecord(value)) {\n throw new Error('spawn_agent: invalid persisted history-fork metadata');\n }\n const { forkTurns, parentChatId, parentHeadMessageId, sourceMessageIds } =\n value;\n if (\n !isForkTurns(forkTurns) ||\n typeof parentChatId !== 'string' ||\n !parentChatId.trim() ||\n (parentHeadMessageId !== null &&\n (typeof parentHeadMessageId !== 'string' ||\n parentHeadMessageId.length === 0)) ||\n (sourceMessageIds !== undefined &&\n (!Array.isArray(sourceMessageIds) ||\n !sourceMessageIds.every(\n (id): id is string => typeof id === 'string' && id.trim().length > 0,\n ) ||\n new Set(sourceMessageIds).size !== sourceMessageIds.length))\n ) {\n throw new Error('spawn_agent: invalid persisted history-fork metadata');\n }\n return {\n forkTurns,\n parentChatId,\n parentHeadMessageId,\n ...(sourceMessageIds === undefined ? {} : { sourceMessageIds }),\n };\n}\n\nfunction isForkTurns(value: unknown): value is ForkTurns {\n return (\n value === 'none' ||\n value === 'all' ||\n (typeof value === 'number' && Number.isSafeInteger(value) && value > 0)\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isEmptyAssistantPlaceholder(value: unknown): boolean {\n return (\n isRecord(value) &&\n typeof value.id === 'string' &&\n value.role === 'assistant' &&\n Array.isArray(value.parts) &&\n value.parts.length === 0\n );\n}\n\nfunction arraysEqual(left: string[], right: string[]): boolean {\n return (\n left.length === right.length &&\n left.every((value, index) => value === right[index])\n );\n}\n", "import { type UIMessage, isTextUIPart } from 'ai';\nimport { z } from 'zod';\n\nimport {\n ContextEngine,\n type ContextStore,\n type StreamManager,\n type StreamStatus,\n} from '@deepagents/context';\n\nimport type { MailboxCoordinator } from '../mailbox/coordinator.ts';\nimport {\n InterAgentCommunicationType,\n MessageDeliveryMode,\n createInterAgentCommunication,\n} from '../mailbox/types.ts';\nimport type { TurnQueue, TurnRef } from '../queue/turn-queue.ts';\nimport type { ApprovalController } from '../runtime/approval-controller.ts';\nimport type { AgentDirectory } from './agent-directory.ts';\nimport type { AgentThread } from './agent-thread.ts';\n\nexport const listedAgentStatusSchema = z.union([\n z.enum(['pending_init', 'running', 'interrupted', 'shutdown', 'not_found']),\n z.object({ completed: z.string().nullable() }).strict(),\n z.object({ errored: z.string() }).strict(),\n]);\n\nexport type ListedAgentStatus = z.infer<typeof listedAgentStatusSchema>;\n\nexport const listedAgentSchema = z\n .object({\n agent_name: z.string(),\n agent_status: listedAgentStatusSchema,\n })\n .strict();\n\nexport type ListedAgent = z.infer<typeof listedAgentSchema>;\n\nexport interface AgentStatusProjectorOptions {\n store: ContextStore;\n streams: StreamManager;\n queue: TurnQueue;\n mailbox: MailboxCoordinator;\n directory: AgentDirectory;\n approvals: ApprovalController;\n}\n\n/** Projects durable execution state into agent-facing status and terminal mail. */\nexport class AgentStatusProjector {\n readonly #store: ContextStore;\n readonly #streams: StreamManager;\n readonly #queue: TurnQueue;\n readonly #mailbox: MailboxCoordinator;\n readonly #directory: AgentDirectory;\n readonly #approvals: ApprovalController;\n\n constructor(options: AgentStatusProjectorOptions) {\n this.#store = options.store;\n this.#streams = options.streams;\n this.#queue = options.queue;\n this.#mailbox = options.mailbox;\n this.#directory = options.directory;\n this.#approvals = options.approvals;\n }\n\n async projectListedAgent(\n currentTurn: TurnRef,\n thread: AgentThread,\n ): Promise<ListedAgent> {\n const messages = await this.#messages(thread);\n const head = messages.at(-1);\n const streamId =\n thread.lastTurnId ?? (head?.role === 'assistant' ? head.id : undefined);\n const stream = streamId\n ? await this.#streams.store.getStream(streamId)\n : undefined;\n const scheduledTurn = await this.#queue.getCurrentTurn(thread.conversation);\n const scheduledStream = scheduledTurn\n ? await this.#streams.store.getStream(scheduledTurn.streamId)\n : undefined;\n let status = AgentStatusProjector.#listedStatus(\n stream?.status,\n stream?.error,\n head,\n );\n if (stream?.status === 'completed' && this.#approvals.isPaused(head)) {\n status = 'running';\n }\n if (\n thread.conversation.chatId === currentTurn.chatId ||\n (thread.lastTurnId !== undefined &&\n scheduledTurn?.streamId !== thread.lastTurnId &&\n (scheduledStream?.status === 'queued' ||\n scheduledStream?.status === 'running'))\n ) {\n status = 'running';\n }\n\n return {\n agent_name: thread.path.toString(),\n agent_status: status,\n };\n }\n\n async projectTerminal(turn: TurnRef, thread: AgentThread): Promise<void> {\n if (thread.parentChatId === null) return;\n const stream = await this.#streams.store.getStream(turn.streamId);\n if (\n !stream ||\n (stream.status !== 'completed' &&\n stream.status !== 'failed' &&\n stream.status !== 'cancelled')\n ) {\n return;\n }\n\n const message = (await this.#messages(thread)).find(\n (candidate) =>\n candidate.role === 'assistant' && candidate.id === turn.streamId,\n );\n if (stream.status === 'completed' && this.#approvals.isPaused(message)) {\n return;\n }\n const text =\n message?.role === 'assistant'\n ? AgentStatusProjector.#messageText(message)\n : '';\n let content = text || 'Agent completed without a text response.';\n if (stream.status === 'failed') {\n content = `Agent failed: ${stream.error || 'unknown error'}`;\n } else if (stream.status === 'cancelled') {\n content = 'Agent was interrupted.';\n }\n const parent = await this.#directory.load({\n chatId: thread.parentChatId,\n userId: thread.conversation.userId,\n });\n\n await this.#mailbox.deliver(\n createInterAgentCommunication({\n id: `zukhruf:child-terminal:${turn.streamId}`,\n type: InterAgentCommunicationType.FinalAnswer,\n author: thread.conversation,\n recipient: {\n chatId: thread.parentChatId,\n userId: thread.conversation.userId,\n },\n content,\n metadata: {\n authorPath: thread.path.toString(),\n recipientPath: parent?.path.toString() ?? thread.parentChatId,\n streamId: turn.streamId,\n status: stream.status,\n },\n }),\n MessageDeliveryMode.QueueOnly,\n );\n }\n\n async #messages(thread: AgentThread): Promise<UIMessage[]> {\n const engine = new ContextEngine({\n store: this.#store,\n chatId: thread.conversation.chatId,\n userId: thread.conversation.userId,\n });\n return engine.getMessages();\n }\n\n static #listedStatus(\n status: StreamStatus | undefined,\n error: string | null | undefined,\n head: UIMessage | undefined,\n ): ListedAgentStatus {\n switch (status) {\n case 'running':\n return 'running';\n case 'completed':\n return {\n completed:\n head?.role === 'assistant'\n ? AgentStatusProjector.#messageText(head) || null\n : null,\n };\n case 'failed':\n return { errored: error || 'Agent turn failed.' };\n case 'cancelled':\n return 'interrupted';\n case 'queued':\n case undefined:\n return 'pending_init';\n }\n }\n\n static #messageText(message: UIMessage): string {\n return message.parts\n .filter(isTextUIPart)\n .map((part) => part.text)\n .join('\\n')\n .trim();\n }\n}\n", "import { v5 as uuidv5 } from 'uuid';\n\nimport type { ConversationId } from '../mailbox/types.ts';\n\n/** Conversation-scoped durable identity for one caller-supplied turn key. */\nexport class AgentTurnId {\n static readonly #prefix = 'zukhruf-turn';\n readonly #value: string;\n\n private constructor(value: string) {\n this.#value = value;\n }\n\n static fromRequest(\n conversation: ConversationId,\n requestId: string,\n ): AgentTurnId {\n if (!requestId.trim()) {\n throw new Error('turn id cannot be empty');\n }\n const scope = conversationNamespace(conversation);\n return new AgentTurnId(\n `${AgentTurnId.#prefix}:${scope}:${uuidv5(requestId, scope)}`,\n );\n }\n\n static random(conversation: ConversationId): AgentTurnId {\n return AgentTurnId.fromRequest(conversation, crypto.randomUUID());\n }\n\n static assertOwner(conversation: ConversationId, streamId: string): void {\n const expectedPrefix = `${AgentTurnId.#prefix}:${conversationNamespace(conversation)}:`;\n if (!streamId.startsWith(expectedPrefix)) {\n throw new Error(\n `stream \"${streamId}\" does not belong to conversation \"${conversation.chatId}\"`,\n );\n }\n }\n\n toString(): string {\n return this.#value;\n }\n}\n\nexport function conversationNamespace(conversation: ConversationId): string {\n if (!conversation.chatId.trim() || !conversation.userId.trim()) {\n throw new Error('conversation requires non-empty chatId and userId');\n }\n return uuidv5(\n JSON.stringify([conversation.userId, conversation.chatId]),\n uuidv5.URL,\n );\n}\n", "import { setTimeout as delay } from 'node:timers/promises';\n\nimport type { StreamManager } from '@deepagents/context';\n\nimport { AgentTurnId } from '../control-plane/agent-turn-id.ts';\nimport type { TurnQueue, TurnRef } from '../queue/turn-queue.ts';\nimport type { MailboxStore } from './store.ts';\nimport {\n type ConversationId,\n MessageDeliveryMode as DeliveryMode,\n type InterAgentCommunication,\n InterAgentCommunicationType,\n type MessageDeliveryMode,\n assertCommunication,\n} from './types.ts';\n\nexport interface MailboxCoordinatorOptions {\n store: MailboxStore;\n queue: Pick<TurnQueue, 'push'>;\n streams: StreamManager;\n}\n\nconst WAIT_POLL_INTERVAL_MS = 50;\n\n/** Owns durable mail delivery and the serialized turns that wake recipients. */\nexport class MailboxCoordinator {\n readonly #store: MailboxStore;\n readonly #queue: Pick<TurnQueue, 'push'>;\n readonly #streams: StreamManager;\n readonly #wakeRequests = new Map<string, Promise<void>>();\n\n constructor(options: MailboxCoordinatorOptions) {\n this.#store = options.store;\n this.#queue = options.queue;\n this.#streams = options.streams;\n }\n\n async deliver(\n communication: InterAgentCommunication,\n mode: MessageDeliveryMode,\n ): Promise<void> {\n const delivered = {\n ...communication,\n type:\n mode === DeliveryMode.TriggerTurn\n ? InterAgentCommunicationType.NewTask\n : communication.type,\n triggerTurn: mode === DeliveryMode.TriggerTurn,\n };\n assertCommunication(delivered);\n\n const { recipientActive } = await this.#store.enqueue(delivered);\n if (delivered.triggerTurn || recipientActive) {\n // Queue-only mail sent during an active turn gets a serialized fallback\n // in case sampling has already crossed its final safe drain boundary.\n await this.#scheduleWake(delivered.recipient);\n }\n }\n\n beginTurn(turn: TurnRef): Promise<void> {\n return this.#store.beginTurn(turn, turn.streamId);\n }\n\n async endTurn(\n turn: TurnRef,\n options: { parked?: boolean } = {},\n ): Promise<void> {\n const { hasPending, turnEnded } = await this.#store.endTurn(\n turn,\n turn.streamId,\n );\n if (turnEnded && hasPending && !options.parked) {\n await this.#scheduleWake(turn);\n }\n }\n\n drainLeadingQueueOnly(\n recipient: ConversationId,\n ): Promise<InterAgentCommunication[]> {\n return this.#store.drainLeadingQueueOnly(recipient);\n }\n\n drain(recipient: ConversationId): Promise<InterAgentCommunication[]> {\n return this.#store.drain(recipient);\n }\n\n async waitForPending(\n recipient: ConversationId,\n options: { timeoutMs: number; signal?: AbortSignal },\n ): Promise<boolean> {\n const deadline = Date.now() + options.timeoutMs;\n while (true) {\n options.signal?.throwIfAborted();\n if (await this.#store.hasPending(recipient)) return true;\n const remaining = deadline - Date.now();\n if (remaining <= 0) return false;\n await delay(Math.min(WAIT_POLL_INTERVAL_MS, remaining), undefined, {\n signal: options.signal,\n });\n }\n }\n\n #scheduleWake(target: ConversationId): Promise<void> {\n const key = this.#conversationKey(target);\n const existing = this.#wakeRequests.get(key);\n if (existing) return existing;\n\n // This map coalesces only concurrent requests in this process. A fulfilled\n // request is removed because another process may consume the wake.\n const request = (async () => {\n const wakeId = AgentTurnId.random(target).toString();\n await this.#streams.register(wakeId);\n try {\n await this.#queue.push({\n kind: 'mailbox',\n streamId: wakeId,\n chatId: target.chatId,\n userId: target.userId,\n } satisfies TurnRef);\n } catch (error) {\n await this.#streams.store.updateStreamStatus(wakeId, 'failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n })();\n this.#wakeRequests.set(key, request);\n\n const clearRequest = () => {\n if (this.#wakeRequests.get(key) === request) {\n this.#wakeRequests.delete(key);\n }\n };\n void request.then(clearRequest, clearRequest);\n return request;\n }\n\n #conversationKey(conversation: ConversationId): string {\n return JSON.stringify([conversation.chatId, conversation.userId]);\n }\n}\n", "const DEFAULT_MIN_WAIT_TIMEOUT_MS = 10_000;\nconst DEFAULT_WAIT_TIMEOUT_MS = 30_000;\nconst DEFAULT_MAX_WAIT_TIMEOUT_MS = 3_600_000;\n\nconst RESERVED_TOOL_NAMESPACES = new Set([\n 'api_tool',\n 'browser',\n 'computer',\n 'container',\n 'file_search',\n 'functions',\n 'image_gen',\n 'multi_tool_use',\n 'python',\n 'python_user_visible',\n 'submodel_delegator',\n 'terminal',\n 'tool_search',\n 'web',\n]);\n\n/** Host-level controls matching Codex MultiAgentV2 configuration. */\nexport interface MultiAgentV2HostConfig {\n minWaitTimeoutMs?: number;\n defaultWaitTimeoutMs?: number;\n maxWaitTimeoutMs?: number;\n /** Additional guidance appended to the spawn_agent tool description. */\n usageHintText?: string;\n /** Complete root guidance override. An empty string disables the hint. */\n rootAgentUsageHintText?: string;\n /** Complete child guidance override. An empty string disables the hint. */\n subagentUsageHintText?: string;\n /** Native OpenAI Responses namespace for the six collaboration tools. */\n toolNamespace?: string;\n /**\n * Keeps collaboration tools on the direct model surface instead of a nested\n * code-mode executor. Defaults to true. Zukhruf currently rejects false\n * because it has no nested code-mode executor in which to expose the tools.\n */\n nonCodeModeOnly?: boolean;\n}\n\nexport interface ResolvedMultiAgentV2HostConfig {\n minWaitTimeoutMs: number;\n defaultWaitTimeoutMs: number;\n maxWaitTimeoutMs: number;\n usageHintText?: string;\n rootAgentUsageHintText?: string;\n subagentUsageHintText?: string;\n toolNamespace?: string;\n nonCodeModeOnly: boolean;\n}\n\nexport function resolveMultiAgentV2HostConfig(\n input: MultiAgentV2HostConfig = {},\n): ResolvedMultiAgentV2HostConfig {\n const minWaitTimeoutMs =\n input.minWaitTimeoutMs ?? DEFAULT_MIN_WAIT_TIMEOUT_MS;\n const defaultWaitTimeoutMs =\n input.defaultWaitTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;\n const maxWaitTimeoutMs =\n input.maxWaitTimeoutMs ?? DEFAULT_MAX_WAIT_TIMEOUT_MS;\n assertTimeout('minWaitTimeoutMs', minWaitTimeoutMs);\n assertTimeout('defaultWaitTimeoutMs', defaultWaitTimeoutMs);\n assertTimeout('maxWaitTimeoutMs', maxWaitTimeoutMs);\n if (minWaitTimeoutMs > maxWaitTimeoutMs) {\n throw new Error(\n 'AgentRuntime: multiAgentV2.minWaitTimeoutMs must be at most maxWaitTimeoutMs',\n );\n }\n if (defaultWaitTimeoutMs < minWaitTimeoutMs) {\n throw new Error(\n 'AgentRuntime: multiAgentV2.defaultWaitTimeoutMs must be at least minWaitTimeoutMs',\n );\n }\n if (defaultWaitTimeoutMs > maxWaitTimeoutMs) {\n throw new Error(\n 'AgentRuntime: multiAgentV2.defaultWaitTimeoutMs must be at most maxWaitTimeoutMs',\n );\n }\n\n const toolNamespace = input.toolNamespace;\n if (\n toolNamespace !== undefined &&\n (toolNamespace.length === 0 || toolNamespace.trim() !== toolNamespace)\n ) {\n throw new Error(\n 'AgentRuntime: multiAgentV2.toolNamespace cannot be empty or padded',\n );\n }\n if (toolNamespace !== undefined) validateToolNamespace(toolNamespace);\n\n const nonCodeModeOnly = input.nonCodeModeOnly ?? true;\n if (!nonCodeModeOnly) {\n throw new Error(\n 'AgentRuntime: multiAgentV2.nonCodeModeOnly=false requires a nested code-mode executor, which Zukhruf does not provide',\n );\n }\n const tool = (name: string) =>\n toolNamespace === undefined ? name : `${toolNamespace}.${name}`;\n const collaborationTools = [\n 'spawn_agent',\n 'send_message',\n 'followup_task',\n 'wait_agent',\n 'interrupt_agent',\n 'list_agents',\n ]\n .map((name) => `\\`${tool(name)}\\``)\n .join(', ');\n const shared = `Call ${collaborationTools} directly. They are intentionally unavailable inside nested code execution.\n\nAll agents share the same workspace, current working directory, and filesystem.`;\n\n return {\n minWaitTimeoutMs,\n defaultWaitTimeoutMs,\n maxWaitTimeoutMs,\n usageHintText: nonEmptyText(input.usageHintText),\n rootAgentUsageHintText:\n input.rootAgentUsageHintText === undefined\n ? defaultRootUsageHint(tool, shared)\n : nonEmptyText(input.rootAgentUsageHintText),\n subagentUsageHintText:\n input.subagentUsageHintText === undefined\n ? defaultSubagentUsageHint(tool, shared)\n : nonEmptyText(input.subagentUsageHintText),\n toolNamespace,\n nonCodeModeOnly,\n };\n}\n\nfunction assertTimeout(name: string, value: number): void {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(\n `AgentRuntime: multiAgentV2.${name} must be a non-negative safe integer`,\n );\n }\n}\n\nfunction validateToolNamespace(namespace: string): void {\n if (\n namespace.length > 64 ||\n !/^[a-zA-Z0-9_-]+$/.test(namespace) ||\n namespace === 'mcp' ||\n namespace.startsWith('mcp__') ||\n RESERVED_TOOL_NAMESPACES.has(namespace)\n ) {\n throw new Error(\n `AgentRuntime: multiAgentV2.toolNamespace \"${namespace}\" is a reserved tool namespace or invalid`,\n );\n }\n}\n\nfunction nonEmptyText(value: string | undefined): string | undefined {\n if (value === undefined) return undefined;\n return value.length === 0 ? undefined : value;\n}\n\nfunction defaultRootUsageHint(\n tool: (name: string) => string,\n shared: string,\n): string {\n return `You are \\`/root\\`, the primary agent in a team of agents collaborating to fulfill the user's goals.\n\nAt the start of your turn, you are the active agent. You can spawn sub-agents to handle subtasks, and those agents can recursively spawn their own declared sub-agents. All agents are equally capable and receive the tools declared for their agent type.\n\nUse \\`${tool('spawn_agent')}\\` to create an agent, \\`${tool('followup_task')}\\` to assign a new task and trigger a turn, and \\`${tool('send_message')}\\` to queue a message without triggering a turn. Use \\`fork_turns\\` to control how much parent history the child receives.\n\nChild messages arrive as \\`MESSAGE\\` or \\`FINAL_ANSWER\\` mailbox envelopes with their task name, sender, and payload preserved.\n\n${shared}`;\n}\n\nfunction defaultSubagentUsageHint(\n tool: (name: string) => string,\n shared: string,\n): string {\n return `You are an agent in a team collaborating to complete a task.\n\nYou can spawn declared sub-agents recursively. All agents are equally capable and receive the tools declared for their agent type. Use \\`${tool('spawn_agent')}\\` to create one, \\`${tool('followup_task')}\\` to assign a new task and trigger a turn, and \\`${tool('send_message')}\\` to queue a message for another agent.\n\nYour final response is delivered automatically to your parent agent. Mailbox messages arrive as \\`NEW_TASK\\`, \\`MESSAGE\\`, or \\`FINAL_ANSWER\\` envelopes with their task name, sender, and payload preserved.\n\n${shared}`;\n}\n", "import type { UIMessage } from 'ai';\n\nimport {\n type AvailableSkill,\n ContextEngine,\n type ContextStore,\n type StreamManager,\n agent,\n assistant,\n chat,\n role,\n user,\n} from '@deepagents/context';\n\nimport type { ZukhrufSandbox } from '../agent.ts';\nimport type { AgentToolContext } from '../collaboration/agent-tool-context.ts';\nimport { createCollaborationTools } from '../collaboration/collaboration-tools.ts';\nimport type { AgentControlPlane } from '../control-plane/agent-control-plane.ts';\nimport type { MailboxCoordinator } from '../mailbox/coordinator.ts';\nimport type {\n ConversationId,\n InterAgentCommunication,\n} from '../mailbox/types.ts';\nimport type { ResolvedMultiAgentV2HostConfig } from '../multi-agent-v2-config.ts';\nimport type { ConsumeContext, TurnRef } from '../queue/turn-queue.ts';\nimport {\n type AgentSkills,\n createAgentSkills,\n discoverAgentSkills,\n} from './agent-skills.ts';\nimport type { ApprovalController } from './approval-controller.ts';\n\nexport interface AgentTurnExecutorOptions {\n store: ContextStore;\n streams: StreamManager;\n controlPlane: AgentControlPlane;\n mailbox: MailboxCoordinator;\n approvals: ApprovalController;\n multiAgentV2: ResolvedMultiAgentV2HostConfig;\n}\n\ninterface SamplingMailboxState {\n firstRequest: boolean;\n}\n\n/** Executes one queued turn without owning host lifecycle or agent routing. */\nexport class AgentTurnExecutor {\n readonly #store: ContextStore;\n readonly #streams: StreamManager;\n readonly #controlPlane: AgentControlPlane;\n readonly #mailbox: MailboxCoordinator;\n readonly #approvals: ApprovalController;\n readonly #multiAgentV2: ResolvedMultiAgentV2HostConfig;\n readonly #collaborationTools: ReturnType<typeof createCollaborationTools>;\n\n constructor(options: AgentTurnExecutorOptions) {\n this.#store = options.store;\n this.#streams = options.streams;\n this.#controlPlane = options.controlPlane;\n this.#mailbox = options.mailbox;\n this.#approvals = options.approvals;\n this.#multiAgentV2 = options.multiAgentV2;\n this.#collaborationTools = createCollaborationTools(options.multiAgentV2);\n }\n\n async execute(turn: TurnRef, context: ConsumeContext): Promise<void> {\n if (turn.kind === 'approval') {\n if (!(await this.#approvals.applyDecision(turn))) return;\n await this.#reopen(turn.streamId);\n return this.execute(\n {\n kind: 'continuation',\n streamId: turn.streamId,\n chatId: turn.chatId,\n userId: turn.userId,\n },\n context,\n );\n }\n if (turn.kind === 'continuation' && turn.recovery !== undefined) {\n await this.#reopen(turn.streamId);\n }\n if (await this.#projectSkippedTerminalTurn(turn)) return;\n\n let parked = false;\n await this.#mailbox.beginTurn(turn);\n try {\n await this.#executeTurn(turn, {\n ...context,\n park: async () => {\n parked = true;\n await context.park();\n },\n });\n } finally {\n await this.#mailbox.endTurn(turn, { parked });\n }\n }\n\n async #executeTurn(\n turn: TurnRef,\n { signal, park }: ConsumeContext,\n ): Promise<void> {\n if (await this.#projectSkippedTerminalTurn(turn)) return;\n\n const { declaration, thread } = await this.#controlPlane.resolve(turn);\n const usageHint = thread.path.isRoot\n ? this.#multiAgentV2.rootAgentUsageHintText\n : this.#multiAgentV2.subagentUsageHintText;\n const engine = this.#engineFor(turn);\n\n if (turn.kind === 'ask' || turn.kind === 'mailbox') {\n const head = (await engine.getMessages()).at(-1);\n if (this.#approvals.isPaused(head)) {\n await park();\n return;\n }\n }\n\n let communications: InterAgentCommunication[] = [];\n if (turn.kind === 'ask') {\n communications = await this.#mailbox.drainLeadingQueueOnly(turn);\n } else if (turn.kind === 'mailbox') {\n communications = await this.#mailbox.drain(turn);\n }\n\n if (turn.kind === 'mailbox' && communications.length === 0) {\n // Duplicate wakes are harmless scheduling receipts once mail is gone.\n await this.#streams.store.updateStreamStatus(turn.streamId, 'completed');\n return;\n }\n\n await this.#controlPlane.recordLatestTurn(turn, turn.streamId);\n await this.#prepareChain(turn, engine, communications);\n\n const sandbox = await declaration.sandbox({\n chatId: turn.chatId,\n userId: turn.userId,\n });\n const agentSkills = await this.#skillsFor(turn, sandbox, signal);\n engine.set(\n ...declaration.instructions,\n ...agentSkills.fragments,\n ...(usageHint === undefined ? [] : [role(usageHint)]),\n );\n\n if (await this.#projectSkippedTerminalTurn(turn)) return;\n if (!(await this.#streams.claim(turn.streamId))) {\n await this.#projectSkippedTerminalTurn(turn);\n return;\n }\n const mailboxState: SamplingMailboxState = { firstRequest: true };\n const ai = agent<AgentToolContext>({\n name: declaration.name,\n model: declaration.model,\n sandbox,\n context: engine,\n tools: {\n ...declaration.tools,\n ...this.#collaborationTools,\n },\n telemetry: declaration.telemetry,\n prepareStepInput: () => this.#prepareStepInput(turn, mailboxState),\n });\n\n const abort = new AbortController();\n const onWorkerAbort = () => abort.abort();\n signal.addEventListener('abort', onWorkerAbort, { once: true });\n try {\n const setupCancellation = this.#streams.monitorCancellation(\n turn.streamId,\n () => abort.abort(),\n );\n let stream: Awaited<ReturnType<typeof chat>>;\n try {\n stream = await chat(ai, {\n abortSignal: abort.signal,\n contextVariables: {\n controlPlane: this.#controlPlane,\n actor: { turn, thread, declaration },\n },\n });\n } finally {\n await setupCancellation[Symbol.asyncDispose]();\n }\n await this.#streams.persist(stream, turn.streamId, {\n preclaimed: true,\n onCancelDetected: () => abort.abort(),\n });\n if (turn.kind === 'continuation') {\n await this.#reconcileTerminalContinuation(turn);\n }\n await this.#controlPlane.projectTerminal(turn, thread);\n } finally {\n signal.removeEventListener('abort', onWorkerAbort);\n }\n }\n\n async #projectSkippedTerminalTurn(turn: TurnRef): Promise<boolean> {\n const status = await this.#streams.store.getStreamStatus(turn.streamId);\n if (status === 'queued' || status === 'running') return false;\n if (status === undefined || turn.kind === 'mailbox') return true;\n\n if (turn.kind === 'continuation') {\n await this.#reconcileTerminalContinuation(turn);\n }\n\n const { thread } = await this.#controlPlane.resolve(turn);\n if (\n thread.lastTurnId === undefined ||\n thread.lastTurnId === turn.streamId\n ) {\n await this.#controlPlane.recordLatestTurnIfCurrent(\n turn,\n turn.streamId,\n thread.lastTurnId,\n );\n }\n await this.#controlPlane.projectTerminal(turn, thread);\n return true;\n }\n\n async #reconcileTerminalContinuation(turn: TurnRef): Promise<void> {\n const stream = await this.#streams.store.getStream(turn.streamId);\n if (\n stream?.status !== 'completed' &&\n stream?.status !== 'failed' &&\n stream?.status !== 'cancelled'\n ) {\n return;\n }\n await this.#approvals.reconcileTerminalContinuation(\n turn,\n turn.streamId,\n stream.status,\n stream.error,\n );\n }\n\n async #reopen(streamId: string): Promise<void> {\n const status = await this.#streams.store.getStreamStatus(streamId);\n if (status === 'queued' || status === 'running') return;\n await this.#streams.reopen(streamId);\n }\n\n async #prepareChain(\n turn: TurnRef,\n engine: ContextEngine,\n communications: InterAgentCommunication[],\n ): Promise<void> {\n if (turn.kind === 'ask') {\n engine.set(\n ...communications.map((communication) =>\n user(this.#mailboxInputMessage(communication)),\n ),\n user(turn.input),\n assistant({ id: turn.streamId, role: 'assistant', parts: [] }),\n );\n await engine.save({ branch: true });\n } else if (turn.kind === 'mailbox') {\n engine.set(\n ...communications.map((communication) =>\n user(this.#mailboxInputMessage(communication)),\n ),\n assistant({ id: turn.streamId, role: 'assistant', parts: [] }),\n );\n await engine.save({ branch: true });\n }\n }\n\n async #prepareStepInput(\n turn: TurnRef,\n state: SamplingMailboxState,\n ): Promise<Array<UIMessage & { role: 'user' }> | undefined> {\n const communications =\n turn.kind === 'ask' && state.firstRequest\n ? await this.#mailbox.drainLeadingQueueOnly(turn)\n : await this.#mailbox.drain(turn);\n state.firstRequest = false;\n return communications.length === 0\n ? undefined\n : communications.map((communication) =>\n this.#mailboxInputMessage(communication),\n );\n }\n\n async #skillsFor(\n turn: TurnRef,\n sandbox: ZukhrufSandbox,\n signal: AbortSignal,\n ): Promise<AgentSkills> {\n const chat = await this.#store.getChat(turn.chatId);\n const existing = readSkills(chat?.metadata);\n if (existing !== undefined) return createAgentSkills(existing);\n if (sandbox.workingDirectory === undefined) return createAgentSkills([]);\n\n const discovered = await discoverAgentSkills(sandbox, signal);\n let available = discovered.available;\n await this.#store.updateChat(turn.chatId, ({ metadata }) => {\n const persisted = readSkills(metadata);\n if (persisted !== undefined) {\n available = persisted;\n return undefined;\n }\n\n const zukhruf = isRecord(metadata?.zukhruf) ? metadata.zukhruf : {};\n return {\n metadata: {\n ...metadata,\n zukhruf: { ...zukhruf, skills: available },\n },\n };\n });\n return available === discovered.available\n ? discovered\n : createAgentSkills(available);\n }\n\n #engineFor({ chatId, userId }: ConversationId): ContextEngine {\n return new ContextEngine({ store: this.#store, chatId, userId });\n }\n\n #mailboxInputMessage(\n communication: InterAgentCommunication,\n ): UIMessage & { role: 'user' } {\n return {\n id: crypto.randomUUID(),\n role: 'user',\n parts: [\n {\n type: 'text',\n text: this.#renderInterAgentCommunication(communication),\n },\n ],\n metadata: { interAgentCommunication: communication },\n };\n }\n\n #renderInterAgentCommunication(\n communication: InterAgentCommunication,\n ): string {\n const recipientPath = communication.metadata?.recipientPath;\n const authorPath = communication.metadata?.authorPath;\n const taskName =\n typeof recipientPath === 'string'\n ? recipientPath\n : communication.recipient.chatId;\n const sender =\n typeof authorPath === 'string' ? authorPath : communication.author.chatId;\n return `Message Type: ${communication.type}\\nTask name: ${taskName}\\nSender: ${sender}\\nPayload:\\n${communication.content}`;\n }\n}\n\nfunction readSkills(\n metadata: Record<string, unknown> | undefined,\n): readonly AvailableSkill[] | undefined {\n const zukhruf = metadata?.zukhruf;\n if (!isRecord(zukhruf) || !Object.hasOwn(zukhruf, 'skills')) {\n return undefined;\n }\n if (!Array.isArray(zukhruf.skills) || !zukhruf.skills.every(isSkill)) {\n throw new Error('AgentRuntime: stored skill catalog is invalid');\n }\n return zukhruf.skills;\n}\n\nfunction isSkill(value: unknown): value is AvailableSkill {\n return (\n isRecord(value) &&\n typeof value.name === 'string' &&\n typeof value.description === 'string' &&\n typeof value.path === 'string'\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n", "import { tool } from 'ai';\nimport { z } from 'zod';\n\nimport {\n type ListedAgentStatus,\n listedAgentStatusSchema,\n} from '../control-plane/agent-status-projector.ts';\nimport type { AgentToolContext } from './agent-tool-context.ts';\n\nconst interruptAgentInputSchema = z.object({\n target: z\n .string()\n .trim()\n .min(1)\n .describe(\n 'The canonical /root/... path, or a descendant-relative target name.',\n ),\n});\n\ntype InterruptAgentInput = z.infer<typeof interruptAgentInputSchema>;\n\nconst interruptAgentOutputSchema = z\n .object({ previous_status: listedAgentStatusSchema })\n .strict();\n\nexport const interruptAgentTool = tool<\n InterruptAgentInput,\n { previous_status: ListedAgentStatus },\n AgentToolContext\n>({\n description:\n \"Interrupt an agent's current turn, if any, and return its previous status. The agent remains available for messages and follow-up tasks.\",\n inputSchema: interruptAgentInputSchema,\n outputSchema: interruptAgentOutputSchema,\n execute: async (input, { context }) =>\n context.controlPlane.interruptAgent(context.actor, input),\n});\n", "import { tool } from 'ai';\nimport { z } from 'zod';\n\nimport {\n type ListedAgent,\n listedAgentSchema,\n} from '../control-plane/agent-status-projector.ts';\nimport type { AgentToolContext } from './agent-tool-context.ts';\n\nconst listAgentsInputSchema = z.object({\n path_prefix: z\n .string()\n .trim()\n .min(1)\n .describe(\n 'Task-path prefix without a trailing slash. Omit to list the whole tree.',\n )\n .optional(),\n});\n\ntype ListAgentsInput = z.infer<typeof listAgentsInputSchema>;\n\nconst listAgentsOutputSchema = z\n .object({ agents: z.array(listedAgentSchema) })\n .strict();\n\nexport const listAgentsTool = tool<\n ListAgentsInput,\n { agents: ListedAgent[] },\n AgentToolContext\n>({\n description:\n 'List live agents in the current root thread tree. Optionally filter by task-path prefix.',\n inputSchema: listAgentsInputSchema,\n outputSchema: listAgentsOutputSchema,\n execute: async ({ path_prefix }, { context }) =>\n context.controlPlane.listAgents(context.actor, path_prefix),\n});\n", "import { tool } from 'ai';\nimport { z } from 'zod';\n\nimport type { AgentToolContext } from './agent-tool-context.ts';\n\nconst agentMessageInputSchema = z.object({\n target: z\n .string()\n .trim()\n .min(1)\n .describe(\n 'The canonical /root/... path, or a descendant-relative target name.',\n ),\n message: z.string().trim().min(1).describe('The message or follow-up task.'),\n});\n\ntype AgentMessageInput = z.infer<typeof agentMessageInputSchema>;\ntype AgentMessageOutput = string;\n\nexport const sendMessageTool = tool<\n AgentMessageInput,\n AgentMessageOutput,\n AgentToolContext\n>({\n description:\n 'Queue a message for another agent. Address siblings with their canonical /root/... path.',\n inputSchema: agentMessageInputSchema,\n execute: async (input, { context }) => {\n await context.controlPlane.sendMessage(context.actor, input);\n return '';\n },\n});\n\nexport const followupTaskTool = tool<\n AgentMessageInput,\n AgentMessageOutput,\n AgentToolContext\n>({\n description:\n 'Send a follow-up task to an existing non-root agent and wake its thread.',\n inputSchema: agentMessageInputSchema,\n execute: async (input, { context }) => {\n await context.controlPlane.followupTask(context.actor, input);\n return '';\n },\n});\n", "import { tool } from 'ai';\nimport { z } from 'zod';\n\nimport { forkTurnsError, parseForkTurns } from '../control-plane/fork-turns.ts';\nimport type { AgentToolContext } from './agent-tool-context.ts';\n\nconst spawnAgentInputSchema = z.object({\n agent_type: z\n .string()\n .trim()\n .min(1)\n .describe('The name of one available subagent declaration.'),\n task_name: z\n .string()\n .trim()\n .min(1)\n .refine(\n (value) => value !== '.' && value !== '..' && !value.includes('/'),\n 'task_name must be one non-empty path segment',\n )\n .describe('One path segment naming this independent agent task.'),\n message: z\n .string()\n .refine((value) => value.trim().length > 0, 'message cannot be empty')\n .describe('The initial task for the spawned agent.'),\n fork_turns: z\n .string()\n .trim()\n .default('all')\n .refine((value) => parseForkTurns(value) !== undefined, forkTurnsError)\n .describe(\n 'Optional number of parent turns to fork. Defaults to `all`. Use `none`, `all`, or a positive integer string such as `3`.',\n ),\n});\n\ntype SpawnAgentInput = z.infer<typeof spawnAgentInputSchema>;\n\nconst spawnAgentOutputSchema = z.object({ task_name: z.string() }).strict();\n\nexport function createSpawnAgentTool(options?: { usageHintText?: string }) {\n return tool<SpawnAgentInput, { task_name: string }, AgentToolContext>({\n description: ({ context }) => {\n const available = (context.actor.declaration.subagents ?? [])\n .map((subagent) => subagent.name)\n .join(', ');\n return [\n `Spawn an independent subagent. Available agent types: ${available || 'none'}.`,\n options?.usageHintText,\n ]\n .filter(Boolean)\n .join(' ');\n },\n inputSchema: spawnAgentInputSchema,\n outputSchema: spawnAgentOutputSchema,\n execute: async (\n { agent_type, task_name, message, fork_turns },\n { context },\n ) => {\n const forkTurns = parseForkTurns(fork_turns);\n if (forkTurns === undefined) throw new Error(forkTurnsError);\n return context.controlPlane.spawn(context.actor, {\n agentType: agent_type,\n taskName: task_name,\n message,\n forkTurns,\n });\n },\n });\n}\n", "export type ForkTurns = 'none' | 'all' | number;\n\nexport const forkTurnsError =\n 'fork_turns must be `none`, `all`, or a positive integer string';\n\nexport function parseForkTurns(value: string): ForkTurns | undefined {\n const normalized = value.trim().toLowerCase();\n if (normalized === 'none' || normalized === 'all') return normalized;\n if (!/^\\d+$/.test(normalized)) return undefined;\n\n const turns = Number(normalized);\n return Number.isSafeInteger(turns) && turns > 0 ? turns : undefined;\n}\n", "import { tool } from 'ai';\nimport { z } from 'zod';\n\nimport type { AgentToolContext } from './agent-tool-context.ts';\n\nconst waitAgentOutputSchema = z\n .object({ message: z.string(), timed_out: z.boolean() })\n .strict();\n\nexport function createWaitAgentTool(options: {\n minTimeoutMs: number;\n defaultTimeoutMs: number;\n maxTimeoutMs: number;\n}) {\n const waitAgentInputSchema = z.object({\n timeout_ms: z\n .number()\n .int()\n .min(options.minTimeoutMs)\n .max(options.maxTimeoutMs)\n .optional()\n .describe('Maximum time to wait in milliseconds.'),\n });\n type WaitAgentInput = z.infer<typeof waitAgentInputSchema>;\n\n return tool<\n WaitAgentInput,\n { message: string; timed_out: boolean },\n AgentToolContext\n >({\n description:\n 'Wait for pending mail addressed to this agent without consuming it.',\n inputSchema: waitAgentInputSchema,\n outputSchema: waitAgentOutputSchema,\n execute: async ({ timeout_ms }, { abortSignal, context }) => {\n const received = await context.controlPlane.waitForMailbox(\n context.actor,\n {\n timeoutMs: timeout_ms ?? options.defaultTimeoutMs,\n signal: abortSignal,\n },\n );\n return received\n ? { message: 'Wait completed.', timed_out: false }\n : { message: 'Wait timed out.', timed_out: true };\n },\n });\n}\n", "import type { Tool, ToolSet } from 'ai';\n\nimport type { ResolvedMultiAgentV2HostConfig } from '../multi-agent-v2-config.ts';\nimport { interruptAgentTool } from './interrupt-agent.ts';\nimport { listAgentsTool } from './list-agents.ts';\nimport { followupTaskTool, sendMessageTool } from './message-tools.ts';\nimport { createSpawnAgentTool } from './spawn-agent.ts';\nimport { createWaitAgentTool } from './wait-agent.ts';\n\nconst NAMESPACE_DESCRIPTION = 'Tools for spawning and managing sub-agents.';\n\nexport function createCollaborationTools(\n config: ResolvedMultiAgentV2HostConfig,\n): ToolSet {\n const tools: ToolSet = {\n spawn_agent: createSpawnAgentTool({\n usageHintText: config.usageHintText,\n }),\n send_message: sendMessageTool,\n followup_task: followupTaskTool,\n list_agents: listAgentsTool,\n wait_agent: createWaitAgentTool({\n minTimeoutMs: config.minWaitTimeoutMs,\n defaultTimeoutMs: config.defaultWaitTimeoutMs,\n maxTimeoutMs: config.maxWaitTimeoutMs,\n }),\n interrupt_agent: interruptAgentTool,\n };\n\n return Object.fromEntries(\n Object.entries(tools).map(([name, collaborationTool]) => [\n name,\n configureTool(collaborationTool, config),\n ]),\n );\n}\n\nfunction configureTool(\n collaborationTool: Tool,\n config: ResolvedMultiAgentV2HostConfig,\n): Tool {\n const openai = collaborationTool.providerOptions?.openai;\n return {\n ...collaborationTool,\n providerOptions: {\n ...collaborationTool.providerOptions,\n ...(config.toolNamespace === undefined\n ? {}\n : {\n openai: {\n ...(typeof openai === 'object' && openai !== null ? openai : {}),\n namespace: {\n name: config.toolNamespace,\n description: NAMESPACE_DESCRIPTION,\n },\n },\n }),\n },\n metadata: {\n ...collaborationTool.metadata,\n zukhruf: {\n kind: 'collaboration',\n codeModeExposure: 'direct-model-only',\n },\n },\n };\n}\n", "import path from 'node:path';\n\nimport {\n type AvailableSkill,\n type ContextFragment,\n parseFrontmatter,\n skills,\n} from '@deepagents/context';\n\nimport type { ZukhrufSandbox } from '../agent.ts';\n\nexport interface AgentSkills {\n available: readonly AvailableSkill[];\n fragments: readonly ContextFragment[];\n}\n\nconst EMPTY_SKILLS: AgentSkills = { available: [], fragments: [] };\n\nexport async function discoverAgentSkills(\n sandbox: ZukhrufSandbox,\n signal?: AbortSignal,\n): Promise<AgentSkills> {\n if (sandbox.workingDirectory === undefined) return EMPTY_SKILLS;\n const skillsDirectory = path.posix.join(sandbox.workingDirectory, 'skills');\n const quotedSkillsDirectory = shellQuote(skillsDirectory);\n const result = await sandbox.sandbox.executeCommand(\n `if [ -d ${quotedSkillsDirectory} ]; then find ${quotedSkillsDirectory} -mindepth 1 -maxdepth 1 -type d -print; fi`,\n { signal },\n );\n if (result.exitCode !== 0) {\n throw new Error(\n `AgentRuntime: failed to discover sandbox skills: ${result.stderr.trim() || `exit ${result.exitCode}`}`,\n );\n }\n\n const skillDirectories = result.stdout\n .split('\\n')\n .filter(Boolean)\n .filter((directory) => !path.posix.basename(directory).startsWith('.'))\n .toSorted();\n if (skillDirectories.length === 0) return EMPTY_SKILLS;\n\n const discovered = await Promise.all(\n skillDirectories.map((directory) => loadSkill(sandbox, directory)),\n );\n\n return createAgentSkills(discovered);\n}\n\nexport function createAgentSkills(\n available: readonly AvailableSkill[],\n): AgentSkills {\n if (available.length === 0) return EMPTY_SKILLS;\n const snapshot = [...available];\n return { available: snapshot, fragments: [skills(snapshot)] };\n}\n\nasync function loadSkill(\n sandbox: ZukhrufSandbox,\n directory: string,\n): Promise<AvailableSkill> {\n const directoryName = path.posix.basename(directory);\n const skillMd = await sandbox.sandbox.readFile(\n path.posix.join(directory, 'SKILL.md'),\n );\n const { frontmatter } = parseFrontmatter(skillMd);\n if (frontmatter.name !== directoryName) {\n throw new Error(\n `AgentRuntime: skill \"${frontmatter.name}\" must use matching directory \"${directoryName}\"`,\n );\n }\n\n return {\n name: frontmatter.name,\n description: frontmatter.description,\n path: path.posix.join('skills', directoryName, 'SKILL.md'),\n };\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n", "import {\n type DynamicToolUIPart,\n type ToolUIPart,\n type UIMessage,\n getToolName,\n isToolUIPart,\n} from 'ai';\n\nimport {\n ContextEngine,\n type ContextStore,\n assistant,\n} from '@deepagents/context';\n\nimport type { ConversationId } from '../mailbox/types.ts';\nimport type {\n ApprovalTurnRef,\n TurnQueue,\n TurnRef,\n} from '../queue/turn-queue.ts';\nimport type { ZukhrufToolSet } from '../tool.ts';\nimport { approvalJobId } from './approval-job-id.ts';\n\nexport interface ApprovalControllerOptions {\n store: ContextStore;\n queue: TurnQueue;\n}\n\ntype ApprovalToolPart = DynamicToolUIPart | ToolUIPart;\n\n/** Durable approval-response and continuation state machine. */\nexport class ApprovalController {\n static readonly #settledToolStates = new Set([\n 'output-available',\n 'output-error',\n 'output-denied',\n ]);\n\n readonly #store: ContextStore;\n readonly #queue: TurnQueue;\n\n constructor(options: ApprovalControllerOptions) {\n this.#store = options.store;\n this.#queue = options.queue;\n }\n\n isPaused(message: UIMessage | undefined): boolean {\n return (\n message?.role === 'assistant' &&\n this.#pendingToolPart(message) !== undefined\n );\n }\n\n approve(conversation: ConversationId, input: { toolCallId: string }) {\n return this.#respond('approve', conversation, input.toolCallId, {\n approved: true,\n });\n }\n\n deny(\n conversation: ConversationId,\n input: { toolCallId: string; reason?: string },\n ) {\n return this.#respond('deny', conversation, input.toolCallId, {\n approved: false,\n reason: input.reason,\n });\n }\n\n async settleDeniedApprovals(\n conversation: ConversationId,\n streamId: string,\n ): Promise<void> {\n const engine = this.#engineFor(conversation);\n const head = (await engine.getMessages()).at(-1);\n if (head?.role !== 'assistant' || head.id !== streamId) return;\n const hasDenied = head.parts.some(\n (part) =>\n isToolUIPart(part) &&\n part.state === 'approval-responded' &&\n part.approval.approved === false,\n );\n if (!hasDenied) return;\n\n const updated: UIMessage = {\n ...head,\n parts: head.parts.map((part) => {\n if (\n !isToolUIPart(part) ||\n part.state !== 'approval-responded' ||\n part.approval.approved !== false\n ) {\n return part;\n }\n const settled: ApprovalToolPart = {\n ...part,\n state: 'output-denied',\n approval: { ...part.approval, approved: false },\n };\n return settled;\n }),\n };\n await engine.continue(assistant(updated));\n }\n\n async settleFailedApprovals(\n conversation: ConversationId,\n streamId: string,\n error: string,\n ): Promise<void> {\n const engine = this.#engineFor(conversation);\n const head = (await engine.getMessages()).at(-1);\n if (head?.role !== 'assistant' || head.id !== streamId) return;\n const hasResponded = head.parts.some(\n (part) => isToolUIPart(part) && part.state === 'approval-responded',\n );\n if (!hasResponded) return;\n\n const updated: UIMessage = {\n ...head,\n parts: head.parts.map((part) => {\n if (!isToolUIPart(part) || part.state !== 'approval-responded') {\n return part;\n }\n if (part.approval.approved === false) {\n const denied: ApprovalToolPart = {\n ...part,\n state: 'output-denied',\n approval: { ...part.approval, approved: false },\n };\n return denied;\n }\n const failed: ApprovalToolPart = {\n ...part,\n state: 'output-error',\n errorText: error,\n approval: { ...part.approval, approved: true },\n };\n return failed;\n }),\n };\n await engine.continue(assistant(updated));\n }\n\n async reconcileTerminalContinuation(\n conversation: ConversationId,\n streamId: string,\n status: 'completed' | 'failed' | 'cancelled',\n error?: string | null,\n ): Promise<void> {\n if (status === 'completed') {\n await this.settleDeniedApprovals(conversation, streamId);\n } else {\n await this.settleFailedApprovals(\n conversation,\n streamId,\n error ?? `approval continuation ${status}`,\n );\n }\n await this.#queue.resumeParked(conversation.chatId);\n }\n\n async retryIdempotentContinuation(\n conversation: ConversationId,\n streamId: string,\n tools: ZukhrufToolSet,\n ): Promise<boolean> {\n const head = (await this.#engineFor(conversation).getMessages()).at(-1);\n if (head?.role !== 'assistant' || head.id !== streamId) return false;\n const approved = head.parts.filter(\n (part): part is ApprovalToolPart =>\n isToolUIPart(part) &&\n part.state === 'approval-responded' &&\n part.approval.approved === true,\n );\n const retryable =\n approved.length > 0 &&\n approved.every((part) => {\n const tool = tools[getToolName(part)];\n return (\n tool?.recovery === 'idempotent' && typeof tool.execute === 'function'\n );\n });\n if (!retryable) return false;\n\n await this.#queue.push({\n kind: 'continuation',\n streamId,\n chatId: conversation.chatId,\n userId: conversation.userId,\n recovery: 'idempotent',\n });\n return true;\n }\n\n async applyDecision(turn: ApprovalTurnRef): Promise<boolean> {\n const engine = this.#engineFor(turn);\n const head = (await engine.getMessages()).at(-1);\n if (head?.role !== 'assistant' || head.id !== turn.streamId) return false;\n\n const part = this.#findToolPart(head, turn.toolCallId);\n if (part?.approval?.id !== turn.approvalId) return false;\n if (part.approval.approved !== undefined) return false;\n if (part.state !== 'approval-requested') return false;\n\n const responded: ApprovalToolPart = {\n ...part,\n state: 'approval-responded',\n approval: { ...part.approval, ...turn.decision },\n };\n const updated: UIMessage = {\n ...head,\n parts: head.parts.map((candidate) =>\n candidate === part ? responded : candidate,\n ),\n };\n await engine.continue(assistant(updated));\n return !this.#hasUnansweredApprovals(updated);\n }\n\n async recoverUnstartedContinuation(\n turn: TurnRef,\n streamId: string,\n ): Promise<boolean> {\n if (turn.kind === 'approval') await this.applyDecision(turn);\n const head = (await this.#engineFor(turn).getMessages()).at(-1);\n if (\n head?.role !== 'assistant' ||\n head.id !== streamId ||\n this.#hasUnansweredApprovals(head) ||\n !head.parts.some(\n (part) => isToolUIPart(part) && part.state === 'approval-responded',\n )\n ) {\n return false;\n }\n\n await this.#queue.push({\n kind: 'continuation',\n streamId,\n chatId: turn.chatId,\n userId: turn.userId,\n recovery: 'handoff',\n });\n return true;\n }\n\n async #respond(\n operation: 'approve' | 'deny',\n conversation: ConversationId,\n toolCallId: string,\n approval: { approved: true } | { approved: false; reason?: string },\n ) {\n const head = (await this.#engineFor(conversation).getMessages()).at(-1);\n if (head?.role !== 'assistant') {\n throw new Error(\n `ApprovalController.${operation}: no paused turn \u2014 the chain head is not an assistant message`,\n );\n }\n const part = this.#findToolPart(head, toolCallId);\n if (!part) {\n throw new Error(\n `ApprovalController.${operation}: no tool call \"${toolCallId}\" on the paused turn`,\n );\n }\n if (!part.approval) {\n throw new Error(\n `ApprovalController.${operation}: tool call \"${toolCallId}\" is not awaiting approval`,\n );\n }\n const jobId = approvalJobId(conversation, part.approval.id);\n if (part.approval.approved !== undefined) {\n if (part.approval.approved !== approval.approved) {\n throw new Error(\n `ApprovalController.${operation}: approval already answered with a different decision`,\n );\n }\n return { id: head.id, jobId, status: 'already-applied' as const };\n }\n if (part.state !== 'approval-requested') {\n throw new Error(\n `ApprovalController.${operation}: tool call \"${toolCallId}\" is not awaiting approval`,\n );\n }\n\n const result = await this.#queue.push({\n kind: 'approval',\n streamId: head.id,\n chatId: conversation.chatId,\n userId: conversation.userId,\n toolCallId,\n approvalId: part.approval.id,\n decision: approval,\n });\n return {\n id: head.id,\n jobId,\n status: result.inserted\n ? ('queued' as const)\n : ('already-queued' as const),\n };\n }\n\n #pendingToolPart(message: UIMessage) {\n return message.parts.find(\n (part) =>\n isToolUIPart(part) &&\n !ApprovalController.#settledToolStates.has(part.state),\n );\n }\n\n #hasUnansweredApprovals(message: UIMessage): boolean {\n return message.parts.some(\n (part) => isToolUIPart(part) && part.state === 'approval-requested',\n );\n }\n\n #findToolPart(\n message: UIMessage,\n toolCallId: string,\n ): ApprovalToolPart | undefined {\n return message.parts.find(\n (part): part is ApprovalToolPart =>\n isToolUIPart(part) && part.toolCallId === toolCallId,\n );\n }\n\n #engineFor({ chatId, userId }: ConversationId): ContextEngine {\n return new ContextEngine({ store: this.#store, chatId, userId });\n }\n}\n", "import { v5 as uuidv5 } from 'uuid';\n\nimport { conversationNamespace } from '../control-plane/agent-turn-id.ts';\nimport type { ConversationId } from '../mailbox/types.ts';\n\nexport function approvalJobId(\n conversation: ConversationId,\n approvalId: string,\n): string {\n return uuidv5(`approval:${approvalId}`, conversationNamespace(conversation));\n}\n", "import type { ContextFragment } from '@deepagents/context';\n\nexport function defineInstructions(...fragments: ContextFragment[]) {\n return fragments;\n}\n", "import { DatabaseSync } from 'node:sqlite';\n\nimport {\n type MailboxEndTurnResult,\n type MailboxEnqueueResult,\n MailboxStore,\n} from './store.ts';\nimport {\n type ConversationId,\n type InterAgentCommunication,\n InterAgentCommunicationType,\n} from './types.ts';\n\nconst DDL = `\n PRAGMA journal_mode = WAL;\n PRAGMA synchronous = NORMAL;\n\n CREATE TABLE IF NOT EXISTS zukhruf_mailbox_items (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n recipient_chat_id TEXT NOT NULL,\n recipient_user_id TEXT NOT NULL,\n communication TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS zukhruf_mailbox_activity (\n recipient_chat_id TEXT NOT NULL,\n recipient_user_id TEXT NOT NULL,\n turn_id TEXT NOT NULL,\n PRIMARY KEY (recipient_chat_id, recipient_user_id)\n );\n\n CREATE TABLE IF NOT EXISTS zukhruf_mailbox_consumed_terminal_ids (\n communication_id TEXT PRIMARY KEY\n );\n\n CREATE INDEX IF NOT EXISTS zukhruf_mailbox_recipient_sequence\n ON zukhruf_mailbox_items (\n recipient_chat_id,\n recipient_user_id,\n sequence\n );\n\n CREATE UNIQUE INDEX IF NOT EXISTS zukhruf_mailbox_communication_id\n ON zukhruf_mailbox_items (\n json_extract(communication, '$.id')\n );\n`;\n\nconst BUSY_TIMEOUT_MS = 5_000;\n\n/** SQLite-backed mailbox for durable cross-process delivery. */\nexport class SqliteMailboxStore extends MailboxStore implements Disposable {\n #database: DatabaseSync;\n #closed = false;\n\n constructor(path: string) {\n super();\n this.#database = new DatabaseSync(path, { timeout: BUSY_TIMEOUT_MS });\n this.#database.exec(DDL);\n }\n\n override async beginTurn(\n recipient: ConversationId,\n turnId: string,\n ): Promise<void> {\n this.#transaction(() => {\n this.#database\n .prepare(\n `INSERT INTO zukhruf_mailbox_activity (\n recipient_chat_id,\n recipient_user_id,\n turn_id\n ) VALUES (?, ?, ?)\n ON CONFLICT (recipient_chat_id, recipient_user_id)\n DO UPDATE SET turn_id = excluded.turn_id`,\n )\n .run(recipient.chatId, recipient.userId, turnId);\n });\n }\n\n override async enqueue(\n communication: InterAgentCommunication,\n ): Promise<MailboxEnqueueResult> {\n return this.#transaction(() => {\n const consumedTerminal =\n communication.type === InterAgentCommunicationType.FinalAnswer &&\n this.#hasConsumedTerminal(communication.id);\n if (!consumedTerminal) {\n this.#database\n .prepare(\n `INSERT OR IGNORE INTO zukhruf_mailbox_items (\n recipient_chat_id,\n recipient_user_id,\n communication\n ) VALUES (?, ?, ?)`,\n )\n .run(\n communication.recipient.chatId,\n communication.recipient.userId,\n JSON.stringify(communication),\n );\n }\n return {\n recipientActive: this.#isTurnActive(communication.recipient),\n };\n });\n }\n\n override async endTurn(\n recipient: ConversationId,\n turnId: string,\n ): Promise<MailboxEndTurnResult> {\n return this.#transaction(() => {\n const result = this.#database\n .prepare(\n `DELETE FROM zukhruf_mailbox_activity\n WHERE recipient_chat_id = ?\n AND recipient_user_id = ?\n AND turn_id = ?`,\n )\n .run(recipient.chatId, recipient.userId, turnId);\n return {\n hasPending: this.#hasPending(recipient),\n turnEnded: result.changes > 0,\n };\n });\n }\n\n override async hasPending(recipient: ConversationId): Promise<boolean> {\n return this.#hasPending(recipient);\n }\n\n #hasPending(recipient: ConversationId): boolean {\n const row = this.#database\n .prepare(\n `SELECT 1\n FROM zukhruf_mailbox_items\n WHERE recipient_chat_id = ?\n AND recipient_user_id = ?\n LIMIT 1`,\n )\n .get(recipient.chatId, recipient.userId);\n return row !== undefined;\n }\n\n #isTurnActive(recipient: ConversationId): boolean {\n const row = this.#database\n .prepare(\n `SELECT 1\n FROM zukhruf_mailbox_activity\n WHERE recipient_chat_id = ?\n AND recipient_user_id = ?\n LIMIT 1`,\n )\n .get(recipient.chatId, recipient.userId);\n return row !== undefined;\n }\n\n #hasConsumedTerminal(communicationId: string): boolean {\n const row = this.#database\n .prepare(\n `SELECT 1\n FROM zukhruf_mailbox_consumed_terminal_ids\n WHERE communication_id = ?\n LIMIT 1`,\n )\n .get(communicationId);\n return row !== undefined;\n }\n\n override async drain(\n recipient: ConversationId,\n ): Promise<InterAgentCommunication[]> {\n return this.#drain(recipient, false);\n }\n\n override async drainLeadingQueueOnly(\n recipient: ConversationId,\n ): Promise<InterAgentCommunication[]> {\n return this.#drain(recipient, true);\n }\n\n #drain(\n recipient: ConversationId,\n leadingQueueOnly: boolean,\n ): InterAgentCommunication[] {\n return this.#transaction(() => {\n const rows = this.#database\n .prepare(\n `SELECT sequence, communication\n FROM zukhruf_mailbox_items\n WHERE recipient_chat_id = ?\n AND recipient_user_id = ?\n ORDER BY sequence`,\n )\n .all(recipient.chatId, recipient.userId) as Array<{\n sequence: number;\n communication: string;\n }>;\n const items = rows.map((row) => ({\n sequence: row.sequence,\n communication: JSON.parse(row.communication) as InterAgentCommunication,\n }));\n const firstTrigger = leadingQueueOnly\n ? items.findIndex(({ communication }) => communication.triggerTurn)\n : -1;\n const consumed =\n firstTrigger === -1 ? items : items.slice(0, firstTrigger);\n const lastConsumed = consumed.at(-1);\n if (lastConsumed) {\n // Only terminal IDs get durable tombstones. Ordinary random-ID mail\n // does not need permanent dedup state after FIFO consumption.\n const tombstone = this.#database.prepare(\n `INSERT OR IGNORE\n INTO zukhruf_mailbox_consumed_terminal_ids (communication_id)\n VALUES (?)`,\n );\n for (const { communication } of consumed) {\n if (communication.type === InterAgentCommunicationType.FinalAnswer) {\n tombstone.run(communication.id);\n }\n }\n this.#database\n .prepare(\n `DELETE FROM zukhruf_mailbox_items\n WHERE recipient_chat_id = ?\n AND recipient_user_id = ?\n AND sequence <= ?`,\n )\n .run(recipient.chatId, recipient.userId, lastConsumed.sequence);\n }\n return consumed.map(({ communication }) => communication);\n });\n }\n\n #transaction<T>(operation: () => T): T {\n this.#database.exec('BEGIN IMMEDIATE');\n try {\n const result = operation();\n this.#database.exec('COMMIT');\n return result;\n } catch (error) {\n try {\n this.#database.exec('ROLLBACK');\n } catch {\n // Preserve the operation error when SQLite already ended the transaction.\n }\n throw error;\n }\n }\n\n close(): void {\n if (this.#closed) return;\n this.#closed = true;\n this.#database.close();\n }\n\n [Symbol.dispose](): void {\n this.close();\n }\n}\n", "import type { ConversationId, InterAgentCommunication } from './types.ts';\n\nexport interface MailboxEnqueueResult {\n recipientActive: boolean;\n}\n\nexport interface MailboxEndTurnResult {\n hasPending: boolean;\n turnEnded: boolean;\n}\n\n/** Durable pending-mail storage. This is deliberately not an execution queue. */\nexport abstract class MailboxStore {\n abstract beginTurn(recipient: ConversationId, turnId: string): Promise<void>;\n\n abstract enqueue(\n communication: InterAgentCommunication,\n ): Promise<MailboxEnqueueResult>;\n\n abstract endTurn(\n recipient: ConversationId,\n turnId: string,\n ): Promise<MailboxEndTurnResult>;\n\n abstract hasPending(recipient: ConversationId): Promise<boolean>;\n\n /** Consumes the contiguous queue-only prefix, stopping before the first trigger. */\n abstract drainLeadingQueueOnly(\n recipient: ConversationId,\n ): Promise<InterAgentCommunication[]>;\n\n /** Draining is consumption: removes and returns all pending mail in FIFO order. */\n abstract drain(recipient: ConversationId): Promise<InterAgentCommunication[]>;\n}\n", "import type { JobWithMetadata, PgBoss } from 'pg-boss';\nimport { v7 as uuidv7 } from 'uuid';\n\nimport { approvalJobId } from '../runtime/approval-job-id.ts';\nimport {\n type ConsumeContext,\n type ConsumeOptions,\n type TurnActivity,\n type TurnPushResult,\n TurnQueue,\n type TurnRef,\n} from './turn-queue.ts';\n\nexport interface PgBossTurnQueueOptions {\n queue?: string;\n /** Required for custom DB adapters; must match the PgBoss schema. */\n schema?: string;\n /** Hard cap on one turn attempt; the job fails past this. */\n expireInSeconds?: number;\n /** Dead-worker detection window; must be >= 10 (pg-boss constraint). */\n heartbeatSeconds?: number;\n pollingIntervalSeconds?: number;\n}\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n\n/**\n * TurnQueue on pg-boss.\n *\n * - `key_strict_fifo` policy with `singletonKey = chatId` gives the per-chat\n * serialization contract structurally: one active turn per chat and strict\n * push order.\n * - `group.id = chatId` with global `groupConcurrency: 1` excludes an active\n * chat before pg-boss selects the next job, so its queued successor cannot\n * block ready turns from other chats.\n * - `retryLimit: 0` \u2014 a crashed turn is never silently re-run (its bash\n * already executed). It dead-letters instead.\n * - A failed job blocks its chat's key until acknowledged; the dead-letter\n * consumer is that acknowledgement: it reports the orphan via\n * `onOrphaned`, then deletes the source job, unblocking the chat.\n * - `deleteAfterSeconds: 0` \u2014 pg-boss never deletes a terminal job on a\n * wall-clock timer. That is what makes a parked (cancelled) turn durable: it\n * awaits its approval for as long as it takes, with no retention deadline.\n * Cleanup is commit-driven instead \u2014 `consume` deletes a job the moment its\n * turn runs and commits to the chain \u2014 so completed jobs don't accumulate.\n * (`retentionSeconds`, which governs still-`created` jobs, can't be 0; its\n * default 14d is never approached because a queued turn only waits behind one\n * running turn.)\n * - Interrupting an active turn aborts the adapter-local handler but leaves its\n * pg-boss row `active` until that handler exits. Cancelling the row itself\n * would surrender the strict-FIFO key early and let the successor overlap.\n * Cross-process handler abort comes from the runtime's durable stream\n * cancellation; this queue remains the scheduler-ordering authority.\n *\n * The `PgBoss` instance is borrowed: the caller `start()`s and `stop()`s it.\n */\nexport class PgBossTurnQueue extends TurnQueue {\n #boss: PgBoss;\n #queue: string;\n #schema: string;\n #schemaConfigurationError?: string;\n #table?: string;\n #expireInSeconds: number;\n #cancelIntentTtlMs: number;\n #heartbeatSeconds: number;\n #pollingIntervalSeconds: number;\n #active = new Map<string, Set<AbortController>>();\n #cancelIntents = new Map<string, number>();\n #cancelIntentExpiryTimer?: ReturnType<typeof globalThis.setTimeout>;\n\n constructor(boss: PgBoss, options: PgBossTurnQueueOptions = {}) {\n super();\n this.#boss = boss;\n this.#queue = options.queue ?? 'zukhruf-turns';\n const configuredSchema = (boss.getDb() as { config?: { schema?: unknown } })\n .config?.schema;\n const bossSchema =\n typeof configuredSchema === 'string' ? configuredSchema : undefined;\n this.#schema = options.schema ?? bossSchema ?? 'pgboss';\n if (options.schema === undefined && bossSchema === undefined) {\n this.#schemaConfigurationError =\n 'PgBossTurnQueue cannot read the schema from a custom PgBoss database adapter; pass the PgBoss schema in options.schema';\n } else if (\n options.schema !== undefined &&\n bossSchema !== undefined &&\n options.schema !== bossSchema\n ) {\n this.#schemaConfigurationError = `PgBossTurnQueue schema \"${options.schema}\" does not match the PgBoss schema \"${bossSchema}\"`;\n }\n this.#expireInSeconds = options.expireInSeconds ?? 3600;\n this.#cancelIntentTtlMs = this.#expireInSeconds * 1_000;\n if (\n !Number.isFinite(this.#expireInSeconds) ||\n this.#expireInSeconds <= 0 ||\n !Number.isSafeInteger(this.#cancelIntentTtlMs) ||\n this.#cancelIntentTtlMs > Number.MAX_SAFE_INTEGER - Date.now()\n ) {\n throw new Error(\n 'PgBossTurnQueue expireInSeconds must be a finite positive duration',\n );\n }\n this.#heartbeatSeconds = options.heartbeatSeconds ?? 30;\n this.#pollingIntervalSeconds = options.pollingIntervalSeconds ?? 1;\n }\n\n get queue(): string {\n return this.#queue;\n }\n\n get deadLetterQueue(): string {\n return `${this.#queue}-dead`;\n }\n\n async initialize(): Promise<void> {\n if (this.#schemaConfigurationError) {\n throw new Error(this.#schemaConfigurationError);\n }\n if (!(await this.#boss.getQueue(this.deadLetterQueue))) {\n await this.#boss.createQueue(this.deadLetterQueue);\n }\n let queue = await this.#boss.getQueue(this.#queue);\n if (!queue) {\n await this.#boss.createQueue(this.#queue, {\n policy: 'key_strict_fifo',\n retryLimit: 0,\n expireInSeconds: this.#expireInSeconds,\n heartbeatSeconds: this.#heartbeatSeconds,\n deleteAfterSeconds: 0,\n deadLetter: this.deadLetterQueue,\n });\n queue = await this.#boss.getQueue(this.#queue);\n }\n if (!queue) throw new Error(`Queue \"${this.#queue}\" was not initialized`);\n this.#table = queue.table;\n try {\n const catalog = await this.#boss.getDb().executeSql(\n `SELECT table_name AS \"table\"\n FROM ${PgBossTurnQueue.#quoteIdentifier(this.#schema)}.\"queue\"\n WHERE name = $1`,\n [this.#queue],\n );\n if (\n catalog.rows.length !== 1 ||\n (catalog.rows[0] as { table?: unknown }).table !== this.#table\n ) {\n throw new Error('queue catalog does not match');\n }\n await this.#boss\n .getDb()\n .executeSql(`SELECT 1 FROM ${this.#relation()} WHERE false`);\n } catch (cause) {\n throw new Error(\n `PgBossTurnQueue schema \"${this.#schema}\" does not match the PgBoss queue; pass the PgBoss schema in options.schema`,\n { cause },\n );\n }\n }\n\n async push(turn: TurnRef): Promise<TurnPushResult> {\n // pg-boss fetches `ORDER BY priority desc, created_on, id`. A monotonic\n // UUIDv7 job id makes the id tiebreak follow push order, so FIFO survives\n // created_on timestamp ties (millisecond-resolution clocks like PGlite).\n // Non-approval pushes create new jobs for at-least-once delivery. Approval\n // pushes use the persisted approval id, so pg-boss's id uniqueness makes\n // concurrent commands converge on the first inserted decision.\n // Approval and recovery jobs outrank waiting turns: revived parked jobs\n // keep their original (older) created_on, so priority is what puts the\n // command/recovery first.\n const jobId =\n turn.kind === 'approval'\n ? approvalJobId(turn, turn.approvalId)\n : uuidv7();\n const inserted = await this.#boss.send(this.#queue, turn, {\n id: jobId,\n singletonKey: turn.chatId,\n group: { id: turn.chatId },\n priority:\n turn.kind === 'approval' || turn.kind === 'continuation' ? 1 : 0,\n });\n if (inserted === null && turn.kind !== 'approval') {\n throw new Error(`PgBossTurnQueue job id collision: ${jobId}`);\n }\n return { jobId, inserted: inserted !== null };\n }\n\n override async getTurnActivity(\n conversation: Pick<TurnRef, 'chatId' | 'userId'>,\n ): Promise<TurnActivity> {\n const jobs = await this.#boss.findJobs<TurnRef>(this.#queue, {\n key: conversation.chatId,\n });\n const conversationJobs = jobs.filter(\n (job) =>\n job.data.userId === conversation.userId &&\n (job.state === 'created' ||\n job.state === 'retry' ||\n job.state === 'active'),\n );\n if (conversationJobs.some((job) => job.state === 'active')) {\n return 'running';\n }\n return conversationJobs.length > 0 ? 'queued' : 'idle';\n }\n\n override async getCurrentTurn(\n conversation: Pick<TurnRef, 'chatId' | 'userId'>,\n ): Promise<TurnRef | undefined> {\n const jobs = await this.#boss.findJobs<TurnRef>(this.#queue, {\n key: conversation.chatId,\n });\n return jobs\n .filter(\n (job) =>\n job.data.userId === conversation.userId &&\n (job.state === 'active' ||\n job.state === 'created' ||\n job.state === 'retry'),\n )\n .sort(PgBossTurnQueue.#interruptOrder)[0]?.data;\n }\n\n override async cancel(streamId: string): Promise<void> {\n this.#rememberCancelIntent(streamId);\n this.#abortLocal(streamId);\n const jobs = await this.#boss.findJobs<TurnRef>(this.#queue, {\n data: { streamId },\n });\n // An active row must retain the strict-FIFO key until its handler exits.\n // Delete only rows that are still queued at mutation time: a worker may\n // claim one after findJobs() returns, and pg-boss's public cancel/delete\n // methods do not provide the state predicate needed to close that race.\n // Remote active handlers are stopped by the runtime's durable stream\n // cancellation; their normal handler exit performs commit-driven GC.\n const queued = jobs\n .filter((job) => job.state === 'created' || job.state === 'retry')\n .map((job) => job.id);\n if (queued.length > 0) await this.#deleteIfStillQueued(queued);\n\n // Close the inverse race too: a local worker can claim after the first\n // controller scan but before the state-conditional delete.\n this.#abortLocal(streamId);\n const remaining = await this.#boss.findJobs<TurnRef>(this.#queue, {\n data: { streamId },\n });\n if (!remaining.some((job) => job.state === 'active')) {\n this.#forgetCancelIntent(streamId);\n }\n }\n\n async consume(\n handler: (turn: TurnRef, context: ConsumeContext) => Promise<void>,\n options: ConsumeOptions,\n ): Promise<AsyncDisposable> {\n const turnWorkerId = await this.#boss.work<TurnRef>(\n this.#queue,\n {\n localConcurrency: options.concurrency ?? 1,\n groupConcurrency: 1,\n pollingIntervalSeconds: this.#pollingIntervalSeconds,\n },\n async ([job]) => {\n let parked = false;\n const localAbort = new AbortController();\n const active = this.#active.get(job.data.streamId) ?? new Set();\n active.add(localAbort);\n this.#active.set(job.data.streamId, active);\n if (this.#hasCancelIntent(job.data.streamId)) localAbort.abort();\n try {\n await handler(job.data, {\n signal: AbortSignal.any([job.signal, localAbort.signal]),\n // Parking = self-cancel: a cancelled job stops blocking the chat's\n // key and is revived (original created_on, so original order) by\n // resumeParked(). The worker's completion of a cancelled job is a\n // clean no-op (probe-verified).\n park: async () => {\n parked = true;\n await this.#boss.cancel(this.#queue, job.id);\n },\n });\n } finally {\n active.delete(localAbort);\n if (active.size === 0) {\n this.#active.delete(job.data.streamId);\n this.#forgetCancelIntent(job.data.streamId);\n }\n }\n // Commit-driven GC. A handler that returns without parking has run its\n // turn to a terminal stream and committed to the chain (the permanent\n // record) \u2014 the job is spent, so delete it now instead of leaning on a\n // wall-clock timer (`deleteAfterSeconds: 0` disables that). Deleting an\n // active job from inside its own handler is safe: pg-boss's subsequent\n // completion finds no row and no-ops (probe-verified, zero errors). A\n // parked turn is skipped \u2014 it must stay `cancelled` for resumeParked to\n // revive it. A throwing handler is skipped too \u2014 the throw propagates to\n // pg-boss and the turn dead-letters.\n if (!parked) {\n await this.#boss.deleteJob(this.#queue, job.id);\n }\n },\n );\n\n const deadWorkerId = await this.#boss.work(\n this.deadLetterQueue,\n {\n includeMetadata: true,\n pollingIntervalSeconds: this.#pollingIntervalSeconds,\n },\n async ([job]: JobWithMetadata<TurnRef>[]) => {\n try {\n await options.onOrphaned(\n job.data,\n PgBossTurnQueue.#orphanError(job.output),\n );\n } finally {\n // The failed source job owns the strict-FIFO key. Reconciliation may\n // retry through this DLQ job, but it must never retain that key and\n // wedge every later turn in the conversation.\n if (job.sourceId) {\n await this.#boss.deleteJob(this.#queue, job.sourceId);\n }\n }\n },\n );\n\n return {\n [Symbol.asyncDispose]: async () => {\n await this.#boss.offWork(this.#queue, { id: turnWorkerId });\n await this.#boss.offWork(this.deadLetterQueue, { id: deadWorkerId });\n },\n };\n }\n\n async resumeParked(chatId: string): Promise<void> {\n // Revives every cancelled job for the chat. A revived USER-cancelled\n // turn is harmless \u2014 the consumer's terminal-stream check skips it \u2014\n // so no parked-vs-cancelled bookkeeping is needed here.\n const jobs = await this.#boss.findJobs(this.#queue, { key: chatId });\n const parked = jobs\n .filter((job) => job.state === 'cancelled')\n .map((job) => job.id);\n if (parked.length > 0) {\n await this.#boss.resume(this.#queue, parked);\n }\n }\n\n #abortLocal(streamId: string): void {\n for (const controller of this.#active.get(streamId) ?? []) {\n controller.abort();\n }\n }\n\n #rememberCancelIntent(streamId: string): void {\n this.#pruneCancelIntents();\n this.#cancelIntents.set(streamId, Date.now() + this.#cancelIntentTtlMs);\n this.#scheduleCancelIntentExpiry();\n }\n\n #hasCancelIntent(streamId: string): boolean {\n this.#pruneCancelIntents();\n return this.#cancelIntents.has(streamId);\n }\n\n #pruneCancelIntents(): void {\n const now = Date.now();\n for (const [streamId, expiresAt] of this.#cancelIntents) {\n if (expiresAt <= now) this.#cancelIntents.delete(streamId);\n }\n this.#scheduleCancelIntentExpiry();\n }\n\n #forgetCancelIntent(streamId: string): void {\n this.#cancelIntents.delete(streamId);\n this.#scheduleCancelIntentExpiry();\n }\n\n #scheduleCancelIntentExpiry(): void {\n if (this.#cancelIntentExpiryTimer !== undefined) {\n globalThis.clearTimeout(this.#cancelIntentExpiryTimer);\n this.#cancelIntentExpiryTimer = undefined;\n }\n let nextExpiry = Number.POSITIVE_INFINITY;\n for (const expiresAt of this.#cancelIntents.values()) {\n nextExpiry = Math.min(nextExpiry, expiresAt);\n }\n if (!Number.isFinite(nextExpiry)) return;\n\n const timer = globalThis.setTimeout(\n () => {\n if (this.#cancelIntentExpiryTimer !== timer) return;\n this.#cancelIntentExpiryTimer = undefined;\n this.#pruneCancelIntents();\n },\n Math.min(MAX_TIMEOUT_MS, Math.max(1, nextExpiry - Date.now())),\n );\n this.#cancelIntentExpiryTimer = timer;\n (timer as { unref?: () => void }).unref?.();\n }\n\n async #deleteIfStillQueued(ids: string[]): Promise<void> {\n if (!this.#table) {\n throw new Error('PgBossTurnQueue.initialize() must run before cancel()');\n }\n await this.#boss.getDb().executeSql(\n `DELETE FROM ${this.#relation()}\n WHERE name = $1\n AND id = ANY($2::uuid[])\n AND state IN ('created', 'retry')`,\n [this.#queue, ids],\n );\n }\n\n #relation(): string {\n if (!this.#table) {\n throw new Error(\n 'PgBossTurnQueue.initialize() must resolve its job table',\n );\n }\n return `${PgBossTurnQueue.#quoteIdentifier(this.#schema)}.${PgBossTurnQueue.#quoteIdentifier(this.#table)}`;\n }\n\n static #quoteIdentifier(identifier: string): string {\n return `\"${identifier.replaceAll('\"', '\"\"')}\"`;\n }\n\n static #orphanError(output: object | null | undefined): string {\n if (output && 'message' in output && typeof output.message === 'string') {\n return output.message;\n }\n return output ? JSON.stringify(output) : 'turn orphaned';\n }\n\n static #interruptOrder(\n left: JobWithMetadata<TurnRef>,\n right: JobWithMetadata<TurnRef>,\n ): number {\n if (left.state === 'active' && right.state !== 'active') return -1;\n if (left.state !== 'active' && right.state === 'active') return 1;\n if (left.priority !== right.priority) return right.priority - left.priority;\n const created = left.createdOn.getTime() - right.createdOn.getTime();\n return created || left.id.localeCompare(right.id);\n }\n}\n", "export type TurnRef = {\n streamId: string;\n chatId: string;\n userId: string;\n} & (\n | {\n kind: 'ask';\n /**\n * The user message, carried by the queue until the turn executes. It\n * enters the context chain only when the turn RUNS \u2014 enqueue-time\n * persistence would let a queued turn's message leak into the running\n * turn's prompt (and `chat()` streams into the chain head, which must\n * be THIS turn's placeholder).\n */\n input: string;\n }\n | {\n /**\n * Recovery-only re-execution of an existing stream. Normal approval\n * responses resume directly inside their approval job.\n */\n kind: 'continuation';\n recovery?: 'handoff' | 'idempotent';\n }\n | {\n kind: 'approval';\n toolCallId: string;\n approvalId: string;\n decision: { approved: true } | { approved: false; reason?: string };\n }\n | {\n /**\n * A mailbox wake-up. The communication payload remains in MailboxStore;\n * TurnQueue carries only the execution request and addressing.\n */\n kind: 'mailbox';\n }\n);\n\nexport interface TurnPushResult {\n jobId: string;\n inserted: boolean;\n}\n\nexport type ApprovalTurnRef = Extract<TurnRef, { kind: 'approval' }>;\n\nexport interface ConsumeContext {\n signal: AbortSignal;\n /**\n * Park the turn being handled: it settles WITHOUT executing and is not\n * delivered again until `resumeParked(chatId)`. Used by the queue-behind\n * gate \u2014 turns arriving while their chat awaits a tool approval.\n */\n park: () => Promise<void>;\n}\n\nexport interface ConsumeOptions {\n /** Max turns processed concurrently by this consumer (across chats). */\n concurrency?: number;\n /**\n * Fires for a turn whose handler crashed or whose worker died mid-turn.\n * After it resolves, the turn's chat is unblocked and its next queued\n * turn becomes eligible.\n */\n onOrphaned: (turn: TurnRef, error: string) => Promise<void>;\n}\n\nexport type TurnActivity = 'idle' | 'queued' | 'running';\n\n/**\n * Durable holding pen for pending turns.\n *\n * Contract every implementation must honor:\n * - `push` is durable: a pushed turn survives process death until consumed.\n * - Delivery is AT-LEAST-ONCE: a pushed non-approval turn is delivered until settled, and\n * duplicate pushes of the same `streamId` may each be delivered. Consumers\n * MUST be idempotent on `streamId` (the zukhruf runtime skips turns whose\n * stream row is terminal \u2014 a check that, unlike queue-side dedup, never\n * expires with job retention).\n * - Approval pushes use their persisted approval id as a deterministic job\n * identity. The first decision inserts; later decisions for that approval\n * report the existing job instead of adding a row.\n * - Per chat, at most ONE handler invocation is active at a time, and turns\n * run in the order they were pushed (strict FIFO per `chatId`) \u2014 this\n * covers duplicates too: they can never run concurrently or out of order.\n * - Turns from different chats may run concurrently.\n * - `getTurnActivity` distinguishes queued from active scheduler work for\n * status inspection; adapters must not silently fall back to stale history.\n * - `getCurrentTurn` returns the active turn, or otherwise the oldest eligible\n * queued turn, for exact interruption. `cancel` removes queued copies of that\n * exact stream and signals an adapter-local active handler, but an active turn\n * retains FIFO ownership until its handler exits. Cross-process handler abort\n * is the runtime stream-control layer's responsibility.\n * - A handler that throws (or a worker that dies mid-turn) does not retry:\n * the turn surfaces once through `onOrphaned`, then the chat unblocks.\n * - Mailbox payloads NEVER live here. A `{kind: 'mailbox'}` item is only a\n * durable wake request; the target MailboxStore remains the pending-input\n * authority.\n * - A parked turn (`context.park()`) is not delivered again until\n * `resumeParked(chatId)`; revived turns keep their original FIFO order,\n * and approval/recovery turns pushed for the chat outrank them.\n *\n * On platforms with native per-conversation serialization (e.g. Durable\n * Objects) this port is absorbed by the host rather than implemented.\n */\nexport abstract class TurnQueue {\n abstract push(turn: TurnRef): Promise<TurnPushResult>;\n\n /** Whether this conversation currently has queued or active scheduler work. */\n abstract getTurnActivity(\n conversation: Pick<TurnRef, 'chatId' | 'userId'>,\n ): Promise<TurnActivity>;\n\n /** Active turn, or the oldest eligible queued turn, for a conversation. */\n abstract getCurrentTurn(\n conversation: Pick<TurnRef, 'chatId' | 'userId'>,\n ): Promise<TurnRef | undefined>;\n\n /** Cancel queued copies and request local active cancellation by stream id. */\n abstract cancel(streamId: string): Promise<void>;\n\n abstract consume(\n handler: (turn: TurnRef, context: ConsumeContext) => Promise<void>,\n options: ConsumeOptions,\n ): Promise<AsyncDisposable>;\n\n abstract resumeParked(chatId: string): Promise<void>;\n}\n", "import type { UIMessageChunk } from 'ai';\nimport { styleText } from 'node:util';\n\nconst dim = (text: string) => styleText('dim', text);\nconst red = (text: string) => styleText('red', text);\n\nfunction oneLine(value: unknown, max = 88): string {\n const text = String(value ?? '')\n .replaceAll(/\\s+/g, ' ')\n .trim();\n return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;\n}\n\nfunction describeToolCall(toolName: string, input: unknown): string {\n const args = (input ?? {}) as Record<string, unknown>;\n switch (toolName) {\n case 'spawn_agent':\n return `\u21C4 spawn ${args.agent_type} \"${args.task_name}\" \u2014 ${args.message}`;\n case 'send_message':\n return `\u21C4 mail ${args.target} \u2014 ${args.message}`;\n case 'followup_task':\n return `\u21C4 follow-up ${args.target} \u2014 ${args.message}`;\n case 'list_agents':\n return '\u21C4 list agents';\n default:\n return `\u00B7 ${toolName}`;\n }\n}\n\n/**\n * Render one turn stream as a conversation: assistant text streams raw, each\n * tool call becomes a single dim line, and failures become a single red line.\n * Reasoning shows up only as one dim ellipsis so silence never looks like a\n * hang. Everything else in the chunk vocabulary is deliberately dropped.\n */\nexport async function renderTurn(\n stream: ReadableStream<UIMessageChunk>,\n): Promise<void> {\n const toolNames = new Map<string, string>();\n let midText = false;\n let thinkingShown = false;\n const breakText = () => {\n if (midText) process.stdout.write('\\n');\n midText = false;\n };\n\n for await (const chunk of stream) {\n switch (chunk.type) {\n case 'reasoning-start':\n if (!thinkingShown) {\n console.log(dim('\u2026'));\n thinkingShown = true;\n }\n break;\n case 'text-delta':\n process.stdout.write(chunk.delta);\n midText = true;\n break;\n case 'text-end':\n breakText();\n break;\n case 'tool-input-available':\n toolNames.set(chunk.toolCallId, chunk.toolName);\n breakText();\n console.log(dim(describeToolCall(chunk.toolName, chunk.input)));\n break;\n case 'tool-output-error':\n breakText();\n console.log(\n red(\n `\u2717 ${toolNames.get(chunk.toolCallId) ?? 'tool'}: ${oneLine(chunk.errorText)}`,\n ),\n );\n break;\n case 'error':\n breakText();\n console.log(red(`\u2717 ${oneLine(chunk.errorText)}`));\n break;\n case 'abort':\n breakText();\n console.log(dim('\u00B7 turn aborted'));\n break;\n }\n }\n breakText();\n}\n", "import { type DisposableSandbox, createBashTool } from '@deepagents/context';\n\nimport type { SandboxContext, ZukhrufSandbox } from '../agent.ts';\n\ntype WrapOptions = Omit<Parameters<typeof createBashTool>[0], 'sandbox'>;\n\nconst DEFAULT_WORKING_DIRECTORY = '/workspace';\n\n/** Wrap a backend with Zukhruf's Bash toolkit and working-directory metadata. */\nexport function defineSandbox(\n createBackend: (context: SandboxContext) => Promise<DisposableSandbox>,\n options?: WrapOptions,\n): (context: SandboxContext) => Promise<ZukhrufSandbox> {\n return async (context) => {\n const workingDirectory = options?.destination ?? DEFAULT_WORKING_DIRECTORY;\n\n return Object.assign(\n await createBashTool({\n sandbox: await createBackend(context),\n ...options,\n destination: workingDirectory,\n }),\n { workingDirectory },\n );\n };\n}\n", "import { type Tool, type ToolExecuteFunction, type ToolSet, tool } from 'ai';\n\nexport type ToolRecovery = 'idempotent';\n\nexport type ZukhrufTool<\n INPUT,\n OUTPUT,\n CONTEXT extends Record<string, unknown>,\n> = Tool<INPUT, OUTPUT, CONTEXT> & {\n /** Allows one automatic replay after a worker crash. */\n recovery?: ToolRecovery;\n};\n\nexport type ZukhrufToolSet = ToolSet &\n Record<string, { recovery?: ToolRecovery }>;\n\nexport function defineTool<\n INPUT,\n OUTPUT,\n CONTEXT extends Record<string, unknown>,\n>(\n definition: ZukhrufTool<INPUT, OUTPUT, CONTEXT> & {\n execute: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;\n },\n): ZukhrufTool<INPUT, OUTPUT, CONTEXT> & {\n execute: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;\n};\nexport function defineTool<\n INPUT,\n OUTPUT,\n CONTEXT extends Record<string, unknown>,\n>(\n definition: ZukhrufTool<INPUT, OUTPUT, CONTEXT>,\n): ZukhrufTool<INPUT, OUTPUT, CONTEXT>;\nexport function defineTool<INPUT, CONTEXT extends Record<string, unknown>>(\n definition: ZukhrufTool<INPUT, never, CONTEXT>,\n): ZukhrufTool<INPUT, never, CONTEXT>;\nexport function defineTool<OUTPUT, CONTEXT extends Record<string, unknown>>(\n definition: ZukhrufTool<never, OUTPUT, CONTEXT>,\n): ZukhrufTool<never, OUTPUT, CONTEXT>;\nexport function defineTool<CONTEXT extends Record<string, unknown>>(\n definition: ZukhrufTool<never, never, CONTEXT>,\n): ZukhrufTool<never, never, CONTEXT>;\nexport function defineTool(definition: unknown): unknown {\n return tool(definition as Tool);\n}\n"],
5
+ "mappings": ";;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSA,eAAsB,qBACpB,OACA,QACuC;AACvC,QAAM,aACJ,MAAM,oBAAoB,eACtB,MAAM,mBAAmB,OAAO,OAAO,MAAM,IAC7C;AACN,MAAI,YAAY;AACd,WAAO;AAAA,MACL,oBAAoB;AAAA,QAClB,eAAe,MAAM;AAAA,QACrB,oBAAoB;AAAA,QACpB,0BACE,WAAW,eAAe,mBAAmB,WAAW,MAAM,KAAK;AAAA,MACvE;AAAA,IACF;AAAA,EACF;AAEA,MACE,MAAM,qBAAqB,SAC1B,MAAM,oBAAoB,UACzB,MAAM,oBAAoB,iBAC5B;AACA,WAAO;AAAA,EACT;AAEA,QAAM,YAAY,MAAM,kBAAkB,OAAO,OAAO,SAAS;AACjE,MAAI,UAAU,WAAW,EAAG,QAAO;AAEnC,SAAO;AAAA,IACL,oBAAoB;AAAA,MAClB,eAAe,MAAM;AAAA,MACrB,mBAAmB,UAAU,KAAK,MAAM;AAAA,IAC1C;AAAA,EACF;AACF;AAEA,eAAe,mBACb,OACA,QACgE;AAChE,aAAW,QAAQ,QAAQ;AACzB,QAAI;AACF,UAAI,MAAM,KAAK,KAAK,KAAK,EAAG,QAAO,EAAE,KAAK;AAAA,IAC5C,SAAS,OAAO;AACd,cAAQ,MAAM,UAAU,KAAK,EAAE,sBAAsB,KAAK;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ACA,SACsD;AACtD,SAAO,OAAO,YAAY;AACxB,UAAM,mBAAmB,SAAS,eAAe;AAEjD,WAAO,OAAO;AAAA,MACZ,MAAM,eAAe;AAAA,QACnB,SAAS,MAAM,cAAc,OAAO;AAAA,QACpC,GAAG;AAAA,QACH,aAAa;AAAA,MACf,CAAC;AAAA,MACD,EAAE,iBAAiB;AAAA,IACrB;AAAA,EACF;AACF;;;ACzBA,SAA4D,QAAAC,aAAY;AA2CjE,SAAS,WAAW,YAA8B;AACvD,SAAOA,MAAK,UAAkB;AAChC;",
6
+ "names": ["path", "path", "ContextEngine", "uuidv5", "chat", "path", "uuidv5", "chat", "uuidv5", "uuidv5", "tool", "ContextEngine", "z", "z", "tool", "z", "z", "tool", "tool", "z", "tool", "z", "z", "tool", "tool", "z", "chat", "isRecord", "ContextEngine", "ContextEngine", "assistant", "uuidv5", "uuidv5", "assistant", "tool", "ContextEngine", "ContextEngine", "chat", "path", "tool"]
7
7
  }