@deepagents/experimental 4.2.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 ADDED
@@ -0,0 +1,33 @@
1
+ # @deepagents/experimental
2
+
3
+ A home for unstable, in-progress building blocks that are not yet part of the
4
+ stable `@deepagents/*` surface. APIs here may change without notice.
5
+
6
+ ## `@deepagents/experimental/zukhruf`
7
+
8
+ `zukhruf` is an internal DSL for **declaring** an agent, plus a **runtime** that
9
+ executes that declaration as a **durable background agent** — built on
10
+ `@deepagents/context` primitives (`agent()`, `ContextEngine`, `AgentSandbox`,
11
+ fragments, the stream subsystem).
12
+
13
+ ```ts
14
+ import {
15
+ PgBossTurnQueue,
16
+ createRuntime,
17
+ defineAgent,
18
+ } from '@deepagents/experimental/zukhruf';
19
+ ```
20
+
21
+ The declaration layer (`defineAgent` / `defineInstructions` / `defineTool` /
22
+ `defineSandbox`) is pure data with a types-only dependency on
23
+ `@deepagents/context`; the runtime (`createRuntime`) is the only layer that
24
+ touches engines, sandboxes, and durability. See
25
+ [`src/zukhruf/DESIGN.md`](./src/zukhruf/DESIGN.md) for the decided semantics,
26
+ [`TODO.md`](./src/zukhruf/TODO.md) for the convergence plan, and
27
+ [`BUGS.md`](./src/zukhruf/BUGS.md) for known residue.
28
+
29
+ Runnable end-to-end showcases live in
30
+ [`demo/zukhruf-durable-turns`](../../demo/zukhruf-durable-turns) (the durable
31
+ executor: enqueue, detach, resume, strict per-chat FIFO) and
32
+ [`demo/zukhruf-research-bot`](../../demo/zukhruf-research-bot) (an agentic
33
+ research bot: plan → web-search subagent → streamed report).
@@ -0,0 +1,2 @@
1
+ export * as zukhruf from './zukhruf/index.ts';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,MAAM,oBAAoB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,336 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // packages/experimental/src/zukhruf/index.ts
8
+ var zukhruf_exports = {};
9
+ __export(zukhruf_exports, {
10
+ PgBossTurnQueue: () => PgBossTurnQueue,
11
+ TurnQueue: () => TurnQueue,
12
+ createRuntime: () => createRuntime,
13
+ defineAgent: () => defineAgent,
14
+ defineInstructions: () => defineInstructions,
15
+ defineSandbox: () => defineSandbox,
16
+ defineTool: () => tool
17
+ });
18
+
19
+ // packages/experimental/src/zukhruf/agent.ts
20
+ function defineAgent(declaration) {
21
+ return {
22
+ name: declaration.name ?? "agent",
23
+ model: declaration.model,
24
+ sandbox: declaration.sandbox,
25
+ instructions: declaration.instructions,
26
+ tools: declaration.tools
27
+ };
28
+ }
29
+
30
+ // packages/experimental/src/zukhruf/instructions.ts
31
+ function defineInstructions(...fragments) {
32
+ return fragments;
33
+ }
34
+
35
+ // packages/experimental/src/zukhruf/tool.ts
36
+ import { tool } from "ai";
37
+
38
+ // packages/experimental/src/zukhruf/sandbox/define.ts
39
+ import {
40
+ createBashTool
41
+ } from "@deepagents/context";
42
+ function defineSandbox(createBackend, options) {
43
+ return async (context) => createBashTool({ sandbox: await createBackend(context), ...options });
44
+ }
45
+
46
+ // packages/experimental/src/zukhruf/runtime.ts
47
+ import { isToolUIPart } from "ai";
48
+ import {
49
+ ContextEngine,
50
+ PollingChangeSource,
51
+ StreamManager,
52
+ agent,
53
+ assistant,
54
+ chat,
55
+ user
56
+ } from "@deepagents/context";
57
+ var SETTLED_TOOL_STATES = /* @__PURE__ */ new Set([
58
+ "output-available",
59
+ "output-error",
60
+ "output-denied"
61
+ ]);
62
+ function pendingToolPart(message) {
63
+ return message.parts.find(
64
+ (part) => isToolUIPart(part) && !SETTLED_TOOL_STATES.has(part.state)
65
+ );
66
+ }
67
+ function createRuntime(declaration, options) {
68
+ const { store, streamStore, queue } = options;
69
+ const manager = new StreamManager({
70
+ store: streamStore,
71
+ changeSource: new PollingChangeSource({ reads: streamStore })
72
+ });
73
+ function engineFor({ chatId, userId }) {
74
+ return new ContextEngine({ store, chatId, userId });
75
+ }
76
+ async function executeTurn(turn, { signal, park }) {
77
+ const status = await streamStore.getStreamStatus(turn.streamId);
78
+ if (status !== "queued" && status !== "running") return;
79
+ const engine = engineFor(turn).set(...declaration.instructions);
80
+ if (turn.kind === "ask") {
81
+ const head = (await engine.getMessages()).at(-1);
82
+ if (head?.role === "assistant" && pendingToolPart(head)) {
83
+ await park();
84
+ return;
85
+ }
86
+ engine.set(
87
+ user(turn.input),
88
+ assistant({ id: turn.streamId, role: "assistant", parts: [] })
89
+ );
90
+ await engine.save({ branch: true });
91
+ }
92
+ const sandbox = await declaration.sandbox({
93
+ chatId: turn.chatId,
94
+ userId: turn.userId
95
+ });
96
+ const ai = agent({
97
+ name: declaration.name,
98
+ model: declaration.model,
99
+ sandbox,
100
+ context: engine,
101
+ tools: declaration.tools
102
+ });
103
+ const abort = new AbortController();
104
+ const onWorkerAbort = () => abort.abort();
105
+ signal.addEventListener("abort", onWorkerAbort, { once: true });
106
+ try {
107
+ const stream = await chat(ai, { abortSignal: abort.signal });
108
+ await manager.persist(stream, turn.streamId, {
109
+ onCancelDetected: () => abort.abort()
110
+ });
111
+ } finally {
112
+ signal.removeEventListener("abort", onWorkerAbort);
113
+ }
114
+ }
115
+ async function respondToApproval(conversation, toolCallId, approval) {
116
+ const engine = engineFor(conversation);
117
+ const head = (await engine.getMessages()).at(-1);
118
+ if (head?.role !== "assistant") {
119
+ throw new Error(
120
+ "approve: no paused turn \u2014 the chain head is not an assistant message"
121
+ );
122
+ }
123
+ const part = head.parts.find(
124
+ (p) => isToolUIPart(p) && p.toolCallId === toolCallId
125
+ );
126
+ if (!part || !isToolUIPart(part)) {
127
+ throw new Error(
128
+ `approve: no tool call "${toolCallId}" on the paused turn`
129
+ );
130
+ }
131
+ if (part.state !== "approval-requested") {
132
+ return { id: head.id, stream: manager.watch(head.id) };
133
+ }
134
+ const responded = {
135
+ ...part,
136
+ state: "approval-responded",
137
+ approval: { ...part.approval, ...approval }
138
+ };
139
+ const updated = {
140
+ ...head,
141
+ parts: head.parts.map((p) => p === part ? responded : p)
142
+ };
143
+ await engine.continue(assistant(updated));
144
+ try {
145
+ await manager.reopen(head.id);
146
+ } catch {
147
+ return { id: head.id, stream: manager.watch(head.id) };
148
+ }
149
+ await queue.push({
150
+ kind: "continuation",
151
+ streamId: head.id,
152
+ chatId: conversation.chatId,
153
+ userId: conversation.userId
154
+ });
155
+ await queue.resumeParked(conversation.chatId);
156
+ return { id: head.id, stream: manager.watch(head.id) };
157
+ }
158
+ return {
159
+ async enqueue({ chatId, userId }, turn) {
160
+ if (!turn.id) {
161
+ throw new Error(
162
+ "enqueue: turn id is required \u2014 it names the ask, making retries idempotent"
163
+ );
164
+ }
165
+ await manager.register(turn.id);
166
+ await queue.push({
167
+ kind: "ask",
168
+ streamId: turn.id,
169
+ chatId,
170
+ userId,
171
+ input: turn.input
172
+ });
173
+ return { id: turn.id, stream: manager.watch(turn.id) };
174
+ },
175
+ async approve(conversation, input) {
176
+ return respondToApproval(conversation, input.toolCallId, {
177
+ approved: true
178
+ });
179
+ },
180
+ async deny(conversation, input) {
181
+ return respondToApproval(conversation, input.toolCallId, {
182
+ approved: false,
183
+ reason: input.reason
184
+ });
185
+ },
186
+ observe({ chatId, userId }) {
187
+ const engine = engineFor({ chatId, userId });
188
+ async function headStreamId() {
189
+ const head = await engine.headMessage();
190
+ return head?.name === "assistant" ? head.id : void 0;
191
+ }
192
+ return {
193
+ engine,
194
+ async resume() {
195
+ const id = await headStreamId();
196
+ if (!id) return null;
197
+ const status = await streamStore.getStreamStatus(id);
198
+ return status ? manager.watch(id) : null;
199
+ },
200
+ async cancel(streamId) {
201
+ const id = streamId ?? await headStreamId();
202
+ if (!id) return;
203
+ const status = await streamStore.getStreamStatus(id);
204
+ if (status === "queued" || status === "running") {
205
+ await manager.cancel(id);
206
+ }
207
+ }
208
+ };
209
+ },
210
+ async work(options2) {
211
+ return queue.consume(executeTurn, {
212
+ concurrency: options2?.concurrency,
213
+ onOrphaned: async (turn, error) => {
214
+ const status = await streamStore.getStreamStatus(turn.streamId);
215
+ if (status === "queued" || status === "running") {
216
+ await streamStore.updateStreamStatus(turn.streamId, "failed", {
217
+ error
218
+ });
219
+ }
220
+ }
221
+ });
222
+ }
223
+ };
224
+ }
225
+
226
+ // packages/experimental/src/zukhruf/queue/turn-queue.ts
227
+ var TurnQueue = class {
228
+ };
229
+
230
+ // packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
231
+ import { v7 as uuidv7 } from "uuid";
232
+ var PgBossTurnQueue = class extends TurnQueue {
233
+ #boss;
234
+ #queue;
235
+ #expireInSeconds;
236
+ #heartbeatSeconds;
237
+ #pollingIntervalSeconds;
238
+ constructor(boss, options = {}) {
239
+ super();
240
+ this.#boss = boss;
241
+ this.#queue = options.queue ?? "zukhruf-turns";
242
+ this.#expireInSeconds = options.expireInSeconds ?? 3600;
243
+ this.#heartbeatSeconds = options.heartbeatSeconds ?? 30;
244
+ this.#pollingIntervalSeconds = options.pollingIntervalSeconds ?? 1;
245
+ }
246
+ get queue() {
247
+ return this.#queue;
248
+ }
249
+ get deadLetterQueue() {
250
+ return `${this.#queue}-dead`;
251
+ }
252
+ async initialize() {
253
+ if (!await this.#boss.getQueue(this.deadLetterQueue)) {
254
+ await this.#boss.createQueue(this.deadLetterQueue);
255
+ }
256
+ if (!await this.#boss.getQueue(this.#queue)) {
257
+ await this.#boss.createQueue(this.#queue, {
258
+ policy: "key_strict_fifo",
259
+ retryLimit: 0,
260
+ expireInSeconds: this.#expireInSeconds,
261
+ heartbeatSeconds: this.#heartbeatSeconds,
262
+ deleteAfterSeconds: 0,
263
+ deadLetter: this.deadLetterQueue
264
+ });
265
+ }
266
+ }
267
+ async push(turn) {
268
+ await this.#boss.send(this.#queue, turn, {
269
+ id: uuidv7(),
270
+ singletonKey: turn.chatId,
271
+ priority: turn.kind === "continuation" ? 1 : 0
272
+ });
273
+ }
274
+ async consume(handler, options) {
275
+ const turnWorkerId = await this.#boss.work(
276
+ this.#queue,
277
+ {
278
+ localConcurrency: options.concurrency ?? 1,
279
+ pollingIntervalSeconds: this.#pollingIntervalSeconds
280
+ },
281
+ async ([job]) => {
282
+ let parked = false;
283
+ await handler(job.data, {
284
+ signal: job.signal,
285
+ // Parking = self-cancel: a cancelled job stops blocking the chat's
286
+ // key and is revived (original created_on, so original order) by
287
+ // resumeParked(). The worker's completion of a cancelled job is a
288
+ // clean no-op (probe-verified).
289
+ park: async () => {
290
+ parked = true;
291
+ await this.#boss.cancel(this.#queue, job.id);
292
+ }
293
+ });
294
+ if (!parked) {
295
+ await this.#boss.deleteJob(this.#queue, job.id);
296
+ }
297
+ }
298
+ );
299
+ const deadWorkerId = await this.#boss.work(
300
+ this.deadLetterQueue,
301
+ {
302
+ includeMetadata: true,
303
+ pollingIntervalSeconds: this.#pollingIntervalSeconds
304
+ },
305
+ async ([job]) => {
306
+ await options.onOrphaned(job.data, orphanError(job.output));
307
+ if (job.sourceId) {
308
+ await this.#boss.deleteJob(this.#queue, job.sourceId);
309
+ }
310
+ }
311
+ );
312
+ return {
313
+ [Symbol.asyncDispose]: async () => {
314
+ await this.#boss.offWork(this.#queue, { id: turnWorkerId });
315
+ await this.#boss.offWork(this.deadLetterQueue, { id: deadWorkerId });
316
+ }
317
+ };
318
+ }
319
+ async resumeParked(chatId) {
320
+ const jobs = await this.#boss.findJobs(this.#queue, { key: chatId });
321
+ const parked = jobs.filter((job) => job.state === "cancelled").map((job) => job.id);
322
+ if (parked.length > 0) {
323
+ await this.#boss.resume(this.#queue, parked);
324
+ }
325
+ }
326
+ };
327
+ function orphanError(output) {
328
+ if (output && "message" in output && typeof output.message === "string") {
329
+ return output.message;
330
+ }
331
+ return output ? JSON.stringify(output) : "turn orphaned";
332
+ }
333
+ export {
334
+ zukhruf_exports as zukhruf
335
+ };
336
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/zukhruf/index.ts", "../src/zukhruf/agent.ts", "../src/zukhruf/instructions.ts", "../src/zukhruf/tool.ts", "../src/zukhruf/sandbox/define.ts", "../src/zukhruf/runtime.ts", "../src/zukhruf/queue/turn-queue.ts", "../src/zukhruf/queue/pg-boss.turn-queue.ts"],
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,CAA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AO,OAAO;AAAA,EAChB;AACA,SAAO,SAAS,KAAK,UAAU,MAAM,IAAI;AAC3C;",
6
+ "names": ["options"]
7
+ }
@@ -0,0 +1,26 @@
1
+ import type { ToolSet } from 'ai';
2
+ import type { AgentModel, AgentSandbox, ContextFragment } from '@deepagents/context';
3
+ /**
4
+ * Sandboxes are per-chat: the factory receives the conversation identity so
5
+ * the backend can be named by `chatId` and re-attached across turns, workers,
6
+ * and restarts (the container engine is the registry — no in-memory state).
7
+ */
8
+ export interface SandboxContext {
9
+ chatId: string;
10
+ userId: string;
11
+ }
12
+ export interface AgentDeclaration {
13
+ name: string;
14
+ model: AgentModel;
15
+ sandbox: (context: SandboxContext) => Promise<AgentSandbox>;
16
+ instructions: ContextFragment[];
17
+ tools?: ToolSet;
18
+ }
19
+ export declare function defineAgent(declaration: {
20
+ model: AgentModel;
21
+ sandbox: (context: SandboxContext) => Promise<AgentSandbox>;
22
+ instructions: ContextFragment[];
23
+ tools?: ToolSet;
24
+ name?: string;
25
+ }): AgentDeclaration;
26
+ //# sourceMappingURL=agent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/zukhruf/agent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAElC,OAAO,KAAK,EACV,UAAU,EACV,YAAY,EACZ,eAAe,EAChB,MAAM,qBAAqB,CAAC;AAE7B;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,UAAU,CAAC;IAClB,OAAO,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,OAAO,CAAC,YAAY,CAAC,CAAC;IAC5D,YAAY,EAAE,eAAe,EAAE,CAAC;IAChC,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED,wBAAgB,WAAW,CAAC,WAAW,EAAE;IACvC,KAAK,EAAE,UAAU,CAAC;IAClB,OAAO,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,OAAO,CAAC,YAAY,CAAC,CAAC;IAC5D,YAAY,EAAE,eAAe,EAAE,CAAC;IAChC,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,GAAG,gBAAgB,CAQnB"}
@@ -0,0 +1,12 @@
1
+ export { defineAgent } from './agent.ts';
2
+ export type { AgentDeclaration, SandboxContext } from './agent.ts';
3
+ export { defineInstructions } from './instructions.ts';
4
+ export { defineTool } from './tool.ts';
5
+ export { defineSandbox } from './sandbox/define.ts';
6
+ export { createRuntime } from './runtime.ts';
7
+ export type { ConversationId, RuntimeOptions, TurnInput, WorkOptions, } from './runtime.ts';
8
+ export { TurnQueue } from './queue/turn-queue.ts';
9
+ export type { ConsumeContext, ConsumeOptions, TurnRef, } from './queue/turn-queue.ts';
10
+ export { PgBossTurnQueue } from './queue/pg-boss.turn-queue.ts';
11
+ export type { PgBossTurnQueueOptions } from './queue/pg-boss.turn-queue.ts';
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/zukhruf/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,YAAY,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACvC,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,YAAY,EACV,cAAc,EACd,cAAc,EACd,SAAS,EACT,WAAW,GACZ,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,YAAY,EACV,cAAc,EACd,cAAc,EACd,OAAO,GACR,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,YAAY,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC"}
@@ -0,0 +1,324 @@
1
+ // packages/experimental/src/zukhruf/agent.ts
2
+ function defineAgent(declaration) {
3
+ return {
4
+ name: declaration.name ?? "agent",
5
+ model: declaration.model,
6
+ sandbox: declaration.sandbox,
7
+ instructions: declaration.instructions,
8
+ tools: declaration.tools
9
+ };
10
+ }
11
+
12
+ // packages/experimental/src/zukhruf/instructions.ts
13
+ function defineInstructions(...fragments) {
14
+ return fragments;
15
+ }
16
+
17
+ // packages/experimental/src/zukhruf/tool.ts
18
+ import { tool } from "ai";
19
+
20
+ // packages/experimental/src/zukhruf/sandbox/define.ts
21
+ import {
22
+ createBashTool
23
+ } from "@deepagents/context";
24
+ function defineSandbox(createBackend, options) {
25
+ return async (context) => createBashTool({ sandbox: await createBackend(context), ...options });
26
+ }
27
+
28
+ // packages/experimental/src/zukhruf/runtime.ts
29
+ import { isToolUIPart } from "ai";
30
+ import {
31
+ ContextEngine,
32
+ PollingChangeSource,
33
+ StreamManager,
34
+ agent,
35
+ assistant,
36
+ chat,
37
+ user
38
+ } from "@deepagents/context";
39
+ var SETTLED_TOOL_STATES = /* @__PURE__ */ new Set([
40
+ "output-available",
41
+ "output-error",
42
+ "output-denied"
43
+ ]);
44
+ function pendingToolPart(message) {
45
+ return message.parts.find(
46
+ (part) => isToolUIPart(part) && !SETTLED_TOOL_STATES.has(part.state)
47
+ );
48
+ }
49
+ function createRuntime(declaration, options) {
50
+ const { store, streamStore, queue } = options;
51
+ const manager = new StreamManager({
52
+ store: streamStore,
53
+ changeSource: new PollingChangeSource({ reads: streamStore })
54
+ });
55
+ function engineFor({ chatId, userId }) {
56
+ return new ContextEngine({ store, chatId, userId });
57
+ }
58
+ async function executeTurn(turn, { signal, park }) {
59
+ const status = await streamStore.getStreamStatus(turn.streamId);
60
+ if (status !== "queued" && status !== "running") return;
61
+ const engine = engineFor(turn).set(...declaration.instructions);
62
+ if (turn.kind === "ask") {
63
+ const head = (await engine.getMessages()).at(-1);
64
+ if (head?.role === "assistant" && pendingToolPart(head)) {
65
+ await park();
66
+ return;
67
+ }
68
+ engine.set(
69
+ user(turn.input),
70
+ assistant({ id: turn.streamId, role: "assistant", parts: [] })
71
+ );
72
+ await engine.save({ branch: true });
73
+ }
74
+ const sandbox = await declaration.sandbox({
75
+ chatId: turn.chatId,
76
+ userId: turn.userId
77
+ });
78
+ const ai = agent({
79
+ name: declaration.name,
80
+ model: declaration.model,
81
+ sandbox,
82
+ context: engine,
83
+ tools: declaration.tools
84
+ });
85
+ const abort = new AbortController();
86
+ const onWorkerAbort = () => abort.abort();
87
+ signal.addEventListener("abort", onWorkerAbort, { once: true });
88
+ try {
89
+ const stream = await chat(ai, { abortSignal: abort.signal });
90
+ await manager.persist(stream, turn.streamId, {
91
+ onCancelDetected: () => abort.abort()
92
+ });
93
+ } finally {
94
+ signal.removeEventListener("abort", onWorkerAbort);
95
+ }
96
+ }
97
+ async function respondToApproval(conversation, toolCallId, approval) {
98
+ const engine = engineFor(conversation);
99
+ const head = (await engine.getMessages()).at(-1);
100
+ if (head?.role !== "assistant") {
101
+ throw new Error(
102
+ "approve: no paused turn \u2014 the chain head is not an assistant message"
103
+ );
104
+ }
105
+ const part = head.parts.find(
106
+ (p) => isToolUIPart(p) && p.toolCallId === toolCallId
107
+ );
108
+ if (!part || !isToolUIPart(part)) {
109
+ throw new Error(
110
+ `approve: no tool call "${toolCallId}" on the paused turn`
111
+ );
112
+ }
113
+ if (part.state !== "approval-requested") {
114
+ return { id: head.id, stream: manager.watch(head.id) };
115
+ }
116
+ const responded = {
117
+ ...part,
118
+ state: "approval-responded",
119
+ approval: { ...part.approval, ...approval }
120
+ };
121
+ const updated = {
122
+ ...head,
123
+ parts: head.parts.map((p) => p === part ? responded : p)
124
+ };
125
+ await engine.continue(assistant(updated));
126
+ try {
127
+ await manager.reopen(head.id);
128
+ } catch {
129
+ return { id: head.id, stream: manager.watch(head.id) };
130
+ }
131
+ await queue.push({
132
+ kind: "continuation",
133
+ streamId: head.id,
134
+ chatId: conversation.chatId,
135
+ userId: conversation.userId
136
+ });
137
+ await queue.resumeParked(conversation.chatId);
138
+ return { id: head.id, stream: manager.watch(head.id) };
139
+ }
140
+ return {
141
+ async enqueue({ chatId, userId }, turn) {
142
+ if (!turn.id) {
143
+ throw new Error(
144
+ "enqueue: turn id is required \u2014 it names the ask, making retries idempotent"
145
+ );
146
+ }
147
+ await manager.register(turn.id);
148
+ await queue.push({
149
+ kind: "ask",
150
+ streamId: turn.id,
151
+ chatId,
152
+ userId,
153
+ input: turn.input
154
+ });
155
+ return { id: turn.id, stream: manager.watch(turn.id) };
156
+ },
157
+ async approve(conversation, input) {
158
+ return respondToApproval(conversation, input.toolCallId, {
159
+ approved: true
160
+ });
161
+ },
162
+ async deny(conversation, input) {
163
+ return respondToApproval(conversation, input.toolCallId, {
164
+ approved: false,
165
+ reason: input.reason
166
+ });
167
+ },
168
+ observe({ chatId, userId }) {
169
+ const engine = engineFor({ chatId, userId });
170
+ async function headStreamId() {
171
+ const head = await engine.headMessage();
172
+ return head?.name === "assistant" ? head.id : void 0;
173
+ }
174
+ return {
175
+ engine,
176
+ async resume() {
177
+ const id = await headStreamId();
178
+ if (!id) return null;
179
+ const status = await streamStore.getStreamStatus(id);
180
+ return status ? manager.watch(id) : null;
181
+ },
182
+ async cancel(streamId) {
183
+ const id = streamId ?? await headStreamId();
184
+ if (!id) return;
185
+ const status = await streamStore.getStreamStatus(id);
186
+ if (status === "queued" || status === "running") {
187
+ await manager.cancel(id);
188
+ }
189
+ }
190
+ };
191
+ },
192
+ async work(options2) {
193
+ return queue.consume(executeTurn, {
194
+ concurrency: options2?.concurrency,
195
+ onOrphaned: async (turn, error) => {
196
+ const status = await streamStore.getStreamStatus(turn.streamId);
197
+ if (status === "queued" || status === "running") {
198
+ await streamStore.updateStreamStatus(turn.streamId, "failed", {
199
+ error
200
+ });
201
+ }
202
+ }
203
+ });
204
+ }
205
+ };
206
+ }
207
+
208
+ // packages/experimental/src/zukhruf/queue/turn-queue.ts
209
+ var TurnQueue = class {
210
+ };
211
+
212
+ // packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
213
+ import { v7 as uuidv7 } from "uuid";
214
+ var PgBossTurnQueue = class extends TurnQueue {
215
+ #boss;
216
+ #queue;
217
+ #expireInSeconds;
218
+ #heartbeatSeconds;
219
+ #pollingIntervalSeconds;
220
+ constructor(boss, options = {}) {
221
+ super();
222
+ this.#boss = boss;
223
+ this.#queue = options.queue ?? "zukhruf-turns";
224
+ this.#expireInSeconds = options.expireInSeconds ?? 3600;
225
+ this.#heartbeatSeconds = options.heartbeatSeconds ?? 30;
226
+ this.#pollingIntervalSeconds = options.pollingIntervalSeconds ?? 1;
227
+ }
228
+ get queue() {
229
+ return this.#queue;
230
+ }
231
+ get deadLetterQueue() {
232
+ return `${this.#queue}-dead`;
233
+ }
234
+ async initialize() {
235
+ if (!await this.#boss.getQueue(this.deadLetterQueue)) {
236
+ await this.#boss.createQueue(this.deadLetterQueue);
237
+ }
238
+ if (!await this.#boss.getQueue(this.#queue)) {
239
+ await this.#boss.createQueue(this.#queue, {
240
+ policy: "key_strict_fifo",
241
+ retryLimit: 0,
242
+ expireInSeconds: this.#expireInSeconds,
243
+ heartbeatSeconds: this.#heartbeatSeconds,
244
+ deleteAfterSeconds: 0,
245
+ deadLetter: this.deadLetterQueue
246
+ });
247
+ }
248
+ }
249
+ async push(turn) {
250
+ await this.#boss.send(this.#queue, turn, {
251
+ id: uuidv7(),
252
+ singletonKey: turn.chatId,
253
+ priority: turn.kind === "continuation" ? 1 : 0
254
+ });
255
+ }
256
+ async consume(handler, options) {
257
+ const turnWorkerId = await this.#boss.work(
258
+ this.#queue,
259
+ {
260
+ localConcurrency: options.concurrency ?? 1,
261
+ pollingIntervalSeconds: this.#pollingIntervalSeconds
262
+ },
263
+ async ([job]) => {
264
+ let parked = false;
265
+ await handler(job.data, {
266
+ signal: job.signal,
267
+ // Parking = self-cancel: a cancelled job stops blocking the chat's
268
+ // key and is revived (original created_on, so original order) by
269
+ // resumeParked(). The worker's completion of a cancelled job is a
270
+ // clean no-op (probe-verified).
271
+ park: async () => {
272
+ parked = true;
273
+ await this.#boss.cancel(this.#queue, job.id);
274
+ }
275
+ });
276
+ if (!parked) {
277
+ await this.#boss.deleteJob(this.#queue, job.id);
278
+ }
279
+ }
280
+ );
281
+ const deadWorkerId = await this.#boss.work(
282
+ this.deadLetterQueue,
283
+ {
284
+ includeMetadata: true,
285
+ pollingIntervalSeconds: this.#pollingIntervalSeconds
286
+ },
287
+ async ([job]) => {
288
+ await options.onOrphaned(job.data, orphanError(job.output));
289
+ if (job.sourceId) {
290
+ await this.#boss.deleteJob(this.#queue, job.sourceId);
291
+ }
292
+ }
293
+ );
294
+ return {
295
+ [Symbol.asyncDispose]: async () => {
296
+ await this.#boss.offWork(this.#queue, { id: turnWorkerId });
297
+ await this.#boss.offWork(this.deadLetterQueue, { id: deadWorkerId });
298
+ }
299
+ };
300
+ }
301
+ async resumeParked(chatId) {
302
+ const jobs = await this.#boss.findJobs(this.#queue, { key: chatId });
303
+ const parked = jobs.filter((job) => job.state === "cancelled").map((job) => job.id);
304
+ if (parked.length > 0) {
305
+ await this.#boss.resume(this.#queue, parked);
306
+ }
307
+ }
308
+ };
309
+ function orphanError(output) {
310
+ if (output && "message" in output && typeof output.message === "string") {
311
+ return output.message;
312
+ }
313
+ return output ? JSON.stringify(output) : "turn orphaned";
314
+ }
315
+ export {
316
+ PgBossTurnQueue,
317
+ TurnQueue,
318
+ createRuntime,
319
+ defineAgent,
320
+ defineInstructions,
321
+ defineSandbox,
322
+ tool as defineTool
323
+ };
324
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/zukhruf/agent.ts", "../../src/zukhruf/instructions.ts", "../../src/zukhruf/tool.ts", "../../src/zukhruf/sandbox/define.ts", "../../src/zukhruf/runtime.ts", "../../src/zukhruf/queue/turn-queue.ts", "../../src/zukhruf/queue/pg-boss.turn-queue.ts"],
4
+ "sourcesContent": ["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": ";AA0BO,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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,KAAK,QAAQ,IAAI,QAAQ;AAAA,QACtD;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,MACL,CAAC,OAAO,YAAY,GAAG,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": ["options"]
7
+ }
@@ -0,0 +1,3 @@
1
+ import type { ContextFragment } from '@deepagents/context';
2
+ export declare function defineInstructions(...fragments: ContextFragment[]): ContextFragment<import("@deepagents/context").FragmentData>[];
3
+ //# sourceMappingURL=instructions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instructions.d.ts","sourceRoot":"","sources":["../../src/zukhruf/instructions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAE3D,wBAAgB,kBAAkB,CAAC,GAAG,SAAS,EAAE,eAAe,EAAE,iEAEjE"}
@@ -0,0 +1,43 @@
1
+ import type { PgBoss } from 'pg-boss';
2
+ import { type ConsumeContext, type ConsumeOptions, TurnQueue, type TurnRef } from './turn-queue.ts';
3
+ export interface PgBossTurnQueueOptions {
4
+ queue?: string;
5
+ /** Hard cap on one turn attempt; the job fails past this. */
6
+ expireInSeconds?: number;
7
+ /** Dead-worker detection window; must be >= 10 (pg-boss constraint). */
8
+ heartbeatSeconds?: number;
9
+ pollingIntervalSeconds?: number;
10
+ }
11
+ /**
12
+ * TurnQueue on pg-boss.
13
+ *
14
+ * - `key_strict_fifo` policy with `singletonKey = chatId` gives the per-chat
15
+ * serialization contract structurally: one active turn per chat, strict
16
+ * push order, cross-chat concurrency.
17
+ * - `retryLimit: 0` — a crashed turn is never silently re-run (its bash
18
+ * already executed). It dead-letters instead.
19
+ * - A failed job blocks its chat's key until acknowledged; the dead-letter
20
+ * consumer is that acknowledgement: it reports the orphan via
21
+ * `onOrphaned`, then deletes the source job, unblocking the chat.
22
+ * - `deleteAfterSeconds: 0` — pg-boss never deletes a terminal job on a
23
+ * wall-clock timer. That is what makes a parked (cancelled) turn durable: it
24
+ * awaits its approval for as long as it takes, with no retention deadline.
25
+ * Cleanup is commit-driven instead — `consume` deletes a job the moment its
26
+ * turn runs and commits to the chain — so completed jobs don't accumulate.
27
+ * (`retentionSeconds`, which governs still-`created` jobs, can't be 0; its
28
+ * default 14d is never approached because a queued turn only waits behind one
29
+ * running turn.)
30
+ *
31
+ * The `PgBoss` instance is borrowed: the caller `start()`s and `stop()`s it.
32
+ */
33
+ export declare class PgBossTurnQueue extends TurnQueue {
34
+ #private;
35
+ constructor(boss: PgBoss, options?: PgBossTurnQueueOptions);
36
+ get queue(): string;
37
+ get deadLetterQueue(): string;
38
+ initialize(): Promise<void>;
39
+ push(turn: TurnRef): Promise<void>;
40
+ consume(handler: (turn: TurnRef, context: ConsumeContext) => Promise<void>, options: ConsumeOptions): Promise<AsyncDisposable>;
41
+ resumeParked(chatId: string): Promise<void>;
42
+ }
43
+ //# sourceMappingURL=pg-boss.turn-queue.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pg-boss.turn-queue.d.ts","sourceRoot":"","sources":["../../../src/zukhruf/queue/pg-boss.turn-queue.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAmB,MAAM,EAAE,MAAM,SAAS,CAAC;AAGvD,OAAO,EACL,KAAK,cAAc,EACnB,KAAK,cAAc,EACnB,SAAS,EACT,KAAK,OAAO,EACb,MAAM,iBAAiB,CAAC;AAEzB,MAAM,WAAW,sBAAsB;IACrC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,6DAA6D;IAC7D,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,wEAAwE;IACxE,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,sBAAsB,CAAC,EAAE,MAAM,CAAC;CACjC;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,qBAAa,eAAgB,SAAQ,SAAS;;gBAOhC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,sBAA2B;IAS9D,IAAI,KAAK,IAAI,MAAM,CAElB;IAED,IAAI,eAAe,IAAI,MAAM,CAE5B;IAEK,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAgB3B,IAAI,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAgBlC,OAAO,CACX,OAAO,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,EAClE,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,eAAe,CAAC;IAyDrB,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAYlD"}
@@ -0,0 +1,70 @@
1
+ export type TurnRef = {
2
+ streamId: string;
3
+ chatId: string;
4
+ userId: string;
5
+ } & ({
6
+ kind: 'ask';
7
+ /**
8
+ * The user message, carried by the queue until the turn executes. It
9
+ * enters the context chain only when the turn RUNS — enqueue-time
10
+ * persistence would let a queued turn's message leak into the running
11
+ * turn's prompt (and `chat()` streams into the chain head, which must
12
+ * be THIS turn's placeholder).
13
+ */
14
+ input: string;
15
+ } | {
16
+ /**
17
+ * Re-execution of an existing (reopened) stream after a tool approval
18
+ * or denial. Carries no payload: the chain was already updated in
19
+ * place by `approve()`/`deny()`.
20
+ */
21
+ kind: 'continuation';
22
+ });
23
+ export interface ConsumeContext {
24
+ signal: AbortSignal;
25
+ /**
26
+ * Park the turn being handled: it settles WITHOUT executing and is not
27
+ * delivered again until `resumeParked(chatId)`. Used by the queue-behind
28
+ * gate — turns arriving while their chat awaits a tool approval.
29
+ */
30
+ park: () => Promise<void>;
31
+ }
32
+ export interface ConsumeOptions {
33
+ /** Max turns processed concurrently by this consumer (across chats). */
34
+ concurrency?: number;
35
+ /**
36
+ * Fires for a turn whose handler crashed or whose worker died mid-turn.
37
+ * After it resolves, the turn's chat is unblocked and its next queued
38
+ * turn becomes eligible.
39
+ */
40
+ onOrphaned: (turn: TurnRef, error: string) => Promise<void>;
41
+ }
42
+ /**
43
+ * Durable holding pen for pending turns.
44
+ *
45
+ * Contract every implementation must honor:
46
+ * - `push` is durable: a pushed turn survives process death until consumed.
47
+ * - Delivery is AT-LEAST-ONCE: a pushed turn is delivered until settled, and
48
+ * duplicate pushes of the same `streamId` may each be delivered. Consumers
49
+ * MUST be idempotent on `streamId` (the zukhruf runtime skips turns whose
50
+ * stream row is terminal — a check that, unlike queue-side dedup, never
51
+ * expires with job retention).
52
+ * - Per chat, at most ONE handler invocation is active at a time, and turns
53
+ * run in the order they were pushed (strict FIFO per `chatId`) — this
54
+ * covers duplicates too: they can never run concurrently or out of order.
55
+ * - Turns from different chats may run concurrently.
56
+ * - A handler that throws (or a worker that dies mid-turn) does not retry:
57
+ * the turn surfaces once through `onOrphaned`, then the chat unblocks.
58
+ * - A parked turn (`context.park()`) is not delivered again until
59
+ * `resumeParked(chatId)`; revived turns keep their original FIFO order,
60
+ * and a `'continuation'` turn pushed for the chat outranks them.
61
+ *
62
+ * On platforms with native per-conversation serialization (e.g. Durable
63
+ * Objects) this port is absorbed by the host rather than implemented.
64
+ */
65
+ export declare abstract class TurnQueue {
66
+ abstract push(turn: TurnRef): Promise<void>;
67
+ abstract consume(handler: (turn: TurnRef, context: ConsumeContext) => Promise<void>, options: ConsumeOptions): Promise<AsyncDisposable>;
68
+ abstract resumeParked(chatId: string): Promise<void>;
69
+ }
70
+ //# sourceMappingURL=turn-queue.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"turn-queue.d.ts","sourceRoot":"","sources":["../../../src/zukhruf/queue/turn-queue.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,OAAO,GAAG;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB,GAAG,CACA;IACE,IAAI,EAAE,KAAK,CAAC;IACZ;;;;;;OAMG;IACH,KAAK,EAAE,MAAM,CAAC;CACf,GACD;IACE;;;;OAIG;IACH,IAAI,EAAE,cAAc,CAAC;CACtB,CACJ,CAAC;AAEF,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,WAAW,CAAC;IACpB;;;;OAIG;IACH,IAAI,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3B;AAED,MAAM,WAAW,cAAc;IAC7B,wEAAwE;IACxE,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;OAIG;IACH,UAAU,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7D;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,8BAAsB,SAAS;IAC7B,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAE3C,QAAQ,CAAC,OAAO,CACd,OAAO,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,EAClE,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,eAAe,CAAC;IAE3B,QAAQ,CAAC,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CACrD"}
@@ -0,0 +1,67 @@
1
+ import { ContextEngine, type ContextStore, type StreamStore } from '@deepagents/context';
2
+ import type { AgentDeclaration } from './agent.ts';
3
+ import type { TurnQueue } from './queue/turn-queue.ts';
4
+ export interface RuntimeOptions {
5
+ store: ContextStore;
6
+ streamStore: StreamStore;
7
+ queue: TurnQueue;
8
+ }
9
+ export interface ConversationId {
10
+ chatId: string;
11
+ userId: string;
12
+ }
13
+ export interface WorkOptions {
14
+ concurrency?: number;
15
+ }
16
+ export interface TurnInput {
17
+ /**
18
+ * The ask's identity, supplied by the caller: any unique string (a client's
19
+ * message id, or `crypto.randomUUID()` when the caller has no natural key).
20
+ * It doubles as the stream id and the assistant message id. Enqueueing the
21
+ * same id again reattaches to the existing turn instead of running it
22
+ * twice; the first call's `input` wins.
23
+ */
24
+ id: string;
25
+ input: string;
26
+ }
27
+ /**
28
+ * Executes an AgentDeclaration as a background agent, split into three roles:
29
+ *
30
+ * - `enqueue` — durably queue a turn (the queue carries the user message
31
+ * until execution); executes nothing. Safe from any short-lived process.
32
+ * - `work` — start a worker that consumes queued turns; each turn runs
33
+ * start-to-finish in this process, serialized per chat by the TurnQueue.
34
+ * - `observe` — reconnect/cancel from anywhere; never spins a sandbox.
35
+ *
36
+ * Plus the approval verbs: a turn pauses when the model calls a
37
+ * `needsApproval` tool (the pause is pure data — a dangling tool part on the
38
+ * chain head + a terminal stream); `approve`/`deny` resolve it and re-run the
39
+ * turn as a continuation. Turns enqueued while a chat awaits approval QUEUE
40
+ * BEHIND it (parked, revived in order after the continuation).
41
+ */
42
+ export declare function createRuntime(declaration: AgentDeclaration, options: RuntimeOptions): {
43
+ enqueue({ chatId, userId }: ConversationId, turn: TurnInput): Promise<{
44
+ id: string;
45
+ stream: ReadableStream<import("@deepagents/context").StreamPart>;
46
+ }>;
47
+ approve(conversation: ConversationId, input: {
48
+ toolCallId: string;
49
+ }): Promise<{
50
+ id: string;
51
+ stream: ReadableStream<import("@deepagents/context").StreamPart>;
52
+ }>;
53
+ deny(conversation: ConversationId, input: {
54
+ toolCallId: string;
55
+ reason?: string;
56
+ }): Promise<{
57
+ id: string;
58
+ stream: ReadableStream<import("@deepagents/context").StreamPart>;
59
+ }>;
60
+ observe({ chatId, userId }: ConversationId): {
61
+ engine: ContextEngine;
62
+ resume(): Promise<ReadableStream<import("@deepagents/context").StreamPart> | null>;
63
+ cancel(streamId?: string): Promise<void>;
64
+ };
65
+ work(options?: WorkOptions): Promise<AsyncDisposable>;
66
+ };
67
+ //# sourceMappingURL=runtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../src/zukhruf/runtime.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,aAAa,EACb,KAAK,YAAY,EAGjB,KAAK,WAAW,EAKjB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,KAAK,EAAkB,SAAS,EAAW,MAAM,uBAAuB,CAAC;AAEhF,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,YAAY,CAAC;IACpB,WAAW,EAAE,WAAW,CAAC;IACzB,KAAK,EAAE,SAAS,CAAC;CAClB;AAED,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,WAAW;IAC1B,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,SAAS;IACxB;;;;;;OAMG;IACH,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;CACf;AAcD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,aAAa,CAC3B,WAAW,EAAE,gBAAgB,EAC7B,OAAO,EAAE,cAAc;gCAmHa,cAAc,QAAQ,SAAS;;;;0BAsBrC,cAAc,SAAS;QAAE,UAAU,EAAE,MAAM,CAAA;KAAE;;;;uBAOzD,cAAc,SACrB;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE;;;;gCAQpB,cAAc;;;0BAgBd,MAAM;;mBAWb,WAAW,GAAG,OAAO,CAAC,eAAe,CAAC;EAc9D"}
@@ -0,0 +1,6 @@
1
+ import { type AgentSandbox, type DisposableSandbox, createBashTool } from '@deepagents/context';
2
+ import type { SandboxContext } from '../agent.ts';
3
+ type WrapOptions = Omit<Parameters<typeof createBashTool>[0], 'sandbox'>;
4
+ export declare function defineSandbox(createBackend: (context: SandboxContext) => Promise<DisposableSandbox>, options?: WrapOptions): (context: SandboxContext) => Promise<AgentSandbox>;
5
+ export {};
6
+ //# sourceMappingURL=define.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"define.d.ts","sourceRoot":"","sources":["../../../src/zukhruf/sandbox/define.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,YAAY,EACjB,KAAK,iBAAiB,EACtB,cAAc,EACf,MAAM,qBAAqB,CAAC;AAE7B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAElD,KAAK,WAAW,GAAG,IAAI,CAAC,UAAU,CAAC,OAAO,cAAc,CAAC,CAAC,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;AAEzE,wBAAgB,aAAa,CAC3B,aAAa,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,OAAO,CAAC,iBAAiB,CAAC,EACtE,OAAO,CAAC,EAAE,WAAW,GACpB,CAAC,OAAO,EAAE,cAAc,KAAK,OAAO,CAAC,YAAY,CAAC,CAGpD"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Declaration-layer tool definition: a pure passthrough of the AI SDK's
3
+ * `tool()` (full generics, zero side effects). Set `needsApproval: true` to
4
+ * pause the turn on this tool's call until `runtime.approve()`/`deny()`.
5
+ */
6
+ export { tool as defineTool } from 'ai';
7
+ //# sourceMappingURL=tool.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool.d.ts","sourceRoot":"","sources":["../../src/zukhruf/tool.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,IAAI,IAAI,UAAU,EAAE,MAAM,IAAI,CAAC"}
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@deepagents/experimental",
3
+ "version": "4.2.0",
4
+ "license": "MIT",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/JanuaryLabs/deepagents",
8
+ "directory": "packages/experimental"
9
+ },
10
+ "bugs": {
11
+ "url": "https://github.com/JanuaryLabs/deepagents/issues"
12
+ },
13
+ "homepage": "https://github.com/JanuaryLabs/deepagents#readme",
14
+ "type": "module",
15
+ "main": "./dist/index.js",
16
+ "module": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ "./package.json": "./package.json",
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js",
23
+ "default": "./dist/index.js"
24
+ },
25
+ "./zukhruf": {
26
+ "types": "./dist/zukhruf/index.d.ts",
27
+ "import": "./dist/zukhruf/index.js",
28
+ "default": "./dist/zukhruf/index.js"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "!**/*.tsbuildinfo",
34
+ "!**/*.test.*"
35
+ ],
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "dependencies": {
40
+ "@deepagents/context": "4.2.0",
41
+ "ai": "^6.0.218",
42
+ "pg-boss": "^12.24.1",
43
+ "uuid": "^13.0.2"
44
+ },
45
+ "devDependencies": {
46
+ "@ai-sdk/provider": "^3.0.13",
47
+ "@deepagents/test": "0.15.0",
48
+ "@electric-sql/pglite": "^0.5.3",
49
+ "just-bash": "^3.0.1",
50
+ "zod": "^3.25.76 || ^4.0.0"
51
+ }
52
+ }