@deepagents/experimental 4.2.1 → 5.0.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/README.md +18 -5
- package/dist/coding-agent-reminders/context.d.ts +15 -0
- package/dist/coding-agent-reminders/context.d.ts.map +1 -0
- package/dist/coding-agent-reminders/evaluate.d.ts +3 -0
- package/dist/coding-agent-reminders/evaluate.d.ts.map +1 -0
- package/dist/coding-agent-reminders/index.d.ts +5 -0
- package/dist/coding-agent-reminders/index.d.ts.map +1 -0
- package/dist/coding-agent-reminders/index.js +310 -0
- package/dist/coding-agent-reminders/index.js.map +7 -0
- package/dist/coding-agent-reminders/io.d.ts +4 -0
- package/dist/coding-agent-reminders/io.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/classifier.d.ts +10 -0
- package/dist/coding-agent-reminders/predicates/classifier.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/combinators.d.ts +6 -0
- package/dist/coding-agent-reminders/predicates/combinators.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/content.d.ts +7 -0
- package/dist/coding-agent-reminders/predicates/content.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/count.d.ts +4 -0
- package/dist/coding-agent-reminders/predicates/count.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/environment.d.ts +3 -0
- package/dist/coding-agent-reminders/predicates/environment.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/event.d.ts +3 -0
- package/dist/coding-agent-reminders/predicates/event.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/index.d.ts +8 -0
- package/dist/coding-agent-reminders/predicates/index.d.ts.map +1 -0
- package/dist/coding-agent-reminders/predicates/tool.d.ts +11 -0
- package/dist/coding-agent-reminders/predicates/tool.d.ts.map +1 -0
- package/dist/coding-agent-reminders/types.d.ts +86 -0
- package/dist/coding-agent-reminders/types.d.ts.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2036 -158
- package/dist/index.js.map +4 -4
- package/dist/zukhruf/agent-control-plane.d.ts +68 -0
- package/dist/zukhruf/agent-control-plane.d.ts.map +1 -0
- package/dist/zukhruf/agent-declaration-registry.d.ts +9 -0
- package/dist/zukhruf/agent-declaration-registry.d.ts.map +1 -0
- package/dist/zukhruf/agent-directory.d.ts +21 -0
- package/dist/zukhruf/agent-directory.d.ts.map +1 -0
- package/dist/zukhruf/agent-path.d.ts +15 -0
- package/dist/zukhruf/agent-path.d.ts.map +1 -0
- package/dist/zukhruf/agent-runtime.d.ts +53 -0
- package/dist/zukhruf/agent-runtime.d.ts.map +1 -0
- package/dist/zukhruf/agent-status-projector.d.ts +32 -0
- package/dist/zukhruf/agent-status-projector.d.ts.map +1 -0
- package/dist/zukhruf/agent-thread.d.ts +31 -0
- package/dist/zukhruf/agent-thread.d.ts.map +1 -0
- package/dist/zukhruf/agent-tool-context.d.ts +6 -0
- package/dist/zukhruf/agent-tool-context.d.ts.map +1 -0
- package/dist/zukhruf/agent-turn-executor.d.ts +19 -0
- package/dist/zukhruf/agent-turn-executor.d.ts.map +1 -0
- package/dist/zukhruf/agent-turn-id.d.ts +11 -0
- package/dist/zukhruf/agent-turn-id.d.ts.map +1 -0
- package/dist/zukhruf/agent.d.ts +13 -8
- package/dist/zukhruf/agent.d.ts.map +1 -1
- package/dist/zukhruf/approval-controller.d.ts +34 -0
- package/dist/zukhruf/approval-controller.d.ts.map +1 -0
- package/dist/zukhruf/approval-mutex.d.ts +5 -0
- package/dist/zukhruf/approval-mutex.d.ts.map +1 -0
- package/dist/zukhruf/index.d.ts +15 -11
- package/dist/zukhruf/index.d.ts.map +1 -1
- package/dist/zukhruf/index.js +1716 -152
- package/dist/zukhruf/index.js.map +4 -4
- package/dist/zukhruf/list-agents.d.ts +234 -0
- package/dist/zukhruf/list-agents.d.ts.map +1 -0
- package/dist/zukhruf/mailbox/coordinator.d.ts +22 -0
- package/dist/zukhruf/mailbox/coordinator.d.ts.map +1 -0
- package/dist/zukhruf/mailbox/sqlite.store.d.ts +16 -0
- package/dist/zukhruf/mailbox/sqlite.store.d.ts.map +1 -0
- package/dist/zukhruf/mailbox/store.d.ts +20 -0
- package/dist/zukhruf/mailbox/store.d.ts.map +1 -0
- package/dist/zukhruf/mailbox/types.d.ts +35 -0
- package/dist/zukhruf/mailbox/types.d.ts.map +1 -0
- package/dist/zukhruf/message-tools.d.ts +456 -0
- package/dist/zukhruf/message-tools.d.ts.map +1 -0
- package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts +2 -1
- package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts.map +1 -1
- package/dist/zukhruf/queue/turn-queue.d.ts +14 -0
- package/dist/zukhruf/queue/turn-queue.d.ts.map +1 -1
- package/dist/zukhruf/spawn-agent.d.ts +301 -0
- package/dist/zukhruf/spawn-agent.d.ts.map +1 -0
- package/dist/zukhruf/sqlite-approval-mutex.d.ts +17 -0
- package/dist/zukhruf/sqlite-approval-mutex.d.ts.map +1 -0
- package/package.json +14 -7
- package/dist/zukhruf/runtime.d.ts +0 -67
- package/dist/zukhruf/runtime.d.ts.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/zukhruf/index.ts", "../src/zukhruf/agent.ts", "../src/zukhruf/
|
|
4
|
-
"sourcesContent": ["export { defineAgent } from './agent.ts';\nexport type { AgentDeclaration, SandboxContext } from './agent.ts';\nexport { defineInstructions } from './instructions.ts';\nexport { defineTool } from './tool.ts';\nexport { defineSandbox } from './sandbox/define.ts';\nexport { createRuntime } from './runtime.ts';\nexport type {\n ConversationId,\n RuntimeOptions,\n TurnInput,\n WorkOptions,\n} from './runtime.ts';\nexport { TurnQueue } from './queue/turn-queue.ts';\nexport type {\n ConsumeContext,\n ConsumeOptions,\n TurnRef,\n} from './queue/turn-queue.ts';\nexport { PgBossTurnQueue } from './queue/pg-boss.turn-queue.ts';\nexport type { PgBossTurnQueueOptions } from './queue/pg-boss.turn-queue.ts';\n", "import type { ToolSet } from 'ai';\n\nimport type {\n AgentModel,\n AgentSandbox,\n ContextFragment,\n} from '@deepagents/context';\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 name: string;\n model: AgentModel;\n sandbox: (context: SandboxContext) => Promise<AgentSandbox>;\n instructions: ContextFragment[];\n tools?: ToolSet;\n}\n\nexport function defineAgent(declaration: {\n model: AgentModel;\n sandbox: (context: SandboxContext) => Promise<AgentSandbox>;\n instructions: ContextFragment[];\n tools?: ToolSet;\n name?: string;\n}): AgentDeclaration {\n return {\n name: declaration.name ?? 'agent',\n model: declaration.model,\n sandbox: declaration.sandbox,\n instructions: declaration.instructions,\n tools: declaration.tools,\n };\n}\n", "import type { ContextFragment } from '@deepagents/context';\n\nexport function defineInstructions(...fragments: ContextFragment[]) {\n return fragments;\n}\n", "/**\n * Declaration-layer tool definition: a pure passthrough of the AI SDK's\n * `tool()` (full generics, zero side effects). Set `needsApproval: true` to\n * pause the turn on this tool's call until `runtime.approve()`/`deny()`.\n */\nexport { tool as defineTool } from 'ai';\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 UIMessage, isToolUIPart } from 'ai';\n\nimport {\n ContextEngine,\n type ContextStore,\n PollingChangeSource,\n StreamManager,\n type StreamStore,\n agent,\n assistant,\n chat,\n user,\n} from '@deepagents/context';\n\nimport type { AgentDeclaration } from './agent.ts';\nimport type { ConsumeContext, TurnQueue, TurnRef } from './queue/turn-queue.ts';\n\nexport interface RuntimeOptions {\n store: ContextStore;\n streamStore: StreamStore;\n queue: TurnQueue;\n}\n\nexport interface ConversationId {\n chatId: string;\n userId: string;\n}\n\nexport interface WorkOptions {\n concurrency?: number;\n}\n\nexport interface TurnInput {\n /**\n * The ask's identity, supplied by the caller: any unique string (a client's\n * message id, or `crypto.randomUUID()` when the caller has no natural key).\n * It doubles as the stream id and the assistant message id. Enqueueing the\n * same id again reattaches to the existing turn instead of running it\n * twice; the first call's `input` wins.\n */\n id: string;\n input: string;\n}\n\nconst SETTLED_TOOL_STATES = new Set([\n 'output-available',\n 'output-error',\n 'output-denied',\n]);\n\nfunction pendingToolPart(message: UIMessage) {\n return message.parts.find(\n (part) => isToolUIPart(part) && !SETTLED_TOOL_STATES.has(part.state),\n );\n}\n\n/**\n * Executes an AgentDeclaration as a background agent, split into three roles:\n *\n * - `enqueue` \u2014 durably queue a turn (the queue carries the user message\n * until execution); executes nothing. Safe from any short-lived process.\n * - `work` \u2014 start a worker that consumes queued turns; each turn runs\n * start-to-finish in this process, serialized per chat by the TurnQueue.\n * - `observe` \u2014 reconnect/cancel from anywhere; never spins a sandbox.\n *\n * Plus the approval verbs: a turn pauses when the model calls a\n * `needsApproval` tool (the pause is pure data \u2014 a dangling tool part on the\n * chain head + a terminal stream); `approve`/`deny` resolve it and re-run the\n * turn as a continuation. Turns enqueued while a chat awaits approval QUEUE\n * BEHIND it (parked, revived in order after the continuation).\n */\nexport function createRuntime(\n declaration: AgentDeclaration,\n options: RuntimeOptions,\n) {\n const { store, streamStore, queue } = options;\n const manager = new StreamManager({\n store: streamStore,\n changeSource: new PollingChangeSource({ reads: streamStore }),\n });\n\n function engineFor({ chatId, userId }: ConversationId) {\n return new ContextEngine({ store, chatId, userId });\n }\n\n async function executeTurn(\n turn: TurnRef,\n { signal, park }: ConsumeContext,\n ): Promise<void> {\n const status = await streamStore.getStreamStatus(turn.streamId);\n if (status !== 'queued' && status !== 'running') return;\n\n const engine = engineFor(turn).set(...declaration.instructions);\n\n if (turn.kind === 'ask') {\n const head = (await engine.getMessages()).at(-1);\n if (head?.role === 'assistant' && pendingToolPart(head)) {\n await park();\n return;\n }\n engine.set(\n user(turn.input),\n assistant({ id: turn.streamId, role: 'assistant', parts: [] }),\n );\n await engine.save({ branch: true });\n }\n\n const sandbox = await declaration.sandbox({\n chatId: turn.chatId,\n userId: turn.userId,\n });\n const ai = agent({\n name: declaration.name,\n model: declaration.model,\n sandbox,\n context: engine,\n tools: declaration.tools,\n });\n\n const abort = new AbortController();\n const onWorkerAbort = () => abort.abort();\n signal.addEventListener('abort', onWorkerAbort, { once: true });\n try {\n const stream = await chat(ai, { abortSignal: abort.signal });\n await manager.persist(stream, turn.streamId, {\n onCancelDetected: () => abort.abort(),\n });\n } finally {\n signal.removeEventListener('abort', onWorkerAbort);\n }\n }\n\n async function respondToApproval(\n conversation: ConversationId,\n toolCallId: string,\n approval: { approved: true } | { approved: false; reason?: string },\n ) {\n const engine = engineFor(conversation);\n const head = (await engine.getMessages()).at(-1);\n if (head?.role !== 'assistant') {\n throw new Error(\n 'approve: no paused turn \u2014 the chain head is not an assistant message',\n );\n }\n const part = head.parts.find(\n (p) => isToolUIPart(p) && p.toolCallId === toolCallId,\n );\n if (!part || !isToolUIPart(part)) {\n throw new Error(\n `approve: no tool call \"${toolCallId}\" on the paused turn`,\n );\n }\n if (part.state !== 'approval-requested') {\n // Already responded (or settled) \u2014 idempotent reattach.\n return { id: head.id, stream: manager.watch(head.id) };\n }\n\n const responded = {\n ...part,\n state: 'approval-responded',\n approval: { ...part.approval, ...approval },\n };\n const updated: UIMessage = {\n ...head,\n parts: head.parts.map((p) => (p === part ? responded : p)),\n } as UIMessage;\n await engine.continue(assistant(updated));\n\n try {\n await manager.reopen(head.id);\n } catch {\n // Lost the benign race: a concurrent approve already reopened (stream\n // no longer terminal) and pushed the continuation. Reattach.\n return { id: head.id, stream: manager.watch(head.id) };\n }\n await queue.push({\n kind: 'continuation',\n streamId: head.id,\n chatId: conversation.chatId,\n userId: conversation.userId,\n });\n // Revive turns that parked behind the approval; the continuation's\n // priority guarantees it runs before them.\n await queue.resumeParked(conversation.chatId);\n return { id: head.id, stream: manager.watch(head.id) };\n }\n\n return {\n async enqueue({ chatId, userId }: ConversationId, turn: TurnInput) {\n if (!turn.id) {\n throw new Error(\n 'enqueue: turn id is required \u2014 it names the ask, making retries idempotent',\n );\n }\n // register is an upsert (ON CONFLICT DO NOTHING) and the queue is\n // at-least-once, so a retried enqueue may create a duplicate job \u2014 the\n // queue serializes it behind the original and executeTurn's terminal\n // check turns it into a no-op. The stream row, not the queue, is the\n // durable dedup: it never expires with job retention.\n await manager.register(turn.id);\n await queue.push({\n kind: 'ask',\n streamId: turn.id,\n chatId,\n userId,\n input: turn.input,\n });\n return { id: turn.id, stream: manager.watch(turn.id) };\n },\n\n async approve(conversation: ConversationId, input: { toolCallId: string }) {\n return respondToApproval(conversation, input.toolCallId, {\n approved: true,\n });\n },\n\n async deny(\n conversation: ConversationId,\n input: { toolCallId: string; reason?: string },\n ) {\n return respondToApproval(conversation, input.toolCallId, {\n approved: false,\n reason: input.reason,\n });\n },\n\n observe({ chatId, userId }: ConversationId) {\n const engine = engineFor({ chatId, userId });\n\n async function headStreamId(): Promise<string | undefined> {\n const head = await engine.headMessage();\n return head?.name === 'assistant' ? head.id : undefined;\n }\n\n return {\n engine,\n async resume() {\n const id = await headStreamId();\n if (!id) return null;\n const status = await streamStore.getStreamStatus(id);\n return status ? manager.watch(id) : null;\n },\n async cancel(streamId?: string) {\n const id = streamId ?? (await headStreamId());\n if (!id) return;\n const status = await streamStore.getStreamStatus(id);\n if (status === 'queued' || status === 'running') {\n await manager.cancel(id);\n }\n },\n };\n },\n\n async work(options?: WorkOptions): Promise<AsyncDisposable> {\n return queue.consume(executeTurn, {\n concurrency: options?.concurrency,\n onOrphaned: async (turn, error) => {\n const status = await streamStore.getStreamStatus(turn.streamId);\n if (status === 'queued' || status === 'running') {\n await streamStore.updateStreamStatus(turn.streamId, 'failed', {\n error,\n });\n }\n },\n });\n },\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 * Re-execution of an existing (reopened) stream after a tool approval\n * or denial. Carries no payload: the chain was already updated in\n * place by `approve()`/`deny()`.\n */\n kind: 'continuation';\n }\n);\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\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 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 * - 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 * - 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 * - A parked turn (`context.park()`) is not delivered again until\n * `resumeParked(chatId)`; revived turns keep their original FIFO order,\n * and a `'continuation'` turn pushed for the chat outranks 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<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 { JobWithMetadata, PgBoss } from 'pg-boss';\nimport { v7 as uuidv7 } from 'uuid';\n\nimport {\n type ConsumeContext,\n type ConsumeOptions,\n TurnQueue,\n type TurnRef,\n} from './turn-queue.ts';\n\nexport interface PgBossTurnQueueOptions {\n queue?: 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\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, strict\n * push order, cross-chat concurrency.\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 *\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 #expireInSeconds: number;\n #heartbeatSeconds: number;\n #pollingIntervalSeconds: number;\n\n constructor(boss: PgBoss, options: PgBossTurnQueueOptions = {}) {\n super();\n this.#boss = boss;\n this.#queue = options.queue ?? 'zukhruf-turns';\n this.#expireInSeconds = options.expireInSeconds ?? 3600;\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 (!(await this.#boss.getQueue(this.deadLetterQueue))) {\n await this.#boss.createQueue(this.deadLetterQueue);\n }\n if (!(await this.#boss.getQueue(this.#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 }\n }\n\n async push(turn: TurnRef): Promise<void> {\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 // Every push creates a job \u2014 delivery is at-least-once; turn-level dedup\n // lives in the consumer (the runtime skips terminal streams).\n // Continuations outrank waiting turns: revived parked jobs keep their\n // original (older) created_on, so priority is what puts the continuation\n // first.\n await this.#boss.send(this.#queue, turn, {\n id: uuidv7(),\n singletonKey: turn.chatId,\n priority: turn.kind === 'continuation' ? 1 : 0,\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 pollingIntervalSeconds: this.#pollingIntervalSeconds,\n },\n async ([job]) => {\n let parked = false;\n await handler(job.data, {\n signal: job.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 // 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 await options.onOrphaned(job.data, orphanError(job.output));\n if (job.sourceId) {\n await this.#boss.deleteJob(this.#queue, job.sourceId);\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\nfunction 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"],
|
|
5
|
-
"mappings": ";;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC0BO,SAAS,YAAY,aAMP;AACnB,SAAO;AAAA,IACL,MAAM,YAAY,QAAQ;AAAA,IAC1B,OAAO,YAAY;AAAA,IACnB,SAAS,YAAY;AAAA,IACrB,cAAc,YAAY;AAAA,IAC1B,OAAO,YAAY;AAAA,EACrB;AACF;;;ACtCO,SAAS,sBAAsB,WAA8B;AAClE,SAAO;AACT;;;ACCA,SAAiB,YAAkB;;;ACLnC;AAAA,EAGE;AAAA,OACK;AAMA,SAAS,cACd,eACA,SACoD;AACpD,SAAO,OAAO,YACZ,eAAe,EAAE,SAAS,MAAM,cAAc,OAAO,GAAG,GAAG,QAAQ,CAAC;AACxE;;;AChBA,SAAyB,oBAAoB;AAE7C;AAAA,EACE;AAAA,EAEA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAgCP,IAAM,sBAAsB,oBAAI,IAAI;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,SAAS,gBAAgB,SAAoB;AAC3C,SAAO,QAAQ,MAAM;AAAA,IACnB,CAAC,SAAS,aAAa,IAAI,KAAK,CAAC,oBAAoB,IAAI,KAAK,KAAK;AAAA,EACrE;AACF;AAiBO,SAAS,cACd,aACA,SACA;AACA,QAAM,EAAE,OAAO,aAAa,MAAM,IAAI;AACtC,QAAM,UAAU,IAAI,cAAc;AAAA,IAChC,OAAO;AAAA,IACP,cAAc,IAAI,oBAAoB,EAAE,OAAO,YAAY,CAAC;AAAA,EAC9D,CAAC;AAED,WAAS,UAAU,EAAE,QAAQ,OAAO,GAAmB;AACrD,WAAO,IAAI,cAAc,EAAE,OAAO,QAAQ,OAAO,CAA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AAG,YAAY;AACjC,cAAM,KAAK,MAAM,QAAQ,KAAK,QAAQ,EAAE,IAAI,aAAa,CAAC;AAC1D,cAAM,KAAK,MAAM,QAAQ,KAAK,iBAAiB,EAAE,IAAI,aAAa,CAAC;AAAA,MACrE;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,aAAa,QAA+B;AAIhD,UAAM,OAAO,MAAM,KAAK,MAAM,SAAS,KAAK,QAAQ,EAAE,KAAK,OAAO,CAAC;AACnE,UAAM,SAAS,KACZ,OAAO,CAAC,QAAQ,IAAI,UAAU,WAAW,EACzC,IAAI,CAAC,QAAQ,IAAI,EAAE;AACtB,QAAI,OAAO,SAAS,GAAG;AACrB,YAAM,KAAK,MAAM,OAAO,KAAK,QAAQ,MAAM;AAAA,IAC7C;AAAA,EACF;AACF;AAEA,SAAS,YAAY,QAA2C;AAC9D,MAAI,UAAU,aAAa,UAAU,OAAO,OAAO,YAAY,UAAU;AACvE,WAAO,OAAO;AAAA,EAChB;AACA,SAAO,SAAS,KAAK,UAAU,MAAM,IAAI;AAC3C;",
|
|
6
|
-
"names": ["
|
|
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-path.ts", "../src/zukhruf/agent-thread.ts", "../src/zukhruf/agent.ts", "../src/zukhruf/agent-runtime.ts", "../src/zukhruf/agent-control-plane.ts", "../src/zukhruf/agent-declaration-registry.ts", "../src/zukhruf/agent-directory.ts", "../src/zukhruf/agent-status-projector.ts", "../src/zukhruf/mailbox/types.ts", "../src/zukhruf/agent-turn-id.ts", "../src/zukhruf/agent-turn-executor.ts", "../src/zukhruf/list-agents.ts", "../src/zukhruf/message-tools.ts", "../src/zukhruf/spawn-agent.ts", "../src/zukhruf/approval-controller.ts", "../src/zukhruf/mailbox/coordinator.ts", "../src/zukhruf/approval-mutex.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/sandbox/define.ts", "../src/zukhruf/sqlite-approval-mutex.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-thread.ts';\nexport * from './agent.ts';\nexport * from './agent-path.ts';\nexport * from './agent-runtime.ts';\nexport * from './approval-mutex.ts';\nexport type { TurnInput } from './agent-control-plane.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 './sandbox/define.ts';\nexport * from './sqlite-approval-mutex.ts';\nexport * from './tool.ts';\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 { AgentPath } from './agent-path.ts';\nimport type { ConversationId } from './mailbox/types.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 type { ToolSet, generateText } from 'ai';\n\nimport type {\n AgentModel,\n AgentSandbox,\n ContextFragment,\n} from '@deepagents/context';\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?: ToolSet;\n subagents?: AgentDeclaration[];\n telemetry?: Parameters<typeof generateText>[0]['telemetry'];\n}\n\nexport interface DefinedAgentDeclaration extends AgentDeclaration {\n tools: ToolSet;\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", "import {\n ContextEngine,\n type ContextStore,\n PollingChangeSource,\n StreamManager,\n type StreamStore,\n} from '@deepagents/context';\n\nimport { AgentControlPlane, type TurnInput } from './agent-control-plane.ts';\nimport { AgentDeclarationRegistry } from './agent-declaration-registry.ts';\nimport { AgentDirectory } from './agent-directory.ts';\nimport { AgentStatusProjector } from './agent-status-projector.ts';\nimport { AgentTurnExecutor } from './agent-turn-executor.ts';\nimport { AgentTurnId } from './agent-turn-id.ts';\nimport type { AgentDeclaration } from './agent.ts';\nimport { ApprovalController } from './approval-controller.ts';\nimport type { ApprovalMutex } from './approval-mutex.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 type { TurnQueue, TurnRef } from './queue/turn-queue.ts';\n\nexport interface AgentRuntimeOptions {\n store: ContextStore;\n streamStore: StreamStore;\n queue: TurnQueue;\n /** Durable pending inter-agent input. Distinct from the TurnQueue scheduler. */\n mailboxStore: MailboxStore;\n /** Cross-process serialization for assistant-message approval transitions. */\n approvalMutex: ApprovalMutex;\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 declarations = new AgentDeclarationRegistry(root);\n const directory = new AgentDirectory(options.store);\n const streams = new StreamManager({\n store: options.streamStore,\n changeSource: new PollingChangeSource({ reads: options.streamStore }),\n });\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 streams,\n queue: options.queue,\n mutex: options.approvalMutex,\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 controlPlane = new AgentControlPlane({\n root,\n streams,\n queue: options.queue,\n mailbox,\n declarations,\n directory,\n statusProjector,\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 });\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 if (\n 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 === '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 { AgentDeclarationRegistry } from './agent-declaration-registry.ts';\nimport { AgentDirectory } from './agent-directory.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 { 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';\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}\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}\n\nexport interface SpawnAgentOutput {\n task_name: string;\n agent_path: 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\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 }\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.enqueue(child.conversation, {\n id: requestId,\n input: input.message,\n });\n return { task_name: input.taskName, agent_path: 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 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 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 { AgentThread } from './agent-thread.ts';\nimport type { ConversationId } from './mailbox/types.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.listTree(thread)).find((candidate) =>\n candidate.path.equals(path),\n );\n if (match) return match;\n throw new Error(`agent path \"${path}\" does not exist in this tree`);\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, isTextUIPart } from 'ai';\n\nimport {\n ContextEngine,\n type ContextStore,\n type StreamManager,\n type StreamStatus,\n} from '@deepagents/context';\n\nimport type { AgentDirectory } from './agent-directory.ts';\nimport type { AgentThread } from './agent-thread.ts';\nimport type { ApprovalController } from './approval-controller.ts';\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';\n\nexport type ListedAgentStatus =\n | 'pending_init'\n | 'running'\n | 'waiting_approval'\n | 'interrupted'\n | { completed: string | null }\n | { errored: string };\n\nexport interface ListedAgent {\n agent_name: string;\n agent_status: ListedAgentStatus;\n last_task_message: string | null;\n}\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 activity = await this.#queue.getTurnActivity(thread.conversation);\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 = 'waiting_approval';\n }\n if (\n thread.conversation.chatId === currentTurn.chatId ||\n activity === 'running' ||\n (activity === 'queued' && stream !== undefined)\n ) {\n status = 'running';\n }\n\n return {\n agent_name: thread.path.toString(),\n agent_status: status,\n last_task_message: thread.path.isRoot\n ? 'Main thread'\n : AgentStatusProjector.#lastUserMessage(messages),\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 const content =\n stream.status === 'failed'\n ? `Agent failed: ${stream.error || 'unknown error'}`\n : stream.status === 'cancelled'\n ? 'Agent was interrupted.'\n : text || 'Agent completed without a text response.';\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 #lastUserMessage(messages: UIMessage[]): string | null {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index];\n if (message?.role === 'user') {\n return AgentStatusProjector.#messageText(message) || null;\n }\n }\n return null;\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 { 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 { 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 = AgentTurnId.#scope(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}:${AgentTurnId.#scope(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 static #scope(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}\n", "import type { UIMessage } from 'ai';\n\nimport {\n ContextEngine,\n type ContextStore,\n type StreamManager,\n agent,\n assistant,\n chat,\n user,\n} from '@deepagents/context';\n\nimport type { AgentControlPlane } from './agent-control-plane.ts';\nimport type { AgentToolContext } from './agent-tool-context.ts';\nimport type { ApprovalController } from './approval-controller.ts';\nimport { listAgentsTool } from './list-agents.ts';\nimport type { MailboxCoordinator } from './mailbox/coordinator.ts';\nimport type {\n ConversationId,\n InterAgentCommunication,\n} from './mailbox/types.ts';\nimport { followupTaskTool, sendMessageTool } from './message-tools.ts';\nimport type { ConsumeContext, TurnRef } from './queue/turn-queue.ts';\nimport { spawnAgentTool } from './spawn-agent.ts';\n\nexport interface AgentTurnExecutorOptions {\n store: ContextStore;\n streams: StreamManager;\n controlPlane: AgentControlPlane;\n mailbox: MailboxCoordinator;\n approvals: ApprovalController;\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\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 }\n\n async execute(turn: TurnRef, context: ConsumeContext): Promise<void> {\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 engine = this.#engineFor(turn).set(...declaration.instructions);\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 const communications =\n turn.kind === 'ask'\n ? await this.#mailbox.drainLeadingQueueOnly(turn)\n : turn.kind === 'mailbox'\n ? 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 spawn_agent: spawnAgentTool,\n send_message: sendMessageTool,\n followup_task: followupTaskTool,\n list_agents: listAgentsTool,\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 #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 type { ListedAgent } from './agent-control-plane.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\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 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 = { target: 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 context.controlPlane.sendMessage(context.actor, input),\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 context.controlPlane.followupTask(context.actor, input),\n});\n", "import { tool } from 'ai';\nimport { z } from 'zod';\n\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});\n\ntype SpawnAgentInput = z.infer<typeof spawnAgentInputSchema>;\n\nexport const spawnAgentTool = tool<\n SpawnAgentInput,\n { task_name: string; agent_path: string },\n AgentToolContext\n>({\n description: ({ context }) => {\n const available = (context.actor.declaration.subagents ?? [])\n .map((subagent) => subagent.name)\n .join(', ');\n return `Spawn an independent subagent. Available agent types: ${available || 'none'}.`;\n },\n inputSchema: spawnAgentInputSchema,\n execute: async ({ agent_type, task_name, message }, { context }) =>\n context.controlPlane.spawn(context.actor, {\n agentType: agent_type,\n taskName: task_name,\n message,\n }),\n});\n", "import {\n type DynamicToolUIPart,\n type ToolUIPart,\n type UIMessage,\n isToolUIPart,\n} from 'ai';\n\nimport {\n ContextEngine,\n type ContextStore,\n type StreamManager,\n assistant,\n} from '@deepagents/context';\n\nimport type { ApprovalMutex } from './approval-mutex.ts';\nimport type { ConversationId } from './mailbox/types.ts';\nimport type { TurnQueue } from './queue/turn-queue.ts';\n\nexport interface ApprovalControllerOptions {\n store: ContextStore;\n streams: StreamManager;\n queue: TurnQueue;\n mutex: ApprovalMutex;\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 #streams: StreamManager;\n readonly #queue: TurnQueue;\n readonly #mutex: ApprovalMutex;\n\n constructor(options: ApprovalControllerOptions) {\n this.#store = options.store;\n this.#streams = options.streams;\n this.#queue = options.queue;\n this.#mutex = options.mutex;\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 await this.#mutex.runExclusive(conversation.chatId, async () => {\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 denied = head.parts.filter(\n (part) =>\n isToolUIPart(part) &&\n part.state === 'approval-responded' &&\n part.approval.approved === false,\n );\n if (denied.length === 0) return;\n\n const updated = {\n ...head,\n parts: head.parts.map((part) =>\n denied.includes(part as ApprovalToolPart)\n ? { ...part, state: 'output-denied' }\n : part,\n ),\n } as UIMessage;\n await engine.continue(assistant(updated));\n });\n }\n\n async settleFailedApprovals(\n conversation: ConversationId,\n streamId: string,\n error: string,\n ): Promise<void> {\n await this.#mutex.runExclusive(conversation.chatId, async () => {\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 responded = head.parts.filter(\n (part) => isToolUIPart(part) && part.state === 'approval-responded',\n );\n if (responded.length === 0) return;\n\n const updated = {\n ...head,\n parts: head.parts.map((part) =>\n isToolUIPart(part) && part.state === 'approval-responded'\n ? part.approval.approved === false\n ? { ...part, state: 'output-denied' }\n : { ...part, state: 'output-error', errorText: error }\n : part,\n ),\n } as UIMessage;\n await engine.continue(assistant(updated));\n });\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 ??\n (status === 'cancelled'\n ? 'approval continuation cancelled'\n : 'approval continuation failed'),\n );\n }\n await this.#queue.resumeParked(conversation.chatId);\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 result = await this.#mutex.runExclusive(\n conversation.chatId,\n async () => {\n const engine = this.#engineFor(conversation);\n const head = (await engine.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 (\n part.approval?.approved !== undefined &&\n part.approval.approved !== approval.approved\n ) {\n throw new Error(\n `ApprovalController.${operation}: approval already answered with a different decision`,\n );\n }\n\n let updated = head;\n let answered = part;\n if (part.state === 'approval-requested') {\n const responded = {\n ...part,\n state: 'approval-responded',\n approval: { ...part.approval, ...approval },\n } as ApprovalToolPart;\n updated = {\n ...head,\n parts: head.parts.map((candidate) =>\n candidate === part ? responded : candidate,\n ),\n } as UIMessage;\n await engine.continue(assistant(updated));\n answered = responded;\n }\n\n return {\n id: updated.id,\n hasUnansweredApprovals: this.#hasUnansweredApprovals(updated),\n shouldSchedule: answered.state === 'approval-responded',\n };\n },\n );\n\n if (!result.hasUnansweredApprovals) {\n if (result.shouldSchedule) {\n await this.#scheduleContinuation(conversation, result.id);\n } else {\n // A retry after the continuation settled is also the reconciliation\n // path for a crash between queueing that continuation and reviving the\n // older turns it had parked.\n await this.#queue.resumeParked(conversation.chatId);\n }\n }\n return { id: result.id, stream: this.#streams.watch(result.id) };\n }\n\n async #scheduleContinuation(\n conversation: ConversationId,\n streamId: string,\n ): Promise<void> {\n let status = await this.#streams.store.getStreamStatus(streamId);\n if (status === 'completed') {\n try {\n await this.#streams.reopen(streamId);\n status = 'queued';\n } catch (error) {\n status = await this.#streams.store.getStreamStatus(streamId);\n if (status !== 'queued' && status !== 'running') throw error;\n }\n } else if (status !== 'queued' && status !== 'running') {\n return;\n }\n\n if (status !== 'running') {\n await this.#queue.push({\n kind: 'continuation',\n streamId,\n chatId: conversation.chatId,\n userId: conversation.userId,\n });\n }\n await this.#queue.resumeParked(conversation.chatId);\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 type { StreamManager } from '@deepagents/context';\n\nimport { AgentTurnId } from '../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\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 #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", "/** Serializes approval state transitions for one durable conversation. */\nexport abstract class ApprovalMutex {\n abstract runExclusive<T>(\n conversationId: string,\n operation: () => Promise<T>,\n ): Promise<T>;\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 {\n type ConsumeContext,\n type ConsumeOptions,\n type TurnActivity,\n TurnQueue,\n type TurnRef,\n} from './turn-queue.ts';\n\nexport interface PgBossTurnQueueOptions {\n queue?: 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\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, strict\n * push order, cross-chat concurrency.\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 *\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 #expireInSeconds: number;\n #heartbeatSeconds: number;\n #pollingIntervalSeconds: number;\n\n constructor(boss: PgBoss, options: PgBossTurnQueueOptions = {}) {\n super();\n this.#boss = boss;\n this.#queue = options.queue ?? 'zukhruf-turns';\n this.#expireInSeconds = options.expireInSeconds ?? 3600;\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 (!(await this.#boss.getQueue(this.deadLetterQueue))) {\n await this.#boss.createQueue(this.deadLetterQueue);\n }\n if (!(await this.#boss.getQueue(this.#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 }\n }\n\n async push(turn: TurnRef): Promise<void> {\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 // Every push creates a job \u2014 delivery is at-least-once; turn-level dedup\n // lives in the consumer (the runtime skips terminal streams).\n // Continuations outrank waiting turns: revived parked jobs keep their\n // original (older) created_on, so priority is what puts the continuation\n // first.\n await this.#boss.send(this.#queue, turn, {\n id: uuidv7(),\n singletonKey: turn.chatId,\n priority: turn.kind === 'continuation' ? 1 : 0,\n });\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 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 pollingIntervalSeconds: this.#pollingIntervalSeconds,\n },\n async ([job]) => {\n let parked = false;\n await handler(job.data, {\n signal: job.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 // 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 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", "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 * Re-execution of an existing (reopened) stream after a tool approval\n * or denial. Carries no payload: the chain was already updated in\n * place by `approve()`/`deny()`.\n */\n kind: 'continuation';\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 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 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 * - 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 * - 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 a `'continuation'` turn pushed for the chat outranks 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<void>;\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 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 {\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 { resolve } from 'node:path';\nimport { DatabaseSync } from 'node:sqlite';\n\nimport { ApprovalMutex } from './approval-mutex.ts';\n\n/**\n * Cross-process approval mutex backed by a dedicated SQLite database.\n *\n * SQLite write locks are database-wide, so one file serializes all approval\n * transitions that use it. Do not use the ContextStore database file: the\n * protected operation must be able to persist the assistant message while this\n * transaction is open.\n */\nexport class SqliteApprovalMutex extends ApprovalMutex implements Disposable {\n static readonly #tails = new Map<string, Promise<void>>();\n\n readonly #db: DatabaseSync;\n readonly #coordinationKey: string;\n\n constructor(path: string) {\n super();\n this.#coordinationKey =\n path === ':memory:' ? crypto.randomUUID() : resolve(path);\n this.#db = new DatabaseSync(path);\n this.#db.exec(`\n PRAGMA busy_timeout = 5000;\n CREATE TABLE IF NOT EXISTS approval_mutex (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n conversationId TEXT NOT NULL,\n touchedAt INTEGER NOT NULL\n );\n `);\n }\n\n async runExclusive<T>(\n conversationId: string,\n operation: () => Promise<T>,\n ): Promise<T> {\n const release = await this.#acquireLocalGate();\n try {\n this.#db.exec('BEGIN IMMEDIATE');\n try {\n this.#db\n .prepare(\n `INSERT INTO approval_mutex (id, conversationId, touchedAt)\n VALUES (1, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n conversationId = excluded.conversationId,\n touchedAt = excluded.touchedAt`,\n )\n .run(conversationId, Date.now());\n const result = await operation();\n this.#db.exec('COMMIT');\n return result;\n } catch (error) {\n try {\n this.#db.exec('ROLLBACK');\n } catch {\n // Preserve the operation error if SQLite already ended the transaction.\n }\n throw error;\n }\n } finally {\n release();\n }\n }\n\n close(): void {\n this.#db.close();\n }\n\n [Symbol.dispose](): void {\n this.close();\n }\n\n async #acquireLocalGate(): Promise<() => void> {\n const previous =\n SqliteApprovalMutex.#tails.get(this.#coordinationKey) ??\n Promise.resolve();\n const gate = Promise.withResolvers<void>();\n const tail = previous.then(() => gate.promise);\n SqliteApprovalMutex.#tails.set(this.#coordinationKey, tail);\n await previous;\n return () => {\n gate.resolve();\n if (SqliteApprovalMutex.#tails.get(this.#coordinationKey) === tail) {\n SqliteApprovalMutex.#tails.delete(this.#coordinationKey);\n }\n };\n }\n}\n", "/**\n * Declaration-layer tool definition: a pure passthrough of the AI SDK's\n * `tool()` (full generics, zero side effects). Set `needsApproval: true` to\n * pause the turn on this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AC/B,UAAI;AACF,aAAK,IACF;AAAA,UACC;AAAA;AAAA;AAAA;AAAA;AAAA,QAKF,EACC,IAAI,gBAAgB,KAAK,IAAI,CAAC;AACjC,cAAM,SAAS,MAAM,UAAU;AAC/B,aAAK,IAAI,KAAK,QAAQ;AACtB,eAAO;AAAA,MACT,SAAS,OAAO;AACd,YAAI;AACF,eAAK,IAAI,KAAK,UAAU;AAAA,QAC1B,QAAQ;AAAA,QAER;AACA,cAAM;AAAA,MACR;AAAA,IACF,UAAE;AACA,cAAQ;AAAA,IACV;AAAA,EACF;AAAA,EAEA,QAAc;AACZ,SAAK,IAAI,MAAM;AAAA,EACjB;AAAA,EAEA,CAAC,OAAO,OAAO,IAAU;AACvB,SAAK,MAAM;AAAA,EACb;AAAA,EAEA,MAAM,oBAAyC;AAC7C,UAAM,WACJ,qBAAoB,OAAO,IAAI,KAAK,gBAAgB,KACpD,QAAQ,QAAQ;AAClB,UAAM,OAAO,QAAQ,cAAoB;AACzC,UAAM,OAAO,SAAS,KAAK,MAAM,KAAK,OAAO;AAC7C,yBAAoB,OAAO,IAAI,KAAK,kBAAkB,IAAI;AAC1D,UAAM;AACN,WAAO,MAAM;AACX,WAAK,QAAQ;AACb,UAAI,qBAAoB,OAAO,IAAI,KAAK,gBAAgB,MAAM,MAAM;AAClE,6BAAoB,OAAO,OAAO,KAAK,gBAAgB;AAAA,MACzD;AAAA,IACF;AAAA,EACF;AACF;;;ACrFA,SAAiB,QAARC,aAA0B;",
|
|
6
|
+
"names": ["tool", "ContextEngine", "uuidv5", "chat", "uuidv5", "uuidv5", "ContextEngine", "tool", "z", "tool", "z", "ContextEngine", "ContextEngine", "assistant", "ContextEngine", "chat", "DatabaseSync", "DatabaseSync", "tool"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { StreamManager } from '@deepagents/context';
|
|
2
|
+
import { AgentDeclarationRegistry } from './agent-declaration-registry.ts';
|
|
3
|
+
import { AgentDirectory } from './agent-directory.ts';
|
|
4
|
+
import { type AgentStatusProjector, type ListedAgent } from './agent-status-projector.ts';
|
|
5
|
+
import type { AgentThread } from './agent-thread.ts';
|
|
6
|
+
import type { AgentDeclaration } from './agent.ts';
|
|
7
|
+
import type { MailboxCoordinator } from './mailbox/coordinator.ts';
|
|
8
|
+
import type { ConversationId } from './mailbox/types.ts';
|
|
9
|
+
import type { TurnQueue, TurnRef } from './queue/turn-queue.ts';
|
|
10
|
+
export interface AgentControlPlaneOptions {
|
|
11
|
+
root: AgentDeclaration;
|
|
12
|
+
streams: StreamManager;
|
|
13
|
+
queue: TurnQueue;
|
|
14
|
+
mailbox: MailboxCoordinator;
|
|
15
|
+
declarations: AgentDeclarationRegistry;
|
|
16
|
+
directory: AgentDirectory;
|
|
17
|
+
statusProjector: AgentStatusProjector;
|
|
18
|
+
}
|
|
19
|
+
export interface AgentActor {
|
|
20
|
+
turn: TurnRef;
|
|
21
|
+
thread: AgentThread;
|
|
22
|
+
declaration: AgentDeclaration;
|
|
23
|
+
}
|
|
24
|
+
export interface TurnInput {
|
|
25
|
+
/** Caller-supplied idempotency key; enqueue returns its scoped durable id. */
|
|
26
|
+
id: string;
|
|
27
|
+
input: string;
|
|
28
|
+
}
|
|
29
|
+
export interface SpawnAgentInput {
|
|
30
|
+
agentType: string;
|
|
31
|
+
taskName: string;
|
|
32
|
+
message: string;
|
|
33
|
+
}
|
|
34
|
+
export interface SpawnAgentOutput {
|
|
35
|
+
task_name: string;
|
|
36
|
+
agent_path: string;
|
|
37
|
+
}
|
|
38
|
+
export type { ListedAgent, ListedAgentStatus, } from './agent-status-projector.ts';
|
|
39
|
+
/** Application-level coordination for one declared agent tree. */
|
|
40
|
+
export declare class AgentControlPlane {
|
|
41
|
+
#private;
|
|
42
|
+
constructor(options: AgentControlPlaneOptions);
|
|
43
|
+
resolve(conversation: ConversationId): Promise<{
|
|
44
|
+
declaration: AgentDeclaration;
|
|
45
|
+
thread: AgentThread;
|
|
46
|
+
}>;
|
|
47
|
+
enqueue(conversation: ConversationId, turn: TurnInput): Promise<string>;
|
|
48
|
+
recordLatestTurn(conversation: ConversationId, streamId: string): Promise<AgentThread>;
|
|
49
|
+
recordLatestTurnIfCurrent(conversation: ConversationId, streamId: string, expectedLastTurnId: string | undefined): Promise<AgentThread | undefined>;
|
|
50
|
+
spawn(actor: AgentActor, input: SpawnAgentInput): Promise<SpawnAgentOutput>;
|
|
51
|
+
sendMessage(actor: AgentActor, input: {
|
|
52
|
+
target: string;
|
|
53
|
+
message: string;
|
|
54
|
+
}): Promise<{
|
|
55
|
+
target: string;
|
|
56
|
+
}>;
|
|
57
|
+
followupTask(actor: AgentActor, input: {
|
|
58
|
+
target: string;
|
|
59
|
+
message: string;
|
|
60
|
+
}): Promise<{
|
|
61
|
+
target: string;
|
|
62
|
+
}>;
|
|
63
|
+
listAgents(actor: AgentActor, pathPrefix?: string): Promise<{
|
|
64
|
+
agents: ListedAgent[];
|
|
65
|
+
}>;
|
|
66
|
+
projectTerminal(turn: TurnRef, thread: AgentThread): Promise<void>;
|
|
67
|
+
}
|
|
68
|
+
//# sourceMappingURL=agent-control-plane.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent-control-plane.d.ts","sourceRoot":"","sources":["../../src/zukhruf/agent-control-plane.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEzD,OAAO,EAAE,wBAAwB,EAAE,MAAM,iCAAiC,CAAC;AAC3E,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EACL,KAAK,oBAAoB,EACzB,KAAK,WAAW,EACjB,MAAM,6BAA6B,CAAC;AACrC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAErD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAA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AAM,GACf,OAAO,CAAC,WAAW,CAAC;IAIvB,yBAAyB,CACvB,YAAY,EAAE,cAAc,EAC5B,QAAQ,EAAE,MAAM,EAChB,kBAAkB,EAAE,MAAM,GAAG,SAAS,GACrC,OAAO,CAAC,WAAW,GAAG,SAAS,CAAC;IAQ7B,KAAK,CACT,KAAK,EAAE,UAAU,EACjB,KAAK,EAAE,eAAe,GACrB,OAAO,CAAC,gBAAgB,CAAC;IAiDtB,WAAW,CACf,KAAK,EAAE,UAAU,EACjB,KAAK,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,GACzC,OAAO,CAAC;QAAE,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;IAQxB,YAAY,CAChB,KAAK,EAAE,UAAU,EACjB,KAAK,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,GACzC,OAAO,CAAC;QAAE,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;IAQxB,UAAU,CACd,KAAK,EAAE,UAAU,EACjB,UAAU,CAAC,EAAE,MAAM,GAClB,OAAO,CAAC;QAAE,MAAM,EAAE,WAAW,EAAE,CAAA;KAAE,CAAC;IAiB/B,eAAe,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;CAsCzE"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { AgentDeclaration } from './agent.ts';
|
|
2
|
+
/** Immutable declaration lookup compiled once for one agent runtime. */
|
|
3
|
+
export declare class AgentDeclarationRegistry {
|
|
4
|
+
#private;
|
|
5
|
+
readonly root: AgentDeclaration;
|
|
6
|
+
constructor(root: AgentDeclaration);
|
|
7
|
+
get(name: string): AgentDeclaration | undefined;
|
|
8
|
+
}
|
|
9
|
+
//# sourceMappingURL=agent-declaration-registry.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent-declaration-registry.d.ts","sourceRoot":"","sources":["../../src/zukhruf/agent-declaration-registry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnD,wEAAwE;AACxE,qBAAa,wBAAwB;;IACnC,QAAQ,CAAC,IAAI,EAAE,gBAAgB,CAAC;gBAIpB,IAAI,EAAE,gBAAgB;IAKlC,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,gBAAgB,GAAG,SAAS;CAgChD"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { ContextStore } from '@deepagents/context';
|
|
2
|
+
import { AgentThread } from './agent-thread.ts';
|
|
3
|
+
import type { ConversationId } from './mailbox/types.ts';
|
|
4
|
+
/** ContextStore-backed directory of durable agent instances. */
|
|
5
|
+
export declare class AgentDirectory {
|
|
6
|
+
#private;
|
|
7
|
+
constructor(store: ContextStore);
|
|
8
|
+
assertOwnerIfExists(conversation: ConversationId): Promise<void>;
|
|
9
|
+
load(conversation: ConversationId): Promise<AgentThread | undefined>;
|
|
10
|
+
loadOrCreateRoot(conversation: ConversationId, declarationName: string): Promise<AgentThread>;
|
|
11
|
+
recordLatestTurn(conversation: ConversationId, streamId: string): Promise<AgentThread>;
|
|
12
|
+
recordLatestTurnIfCurrent(conversation: ConversationId, streamId: string, expectedLastTurnId: string | undefined): Promise<AgentThread | undefined>;
|
|
13
|
+
listTree(thread: AgentThread): Promise<AgentThread[]>;
|
|
14
|
+
resolve(thread: AgentThread, target: string): Promise<AgentThread>;
|
|
15
|
+
createChild(options: {
|
|
16
|
+
parent: AgentThread;
|
|
17
|
+
taskName: string;
|
|
18
|
+
declarationName: string;
|
|
19
|
+
}): Promise<AgentThread>;
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=agent-directory.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent-directory.d.ts","sourceRoot":"","sources":["../../src/zukhruf/agent-directory.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEzD,gEAAgE;AAChE,qBAAa,cAAc;;gBAGb,KAAK,EAAE,YAAY;IAIzB,mBAAmB,CAAC,YAAY,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAQhE,IAAI,CAAC,YAAY,EAAE,cAAc,GAAG,OAAO,CAAC,WAAW,GAAG,SAAS,CAAC;IASpE,gBAAgB,CACpB,YAAY,EAAE,cAAc,EAC5B,eAAe,EAAE,MAAM,GACtB,OAAO,CAAC,WAAW,CAAC;IAyBjB,gBAAgB,CACpB,YAAY,EAAE,cAAc,EAC5B,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,WAAW,CAAC;IAIjB,yBAAyB,CAC7B,YAAY,EAAE,cAAc,EAC5B,QAAQ,EAAE,MAAM,EAChB,kBAAkB,EAAE,MAAM,GAAG,SAAS,GACrC,OAAO,CAAC,WAAW,GAAG,SAAS,CAAC;IAI7B,QAAQ,CAAC,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC;IAoBrD,OAAO,CAAC,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC;IASlE,WAAW,CAAC,OAAO,EAAE;QACzB,MAAM,EAAE,WAAW,CAAC;QACpB,QAAQ,EAAE,MAAM,CAAC;QACjB,eAAe,EAAE,MAAM,CAAC;KACzB,GAAG,OAAO,CAAC,WAAW,CAAC;CA6IzB"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Canonical model-facing address for one agent in a Zukhruf tree. */
|
|
2
|
+
export declare class AgentPath {
|
|
3
|
+
#private;
|
|
4
|
+
private constructor();
|
|
5
|
+
static root(): AgentPath;
|
|
6
|
+
static parse(value: string): AgentPath;
|
|
7
|
+
/** Relative targets name descendants; absolute targets keep their canonical path. */
|
|
8
|
+
resolve(target: string): AgentPath;
|
|
9
|
+
contains(candidate: AgentPath): boolean;
|
|
10
|
+
equals(other: AgentPath): boolean;
|
|
11
|
+
get isRoot(): boolean;
|
|
12
|
+
get parent(): AgentPath | null;
|
|
13
|
+
toString(): string;
|
|
14
|
+
}
|
|
15
|
+
//# sourceMappingURL=agent-path.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent-path.d.ts","sourceRoot":"","sources":["../../src/zukhruf/agent-path.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,qBAAa,SAAS;;IAGpB,OAAO;IAIP,MAAM,CAAC,IAAI,IAAI,SAAS;IAIxB,MAAM,CAAC,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS;IAqBtC,qFAAqF;IACrF,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS;IAQlC,QAAQ,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO;IAMvC,MAAM,CAAC,KAAK,EAAE,SAAS,GAAG,OAAO;IAIjC,IAAI,MAAM,IAAI,OAAO,CAEpB;IAED,IAAI,MAAM,IAAI,SAAS,GAAG,IAAI,CAG7B;IAED,QAAQ,IAAI,MAAM;CAGnB"}
|