@deepagents/experimental 4.3.0 → 6.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.
Files changed (70) hide show
  1. package/README.md +24 -9
  2. package/dist/index.js +2613 -167
  3. package/dist/index.js.map +4 -4
  4. package/dist/zukhruf/agent.d.ts +15 -9
  5. package/dist/zukhruf/agent.d.ts.map +1 -1
  6. package/dist/zukhruf/collaboration/agent-tool-context.d.ts +6 -0
  7. package/dist/zukhruf/collaboration/agent-tool-context.d.ts.map +1 -0
  8. package/dist/zukhruf/collaboration/collaboration-tools.d.ts +4 -0
  9. package/dist/zukhruf/collaboration/collaboration-tools.d.ts.map +1 -0
  10. package/dist/zukhruf/collaboration/interrupt-agent.d.ts +234 -0
  11. package/dist/zukhruf/collaboration/interrupt-agent.d.ts.map +1 -0
  12. package/dist/zukhruf/collaboration/list-agents.d.ts +234 -0
  13. package/dist/zukhruf/collaboration/list-agents.d.ts.map +1 -0
  14. package/dist/zukhruf/collaboration/message-tools.d.ts +452 -0
  15. package/dist/zukhruf/collaboration/message-tools.d.ts.map +1 -0
  16. package/dist/zukhruf/collaboration/spawn-agent.d.ts +313 -0
  17. package/dist/zukhruf/collaboration/spawn-agent.d.ts.map +1 -0
  18. package/dist/zukhruf/collaboration/wait-agent.d.ts +253 -0
  19. package/dist/zukhruf/collaboration/wait-agent.d.ts.map +1 -0
  20. package/dist/zukhruf/control-plane/agent-control-plane.d.ts +80 -0
  21. package/dist/zukhruf/control-plane/agent-control-plane.d.ts.map +1 -0
  22. package/dist/zukhruf/control-plane/agent-declaration-registry.d.ts +9 -0
  23. package/dist/zukhruf/control-plane/agent-declaration-registry.d.ts.map +1 -0
  24. package/dist/zukhruf/control-plane/agent-directory.d.ts +22 -0
  25. package/dist/zukhruf/control-plane/agent-directory.d.ts.map +1 -0
  26. package/dist/zukhruf/control-plane/agent-history-forker.d.ts +10 -0
  27. package/dist/zukhruf/control-plane/agent-history-forker.d.ts.map +1 -0
  28. package/dist/zukhruf/control-plane/agent-path.d.ts +15 -0
  29. package/dist/zukhruf/control-plane/agent-path.d.ts.map +1 -0
  30. package/dist/zukhruf/control-plane/agent-status-projector.d.ts +50 -0
  31. package/dist/zukhruf/control-plane/agent-status-projector.d.ts.map +1 -0
  32. package/dist/zukhruf/control-plane/agent-thread.d.ts +31 -0
  33. package/dist/zukhruf/control-plane/agent-thread.d.ts.map +1 -0
  34. package/dist/zukhruf/control-plane/agent-turn-id.d.ts +12 -0
  35. package/dist/zukhruf/control-plane/agent-turn-id.d.ts.map +1 -0
  36. package/dist/zukhruf/control-plane/fork-turns.d.ts +4 -0
  37. package/dist/zukhruf/control-plane/fork-turns.d.ts.map +1 -0
  38. package/dist/zukhruf/index.d.ts +15 -11
  39. package/dist/zukhruf/index.d.ts.map +1 -1
  40. package/dist/zukhruf/index.js +2613 -167
  41. package/dist/zukhruf/index.js.map +4 -4
  42. package/dist/zukhruf/mailbox/coordinator.d.ts +26 -0
  43. package/dist/zukhruf/mailbox/coordinator.d.ts.map +1 -0
  44. package/dist/zukhruf/mailbox/sqlite.store.d.ts +16 -0
  45. package/dist/zukhruf/mailbox/sqlite.store.d.ts.map +1 -0
  46. package/dist/zukhruf/mailbox/store.d.ts +20 -0
  47. package/dist/zukhruf/mailbox/store.d.ts.map +1 -0
  48. package/dist/zukhruf/mailbox/types.d.ts +35 -0
  49. package/dist/zukhruf/mailbox/types.d.ts.map +1 -0
  50. package/dist/zukhruf/multi-agent-v2-config.d.ts +32 -0
  51. package/dist/zukhruf/multi-agent-v2-config.d.ts.map +1 -0
  52. package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts +17 -4
  53. package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts.map +1 -1
  54. package/dist/zukhruf/queue/turn-queue.d.ts +49 -6
  55. package/dist/zukhruf/queue/turn-queue.d.ts.map +1 -1
  56. package/dist/zukhruf/render-turn.d.ts +9 -0
  57. package/dist/zukhruf/render-turn.d.ts.map +1 -0
  58. package/dist/zukhruf/runtime/agent-runtime.d.ts +64 -0
  59. package/dist/zukhruf/runtime/agent-runtime.d.ts.map +1 -0
  60. package/dist/zukhruf/runtime/agent-turn-executor.d.ts +21 -0
  61. package/dist/zukhruf/runtime/agent-turn-executor.d.ts.map +1 -0
  62. package/dist/zukhruf/runtime/approval-controller.d.ts +45 -0
  63. package/dist/zukhruf/runtime/approval-controller.d.ts.map +1 -0
  64. package/dist/zukhruf/runtime/approval-job-id.d.ts +3 -0
  65. package/dist/zukhruf/runtime/approval-job-id.d.ts.map +1 -0
  66. package/dist/zukhruf/tool.d.ts +18 -6
  67. package/dist/zukhruf/tool.d.ts.map +1 -1
  68. package/package.json +11 -10
  69. package/dist/zukhruf/runtime.d.ts +0 -67
  70. package/dist/zukhruf/runtime.d.ts.map +0 -1
@@ -1,227 +1,2415 @@
1
1
  // packages/experimental/src/zukhruf/agent.ts
2
2
  function defineAgent(declaration) {
3
3
  return {
4
- name: declaration.name ?? "agent",
4
+ name: declaration.name,
5
5
  model: declaration.model,
6
6
  sandbox: declaration.sandbox,
7
7
  instructions: declaration.instructions,
8
- tools: declaration.tools
8
+ tools: declaration.tools ?? {},
9
+ subagents: declaration.subagents ?? [],
10
+ telemetry: declaration.telemetry
9
11
  };
10
12
  }
11
13
 
12
- // packages/experimental/src/zukhruf/instructions.ts
13
- function defineInstructions(...fragments) {
14
- return fragments;
14
+ // packages/experimental/src/zukhruf/control-plane/agent-path.ts
15
+ var AgentPath = class _AgentPath {
16
+ #value;
17
+ constructor(value) {
18
+ this.#value = value;
19
+ }
20
+ static root() {
21
+ return new _AgentPath("/root");
22
+ }
23
+ static parse(value) {
24
+ const path = value.trim();
25
+ if (path !== "/root" && !path.startsWith("/root/")) {
26
+ throw new Error(`agent path "${value}" must start at /root`);
27
+ }
28
+ const segments = path.slice(1).split("/");
29
+ if (segments.some(
30
+ (segment) => segment.length === 0 || segment !== segment.trim() || segment === "." || segment === ".."
31
+ )) {
32
+ throw new Error(`agent path "${value}" contains an invalid segment`);
33
+ }
34
+ return new _AgentPath(path);
35
+ }
36
+ /** Relative targets name descendants; absolute targets keep their canonical path. */
37
+ resolve(target) {
38
+ const requested = target.trim();
39
+ if (!requested) throw new Error("agent path cannot be empty");
40
+ return _AgentPath.parse(
41
+ requested.startsWith("/") ? requested : `${this.#value}/${requested}`
42
+ );
43
+ }
44
+ contains(candidate) {
45
+ return this.equals(candidate) || candidate.#value.startsWith(`${this.#value}/`);
46
+ }
47
+ equals(other) {
48
+ return this.#value === other.#value;
49
+ }
50
+ get isRoot() {
51
+ return this.#value === "/root";
52
+ }
53
+ get parent() {
54
+ if (this.isRoot) return null;
55
+ return _AgentPath.parse(this.#value.slice(0, this.#value.lastIndexOf("/")));
56
+ }
57
+ toString() {
58
+ return this.#value;
59
+ }
60
+ };
61
+
62
+ // packages/experimental/src/zukhruf/control-plane/agent-thread.ts
63
+ var AgentThread = class _AgentThread {
64
+ conversation;
65
+ treeId;
66
+ path;
67
+ parentChatId;
68
+ declarationName;
69
+ lastTurnId;
70
+ constructor(options) {
71
+ _AgentThread.#assertTopology(options);
72
+ this.conversation = options.conversation;
73
+ this.treeId = options.treeId;
74
+ this.path = options.path;
75
+ this.parentChatId = options.parentChatId;
76
+ this.declarationName = options.declarationName;
77
+ this.lastTurnId = options.lastTurnId;
78
+ }
79
+ static root(conversation, declarationName) {
80
+ return new _AgentThread({
81
+ conversation,
82
+ treeId: conversation.chatId,
83
+ path: AgentPath.root(),
84
+ parentChatId: null,
85
+ declarationName
86
+ });
87
+ }
88
+ static metadataFilter(treeId) {
89
+ return { key: "zukhrufTreeId", value: treeId };
90
+ }
91
+ static hasReservedMetadata(metadata) {
92
+ return Boolean(
93
+ metadata && (Object.hasOwn(metadata, "zukhrufTreeId") || Object.hasOwn(metadata, "zukhruf"))
94
+ );
95
+ }
96
+ static fromMetadata(conversation, metadata) {
97
+ const treeId = metadata?.zukhrufTreeId;
98
+ const zukhruf = metadata?.zukhruf;
99
+ if (typeof treeId !== "string" || !_AgentThread.#isRecord(zukhruf)) {
100
+ return void 0;
101
+ }
102
+ const { path, parentChatId, declarationName, lastTurnId } = zukhruf;
103
+ if (typeof path !== "string" || parentChatId !== null && typeof parentChatId !== "string" || typeof declarationName !== "string" || lastTurnId !== void 0 && typeof lastTurnId !== "string") {
104
+ return void 0;
105
+ }
106
+ let parsedPath;
107
+ try {
108
+ parsedPath = AgentPath.parse(path);
109
+ } catch {
110
+ return void 0;
111
+ }
112
+ if (parsedPath.toString() !== path) return void 0;
113
+ try {
114
+ return new _AgentThread({
115
+ conversation,
116
+ treeId,
117
+ path: parsedPath,
118
+ parentChatId,
119
+ declarationName,
120
+ ...lastTurnId === void 0 ? {} : { lastTurnId }
121
+ });
122
+ } catch {
123
+ return void 0;
124
+ }
125
+ }
126
+ withLatestTurn(lastTurnId) {
127
+ return new _AgentThread({
128
+ conversation: this.conversation,
129
+ treeId: this.treeId,
130
+ path: this.path,
131
+ parentChatId: this.parentChatId,
132
+ declarationName: this.declarationName,
133
+ lastTurnId
134
+ });
135
+ }
136
+ toMetadata(metadata) {
137
+ const existing = _AgentThread.#isRecord(metadata?.zukhruf) ? metadata.zukhruf : {};
138
+ return {
139
+ ...metadata,
140
+ zukhrufTreeId: this.treeId,
141
+ zukhruf: {
142
+ ...existing,
143
+ path: this.path.toString(),
144
+ parentChatId: this.parentChatId,
145
+ declarationName: this.declarationName,
146
+ ...this.lastTurnId === void 0 ? {} : { lastTurnId: this.lastTurnId }
147
+ }
148
+ };
149
+ }
150
+ static #isRecord(value) {
151
+ return typeof value === "object" && value !== null && !Array.isArray(value);
152
+ }
153
+ static #assertTopology(options) {
154
+ if (options.path.isRoot) {
155
+ if (options.treeId !== options.conversation.chatId) {
156
+ throw new Error("root agent thread treeId must match its chatId");
157
+ }
158
+ if (options.parentChatId !== null) {
159
+ throw new Error("root agent thread cannot have a parent");
160
+ }
161
+ return;
162
+ }
163
+ if (options.parentChatId === null) {
164
+ throw new Error("child agent thread requires a parent");
165
+ }
166
+ if (options.parentChatId === options.conversation.chatId) {
167
+ throw new Error("child agent thread cannot parent itself");
168
+ }
169
+ }
170
+ };
171
+
172
+ // packages/experimental/src/zukhruf/runtime/agent-runtime.ts
173
+ import {
174
+ ContextEngine as ContextEngine4
175
+ } from "@deepagents/context";
176
+
177
+ // packages/experimental/src/zukhruf/control-plane/agent-control-plane.ts
178
+ import { v5 as uuidv54 } from "uuid";
179
+
180
+ // packages/experimental/src/zukhruf/mailbox/types.ts
181
+ import { randomUUID } from "node:crypto";
182
+ var MessageDeliveryMode = {
183
+ QueueOnly: "queue-only",
184
+ TriggerTurn: "trigger-turn"
185
+ };
186
+ var InterAgentCommunicationType = {
187
+ Message: "MESSAGE",
188
+ NewTask: "NEW_TASK",
189
+ FinalAnswer: "FINAL_ANSWER"
190
+ };
191
+ function createInterAgentCommunication(communication) {
192
+ const value = {
193
+ ...communication,
194
+ id: communication.id ?? randomUUID(),
195
+ type: communication.type ?? InterAgentCommunicationType.Message,
196
+ otherRecipients: communication.otherRecipients ?? [],
197
+ triggerTurn: false
198
+ };
199
+ assertCommunication(value);
200
+ return value;
201
+ }
202
+ function assertCommunication(communication) {
203
+ if (!communication.id.trim()) {
204
+ throw new Error("inter-agent communication id cannot be empty");
205
+ }
206
+ if (!Object.values(InterAgentCommunicationType).includes(communication.type)) {
207
+ throw new Error("inter-agent communication type is invalid");
208
+ }
209
+ assertConversationId(communication.author, "author");
210
+ assertConversationId(communication.recipient, "recipient");
211
+ for (const recipient of communication.otherRecipients) {
212
+ assertConversationId(recipient, "other recipient");
213
+ }
214
+ if (!communication.content.trim()) {
215
+ throw new Error("inter-agent communication content cannot be empty");
216
+ }
217
+ }
218
+ function assertConversationId(value, label) {
219
+ if (!value.chatId.trim() || !value.userId.trim()) {
220
+ throw new Error(
221
+ `inter-agent communication ${label} requires chatId and userId`
222
+ );
223
+ }
15
224
  }
16
225
 
17
- // packages/experimental/src/zukhruf/tool.ts
18
- import { tool } from "ai";
226
+ // packages/experimental/src/zukhruf/control-plane/agent-declaration-registry.ts
227
+ var AgentDeclarationRegistry = class {
228
+ root;
229
+ #declarations = /* @__PURE__ */ new Map();
230
+ constructor(root) {
231
+ this.root = root;
232
+ this.#register(root, /* @__PURE__ */ new Set());
233
+ }
234
+ get(name) {
235
+ return this.#declarations.get(name);
236
+ }
237
+ #register(declaration, visited) {
238
+ if (visited.has(declaration)) return;
239
+ visited.add(declaration);
240
+ if (!declaration.name.trim()) {
241
+ throw new Error("AgentRuntime: agent declaration name cannot be empty");
242
+ }
243
+ if (declaration.name !== declaration.name.trim()) {
244
+ throw new Error(
245
+ `AgentRuntime: agent declaration name "${declaration.name}" must not contain surrounding whitespace`
246
+ );
247
+ }
248
+ const existing = this.#declarations.get(declaration.name);
249
+ if (existing && existing !== declaration) {
250
+ throw new Error(
251
+ `AgentRuntime: duplicate agent declaration name "${declaration.name}"`
252
+ );
253
+ }
254
+ this.#declarations.set(declaration.name, declaration);
255
+ for (const subagent of declaration.subagents ?? []) {
256
+ this.#register(subagent, visited);
257
+ }
258
+ }
259
+ };
19
260
 
20
- // packages/experimental/src/zukhruf/sandbox/define.ts
261
+ // packages/experimental/src/zukhruf/control-plane/agent-directory.ts
262
+ import { v5 as uuidv5 } from "uuid";
263
+ var AgentDirectory = class _AgentDirectory {
264
+ #store;
265
+ constructor(store) {
266
+ this.#store = store;
267
+ }
268
+ async assertOwnerIfExists(conversation) {
269
+ const chat2 = await this.#store.getChat(conversation.chatId);
270
+ if (!chat2) return;
271
+ this.#assertOwner(conversation, chat2.userId);
272
+ const thread = this.#threadFromMetadata(conversation, chat2.metadata);
273
+ if (thread) await this.#assertValidParent(thread);
274
+ }
275
+ async load(conversation) {
276
+ const chat2 = await this.#store.getChat(conversation.chatId);
277
+ if (chat2) this.#assertOwner(conversation, chat2.userId);
278
+ if (!chat2) return void 0;
279
+ const thread = this.#threadFromMetadata(conversation, chat2.metadata);
280
+ if (thread) await this.#assertValidParent(thread);
281
+ return thread;
282
+ }
283
+ async loadOrCreateRoot(conversation, declarationName) {
284
+ await this.#store.upsertChat({
285
+ id: conversation.chatId,
286
+ userId: conversation.userId
287
+ });
288
+ let thread;
289
+ let adopted = false;
290
+ await this.#store.updateChat(conversation.chatId, (chat2) => {
291
+ this.#assertOwner(conversation, chat2.userId);
292
+ const existing = this.#threadFromMetadata(conversation, chat2.metadata);
293
+ if (existing) {
294
+ thread = existing;
295
+ adopted = true;
296
+ return void 0;
297
+ }
298
+ thread = AgentThread.root(conversation, declarationName);
299
+ adopted = false;
300
+ return { metadata: thread.toMetadata(chat2.metadata) };
301
+ });
302
+ if (adopted) {
303
+ await this.#assertValidParent(thread);
304
+ }
305
+ return thread;
306
+ }
307
+ async recordLatestTurn(conversation, streamId) {
308
+ return this.#updateLatestTurn(conversation, streamId);
309
+ }
310
+ async recordLatestTurnIfCurrent(conversation, streamId, expectedLastTurnId) {
311
+ return this.#updateLatestTurn(conversation, streamId, expectedLastTurnId);
312
+ }
313
+ async listTree(thread) {
314
+ const chats = await this.#store.listChats({
315
+ userId: thread.conversation.userId,
316
+ metadata: AgentThread.metadataFilter(thread.treeId)
317
+ });
318
+ return Promise.all(
319
+ chats.map(async (chat2) => {
320
+ const conversation = { chatId: chat2.id, userId: chat2.userId };
321
+ const member = this.#threadFromMetadata(conversation, chat2.metadata);
322
+ if (!member) {
323
+ throw new Error(
324
+ `AgentDirectory.listTree: chat "${chat2.id}" is missing Zukhruf metadata`
325
+ );
326
+ }
327
+ await this.#assertValidParent(member);
328
+ return member;
329
+ })
330
+ );
331
+ }
332
+ async resolve(thread, target) {
333
+ const path = thread.path.resolve(target);
334
+ const match = await this.find(thread, target);
335
+ if (match) return match;
336
+ throw new Error(`agent path "${path}" does not exist in this tree`);
337
+ }
338
+ async find(thread, target) {
339
+ const path = thread.path.resolve(target);
340
+ return (await this.listTree(thread)).find(
341
+ (candidate) => candidate.path.equals(path)
342
+ );
343
+ }
344
+ async createChild(options) {
345
+ const path = options.parent.path.resolve(options.taskName);
346
+ const pathString = path.toString();
347
+ const conversation = {
348
+ chatId: _AgentDirectory.#childChatId(
349
+ options.parent.conversation.userId,
350
+ options.parent.treeId,
351
+ pathString
352
+ ),
353
+ userId: options.parent.conversation.userId
354
+ };
355
+ const occupied = (await this.listTree(options.parent)).find(
356
+ (thread) => thread.path.equals(path)
357
+ );
358
+ if (occupied && occupied.conversation.chatId !== conversation.chatId) {
359
+ throw new Error(`agent path "${pathString}" already exists`);
360
+ }
361
+ const child = new AgentThread({
362
+ conversation,
363
+ treeId: options.parent.treeId,
364
+ path,
365
+ parentChatId: options.parent.conversation.chatId,
366
+ declarationName: options.declarationName
367
+ });
368
+ const storedChat = await this.#store.upsertChat({
369
+ id: conversation.chatId,
370
+ userId: conversation.userId,
371
+ metadata: child.toMetadata(void 0)
372
+ });
373
+ const stored = AgentThread.fromMetadata(
374
+ { chatId: storedChat.id, userId: storedChat.userId },
375
+ storedChat.metadata
376
+ );
377
+ if (storedChat.userId !== conversation.userId || stored?.treeId !== child.treeId || !stored.path.equals(child.path) || stored.parentChatId !== child.parentChatId || stored.declarationName !== child.declarationName) {
378
+ throw new Error(`agent path "${pathString}" already exists`);
379
+ }
380
+ return stored;
381
+ }
382
+ static #childChatId(userId, treeId, path) {
383
+ return uuidv5(
384
+ `urn:deepagents:zukhruf:agent:${JSON.stringify([userId, treeId, path])}`,
385
+ uuidv5.URL
386
+ );
387
+ }
388
+ #assertOwner(conversation, storedUserId) {
389
+ if (storedUserId === conversation.userId) return;
390
+ throw new Error(
391
+ `chat "${conversation.chatId}" belongs to user "${storedUserId}", not "${conversation.userId}"`
392
+ );
393
+ }
394
+ #threadFromMetadata(conversation, metadata) {
395
+ const thread = AgentThread.fromMetadata(conversation, metadata);
396
+ if (!thread && AgentThread.hasReservedMetadata(metadata)) {
397
+ throw new Error(
398
+ `invalid Zukhruf metadata for chat "${conversation.chatId}"`
399
+ );
400
+ }
401
+ return thread;
402
+ }
403
+ async #assertValidParent(thread) {
404
+ if (thread.path.isRoot) return;
405
+ const parentChatId = thread.parentChatId;
406
+ if (!parentChatId) {
407
+ throw new Error(
408
+ `invalid Zukhruf parent for chat "${thread.conversation.chatId}"`
409
+ );
410
+ }
411
+ const parentChat = await this.#store.getChat(parentChatId);
412
+ if (!parentChat || parentChat.userId !== thread.conversation.userId) {
413
+ throw new Error(
414
+ `invalid Zukhruf parent for chat "${thread.conversation.chatId}"`
415
+ );
416
+ }
417
+ const parent = this.#threadFromMetadata(
418
+ { chatId: parentChat.id, userId: parentChat.userId },
419
+ parentChat.metadata
420
+ );
421
+ const expectedPath = thread.path.parent;
422
+ if (!parent || !expectedPath || parent.treeId !== thread.treeId || !parent.path.equals(expectedPath)) {
423
+ throw new Error(
424
+ `invalid Zukhruf parent for chat "${thread.conversation.chatId}"`
425
+ );
426
+ }
427
+ }
428
+ async #updateLatestTurn(conversation, streamId, ...expected) {
429
+ let result;
430
+ await this.#store.updateChat(conversation.chatId, (chat2) => {
431
+ this.#assertOwner(conversation, chat2.userId);
432
+ const thread = this.#threadFromMetadata(conversation, chat2.metadata);
433
+ if (!thread) {
434
+ throw new Error(
435
+ `AgentDirectory.recordLatestTurn: missing agent metadata for chat "${conversation.chatId}"`
436
+ );
437
+ }
438
+ if (expected.length > 0 && thread.lastTurnId !== expected[0]) {
439
+ result = void 0;
440
+ return void 0;
441
+ }
442
+ if (thread.lastTurnId === streamId) {
443
+ result = thread;
444
+ return void 0;
445
+ }
446
+ result = thread.withLatestTurn(streamId);
447
+ return { metadata: result.toMetadata(chat2.metadata) };
448
+ });
449
+ return result;
450
+ }
451
+ };
452
+
453
+ // packages/experimental/src/zukhruf/control-plane/agent-history-forker.ts
454
+ import { validateUIMessages } from "ai";
455
+ import { v5 as uuidv52 } from "uuid";
21
456
  import {
22
- createBashTool
457
+ isSyntheticReminderMessage
23
458
  } from "@deepagents/context";
24
- function defineSandbox(createBackend, options) {
25
- return async (context) => createBashTool({ sandbox: await createBackend(context), ...options });
459
+ var AgentHistoryForker = class {
460
+ #store;
461
+ constructor(store) {
462
+ this.#store = store;
463
+ }
464
+ async fork(parent, child, forkTurns) {
465
+ const record = await this.#claim(parent, child, forkTurns);
466
+ if (record.forkTurns === "none" || record.parentHeadMessageId === null) {
467
+ return;
468
+ }
469
+ const selected = await this.#selectedMessages(parent, child, record);
470
+ if (selected.length === 0) return;
471
+ const cloned = this.#cloneMessages(child, selected);
472
+ const expectedIds = cloned.map((message) => message.id);
473
+ const branch = await this.#store.getActiveBranch(child.conversation.chatId);
474
+ if (!branch) {
475
+ throw new Error(
476
+ `spawn_agent: child chat "${child.conversation.chatId}" has no active branch`
477
+ );
478
+ }
479
+ if (branch.headMessageId !== null) {
480
+ if (await this.#hasForkedPrefix(child, expectedIds)) return;
481
+ throw new Error(
482
+ `spawn_agent: cannot apply parent history after child "${child.path}" has started`
483
+ );
484
+ }
485
+ const head = cloned.at(-1);
486
+ if (!head) return;
487
+ await this.#store.addMessages(cloned);
488
+ const committed = await this.#store.updateBranchHead(
489
+ branch.id,
490
+ head.id,
491
+ null
492
+ );
493
+ if (!committed && !await this.#hasForkedPrefix(child, expectedIds)) {
494
+ throw new Error(
495
+ `spawn_agent: child "${child.path}" started before parent history was applied`
496
+ );
497
+ }
498
+ if (!await this.#hasForkedPrefix(child, expectedIds)) {
499
+ throw new Error(
500
+ `spawn_agent: failed to persist parent history for child "${child.path}"`
501
+ );
502
+ }
503
+ }
504
+ async #claim(parent, child, forkTurns) {
505
+ const parentBranch = await this.#store.getActiveBranch(
506
+ parent.conversation.chatId
507
+ );
508
+ if (!parentBranch) {
509
+ throw new Error(
510
+ `spawn_agent: parent chat "${parent.conversation.chatId}" has no active branch`
511
+ );
512
+ }
513
+ const proposed = {
514
+ forkTurns,
515
+ parentChatId: parent.conversation.chatId,
516
+ parentHeadMessageId: forkTurns === "none" ? null : parentBranch.headMessageId
517
+ };
518
+ let claimed;
519
+ await this.#store.updateChat(child.conversation.chatId, (chat2) => {
520
+ const metadata = chat2.metadata;
521
+ const zukhruf = metadata?.zukhruf;
522
+ if (!isRecord(zukhruf)) {
523
+ throw new Error(
524
+ `spawn_agent: child chat "${child.conversation.chatId}" is missing Zukhruf metadata`
525
+ );
526
+ }
527
+ if (zukhruf.historyFork !== void 0) {
528
+ claimed = parseHistoryForkRecord(zukhruf.historyFork);
529
+ if (claimed.parentChatId !== proposed.parentChatId || claimed.forkTurns !== proposed.forkTurns) {
530
+ throw new Error(
531
+ `spawn_agent: agent path "${child.path}" already exists with a different fork_turns setting`
532
+ );
533
+ }
534
+ return void 0;
535
+ }
536
+ claimed = proposed;
537
+ return {
538
+ metadata: {
539
+ ...metadata,
540
+ zukhruf: { ...zukhruf, historyFork: proposed }
541
+ }
542
+ };
543
+ });
544
+ if (!claimed) {
545
+ throw new Error(
546
+ `spawn_agent: failed to claim history for child "${child.path}"`
547
+ );
548
+ }
549
+ return claimed;
550
+ }
551
+ async #sourceMessages(parent, record) {
552
+ const headId = record.parentHeadMessageId;
553
+ if (headId === null) return [];
554
+ const chain = await this.#store.getMessageChain(headId);
555
+ if (chain.at(-1)?.id !== headId) {
556
+ throw new Error(
557
+ `spawn_agent: parent history head "${headId}" is unavailable`
558
+ );
559
+ }
560
+ if (chain.some((message) => message.chatId !== parent.conversation.chatId)) {
561
+ throw new Error("spawn_agent: parent history crosses chat boundaries");
562
+ }
563
+ const materialized = chain.filter(
564
+ (message) => !isEmptyAssistantPlaceholder(message.data)
565
+ );
566
+ const messages = await validateUIMessages({
567
+ messages: materialized.map((message) => message.data)
568
+ });
569
+ return materialized.map((stored, index) => {
570
+ const message = messages[index];
571
+ if (message.id !== stored.id) {
572
+ throw new Error(
573
+ `spawn_agent: stored message "${stored.id}" has a mismatched payload id`
574
+ );
575
+ }
576
+ return { stored, message };
577
+ });
578
+ }
579
+ async #selectedMessages(parent, child, record) {
580
+ if (record.forkTurns === "none") return [];
581
+ if (record.sourceMessageIds !== void 0) {
582
+ return this.#messagesById(parent, record.sourceMessageIds);
583
+ }
584
+ const source = await this.#sourceMessages(parent, record);
585
+ const selected = this.#select(source, record.forkTurns).map((entry) => this.#keepHistoryMessage(entry)).filter((entry) => entry !== void 0);
586
+ const sourceMessageIds = await this.#claimSelection(
587
+ child,
588
+ selected.map(({ stored }) => stored.id)
589
+ );
590
+ return arraysEqual(
591
+ sourceMessageIds,
592
+ selected.map(({ stored }) => stored.id)
593
+ ) ? selected : this.#messagesById(parent, sourceMessageIds);
594
+ }
595
+ async #messagesById(parent, sourceMessageIds) {
596
+ const storedMessages = await Promise.all(
597
+ sourceMessageIds.map((id) => this.#store.getMessage(id))
598
+ );
599
+ if (storedMessages.some(
600
+ (message) => message === void 0 || message.chatId !== parent.conversation.chatId
601
+ )) {
602
+ throw new Error(
603
+ "spawn_agent: persisted parent-history snapshot is unavailable"
604
+ );
605
+ }
606
+ const stored = storedMessages;
607
+ const messages = await validateUIMessages({
608
+ messages: stored.map((message) => message.data)
609
+ });
610
+ return stored.map((messageData, index) => {
611
+ const source = this.#keepHistoryMessage({
612
+ stored: messageData,
613
+ message: messages[index]
614
+ });
615
+ if (!source || source.message.id !== messageData.id) {
616
+ throw new Error(
617
+ `spawn_agent: persisted parent-history message "${messageData.id}" changed shape`
618
+ );
619
+ }
620
+ return source;
621
+ });
622
+ }
623
+ async #claimSelection(child, proposedIds) {
624
+ let sourceMessageIds;
625
+ await this.#store.updateChat(child.conversation.chatId, (chat2) => {
626
+ const metadata = chat2.metadata;
627
+ const zukhruf = metadata?.zukhruf;
628
+ if (!isRecord(zukhruf)) {
629
+ throw new Error(
630
+ `spawn_agent: child chat "${child.conversation.chatId}" is missing Zukhruf metadata`
631
+ );
632
+ }
633
+ const record = parseHistoryForkRecord(zukhruf.historyFork);
634
+ if (record.sourceMessageIds !== void 0) {
635
+ sourceMessageIds = record.sourceMessageIds;
636
+ return void 0;
637
+ }
638
+ sourceMessageIds = proposedIds;
639
+ return {
640
+ metadata: {
641
+ ...metadata,
642
+ zukhruf: {
643
+ ...zukhruf,
644
+ historyFork: { ...record, sourceMessageIds: proposedIds }
645
+ }
646
+ }
647
+ };
648
+ });
649
+ if (!sourceMessageIds) {
650
+ throw new Error(
651
+ `spawn_agent: failed to claim parent-history messages for child "${child.path}"`
652
+ );
653
+ }
654
+ return sourceMessageIds;
655
+ }
656
+ #select(source, forkTurns) {
657
+ if (forkTurns === "all") return source;
658
+ const boundaries = source.flatMap(
659
+ (entry, index) => isForkTurnBoundary(entry.message) ? [index] : []
660
+ );
661
+ const start = boundaries.at(-forkTurns) ?? boundaries[0];
662
+ return start === void 0 ? [] : source.slice(start);
663
+ }
664
+ #keepHistoryMessage(entry) {
665
+ const { message } = entry;
666
+ if (message.role === "user") {
667
+ if (isSyntheticReminderMessage(message) || interAgentCommunication(message) !== void 0) {
668
+ return void 0;
669
+ }
670
+ return entry;
671
+ }
672
+ if (message.role !== "assistant") return void 0;
673
+ const finalStepStart = message.parts.findLastIndex(
674
+ (part) => part.type === "step-start"
675
+ );
676
+ const parts = message.parts.slice(finalStepStart + 1).filter(
677
+ (part) => ["text", "file", "source-url", "source-document"].includes(part.type)
678
+ );
679
+ return parts.length === 0 ? void 0 : { ...entry, message: { ...message, parts } };
680
+ }
681
+ #cloneMessages(child, selected) {
682
+ let parentId = null;
683
+ return selected.map(({ stored, message }) => {
684
+ const id = uuidv52(
685
+ `urn:deepagents:zukhruf:forked-message:${JSON.stringify([
686
+ child.conversation.chatId,
687
+ stored.id
688
+ ])}`,
689
+ uuidv52.URL
690
+ );
691
+ const clone = {
692
+ id,
693
+ chatId: child.conversation.chatId,
694
+ parentId,
695
+ name: message.role,
696
+ type: "message",
697
+ data: { ...message, id },
698
+ createdAt: stored.createdAt
699
+ };
700
+ parentId = id;
701
+ return clone;
702
+ });
703
+ }
704
+ async #hasForkedPrefix(child, expectedIds) {
705
+ const branch = await this.#store.getActiveBranch(child.conversation.chatId);
706
+ if (!branch?.headMessageId) return false;
707
+ const chain = await this.#store.getMessageChain(branch.headMessageId);
708
+ return expectedIds.every(
709
+ (id, index) => chain[index]?.id === id && chain[index]?.chatId === child.conversation.chatId
710
+ );
711
+ }
712
+ };
713
+ function isForkTurnBoundary(message) {
714
+ if (message.role !== "user" || isSyntheticReminderMessage(message)) {
715
+ return false;
716
+ }
717
+ return interAgentCommunication(message)?.triggerTurn ?? true;
718
+ }
719
+ function interAgentCommunication(message) {
720
+ if (!isRecord(message.metadata)) return void 0;
721
+ if (!Object.hasOwn(message.metadata, "interAgentCommunication")) {
722
+ return void 0;
723
+ }
724
+ const communication = message.metadata.interAgentCommunication;
725
+ if (!isRecord(communication) || typeof communication.triggerTurn !== "boolean") {
726
+ throw new Error(
727
+ `spawn_agent: message "${message.id}" has invalid inter-agent metadata`
728
+ );
729
+ }
730
+ return { triggerTurn: communication.triggerTurn };
731
+ }
732
+ function parseHistoryForkRecord(value) {
733
+ if (!isRecord(value)) {
734
+ throw new Error("spawn_agent: invalid persisted history-fork metadata");
735
+ }
736
+ const { forkTurns, parentChatId, parentHeadMessageId, sourceMessageIds } = value;
737
+ if (!isForkTurns(forkTurns) || typeof parentChatId !== "string" || !parentChatId.trim() || parentHeadMessageId !== null && (typeof parentHeadMessageId !== "string" || parentHeadMessageId.length === 0) || sourceMessageIds !== void 0 && (!Array.isArray(sourceMessageIds) || !sourceMessageIds.every(
738
+ (id) => typeof id === "string" && id.trim().length > 0
739
+ ) || new Set(sourceMessageIds).size !== sourceMessageIds.length)) {
740
+ throw new Error("spawn_agent: invalid persisted history-fork metadata");
741
+ }
742
+ return {
743
+ forkTurns,
744
+ parentChatId,
745
+ parentHeadMessageId,
746
+ ...sourceMessageIds === void 0 ? {} : { sourceMessageIds }
747
+ };
748
+ }
749
+ function isForkTurns(value) {
750
+ return value === "none" || value === "all" || typeof value === "number" && Number.isSafeInteger(value) && value > 0;
751
+ }
752
+ function isRecord(value) {
753
+ return typeof value === "object" && value !== null && !Array.isArray(value);
754
+ }
755
+ function isEmptyAssistantPlaceholder(value) {
756
+ return isRecord(value) && typeof value.id === "string" && value.role === "assistant" && Array.isArray(value.parts) && value.parts.length === 0;
757
+ }
758
+ function arraysEqual(left, right) {
759
+ return left.length === right.length && left.every((value, index) => value === right[index]);
26
760
  }
27
761
 
28
- // packages/experimental/src/zukhruf/runtime.ts
29
- import { isToolUIPart } from "ai";
762
+ // packages/experimental/src/zukhruf/control-plane/agent-status-projector.ts
763
+ import { isTextUIPart } from "ai";
764
+ import { z } from "zod";
30
765
  import {
31
- ContextEngine,
32
- PollingChangeSource,
33
- StreamManager,
766
+ ContextEngine
767
+ } from "@deepagents/context";
768
+ var listedAgentStatusSchema = z.union([
769
+ z.enum(["pending_init", "running", "interrupted", "shutdown", "not_found"]),
770
+ z.object({ completed: z.string().nullable() }).strict(),
771
+ z.object({ errored: z.string() }).strict()
772
+ ]);
773
+ var listedAgentSchema = z.object({
774
+ agent_name: z.string(),
775
+ agent_status: listedAgentStatusSchema
776
+ }).strict();
777
+ var AgentStatusProjector = class _AgentStatusProjector {
778
+ #store;
779
+ #streams;
780
+ #queue;
781
+ #mailbox;
782
+ #directory;
783
+ #approvals;
784
+ constructor(options) {
785
+ this.#store = options.store;
786
+ this.#streams = options.streams;
787
+ this.#queue = options.queue;
788
+ this.#mailbox = options.mailbox;
789
+ this.#directory = options.directory;
790
+ this.#approvals = options.approvals;
791
+ }
792
+ async projectListedAgent(currentTurn, thread) {
793
+ const messages = await this.#messages(thread);
794
+ const head = messages.at(-1);
795
+ const streamId = thread.lastTurnId ?? (head?.role === "assistant" ? head.id : void 0);
796
+ const stream = streamId ? await this.#streams.store.getStream(streamId) : void 0;
797
+ const scheduledTurn = await this.#queue.getCurrentTurn(thread.conversation);
798
+ const scheduledStream = scheduledTurn ? await this.#streams.store.getStream(scheduledTurn.streamId) : void 0;
799
+ let status = _AgentStatusProjector.#listedStatus(
800
+ stream?.status,
801
+ stream?.error,
802
+ head
803
+ );
804
+ if (stream?.status === "completed" && this.#approvals.isPaused(head)) {
805
+ status = "running";
806
+ }
807
+ if (thread.conversation.chatId === currentTurn.chatId || thread.lastTurnId !== void 0 && scheduledTurn?.streamId !== thread.lastTurnId && (scheduledStream?.status === "queued" || scheduledStream?.status === "running")) {
808
+ status = "running";
809
+ }
810
+ return {
811
+ agent_name: thread.path.toString(),
812
+ agent_status: status
813
+ };
814
+ }
815
+ async projectTerminal(turn, thread) {
816
+ if (thread.parentChatId === null) return;
817
+ const stream = await this.#streams.store.getStream(turn.streamId);
818
+ if (!stream || stream.status !== "completed" && stream.status !== "failed" && stream.status !== "cancelled") {
819
+ return;
820
+ }
821
+ const message = (await this.#messages(thread)).find(
822
+ (candidate) => candidate.role === "assistant" && candidate.id === turn.streamId
823
+ );
824
+ if (stream.status === "completed" && this.#approvals.isPaused(message)) {
825
+ return;
826
+ }
827
+ const text = message?.role === "assistant" ? _AgentStatusProjector.#messageText(message) : "";
828
+ let content = text || "Agent completed without a text response.";
829
+ if (stream.status === "failed") {
830
+ content = `Agent failed: ${stream.error || "unknown error"}`;
831
+ } else if (stream.status === "cancelled") {
832
+ content = "Agent was interrupted.";
833
+ }
834
+ const parent = await this.#directory.load({
835
+ chatId: thread.parentChatId,
836
+ userId: thread.conversation.userId
837
+ });
838
+ await this.#mailbox.deliver(
839
+ createInterAgentCommunication({
840
+ id: `zukhruf:child-terminal:${turn.streamId}`,
841
+ type: InterAgentCommunicationType.FinalAnswer,
842
+ author: thread.conversation,
843
+ recipient: {
844
+ chatId: thread.parentChatId,
845
+ userId: thread.conversation.userId
846
+ },
847
+ content,
848
+ metadata: {
849
+ authorPath: thread.path.toString(),
850
+ recipientPath: parent?.path.toString() ?? thread.parentChatId,
851
+ streamId: turn.streamId,
852
+ status: stream.status
853
+ }
854
+ }),
855
+ MessageDeliveryMode.QueueOnly
856
+ );
857
+ }
858
+ async #messages(thread) {
859
+ const engine = new ContextEngine({
860
+ store: this.#store,
861
+ chatId: thread.conversation.chatId,
862
+ userId: thread.conversation.userId
863
+ });
864
+ return engine.getMessages();
865
+ }
866
+ static #listedStatus(status, error, head) {
867
+ switch (status) {
868
+ case "running":
869
+ return "running";
870
+ case "completed":
871
+ return {
872
+ completed: head?.role === "assistant" ? _AgentStatusProjector.#messageText(head) || null : null
873
+ };
874
+ case "failed":
875
+ return { errored: error || "Agent turn failed." };
876
+ case "cancelled":
877
+ return "interrupted";
878
+ case "queued":
879
+ case void 0:
880
+ return "pending_init";
881
+ }
882
+ }
883
+ static #messageText(message) {
884
+ return message.parts.filter(isTextUIPart).map((part) => part.text).join("\n").trim();
885
+ }
886
+ };
887
+
888
+ // packages/experimental/src/zukhruf/control-plane/agent-turn-id.ts
889
+ import { v5 as uuidv53 } from "uuid";
890
+ var AgentTurnId = class _AgentTurnId {
891
+ static #prefix = "zukhruf-turn";
892
+ #value;
893
+ constructor(value) {
894
+ this.#value = value;
895
+ }
896
+ static fromRequest(conversation, requestId) {
897
+ if (!requestId.trim()) {
898
+ throw new Error("turn id cannot be empty");
899
+ }
900
+ const scope = conversationNamespace(conversation);
901
+ return new _AgentTurnId(
902
+ `${_AgentTurnId.#prefix}:${scope}:${uuidv53(requestId, scope)}`
903
+ );
904
+ }
905
+ static random(conversation) {
906
+ return _AgentTurnId.fromRequest(conversation, crypto.randomUUID());
907
+ }
908
+ static assertOwner(conversation, streamId) {
909
+ const expectedPrefix = `${_AgentTurnId.#prefix}:${conversationNamespace(conversation)}:`;
910
+ if (!streamId.startsWith(expectedPrefix)) {
911
+ throw new Error(
912
+ `stream "${streamId}" does not belong to conversation "${conversation.chatId}"`
913
+ );
914
+ }
915
+ }
916
+ toString() {
917
+ return this.#value;
918
+ }
919
+ };
920
+ function conversationNamespace(conversation) {
921
+ if (!conversation.chatId.trim() || !conversation.userId.trim()) {
922
+ throw new Error("conversation requires non-empty chatId and userId");
923
+ }
924
+ return uuidv53(
925
+ JSON.stringify([conversation.userId, conversation.chatId]),
926
+ uuidv53.URL
927
+ );
928
+ }
929
+
930
+ // packages/experimental/src/zukhruf/control-plane/agent-control-plane.ts
931
+ var AgentControlPlane = class _AgentControlPlane {
932
+ #root;
933
+ #streams;
934
+ #queue;
935
+ #mailbox;
936
+ #declarations;
937
+ #directory;
938
+ #statusProjector;
939
+ #historyForker;
940
+ constructor(options) {
941
+ this.#root = options.root;
942
+ this.#streams = options.streams;
943
+ this.#queue = options.queue;
944
+ this.#mailbox = options.mailbox;
945
+ this.#declarations = options.declarations;
946
+ this.#directory = options.directory;
947
+ this.#statusProjector = options.statusProjector;
948
+ this.#historyForker = options.historyForker;
949
+ }
950
+ async resolve(conversation) {
951
+ const thread = await this.#directory.loadOrCreateRoot(
952
+ conversation,
953
+ this.#root.name
954
+ );
955
+ const declaration = this.#declarations.get(thread.declarationName);
956
+ if (!declaration) {
957
+ throw new Error(
958
+ `AgentControlPlane.resolve: unknown agent declaration "${thread.declarationName}"`
959
+ );
960
+ }
961
+ return { declaration, thread };
962
+ }
963
+ async enqueue(conversation, turn) {
964
+ if (!turn.id.trim()) {
965
+ throw new Error(
966
+ "enqueue: turn id is required \u2014 it names the ask, making retries idempotent"
967
+ );
968
+ }
969
+ await this.#directory.assertOwnerIfExists(conversation);
970
+ const streamId = AgentTurnId.fromRequest(conversation, turn.id).toString();
971
+ await this.#streams.register(streamId);
972
+ await this.#queue.push({
973
+ kind: "ask",
974
+ streamId,
975
+ chatId: conversation.chatId,
976
+ userId: conversation.userId,
977
+ input: turn.input
978
+ });
979
+ return streamId;
980
+ }
981
+ recordLatestTurn(conversation, streamId) {
982
+ return this.#directory.recordLatestTurn(conversation, streamId);
983
+ }
984
+ recordLatestTurnIfCurrent(conversation, streamId, expectedLastTurnId) {
985
+ return this.#directory.recordLatestTurnIfCurrent(
986
+ conversation,
987
+ streamId,
988
+ expectedLastTurnId
989
+ );
990
+ }
991
+ async spawn(actor, input) {
992
+ const childDeclaration = (actor.declaration.subagents ?? []).find(
993
+ (subagent) => subagent.name === input.agentType
994
+ );
995
+ if (!childDeclaration) {
996
+ throw new Error(
997
+ `spawn_agent: agent type "${input.agentType}" is not a subagent of "${actor.declaration.name}"`
998
+ );
999
+ }
1000
+ let child;
1001
+ try {
1002
+ child = await this.#directory.createChild({
1003
+ parent: actor.thread,
1004
+ taskName: input.taskName,
1005
+ declarationName: childDeclaration.name
1006
+ });
1007
+ } catch (error) {
1008
+ if (error instanceof Error && error.message.startsWith("agent path ")) {
1009
+ throw new Error(`spawn_agent: ${error.message}`);
1010
+ }
1011
+ throw error;
1012
+ }
1013
+ const childPath = child.path.toString();
1014
+ const requestId = _AgentControlPlane.#initialTurnId(
1015
+ child.conversation.chatId
1016
+ );
1017
+ const streamId = AgentTurnId.fromRequest(
1018
+ child.conversation,
1019
+ requestId
1020
+ ).toString();
1021
+ const status = await this.#streams.store.getStreamStatus(streamId);
1022
+ if (status === "completed" || status === "failed" || status === "cancelled") {
1023
+ throw new Error(
1024
+ `spawn_agent: agent path "${childPath}" already finished with status "${status}"`
1025
+ );
1026
+ }
1027
+ await this.#historyForker.fork(actor.thread, child, input.forkTurns);
1028
+ await this.enqueue(child.conversation, {
1029
+ id: requestId,
1030
+ input: input.message
1031
+ });
1032
+ return { task_name: childPath };
1033
+ }
1034
+ async sendMessage(actor, input) {
1035
+ return this.#deliverAgentMessage(actor, input, {
1036
+ type: InterAgentCommunicationType.Message,
1037
+ mode: MessageDeliveryMode.QueueOnly,
1038
+ rejectRoot: false
1039
+ });
1040
+ }
1041
+ async followupTask(actor, input) {
1042
+ return this.#deliverAgentMessage(actor, input, {
1043
+ type: InterAgentCommunicationType.NewTask,
1044
+ mode: MessageDeliveryMode.TriggerTurn,
1045
+ rejectRoot: true
1046
+ });
1047
+ }
1048
+ async listAgents(actor, pathPrefix) {
1049
+ const prefix = pathPrefix ? actor.thread.path.resolve(pathPrefix) : void 0;
1050
+ const threads = await this.#directory.listTree(actor.thread);
1051
+ const agents = await Promise.all(
1052
+ threads.flatMap((thread) => {
1053
+ if (prefix && !prefix.contains(thread.path)) return [];
1054
+ return [this.#statusProjector.projectListedAgent(actor.turn, thread)];
1055
+ })
1056
+ );
1057
+ agents.sort(
1058
+ (left, right) => left.agent_name.localeCompare(right.agent_name)
1059
+ );
1060
+ return { agents };
1061
+ }
1062
+ async interruptAgent(actor, input) {
1063
+ const target = await this.#directory.find(actor.thread, input.target);
1064
+ if (!target) return { previous_status: "not_found" };
1065
+ if (target.path.isRoot) {
1066
+ throw new Error("interrupt_agent: the root agent cannot be interrupted");
1067
+ }
1068
+ if (target.path.equals(actor.thread.path)) {
1069
+ throw new Error("interrupt_agent: an agent cannot interrupt itself");
1070
+ }
1071
+ const previous = await this.#statusProjector.projectListedAgent(
1072
+ actor.turn,
1073
+ target
1074
+ );
1075
+ const currentTurn = await this.#queue.getCurrentTurn(target.conversation);
1076
+ if (currentTurn) {
1077
+ const interruptedThread = await this.#directory.recordLatestTurnIfCurrent(
1078
+ target.conversation,
1079
+ currentTurn.streamId,
1080
+ target.lastTurnId
1081
+ ) ?? target;
1082
+ await this.#streams.cancel(currentTurn.streamId);
1083
+ await this.#statusProjector.projectTerminal(
1084
+ currentTurn,
1085
+ interruptedThread
1086
+ );
1087
+ await this.#queue.cancel(currentTurn.streamId);
1088
+ }
1089
+ return { previous_status: previous.agent_status };
1090
+ }
1091
+ waitForMailbox(actor, options) {
1092
+ return this.#mailbox.waitForPending(actor.thread.conversation, options);
1093
+ }
1094
+ async projectTerminal(turn, thread) {
1095
+ await this.#statusProjector.projectTerminal(turn, thread);
1096
+ }
1097
+ async #deliverAgentMessage(actor, input, options) {
1098
+ const target = await this.#directory.resolve(actor.thread, input.target);
1099
+ if (options.rejectRoot && target.path.isRoot) {
1100
+ throw new Error(
1101
+ "followup_task: the root agent cannot receive a follow-up"
1102
+ );
1103
+ }
1104
+ await this.#mailbox.deliver(
1105
+ createInterAgentCommunication({
1106
+ type: options.type,
1107
+ author: actor.thread.conversation,
1108
+ recipient: target.conversation,
1109
+ content: input.message,
1110
+ metadata: {
1111
+ authorPath: actor.thread.path.toString(),
1112
+ recipientPath: target.path.toString()
1113
+ }
1114
+ }),
1115
+ options.mode
1116
+ );
1117
+ return { target: target.path.toString() };
1118
+ }
1119
+ static #initialTurnId(chatId) {
1120
+ return uuidv54(`urn:deepagents:zukhruf:initial-turn:${chatId}`, uuidv54.URL);
1121
+ }
1122
+ };
1123
+
1124
+ // packages/experimental/src/zukhruf/mailbox/coordinator.ts
1125
+ import { setTimeout as delay } from "node:timers/promises";
1126
+ var WAIT_POLL_INTERVAL_MS = 50;
1127
+ var MailboxCoordinator = class {
1128
+ #store;
1129
+ #queue;
1130
+ #streams;
1131
+ #wakeRequests = /* @__PURE__ */ new Map();
1132
+ constructor(options) {
1133
+ this.#store = options.store;
1134
+ this.#queue = options.queue;
1135
+ this.#streams = options.streams;
1136
+ }
1137
+ async deliver(communication, mode) {
1138
+ const delivered = {
1139
+ ...communication,
1140
+ type: mode === MessageDeliveryMode.TriggerTurn ? InterAgentCommunicationType.NewTask : communication.type,
1141
+ triggerTurn: mode === MessageDeliveryMode.TriggerTurn
1142
+ };
1143
+ assertCommunication(delivered);
1144
+ const { recipientActive } = await this.#store.enqueue(delivered);
1145
+ if (delivered.triggerTurn || recipientActive) {
1146
+ await this.#scheduleWake(delivered.recipient);
1147
+ }
1148
+ }
1149
+ beginTurn(turn) {
1150
+ return this.#store.beginTurn(turn, turn.streamId);
1151
+ }
1152
+ async endTurn(turn, options = {}) {
1153
+ const { hasPending, turnEnded } = await this.#store.endTurn(
1154
+ turn,
1155
+ turn.streamId
1156
+ );
1157
+ if (turnEnded && hasPending && !options.parked) {
1158
+ await this.#scheduleWake(turn);
1159
+ }
1160
+ }
1161
+ drainLeadingQueueOnly(recipient) {
1162
+ return this.#store.drainLeadingQueueOnly(recipient);
1163
+ }
1164
+ drain(recipient) {
1165
+ return this.#store.drain(recipient);
1166
+ }
1167
+ async waitForPending(recipient, options) {
1168
+ const deadline = Date.now() + options.timeoutMs;
1169
+ while (true) {
1170
+ options.signal?.throwIfAborted();
1171
+ if (await this.#store.hasPending(recipient)) return true;
1172
+ const remaining = deadline - Date.now();
1173
+ if (remaining <= 0) return false;
1174
+ await delay(Math.min(WAIT_POLL_INTERVAL_MS, remaining), void 0, {
1175
+ signal: options.signal
1176
+ });
1177
+ }
1178
+ }
1179
+ #scheduleWake(target) {
1180
+ const key = this.#conversationKey(target);
1181
+ const existing = this.#wakeRequests.get(key);
1182
+ if (existing) return existing;
1183
+ const request = (async () => {
1184
+ const wakeId = AgentTurnId.random(target).toString();
1185
+ await this.#streams.register(wakeId);
1186
+ try {
1187
+ await this.#queue.push({
1188
+ kind: "mailbox",
1189
+ streamId: wakeId,
1190
+ chatId: target.chatId,
1191
+ userId: target.userId
1192
+ });
1193
+ } catch (error) {
1194
+ await this.#streams.store.updateStreamStatus(wakeId, "failed", {
1195
+ error: error instanceof Error ? error.message : String(error)
1196
+ });
1197
+ throw error;
1198
+ }
1199
+ })();
1200
+ this.#wakeRequests.set(key, request);
1201
+ const clearRequest = () => {
1202
+ if (this.#wakeRequests.get(key) === request) {
1203
+ this.#wakeRequests.delete(key);
1204
+ }
1205
+ };
1206
+ void request.then(clearRequest, clearRequest);
1207
+ return request;
1208
+ }
1209
+ #conversationKey(conversation) {
1210
+ return JSON.stringify([conversation.chatId, conversation.userId]);
1211
+ }
1212
+ };
1213
+
1214
+ // packages/experimental/src/zukhruf/multi-agent-v2-config.ts
1215
+ var DEFAULT_MIN_WAIT_TIMEOUT_MS = 1e4;
1216
+ var DEFAULT_WAIT_TIMEOUT_MS = 3e4;
1217
+ var DEFAULT_MAX_WAIT_TIMEOUT_MS = 36e5;
1218
+ var RESERVED_TOOL_NAMESPACES = /* @__PURE__ */ new Set([
1219
+ "api_tool",
1220
+ "browser",
1221
+ "computer",
1222
+ "container",
1223
+ "file_search",
1224
+ "functions",
1225
+ "image_gen",
1226
+ "multi_tool_use",
1227
+ "python",
1228
+ "python_user_visible",
1229
+ "submodel_delegator",
1230
+ "terminal",
1231
+ "tool_search",
1232
+ "web"
1233
+ ]);
1234
+ function resolveMultiAgentV2HostConfig(input = {}) {
1235
+ const minWaitTimeoutMs = input.minWaitTimeoutMs ?? DEFAULT_MIN_WAIT_TIMEOUT_MS;
1236
+ const defaultWaitTimeoutMs = input.defaultWaitTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
1237
+ const maxWaitTimeoutMs = input.maxWaitTimeoutMs ?? DEFAULT_MAX_WAIT_TIMEOUT_MS;
1238
+ assertTimeout("minWaitTimeoutMs", minWaitTimeoutMs);
1239
+ assertTimeout("defaultWaitTimeoutMs", defaultWaitTimeoutMs);
1240
+ assertTimeout("maxWaitTimeoutMs", maxWaitTimeoutMs);
1241
+ if (minWaitTimeoutMs > maxWaitTimeoutMs) {
1242
+ throw new Error(
1243
+ "AgentRuntime: multiAgentV2.minWaitTimeoutMs must be at most maxWaitTimeoutMs"
1244
+ );
1245
+ }
1246
+ if (defaultWaitTimeoutMs < minWaitTimeoutMs) {
1247
+ throw new Error(
1248
+ "AgentRuntime: multiAgentV2.defaultWaitTimeoutMs must be at least minWaitTimeoutMs"
1249
+ );
1250
+ }
1251
+ if (defaultWaitTimeoutMs > maxWaitTimeoutMs) {
1252
+ throw new Error(
1253
+ "AgentRuntime: multiAgentV2.defaultWaitTimeoutMs must be at most maxWaitTimeoutMs"
1254
+ );
1255
+ }
1256
+ const toolNamespace = input.toolNamespace;
1257
+ if (toolNamespace !== void 0 && (toolNamespace.length === 0 || toolNamespace.trim() !== toolNamespace)) {
1258
+ throw new Error(
1259
+ "AgentRuntime: multiAgentV2.toolNamespace cannot be empty or padded"
1260
+ );
1261
+ }
1262
+ if (toolNamespace !== void 0) validateToolNamespace(toolNamespace);
1263
+ const nonCodeModeOnly = input.nonCodeModeOnly ?? true;
1264
+ if (!nonCodeModeOnly) {
1265
+ throw new Error(
1266
+ "AgentRuntime: multiAgentV2.nonCodeModeOnly=false requires a nested code-mode executor, which Zukhruf does not provide"
1267
+ );
1268
+ }
1269
+ const tool7 = (name) => toolNamespace === void 0 ? name : `${toolNamespace}.${name}`;
1270
+ const collaborationTools = [
1271
+ "spawn_agent",
1272
+ "send_message",
1273
+ "followup_task",
1274
+ "wait_agent",
1275
+ "interrupt_agent",
1276
+ "list_agents"
1277
+ ].map((name) => `\`${tool7(name)}\``).join(", ");
1278
+ const shared = `Call ${collaborationTools} directly. They are intentionally unavailable inside nested code execution.
1279
+
1280
+ All agents share the same workspace, current working directory, and filesystem.`;
1281
+ return {
1282
+ minWaitTimeoutMs,
1283
+ defaultWaitTimeoutMs,
1284
+ maxWaitTimeoutMs,
1285
+ usageHintText: nonEmptyText(input.usageHintText),
1286
+ rootAgentUsageHintText: input.rootAgentUsageHintText === void 0 ? defaultRootUsageHint(tool7, shared) : nonEmptyText(input.rootAgentUsageHintText),
1287
+ subagentUsageHintText: input.subagentUsageHintText === void 0 ? defaultSubagentUsageHint(tool7, shared) : nonEmptyText(input.subagentUsageHintText),
1288
+ toolNamespace,
1289
+ nonCodeModeOnly
1290
+ };
1291
+ }
1292
+ function assertTimeout(name, value) {
1293
+ if (!Number.isSafeInteger(value) || value < 0) {
1294
+ throw new Error(
1295
+ `AgentRuntime: multiAgentV2.${name} must be a non-negative safe integer`
1296
+ );
1297
+ }
1298
+ }
1299
+ function validateToolNamespace(namespace) {
1300
+ if (namespace.length > 64 || !/^[a-zA-Z0-9_-]+$/.test(namespace) || namespace === "mcp" || namespace.startsWith("mcp__") || RESERVED_TOOL_NAMESPACES.has(namespace)) {
1301
+ throw new Error(
1302
+ `AgentRuntime: multiAgentV2.toolNamespace "${namespace}" is a reserved tool namespace or invalid`
1303
+ );
1304
+ }
1305
+ }
1306
+ function nonEmptyText(value) {
1307
+ if (value === void 0) return void 0;
1308
+ return value.length === 0 ? void 0 : value;
1309
+ }
1310
+ function defaultRootUsageHint(tool7, shared) {
1311
+ return `You are \`/root\`, the primary agent in a team of agents collaborating to fulfill the user's goals.
1312
+
1313
+ At the start of your turn, you are the active agent. You can spawn sub-agents to handle subtasks, and those agents can recursively spawn their own declared sub-agents. All agents are equally capable and receive the tools declared for their agent type.
1314
+
1315
+ Use \`${tool7("spawn_agent")}\` to create an agent, \`${tool7("followup_task")}\` to assign a new task and trigger a turn, and \`${tool7("send_message")}\` to queue a message without triggering a turn. Use \`fork_turns\` to control how much parent history the child receives.
1316
+
1317
+ Child messages arrive as \`MESSAGE\` or \`FINAL_ANSWER\` mailbox envelopes with their task name, sender, and payload preserved.
1318
+
1319
+ ${shared}`;
1320
+ }
1321
+ function defaultSubagentUsageHint(tool7, shared) {
1322
+ return `You are an agent in a team collaborating to complete a task.
1323
+
1324
+ You can spawn declared sub-agents recursively. All agents are equally capable and receive the tools declared for their agent type. Use \`${tool7("spawn_agent")}\` to create one, \`${tool7("followup_task")}\` to assign a new task and trigger a turn, and \`${tool7("send_message")}\` to queue a message for another agent.
1325
+
1326
+ Your final response is delivered automatically to your parent agent. Mailbox messages arrive as \`NEW_TASK\`, \`MESSAGE\`, or \`FINAL_ANSWER\` envelopes with their task name, sender, and payload preserved.
1327
+
1328
+ ${shared}`;
1329
+ }
1330
+
1331
+ // packages/experimental/src/zukhruf/runtime/agent-turn-executor.ts
1332
+ import {
1333
+ ContextEngine as ContextEngine2,
34
1334
  agent,
35
1335
  assistant,
36
1336
  chat,
1337
+ role,
37
1338
  user
38
1339
  } 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
- );
1340
+
1341
+ // packages/experimental/src/zukhruf/collaboration/interrupt-agent.ts
1342
+ import { tool } from "ai";
1343
+ import { z as z2 } from "zod";
1344
+ var interruptAgentInputSchema = z2.object({
1345
+ target: z2.string().trim().min(1).describe(
1346
+ "The canonical /root/... path, or a descendant-relative target name."
1347
+ )
1348
+ });
1349
+ var interruptAgentOutputSchema = z2.object({ previous_status: listedAgentStatusSchema }).strict();
1350
+ var interruptAgentTool = tool({
1351
+ description: "Interrupt an agent's current turn, if any, and return its previous status. The agent remains available for messages and follow-up tasks.",
1352
+ inputSchema: interruptAgentInputSchema,
1353
+ outputSchema: interruptAgentOutputSchema,
1354
+ execute: async (input, { context }) => context.controlPlane.interruptAgent(context.actor, input)
1355
+ });
1356
+
1357
+ // packages/experimental/src/zukhruf/collaboration/list-agents.ts
1358
+ import { tool as tool2 } from "ai";
1359
+ import { z as z3 } from "zod";
1360
+ var listAgentsInputSchema = z3.object({
1361
+ path_prefix: z3.string().trim().min(1).describe(
1362
+ "Task-path prefix without a trailing slash. Omit to list the whole tree."
1363
+ ).optional()
1364
+ });
1365
+ var listAgentsOutputSchema = z3.object({ agents: z3.array(listedAgentSchema) }).strict();
1366
+ var listAgentsTool = tool2({
1367
+ description: "List live agents in the current root thread tree. Optionally filter by task-path prefix.",
1368
+ inputSchema: listAgentsInputSchema,
1369
+ outputSchema: listAgentsOutputSchema,
1370
+ execute: async ({ path_prefix }, { context }) => context.controlPlane.listAgents(context.actor, path_prefix)
1371
+ });
1372
+
1373
+ // packages/experimental/src/zukhruf/collaboration/message-tools.ts
1374
+ import { tool as tool3 } from "ai";
1375
+ import { z as z4 } from "zod";
1376
+ var agentMessageInputSchema = z4.object({
1377
+ target: z4.string().trim().min(1).describe(
1378
+ "The canonical /root/... path, or a descendant-relative target name."
1379
+ ),
1380
+ message: z4.string().trim().min(1).describe("The message or follow-up task.")
1381
+ });
1382
+ var sendMessageTool = tool3({
1383
+ description: "Queue a message for another agent. Address siblings with their canonical /root/... path.",
1384
+ inputSchema: agentMessageInputSchema,
1385
+ execute: async (input, { context }) => {
1386
+ await context.controlPlane.sendMessage(context.actor, input);
1387
+ return "";
1388
+ }
1389
+ });
1390
+ var followupTaskTool = tool3({
1391
+ description: "Send a follow-up task to an existing non-root agent and wake its thread.",
1392
+ inputSchema: agentMessageInputSchema,
1393
+ execute: async (input, { context }) => {
1394
+ await context.controlPlane.followupTask(context.actor, input);
1395
+ return "";
1396
+ }
1397
+ });
1398
+
1399
+ // packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
1400
+ import { tool as tool4 } from "ai";
1401
+ import { z as z5 } from "zod";
1402
+
1403
+ // packages/experimental/src/zukhruf/control-plane/fork-turns.ts
1404
+ var forkTurnsError = "fork_turns must be `none`, `all`, or a positive integer string";
1405
+ function parseForkTurns(value) {
1406
+ const normalized = value.trim().toLowerCase();
1407
+ if (normalized === "none" || normalized === "all") return normalized;
1408
+ if (!/^\d+$/.test(normalized)) return void 0;
1409
+ const turns = Number(normalized);
1410
+ return Number.isSafeInteger(turns) && turns > 0 ? turns : void 0;
48
1411
  }
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 })
1412
+
1413
+ // packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
1414
+ var spawnAgentInputSchema = z5.object({
1415
+ agent_type: z5.string().trim().min(1).describe("The name of one available subagent declaration."),
1416
+ task_name: z5.string().trim().min(1).refine(
1417
+ (value) => value !== "." && value !== ".." && !value.includes("/"),
1418
+ "task_name must be one non-empty path segment"
1419
+ ).describe("One path segment naming this independent agent task."),
1420
+ message: z5.string().refine((value) => value.trim().length > 0, "message cannot be empty").describe("The initial task for the spawned agent."),
1421
+ fork_turns: z5.string().trim().default("all").refine((value) => parseForkTurns(value) !== void 0, forkTurnsError).describe(
1422
+ "Optional number of parent turns to fork. Defaults to `all`. Use `none`, `all`, or a positive integer string such as `3`."
1423
+ )
1424
+ });
1425
+ var spawnAgentOutputSchema = z5.object({ task_name: z5.string() }).strict();
1426
+ function createSpawnAgentTool(options) {
1427
+ return tool4({
1428
+ description: ({ context }) => {
1429
+ const available = (context.actor.declaration.subagents ?? []).map((subagent) => subagent.name).join(", ");
1430
+ return [
1431
+ `Spawn an independent subagent. Available agent types: ${available || "none"}.`,
1432
+ options?.usageHintText
1433
+ ].filter(Boolean).join(" ");
1434
+ },
1435
+ inputSchema: spawnAgentInputSchema,
1436
+ outputSchema: spawnAgentOutputSchema,
1437
+ execute: async ({ agent_type, task_name, message, fork_turns }, { context }) => {
1438
+ const forkTurns = parseForkTurns(fork_turns);
1439
+ if (forkTurns === void 0) throw new Error(forkTurnsError);
1440
+ return context.controlPlane.spawn(context.actor, {
1441
+ agentType: agent_type,
1442
+ taskName: task_name,
1443
+ message,
1444
+ forkTurns
1445
+ });
1446
+ }
1447
+ });
1448
+ }
1449
+
1450
+ // packages/experimental/src/zukhruf/collaboration/wait-agent.ts
1451
+ import { tool as tool5 } from "ai";
1452
+ import { z as z6 } from "zod";
1453
+ var waitAgentOutputSchema = z6.object({ message: z6.string(), timed_out: z6.boolean() }).strict();
1454
+ function createWaitAgentTool(options) {
1455
+ const waitAgentInputSchema = z6.object({
1456
+ timeout_ms: z6.number().int().min(options.minTimeoutMs).max(options.maxTimeoutMs).optional().describe("Maximum time to wait in milliseconds.")
1457
+ });
1458
+ return tool5({
1459
+ description: "Wait for pending mail addressed to this agent without consuming it.",
1460
+ inputSchema: waitAgentInputSchema,
1461
+ outputSchema: waitAgentOutputSchema,
1462
+ execute: async ({ timeout_ms }, { abortSignal, context }) => {
1463
+ const received = await context.controlPlane.waitForMailbox(
1464
+ context.actor,
1465
+ {
1466
+ timeoutMs: timeout_ms ?? options.defaultTimeoutMs,
1467
+ signal: abortSignal
1468
+ }
1469
+ );
1470
+ return received ? { message: "Wait completed.", timed_out: false } : { message: "Wait timed out.", timed_out: true };
1471
+ }
54
1472
  });
55
- function engineFor({ chatId, userId }) {
56
- return new ContextEngine({ store, chatId, userId });
1473
+ }
1474
+
1475
+ // packages/experimental/src/zukhruf/collaboration/collaboration-tools.ts
1476
+ var NAMESPACE_DESCRIPTION = "Tools for spawning and managing sub-agents.";
1477
+ function createCollaborationTools(config) {
1478
+ const tools = {
1479
+ spawn_agent: createSpawnAgentTool({
1480
+ usageHintText: config.usageHintText
1481
+ }),
1482
+ send_message: sendMessageTool,
1483
+ followup_task: followupTaskTool,
1484
+ list_agents: listAgentsTool,
1485
+ wait_agent: createWaitAgentTool({
1486
+ minTimeoutMs: config.minWaitTimeoutMs,
1487
+ defaultTimeoutMs: config.defaultWaitTimeoutMs,
1488
+ maxTimeoutMs: config.maxWaitTimeoutMs
1489
+ }),
1490
+ interrupt_agent: interruptAgentTool
1491
+ };
1492
+ return Object.fromEntries(
1493
+ Object.entries(tools).map(([name, collaborationTool]) => [
1494
+ name,
1495
+ configureTool(collaborationTool, config)
1496
+ ])
1497
+ );
1498
+ }
1499
+ function configureTool(collaborationTool, config) {
1500
+ const openai = collaborationTool.providerOptions?.openai;
1501
+ return {
1502
+ ...collaborationTool,
1503
+ providerOptions: {
1504
+ ...collaborationTool.providerOptions,
1505
+ ...config.toolNamespace === void 0 ? {} : {
1506
+ openai: {
1507
+ ...typeof openai === "object" && openai !== null ? openai : {},
1508
+ namespace: {
1509
+ name: config.toolNamespace,
1510
+ description: NAMESPACE_DESCRIPTION
1511
+ }
1512
+ }
1513
+ }
1514
+ },
1515
+ metadata: {
1516
+ ...collaborationTool.metadata,
1517
+ zukhruf: {
1518
+ kind: "collaboration",
1519
+ codeModeExposure: "direct-model-only"
1520
+ }
1521
+ }
1522
+ };
1523
+ }
1524
+
1525
+ // packages/experimental/src/zukhruf/runtime/agent-turn-executor.ts
1526
+ var AgentTurnExecutor = class {
1527
+ #store;
1528
+ #streams;
1529
+ #controlPlane;
1530
+ #mailbox;
1531
+ #approvals;
1532
+ #multiAgentV2;
1533
+ #collaborationTools;
1534
+ constructor(options) {
1535
+ this.#store = options.store;
1536
+ this.#streams = options.streams;
1537
+ this.#controlPlane = options.controlPlane;
1538
+ this.#mailbox = options.mailbox;
1539
+ this.#approvals = options.approvals;
1540
+ this.#multiAgentV2 = options.multiAgentV2;
1541
+ this.#collaborationTools = createCollaborationTools(options.multiAgentV2);
57
1542
  }
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") {
1543
+ async execute(turn, context) {
1544
+ if (turn.kind === "approval") {
1545
+ if (!await this.#approvals.applyDecision(turn)) return;
1546
+ await this.#reopen(turn.streamId);
1547
+ return this.execute(
1548
+ {
1549
+ kind: "continuation",
1550
+ streamId: turn.streamId,
1551
+ chatId: turn.chatId,
1552
+ userId: turn.userId
1553
+ },
1554
+ context
1555
+ );
1556
+ }
1557
+ if (turn.kind === "continuation" && turn.recovery !== void 0) {
1558
+ await this.#reopen(turn.streamId);
1559
+ }
1560
+ if (await this.#projectSkippedTerminalTurn(turn)) return;
1561
+ let parked = false;
1562
+ await this.#mailbox.beginTurn(turn);
1563
+ try {
1564
+ await this.#executeTurn(turn, {
1565
+ ...context,
1566
+ park: async () => {
1567
+ parked = true;
1568
+ await context.park();
1569
+ }
1570
+ });
1571
+ } finally {
1572
+ await this.#mailbox.endTurn(turn, { parked });
1573
+ }
1574
+ }
1575
+ async #executeTurn(turn, { signal, park }) {
1576
+ if (await this.#projectSkippedTerminalTurn(turn)) return;
1577
+ const { declaration, thread } = await this.#controlPlane.resolve(turn);
1578
+ const usageHint = thread.path.isRoot ? this.#multiAgentV2.rootAgentUsageHintText : this.#multiAgentV2.subagentUsageHintText;
1579
+ const engine = this.#engineFor(turn).set(
1580
+ ...declaration.instructions,
1581
+ ...usageHint === void 0 ? [] : [role(usageHint)]
1582
+ );
1583
+ if (turn.kind === "ask" || turn.kind === "mailbox") {
63
1584
  const head = (await engine.getMessages()).at(-1);
64
- if (head?.role === "assistant" && pendingToolPart(head)) {
1585
+ if (this.#approvals.isPaused(head)) {
65
1586
  await park();
66
1587
  return;
67
1588
  }
1589
+ }
1590
+ let communications = [];
1591
+ if (turn.kind === "ask") {
1592
+ communications = await this.#mailbox.drainLeadingQueueOnly(turn);
1593
+ } else if (turn.kind === "mailbox") {
1594
+ communications = await this.#mailbox.drain(turn);
1595
+ }
1596
+ if (turn.kind === "mailbox" && communications.length === 0) {
1597
+ await this.#streams.store.updateStreamStatus(turn.streamId, "completed");
1598
+ return;
1599
+ }
1600
+ await this.#controlPlane.recordLatestTurn(turn, turn.streamId);
1601
+ await this.#prepareChain(turn, engine, communications);
1602
+ const sandbox = await declaration.sandbox({
1603
+ chatId: turn.chatId,
1604
+ userId: turn.userId
1605
+ });
1606
+ if (await this.#projectSkippedTerminalTurn(turn)) return;
1607
+ if (!await this.#streams.claim(turn.streamId)) {
1608
+ await this.#projectSkippedTerminalTurn(turn);
1609
+ return;
1610
+ }
1611
+ const mailboxState = { firstRequest: true };
1612
+ const ai = agent({
1613
+ name: declaration.name,
1614
+ model: declaration.model,
1615
+ sandbox,
1616
+ context: engine,
1617
+ tools: {
1618
+ ...declaration.tools,
1619
+ ...this.#collaborationTools
1620
+ },
1621
+ telemetry: declaration.telemetry,
1622
+ prepareStepInput: () => this.#prepareStepInput(turn, mailboxState)
1623
+ });
1624
+ const abort = new AbortController();
1625
+ const onWorkerAbort = () => abort.abort();
1626
+ signal.addEventListener("abort", onWorkerAbort, { once: true });
1627
+ try {
1628
+ const setupCancellation = this.#streams.monitorCancellation(
1629
+ turn.streamId,
1630
+ () => abort.abort()
1631
+ );
1632
+ let stream;
1633
+ try {
1634
+ stream = await chat(ai, {
1635
+ abortSignal: abort.signal,
1636
+ contextVariables: {
1637
+ controlPlane: this.#controlPlane,
1638
+ actor: { turn, thread, declaration }
1639
+ }
1640
+ });
1641
+ } finally {
1642
+ await setupCancellation[Symbol.asyncDispose]();
1643
+ }
1644
+ await this.#streams.persist(stream, turn.streamId, {
1645
+ preclaimed: true,
1646
+ onCancelDetected: () => abort.abort()
1647
+ });
1648
+ if (turn.kind === "continuation") {
1649
+ await this.#reconcileTerminalContinuation(turn);
1650
+ }
1651
+ await this.#controlPlane.projectTerminal(turn, thread);
1652
+ } finally {
1653
+ signal.removeEventListener("abort", onWorkerAbort);
1654
+ }
1655
+ }
1656
+ async #projectSkippedTerminalTurn(turn) {
1657
+ const status = await this.#streams.store.getStreamStatus(turn.streamId);
1658
+ if (status === "queued" || status === "running") return false;
1659
+ if (status === void 0 || turn.kind === "mailbox") return true;
1660
+ if (turn.kind === "continuation") {
1661
+ await this.#reconcileTerminalContinuation(turn);
1662
+ }
1663
+ const { thread } = await this.#controlPlane.resolve(turn);
1664
+ if (thread.lastTurnId === void 0 || thread.lastTurnId === turn.streamId) {
1665
+ await this.#controlPlane.recordLatestTurnIfCurrent(
1666
+ turn,
1667
+ turn.streamId,
1668
+ thread.lastTurnId
1669
+ );
1670
+ }
1671
+ await this.#controlPlane.projectTerminal(turn, thread);
1672
+ return true;
1673
+ }
1674
+ async #reconcileTerminalContinuation(turn) {
1675
+ const stream = await this.#streams.store.getStream(turn.streamId);
1676
+ if (stream?.status !== "completed" && stream?.status !== "failed" && stream?.status !== "cancelled") {
1677
+ return;
1678
+ }
1679
+ await this.#approvals.reconcileTerminalContinuation(
1680
+ turn,
1681
+ turn.streamId,
1682
+ stream.status,
1683
+ stream.error
1684
+ );
1685
+ }
1686
+ async #reopen(streamId) {
1687
+ const status = await this.#streams.store.getStreamStatus(streamId);
1688
+ if (status === "queued" || status === "running") return;
1689
+ await this.#streams.reopen(streamId);
1690
+ }
1691
+ async #prepareChain(turn, engine, communications) {
1692
+ if (turn.kind === "ask") {
68
1693
  engine.set(
1694
+ ...communications.map(
1695
+ (communication) => user(this.#mailboxInputMessage(communication))
1696
+ ),
69
1697
  user(turn.input),
70
1698
  assistant({ id: turn.streamId, role: "assistant", parts: [] })
71
1699
  );
72
1700
  await engine.save({ branch: true });
1701
+ } else if (turn.kind === "mailbox") {
1702
+ engine.set(
1703
+ ...communications.map(
1704
+ (communication) => user(this.#mailboxInputMessage(communication))
1705
+ ),
1706
+ assistant({ id: turn.streamId, role: "assistant", parts: [] })
1707
+ );
1708
+ await engine.save({ branch: true });
73
1709
  }
74
- const sandbox = await declaration.sandbox({
75
- chatId: turn.chatId,
76
- userId: turn.userId
1710
+ }
1711
+ async #prepareStepInput(turn, state) {
1712
+ const communications = turn.kind === "ask" && state.firstRequest ? await this.#mailbox.drainLeadingQueueOnly(turn) : await this.#mailbox.drain(turn);
1713
+ state.firstRequest = false;
1714
+ return communications.length === 0 ? void 0 : communications.map(
1715
+ (communication) => this.#mailboxInputMessage(communication)
1716
+ );
1717
+ }
1718
+ #engineFor({ chatId, userId }) {
1719
+ return new ContextEngine2({ store: this.#store, chatId, userId });
1720
+ }
1721
+ #mailboxInputMessage(communication) {
1722
+ return {
1723
+ id: crypto.randomUUID(),
1724
+ role: "user",
1725
+ parts: [
1726
+ {
1727
+ type: "text",
1728
+ text: this.#renderInterAgentCommunication(communication)
1729
+ }
1730
+ ],
1731
+ metadata: { interAgentCommunication: communication }
1732
+ };
1733
+ }
1734
+ #renderInterAgentCommunication(communication) {
1735
+ const recipientPath = communication.metadata?.recipientPath;
1736
+ const authorPath = communication.metadata?.authorPath;
1737
+ const taskName = typeof recipientPath === "string" ? recipientPath : communication.recipient.chatId;
1738
+ const sender = typeof authorPath === "string" ? authorPath : communication.author.chatId;
1739
+ return `Message Type: ${communication.type}
1740
+ Task name: ${taskName}
1741
+ Sender: ${sender}
1742
+ Payload:
1743
+ ${communication.content}`;
1744
+ }
1745
+ };
1746
+
1747
+ // packages/experimental/src/zukhruf/runtime/approval-controller.ts
1748
+ import {
1749
+ getToolName,
1750
+ isToolUIPart
1751
+ } from "ai";
1752
+ import {
1753
+ ContextEngine as ContextEngine3,
1754
+ assistant as assistant2
1755
+ } from "@deepagents/context";
1756
+
1757
+ // packages/experimental/src/zukhruf/runtime/approval-job-id.ts
1758
+ import { v5 as uuidv55 } from "uuid";
1759
+ function approvalJobId(conversation, approvalId) {
1760
+ return uuidv55(`approval:${approvalId}`, conversationNamespace(conversation));
1761
+ }
1762
+
1763
+ // packages/experimental/src/zukhruf/runtime/approval-controller.ts
1764
+ var ApprovalController = class _ApprovalController {
1765
+ static #settledToolStates = /* @__PURE__ */ new Set([
1766
+ "output-available",
1767
+ "output-error",
1768
+ "output-denied"
1769
+ ]);
1770
+ #store;
1771
+ #queue;
1772
+ constructor(options) {
1773
+ this.#store = options.store;
1774
+ this.#queue = options.queue;
1775
+ }
1776
+ isPaused(message) {
1777
+ return message?.role === "assistant" && this.#pendingToolPart(message) !== void 0;
1778
+ }
1779
+ approve(conversation, input) {
1780
+ return this.#respond("approve", conversation, input.toolCallId, {
1781
+ approved: true
77
1782
  });
78
- const ai = agent({
79
- name: declaration.name,
80
- model: declaration.model,
81
- sandbox,
82
- context: engine,
83
- tools: declaration.tools
1783
+ }
1784
+ deny(conversation, input) {
1785
+ return this.#respond("deny", conversation, input.toolCallId, {
1786
+ approved: false,
1787
+ reason: input.reason
84
1788
  });
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
1789
  }
97
- async function respondToApproval(conversation, toolCallId, approval) {
98
- const engine = engineFor(conversation);
1790
+ async settleDeniedApprovals(conversation, streamId) {
1791
+ const engine = this.#engineFor(conversation);
99
1792
  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
1793
+ if (head?.role !== "assistant" || head.id !== streamId) return;
1794
+ const hasDenied = head.parts.some(
1795
+ (part) => isToolUIPart(part) && part.state === "approval-responded" && part.approval.approved === false
107
1796
  );
108
- if (!part || !isToolUIPart(part)) {
109
- throw new Error(
110
- `approve: no tool call "${toolCallId}" on the paused turn`
1797
+ if (!hasDenied) return;
1798
+ const updated = {
1799
+ ...head,
1800
+ parts: head.parts.map((part) => {
1801
+ if (!isToolUIPart(part) || part.state !== "approval-responded" || part.approval.approved !== false) {
1802
+ return part;
1803
+ }
1804
+ const settled = {
1805
+ ...part,
1806
+ state: "output-denied",
1807
+ approval: { ...part.approval, approved: false }
1808
+ };
1809
+ return settled;
1810
+ })
1811
+ };
1812
+ await engine.continue(assistant2(updated));
1813
+ }
1814
+ async settleFailedApprovals(conversation, streamId, error) {
1815
+ const engine = this.#engineFor(conversation);
1816
+ const head = (await engine.getMessages()).at(-1);
1817
+ if (head?.role !== "assistant" || head.id !== streamId) return;
1818
+ const hasResponded = head.parts.some(
1819
+ (part) => isToolUIPart(part) && part.state === "approval-responded"
1820
+ );
1821
+ if (!hasResponded) return;
1822
+ const updated = {
1823
+ ...head,
1824
+ parts: head.parts.map((part) => {
1825
+ if (!isToolUIPart(part) || part.state !== "approval-responded") {
1826
+ return part;
1827
+ }
1828
+ if (part.approval.approved === false) {
1829
+ const denied = {
1830
+ ...part,
1831
+ state: "output-denied",
1832
+ approval: { ...part.approval, approved: false }
1833
+ };
1834
+ return denied;
1835
+ }
1836
+ const failed = {
1837
+ ...part,
1838
+ state: "output-error",
1839
+ errorText: error,
1840
+ approval: { ...part.approval, approved: true }
1841
+ };
1842
+ return failed;
1843
+ })
1844
+ };
1845
+ await engine.continue(assistant2(updated));
1846
+ }
1847
+ async reconcileTerminalContinuation(conversation, streamId, status, error) {
1848
+ if (status === "completed") {
1849
+ await this.settleDeniedApprovals(conversation, streamId);
1850
+ } else {
1851
+ await this.settleFailedApprovals(
1852
+ conversation,
1853
+ streamId,
1854
+ error ?? `approval continuation ${status}`
111
1855
  );
112
1856
  }
113
- if (part.state !== "approval-requested") {
114
- return { id: head.id, stream: manager.watch(head.id) };
115
- }
1857
+ await this.#queue.resumeParked(conversation.chatId);
1858
+ }
1859
+ async retryIdempotentContinuation(conversation, streamId, tools) {
1860
+ const head = (await this.#engineFor(conversation).getMessages()).at(-1);
1861
+ if (head?.role !== "assistant" || head.id !== streamId) return false;
1862
+ const approved = head.parts.filter(
1863
+ (part) => isToolUIPart(part) && part.state === "approval-responded" && part.approval.approved === true
1864
+ );
1865
+ const retryable = approved.length > 0 && approved.every((part) => {
1866
+ const tool7 = tools[getToolName(part)];
1867
+ return tool7?.recovery === "idempotent" && typeof tool7.execute === "function";
1868
+ });
1869
+ if (!retryable) return false;
1870
+ await this.#queue.push({
1871
+ kind: "continuation",
1872
+ streamId,
1873
+ chatId: conversation.chatId,
1874
+ userId: conversation.userId,
1875
+ recovery: "idempotent"
1876
+ });
1877
+ return true;
1878
+ }
1879
+ async applyDecision(turn) {
1880
+ const engine = this.#engineFor(turn);
1881
+ const head = (await engine.getMessages()).at(-1);
1882
+ if (head?.role !== "assistant" || head.id !== turn.streamId) return false;
1883
+ const part = this.#findToolPart(head, turn.toolCallId);
1884
+ if (part?.approval?.id !== turn.approvalId) return false;
1885
+ if (part.approval.approved !== void 0) return false;
1886
+ if (part.state !== "approval-requested") return false;
116
1887
  const responded = {
117
1888
  ...part,
118
1889
  state: "approval-responded",
119
- approval: { ...part.approval, ...approval }
1890
+ approval: { ...part.approval, ...turn.decision }
120
1891
  };
121
1892
  const updated = {
122
1893
  ...head,
123
- parts: head.parts.map((p) => p === part ? responded : p)
1894
+ parts: head.parts.map(
1895
+ (candidate) => candidate === part ? responded : candidate
1896
+ )
124
1897
  };
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) };
1898
+ await engine.continue(assistant2(updated));
1899
+ return !this.#hasUnansweredApprovals(updated);
1900
+ }
1901
+ async recoverUnstartedContinuation(turn, streamId) {
1902
+ if (turn.kind === "approval") await this.applyDecision(turn);
1903
+ const head = (await this.#engineFor(turn).getMessages()).at(-1);
1904
+ if (head?.role !== "assistant" || head.id !== streamId || this.#hasUnansweredApprovals(head) || !head.parts.some(
1905
+ (part) => isToolUIPart(part) && part.state === "approval-responded"
1906
+ )) {
1907
+ return false;
130
1908
  }
131
- await queue.push({
1909
+ await this.#queue.push({
132
1910
  kind: "continuation",
1911
+ streamId,
1912
+ chatId: turn.chatId,
1913
+ userId: turn.userId,
1914
+ recovery: "handoff"
1915
+ });
1916
+ return true;
1917
+ }
1918
+ async #respond(operation, conversation, toolCallId, approval) {
1919
+ const head = (await this.#engineFor(conversation).getMessages()).at(-1);
1920
+ if (head?.role !== "assistant") {
1921
+ throw new Error(
1922
+ `ApprovalController.${operation}: no paused turn \u2014 the chain head is not an assistant message`
1923
+ );
1924
+ }
1925
+ const part = this.#findToolPart(head, toolCallId);
1926
+ if (!part) {
1927
+ throw new Error(
1928
+ `ApprovalController.${operation}: no tool call "${toolCallId}" on the paused turn`
1929
+ );
1930
+ }
1931
+ if (!part.approval) {
1932
+ throw new Error(
1933
+ `ApprovalController.${operation}: tool call "${toolCallId}" is not awaiting approval`
1934
+ );
1935
+ }
1936
+ const jobId = approvalJobId(conversation, part.approval.id);
1937
+ if (part.approval.approved !== void 0) {
1938
+ if (part.approval.approved !== approval.approved) {
1939
+ throw new Error(
1940
+ `ApprovalController.${operation}: approval already answered with a different decision`
1941
+ );
1942
+ }
1943
+ return { id: head.id, jobId, status: "already-applied" };
1944
+ }
1945
+ if (part.state !== "approval-requested") {
1946
+ throw new Error(
1947
+ `ApprovalController.${operation}: tool call "${toolCallId}" is not awaiting approval`
1948
+ );
1949
+ }
1950
+ const result = await this.#queue.push({
1951
+ kind: "approval",
133
1952
  streamId: head.id,
134
1953
  chatId: conversation.chatId,
1954
+ userId: conversation.userId,
1955
+ toolCallId,
1956
+ approvalId: part.approval.id,
1957
+ decision: approval
1958
+ });
1959
+ return {
1960
+ id: head.id,
1961
+ jobId,
1962
+ status: result.inserted ? "queued" : "already-queued"
1963
+ };
1964
+ }
1965
+ #pendingToolPart(message) {
1966
+ return message.parts.find(
1967
+ (part) => isToolUIPart(part) && !_ApprovalController.#settledToolStates.has(part.state)
1968
+ );
1969
+ }
1970
+ #hasUnansweredApprovals(message) {
1971
+ return message.parts.some(
1972
+ (part) => isToolUIPart(part) && part.state === "approval-requested"
1973
+ );
1974
+ }
1975
+ #findToolPart(message, toolCallId) {
1976
+ return message.parts.find(
1977
+ (part) => isToolUIPart(part) && part.toolCallId === toolCallId
1978
+ );
1979
+ }
1980
+ #engineFor({ chatId, userId }) {
1981
+ return new ContextEngine3({ store: this.#store, chatId, userId });
1982
+ }
1983
+ };
1984
+
1985
+ // packages/experimental/src/zukhruf/runtime/agent-runtime.ts
1986
+ var AgentObservation = class {
1987
+ engine;
1988
+ #conversation;
1989
+ #store;
1990
+ #streams;
1991
+ constructor(conversation, store, streams) {
1992
+ this.engine = new ContextEngine4({
1993
+ store,
1994
+ chatId: conversation.chatId,
135
1995
  userId: conversation.userId
136
1996
  });
137
- await queue.resumeParked(conversation.chatId);
138
- return { id: head.id, stream: manager.watch(head.id) };
1997
+ this.#conversation = conversation;
1998
+ this.#store = store;
1999
+ this.#streams = streams;
139
2000
  }
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"
2001
+ async resume() {
2002
+ const id = await this.#headStreamId();
2003
+ if (!id) return null;
2004
+ AgentTurnId.assertOwner(this.#conversation, id);
2005
+ const status = await this.#streams.store.getStreamStatus(id);
2006
+ return status ? this.#streams.watch(id) : null;
2007
+ }
2008
+ async cancel(streamId) {
2009
+ const chat2 = await this.#store.getChat(this.#conversation.chatId);
2010
+ if (chat2 && chat2.userId !== this.#conversation.userId) {
2011
+ throw new Error(
2012
+ `chat "${this.#conversation.chatId}" belongs to user "${chat2.userId}", not "${this.#conversation.userId}"`
2013
+ );
2014
+ }
2015
+ const id = streamId ?? await this.#headStreamId();
2016
+ if (!id) return;
2017
+ AgentTurnId.assertOwner(this.#conversation, id);
2018
+ const status = await this.#streams.store.getStreamStatus(id);
2019
+ if (status === "queued" || status === "running") {
2020
+ await this.#streams.cancel(id);
2021
+ }
2022
+ }
2023
+ async #headStreamId() {
2024
+ const head = await this.engine.headMessage();
2025
+ return head?.name === "assistant" ? head.id : void 0;
2026
+ }
2027
+ };
2028
+ var AgentRuntime = class {
2029
+ #store;
2030
+ #queue;
2031
+ #streams;
2032
+ #mailbox;
2033
+ #directory;
2034
+ #controlPlane;
2035
+ #approvals;
2036
+ #executor;
2037
+ constructor(root, options) {
2038
+ const multiAgentV2 = resolveMultiAgentV2HostConfig(options.multiAgentV2);
2039
+ const declarations = new AgentDeclarationRegistry(root);
2040
+ const directory = new AgentDirectory(options.store);
2041
+ const streams = options.streams;
2042
+ const mailbox = new MailboxCoordinator({
2043
+ store: options.mailboxStore,
2044
+ queue: options.queue,
2045
+ streams
2046
+ });
2047
+ const approvals = new ApprovalController({
2048
+ store: options.store,
2049
+ queue: options.queue
2050
+ });
2051
+ const statusProjector = new AgentStatusProjector({
2052
+ store: options.store,
2053
+ streams,
2054
+ queue: options.queue,
2055
+ mailbox,
2056
+ directory,
2057
+ approvals
2058
+ });
2059
+ const historyForker = new AgentHistoryForker(options.store);
2060
+ const controlPlane = new AgentControlPlane({
2061
+ root,
2062
+ streams,
2063
+ queue: options.queue,
2064
+ mailbox,
2065
+ declarations,
2066
+ directory,
2067
+ statusProjector,
2068
+ historyForker
2069
+ });
2070
+ this.#store = options.store;
2071
+ this.#queue = options.queue;
2072
+ this.#streams = streams;
2073
+ this.#mailbox = mailbox;
2074
+ this.#directory = directory;
2075
+ this.#controlPlane = controlPlane;
2076
+ this.#approvals = approvals;
2077
+ this.#executor = new AgentTurnExecutor({
2078
+ store: options.store,
2079
+ streams,
2080
+ controlPlane,
2081
+ mailbox,
2082
+ approvals,
2083
+ multiAgentV2
2084
+ });
2085
+ }
2086
+ async enqueue(conversation, turn) {
2087
+ const streamId = await this.#controlPlane.enqueue(conversation, turn);
2088
+ return { id: streamId, stream: this.#streams.watch(streamId) };
2089
+ }
2090
+ async deliver(communication, mode) {
2091
+ await this.#directory.assertOwnerIfExists(communication.recipient);
2092
+ await this.#mailbox.deliver(communication, mode);
2093
+ }
2094
+ approve(conversation, input) {
2095
+ return this.#approvals.approve(conversation, input);
2096
+ }
2097
+ deny(conversation, input) {
2098
+ return this.#approvals.deny(conversation, input);
2099
+ }
2100
+ observe(conversation) {
2101
+ return new AgentObservation(conversation, this.#store, this.#streams);
2102
+ }
2103
+ work(options) {
2104
+ return this.#queue.consume(this.#executor.execute.bind(this.#executor), {
2105
+ concurrency: options?.concurrency,
2106
+ onOrphaned: this.#onOrphaned.bind(this)
2107
+ });
2108
+ }
2109
+ async #onOrphaned(turn, error) {
2110
+ try {
2111
+ let stream = await this.#streams.store.getStream(turn.streamId);
2112
+ const firstReconciliation = stream?.status === "queued" || stream?.status === "running";
2113
+ if (firstReconciliation) {
2114
+ await this.#streams.store.updateStreamStatus(turn.streamId, "failed", {
2115
+ error
2116
+ });
2117
+ stream = await this.#streams.store.getStream(turn.streamId);
2118
+ }
2119
+ let declaration;
2120
+ if ((turn.kind === "approval" || turn.kind === "continuation" && turn.recovery !== "idempotent") && stream?.status === "failed") {
2121
+ try {
2122
+ ({ declaration } = await this.#controlPlane.resolve(turn));
2123
+ } catch {
2124
+ }
2125
+ }
2126
+ if (declaration !== void 0 && await this.#approvals.retryIdempotentContinuation(
2127
+ turn,
2128
+ turn.streamId,
2129
+ declaration.tools ?? {}
2130
+ )) {
2131
+ return;
2132
+ }
2133
+ if ((turn.kind === "approval" || turn.kind === "continuation") && stream?.status === "completed" && await this.#approvals.recoverUnstartedContinuation(
2134
+ turn,
2135
+ turn.streamId
2136
+ )) {
2137
+ return;
2138
+ }
2139
+ stream = await this.#streams.store.getStream(turn.streamId);
2140
+ if ((turn.kind === "approval" || turn.kind === "continuation") && (stream?.status === "completed" || stream?.status === "failed" || stream?.status === "cancelled")) {
2141
+ await this.#approvals.reconcileTerminalContinuation(
2142
+ turn,
2143
+ turn.streamId,
2144
+ stream.status,
2145
+ stream.error ?? error
145
2146
  );
146
2147
  }
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;
2148
+ const { thread } = await this.#controlPlane.resolve(turn);
2149
+ if (thread.lastTurnId === void 0 || thread.lastTurnId === turn.streamId) {
2150
+ await this.#controlPlane.recordLatestTurnIfCurrent(
2151
+ turn,
2152
+ turn.streamId,
2153
+ thread.lastTurnId
2154
+ );
173
2155
  }
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
- }
2156
+ await this.#controlPlane.projectTerminal(turn, thread);
2157
+ } finally {
2158
+ try {
2159
+ if (turn.kind === "approval" || turn.kind === "continuation") {
2160
+ await this.#queue.resumeParked(turn.chatId);
189
2161
  }
2162
+ } finally {
2163
+ await this.#mailbox.endTurn(turn);
2164
+ }
2165
+ }
2166
+ }
2167
+ };
2168
+
2169
+ // packages/experimental/src/zukhruf/instructions.ts
2170
+ function defineInstructions(...fragments) {
2171
+ return fragments;
2172
+ }
2173
+
2174
+ // packages/experimental/src/zukhruf/mailbox/sqlite.store.ts
2175
+ import { DatabaseSync } from "node:sqlite";
2176
+
2177
+ // packages/experimental/src/zukhruf/mailbox/store.ts
2178
+ var MailboxStore = class {
2179
+ };
2180
+
2181
+ // packages/experimental/src/zukhruf/mailbox/sqlite.store.ts
2182
+ var DDL = `
2183
+ PRAGMA journal_mode = WAL;
2184
+ PRAGMA synchronous = NORMAL;
2185
+
2186
+ CREATE TABLE IF NOT EXISTS zukhruf_mailbox_items (
2187
+ sequence INTEGER PRIMARY KEY AUTOINCREMENT,
2188
+ recipient_chat_id TEXT NOT NULL,
2189
+ recipient_user_id TEXT NOT NULL,
2190
+ communication TEXT NOT NULL
2191
+ );
2192
+
2193
+ CREATE TABLE IF NOT EXISTS zukhruf_mailbox_activity (
2194
+ recipient_chat_id TEXT NOT NULL,
2195
+ recipient_user_id TEXT NOT NULL,
2196
+ turn_id TEXT NOT NULL,
2197
+ PRIMARY KEY (recipient_chat_id, recipient_user_id)
2198
+ );
2199
+
2200
+ CREATE TABLE IF NOT EXISTS zukhruf_mailbox_consumed_terminal_ids (
2201
+ communication_id TEXT PRIMARY KEY
2202
+ );
2203
+
2204
+ CREATE INDEX IF NOT EXISTS zukhruf_mailbox_recipient_sequence
2205
+ ON zukhruf_mailbox_items (
2206
+ recipient_chat_id,
2207
+ recipient_user_id,
2208
+ sequence
2209
+ );
2210
+
2211
+ CREATE UNIQUE INDEX IF NOT EXISTS zukhruf_mailbox_communication_id
2212
+ ON zukhruf_mailbox_items (
2213
+ json_extract(communication, '$.id')
2214
+ );
2215
+ `;
2216
+ var BUSY_TIMEOUT_MS = 5e3;
2217
+ var SqliteMailboxStore = class extends MailboxStore {
2218
+ #database;
2219
+ #closed = false;
2220
+ constructor(path) {
2221
+ super();
2222
+ this.#database = new DatabaseSync(path, { timeout: BUSY_TIMEOUT_MS });
2223
+ this.#database.exec(DDL);
2224
+ }
2225
+ async beginTurn(recipient, turnId) {
2226
+ this.#transaction(() => {
2227
+ this.#database.prepare(
2228
+ `INSERT INTO zukhruf_mailbox_activity (
2229
+ recipient_chat_id,
2230
+ recipient_user_id,
2231
+ turn_id
2232
+ ) VALUES (?, ?, ?)
2233
+ ON CONFLICT (recipient_chat_id, recipient_user_id)
2234
+ DO UPDATE SET turn_id = excluded.turn_id`
2235
+ ).run(recipient.chatId, recipient.userId, turnId);
2236
+ });
2237
+ }
2238
+ async enqueue(communication) {
2239
+ return this.#transaction(() => {
2240
+ const consumedTerminal = communication.type === InterAgentCommunicationType.FinalAnswer && this.#hasConsumedTerminal(communication.id);
2241
+ if (!consumedTerminal) {
2242
+ this.#database.prepare(
2243
+ `INSERT OR IGNORE INTO zukhruf_mailbox_items (
2244
+ recipient_chat_id,
2245
+ recipient_user_id,
2246
+ communication
2247
+ ) VALUES (?, ?, ?)`
2248
+ ).run(
2249
+ communication.recipient.chatId,
2250
+ communication.recipient.userId,
2251
+ JSON.stringify(communication)
2252
+ );
2253
+ }
2254
+ return {
2255
+ recipientActive: this.#isTurnActive(communication.recipient)
190
2256
  };
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
- });
2257
+ });
2258
+ }
2259
+ async endTurn(recipient, turnId) {
2260
+ return this.#transaction(() => {
2261
+ const result = this.#database.prepare(
2262
+ `DELETE FROM zukhruf_mailbox_activity
2263
+ WHERE recipient_chat_id = ?
2264
+ AND recipient_user_id = ?
2265
+ AND turn_id = ?`
2266
+ ).run(recipient.chatId, recipient.userId, turnId);
2267
+ return {
2268
+ hasPending: this.#hasPending(recipient),
2269
+ turnEnded: result.changes > 0
2270
+ };
2271
+ });
2272
+ }
2273
+ async hasPending(recipient) {
2274
+ return this.#hasPending(recipient);
2275
+ }
2276
+ #hasPending(recipient) {
2277
+ const row = this.#database.prepare(
2278
+ `SELECT 1
2279
+ FROM zukhruf_mailbox_items
2280
+ WHERE recipient_chat_id = ?
2281
+ AND recipient_user_id = ?
2282
+ LIMIT 1`
2283
+ ).get(recipient.chatId, recipient.userId);
2284
+ return row !== void 0;
2285
+ }
2286
+ #isTurnActive(recipient) {
2287
+ const row = this.#database.prepare(
2288
+ `SELECT 1
2289
+ FROM zukhruf_mailbox_activity
2290
+ WHERE recipient_chat_id = ?
2291
+ AND recipient_user_id = ?
2292
+ LIMIT 1`
2293
+ ).get(recipient.chatId, recipient.userId);
2294
+ return row !== void 0;
2295
+ }
2296
+ #hasConsumedTerminal(communicationId) {
2297
+ const row = this.#database.prepare(
2298
+ `SELECT 1
2299
+ FROM zukhruf_mailbox_consumed_terminal_ids
2300
+ WHERE communication_id = ?
2301
+ LIMIT 1`
2302
+ ).get(communicationId);
2303
+ return row !== void 0;
2304
+ }
2305
+ async drain(recipient) {
2306
+ return this.#drain(recipient, false);
2307
+ }
2308
+ async drainLeadingQueueOnly(recipient) {
2309
+ return this.#drain(recipient, true);
2310
+ }
2311
+ #drain(recipient, leadingQueueOnly) {
2312
+ return this.#transaction(() => {
2313
+ const rows = this.#database.prepare(
2314
+ `SELECT sequence, communication
2315
+ FROM zukhruf_mailbox_items
2316
+ WHERE recipient_chat_id = ?
2317
+ AND recipient_user_id = ?
2318
+ ORDER BY sequence`
2319
+ ).all(recipient.chatId, recipient.userId);
2320
+ const items = rows.map((row) => ({
2321
+ sequence: row.sequence,
2322
+ communication: JSON.parse(row.communication)
2323
+ }));
2324
+ const firstTrigger = leadingQueueOnly ? items.findIndex(({ communication }) => communication.triggerTurn) : -1;
2325
+ const consumed = firstTrigger === -1 ? items : items.slice(0, firstTrigger);
2326
+ const lastConsumed = consumed.at(-1);
2327
+ if (lastConsumed) {
2328
+ const tombstone = this.#database.prepare(
2329
+ `INSERT OR IGNORE
2330
+ INTO zukhruf_mailbox_consumed_terminal_ids (communication_id)
2331
+ VALUES (?)`
2332
+ );
2333
+ for (const { communication } of consumed) {
2334
+ if (communication.type === InterAgentCommunicationType.FinalAnswer) {
2335
+ tombstone.run(communication.id);
201
2336
  }
202
2337
  }
203
- });
2338
+ this.#database.prepare(
2339
+ `DELETE FROM zukhruf_mailbox_items
2340
+ WHERE recipient_chat_id = ?
2341
+ AND recipient_user_id = ?
2342
+ AND sequence <= ?`
2343
+ ).run(recipient.chatId, recipient.userId, lastConsumed.sequence);
2344
+ }
2345
+ return consumed.map(({ communication }) => communication);
2346
+ });
2347
+ }
2348
+ #transaction(operation) {
2349
+ this.#database.exec("BEGIN IMMEDIATE");
2350
+ try {
2351
+ const result = operation();
2352
+ this.#database.exec("COMMIT");
2353
+ return result;
2354
+ } catch (error) {
2355
+ try {
2356
+ this.#database.exec("ROLLBACK");
2357
+ } catch {
2358
+ }
2359
+ throw error;
204
2360
  }
205
- };
206
- }
2361
+ }
2362
+ close() {
2363
+ if (this.#closed) return;
2364
+ this.#closed = true;
2365
+ this.#database.close();
2366
+ }
2367
+ [Symbol.dispose]() {
2368
+ this.close();
2369
+ }
2370
+ };
2371
+
2372
+ // packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
2373
+ import { v7 as uuidv7 } from "uuid";
207
2374
 
208
2375
  // packages/experimental/src/zukhruf/queue/turn-queue.ts
209
2376
  var TurnQueue = class {
210
2377
  };
211
2378
 
212
2379
  // packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
213
- import { v7 as uuidv7 } from "uuid";
214
- var PgBossTurnQueue = class extends TurnQueue {
2380
+ var MAX_TIMEOUT_MS = 2147483647;
2381
+ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
215
2382
  #boss;
216
2383
  #queue;
2384
+ #schema;
2385
+ #schemaConfigurationError;
2386
+ #table;
217
2387
  #expireInSeconds;
2388
+ #cancelIntentTtlMs;
218
2389
  #heartbeatSeconds;
219
2390
  #pollingIntervalSeconds;
2391
+ #active = /* @__PURE__ */ new Map();
2392
+ #cancelIntents = /* @__PURE__ */ new Map();
2393
+ #cancelIntentExpiryTimer;
220
2394
  constructor(boss, options = {}) {
221
2395
  super();
222
2396
  this.#boss = boss;
223
2397
  this.#queue = options.queue ?? "zukhruf-turns";
2398
+ const configuredSchema = boss.getDb().config?.schema;
2399
+ const bossSchema = typeof configuredSchema === "string" ? configuredSchema : void 0;
2400
+ this.#schema = options.schema ?? bossSchema ?? "pgboss";
2401
+ if (options.schema === void 0 && bossSchema === void 0) {
2402
+ this.#schemaConfigurationError = "PgBossTurnQueue cannot read the schema from a custom PgBoss database adapter; pass the PgBoss schema in options.schema";
2403
+ } else if (options.schema !== void 0 && bossSchema !== void 0 && options.schema !== bossSchema) {
2404
+ this.#schemaConfigurationError = `PgBossTurnQueue schema "${options.schema}" does not match the PgBoss schema "${bossSchema}"`;
2405
+ }
224
2406
  this.#expireInSeconds = options.expireInSeconds ?? 3600;
2407
+ this.#cancelIntentTtlMs = this.#expireInSeconds * 1e3;
2408
+ if (!Number.isFinite(this.#expireInSeconds) || this.#expireInSeconds <= 0 || !Number.isSafeInteger(this.#cancelIntentTtlMs) || this.#cancelIntentTtlMs > Number.MAX_SAFE_INTEGER - Date.now()) {
2409
+ throw new Error(
2410
+ "PgBossTurnQueue expireInSeconds must be a finite positive duration"
2411
+ );
2412
+ }
225
2413
  this.#heartbeatSeconds = options.heartbeatSeconds ?? 30;
226
2414
  this.#pollingIntervalSeconds = options.pollingIntervalSeconds ?? 1;
227
2415
  }
@@ -232,10 +2420,14 @@ var PgBossTurnQueue = class extends TurnQueue {
232
2420
  return `${this.#queue}-dead`;
233
2421
  }
234
2422
  async initialize() {
2423
+ if (this.#schemaConfigurationError) {
2424
+ throw new Error(this.#schemaConfigurationError);
2425
+ }
235
2426
  if (!await this.#boss.getQueue(this.deadLetterQueue)) {
236
2427
  await this.#boss.createQueue(this.deadLetterQueue);
237
2428
  }
238
- if (!await this.#boss.getQueue(this.#queue)) {
2429
+ let queue = await this.#boss.getQueue(this.#queue);
2430
+ if (!queue) {
239
2431
  await this.#boss.createQueue(this.#queue, {
240
2432
  policy: "key_strict_fifo",
241
2433
  retryLimit: 0,
@@ -244,35 +2436,111 @@ var PgBossTurnQueue = class extends TurnQueue {
244
2436
  deleteAfterSeconds: 0,
245
2437
  deadLetter: this.deadLetterQueue
246
2438
  });
2439
+ queue = await this.#boss.getQueue(this.#queue);
2440
+ }
2441
+ if (!queue) throw new Error(`Queue "${this.#queue}" was not initialized`);
2442
+ this.#table = queue.table;
2443
+ try {
2444
+ const catalog = await this.#boss.getDb().executeSql(
2445
+ `SELECT table_name AS "table"
2446
+ FROM ${_PgBossTurnQueue.#quoteIdentifier(this.#schema)}."queue"
2447
+ WHERE name = $1`,
2448
+ [this.#queue]
2449
+ );
2450
+ if (catalog.rows.length !== 1 || catalog.rows[0].table !== this.#table) {
2451
+ throw new Error("queue catalog does not match");
2452
+ }
2453
+ await this.#boss.getDb().executeSql(`SELECT 1 FROM ${this.#relation()} WHERE false`);
2454
+ } catch (cause) {
2455
+ throw new Error(
2456
+ `PgBossTurnQueue schema "${this.#schema}" does not match the PgBoss queue; pass the PgBoss schema in options.schema`,
2457
+ { cause }
2458
+ );
247
2459
  }
248
2460
  }
249
2461
  async push(turn) {
250
- await this.#boss.send(this.#queue, turn, {
251
- id: uuidv7(),
2462
+ const jobId = turn.kind === "approval" ? approvalJobId(turn, turn.approvalId) : uuidv7();
2463
+ const inserted = await this.#boss.send(this.#queue, turn, {
2464
+ id: jobId,
252
2465
  singletonKey: turn.chatId,
253
- priority: turn.kind === "continuation" ? 1 : 0
2466
+ group: { id: turn.chatId },
2467
+ priority: turn.kind === "approval" || turn.kind === "continuation" ? 1 : 0
2468
+ });
2469
+ if (inserted === null && turn.kind !== "approval") {
2470
+ throw new Error(`PgBossTurnQueue job id collision: ${jobId}`);
2471
+ }
2472
+ return { jobId, inserted: inserted !== null };
2473
+ }
2474
+ async getTurnActivity(conversation) {
2475
+ const jobs = await this.#boss.findJobs(this.#queue, {
2476
+ key: conversation.chatId
2477
+ });
2478
+ const conversationJobs = jobs.filter(
2479
+ (job) => job.data.userId === conversation.userId && (job.state === "created" || job.state === "retry" || job.state === "active")
2480
+ );
2481
+ if (conversationJobs.some((job) => job.state === "active")) {
2482
+ return "running";
2483
+ }
2484
+ return conversationJobs.length > 0 ? "queued" : "idle";
2485
+ }
2486
+ async getCurrentTurn(conversation) {
2487
+ const jobs = await this.#boss.findJobs(this.#queue, {
2488
+ key: conversation.chatId
2489
+ });
2490
+ return jobs.filter(
2491
+ (job) => job.data.userId === conversation.userId && (job.state === "active" || job.state === "created" || job.state === "retry")
2492
+ ).sort(_PgBossTurnQueue.#interruptOrder)[0]?.data;
2493
+ }
2494
+ async cancel(streamId) {
2495
+ this.#rememberCancelIntent(streamId);
2496
+ this.#abortLocal(streamId);
2497
+ const jobs = await this.#boss.findJobs(this.#queue, {
2498
+ data: { streamId }
2499
+ });
2500
+ const queued = jobs.filter((job) => job.state === "created" || job.state === "retry").map((job) => job.id);
2501
+ if (queued.length > 0) await this.#deleteIfStillQueued(queued);
2502
+ this.#abortLocal(streamId);
2503
+ const remaining = await this.#boss.findJobs(this.#queue, {
2504
+ data: { streamId }
254
2505
  });
2506
+ if (!remaining.some((job) => job.state === "active")) {
2507
+ this.#forgetCancelIntent(streamId);
2508
+ }
255
2509
  }
256
2510
  async consume(handler, options) {
257
2511
  const turnWorkerId = await this.#boss.work(
258
2512
  this.#queue,
259
2513
  {
260
2514
  localConcurrency: options.concurrency ?? 1,
2515
+ groupConcurrency: 1,
261
2516
  pollingIntervalSeconds: this.#pollingIntervalSeconds
262
2517
  },
263
2518
  async ([job]) => {
264
2519
  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);
2520
+ const localAbort = new AbortController();
2521
+ const active = this.#active.get(job.data.streamId) ?? /* @__PURE__ */ new Set();
2522
+ active.add(localAbort);
2523
+ this.#active.set(job.data.streamId, active);
2524
+ if (this.#hasCancelIntent(job.data.streamId)) localAbort.abort();
2525
+ try {
2526
+ await handler(job.data, {
2527
+ signal: AbortSignal.any([job.signal, localAbort.signal]),
2528
+ // Parking = self-cancel: a cancelled job stops blocking the chat's
2529
+ // key and is revived (original created_on, so original order) by
2530
+ // resumeParked(). The worker's completion of a cancelled job is a
2531
+ // clean no-op (probe-verified).
2532
+ park: async () => {
2533
+ parked = true;
2534
+ await this.#boss.cancel(this.#queue, job.id);
2535
+ }
2536
+ });
2537
+ } finally {
2538
+ active.delete(localAbort);
2539
+ if (active.size === 0) {
2540
+ this.#active.delete(job.data.streamId);
2541
+ this.#forgetCancelIntent(job.data.streamId);
274
2542
  }
275
- });
2543
+ }
276
2544
  if (!parked) {
277
2545
  await this.#boss.deleteJob(this.#queue, job.id);
278
2546
  }
@@ -285,9 +2553,15 @@ var PgBossTurnQueue = class extends TurnQueue {
285
2553
  pollingIntervalSeconds: this.#pollingIntervalSeconds
286
2554
  },
287
2555
  async ([job]) => {
288
- await options.onOrphaned(job.data, orphanError(job.output));
289
- if (job.sourceId) {
290
- await this.#boss.deleteJob(this.#queue, job.sourceId);
2556
+ try {
2557
+ await options.onOrphaned(
2558
+ job.data,
2559
+ _PgBossTurnQueue.#orphanError(job.output)
2560
+ );
2561
+ } finally {
2562
+ if (job.sourceId) {
2563
+ await this.#boss.deleteJob(this.#queue, job.sourceId);
2564
+ }
291
2565
  }
292
2566
  }
293
2567
  );
@@ -305,20 +2579,192 @@ var PgBossTurnQueue = class extends TurnQueue {
305
2579
  await this.#boss.resume(this.#queue, parked);
306
2580
  }
307
2581
  }
2582
+ #abortLocal(streamId) {
2583
+ for (const controller of this.#active.get(streamId) ?? []) {
2584
+ controller.abort();
2585
+ }
2586
+ }
2587
+ #rememberCancelIntent(streamId) {
2588
+ this.#pruneCancelIntents();
2589
+ this.#cancelIntents.set(streamId, Date.now() + this.#cancelIntentTtlMs);
2590
+ this.#scheduleCancelIntentExpiry();
2591
+ }
2592
+ #hasCancelIntent(streamId) {
2593
+ this.#pruneCancelIntents();
2594
+ return this.#cancelIntents.has(streamId);
2595
+ }
2596
+ #pruneCancelIntents() {
2597
+ const now = Date.now();
2598
+ for (const [streamId, expiresAt] of this.#cancelIntents) {
2599
+ if (expiresAt <= now) this.#cancelIntents.delete(streamId);
2600
+ }
2601
+ this.#scheduleCancelIntentExpiry();
2602
+ }
2603
+ #forgetCancelIntent(streamId) {
2604
+ this.#cancelIntents.delete(streamId);
2605
+ this.#scheduleCancelIntentExpiry();
2606
+ }
2607
+ #scheduleCancelIntentExpiry() {
2608
+ if (this.#cancelIntentExpiryTimer !== void 0) {
2609
+ globalThis.clearTimeout(this.#cancelIntentExpiryTimer);
2610
+ this.#cancelIntentExpiryTimer = void 0;
2611
+ }
2612
+ let nextExpiry = Number.POSITIVE_INFINITY;
2613
+ for (const expiresAt of this.#cancelIntents.values()) {
2614
+ nextExpiry = Math.min(nextExpiry, expiresAt);
2615
+ }
2616
+ if (!Number.isFinite(nextExpiry)) return;
2617
+ const timer = globalThis.setTimeout(
2618
+ () => {
2619
+ if (this.#cancelIntentExpiryTimer !== timer) return;
2620
+ this.#cancelIntentExpiryTimer = void 0;
2621
+ this.#pruneCancelIntents();
2622
+ },
2623
+ Math.min(MAX_TIMEOUT_MS, Math.max(1, nextExpiry - Date.now()))
2624
+ );
2625
+ this.#cancelIntentExpiryTimer = timer;
2626
+ timer.unref?.();
2627
+ }
2628
+ async #deleteIfStillQueued(ids) {
2629
+ if (!this.#table) {
2630
+ throw new Error("PgBossTurnQueue.initialize() must run before cancel()");
2631
+ }
2632
+ await this.#boss.getDb().executeSql(
2633
+ `DELETE FROM ${this.#relation()}
2634
+ WHERE name = $1
2635
+ AND id = ANY($2::uuid[])
2636
+ AND state IN ('created', 'retry')`,
2637
+ [this.#queue, ids]
2638
+ );
2639
+ }
2640
+ #relation() {
2641
+ if (!this.#table) {
2642
+ throw new Error(
2643
+ "PgBossTurnQueue.initialize() must resolve its job table"
2644
+ );
2645
+ }
2646
+ return `${_PgBossTurnQueue.#quoteIdentifier(this.#schema)}.${_PgBossTurnQueue.#quoteIdentifier(this.#table)}`;
2647
+ }
2648
+ static #quoteIdentifier(identifier) {
2649
+ return `"${identifier.replaceAll('"', '""')}"`;
2650
+ }
2651
+ static #orphanError(output) {
2652
+ if (output && "message" in output && typeof output.message === "string") {
2653
+ return output.message;
2654
+ }
2655
+ return output ? JSON.stringify(output) : "turn orphaned";
2656
+ }
2657
+ static #interruptOrder(left, right) {
2658
+ if (left.state === "active" && right.state !== "active") return -1;
2659
+ if (left.state !== "active" && right.state === "active") return 1;
2660
+ if (left.priority !== right.priority) return right.priority - left.priority;
2661
+ const created = left.createdOn.getTime() - right.createdOn.getTime();
2662
+ return created || left.id.localeCompare(right.id);
2663
+ }
308
2664
  };
309
- function orphanError(output) {
310
- if (output && "message" in output && typeof output.message === "string") {
311
- return output.message;
2665
+
2666
+ // packages/experimental/src/zukhruf/render-turn.ts
2667
+ import { styleText } from "node:util";
2668
+ var dim = (text) => styleText("dim", text);
2669
+ var red = (text) => styleText("red", text);
2670
+ function oneLine(value, max = 88) {
2671
+ const text = String(value ?? "").replaceAll(/\s+/g, " ").trim();
2672
+ return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
2673
+ }
2674
+ function describeToolCall(toolName, input) {
2675
+ const args = input ?? {};
2676
+ switch (toolName) {
2677
+ case "spawn_agent":
2678
+ return `\u21C4 spawn ${args.agent_type} "${args.task_name}" \u2014 ${args.message}`;
2679
+ case "send_message":
2680
+ return `\u21C4 mail ${args.target} \u2014 ${args.message}`;
2681
+ case "followup_task":
2682
+ return `\u21C4 follow-up ${args.target} \u2014 ${args.message}`;
2683
+ case "list_agents":
2684
+ return "\u21C4 list agents";
2685
+ default:
2686
+ return `\xB7 ${toolName}`;
2687
+ }
2688
+ }
2689
+ async function renderTurn(stream) {
2690
+ const toolNames = /* @__PURE__ */ new Map();
2691
+ let midText = false;
2692
+ let thinkingShown = false;
2693
+ const breakText = () => {
2694
+ if (midText) process.stdout.write("\n");
2695
+ midText = false;
2696
+ };
2697
+ for await (const chunk of stream) {
2698
+ switch (chunk.type) {
2699
+ case "reasoning-start":
2700
+ if (!thinkingShown) {
2701
+ console.log(dim("\u2026"));
2702
+ thinkingShown = true;
2703
+ }
2704
+ break;
2705
+ case "text-delta":
2706
+ process.stdout.write(chunk.delta);
2707
+ midText = true;
2708
+ break;
2709
+ case "text-end":
2710
+ breakText();
2711
+ break;
2712
+ case "tool-input-available":
2713
+ toolNames.set(chunk.toolCallId, chunk.toolName);
2714
+ breakText();
2715
+ console.log(dim(describeToolCall(chunk.toolName, chunk.input)));
2716
+ break;
2717
+ case "tool-output-error":
2718
+ breakText();
2719
+ console.log(
2720
+ red(
2721
+ `\u2717 ${toolNames.get(chunk.toolCallId) ?? "tool"}: ${oneLine(chunk.errorText)}`
2722
+ )
2723
+ );
2724
+ break;
2725
+ case "error":
2726
+ breakText();
2727
+ console.log(red(`\u2717 ${oneLine(chunk.errorText)}`));
2728
+ break;
2729
+ case "abort":
2730
+ breakText();
2731
+ console.log(dim("\xB7 turn aborted"));
2732
+ break;
2733
+ }
312
2734
  }
313
- return output ? JSON.stringify(output) : "turn orphaned";
2735
+ breakText();
2736
+ }
2737
+
2738
+ // packages/experimental/src/zukhruf/sandbox/define.ts
2739
+ import {
2740
+ createBashTool
2741
+ } from "@deepagents/context";
2742
+ function defineSandbox(createBackend, options) {
2743
+ return async (context) => createBashTool({ sandbox: await createBackend(context), ...options });
2744
+ }
2745
+
2746
+ // packages/experimental/src/zukhruf/tool.ts
2747
+ import { tool as tool6 } from "ai";
2748
+ function defineTool(definition) {
2749
+ return tool6(definition);
314
2750
  }
315
2751
  export {
2752
+ AgentObservation,
2753
+ AgentPath,
2754
+ AgentRuntime,
2755
+ AgentThread,
2756
+ InterAgentCommunicationType,
2757
+ MailboxStore,
2758
+ MessageDeliveryMode,
316
2759
  PgBossTurnQueue,
2760
+ SqliteMailboxStore,
317
2761
  TurnQueue,
318
- createRuntime,
2762
+ assertCommunication,
2763
+ createInterAgentCommunication,
319
2764
  defineAgent,
320
2765
  defineInstructions,
321
2766
  defineSandbox,
322
- tool as defineTool
2767
+ defineTool,
2768
+ renderTurn
323
2769
  };
324
2770
  //# sourceMappingURL=index.js.map