@deepagents/experimental 5.0.0 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +30 -11
  2. package/dist/index.js +1453 -459
  3. package/dist/index.js.map +4 -4
  4. package/dist/zukhruf/agent.d.ts +9 -4
  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/{list-agents.d.ts → collaboration/list-agents.d.ts} +1 -1
  13. package/dist/zukhruf/collaboration/list-agents.d.ts.map +1 -0
  14. package/dist/zukhruf/{message-tools.d.ts → collaboration/message-tools.d.ts} +84 -88
  15. package/dist/zukhruf/collaboration/message-tools.d.ts.map +1 -0
  16. package/dist/zukhruf/{spawn-agent.d.ts → collaboration/spawn-agent.d.ts} +55 -43
  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/{agent-control-plane.d.ts → control-plane/agent-control-plane.d.ts} +17 -5
  21. package/dist/zukhruf/control-plane/agent-control-plane.d.ts.map +1 -0
  22. package/dist/zukhruf/{agent-declaration-registry.d.ts → control-plane/agent-declaration-registry.d.ts} +1 -1
  23. package/dist/zukhruf/control-plane/agent-declaration-registry.d.ts.map +1 -0
  24. package/dist/zukhruf/{agent-directory.d.ts → control-plane/agent-directory.d.ts} +2 -1
  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.map +1 -0
  29. package/dist/zukhruf/control-plane/agent-status-projector.d.ts +50 -0
  30. package/dist/zukhruf/control-plane/agent-status-projector.d.ts.map +1 -0
  31. package/dist/zukhruf/{agent-thread.d.ts → control-plane/agent-thread.d.ts} +1 -1
  32. package/dist/zukhruf/control-plane/agent-thread.d.ts.map +1 -0
  33. package/dist/zukhruf/{agent-turn-id.d.ts → control-plane/agent-turn-id.d.ts} +2 -1
  34. package/dist/zukhruf/control-plane/agent-turn-id.d.ts.map +1 -0
  35. package/dist/zukhruf/control-plane/fork-turns.d.ts +4 -0
  36. package/dist/zukhruf/control-plane/fork-turns.d.ts.map +1 -0
  37. package/dist/zukhruf/index.d.ts +6 -6
  38. package/dist/zukhruf/index.d.ts.map +1 -1
  39. package/dist/zukhruf/index.js +1453 -459
  40. package/dist/zukhruf/index.js.map +4 -4
  41. package/dist/zukhruf/mailbox/coordinator.d.ts +4 -0
  42. package/dist/zukhruf/mailbox/coordinator.d.ts.map +1 -1
  43. package/dist/zukhruf/multi-agent-v2-config.d.ts +32 -0
  44. package/dist/zukhruf/multi-agent-v2-config.d.ts.map +1 -0
  45. package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts +16 -4
  46. package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts.map +1 -1
  47. package/dist/zukhruf/queue/turn-queue.d.ts +35 -6
  48. package/dist/zukhruf/queue/turn-queue.d.ts.map +1 -1
  49. package/dist/zukhruf/render-turn.d.ts +9 -0
  50. package/dist/zukhruf/render-turn.d.ts.map +1 -0
  51. package/dist/zukhruf/{agent-runtime.d.ts → runtime/agent-runtime.d.ts} +24 -13
  52. package/dist/zukhruf/runtime/agent-runtime.d.ts.map +1 -0
  53. package/dist/zukhruf/runtime/agent-skills.d.ts +9 -0
  54. package/dist/zukhruf/runtime/agent-skills.d.ts.map +1 -0
  55. package/dist/zukhruf/{agent-turn-executor.d.ts → runtime/agent-turn-executor.d.ts} +5 -3
  56. package/dist/zukhruf/runtime/agent-turn-executor.d.ts.map +1 -0
  57. package/dist/zukhruf/{approval-controller.d.ts → runtime/approval-controller.d.ts} +19 -8
  58. package/dist/zukhruf/runtime/approval-controller.d.ts.map +1 -0
  59. package/dist/zukhruf/runtime/approval-job-id.d.ts +3 -0
  60. package/dist/zukhruf/runtime/approval-job-id.d.ts.map +1 -0
  61. package/dist/zukhruf/sandbox/define.d.ts +4 -3
  62. package/dist/zukhruf/sandbox/define.d.ts.map +1 -1
  63. package/dist/zukhruf/tool.d.ts +18 -6
  64. package/dist/zukhruf/tool.d.ts.map +1 -1
  65. package/package.json +9 -9
  66. package/dist/zukhruf/agent-control-plane.d.ts.map +0 -1
  67. package/dist/zukhruf/agent-declaration-registry.d.ts.map +0 -1
  68. package/dist/zukhruf/agent-directory.d.ts.map +0 -1
  69. package/dist/zukhruf/agent-path.d.ts.map +0 -1
  70. package/dist/zukhruf/agent-runtime.d.ts.map +0 -1
  71. package/dist/zukhruf/agent-status-projector.d.ts +0 -32
  72. package/dist/zukhruf/agent-status-projector.d.ts.map +0 -1
  73. package/dist/zukhruf/agent-thread.d.ts.map +0 -1
  74. package/dist/zukhruf/agent-tool-context.d.ts +0 -6
  75. package/dist/zukhruf/agent-tool-context.d.ts.map +0 -1
  76. package/dist/zukhruf/agent-turn-executor.d.ts.map +0 -1
  77. package/dist/zukhruf/agent-turn-id.d.ts.map +0 -1
  78. package/dist/zukhruf/approval-controller.d.ts.map +0 -1
  79. package/dist/zukhruf/approval-mutex.d.ts +0 -5
  80. package/dist/zukhruf/approval-mutex.d.ts.map +0 -1
  81. package/dist/zukhruf/list-agents.d.ts.map +0 -1
  82. package/dist/zukhruf/message-tools.d.ts.map +0 -1
  83. package/dist/zukhruf/spawn-agent.d.ts.map +0 -1
  84. package/dist/zukhruf/sqlite-approval-mutex.d.ts +0 -17
  85. package/dist/zukhruf/sqlite-approval-mutex.d.ts.map +0 -1
  86. /package/dist/zukhruf/{agent-path.d.ts → control-plane/agent-path.d.ts} +0 -0
package/dist/index.js CHANGED
@@ -324,12 +324,10 @@ __export(zukhruf_exports, {
324
324
  AgentPath: () => AgentPath,
325
325
  AgentRuntime: () => AgentRuntime,
326
326
  AgentThread: () => AgentThread,
327
- ApprovalMutex: () => ApprovalMutex,
328
327
  InterAgentCommunicationType: () => InterAgentCommunicationType,
329
328
  MailboxStore: () => MailboxStore,
330
329
  MessageDeliveryMode: () => MessageDeliveryMode,
331
330
  PgBossTurnQueue: () => PgBossTurnQueue,
332
- SqliteApprovalMutex: () => SqliteApprovalMutex,
333
331
  SqliteMailboxStore: () => SqliteMailboxStore,
334
332
  TurnQueue: () => TurnQueue,
335
333
  assertCommunication: () => assertCommunication,
@@ -337,10 +335,24 @@ __export(zukhruf_exports, {
337
335
  defineAgent: () => defineAgent,
338
336
  defineInstructions: () => defineInstructions,
339
337
  defineSandbox: () => defineSandbox,
340
- defineTool: () => tool4
338
+ defineTool: () => defineTool,
339
+ renderTurn: () => renderTurn
341
340
  });
342
341
 
343
- // packages/experimental/src/zukhruf/agent-path.ts
342
+ // packages/experimental/src/zukhruf/agent.ts
343
+ function defineAgent(declaration) {
344
+ return {
345
+ name: declaration.name,
346
+ model: declaration.model,
347
+ sandbox: declaration.sandbox,
348
+ instructions: declaration.instructions,
349
+ tools: declaration.tools ?? {},
350
+ subagents: declaration.subagents ?? [],
351
+ telemetry: declaration.telemetry
352
+ };
353
+ }
354
+
355
+ // packages/experimental/src/zukhruf/control-plane/agent-path.ts
344
356
  var AgentPath = class _AgentPath {
345
357
  #value;
346
358
  constructor(value) {
@@ -350,17 +362,17 @@ var AgentPath = class _AgentPath {
350
362
  return new _AgentPath("/root");
351
363
  }
352
364
  static parse(value) {
353
- const path = value.trim();
354
- if (path !== "/root" && !path.startsWith("/root/")) {
365
+ const path2 = value.trim();
366
+ if (path2 !== "/root" && !path2.startsWith("/root/")) {
355
367
  throw new Error(`agent path "${value}" must start at /root`);
356
368
  }
357
- const segments = path.slice(1).split("/");
369
+ const segments = path2.slice(1).split("/");
358
370
  if (segments.some(
359
371
  (segment) => segment.length === 0 || segment !== segment.trim() || segment === "." || segment === ".."
360
372
  )) {
361
373
  throw new Error(`agent path "${value}" contains an invalid segment`);
362
374
  }
363
- return new _AgentPath(path);
375
+ return new _AgentPath(path2);
364
376
  }
365
377
  /** Relative targets name descendants; absolute targets keep their canonical path. */
366
378
  resolve(target) {
@@ -388,7 +400,7 @@ var AgentPath = class _AgentPath {
388
400
  }
389
401
  };
390
402
 
391
- // packages/experimental/src/zukhruf/agent-thread.ts
403
+ // packages/experimental/src/zukhruf/control-plane/agent-thread.ts
392
404
  var AgentThread = class _AgentThread {
393
405
  conversation;
394
406
  treeId;
@@ -428,17 +440,17 @@ var AgentThread = class _AgentThread {
428
440
  if (typeof treeId !== "string" || !_AgentThread.#isRecord(zukhruf)) {
429
441
  return void 0;
430
442
  }
431
- const { path, parentChatId, declarationName, lastTurnId } = zukhruf;
432
- if (typeof path !== "string" || parentChatId !== null && typeof parentChatId !== "string" || typeof declarationName !== "string" || lastTurnId !== void 0 && typeof lastTurnId !== "string") {
443
+ const { path: path2, parentChatId, declarationName, lastTurnId } = zukhruf;
444
+ if (typeof path2 !== "string" || parentChatId !== null && typeof parentChatId !== "string" || typeof declarationName !== "string" || lastTurnId !== void 0 && typeof lastTurnId !== "string") {
433
445
  return void 0;
434
446
  }
435
447
  let parsedPath;
436
448
  try {
437
- parsedPath = AgentPath.parse(path);
449
+ parsedPath = AgentPath.parse(path2);
438
450
  } catch {
439
451
  return void 0;
440
452
  }
441
- if (parsedPath.toString() !== path) return void 0;
453
+ if (parsedPath.toString() !== path2) return void 0;
442
454
  try {
443
455
  return new _AgentThread({
444
456
  conversation,
@@ -498,30 +510,61 @@ var AgentThread = class _AgentThread {
498
510
  }
499
511
  };
500
512
 
501
- // packages/experimental/src/zukhruf/agent.ts
502
- function defineAgent(declaration) {
503
- return {
504
- name: declaration.name,
505
- model: declaration.model,
506
- sandbox: declaration.sandbox,
507
- instructions: declaration.instructions,
508
- tools: declaration.tools ?? {},
509
- subagents: declaration.subagents ?? [],
510
- telemetry: declaration.telemetry
511
- };
512
- }
513
-
514
- // packages/experimental/src/zukhruf/agent-runtime.ts
513
+ // packages/experimental/src/zukhruf/runtime/agent-runtime.ts
515
514
  import {
516
- ContextEngine as ContextEngine4,
517
- PollingChangeSource,
518
- StreamManager
515
+ ContextEngine as ContextEngine4
519
516
  } from "@deepagents/context";
520
517
 
521
- // packages/experimental/src/zukhruf/agent-control-plane.ts
522
- import { v5 as uuidv53 } from "uuid";
518
+ // packages/experimental/src/zukhruf/control-plane/agent-control-plane.ts
519
+ import { v5 as uuidv54 } from "uuid";
520
+
521
+ // packages/experimental/src/zukhruf/mailbox/types.ts
522
+ import { randomUUID } from "node:crypto";
523
+ var MessageDeliveryMode = {
524
+ QueueOnly: "queue-only",
525
+ TriggerTurn: "trigger-turn"
526
+ };
527
+ var InterAgentCommunicationType = {
528
+ Message: "MESSAGE",
529
+ NewTask: "NEW_TASK",
530
+ FinalAnswer: "FINAL_ANSWER"
531
+ };
532
+ function createInterAgentCommunication(communication) {
533
+ const value = {
534
+ ...communication,
535
+ id: communication.id ?? randomUUID(),
536
+ type: communication.type ?? InterAgentCommunicationType.Message,
537
+ otherRecipients: communication.otherRecipients ?? [],
538
+ triggerTurn: false
539
+ };
540
+ assertCommunication(value);
541
+ return value;
542
+ }
543
+ function assertCommunication(communication) {
544
+ if (!communication.id.trim()) {
545
+ throw new Error("inter-agent communication id cannot be empty");
546
+ }
547
+ if (!Object.values(InterAgentCommunicationType).includes(communication.type)) {
548
+ throw new Error("inter-agent communication type is invalid");
549
+ }
550
+ assertConversationId(communication.author, "author");
551
+ assertConversationId(communication.recipient, "recipient");
552
+ for (const recipient of communication.otherRecipients) {
553
+ assertConversationId(recipient, "other recipient");
554
+ }
555
+ if (!communication.content.trim()) {
556
+ throw new Error("inter-agent communication content cannot be empty");
557
+ }
558
+ }
559
+ function assertConversationId(value, label) {
560
+ if (!value.chatId.trim() || !value.userId.trim()) {
561
+ throw new Error(
562
+ `inter-agent communication ${label} requires chatId and userId`
563
+ );
564
+ }
565
+ }
523
566
 
524
- // packages/experimental/src/zukhruf/agent-declaration-registry.ts
567
+ // packages/experimental/src/zukhruf/control-plane/agent-declaration-registry.ts
525
568
  var AgentDeclarationRegistry = class {
526
569
  root;
527
570
  #declarations = /* @__PURE__ */ new Map();
@@ -556,7 +599,7 @@ var AgentDeclarationRegistry = class {
556
599
  }
557
600
  };
558
601
 
559
- // packages/experimental/src/zukhruf/agent-directory.ts
602
+ // packages/experimental/src/zukhruf/control-plane/agent-directory.ts
560
603
  import { v5 as uuidv5 } from "uuid";
561
604
  var AgentDirectory = class _AgentDirectory {
562
605
  #store;
@@ -628,16 +671,20 @@ var AgentDirectory = class _AgentDirectory {
628
671
  );
629
672
  }
630
673
  async resolve(thread, target) {
631
- const path = thread.path.resolve(target);
632
- const match = (await this.listTree(thread)).find(
633
- (candidate) => candidate.path.equals(path)
634
- );
674
+ const path2 = thread.path.resolve(target);
675
+ const match = await this.find(thread, target);
635
676
  if (match) return match;
636
- throw new Error(`agent path "${path}" does not exist in this tree`);
677
+ throw new Error(`agent path "${path2}" does not exist in this tree`);
678
+ }
679
+ async find(thread, target) {
680
+ const path2 = thread.path.resolve(target);
681
+ return (await this.listTree(thread)).find(
682
+ (candidate) => candidate.path.equals(path2)
683
+ );
637
684
  }
638
685
  async createChild(options) {
639
- const path = options.parent.path.resolve(options.taskName);
640
- const pathString = path.toString();
686
+ const path2 = options.parent.path.resolve(options.taskName);
687
+ const pathString = path2.toString();
641
688
  const conversation = {
642
689
  chatId: _AgentDirectory.#childChatId(
643
690
  options.parent.conversation.userId,
@@ -647,7 +694,7 @@ var AgentDirectory = class _AgentDirectory {
647
694
  userId: options.parent.conversation.userId
648
695
  };
649
696
  const occupied = (await this.listTree(options.parent)).find(
650
- (thread) => thread.path.equals(path)
697
+ (thread) => thread.path.equals(path2)
651
698
  );
652
699
  if (occupied && occupied.conversation.chatId !== conversation.chatId) {
653
700
  throw new Error(`agent path "${pathString}" already exists`);
@@ -655,7 +702,7 @@ var AgentDirectory = class _AgentDirectory {
655
702
  const child = new AgentThread({
656
703
  conversation,
657
704
  treeId: options.parent.treeId,
658
- path,
705
+ path: path2,
659
706
  parentChatId: options.parent.conversation.chatId,
660
707
  declarationName: options.declarationName
661
708
  });
@@ -673,9 +720,9 @@ var AgentDirectory = class _AgentDirectory {
673
720
  }
674
721
  return stored;
675
722
  }
676
- static #childChatId(userId, treeId, path) {
723
+ static #childChatId(userId, treeId, path2) {
677
724
  return uuidv5(
678
- `urn:deepagents:zukhruf:agent:${JSON.stringify([userId, treeId, path])}`,
725
+ `urn:deepagents:zukhruf:agent:${JSON.stringify([userId, treeId, path2])}`,
679
726
  uuidv5.URL
680
727
  );
681
728
  }
@@ -744,59 +791,330 @@ var AgentDirectory = class _AgentDirectory {
744
791
  }
745
792
  };
746
793
 
747
- // packages/experimental/src/zukhruf/agent-status-projector.ts
748
- import { isTextUIPart } from "ai";
794
+ // packages/experimental/src/zukhruf/control-plane/agent-history-forker.ts
795
+ import { validateUIMessages } from "ai";
796
+ import { v5 as uuidv52 } from "uuid";
749
797
  import {
750
- ContextEngine
798
+ isSyntheticReminderMessage
751
799
  } from "@deepagents/context";
752
-
753
- // packages/experimental/src/zukhruf/mailbox/types.ts
754
- import { randomUUID } from "node:crypto";
755
- var MessageDeliveryMode = {
756
- QueueOnly: "queue-only",
757
- TriggerTurn: "trigger-turn"
758
- };
759
- var InterAgentCommunicationType = {
760
- Message: "MESSAGE",
761
- NewTask: "NEW_TASK",
762
- FinalAnswer: "FINAL_ANSWER"
763
- };
764
- function createInterAgentCommunication(communication) {
765
- const value = {
766
- ...communication,
767
- id: communication.id ?? randomUUID(),
768
- type: communication.type ?? InterAgentCommunicationType.Message,
769
- otherRecipients: communication.otherRecipients ?? [],
770
- triggerTurn: false
771
- };
772
- assertCommunication(value);
773
- return value;
774
- }
775
- function assertCommunication(communication) {
776
- if (!communication.id.trim()) {
777
- throw new Error("inter-agent communication id cannot be empty");
800
+ var AgentHistoryForker = class {
801
+ #store;
802
+ constructor(store) {
803
+ this.#store = store;
778
804
  }
779
- if (!Object.values(InterAgentCommunicationType).includes(communication.type)) {
780
- throw new Error("inter-agent communication type is invalid");
805
+ async fork(parent, child, forkTurns) {
806
+ const record = await this.#claim(parent, child, forkTurns);
807
+ if (record.forkTurns === "none" || record.parentHeadMessageId === null) {
808
+ return;
809
+ }
810
+ const selected = await this.#selectedMessages(parent, child, record);
811
+ if (selected.length === 0) return;
812
+ const cloned = this.#cloneMessages(child, selected);
813
+ const expectedIds = cloned.map((message) => message.id);
814
+ const branch = await this.#store.getActiveBranch(child.conversation.chatId);
815
+ if (!branch) {
816
+ throw new Error(
817
+ `spawn_agent: child chat "${child.conversation.chatId}" has no active branch`
818
+ );
819
+ }
820
+ if (branch.headMessageId !== null) {
821
+ if (await this.#hasForkedPrefix(child, expectedIds)) return;
822
+ throw new Error(
823
+ `spawn_agent: cannot apply parent history after child "${child.path}" has started`
824
+ );
825
+ }
826
+ const head = cloned.at(-1);
827
+ if (!head) return;
828
+ await this.#store.addMessages(cloned);
829
+ const committed = await this.#store.updateBranchHead(
830
+ branch.id,
831
+ head.id,
832
+ null
833
+ );
834
+ if (!committed && !await this.#hasForkedPrefix(child, expectedIds)) {
835
+ throw new Error(
836
+ `spawn_agent: child "${child.path}" started before parent history was applied`
837
+ );
838
+ }
839
+ if (!await this.#hasForkedPrefix(child, expectedIds)) {
840
+ throw new Error(
841
+ `spawn_agent: failed to persist parent history for child "${child.path}"`
842
+ );
843
+ }
781
844
  }
782
- assertConversationId(communication.author, "author");
783
- assertConversationId(communication.recipient, "recipient");
784
- for (const recipient of communication.otherRecipients) {
785
- assertConversationId(recipient, "other recipient");
845
+ async #claim(parent, child, forkTurns) {
846
+ const parentBranch = await this.#store.getActiveBranch(
847
+ parent.conversation.chatId
848
+ );
849
+ if (!parentBranch) {
850
+ throw new Error(
851
+ `spawn_agent: parent chat "${parent.conversation.chatId}" has no active branch`
852
+ );
853
+ }
854
+ const proposed = {
855
+ forkTurns,
856
+ parentChatId: parent.conversation.chatId,
857
+ parentHeadMessageId: forkTurns === "none" ? null : parentBranch.headMessageId
858
+ };
859
+ let claimed;
860
+ await this.#store.updateChat(child.conversation.chatId, (chat2) => {
861
+ const metadata = chat2.metadata;
862
+ const zukhruf = metadata?.zukhruf;
863
+ if (!isRecord(zukhruf)) {
864
+ throw new Error(
865
+ `spawn_agent: child chat "${child.conversation.chatId}" is missing Zukhruf metadata`
866
+ );
867
+ }
868
+ if (zukhruf.historyFork !== void 0) {
869
+ claimed = parseHistoryForkRecord(zukhruf.historyFork);
870
+ if (claimed.parentChatId !== proposed.parentChatId || claimed.forkTurns !== proposed.forkTurns) {
871
+ throw new Error(
872
+ `spawn_agent: agent path "${child.path}" already exists with a different fork_turns setting`
873
+ );
874
+ }
875
+ return void 0;
876
+ }
877
+ claimed = proposed;
878
+ return {
879
+ metadata: {
880
+ ...metadata,
881
+ zukhruf: { ...zukhruf, historyFork: proposed }
882
+ }
883
+ };
884
+ });
885
+ if (!claimed) {
886
+ throw new Error(
887
+ `spawn_agent: failed to claim history for child "${child.path}"`
888
+ );
889
+ }
890
+ return claimed;
786
891
  }
787
- if (!communication.content.trim()) {
788
- throw new Error("inter-agent communication content cannot be empty");
892
+ async #sourceMessages(parent, record) {
893
+ const headId = record.parentHeadMessageId;
894
+ if (headId === null) return [];
895
+ const chain = await this.#store.getMessageChain(headId);
896
+ if (chain.at(-1)?.id !== headId) {
897
+ throw new Error(
898
+ `spawn_agent: parent history head "${headId}" is unavailable`
899
+ );
900
+ }
901
+ if (chain.some((message) => message.chatId !== parent.conversation.chatId)) {
902
+ throw new Error("spawn_agent: parent history crosses chat boundaries");
903
+ }
904
+ const materialized = chain.filter(
905
+ (message) => !isEmptyAssistantPlaceholder(message.data)
906
+ );
907
+ const messages = await validateUIMessages({
908
+ messages: materialized.map((message) => message.data)
909
+ });
910
+ return materialized.map((stored, index) => {
911
+ const message = messages[index];
912
+ if (message.id !== stored.id) {
913
+ throw new Error(
914
+ `spawn_agent: stored message "${stored.id}" has a mismatched payload id`
915
+ );
916
+ }
917
+ return { stored, message };
918
+ });
919
+ }
920
+ async #selectedMessages(parent, child, record) {
921
+ if (record.forkTurns === "none") return [];
922
+ if (record.sourceMessageIds !== void 0) {
923
+ return this.#messagesById(parent, record.sourceMessageIds);
924
+ }
925
+ const source = await this.#sourceMessages(parent, record);
926
+ const selected = this.#select(source, record.forkTurns).map((entry) => this.#keepHistoryMessage(entry)).filter((entry) => entry !== void 0);
927
+ const sourceMessageIds = await this.#claimSelection(
928
+ child,
929
+ selected.map(({ stored }) => stored.id)
930
+ );
931
+ return arraysEqual(
932
+ sourceMessageIds,
933
+ selected.map(({ stored }) => stored.id)
934
+ ) ? selected : this.#messagesById(parent, sourceMessageIds);
935
+ }
936
+ async #messagesById(parent, sourceMessageIds) {
937
+ const storedMessages = await Promise.all(
938
+ sourceMessageIds.map((id) => this.#store.getMessage(id))
939
+ );
940
+ if (storedMessages.some(
941
+ (message) => message === void 0 || message.chatId !== parent.conversation.chatId
942
+ )) {
943
+ throw new Error(
944
+ "spawn_agent: persisted parent-history snapshot is unavailable"
945
+ );
946
+ }
947
+ const stored = storedMessages;
948
+ const messages = await validateUIMessages({
949
+ messages: stored.map((message) => message.data)
950
+ });
951
+ return stored.map((messageData, index) => {
952
+ const source = this.#keepHistoryMessage({
953
+ stored: messageData,
954
+ message: messages[index]
955
+ });
956
+ if (!source || source.message.id !== messageData.id) {
957
+ throw new Error(
958
+ `spawn_agent: persisted parent-history message "${messageData.id}" changed shape`
959
+ );
960
+ }
961
+ return source;
962
+ });
963
+ }
964
+ async #claimSelection(child, proposedIds) {
965
+ let sourceMessageIds;
966
+ await this.#store.updateChat(child.conversation.chatId, (chat2) => {
967
+ const metadata = chat2.metadata;
968
+ const zukhruf = metadata?.zukhruf;
969
+ if (!isRecord(zukhruf)) {
970
+ throw new Error(
971
+ `spawn_agent: child chat "${child.conversation.chatId}" is missing Zukhruf metadata`
972
+ );
973
+ }
974
+ const record = parseHistoryForkRecord(zukhruf.historyFork);
975
+ if (record.sourceMessageIds !== void 0) {
976
+ sourceMessageIds = record.sourceMessageIds;
977
+ return void 0;
978
+ }
979
+ sourceMessageIds = proposedIds;
980
+ return {
981
+ metadata: {
982
+ ...metadata,
983
+ zukhruf: {
984
+ ...zukhruf,
985
+ historyFork: { ...record, sourceMessageIds: proposedIds }
986
+ }
987
+ }
988
+ };
989
+ });
990
+ if (!sourceMessageIds) {
991
+ throw new Error(
992
+ `spawn_agent: failed to claim parent-history messages for child "${child.path}"`
993
+ );
994
+ }
995
+ return sourceMessageIds;
789
996
  }
997
+ #select(source, forkTurns) {
998
+ if (forkTurns === "all") return source;
999
+ const boundaries = source.flatMap(
1000
+ (entry, index) => isForkTurnBoundary(entry.message) ? [index] : []
1001
+ );
1002
+ const start = boundaries.at(-forkTurns) ?? boundaries[0];
1003
+ return start === void 0 ? [] : source.slice(start);
1004
+ }
1005
+ #keepHistoryMessage(entry) {
1006
+ const { message } = entry;
1007
+ if (message.role === "user") {
1008
+ if (isSyntheticReminderMessage(message) || interAgentCommunication(message) !== void 0) {
1009
+ return void 0;
1010
+ }
1011
+ return entry;
1012
+ }
1013
+ if (message.role !== "assistant") return void 0;
1014
+ const finalStepStart = message.parts.findLastIndex(
1015
+ (part) => part.type === "step-start"
1016
+ );
1017
+ const parts = message.parts.slice(finalStepStart + 1).filter(
1018
+ (part) => ["text", "file", "source-url", "source-document"].includes(part.type)
1019
+ );
1020
+ return parts.length === 0 ? void 0 : { ...entry, message: { ...message, parts } };
1021
+ }
1022
+ #cloneMessages(child, selected) {
1023
+ let parentId = null;
1024
+ return selected.map(({ stored, message }) => {
1025
+ const id = uuidv52(
1026
+ `urn:deepagents:zukhruf:forked-message:${JSON.stringify([
1027
+ child.conversation.chatId,
1028
+ stored.id
1029
+ ])}`,
1030
+ uuidv52.URL
1031
+ );
1032
+ const clone = {
1033
+ id,
1034
+ chatId: child.conversation.chatId,
1035
+ parentId,
1036
+ name: message.role,
1037
+ type: "message",
1038
+ data: { ...message, id },
1039
+ createdAt: stored.createdAt
1040
+ };
1041
+ parentId = id;
1042
+ return clone;
1043
+ });
1044
+ }
1045
+ async #hasForkedPrefix(child, expectedIds) {
1046
+ const branch = await this.#store.getActiveBranch(child.conversation.chatId);
1047
+ if (!branch?.headMessageId) return false;
1048
+ const chain = await this.#store.getMessageChain(branch.headMessageId);
1049
+ return expectedIds.every(
1050
+ (id, index) => chain[index]?.id === id && chain[index]?.chatId === child.conversation.chatId
1051
+ );
1052
+ }
1053
+ };
1054
+ function isForkTurnBoundary(message) {
1055
+ if (message.role !== "user" || isSyntheticReminderMessage(message)) {
1056
+ return false;
1057
+ }
1058
+ return interAgentCommunication(message)?.triggerTurn ?? true;
790
1059
  }
791
- function assertConversationId(value, label) {
792
- if (!value.chatId.trim() || !value.userId.trim()) {
1060
+ function interAgentCommunication(message) {
1061
+ if (!isRecord(message.metadata)) return void 0;
1062
+ if (!Object.hasOwn(message.metadata, "interAgentCommunication")) {
1063
+ return void 0;
1064
+ }
1065
+ const communication = message.metadata.interAgentCommunication;
1066
+ if (!isRecord(communication) || typeof communication.triggerTurn !== "boolean") {
793
1067
  throw new Error(
794
- `inter-agent communication ${label} requires chatId and userId`
1068
+ `spawn_agent: message "${message.id}" has invalid inter-agent metadata`
795
1069
  );
796
1070
  }
1071
+ return { triggerTurn: communication.triggerTurn };
1072
+ }
1073
+ function parseHistoryForkRecord(value) {
1074
+ if (!isRecord(value)) {
1075
+ throw new Error("spawn_agent: invalid persisted history-fork metadata");
1076
+ }
1077
+ const { forkTurns, parentChatId, parentHeadMessageId, sourceMessageIds } = value;
1078
+ if (!isForkTurns(forkTurns) || typeof parentChatId !== "string" || !parentChatId.trim() || parentHeadMessageId !== null && (typeof parentHeadMessageId !== "string" || parentHeadMessageId.length === 0) || sourceMessageIds !== void 0 && (!Array.isArray(sourceMessageIds) || !sourceMessageIds.every(
1079
+ (id) => typeof id === "string" && id.trim().length > 0
1080
+ ) || new Set(sourceMessageIds).size !== sourceMessageIds.length)) {
1081
+ throw new Error("spawn_agent: invalid persisted history-fork metadata");
1082
+ }
1083
+ return {
1084
+ forkTurns,
1085
+ parentChatId,
1086
+ parentHeadMessageId,
1087
+ ...sourceMessageIds === void 0 ? {} : { sourceMessageIds }
1088
+ };
1089
+ }
1090
+ function isForkTurns(value) {
1091
+ return value === "none" || value === "all" || typeof value === "number" && Number.isSafeInteger(value) && value > 0;
1092
+ }
1093
+ function isRecord(value) {
1094
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1095
+ }
1096
+ function isEmptyAssistantPlaceholder(value) {
1097
+ return isRecord(value) && typeof value.id === "string" && value.role === "assistant" && Array.isArray(value.parts) && value.parts.length === 0;
1098
+ }
1099
+ function arraysEqual(left, right) {
1100
+ return left.length === right.length && left.every((value, index) => value === right[index]);
797
1101
  }
798
1102
 
799
- // packages/experimental/src/zukhruf/agent-status-projector.ts
1103
+ // packages/experimental/src/zukhruf/control-plane/agent-status-projector.ts
1104
+ import { isTextUIPart } from "ai";
1105
+ import { z } from "zod";
1106
+ import {
1107
+ ContextEngine
1108
+ } from "@deepagents/context";
1109
+ var listedAgentStatusSchema = z.union([
1110
+ z.enum(["pending_init", "running", "interrupted", "shutdown", "not_found"]),
1111
+ z.object({ completed: z.string().nullable() }).strict(),
1112
+ z.object({ errored: z.string() }).strict()
1113
+ ]);
1114
+ var listedAgentSchema = z.object({
1115
+ agent_name: z.string(),
1116
+ agent_status: listedAgentStatusSchema
1117
+ }).strict();
800
1118
  var AgentStatusProjector = class _AgentStatusProjector {
801
1119
  #store;
802
1120
  #streams;
@@ -817,22 +1135,22 @@ var AgentStatusProjector = class _AgentStatusProjector {
817
1135
  const head = messages.at(-1);
818
1136
  const streamId = thread.lastTurnId ?? (head?.role === "assistant" ? head.id : void 0);
819
1137
  const stream = streamId ? await this.#streams.store.getStream(streamId) : void 0;
820
- const activity = await this.#queue.getTurnActivity(thread.conversation);
1138
+ const scheduledTurn = await this.#queue.getCurrentTurn(thread.conversation);
1139
+ const scheduledStream = scheduledTurn ? await this.#streams.store.getStream(scheduledTurn.streamId) : void 0;
821
1140
  let status = _AgentStatusProjector.#listedStatus(
822
1141
  stream?.status,
823
1142
  stream?.error,
824
1143
  head
825
1144
  );
826
1145
  if (stream?.status === "completed" && this.#approvals.isPaused(head)) {
827
- status = "waiting_approval";
1146
+ status = "running";
828
1147
  }
829
- if (thread.conversation.chatId === currentTurn.chatId || activity === "running" || activity === "queued" && stream !== void 0) {
1148
+ if (thread.conversation.chatId === currentTurn.chatId || thread.lastTurnId !== void 0 && scheduledTurn?.streamId !== thread.lastTurnId && (scheduledStream?.status === "queued" || scheduledStream?.status === "running")) {
830
1149
  status = "running";
831
1150
  }
832
1151
  return {
833
1152
  agent_name: thread.path.toString(),
834
- agent_status: status,
835
- last_task_message: thread.path.isRoot ? "Main thread" : _AgentStatusProjector.#lastUserMessage(messages)
1153
+ agent_status: status
836
1154
  };
837
1155
  }
838
1156
  async projectTerminal(turn, thread) {
@@ -848,7 +1166,12 @@ var AgentStatusProjector = class _AgentStatusProjector {
848
1166
  return;
849
1167
  }
850
1168
  const text = message?.role === "assistant" ? _AgentStatusProjector.#messageText(message) : "";
851
- const content = stream.status === "failed" ? `Agent failed: ${stream.error || "unknown error"}` : stream.status === "cancelled" ? "Agent was interrupted." : text || "Agent completed without a text response.";
1169
+ let content = text || "Agent completed without a text response.";
1170
+ if (stream.status === "failed") {
1171
+ content = `Agent failed: ${stream.error || "unknown error"}`;
1172
+ } else if (stream.status === "cancelled") {
1173
+ content = "Agent was interrupted.";
1174
+ }
852
1175
  const parent = await this.#directory.load({
853
1176
  chatId: thread.parentChatId,
854
1177
  userId: thread.conversation.userId
@@ -898,22 +1221,13 @@ var AgentStatusProjector = class _AgentStatusProjector {
898
1221
  return "pending_init";
899
1222
  }
900
1223
  }
901
- static #lastUserMessage(messages) {
902
- for (let index = messages.length - 1; index >= 0; index--) {
903
- const message = messages[index];
904
- if (message?.role === "user") {
905
- return _AgentStatusProjector.#messageText(message) || null;
906
- }
907
- }
908
- return null;
909
- }
910
1224
  static #messageText(message) {
911
1225
  return message.parts.filter(isTextUIPart).map((part) => part.text).join("\n").trim();
912
1226
  }
913
1227
  };
914
1228
 
915
- // packages/experimental/src/zukhruf/agent-turn-id.ts
916
- import { v5 as uuidv52 } from "uuid";
1229
+ // packages/experimental/src/zukhruf/control-plane/agent-turn-id.ts
1230
+ import { v5 as uuidv53 } from "uuid";
917
1231
  var AgentTurnId = class _AgentTurnId {
918
1232
  static #prefix = "zukhruf-turn";
919
1233
  #value;
@@ -924,16 +1238,16 @@ var AgentTurnId = class _AgentTurnId {
924
1238
  if (!requestId.trim()) {
925
1239
  throw new Error("turn id cannot be empty");
926
1240
  }
927
- const scope = _AgentTurnId.#scope(conversation);
1241
+ const scope = conversationNamespace(conversation);
928
1242
  return new _AgentTurnId(
929
- `${_AgentTurnId.#prefix}:${scope}:${uuidv52(requestId, scope)}`
1243
+ `${_AgentTurnId.#prefix}:${scope}:${uuidv53(requestId, scope)}`
930
1244
  );
931
1245
  }
932
1246
  static random(conversation) {
933
1247
  return _AgentTurnId.fromRequest(conversation, crypto.randomUUID());
934
1248
  }
935
1249
  static assertOwner(conversation, streamId) {
936
- const expectedPrefix = `${_AgentTurnId.#prefix}:${_AgentTurnId.#scope(conversation)}:`;
1250
+ const expectedPrefix = `${_AgentTurnId.#prefix}:${conversationNamespace(conversation)}:`;
937
1251
  if (!streamId.startsWith(expectedPrefix)) {
938
1252
  throw new Error(
939
1253
  `stream "${streamId}" does not belong to conversation "${conversation.chatId}"`
@@ -943,18 +1257,18 @@ var AgentTurnId = class _AgentTurnId {
943
1257
  toString() {
944
1258
  return this.#value;
945
1259
  }
946
- static #scope(conversation) {
947
- if (!conversation.chatId.trim() || !conversation.userId.trim()) {
948
- throw new Error("conversation requires non-empty chatId and userId");
949
- }
950
- return uuidv52(
951
- JSON.stringify([conversation.userId, conversation.chatId]),
952
- uuidv52.URL
953
- );
954
- }
955
1260
  };
1261
+ function conversationNamespace(conversation) {
1262
+ if (!conversation.chatId.trim() || !conversation.userId.trim()) {
1263
+ throw new Error("conversation requires non-empty chatId and userId");
1264
+ }
1265
+ return uuidv53(
1266
+ JSON.stringify([conversation.userId, conversation.chatId]),
1267
+ uuidv53.URL
1268
+ );
1269
+ }
956
1270
 
957
- // packages/experimental/src/zukhruf/agent-control-plane.ts
1271
+ // packages/experimental/src/zukhruf/control-plane/agent-control-plane.ts
958
1272
  var AgentControlPlane = class _AgentControlPlane {
959
1273
  #root;
960
1274
  #streams;
@@ -963,6 +1277,7 @@ var AgentControlPlane = class _AgentControlPlane {
963
1277
  #declarations;
964
1278
  #directory;
965
1279
  #statusProjector;
1280
+ #historyForker;
966
1281
  constructor(options) {
967
1282
  this.#root = options.root;
968
1283
  this.#streams = options.streams;
@@ -971,6 +1286,7 @@ var AgentControlPlane = class _AgentControlPlane {
971
1286
  this.#declarations = options.declarations;
972
1287
  this.#directory = options.directory;
973
1288
  this.#statusProjector = options.statusProjector;
1289
+ this.#historyForker = options.historyForker;
974
1290
  }
975
1291
  async resolve(conversation) {
976
1292
  const thread = await this.#directory.loadOrCreateRoot(
@@ -1049,11 +1365,12 @@ var AgentControlPlane = class _AgentControlPlane {
1049
1365
  `spawn_agent: agent path "${childPath}" already finished with status "${status}"`
1050
1366
  );
1051
1367
  }
1368
+ await this.#historyForker.fork(actor.thread, child, input.forkTurns);
1052
1369
  await this.enqueue(child.conversation, {
1053
1370
  id: requestId,
1054
1371
  input: input.message
1055
1372
  });
1056
- return { task_name: input.taskName, agent_path: childPath };
1373
+ return { task_name: childPath };
1057
1374
  }
1058
1375
  async sendMessage(actor, input) {
1059
1376
  return this.#deliverAgentMessage(actor, input, {
@@ -1083,6 +1400,38 @@ var AgentControlPlane = class _AgentControlPlane {
1083
1400
  );
1084
1401
  return { agents };
1085
1402
  }
1403
+ async interruptAgent(actor, input) {
1404
+ const target = await this.#directory.find(actor.thread, input.target);
1405
+ if (!target) return { previous_status: "not_found" };
1406
+ if (target.path.isRoot) {
1407
+ throw new Error("interrupt_agent: the root agent cannot be interrupted");
1408
+ }
1409
+ if (target.path.equals(actor.thread.path)) {
1410
+ throw new Error("interrupt_agent: an agent cannot interrupt itself");
1411
+ }
1412
+ const previous = await this.#statusProjector.projectListedAgent(
1413
+ actor.turn,
1414
+ target
1415
+ );
1416
+ const currentTurn = await this.#queue.getCurrentTurn(target.conversation);
1417
+ if (currentTurn) {
1418
+ const interruptedThread = await this.#directory.recordLatestTurnIfCurrent(
1419
+ target.conversation,
1420
+ currentTurn.streamId,
1421
+ target.lastTurnId
1422
+ ) ?? target;
1423
+ await this.#streams.cancel(currentTurn.streamId);
1424
+ await this.#statusProjector.projectTerminal(
1425
+ currentTurn,
1426
+ interruptedThread
1427
+ );
1428
+ await this.#queue.cancel(currentTurn.streamId);
1429
+ }
1430
+ return { previous_status: previous.agent_status };
1431
+ }
1432
+ waitForMailbox(actor, options) {
1433
+ return this.#mailbox.waitForPending(actor.thread.conversation, options);
1434
+ }
1086
1435
  async projectTerminal(turn, thread) {
1087
1436
  await this.#statusProjector.projectTerminal(turn, thread);
1088
1437
  }
@@ -1109,92 +1458,499 @@ var AgentControlPlane = class _AgentControlPlane {
1109
1458
  return { target: target.path.toString() };
1110
1459
  }
1111
1460
  static #initialTurnId(chatId) {
1112
- return uuidv53(`urn:deepagents:zukhruf:initial-turn:${chatId}`, uuidv53.URL);
1461
+ return uuidv54(`urn:deepagents:zukhruf:initial-turn:${chatId}`, uuidv54.URL);
1113
1462
  }
1114
1463
  };
1115
1464
 
1116
- // packages/experimental/src/zukhruf/agent-turn-executor.ts
1117
- import {
1118
- ContextEngine as ContextEngine2,
1119
- agent,
1120
- assistant,
1121
- chat,
1122
- user
1123
- } from "@deepagents/context";
1124
-
1125
- // packages/experimental/src/zukhruf/list-agents.ts
1126
- import { tool } from "ai";
1127
- import { z } from "zod";
1128
- var listAgentsInputSchema = z.object({
1129
- path_prefix: z.string().trim().min(1).describe(
1465
+ // packages/experimental/src/zukhruf/mailbox/coordinator.ts
1466
+ import { setTimeout as delay } from "node:timers/promises";
1467
+ var WAIT_POLL_INTERVAL_MS = 50;
1468
+ var MailboxCoordinator = class {
1469
+ #store;
1470
+ #queue;
1471
+ #streams;
1472
+ #wakeRequests = /* @__PURE__ */ new Map();
1473
+ constructor(options) {
1474
+ this.#store = options.store;
1475
+ this.#queue = options.queue;
1476
+ this.#streams = options.streams;
1477
+ }
1478
+ async deliver(communication, mode) {
1479
+ const delivered = {
1480
+ ...communication,
1481
+ type: mode === MessageDeliveryMode.TriggerTurn ? InterAgentCommunicationType.NewTask : communication.type,
1482
+ triggerTurn: mode === MessageDeliveryMode.TriggerTurn
1483
+ };
1484
+ assertCommunication(delivered);
1485
+ const { recipientActive } = await this.#store.enqueue(delivered);
1486
+ if (delivered.triggerTurn || recipientActive) {
1487
+ await this.#scheduleWake(delivered.recipient);
1488
+ }
1489
+ }
1490
+ beginTurn(turn) {
1491
+ return this.#store.beginTurn(turn, turn.streamId);
1492
+ }
1493
+ async endTurn(turn, options = {}) {
1494
+ const { hasPending, turnEnded } = await this.#store.endTurn(
1495
+ turn,
1496
+ turn.streamId
1497
+ );
1498
+ if (turnEnded && hasPending && !options.parked) {
1499
+ await this.#scheduleWake(turn);
1500
+ }
1501
+ }
1502
+ drainLeadingQueueOnly(recipient) {
1503
+ return this.#store.drainLeadingQueueOnly(recipient);
1504
+ }
1505
+ drain(recipient) {
1506
+ return this.#store.drain(recipient);
1507
+ }
1508
+ async waitForPending(recipient, options) {
1509
+ const deadline = Date.now() + options.timeoutMs;
1510
+ while (true) {
1511
+ options.signal?.throwIfAborted();
1512
+ if (await this.#store.hasPending(recipient)) return true;
1513
+ const remaining = deadline - Date.now();
1514
+ if (remaining <= 0) return false;
1515
+ await delay(Math.min(WAIT_POLL_INTERVAL_MS, remaining), void 0, {
1516
+ signal: options.signal
1517
+ });
1518
+ }
1519
+ }
1520
+ #scheduleWake(target) {
1521
+ const key = this.#conversationKey(target);
1522
+ const existing = this.#wakeRequests.get(key);
1523
+ if (existing) return existing;
1524
+ const request = (async () => {
1525
+ const wakeId = AgentTurnId.random(target).toString();
1526
+ await this.#streams.register(wakeId);
1527
+ try {
1528
+ await this.#queue.push({
1529
+ kind: "mailbox",
1530
+ streamId: wakeId,
1531
+ chatId: target.chatId,
1532
+ userId: target.userId
1533
+ });
1534
+ } catch (error) {
1535
+ await this.#streams.store.updateStreamStatus(wakeId, "failed", {
1536
+ error: error instanceof Error ? error.message : String(error)
1537
+ });
1538
+ throw error;
1539
+ }
1540
+ })();
1541
+ this.#wakeRequests.set(key, request);
1542
+ const clearRequest = () => {
1543
+ if (this.#wakeRequests.get(key) === request) {
1544
+ this.#wakeRequests.delete(key);
1545
+ }
1546
+ };
1547
+ void request.then(clearRequest, clearRequest);
1548
+ return request;
1549
+ }
1550
+ #conversationKey(conversation) {
1551
+ return JSON.stringify([conversation.chatId, conversation.userId]);
1552
+ }
1553
+ };
1554
+
1555
+ // packages/experimental/src/zukhruf/multi-agent-v2-config.ts
1556
+ var DEFAULT_MIN_WAIT_TIMEOUT_MS = 1e4;
1557
+ var DEFAULT_WAIT_TIMEOUT_MS = 3e4;
1558
+ var DEFAULT_MAX_WAIT_TIMEOUT_MS = 36e5;
1559
+ var RESERVED_TOOL_NAMESPACES = /* @__PURE__ */ new Set([
1560
+ "api_tool",
1561
+ "browser",
1562
+ "computer",
1563
+ "container",
1564
+ "file_search",
1565
+ "functions",
1566
+ "image_gen",
1567
+ "multi_tool_use",
1568
+ "python",
1569
+ "python_user_visible",
1570
+ "submodel_delegator",
1571
+ "terminal",
1572
+ "tool_search",
1573
+ "web"
1574
+ ]);
1575
+ function resolveMultiAgentV2HostConfig(input = {}) {
1576
+ const minWaitTimeoutMs = input.minWaitTimeoutMs ?? DEFAULT_MIN_WAIT_TIMEOUT_MS;
1577
+ const defaultWaitTimeoutMs = input.defaultWaitTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
1578
+ const maxWaitTimeoutMs = input.maxWaitTimeoutMs ?? DEFAULT_MAX_WAIT_TIMEOUT_MS;
1579
+ assertTimeout("minWaitTimeoutMs", minWaitTimeoutMs);
1580
+ assertTimeout("defaultWaitTimeoutMs", defaultWaitTimeoutMs);
1581
+ assertTimeout("maxWaitTimeoutMs", maxWaitTimeoutMs);
1582
+ if (minWaitTimeoutMs > maxWaitTimeoutMs) {
1583
+ throw new Error(
1584
+ "AgentRuntime: multiAgentV2.minWaitTimeoutMs must be at most maxWaitTimeoutMs"
1585
+ );
1586
+ }
1587
+ if (defaultWaitTimeoutMs < minWaitTimeoutMs) {
1588
+ throw new Error(
1589
+ "AgentRuntime: multiAgentV2.defaultWaitTimeoutMs must be at least minWaitTimeoutMs"
1590
+ );
1591
+ }
1592
+ if (defaultWaitTimeoutMs > maxWaitTimeoutMs) {
1593
+ throw new Error(
1594
+ "AgentRuntime: multiAgentV2.defaultWaitTimeoutMs must be at most maxWaitTimeoutMs"
1595
+ );
1596
+ }
1597
+ const toolNamespace = input.toolNamespace;
1598
+ if (toolNamespace !== void 0 && (toolNamespace.length === 0 || toolNamespace.trim() !== toolNamespace)) {
1599
+ throw new Error(
1600
+ "AgentRuntime: multiAgentV2.toolNamespace cannot be empty or padded"
1601
+ );
1602
+ }
1603
+ if (toolNamespace !== void 0) validateToolNamespace(toolNamespace);
1604
+ const nonCodeModeOnly = input.nonCodeModeOnly ?? true;
1605
+ if (!nonCodeModeOnly) {
1606
+ throw new Error(
1607
+ "AgentRuntime: multiAgentV2.nonCodeModeOnly=false requires a nested code-mode executor, which Zukhruf does not provide"
1608
+ );
1609
+ }
1610
+ const tool7 = (name) => toolNamespace === void 0 ? name : `${toolNamespace}.${name}`;
1611
+ const collaborationTools = [
1612
+ "spawn_agent",
1613
+ "send_message",
1614
+ "followup_task",
1615
+ "wait_agent",
1616
+ "interrupt_agent",
1617
+ "list_agents"
1618
+ ].map((name) => `\`${tool7(name)}\``).join(", ");
1619
+ const shared = `Call ${collaborationTools} directly. They are intentionally unavailable inside nested code execution.
1620
+
1621
+ All agents share the same workspace, current working directory, and filesystem.`;
1622
+ return {
1623
+ minWaitTimeoutMs,
1624
+ defaultWaitTimeoutMs,
1625
+ maxWaitTimeoutMs,
1626
+ usageHintText: nonEmptyText(input.usageHintText),
1627
+ rootAgentUsageHintText: input.rootAgentUsageHintText === void 0 ? defaultRootUsageHint(tool7, shared) : nonEmptyText(input.rootAgentUsageHintText),
1628
+ subagentUsageHintText: input.subagentUsageHintText === void 0 ? defaultSubagentUsageHint(tool7, shared) : nonEmptyText(input.subagentUsageHintText),
1629
+ toolNamespace,
1630
+ nonCodeModeOnly
1631
+ };
1632
+ }
1633
+ function assertTimeout(name, value) {
1634
+ if (!Number.isSafeInteger(value) || value < 0) {
1635
+ throw new Error(
1636
+ `AgentRuntime: multiAgentV2.${name} must be a non-negative safe integer`
1637
+ );
1638
+ }
1639
+ }
1640
+ function validateToolNamespace(namespace) {
1641
+ if (namespace.length > 64 || !/^[a-zA-Z0-9_-]+$/.test(namespace) || namespace === "mcp" || namespace.startsWith("mcp__") || RESERVED_TOOL_NAMESPACES.has(namespace)) {
1642
+ throw new Error(
1643
+ `AgentRuntime: multiAgentV2.toolNamespace "${namespace}" is a reserved tool namespace or invalid`
1644
+ );
1645
+ }
1646
+ }
1647
+ function nonEmptyText(value) {
1648
+ if (value === void 0) return void 0;
1649
+ return value.length === 0 ? void 0 : value;
1650
+ }
1651
+ function defaultRootUsageHint(tool7, shared) {
1652
+ return `You are \`/root\`, the primary agent in a team of agents collaborating to fulfill the user's goals.
1653
+
1654
+ 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.
1655
+
1656
+ 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.
1657
+
1658
+ Child messages arrive as \`MESSAGE\` or \`FINAL_ANSWER\` mailbox envelopes with their task name, sender, and payload preserved.
1659
+
1660
+ ${shared}`;
1661
+ }
1662
+ function defaultSubagentUsageHint(tool7, shared) {
1663
+ return `You are an agent in a team collaborating to complete a task.
1664
+
1665
+ 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.
1666
+
1667
+ 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.
1668
+
1669
+ ${shared}`;
1670
+ }
1671
+
1672
+ // packages/experimental/src/zukhruf/runtime/agent-turn-executor.ts
1673
+ import {
1674
+ ContextEngine as ContextEngine2,
1675
+ agent,
1676
+ assistant,
1677
+ chat,
1678
+ role,
1679
+ user
1680
+ } from "@deepagents/context";
1681
+
1682
+ // packages/experimental/src/zukhruf/collaboration/interrupt-agent.ts
1683
+ import { tool } from "ai";
1684
+ import { z as z2 } from "zod";
1685
+ var interruptAgentInputSchema = z2.object({
1686
+ target: z2.string().trim().min(1).describe(
1687
+ "The canonical /root/... path, or a descendant-relative target name."
1688
+ )
1689
+ });
1690
+ var interruptAgentOutputSchema = z2.object({ previous_status: listedAgentStatusSchema }).strict();
1691
+ var interruptAgentTool = tool({
1692
+ description: "Interrupt an agent's current turn, if any, and return its previous status. The agent remains available for messages and follow-up tasks.",
1693
+ inputSchema: interruptAgentInputSchema,
1694
+ outputSchema: interruptAgentOutputSchema,
1695
+ execute: async (input, { context }) => context.controlPlane.interruptAgent(context.actor, input)
1696
+ });
1697
+
1698
+ // packages/experimental/src/zukhruf/collaboration/list-agents.ts
1699
+ import { tool as tool2 } from "ai";
1700
+ import { z as z3 } from "zod";
1701
+ var listAgentsInputSchema = z3.object({
1702
+ path_prefix: z3.string().trim().min(1).describe(
1130
1703
  "Task-path prefix without a trailing slash. Omit to list the whole tree."
1131
1704
  ).optional()
1132
1705
  });
1133
- var listAgentsTool = tool({
1706
+ var listAgentsOutputSchema = z3.object({ agents: z3.array(listedAgentSchema) }).strict();
1707
+ var listAgentsTool = tool2({
1134
1708
  description: "List live agents in the current root thread tree. Optionally filter by task-path prefix.",
1135
1709
  inputSchema: listAgentsInputSchema,
1710
+ outputSchema: listAgentsOutputSchema,
1136
1711
  execute: async ({ path_prefix }, { context }) => context.controlPlane.listAgents(context.actor, path_prefix)
1137
1712
  });
1138
1713
 
1139
- // packages/experimental/src/zukhruf/message-tools.ts
1140
- import { tool as tool2 } from "ai";
1141
- import { z as z2 } from "zod";
1142
- var agentMessageInputSchema = z2.object({
1143
- target: z2.string().trim().min(1).describe(
1714
+ // packages/experimental/src/zukhruf/collaboration/message-tools.ts
1715
+ import { tool as tool3 } from "ai";
1716
+ import { z as z4 } from "zod";
1717
+ var agentMessageInputSchema = z4.object({
1718
+ target: z4.string().trim().min(1).describe(
1144
1719
  "The canonical /root/... path, or a descendant-relative target name."
1145
1720
  ),
1146
- message: z2.string().trim().min(1).describe("The message or follow-up task.")
1721
+ message: z4.string().trim().min(1).describe("The message or follow-up task.")
1147
1722
  });
1148
- var sendMessageTool = tool2({
1723
+ var sendMessageTool = tool3({
1149
1724
  description: "Queue a message for another agent. Address siblings with their canonical /root/... path.",
1150
1725
  inputSchema: agentMessageInputSchema,
1151
- execute: async (input, { context }) => context.controlPlane.sendMessage(context.actor, input)
1726
+ execute: async (input, { context }) => {
1727
+ await context.controlPlane.sendMessage(context.actor, input);
1728
+ return "";
1729
+ }
1152
1730
  });
1153
- var followupTaskTool = tool2({
1731
+ var followupTaskTool = tool3({
1154
1732
  description: "Send a follow-up task to an existing non-root agent and wake its thread.",
1155
1733
  inputSchema: agentMessageInputSchema,
1156
- execute: async (input, { context }) => context.controlPlane.followupTask(context.actor, input)
1734
+ execute: async (input, { context }) => {
1735
+ await context.controlPlane.followupTask(context.actor, input);
1736
+ return "";
1737
+ }
1157
1738
  });
1158
1739
 
1159
- // packages/experimental/src/zukhruf/spawn-agent.ts
1160
- import { tool as tool3 } from "ai";
1161
- import { z as z3 } from "zod";
1162
- var spawnAgentInputSchema = z3.object({
1163
- agent_type: z3.string().trim().min(1).describe("The name of one available subagent declaration."),
1164
- task_name: z3.string().trim().min(1).refine(
1740
+ // packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
1741
+ import { tool as tool4 } from "ai";
1742
+ import { z as z5 } from "zod";
1743
+
1744
+ // packages/experimental/src/zukhruf/control-plane/fork-turns.ts
1745
+ var forkTurnsError = "fork_turns must be `none`, `all`, or a positive integer string";
1746
+ function parseForkTurns(value) {
1747
+ const normalized = value.trim().toLowerCase();
1748
+ if (normalized === "none" || normalized === "all") return normalized;
1749
+ if (!/^\d+$/.test(normalized)) return void 0;
1750
+ const turns = Number(normalized);
1751
+ return Number.isSafeInteger(turns) && turns > 0 ? turns : void 0;
1752
+ }
1753
+
1754
+ // packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
1755
+ var spawnAgentInputSchema = z5.object({
1756
+ agent_type: z5.string().trim().min(1).describe("The name of one available subagent declaration."),
1757
+ task_name: z5.string().trim().min(1).refine(
1165
1758
  (value) => value !== "." && value !== ".." && !value.includes("/"),
1166
1759
  "task_name must be one non-empty path segment"
1167
1760
  ).describe("One path segment naming this independent agent task."),
1168
- message: z3.string().refine((value) => value.trim().length > 0, "message cannot be empty").describe("The initial task for the spawned agent.")
1169
- });
1170
- var spawnAgentTool = tool3({
1171
- description: ({ context }) => {
1172
- const available = (context.actor.declaration.subagents ?? []).map((subagent) => subagent.name).join(", ");
1173
- return `Spawn an independent subagent. Available agent types: ${available || "none"}.`;
1174
- },
1175
- inputSchema: spawnAgentInputSchema,
1176
- execute: async ({ agent_type, task_name, message }, { context }) => context.controlPlane.spawn(context.actor, {
1177
- agentType: agent_type,
1178
- taskName: task_name,
1179
- message
1180
- })
1761
+ message: z5.string().refine((value) => value.trim().length > 0, "message cannot be empty").describe("The initial task for the spawned agent."),
1762
+ fork_turns: z5.string().trim().default("all").refine((value) => parseForkTurns(value) !== void 0, forkTurnsError).describe(
1763
+ "Optional number of parent turns to fork. Defaults to `all`. Use `none`, `all`, or a positive integer string such as `3`."
1764
+ )
1181
1765
  });
1766
+ var spawnAgentOutputSchema = z5.object({ task_name: z5.string() }).strict();
1767
+ function createSpawnAgentTool(options) {
1768
+ return tool4({
1769
+ description: ({ context }) => {
1770
+ const available = (context.actor.declaration.subagents ?? []).map((subagent) => subagent.name).join(", ");
1771
+ return [
1772
+ `Spawn an independent subagent. Available agent types: ${available || "none"}.`,
1773
+ options?.usageHintText
1774
+ ].filter(Boolean).join(" ");
1775
+ },
1776
+ inputSchema: spawnAgentInputSchema,
1777
+ outputSchema: spawnAgentOutputSchema,
1778
+ execute: async ({ agent_type, task_name, message, fork_turns }, { context }) => {
1779
+ const forkTurns = parseForkTurns(fork_turns);
1780
+ if (forkTurns === void 0) throw new Error(forkTurnsError);
1781
+ return context.controlPlane.spawn(context.actor, {
1782
+ agentType: agent_type,
1783
+ taskName: task_name,
1784
+ message,
1785
+ forkTurns
1786
+ });
1787
+ }
1788
+ });
1789
+ }
1790
+
1791
+ // packages/experimental/src/zukhruf/collaboration/wait-agent.ts
1792
+ import { tool as tool5 } from "ai";
1793
+ import { z as z6 } from "zod";
1794
+ var waitAgentOutputSchema = z6.object({ message: z6.string(), timed_out: z6.boolean() }).strict();
1795
+ function createWaitAgentTool(options) {
1796
+ const waitAgentInputSchema = z6.object({
1797
+ timeout_ms: z6.number().int().min(options.minTimeoutMs).max(options.maxTimeoutMs).optional().describe("Maximum time to wait in milliseconds.")
1798
+ });
1799
+ return tool5({
1800
+ description: "Wait for pending mail addressed to this agent without consuming it.",
1801
+ inputSchema: waitAgentInputSchema,
1802
+ outputSchema: waitAgentOutputSchema,
1803
+ execute: async ({ timeout_ms }, { abortSignal, context }) => {
1804
+ const received = await context.controlPlane.waitForMailbox(
1805
+ context.actor,
1806
+ {
1807
+ timeoutMs: timeout_ms ?? options.defaultTimeoutMs,
1808
+ signal: abortSignal
1809
+ }
1810
+ );
1811
+ return received ? { message: "Wait completed.", timed_out: false } : { message: "Wait timed out.", timed_out: true };
1812
+ }
1813
+ });
1814
+ }
1815
+
1816
+ // packages/experimental/src/zukhruf/collaboration/collaboration-tools.ts
1817
+ var NAMESPACE_DESCRIPTION = "Tools for spawning and managing sub-agents.";
1818
+ function createCollaborationTools(config) {
1819
+ const tools = {
1820
+ spawn_agent: createSpawnAgentTool({
1821
+ usageHintText: config.usageHintText
1822
+ }),
1823
+ send_message: sendMessageTool,
1824
+ followup_task: followupTaskTool,
1825
+ list_agents: listAgentsTool,
1826
+ wait_agent: createWaitAgentTool({
1827
+ minTimeoutMs: config.minWaitTimeoutMs,
1828
+ defaultTimeoutMs: config.defaultWaitTimeoutMs,
1829
+ maxTimeoutMs: config.maxWaitTimeoutMs
1830
+ }),
1831
+ interrupt_agent: interruptAgentTool
1832
+ };
1833
+ return Object.fromEntries(
1834
+ Object.entries(tools).map(([name, collaborationTool]) => [
1835
+ name,
1836
+ configureTool(collaborationTool, config)
1837
+ ])
1838
+ );
1839
+ }
1840
+ function configureTool(collaborationTool, config) {
1841
+ const openai = collaborationTool.providerOptions?.openai;
1842
+ return {
1843
+ ...collaborationTool,
1844
+ providerOptions: {
1845
+ ...collaborationTool.providerOptions,
1846
+ ...config.toolNamespace === void 0 ? {} : {
1847
+ openai: {
1848
+ ...typeof openai === "object" && openai !== null ? openai : {},
1849
+ namespace: {
1850
+ name: config.toolNamespace,
1851
+ description: NAMESPACE_DESCRIPTION
1852
+ }
1853
+ }
1854
+ }
1855
+ },
1856
+ metadata: {
1857
+ ...collaborationTool.metadata,
1858
+ zukhruf: {
1859
+ kind: "collaboration",
1860
+ codeModeExposure: "direct-model-only"
1861
+ }
1862
+ }
1863
+ };
1864
+ }
1865
+
1866
+ // packages/experimental/src/zukhruf/runtime/agent-skills.ts
1867
+ import path from "node:path";
1868
+ import {
1869
+ parseFrontmatter,
1870
+ skills
1871
+ } from "@deepagents/context";
1872
+ var EMPTY_SKILLS = { available: [], fragments: [] };
1873
+ async function discoverAgentSkills(sandbox, signal) {
1874
+ if (sandbox.workingDirectory === void 0) return EMPTY_SKILLS;
1875
+ const skillsDirectory = path.posix.join(sandbox.workingDirectory, "skills");
1876
+ const quotedSkillsDirectory = shellQuote(skillsDirectory);
1877
+ const result = await sandbox.sandbox.executeCommand(
1878
+ `if [ -d ${quotedSkillsDirectory} ]; then find ${quotedSkillsDirectory} -mindepth 1 -maxdepth 1 -type d -print; fi`,
1879
+ { signal }
1880
+ );
1881
+ if (result.exitCode !== 0) {
1882
+ throw new Error(
1883
+ `AgentRuntime: failed to discover sandbox skills: ${result.stderr.trim() || `exit ${result.exitCode}`}`
1884
+ );
1885
+ }
1886
+ const skillDirectories = result.stdout.split("\n").filter(Boolean).filter((directory) => !path.posix.basename(directory).startsWith(".")).toSorted();
1887
+ if (skillDirectories.length === 0) return EMPTY_SKILLS;
1888
+ const discovered = await Promise.all(
1889
+ skillDirectories.map((directory) => loadSkill(sandbox, directory))
1890
+ );
1891
+ return createAgentSkills(discovered);
1892
+ }
1893
+ function createAgentSkills(available) {
1894
+ if (available.length === 0) return EMPTY_SKILLS;
1895
+ const snapshot = [...available];
1896
+ return { available: snapshot, fragments: [skills(snapshot)] };
1897
+ }
1898
+ async function loadSkill(sandbox, directory) {
1899
+ const directoryName = path.posix.basename(directory);
1900
+ const skillMd = await sandbox.sandbox.readFile(
1901
+ path.posix.join(directory, "SKILL.md")
1902
+ );
1903
+ const { frontmatter } = parseFrontmatter(skillMd);
1904
+ if (frontmatter.name !== directoryName) {
1905
+ throw new Error(
1906
+ `AgentRuntime: skill "${frontmatter.name}" must use matching directory "${directoryName}"`
1907
+ );
1908
+ }
1909
+ return {
1910
+ name: frontmatter.name,
1911
+ description: frontmatter.description,
1912
+ path: path.posix.join("skills", directoryName, "SKILL.md")
1913
+ };
1914
+ }
1915
+ function shellQuote(value) {
1916
+ return `'${value.replaceAll("'", "'\\''")}'`;
1917
+ }
1182
1918
 
1183
- // packages/experimental/src/zukhruf/agent-turn-executor.ts
1919
+ // packages/experimental/src/zukhruf/runtime/agent-turn-executor.ts
1184
1920
  var AgentTurnExecutor = class {
1185
1921
  #store;
1186
1922
  #streams;
1187
1923
  #controlPlane;
1188
1924
  #mailbox;
1189
1925
  #approvals;
1926
+ #multiAgentV2;
1927
+ #collaborationTools;
1190
1928
  constructor(options) {
1191
1929
  this.#store = options.store;
1192
1930
  this.#streams = options.streams;
1193
1931
  this.#controlPlane = options.controlPlane;
1194
1932
  this.#mailbox = options.mailbox;
1195
1933
  this.#approvals = options.approvals;
1934
+ this.#multiAgentV2 = options.multiAgentV2;
1935
+ this.#collaborationTools = createCollaborationTools(options.multiAgentV2);
1196
1936
  }
1197
1937
  async execute(turn, context) {
1938
+ if (turn.kind === "approval") {
1939
+ if (!await this.#approvals.applyDecision(turn)) return;
1940
+ await this.#reopen(turn.streamId);
1941
+ return this.execute(
1942
+ {
1943
+ kind: "continuation",
1944
+ streamId: turn.streamId,
1945
+ chatId: turn.chatId,
1946
+ userId: turn.userId
1947
+ },
1948
+ context
1949
+ );
1950
+ }
1951
+ if (turn.kind === "continuation" && turn.recovery !== void 0) {
1952
+ await this.#reopen(turn.streamId);
1953
+ }
1198
1954
  if (await this.#projectSkippedTerminalTurn(turn)) return;
1199
1955
  let parked = false;
1200
1956
  await this.#mailbox.beginTurn(turn);
@@ -1213,7 +1969,8 @@ var AgentTurnExecutor = class {
1213
1969
  async #executeTurn(turn, { signal, park }) {
1214
1970
  if (await this.#projectSkippedTerminalTurn(turn)) return;
1215
1971
  const { declaration, thread } = await this.#controlPlane.resolve(turn);
1216
- const engine = this.#engineFor(turn).set(...declaration.instructions);
1972
+ const usageHint = thread.path.isRoot ? this.#multiAgentV2.rootAgentUsageHintText : this.#multiAgentV2.subagentUsageHintText;
1973
+ const engine = this.#engineFor(turn);
1217
1974
  if (turn.kind === "ask" || turn.kind === "mailbox") {
1218
1975
  const head = (await engine.getMessages()).at(-1);
1219
1976
  if (this.#approvals.isPaused(head)) {
@@ -1221,7 +1978,12 @@ var AgentTurnExecutor = class {
1221
1978
  return;
1222
1979
  }
1223
1980
  }
1224
- const communications = turn.kind === "ask" ? await this.#mailbox.drainLeadingQueueOnly(turn) : turn.kind === "mailbox" ? await this.#mailbox.drain(turn) : [];
1981
+ let communications = [];
1982
+ if (turn.kind === "ask") {
1983
+ communications = await this.#mailbox.drainLeadingQueueOnly(turn);
1984
+ } else if (turn.kind === "mailbox") {
1985
+ communications = await this.#mailbox.drain(turn);
1986
+ }
1225
1987
  if (turn.kind === "mailbox" && communications.length === 0) {
1226
1988
  await this.#streams.store.updateStreamStatus(turn.streamId, "completed");
1227
1989
  return;
@@ -1232,6 +1994,12 @@ var AgentTurnExecutor = class {
1232
1994
  chatId: turn.chatId,
1233
1995
  userId: turn.userId
1234
1996
  });
1997
+ const agentSkills = await this.#skillsFor(turn, sandbox, signal);
1998
+ engine.set(
1999
+ ...declaration.instructions,
2000
+ ...agentSkills.fragments,
2001
+ ...usageHint === void 0 ? [] : [role(usageHint)]
2002
+ );
1235
2003
  if (await this.#projectSkippedTerminalTurn(turn)) return;
1236
2004
  if (!await this.#streams.claim(turn.streamId)) {
1237
2005
  await this.#projectSkippedTerminalTurn(turn);
@@ -1245,10 +2013,7 @@ var AgentTurnExecutor = class {
1245
2013
  context: engine,
1246
2014
  tools: {
1247
2015
  ...declaration.tools,
1248
- spawn_agent: spawnAgentTool,
1249
- send_message: sendMessageTool,
1250
- followup_task: followupTaskTool,
1251
- list_agents: listAgentsTool
2016
+ ...this.#collaborationTools
1252
2017
  },
1253
2018
  telemetry: declaration.telemetry,
1254
2019
  prepareStepInput: () => this.#prepareStepInput(turn, mailboxState)
@@ -1315,6 +2080,11 @@ var AgentTurnExecutor = class {
1315
2080
  stream.error
1316
2081
  );
1317
2082
  }
2083
+ async #reopen(streamId) {
2084
+ const status = await this.#streams.store.getStreamStatus(streamId);
2085
+ if (status === "queued" || status === "running") return;
2086
+ await this.#streams.reopen(streamId);
2087
+ }
1318
2088
  async #prepareChain(turn, engine, communications) {
1319
2089
  if (turn.kind === "ask") {
1320
2090
  engine.set(
@@ -1342,6 +2112,29 @@ var AgentTurnExecutor = class {
1342
2112
  (communication) => this.#mailboxInputMessage(communication)
1343
2113
  );
1344
2114
  }
2115
+ async #skillsFor(turn, sandbox, signal) {
2116
+ const chat2 = await this.#store.getChat(turn.chatId);
2117
+ const existing = readSkills(chat2?.metadata);
2118
+ if (existing !== void 0) return createAgentSkills(existing);
2119
+ if (sandbox.workingDirectory === void 0) return createAgentSkills([]);
2120
+ const discovered = await discoverAgentSkills(sandbox, signal);
2121
+ let available = discovered.available;
2122
+ await this.#store.updateChat(turn.chatId, ({ metadata }) => {
2123
+ const persisted = readSkills(metadata);
2124
+ if (persisted !== void 0) {
2125
+ available = persisted;
2126
+ return void 0;
2127
+ }
2128
+ const zukhruf = isRecord2(metadata?.zukhruf) ? metadata.zukhruf : {};
2129
+ return {
2130
+ metadata: {
2131
+ ...metadata,
2132
+ zukhruf: { ...zukhruf, skills: available }
2133
+ }
2134
+ };
2135
+ });
2136
+ return available === discovered.available ? discovered : createAgentSkills(available);
2137
+ }
1345
2138
  #engineFor({ chatId, userId }) {
1346
2139
  return new ContextEngine2({ store: this.#store, chatId, userId });
1347
2140
  }
@@ -1370,15 +2163,40 @@ Payload:
1370
2163
  ${communication.content}`;
1371
2164
  }
1372
2165
  };
2166
+ function readSkills(metadata) {
2167
+ const zukhruf = metadata?.zukhruf;
2168
+ if (!isRecord2(zukhruf) || !Object.hasOwn(zukhruf, "skills")) {
2169
+ return void 0;
2170
+ }
2171
+ if (!Array.isArray(zukhruf.skills) || !zukhruf.skills.every(isSkill)) {
2172
+ throw new Error("AgentRuntime: stored skill catalog is invalid");
2173
+ }
2174
+ return zukhruf.skills;
2175
+ }
2176
+ function isSkill(value) {
2177
+ return isRecord2(value) && typeof value.name === "string" && typeof value.description === "string" && typeof value.path === "string";
2178
+ }
2179
+ function isRecord2(value) {
2180
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2181
+ }
1373
2182
 
1374
- // packages/experimental/src/zukhruf/approval-controller.ts
2183
+ // packages/experimental/src/zukhruf/runtime/approval-controller.ts
1375
2184
  import {
2185
+ getToolName,
1376
2186
  isToolUIPart
1377
2187
  } from "ai";
1378
2188
  import {
1379
2189
  ContextEngine as ContextEngine3,
1380
2190
  assistant as assistant2
1381
2191
  } from "@deepagents/context";
2192
+
2193
+ // packages/experimental/src/zukhruf/runtime/approval-job-id.ts
2194
+ import { v5 as uuidv55 } from "uuid";
2195
+ function approvalJobId(conversation, approvalId) {
2196
+ return uuidv55(`approval:${approvalId}`, conversationNamespace(conversation));
2197
+ }
2198
+
2199
+ // packages/experimental/src/zukhruf/runtime/approval-controller.ts
1382
2200
  var ApprovalController = class _ApprovalController {
1383
2201
  static #settledToolStates = /* @__PURE__ */ new Set([
1384
2202
  "output-available",
@@ -1386,14 +2204,10 @@ var ApprovalController = class _ApprovalController {
1386
2204
  "output-denied"
1387
2205
  ]);
1388
2206
  #store;
1389
- #streams;
1390
2207
  #queue;
1391
- #mutex;
1392
2208
  constructor(options) {
1393
2209
  this.#store = options.store;
1394
- this.#streams = options.streams;
1395
2210
  this.#queue = options.queue;
1396
- this.#mutex = options.mutex;
1397
2211
  }
1398
2212
  isPaused(message) {
1399
2213
  return message?.role === "assistant" && this.#pendingToolPart(message) !== void 0;
@@ -1410,40 +2224,61 @@ var ApprovalController = class _ApprovalController {
1410
2224
  });
1411
2225
  }
1412
2226
  async settleDeniedApprovals(conversation, streamId) {
1413
- await this.#mutex.runExclusive(conversation.chatId, async () => {
1414
- const engine = this.#engineFor(conversation);
1415
- const head = (await engine.getMessages()).at(-1);
1416
- if (head?.role !== "assistant" || head.id !== streamId) return;
1417
- const denied = head.parts.filter(
1418
- (part) => isToolUIPart(part) && part.state === "approval-responded" && part.approval.approved === false
1419
- );
1420
- if (denied.length === 0) return;
1421
- const updated = {
1422
- ...head,
1423
- parts: head.parts.map(
1424
- (part) => denied.includes(part) ? { ...part, state: "output-denied" } : part
1425
- )
1426
- };
1427
- await engine.continue(assistant2(updated));
1428
- });
2227
+ const engine = this.#engineFor(conversation);
2228
+ const head = (await engine.getMessages()).at(-1);
2229
+ if (head?.role !== "assistant" || head.id !== streamId) return;
2230
+ const hasDenied = head.parts.some(
2231
+ (part) => isToolUIPart(part) && part.state === "approval-responded" && part.approval.approved === false
2232
+ );
2233
+ if (!hasDenied) return;
2234
+ const updated = {
2235
+ ...head,
2236
+ parts: head.parts.map((part) => {
2237
+ if (!isToolUIPart(part) || part.state !== "approval-responded" || part.approval.approved !== false) {
2238
+ return part;
2239
+ }
2240
+ const settled = {
2241
+ ...part,
2242
+ state: "output-denied",
2243
+ approval: { ...part.approval, approved: false }
2244
+ };
2245
+ return settled;
2246
+ })
2247
+ };
2248
+ await engine.continue(assistant2(updated));
1429
2249
  }
1430
2250
  async settleFailedApprovals(conversation, streamId, error) {
1431
- await this.#mutex.runExclusive(conversation.chatId, async () => {
1432
- const engine = this.#engineFor(conversation);
1433
- const head = (await engine.getMessages()).at(-1);
1434
- if (head?.role !== "assistant" || head.id !== streamId) return;
1435
- const responded = head.parts.filter(
1436
- (part) => isToolUIPart(part) && part.state === "approval-responded"
1437
- );
1438
- if (responded.length === 0) return;
1439
- const updated = {
1440
- ...head,
1441
- parts: head.parts.map(
1442
- (part) => isToolUIPart(part) && part.state === "approval-responded" ? part.approval.approved === false ? { ...part, state: "output-denied" } : { ...part, state: "output-error", errorText: error } : part
1443
- )
1444
- };
1445
- await engine.continue(assistant2(updated));
1446
- });
2251
+ const engine = this.#engineFor(conversation);
2252
+ const head = (await engine.getMessages()).at(-1);
2253
+ if (head?.role !== "assistant" || head.id !== streamId) return;
2254
+ const hasResponded = head.parts.some(
2255
+ (part) => isToolUIPart(part) && part.state === "approval-responded"
2256
+ );
2257
+ if (!hasResponded) return;
2258
+ const updated = {
2259
+ ...head,
2260
+ parts: head.parts.map((part) => {
2261
+ if (!isToolUIPart(part) || part.state !== "approval-responded") {
2262
+ return part;
2263
+ }
2264
+ if (part.approval.approved === false) {
2265
+ const denied = {
2266
+ ...part,
2267
+ state: "output-denied",
2268
+ approval: { ...part.approval, approved: false }
2269
+ };
2270
+ return denied;
2271
+ }
2272
+ const failed = {
2273
+ ...part,
2274
+ state: "output-error",
2275
+ errorText: error,
2276
+ approval: { ...part.approval, approved: true }
2277
+ };
2278
+ return failed;
2279
+ })
2280
+ };
2281
+ await engine.continue(assistant2(updated));
1447
2282
  }
1448
2283
  async reconcileTerminalContinuation(conversation, streamId, status, error) {
1449
2284
  if (status === "completed") {
@@ -1452,88 +2287,116 @@ var ApprovalController = class _ApprovalController {
1452
2287
  await this.settleFailedApprovals(
1453
2288
  conversation,
1454
2289
  streamId,
1455
- error ?? (status === "cancelled" ? "approval continuation cancelled" : "approval continuation failed")
2290
+ error ?? `approval continuation ${status}`
1456
2291
  );
1457
2292
  }
1458
2293
  await this.#queue.resumeParked(conversation.chatId);
1459
2294
  }
1460
- async #respond(operation, conversation, toolCallId, approval) {
1461
- const result = await this.#mutex.runExclusive(
1462
- conversation.chatId,
1463
- async () => {
1464
- const engine = this.#engineFor(conversation);
1465
- const head = (await engine.getMessages()).at(-1);
1466
- if (head?.role !== "assistant") {
1467
- throw new Error(
1468
- `ApprovalController.${operation}: no paused turn \u2014 the chain head is not an assistant message`
1469
- );
1470
- }
1471
- const part = this.#findToolPart(head, toolCallId);
1472
- if (!part) {
1473
- throw new Error(
1474
- `ApprovalController.${operation}: no tool call "${toolCallId}" on the paused turn`
1475
- );
1476
- }
1477
- if (part.approval?.approved !== void 0 && part.approval.approved !== approval.approved) {
1478
- throw new Error(
1479
- `ApprovalController.${operation}: approval already answered with a different decision`
1480
- );
1481
- }
1482
- let updated = head;
1483
- let answered = part;
1484
- if (part.state === "approval-requested") {
1485
- const responded = {
1486
- ...part,
1487
- state: "approval-responded",
1488
- approval: { ...part.approval, ...approval }
1489
- };
1490
- updated = {
1491
- ...head,
1492
- parts: head.parts.map(
1493
- (candidate) => candidate === part ? responded : candidate
1494
- )
1495
- };
1496
- await engine.continue(assistant2(updated));
1497
- answered = responded;
1498
- }
1499
- return {
1500
- id: updated.id,
1501
- hasUnansweredApprovals: this.#hasUnansweredApprovals(updated),
1502
- shouldSchedule: answered.state === "approval-responded"
1503
- };
1504
- }
2295
+ async retryIdempotentContinuation(conversation, streamId, tools) {
2296
+ const head = (await this.#engineFor(conversation).getMessages()).at(-1);
2297
+ if (head?.role !== "assistant" || head.id !== streamId) return false;
2298
+ const approved = head.parts.filter(
2299
+ (part) => isToolUIPart(part) && part.state === "approval-responded" && part.approval.approved === true
1505
2300
  );
1506
- if (!result.hasUnansweredApprovals) {
1507
- if (result.shouldSchedule) {
1508
- await this.#scheduleContinuation(conversation, result.id);
1509
- } else {
1510
- await this.#queue.resumeParked(conversation.chatId);
1511
- }
2301
+ const retryable = approved.length > 0 && approved.every((part) => {
2302
+ const tool7 = tools[getToolName(part)];
2303
+ return tool7?.recovery === "idempotent" && typeof tool7.execute === "function";
2304
+ });
2305
+ if (!retryable) return false;
2306
+ await this.#queue.push({
2307
+ kind: "continuation",
2308
+ streamId,
2309
+ chatId: conversation.chatId,
2310
+ userId: conversation.userId,
2311
+ recovery: "idempotent"
2312
+ });
2313
+ return true;
2314
+ }
2315
+ async applyDecision(turn) {
2316
+ const engine = this.#engineFor(turn);
2317
+ const head = (await engine.getMessages()).at(-1);
2318
+ if (head?.role !== "assistant" || head.id !== turn.streamId) return false;
2319
+ const part = this.#findToolPart(head, turn.toolCallId);
2320
+ if (part?.approval?.id !== turn.approvalId) return false;
2321
+ if (part.approval.approved !== void 0) return false;
2322
+ if (part.state !== "approval-requested") return false;
2323
+ const responded = {
2324
+ ...part,
2325
+ state: "approval-responded",
2326
+ approval: { ...part.approval, ...turn.decision }
2327
+ };
2328
+ const updated = {
2329
+ ...head,
2330
+ parts: head.parts.map(
2331
+ (candidate) => candidate === part ? responded : candidate
2332
+ )
2333
+ };
2334
+ await engine.continue(assistant2(updated));
2335
+ return !this.#hasUnansweredApprovals(updated);
2336
+ }
2337
+ async recoverUnstartedContinuation(turn, streamId) {
2338
+ if (turn.kind === "approval") await this.applyDecision(turn);
2339
+ const head = (await this.#engineFor(turn).getMessages()).at(-1);
2340
+ if (head?.role !== "assistant" || head.id !== streamId || this.#hasUnansweredApprovals(head) || !head.parts.some(
2341
+ (part) => isToolUIPart(part) && part.state === "approval-responded"
2342
+ )) {
2343
+ return false;
1512
2344
  }
1513
- return { id: result.id, stream: this.#streams.watch(result.id) };
2345
+ await this.#queue.push({
2346
+ kind: "continuation",
2347
+ streamId,
2348
+ chatId: turn.chatId,
2349
+ userId: turn.userId,
2350
+ recovery: "handoff"
2351
+ });
2352
+ return true;
1514
2353
  }
1515
- async #scheduleContinuation(conversation, streamId) {
1516
- let status = await this.#streams.store.getStreamStatus(streamId);
1517
- if (status === "completed") {
1518
- try {
1519
- await this.#streams.reopen(streamId);
1520
- status = "queued";
1521
- } catch (error) {
1522
- status = await this.#streams.store.getStreamStatus(streamId);
1523
- if (status !== "queued" && status !== "running") throw error;
2354
+ async #respond(operation, conversation, toolCallId, approval) {
2355
+ const head = (await this.#engineFor(conversation).getMessages()).at(-1);
2356
+ if (head?.role !== "assistant") {
2357
+ throw new Error(
2358
+ `ApprovalController.${operation}: no paused turn \u2014 the chain head is not an assistant message`
2359
+ );
2360
+ }
2361
+ const part = this.#findToolPart(head, toolCallId);
2362
+ if (!part) {
2363
+ throw new Error(
2364
+ `ApprovalController.${operation}: no tool call "${toolCallId}" on the paused turn`
2365
+ );
2366
+ }
2367
+ if (!part.approval) {
2368
+ throw new Error(
2369
+ `ApprovalController.${operation}: tool call "${toolCallId}" is not awaiting approval`
2370
+ );
2371
+ }
2372
+ const jobId = approvalJobId(conversation, part.approval.id);
2373
+ if (part.approval.approved !== void 0) {
2374
+ if (part.approval.approved !== approval.approved) {
2375
+ throw new Error(
2376
+ `ApprovalController.${operation}: approval already answered with a different decision`
2377
+ );
1524
2378
  }
1525
- } else if (status !== "queued" && status !== "running") {
1526
- return;
2379
+ return { id: head.id, jobId, status: "already-applied" };
1527
2380
  }
1528
- if (status !== "running") {
1529
- await this.#queue.push({
1530
- kind: "continuation",
1531
- streamId,
1532
- chatId: conversation.chatId,
1533
- userId: conversation.userId
1534
- });
2381
+ if (part.state !== "approval-requested") {
2382
+ throw new Error(
2383
+ `ApprovalController.${operation}: tool call "${toolCallId}" is not awaiting approval`
2384
+ );
1535
2385
  }
1536
- await this.#queue.resumeParked(conversation.chatId);
2386
+ const result = await this.#queue.push({
2387
+ kind: "approval",
2388
+ streamId: head.id,
2389
+ chatId: conversation.chatId,
2390
+ userId: conversation.userId,
2391
+ toolCallId,
2392
+ approvalId: part.approval.id,
2393
+ decision: approval
2394
+ });
2395
+ return {
2396
+ id: head.id,
2397
+ jobId,
2398
+ status: result.inserted ? "queued" : "already-queued"
2399
+ };
1537
2400
  }
1538
2401
  #pendingToolPart(message) {
1539
2402
  return message.parts.find(
@@ -1555,89 +2418,14 @@ var ApprovalController = class _ApprovalController {
1555
2418
  }
1556
2419
  };
1557
2420
 
1558
- // packages/experimental/src/zukhruf/mailbox/coordinator.ts
1559
- var MailboxCoordinator = class {
1560
- #store;
1561
- #queue;
1562
- #streams;
1563
- #wakeRequests = /* @__PURE__ */ new Map();
1564
- constructor(options) {
1565
- this.#store = options.store;
1566
- this.#queue = options.queue;
1567
- this.#streams = options.streams;
1568
- }
1569
- async deliver(communication, mode) {
1570
- const delivered = {
1571
- ...communication,
1572
- type: mode === MessageDeliveryMode.TriggerTurn ? InterAgentCommunicationType.NewTask : communication.type,
1573
- triggerTurn: mode === MessageDeliveryMode.TriggerTurn
1574
- };
1575
- assertCommunication(delivered);
1576
- const { recipientActive } = await this.#store.enqueue(delivered);
1577
- if (delivered.triggerTurn || recipientActive) {
1578
- await this.#scheduleWake(delivered.recipient);
1579
- }
1580
- }
1581
- beginTurn(turn) {
1582
- return this.#store.beginTurn(turn, turn.streamId);
1583
- }
1584
- async endTurn(turn, options = {}) {
1585
- const { hasPending, turnEnded } = await this.#store.endTurn(
1586
- turn,
1587
- turn.streamId
1588
- );
1589
- if (turnEnded && hasPending && !options.parked) {
1590
- await this.#scheduleWake(turn);
1591
- }
1592
- }
1593
- drainLeadingQueueOnly(recipient) {
1594
- return this.#store.drainLeadingQueueOnly(recipient);
1595
- }
1596
- drain(recipient) {
1597
- return this.#store.drain(recipient);
1598
- }
1599
- #scheduleWake(target) {
1600
- const key = this.#conversationKey(target);
1601
- const existing = this.#wakeRequests.get(key);
1602
- if (existing) return existing;
1603
- const request = (async () => {
1604
- const wakeId = AgentTurnId.random(target).toString();
1605
- await this.#streams.register(wakeId);
1606
- try {
1607
- await this.#queue.push({
1608
- kind: "mailbox",
1609
- streamId: wakeId,
1610
- chatId: target.chatId,
1611
- userId: target.userId
1612
- });
1613
- } catch (error) {
1614
- await this.#streams.store.updateStreamStatus(wakeId, "failed", {
1615
- error: error instanceof Error ? error.message : String(error)
1616
- });
1617
- throw error;
1618
- }
1619
- })();
1620
- this.#wakeRequests.set(key, request);
1621
- const clearRequest = () => {
1622
- if (this.#wakeRequests.get(key) === request) {
1623
- this.#wakeRequests.delete(key);
1624
- }
1625
- };
1626
- void request.then(clearRequest, clearRequest);
1627
- return request;
1628
- }
1629
- #conversationKey(conversation) {
1630
- return JSON.stringify([conversation.chatId, conversation.userId]);
1631
- }
1632
- };
1633
-
1634
- // packages/experimental/src/zukhruf/agent-runtime.ts
2421
+ // packages/experimental/src/zukhruf/runtime/agent-runtime.ts
1635
2422
  var AgentObservation = class {
1636
2423
  engine;
1637
2424
  #conversation;
1638
2425
  #store;
1639
2426
  #streams;
1640
- constructor(conversation, store, streams) {
2427
+ #queue;
2428
+ constructor(conversation, store, streams, queue) {
1641
2429
  this.engine = new ContextEngine4({
1642
2430
  store,
1643
2431
  chatId: conversation.chatId,
@@ -1646,6 +2434,7 @@ var AgentObservation = class {
1646
2434
  this.#conversation = conversation;
1647
2435
  this.#store = store;
1648
2436
  this.#streams = streams;
2437
+ this.#queue = queue;
1649
2438
  }
1650
2439
  async resume() {
1651
2440
  const id = await this.#headStreamId();
@@ -1665,8 +2454,9 @@ var AgentObservation = class {
1665
2454
  if (!id) return;
1666
2455
  AgentTurnId.assertOwner(this.#conversation, id);
1667
2456
  const status = await this.#streams.store.getStreamStatus(id);
1668
- if (status === "queued" || status === "running") {
2457
+ if (status === "queued" || status === "running" || status === "cancelled") {
1669
2458
  await this.#streams.cancel(id);
2459
+ await this.#queue.cancel(id);
1670
2460
  }
1671
2461
  }
1672
2462
  async #headStreamId() {
@@ -1684,12 +2474,10 @@ var AgentRuntime = class {
1684
2474
  #approvals;
1685
2475
  #executor;
1686
2476
  constructor(root, options) {
2477
+ const multiAgentV2 = resolveMultiAgentV2HostConfig(options.multiAgentV2);
1687
2478
  const declarations = new AgentDeclarationRegistry(root);
1688
2479
  const directory = new AgentDirectory(options.store);
1689
- const streams = new StreamManager({
1690
- store: options.streamStore,
1691
- changeSource: new PollingChangeSource({ reads: options.streamStore })
1692
- });
2480
+ const streams = options.streams;
1693
2481
  const mailbox = new MailboxCoordinator({
1694
2482
  store: options.mailboxStore,
1695
2483
  queue: options.queue,
@@ -1697,9 +2485,7 @@ var AgentRuntime = class {
1697
2485
  });
1698
2486
  const approvals = new ApprovalController({
1699
2487
  store: options.store,
1700
- streams,
1701
- queue: options.queue,
1702
- mutex: options.approvalMutex
2488
+ queue: options.queue
1703
2489
  });
1704
2490
  const statusProjector = new AgentStatusProjector({
1705
2491
  store: options.store,
@@ -1709,6 +2495,7 @@ var AgentRuntime = class {
1709
2495
  directory,
1710
2496
  approvals
1711
2497
  });
2498
+ const historyForker = new AgentHistoryForker(options.store);
1712
2499
  const controlPlane = new AgentControlPlane({
1713
2500
  root,
1714
2501
  streams,
@@ -1716,7 +2503,8 @@ var AgentRuntime = class {
1716
2503
  mailbox,
1717
2504
  declarations,
1718
2505
  directory,
1719
- statusProjector
2506
+ statusProjector,
2507
+ historyForker
1720
2508
  });
1721
2509
  this.#store = options.store;
1722
2510
  this.#queue = options.queue;
@@ -1730,7 +2518,8 @@ var AgentRuntime = class {
1730
2518
  streams,
1731
2519
  controlPlane,
1732
2520
  mailbox,
1733
- approvals
2521
+ approvals,
2522
+ multiAgentV2
1734
2523
  });
1735
2524
  }
1736
2525
  async enqueue(conversation, turn) {
@@ -1748,7 +2537,12 @@ var AgentRuntime = class {
1748
2537
  return this.#approvals.deny(conversation, input);
1749
2538
  }
1750
2539
  observe(conversation) {
1751
- return new AgentObservation(conversation, this.#store, this.#streams);
2540
+ return new AgentObservation(
2541
+ conversation,
2542
+ this.#store,
2543
+ this.#streams,
2544
+ this.#queue
2545
+ );
1752
2546
  }
1753
2547
  work(options) {
1754
2548
  return this.#queue.consume(this.#executor.execute.bind(this.#executor), {
@@ -1766,7 +2560,28 @@ var AgentRuntime = class {
1766
2560
  });
1767
2561
  stream = await this.#streams.store.getStream(turn.streamId);
1768
2562
  }
1769
- if (turn.kind === "continuation" && (stream?.status === "completed" || stream?.status === "failed" || stream?.status === "cancelled")) {
2563
+ let declaration;
2564
+ if ((turn.kind === "approval" || turn.kind === "continuation" && turn.recovery !== "idempotent") && stream?.status === "failed") {
2565
+ try {
2566
+ ({ declaration } = await this.#controlPlane.resolve(turn));
2567
+ } catch {
2568
+ }
2569
+ }
2570
+ if (declaration !== void 0 && await this.#approvals.retryIdempotentContinuation(
2571
+ turn,
2572
+ turn.streamId,
2573
+ declaration.tools ?? {}
2574
+ )) {
2575
+ return;
2576
+ }
2577
+ if ((turn.kind === "approval" || turn.kind === "continuation") && stream?.status === "completed" && await this.#approvals.recoverUnstartedContinuation(
2578
+ turn,
2579
+ turn.streamId
2580
+ )) {
2581
+ return;
2582
+ }
2583
+ stream = await this.#streams.store.getStream(turn.streamId);
2584
+ if ((turn.kind === "approval" || turn.kind === "continuation") && (stream?.status === "completed" || stream?.status === "failed" || stream?.status === "cancelled")) {
1770
2585
  await this.#approvals.reconcileTerminalContinuation(
1771
2586
  turn,
1772
2587
  turn.streamId,
@@ -1785,7 +2600,7 @@ var AgentRuntime = class {
1785
2600
  await this.#controlPlane.projectTerminal(turn, thread);
1786
2601
  } finally {
1787
2602
  try {
1788
- if (turn.kind === "continuation") {
2603
+ if (turn.kind === "approval" || turn.kind === "continuation") {
1789
2604
  await this.#queue.resumeParked(turn.chatId);
1790
2605
  }
1791
2606
  } finally {
@@ -1795,10 +2610,6 @@ var AgentRuntime = class {
1795
2610
  }
1796
2611
  };
1797
2612
 
1798
- // packages/experimental/src/zukhruf/approval-mutex.ts
1799
- var ApprovalMutex = class {
1800
- };
1801
-
1802
2613
  // packages/experimental/src/zukhruf/instructions.ts
1803
2614
  function defineInstructions(...fragments) {
1804
2615
  return fragments;
@@ -1850,9 +2661,9 @@ var BUSY_TIMEOUT_MS = 5e3;
1850
2661
  var SqliteMailboxStore = class extends MailboxStore {
1851
2662
  #database;
1852
2663
  #closed = false;
1853
- constructor(path) {
2664
+ constructor(path2) {
1854
2665
  super();
1855
- this.#database = new DatabaseSync(path, { timeout: BUSY_TIMEOUT_MS });
2666
+ this.#database = new DatabaseSync(path2, { timeout: BUSY_TIMEOUT_MS });
1856
2667
  this.#database.exec(DDL);
1857
2668
  }
1858
2669
  async beginTurn(recipient, turnId) {
@@ -2010,17 +2821,39 @@ var TurnQueue = class {
2010
2821
  };
2011
2822
 
2012
2823
  // packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
2824
+ var MAX_TIMEOUT_MS = 2147483647;
2013
2825
  var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
2014
2826
  #boss;
2015
2827
  #queue;
2828
+ #schema;
2829
+ #schemaConfigurationError;
2830
+ #table;
2016
2831
  #expireInSeconds;
2832
+ #cancelIntentTtlMs;
2017
2833
  #heartbeatSeconds;
2018
2834
  #pollingIntervalSeconds;
2835
+ #active = /* @__PURE__ */ new Map();
2836
+ #cancelIntents = /* @__PURE__ */ new Map();
2837
+ #cancelIntentExpiryTimer;
2019
2838
  constructor(boss, options = {}) {
2020
2839
  super();
2021
2840
  this.#boss = boss;
2022
2841
  this.#queue = options.queue ?? "zukhruf-turns";
2842
+ const configuredSchema = boss.getDb().config?.schema;
2843
+ const bossSchema = typeof configuredSchema === "string" ? configuredSchema : void 0;
2844
+ this.#schema = options.schema ?? bossSchema ?? "pgboss";
2845
+ if (options.schema === void 0 && bossSchema === void 0) {
2846
+ this.#schemaConfigurationError = "PgBossTurnQueue cannot read the schema from a custom PgBoss database adapter; pass the PgBoss schema in options.schema";
2847
+ } else if (options.schema !== void 0 && bossSchema !== void 0 && options.schema !== bossSchema) {
2848
+ this.#schemaConfigurationError = `PgBossTurnQueue schema "${options.schema}" does not match the PgBoss schema "${bossSchema}"`;
2849
+ }
2023
2850
  this.#expireInSeconds = options.expireInSeconds ?? 3600;
2851
+ this.#cancelIntentTtlMs = this.#expireInSeconds * 1e3;
2852
+ if (!Number.isFinite(this.#expireInSeconds) || this.#expireInSeconds <= 0 || !Number.isSafeInteger(this.#cancelIntentTtlMs) || this.#cancelIntentTtlMs > Number.MAX_SAFE_INTEGER - Date.now()) {
2853
+ throw new Error(
2854
+ "PgBossTurnQueue expireInSeconds must be a finite positive duration"
2855
+ );
2856
+ }
2024
2857
  this.#heartbeatSeconds = options.heartbeatSeconds ?? 30;
2025
2858
  this.#pollingIntervalSeconds = options.pollingIntervalSeconds ?? 1;
2026
2859
  }
@@ -2031,10 +2864,14 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
2031
2864
  return `${this.#queue}-dead`;
2032
2865
  }
2033
2866
  async initialize() {
2867
+ if (this.#schemaConfigurationError) {
2868
+ throw new Error(this.#schemaConfigurationError);
2869
+ }
2034
2870
  if (!await this.#boss.getQueue(this.deadLetterQueue)) {
2035
2871
  await this.#boss.createQueue(this.deadLetterQueue);
2036
2872
  }
2037
- if (!await this.#boss.getQueue(this.#queue)) {
2873
+ let queue = await this.#boss.getQueue(this.#queue);
2874
+ if (!queue) {
2038
2875
  await this.#boss.createQueue(this.#queue, {
2039
2876
  policy: "key_strict_fifo",
2040
2877
  retryLimit: 0,
@@ -2043,14 +2880,40 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
2043
2880
  deleteAfterSeconds: 0,
2044
2881
  deadLetter: this.deadLetterQueue
2045
2882
  });
2883
+ queue = await this.#boss.getQueue(this.#queue);
2884
+ }
2885
+ if (!queue) throw new Error(`Queue "${this.#queue}" was not initialized`);
2886
+ this.#table = queue.table;
2887
+ try {
2888
+ const catalog = await this.#boss.getDb().executeSql(
2889
+ `SELECT table_name AS "table"
2890
+ FROM ${_PgBossTurnQueue.#quoteIdentifier(this.#schema)}."queue"
2891
+ WHERE name = $1`,
2892
+ [this.#queue]
2893
+ );
2894
+ if (catalog.rows.length !== 1 || catalog.rows[0].table !== this.#table) {
2895
+ throw new Error("queue catalog does not match");
2896
+ }
2897
+ await this.#boss.getDb().executeSql(`SELECT 1 FROM ${this.#relation()} WHERE false`);
2898
+ } catch (cause) {
2899
+ throw new Error(
2900
+ `PgBossTurnQueue schema "${this.#schema}" does not match the PgBoss queue; pass the PgBoss schema in options.schema`,
2901
+ { cause }
2902
+ );
2046
2903
  }
2047
2904
  }
2048
2905
  async push(turn) {
2049
- await this.#boss.send(this.#queue, turn, {
2050
- id: uuidv7(),
2906
+ const jobId = turn.kind === "approval" ? approvalJobId(turn, turn.approvalId) : uuidv7();
2907
+ const inserted = await this.#boss.send(this.#queue, turn, {
2908
+ id: jobId,
2051
2909
  singletonKey: turn.chatId,
2052
- priority: turn.kind === "continuation" ? 1 : 0
2910
+ group: { id: turn.chatId },
2911
+ priority: turn.kind === "approval" || turn.kind === "continuation" ? 1 : 0
2053
2912
  });
2913
+ if (inserted === null && turn.kind !== "approval") {
2914
+ throw new Error(`PgBossTurnQueue job id collision: ${jobId}`);
2915
+ }
2916
+ return { jobId, inserted: inserted !== null };
2054
2917
  }
2055
2918
  async getTurnActivity(conversation) {
2056
2919
  const jobs = await this.#boss.findJobs(this.#queue, {
@@ -2064,26 +2927,64 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
2064
2927
  }
2065
2928
  return conversationJobs.length > 0 ? "queued" : "idle";
2066
2929
  }
2930
+ async getCurrentTurn(conversation) {
2931
+ const jobs = await this.#boss.findJobs(this.#queue, {
2932
+ key: conversation.chatId
2933
+ });
2934
+ return jobs.filter(
2935
+ (job) => job.data.userId === conversation.userId && (job.state === "active" || job.state === "created" || job.state === "retry")
2936
+ ).sort(_PgBossTurnQueue.#interruptOrder)[0]?.data;
2937
+ }
2938
+ async cancel(streamId) {
2939
+ this.#rememberCancelIntent(streamId);
2940
+ this.#abortLocal(streamId);
2941
+ const jobs = await this.#boss.findJobs(this.#queue, {
2942
+ data: { streamId }
2943
+ });
2944
+ const queued = jobs.filter((job) => job.state === "created" || job.state === "retry").map((job) => job.id);
2945
+ if (queued.length > 0) await this.#deleteIfStillQueued(queued);
2946
+ this.#abortLocal(streamId);
2947
+ const remaining = await this.#boss.findJobs(this.#queue, {
2948
+ data: { streamId }
2949
+ });
2950
+ if (!remaining.some((job) => job.state === "active")) {
2951
+ this.#forgetCancelIntent(streamId);
2952
+ }
2953
+ }
2067
2954
  async consume(handler, options) {
2068
2955
  const turnWorkerId = await this.#boss.work(
2069
2956
  this.#queue,
2070
2957
  {
2071
2958
  localConcurrency: options.concurrency ?? 1,
2959
+ groupConcurrency: 1,
2072
2960
  pollingIntervalSeconds: this.#pollingIntervalSeconds
2073
2961
  },
2074
2962
  async ([job]) => {
2075
2963
  let parked = false;
2076
- await handler(job.data, {
2077
- signal: job.signal,
2078
- // Parking = self-cancel: a cancelled job stops blocking the chat's
2079
- // key and is revived (original created_on, so original order) by
2080
- // resumeParked(). The worker's completion of a cancelled job is a
2081
- // clean no-op (probe-verified).
2082
- park: async () => {
2083
- parked = true;
2084
- await this.#boss.cancel(this.#queue, job.id);
2964
+ const localAbort = new AbortController();
2965
+ const active = this.#active.get(job.data.streamId) ?? /* @__PURE__ */ new Set();
2966
+ active.add(localAbort);
2967
+ this.#active.set(job.data.streamId, active);
2968
+ if (this.#hasCancelIntent(job.data.streamId)) localAbort.abort();
2969
+ try {
2970
+ await handler(job.data, {
2971
+ signal: AbortSignal.any([job.signal, localAbort.signal]),
2972
+ // Parking = self-cancel: a cancelled job stops blocking the chat's
2973
+ // key and is revived (original created_on, so original order) by
2974
+ // resumeParked(). The worker's completion of a cancelled job is a
2975
+ // clean no-op (probe-verified).
2976
+ park: async () => {
2977
+ parked = true;
2978
+ await this.#boss.cancel(this.#queue, job.id);
2979
+ }
2980
+ });
2981
+ } finally {
2982
+ active.delete(localAbort);
2983
+ if (active.size === 0) {
2984
+ this.#active.delete(job.data.streamId);
2985
+ this.#forgetCancelIntent(job.data.streamId);
2085
2986
  }
2086
- });
2987
+ }
2087
2988
  if (!parked) {
2088
2989
  await this.#boss.deleteJob(this.#queue, job.id);
2089
2990
  }
@@ -2122,91 +3023,184 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
2122
3023
  await this.#boss.resume(this.#queue, parked);
2123
3024
  }
2124
3025
  }
3026
+ #abortLocal(streamId) {
3027
+ for (const controller of this.#active.get(streamId) ?? []) {
3028
+ controller.abort();
3029
+ }
3030
+ }
3031
+ #rememberCancelIntent(streamId) {
3032
+ this.#pruneCancelIntents();
3033
+ this.#cancelIntents.set(streamId, Date.now() + this.#cancelIntentTtlMs);
3034
+ this.#scheduleCancelIntentExpiry();
3035
+ }
3036
+ #hasCancelIntent(streamId) {
3037
+ this.#pruneCancelIntents();
3038
+ return this.#cancelIntents.has(streamId);
3039
+ }
3040
+ #pruneCancelIntents() {
3041
+ const now = Date.now();
3042
+ for (const [streamId, expiresAt] of this.#cancelIntents) {
3043
+ if (expiresAt <= now) this.#cancelIntents.delete(streamId);
3044
+ }
3045
+ this.#scheduleCancelIntentExpiry();
3046
+ }
3047
+ #forgetCancelIntent(streamId) {
3048
+ this.#cancelIntents.delete(streamId);
3049
+ this.#scheduleCancelIntentExpiry();
3050
+ }
3051
+ #scheduleCancelIntentExpiry() {
3052
+ if (this.#cancelIntentExpiryTimer !== void 0) {
3053
+ globalThis.clearTimeout(this.#cancelIntentExpiryTimer);
3054
+ this.#cancelIntentExpiryTimer = void 0;
3055
+ }
3056
+ let nextExpiry = Number.POSITIVE_INFINITY;
3057
+ for (const expiresAt of this.#cancelIntents.values()) {
3058
+ nextExpiry = Math.min(nextExpiry, expiresAt);
3059
+ }
3060
+ if (!Number.isFinite(nextExpiry)) return;
3061
+ const timer = globalThis.setTimeout(
3062
+ () => {
3063
+ if (this.#cancelIntentExpiryTimer !== timer) return;
3064
+ this.#cancelIntentExpiryTimer = void 0;
3065
+ this.#pruneCancelIntents();
3066
+ },
3067
+ Math.min(MAX_TIMEOUT_MS, Math.max(1, nextExpiry - Date.now()))
3068
+ );
3069
+ this.#cancelIntentExpiryTimer = timer;
3070
+ timer.unref?.();
3071
+ }
3072
+ async #deleteIfStillQueued(ids) {
3073
+ if (!this.#table) {
3074
+ throw new Error("PgBossTurnQueue.initialize() must run before cancel()");
3075
+ }
3076
+ await this.#boss.getDb().executeSql(
3077
+ `DELETE FROM ${this.#relation()}
3078
+ WHERE name = $1
3079
+ AND id = ANY($2::uuid[])
3080
+ AND state IN ('created', 'retry')`,
3081
+ [this.#queue, ids]
3082
+ );
3083
+ }
3084
+ #relation() {
3085
+ if (!this.#table) {
3086
+ throw new Error(
3087
+ "PgBossTurnQueue.initialize() must resolve its job table"
3088
+ );
3089
+ }
3090
+ return `${_PgBossTurnQueue.#quoteIdentifier(this.#schema)}.${_PgBossTurnQueue.#quoteIdentifier(this.#table)}`;
3091
+ }
3092
+ static #quoteIdentifier(identifier) {
3093
+ return `"${identifier.replaceAll('"', '""')}"`;
3094
+ }
2125
3095
  static #orphanError(output) {
2126
3096
  if (output && "message" in output && typeof output.message === "string") {
2127
3097
  return output.message;
2128
3098
  }
2129
3099
  return output ? JSON.stringify(output) : "turn orphaned";
2130
3100
  }
3101
+ static #interruptOrder(left, right) {
3102
+ if (left.state === "active" && right.state !== "active") return -1;
3103
+ if (left.state !== "active" && right.state === "active") return 1;
3104
+ if (left.priority !== right.priority) return right.priority - left.priority;
3105
+ const created = left.createdOn.getTime() - right.createdOn.getTime();
3106
+ return created || left.id.localeCompare(right.id);
3107
+ }
2131
3108
  };
2132
3109
 
2133
- // packages/experimental/src/zukhruf/sandbox/define.ts
2134
- import {
2135
- createBashTool
2136
- } from "@deepagents/context";
2137
- function defineSandbox(createBackend, options) {
2138
- return async (context) => createBashTool({ sandbox: await createBackend(context), ...options });
3110
+ // packages/experimental/src/zukhruf/render-turn.ts
3111
+ import { styleText } from "node:util";
3112
+ var dim = (text) => styleText("dim", text);
3113
+ var red = (text) => styleText("red", text);
3114
+ function oneLine(value, max = 88) {
3115
+ const text = String(value ?? "").replaceAll(/\s+/g, " ").trim();
3116
+ return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
2139
3117
  }
2140
-
2141
- // packages/experimental/src/zukhruf/sqlite-approval-mutex.ts
2142
- import { resolve } from "node:path";
2143
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
2144
- var SqliteApprovalMutex = class _SqliteApprovalMutex extends ApprovalMutex {
2145
- static #tails = /* @__PURE__ */ new Map();
2146
- #db;
2147
- #coordinationKey;
2148
- constructor(path) {
2149
- super();
2150
- this.#coordinationKey = path === ":memory:" ? crypto.randomUUID() : resolve(path);
2151
- this.#db = new DatabaseSync2(path);
2152
- this.#db.exec(`
2153
- PRAGMA busy_timeout = 5000;
2154
- CREATE TABLE IF NOT EXISTS approval_mutex (
2155
- id INTEGER PRIMARY KEY CHECK (id = 1),
2156
- conversationId TEXT NOT NULL,
2157
- touchedAt INTEGER NOT NULL
2158
- );
2159
- `);
3118
+ function describeToolCall(toolName, input) {
3119
+ const args = input ?? {};
3120
+ switch (toolName) {
3121
+ case "spawn_agent":
3122
+ return `\u21C4 spawn ${args.agent_type} "${args.task_name}" \u2014 ${args.message}`;
3123
+ case "send_message":
3124
+ return `\u21C4 mail ${args.target} \u2014 ${args.message}`;
3125
+ case "followup_task":
3126
+ return `\u21C4 follow-up ${args.target} \u2014 ${args.message}`;
3127
+ case "list_agents":
3128
+ return "\u21C4 list agents";
3129
+ default:
3130
+ return `\xB7 ${toolName}`;
2160
3131
  }
2161
- async runExclusive(conversationId, operation) {
2162
- const release = await this.#acquireLocalGate();
2163
- try {
2164
- this.#db.exec("BEGIN IMMEDIATE");
2165
- try {
2166
- this.#db.prepare(
2167
- `INSERT INTO approval_mutex (id, conversationId, touchedAt)
2168
- VALUES (1, ?, ?)
2169
- ON CONFLICT(id) DO UPDATE SET
2170
- conversationId = excluded.conversationId,
2171
- touchedAt = excluded.touchedAt`
2172
- ).run(conversationId, Date.now());
2173
- const result = await operation();
2174
- this.#db.exec("COMMIT");
2175
- return result;
2176
- } catch (error) {
2177
- try {
2178
- this.#db.exec("ROLLBACK");
2179
- } catch {
3132
+ }
3133
+ async function renderTurn(stream) {
3134
+ const toolNames = /* @__PURE__ */ new Map();
3135
+ let midText = false;
3136
+ let thinkingShown = false;
3137
+ const breakText = () => {
3138
+ if (midText) process.stdout.write("\n");
3139
+ midText = false;
3140
+ };
3141
+ for await (const chunk of stream) {
3142
+ switch (chunk.type) {
3143
+ case "reasoning-start":
3144
+ if (!thinkingShown) {
3145
+ console.log(dim("\u2026"));
3146
+ thinkingShown = true;
2180
3147
  }
2181
- throw error;
2182
- }
2183
- } finally {
2184
- release();
3148
+ break;
3149
+ case "text-delta":
3150
+ process.stdout.write(chunk.delta);
3151
+ midText = true;
3152
+ break;
3153
+ case "text-end":
3154
+ breakText();
3155
+ break;
3156
+ case "tool-input-available":
3157
+ toolNames.set(chunk.toolCallId, chunk.toolName);
3158
+ breakText();
3159
+ console.log(dim(describeToolCall(chunk.toolName, chunk.input)));
3160
+ break;
3161
+ case "tool-output-error":
3162
+ breakText();
3163
+ console.log(
3164
+ red(
3165
+ `\u2717 ${toolNames.get(chunk.toolCallId) ?? "tool"}: ${oneLine(chunk.errorText)}`
3166
+ )
3167
+ );
3168
+ break;
3169
+ case "error":
3170
+ breakText();
3171
+ console.log(red(`\u2717 ${oneLine(chunk.errorText)}`));
3172
+ break;
3173
+ case "abort":
3174
+ breakText();
3175
+ console.log(dim("\xB7 turn aborted"));
3176
+ break;
2185
3177
  }
2186
3178
  }
2187
- close() {
2188
- this.#db.close();
2189
- }
2190
- [Symbol.dispose]() {
2191
- this.close();
2192
- }
2193
- async #acquireLocalGate() {
2194
- const previous = _SqliteApprovalMutex.#tails.get(this.#coordinationKey) ?? Promise.resolve();
2195
- const gate = Promise.withResolvers();
2196
- const tail = previous.then(() => gate.promise);
2197
- _SqliteApprovalMutex.#tails.set(this.#coordinationKey, tail);
2198
- await previous;
2199
- return () => {
2200
- gate.resolve();
2201
- if (_SqliteApprovalMutex.#tails.get(this.#coordinationKey) === tail) {
2202
- _SqliteApprovalMutex.#tails.delete(this.#coordinationKey);
2203
- }
2204
- };
2205
- }
2206
- };
3179
+ breakText();
3180
+ }
3181
+
3182
+ // packages/experimental/src/zukhruf/sandbox/define.ts
3183
+ import { createBashTool } from "@deepagents/context";
3184
+ var DEFAULT_WORKING_DIRECTORY = "/workspace";
3185
+ function defineSandbox(createBackend, options) {
3186
+ return async (context) => {
3187
+ const workingDirectory = options?.destination ?? DEFAULT_WORKING_DIRECTORY;
3188
+ return Object.assign(
3189
+ await createBashTool({
3190
+ sandbox: await createBackend(context),
3191
+ ...options,
3192
+ destination: workingDirectory
3193
+ }),
3194
+ { workingDirectory }
3195
+ );
3196
+ };
3197
+ }
2207
3198
 
2208
3199
  // packages/experimental/src/zukhruf/tool.ts
2209
- import { tool as tool4 } from "ai";
3200
+ import { tool as tool6 } from "ai";
3201
+ function defineTool(definition) {
3202
+ return tool6(definition);
3203
+ }
2210
3204
  export {
2211
3205
  coding_agent_reminders_exports as codingAgentReminders,
2212
3206
  zukhruf_exports as zukhruf