@deepagents/experimental 5.0.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +22 -11
  2. package/dist/index.js +1315 -433
  3. package/dist/index.js.map +4 -4
  4. package/dist/zukhruf/agent.d.ts +4 -3
  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 +1316 -434
  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} +23 -12
  52. package/dist/zukhruf/runtime/agent-runtime.d.ts.map +1 -0
  53. package/dist/zukhruf/{agent-turn-executor.d.ts → runtime/agent-turn-executor.d.ts} +5 -3
  54. package/dist/zukhruf/runtime/agent-turn-executor.d.ts.map +1 -0
  55. package/dist/zukhruf/{approval-controller.d.ts → runtime/approval-controller.d.ts} +19 -8
  56. package/dist/zukhruf/runtime/approval-controller.d.ts.map +1 -0
  57. package/dist/zukhruf/runtime/approval-job-id.d.ts +3 -0
  58. package/dist/zukhruf/runtime/approval-job-id.d.ts.map +1 -0
  59. package/dist/zukhruf/tool.d.ts +18 -6
  60. package/dist/zukhruf/tool.d.ts.map +1 -1
  61. package/package.json +9 -9
  62. package/dist/zukhruf/agent-control-plane.d.ts.map +0 -1
  63. package/dist/zukhruf/agent-declaration-registry.d.ts.map +0 -1
  64. package/dist/zukhruf/agent-directory.d.ts.map +0 -1
  65. package/dist/zukhruf/agent-path.d.ts.map +0 -1
  66. package/dist/zukhruf/agent-runtime.d.ts.map +0 -1
  67. package/dist/zukhruf/agent-status-projector.d.ts +0 -32
  68. package/dist/zukhruf/agent-status-projector.d.ts.map +0 -1
  69. package/dist/zukhruf/agent-thread.d.ts.map +0 -1
  70. package/dist/zukhruf/agent-tool-context.d.ts +0 -6
  71. package/dist/zukhruf/agent-tool-context.d.ts.map +0 -1
  72. package/dist/zukhruf/agent-turn-executor.d.ts.map +0 -1
  73. package/dist/zukhruf/agent-turn-id.d.ts.map +0 -1
  74. package/dist/zukhruf/approval-controller.d.ts.map +0 -1
  75. package/dist/zukhruf/approval-mutex.d.ts +0 -5
  76. package/dist/zukhruf/approval-mutex.d.ts.map +0 -1
  77. package/dist/zukhruf/list-agents.d.ts.map +0 -1
  78. package/dist/zukhruf/message-tools.d.ts.map +0 -1
  79. package/dist/zukhruf/spawn-agent.d.ts.map +0 -1
  80. package/dist/zukhruf/sqlite-approval-mutex.d.ts +0 -17
  81. package/dist/zukhruf/sqlite-approval-mutex.d.ts.map +0 -1
  82. /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) {
@@ -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;
@@ -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;
@@ -629,12 +672,16 @@ var AgentDirectory = class _AgentDirectory {
629
672
  }
630
673
  async resolve(thread, target) {
631
674
  const path = thread.path.resolve(target);
632
- const match = (await this.listTree(thread)).find(
633
- (candidate) => candidate.path.equals(path)
634
- );
675
+ const match = await this.find(thread, target);
635
676
  if (match) return match;
636
677
  throw new Error(`agent path "${path}" does not exist in this tree`);
637
678
  }
679
+ async find(thread, target) {
680
+ const path = thread.path.resolve(target);
681
+ return (await this.listTree(thread)).find(
682
+ (candidate) => candidate.path.equals(path)
683
+ );
684
+ }
638
685
  async createChild(options) {
639
686
  const path = options.parent.path.resolve(options.taskName);
640
687
  const pathString = path.toString();
@@ -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;
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
+ );
789
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,446 @@ 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
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
1123
1680
  } from "@deepagents/context";
1124
1681
 
1125
- // packages/experimental/src/zukhruf/list-agents.ts
1682
+ // packages/experimental/src/zukhruf/collaboration/interrupt-agent.ts
1126
1683
  import { tool } from "ai";
1127
- import { z } from "zod";
1128
- var listAgentsInputSchema = z.object({
1129
- path_prefix: z.string().trim().min(1).describe(
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
+ }
1182
1865
 
1183
- // packages/experimental/src/zukhruf/agent-turn-executor.ts
1866
+ // packages/experimental/src/zukhruf/runtime/agent-turn-executor.ts
1184
1867
  var AgentTurnExecutor = class {
1185
1868
  #store;
1186
1869
  #streams;
1187
1870
  #controlPlane;
1188
1871
  #mailbox;
1189
1872
  #approvals;
1873
+ #multiAgentV2;
1874
+ #collaborationTools;
1190
1875
  constructor(options) {
1191
1876
  this.#store = options.store;
1192
1877
  this.#streams = options.streams;
1193
1878
  this.#controlPlane = options.controlPlane;
1194
1879
  this.#mailbox = options.mailbox;
1195
1880
  this.#approvals = options.approvals;
1881
+ this.#multiAgentV2 = options.multiAgentV2;
1882
+ this.#collaborationTools = createCollaborationTools(options.multiAgentV2);
1196
1883
  }
1197
1884
  async execute(turn, context) {
1885
+ if (turn.kind === "approval") {
1886
+ if (!await this.#approvals.applyDecision(turn)) return;
1887
+ await this.#reopen(turn.streamId);
1888
+ return this.execute(
1889
+ {
1890
+ kind: "continuation",
1891
+ streamId: turn.streamId,
1892
+ chatId: turn.chatId,
1893
+ userId: turn.userId
1894
+ },
1895
+ context
1896
+ );
1897
+ }
1898
+ if (turn.kind === "continuation" && turn.recovery !== void 0) {
1899
+ await this.#reopen(turn.streamId);
1900
+ }
1198
1901
  if (await this.#projectSkippedTerminalTurn(turn)) return;
1199
1902
  let parked = false;
1200
1903
  await this.#mailbox.beginTurn(turn);
@@ -1213,7 +1916,11 @@ var AgentTurnExecutor = class {
1213
1916
  async #executeTurn(turn, { signal, park }) {
1214
1917
  if (await this.#projectSkippedTerminalTurn(turn)) return;
1215
1918
  const { declaration, thread } = await this.#controlPlane.resolve(turn);
1216
- const engine = this.#engineFor(turn).set(...declaration.instructions);
1919
+ const usageHint = thread.path.isRoot ? this.#multiAgentV2.rootAgentUsageHintText : this.#multiAgentV2.subagentUsageHintText;
1920
+ const engine = this.#engineFor(turn).set(
1921
+ ...declaration.instructions,
1922
+ ...usageHint === void 0 ? [] : [role(usageHint)]
1923
+ );
1217
1924
  if (turn.kind === "ask" || turn.kind === "mailbox") {
1218
1925
  const head = (await engine.getMessages()).at(-1);
1219
1926
  if (this.#approvals.isPaused(head)) {
@@ -1221,7 +1928,12 @@ var AgentTurnExecutor = class {
1221
1928
  return;
1222
1929
  }
1223
1930
  }
1224
- const communications = turn.kind === "ask" ? await this.#mailbox.drainLeadingQueueOnly(turn) : turn.kind === "mailbox" ? await this.#mailbox.drain(turn) : [];
1931
+ let communications = [];
1932
+ if (turn.kind === "ask") {
1933
+ communications = await this.#mailbox.drainLeadingQueueOnly(turn);
1934
+ } else if (turn.kind === "mailbox") {
1935
+ communications = await this.#mailbox.drain(turn);
1936
+ }
1225
1937
  if (turn.kind === "mailbox" && communications.length === 0) {
1226
1938
  await this.#streams.store.updateStreamStatus(turn.streamId, "completed");
1227
1939
  return;
@@ -1245,10 +1957,7 @@ var AgentTurnExecutor = class {
1245
1957
  context: engine,
1246
1958
  tools: {
1247
1959
  ...declaration.tools,
1248
- spawn_agent: spawnAgentTool,
1249
- send_message: sendMessageTool,
1250
- followup_task: followupTaskTool,
1251
- list_agents: listAgentsTool
1960
+ ...this.#collaborationTools
1252
1961
  },
1253
1962
  telemetry: declaration.telemetry,
1254
1963
  prepareStepInput: () => this.#prepareStepInput(turn, mailboxState)
@@ -1315,6 +2024,11 @@ var AgentTurnExecutor = class {
1315
2024
  stream.error
1316
2025
  );
1317
2026
  }
2027
+ async #reopen(streamId) {
2028
+ const status = await this.#streams.store.getStreamStatus(streamId);
2029
+ if (status === "queued" || status === "running") return;
2030
+ await this.#streams.reopen(streamId);
2031
+ }
1318
2032
  async #prepareChain(turn, engine, communications) {
1319
2033
  if (turn.kind === "ask") {
1320
2034
  engine.set(
@@ -1371,14 +2085,23 @@ ${communication.content}`;
1371
2085
  }
1372
2086
  };
1373
2087
 
1374
- // packages/experimental/src/zukhruf/approval-controller.ts
2088
+ // packages/experimental/src/zukhruf/runtime/approval-controller.ts
1375
2089
  import {
2090
+ getToolName,
1376
2091
  isToolUIPart
1377
2092
  } from "ai";
1378
2093
  import {
1379
2094
  ContextEngine as ContextEngine3,
1380
2095
  assistant as assistant2
1381
2096
  } from "@deepagents/context";
2097
+
2098
+ // packages/experimental/src/zukhruf/runtime/approval-job-id.ts
2099
+ import { v5 as uuidv55 } from "uuid";
2100
+ function approvalJobId(conversation, approvalId) {
2101
+ return uuidv55(`approval:${approvalId}`, conversationNamespace(conversation));
2102
+ }
2103
+
2104
+ // packages/experimental/src/zukhruf/runtime/approval-controller.ts
1382
2105
  var ApprovalController = class _ApprovalController {
1383
2106
  static #settledToolStates = /* @__PURE__ */ new Set([
1384
2107
  "output-available",
@@ -1386,14 +2109,10 @@ var ApprovalController = class _ApprovalController {
1386
2109
  "output-denied"
1387
2110
  ]);
1388
2111
  #store;
1389
- #streams;
1390
2112
  #queue;
1391
- #mutex;
1392
2113
  constructor(options) {
1393
2114
  this.#store = options.store;
1394
- this.#streams = options.streams;
1395
2115
  this.#queue = options.queue;
1396
- this.#mutex = options.mutex;
1397
2116
  }
1398
2117
  isPaused(message) {
1399
2118
  return message?.role === "assistant" && this.#pendingToolPart(message) !== void 0;
@@ -1410,40 +2129,61 @@ var ApprovalController = class _ApprovalController {
1410
2129
  });
1411
2130
  }
1412
2131
  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
- });
2132
+ const engine = this.#engineFor(conversation);
2133
+ const head = (await engine.getMessages()).at(-1);
2134
+ if (head?.role !== "assistant" || head.id !== streamId) return;
2135
+ const hasDenied = head.parts.some(
2136
+ (part) => isToolUIPart(part) && part.state === "approval-responded" && part.approval.approved === false
2137
+ );
2138
+ if (!hasDenied) return;
2139
+ const updated = {
2140
+ ...head,
2141
+ parts: head.parts.map((part) => {
2142
+ if (!isToolUIPart(part) || part.state !== "approval-responded" || part.approval.approved !== false) {
2143
+ return part;
2144
+ }
2145
+ const settled = {
2146
+ ...part,
2147
+ state: "output-denied",
2148
+ approval: { ...part.approval, approved: false }
2149
+ };
2150
+ return settled;
2151
+ })
2152
+ };
2153
+ await engine.continue(assistant2(updated));
1429
2154
  }
1430
2155
  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
- });
2156
+ const engine = this.#engineFor(conversation);
2157
+ const head = (await engine.getMessages()).at(-1);
2158
+ if (head?.role !== "assistant" || head.id !== streamId) return;
2159
+ const hasResponded = head.parts.some(
2160
+ (part) => isToolUIPart(part) && part.state === "approval-responded"
2161
+ );
2162
+ if (!hasResponded) return;
2163
+ const updated = {
2164
+ ...head,
2165
+ parts: head.parts.map((part) => {
2166
+ if (!isToolUIPart(part) || part.state !== "approval-responded") {
2167
+ return part;
2168
+ }
2169
+ if (part.approval.approved === false) {
2170
+ const denied = {
2171
+ ...part,
2172
+ state: "output-denied",
2173
+ approval: { ...part.approval, approved: false }
2174
+ };
2175
+ return denied;
2176
+ }
2177
+ const failed = {
2178
+ ...part,
2179
+ state: "output-error",
2180
+ errorText: error,
2181
+ approval: { ...part.approval, approved: true }
2182
+ };
2183
+ return failed;
2184
+ })
2185
+ };
2186
+ await engine.continue(assistant2(updated));
1447
2187
  }
1448
2188
  async reconcileTerminalContinuation(conversation, streamId, status, error) {
1449
2189
  if (status === "completed") {
@@ -1452,88 +2192,116 @@ var ApprovalController = class _ApprovalController {
1452
2192
  await this.settleFailedApprovals(
1453
2193
  conversation,
1454
2194
  streamId,
1455
- error ?? (status === "cancelled" ? "approval continuation cancelled" : "approval continuation failed")
2195
+ error ?? `approval continuation ${status}`
1456
2196
  );
1457
2197
  }
1458
2198
  await this.#queue.resumeParked(conversation.chatId);
1459
2199
  }
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
- }
2200
+ async retryIdempotentContinuation(conversation, streamId, tools) {
2201
+ const head = (await this.#engineFor(conversation).getMessages()).at(-1);
2202
+ if (head?.role !== "assistant" || head.id !== streamId) return false;
2203
+ const approved = head.parts.filter(
2204
+ (part) => isToolUIPart(part) && part.state === "approval-responded" && part.approval.approved === true
1505
2205
  );
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
- }
2206
+ const retryable = approved.length > 0 && approved.every((part) => {
2207
+ const tool7 = tools[getToolName(part)];
2208
+ return tool7?.recovery === "idempotent" && typeof tool7.execute === "function";
2209
+ });
2210
+ if (!retryable) return false;
2211
+ await this.#queue.push({
2212
+ kind: "continuation",
2213
+ streamId,
2214
+ chatId: conversation.chatId,
2215
+ userId: conversation.userId,
2216
+ recovery: "idempotent"
2217
+ });
2218
+ return true;
2219
+ }
2220
+ async applyDecision(turn) {
2221
+ const engine = this.#engineFor(turn);
2222
+ const head = (await engine.getMessages()).at(-1);
2223
+ if (head?.role !== "assistant" || head.id !== turn.streamId) return false;
2224
+ const part = this.#findToolPart(head, turn.toolCallId);
2225
+ if (part?.approval?.id !== turn.approvalId) return false;
2226
+ if (part.approval.approved !== void 0) return false;
2227
+ if (part.state !== "approval-requested") return false;
2228
+ const responded = {
2229
+ ...part,
2230
+ state: "approval-responded",
2231
+ approval: { ...part.approval, ...turn.decision }
2232
+ };
2233
+ const updated = {
2234
+ ...head,
2235
+ parts: head.parts.map(
2236
+ (candidate) => candidate === part ? responded : candidate
2237
+ )
2238
+ };
2239
+ await engine.continue(assistant2(updated));
2240
+ return !this.#hasUnansweredApprovals(updated);
2241
+ }
2242
+ async recoverUnstartedContinuation(turn, streamId) {
2243
+ if (turn.kind === "approval") await this.applyDecision(turn);
2244
+ const head = (await this.#engineFor(turn).getMessages()).at(-1);
2245
+ if (head?.role !== "assistant" || head.id !== streamId || this.#hasUnansweredApprovals(head) || !head.parts.some(
2246
+ (part) => isToolUIPart(part) && part.state === "approval-responded"
2247
+ )) {
2248
+ return false;
1512
2249
  }
1513
- return { id: result.id, stream: this.#streams.watch(result.id) };
2250
+ await this.#queue.push({
2251
+ kind: "continuation",
2252
+ streamId,
2253
+ chatId: turn.chatId,
2254
+ userId: turn.userId,
2255
+ recovery: "handoff"
2256
+ });
2257
+ return true;
1514
2258
  }
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;
2259
+ async #respond(operation, conversation, toolCallId, approval) {
2260
+ const head = (await this.#engineFor(conversation).getMessages()).at(-1);
2261
+ if (head?.role !== "assistant") {
2262
+ throw new Error(
2263
+ `ApprovalController.${operation}: no paused turn \u2014 the chain head is not an assistant message`
2264
+ );
2265
+ }
2266
+ const part = this.#findToolPart(head, toolCallId);
2267
+ if (!part) {
2268
+ throw new Error(
2269
+ `ApprovalController.${operation}: no tool call "${toolCallId}" on the paused turn`
2270
+ );
2271
+ }
2272
+ if (!part.approval) {
2273
+ throw new Error(
2274
+ `ApprovalController.${operation}: tool call "${toolCallId}" is not awaiting approval`
2275
+ );
2276
+ }
2277
+ const jobId = approvalJobId(conversation, part.approval.id);
2278
+ if (part.approval.approved !== void 0) {
2279
+ if (part.approval.approved !== approval.approved) {
2280
+ throw new Error(
2281
+ `ApprovalController.${operation}: approval already answered with a different decision`
2282
+ );
1524
2283
  }
1525
- } else if (status !== "queued" && status !== "running") {
1526
- return;
2284
+ return { id: head.id, jobId, status: "already-applied" };
1527
2285
  }
1528
- if (status !== "running") {
1529
- await this.#queue.push({
1530
- kind: "continuation",
1531
- streamId,
1532
- chatId: conversation.chatId,
1533
- userId: conversation.userId
1534
- });
2286
+ if (part.state !== "approval-requested") {
2287
+ throw new Error(
2288
+ `ApprovalController.${operation}: tool call "${toolCallId}" is not awaiting approval`
2289
+ );
1535
2290
  }
1536
- await this.#queue.resumeParked(conversation.chatId);
2291
+ const result = await this.#queue.push({
2292
+ kind: "approval",
2293
+ streamId: head.id,
2294
+ chatId: conversation.chatId,
2295
+ userId: conversation.userId,
2296
+ toolCallId,
2297
+ approvalId: part.approval.id,
2298
+ decision: approval
2299
+ });
2300
+ return {
2301
+ id: head.id,
2302
+ jobId,
2303
+ status: result.inserted ? "queued" : "already-queued"
2304
+ };
1537
2305
  }
1538
2306
  #pendingToolPart(message) {
1539
2307
  return message.parts.find(
@@ -1555,83 +2323,7 @@ var ApprovalController = class _ApprovalController {
1555
2323
  }
1556
2324
  };
1557
2325
 
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
2326
+ // packages/experimental/src/zukhruf/runtime/agent-runtime.ts
1635
2327
  var AgentObservation = class {
1636
2328
  engine;
1637
2329
  #conversation;
@@ -1684,12 +2376,10 @@ var AgentRuntime = class {
1684
2376
  #approvals;
1685
2377
  #executor;
1686
2378
  constructor(root, options) {
2379
+ const multiAgentV2 = resolveMultiAgentV2HostConfig(options.multiAgentV2);
1687
2380
  const declarations = new AgentDeclarationRegistry(root);
1688
2381
  const directory = new AgentDirectory(options.store);
1689
- const streams = new StreamManager({
1690
- store: options.streamStore,
1691
- changeSource: new PollingChangeSource({ reads: options.streamStore })
1692
- });
2382
+ const streams = options.streams;
1693
2383
  const mailbox = new MailboxCoordinator({
1694
2384
  store: options.mailboxStore,
1695
2385
  queue: options.queue,
@@ -1697,9 +2387,7 @@ var AgentRuntime = class {
1697
2387
  });
1698
2388
  const approvals = new ApprovalController({
1699
2389
  store: options.store,
1700
- streams,
1701
- queue: options.queue,
1702
- mutex: options.approvalMutex
2390
+ queue: options.queue
1703
2391
  });
1704
2392
  const statusProjector = new AgentStatusProjector({
1705
2393
  store: options.store,
@@ -1709,6 +2397,7 @@ var AgentRuntime = class {
1709
2397
  directory,
1710
2398
  approvals
1711
2399
  });
2400
+ const historyForker = new AgentHistoryForker(options.store);
1712
2401
  const controlPlane = new AgentControlPlane({
1713
2402
  root,
1714
2403
  streams,
@@ -1716,7 +2405,8 @@ var AgentRuntime = class {
1716
2405
  mailbox,
1717
2406
  declarations,
1718
2407
  directory,
1719
- statusProjector
2408
+ statusProjector,
2409
+ historyForker
1720
2410
  });
1721
2411
  this.#store = options.store;
1722
2412
  this.#queue = options.queue;
@@ -1730,7 +2420,8 @@ var AgentRuntime = class {
1730
2420
  streams,
1731
2421
  controlPlane,
1732
2422
  mailbox,
1733
- approvals
2423
+ approvals,
2424
+ multiAgentV2
1734
2425
  });
1735
2426
  }
1736
2427
  async enqueue(conversation, turn) {
@@ -1766,7 +2457,28 @@ var AgentRuntime = class {
1766
2457
  });
1767
2458
  stream = await this.#streams.store.getStream(turn.streamId);
1768
2459
  }
1769
- if (turn.kind === "continuation" && (stream?.status === "completed" || stream?.status === "failed" || stream?.status === "cancelled")) {
2460
+ let declaration;
2461
+ if ((turn.kind === "approval" || turn.kind === "continuation" && turn.recovery !== "idempotent") && stream?.status === "failed") {
2462
+ try {
2463
+ ({ declaration } = await this.#controlPlane.resolve(turn));
2464
+ } catch {
2465
+ }
2466
+ }
2467
+ if (declaration !== void 0 && await this.#approvals.retryIdempotentContinuation(
2468
+ turn,
2469
+ turn.streamId,
2470
+ declaration.tools ?? {}
2471
+ )) {
2472
+ return;
2473
+ }
2474
+ if ((turn.kind === "approval" || turn.kind === "continuation") && stream?.status === "completed" && await this.#approvals.recoverUnstartedContinuation(
2475
+ turn,
2476
+ turn.streamId
2477
+ )) {
2478
+ return;
2479
+ }
2480
+ stream = await this.#streams.store.getStream(turn.streamId);
2481
+ if ((turn.kind === "approval" || turn.kind === "continuation") && (stream?.status === "completed" || stream?.status === "failed" || stream?.status === "cancelled")) {
1770
2482
  await this.#approvals.reconcileTerminalContinuation(
1771
2483
  turn,
1772
2484
  turn.streamId,
@@ -1785,7 +2497,7 @@ var AgentRuntime = class {
1785
2497
  await this.#controlPlane.projectTerminal(turn, thread);
1786
2498
  } finally {
1787
2499
  try {
1788
- if (turn.kind === "continuation") {
2500
+ if (turn.kind === "approval" || turn.kind === "continuation") {
1789
2501
  await this.#queue.resumeParked(turn.chatId);
1790
2502
  }
1791
2503
  } finally {
@@ -1795,10 +2507,6 @@ var AgentRuntime = class {
1795
2507
  }
1796
2508
  };
1797
2509
 
1798
- // packages/experimental/src/zukhruf/approval-mutex.ts
1799
- var ApprovalMutex = class {
1800
- };
1801
-
1802
2510
  // packages/experimental/src/zukhruf/instructions.ts
1803
2511
  function defineInstructions(...fragments) {
1804
2512
  return fragments;
@@ -2010,17 +2718,39 @@ var TurnQueue = class {
2010
2718
  };
2011
2719
 
2012
2720
  // packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
2721
+ var MAX_TIMEOUT_MS = 2147483647;
2013
2722
  var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
2014
2723
  #boss;
2015
2724
  #queue;
2725
+ #schema;
2726
+ #schemaConfigurationError;
2727
+ #table;
2016
2728
  #expireInSeconds;
2729
+ #cancelIntentTtlMs;
2017
2730
  #heartbeatSeconds;
2018
2731
  #pollingIntervalSeconds;
2732
+ #active = /* @__PURE__ */ new Map();
2733
+ #cancelIntents = /* @__PURE__ */ new Map();
2734
+ #cancelIntentExpiryTimer;
2019
2735
  constructor(boss, options = {}) {
2020
2736
  super();
2021
2737
  this.#boss = boss;
2022
2738
  this.#queue = options.queue ?? "zukhruf-turns";
2739
+ const configuredSchema = boss.getDb().config?.schema;
2740
+ const bossSchema = typeof configuredSchema === "string" ? configuredSchema : void 0;
2741
+ this.#schema = options.schema ?? bossSchema ?? "pgboss";
2742
+ if (options.schema === void 0 && bossSchema === void 0) {
2743
+ this.#schemaConfigurationError = "PgBossTurnQueue cannot read the schema from a custom PgBoss database adapter; pass the PgBoss schema in options.schema";
2744
+ } else if (options.schema !== void 0 && bossSchema !== void 0 && options.schema !== bossSchema) {
2745
+ this.#schemaConfigurationError = `PgBossTurnQueue schema "${options.schema}" does not match the PgBoss schema "${bossSchema}"`;
2746
+ }
2023
2747
  this.#expireInSeconds = options.expireInSeconds ?? 3600;
2748
+ this.#cancelIntentTtlMs = this.#expireInSeconds * 1e3;
2749
+ if (!Number.isFinite(this.#expireInSeconds) || this.#expireInSeconds <= 0 || !Number.isSafeInteger(this.#cancelIntentTtlMs) || this.#cancelIntentTtlMs > Number.MAX_SAFE_INTEGER - Date.now()) {
2750
+ throw new Error(
2751
+ "PgBossTurnQueue expireInSeconds must be a finite positive duration"
2752
+ );
2753
+ }
2024
2754
  this.#heartbeatSeconds = options.heartbeatSeconds ?? 30;
2025
2755
  this.#pollingIntervalSeconds = options.pollingIntervalSeconds ?? 1;
2026
2756
  }
@@ -2031,10 +2761,14 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
2031
2761
  return `${this.#queue}-dead`;
2032
2762
  }
2033
2763
  async initialize() {
2764
+ if (this.#schemaConfigurationError) {
2765
+ throw new Error(this.#schemaConfigurationError);
2766
+ }
2034
2767
  if (!await this.#boss.getQueue(this.deadLetterQueue)) {
2035
2768
  await this.#boss.createQueue(this.deadLetterQueue);
2036
2769
  }
2037
- if (!await this.#boss.getQueue(this.#queue)) {
2770
+ let queue = await this.#boss.getQueue(this.#queue);
2771
+ if (!queue) {
2038
2772
  await this.#boss.createQueue(this.#queue, {
2039
2773
  policy: "key_strict_fifo",
2040
2774
  retryLimit: 0,
@@ -2043,14 +2777,40 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
2043
2777
  deleteAfterSeconds: 0,
2044
2778
  deadLetter: this.deadLetterQueue
2045
2779
  });
2780
+ queue = await this.#boss.getQueue(this.#queue);
2781
+ }
2782
+ if (!queue) throw new Error(`Queue "${this.#queue}" was not initialized`);
2783
+ this.#table = queue.table;
2784
+ try {
2785
+ const catalog = await this.#boss.getDb().executeSql(
2786
+ `SELECT table_name AS "table"
2787
+ FROM ${_PgBossTurnQueue.#quoteIdentifier(this.#schema)}."queue"
2788
+ WHERE name = $1`,
2789
+ [this.#queue]
2790
+ );
2791
+ if (catalog.rows.length !== 1 || catalog.rows[0].table !== this.#table) {
2792
+ throw new Error("queue catalog does not match");
2793
+ }
2794
+ await this.#boss.getDb().executeSql(`SELECT 1 FROM ${this.#relation()} WHERE false`);
2795
+ } catch (cause) {
2796
+ throw new Error(
2797
+ `PgBossTurnQueue schema "${this.#schema}" does not match the PgBoss queue; pass the PgBoss schema in options.schema`,
2798
+ { cause }
2799
+ );
2046
2800
  }
2047
2801
  }
2048
2802
  async push(turn) {
2049
- await this.#boss.send(this.#queue, turn, {
2050
- id: uuidv7(),
2803
+ const jobId = turn.kind === "approval" ? approvalJobId(turn, turn.approvalId) : uuidv7();
2804
+ const inserted = await this.#boss.send(this.#queue, turn, {
2805
+ id: jobId,
2051
2806
  singletonKey: turn.chatId,
2052
- priority: turn.kind === "continuation" ? 1 : 0
2807
+ group: { id: turn.chatId },
2808
+ priority: turn.kind === "approval" || turn.kind === "continuation" ? 1 : 0
2053
2809
  });
2810
+ if (inserted === null && turn.kind !== "approval") {
2811
+ throw new Error(`PgBossTurnQueue job id collision: ${jobId}`);
2812
+ }
2813
+ return { jobId, inserted: inserted !== null };
2054
2814
  }
2055
2815
  async getTurnActivity(conversation) {
2056
2816
  const jobs = await this.#boss.findJobs(this.#queue, {
@@ -2064,26 +2824,64 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
2064
2824
  }
2065
2825
  return conversationJobs.length > 0 ? "queued" : "idle";
2066
2826
  }
2827
+ async getCurrentTurn(conversation) {
2828
+ const jobs = await this.#boss.findJobs(this.#queue, {
2829
+ key: conversation.chatId
2830
+ });
2831
+ return jobs.filter(
2832
+ (job) => job.data.userId === conversation.userId && (job.state === "active" || job.state === "created" || job.state === "retry")
2833
+ ).sort(_PgBossTurnQueue.#interruptOrder)[0]?.data;
2834
+ }
2835
+ async cancel(streamId) {
2836
+ this.#rememberCancelIntent(streamId);
2837
+ this.#abortLocal(streamId);
2838
+ const jobs = await this.#boss.findJobs(this.#queue, {
2839
+ data: { streamId }
2840
+ });
2841
+ const queued = jobs.filter((job) => job.state === "created" || job.state === "retry").map((job) => job.id);
2842
+ if (queued.length > 0) await this.#deleteIfStillQueued(queued);
2843
+ this.#abortLocal(streamId);
2844
+ const remaining = await this.#boss.findJobs(this.#queue, {
2845
+ data: { streamId }
2846
+ });
2847
+ if (!remaining.some((job) => job.state === "active")) {
2848
+ this.#forgetCancelIntent(streamId);
2849
+ }
2850
+ }
2067
2851
  async consume(handler, options) {
2068
2852
  const turnWorkerId = await this.#boss.work(
2069
2853
  this.#queue,
2070
2854
  {
2071
2855
  localConcurrency: options.concurrency ?? 1,
2856
+ groupConcurrency: 1,
2072
2857
  pollingIntervalSeconds: this.#pollingIntervalSeconds
2073
2858
  },
2074
2859
  async ([job]) => {
2075
2860
  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);
2861
+ const localAbort = new AbortController();
2862
+ const active = this.#active.get(job.data.streamId) ?? /* @__PURE__ */ new Set();
2863
+ active.add(localAbort);
2864
+ this.#active.set(job.data.streamId, active);
2865
+ if (this.#hasCancelIntent(job.data.streamId)) localAbort.abort();
2866
+ try {
2867
+ await handler(job.data, {
2868
+ signal: AbortSignal.any([job.signal, localAbort.signal]),
2869
+ // Parking = self-cancel: a cancelled job stops blocking the chat's
2870
+ // key and is revived (original created_on, so original order) by
2871
+ // resumeParked(). The worker's completion of a cancelled job is a
2872
+ // clean no-op (probe-verified).
2873
+ park: async () => {
2874
+ parked = true;
2875
+ await this.#boss.cancel(this.#queue, job.id);
2876
+ }
2877
+ });
2878
+ } finally {
2879
+ active.delete(localAbort);
2880
+ if (active.size === 0) {
2881
+ this.#active.delete(job.data.streamId);
2882
+ this.#forgetCancelIntent(job.data.streamId);
2085
2883
  }
2086
- });
2884
+ }
2087
2885
  if (!parked) {
2088
2886
  await this.#boss.deleteJob(this.#queue, job.id);
2089
2887
  }
@@ -2122,14 +2920,162 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
2122
2920
  await this.#boss.resume(this.#queue, parked);
2123
2921
  }
2124
2922
  }
2923
+ #abortLocal(streamId) {
2924
+ for (const controller of this.#active.get(streamId) ?? []) {
2925
+ controller.abort();
2926
+ }
2927
+ }
2928
+ #rememberCancelIntent(streamId) {
2929
+ this.#pruneCancelIntents();
2930
+ this.#cancelIntents.set(streamId, Date.now() + this.#cancelIntentTtlMs);
2931
+ this.#scheduleCancelIntentExpiry();
2932
+ }
2933
+ #hasCancelIntent(streamId) {
2934
+ this.#pruneCancelIntents();
2935
+ return this.#cancelIntents.has(streamId);
2936
+ }
2937
+ #pruneCancelIntents() {
2938
+ const now = Date.now();
2939
+ for (const [streamId, expiresAt] of this.#cancelIntents) {
2940
+ if (expiresAt <= now) this.#cancelIntents.delete(streamId);
2941
+ }
2942
+ this.#scheduleCancelIntentExpiry();
2943
+ }
2944
+ #forgetCancelIntent(streamId) {
2945
+ this.#cancelIntents.delete(streamId);
2946
+ this.#scheduleCancelIntentExpiry();
2947
+ }
2948
+ #scheduleCancelIntentExpiry() {
2949
+ if (this.#cancelIntentExpiryTimer !== void 0) {
2950
+ globalThis.clearTimeout(this.#cancelIntentExpiryTimer);
2951
+ this.#cancelIntentExpiryTimer = void 0;
2952
+ }
2953
+ let nextExpiry = Number.POSITIVE_INFINITY;
2954
+ for (const expiresAt of this.#cancelIntents.values()) {
2955
+ nextExpiry = Math.min(nextExpiry, expiresAt);
2956
+ }
2957
+ if (!Number.isFinite(nextExpiry)) return;
2958
+ const timer = globalThis.setTimeout(
2959
+ () => {
2960
+ if (this.#cancelIntentExpiryTimer !== timer) return;
2961
+ this.#cancelIntentExpiryTimer = void 0;
2962
+ this.#pruneCancelIntents();
2963
+ },
2964
+ Math.min(MAX_TIMEOUT_MS, Math.max(1, nextExpiry - Date.now()))
2965
+ );
2966
+ this.#cancelIntentExpiryTimer = timer;
2967
+ timer.unref?.();
2968
+ }
2969
+ async #deleteIfStillQueued(ids) {
2970
+ if (!this.#table) {
2971
+ throw new Error("PgBossTurnQueue.initialize() must run before cancel()");
2972
+ }
2973
+ await this.#boss.getDb().executeSql(
2974
+ `DELETE FROM ${this.#relation()}
2975
+ WHERE name = $1
2976
+ AND id = ANY($2::uuid[])
2977
+ AND state IN ('created', 'retry')`,
2978
+ [this.#queue, ids]
2979
+ );
2980
+ }
2981
+ #relation() {
2982
+ if (!this.#table) {
2983
+ throw new Error(
2984
+ "PgBossTurnQueue.initialize() must resolve its job table"
2985
+ );
2986
+ }
2987
+ return `${_PgBossTurnQueue.#quoteIdentifier(this.#schema)}.${_PgBossTurnQueue.#quoteIdentifier(this.#table)}`;
2988
+ }
2989
+ static #quoteIdentifier(identifier) {
2990
+ return `"${identifier.replaceAll('"', '""')}"`;
2991
+ }
2125
2992
  static #orphanError(output) {
2126
2993
  if (output && "message" in output && typeof output.message === "string") {
2127
2994
  return output.message;
2128
2995
  }
2129
2996
  return output ? JSON.stringify(output) : "turn orphaned";
2130
2997
  }
2998
+ static #interruptOrder(left, right) {
2999
+ if (left.state === "active" && right.state !== "active") return -1;
3000
+ if (left.state !== "active" && right.state === "active") return 1;
3001
+ if (left.priority !== right.priority) return right.priority - left.priority;
3002
+ const created = left.createdOn.getTime() - right.createdOn.getTime();
3003
+ return created || left.id.localeCompare(right.id);
3004
+ }
2131
3005
  };
2132
3006
 
3007
+ // packages/experimental/src/zukhruf/render-turn.ts
3008
+ import { styleText } from "node:util";
3009
+ var dim = (text) => styleText("dim", text);
3010
+ var red = (text) => styleText("red", text);
3011
+ function oneLine(value, max = 88) {
3012
+ const text = String(value ?? "").replaceAll(/\s+/g, " ").trim();
3013
+ return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
3014
+ }
3015
+ function describeToolCall(toolName, input) {
3016
+ const args = input ?? {};
3017
+ switch (toolName) {
3018
+ case "spawn_agent":
3019
+ return `\u21C4 spawn ${args.agent_type} "${args.task_name}" \u2014 ${args.message}`;
3020
+ case "send_message":
3021
+ return `\u21C4 mail ${args.target} \u2014 ${args.message}`;
3022
+ case "followup_task":
3023
+ return `\u21C4 follow-up ${args.target} \u2014 ${args.message}`;
3024
+ case "list_agents":
3025
+ return "\u21C4 list agents";
3026
+ default:
3027
+ return `\xB7 ${toolName}`;
3028
+ }
3029
+ }
3030
+ async function renderTurn(stream) {
3031
+ const toolNames = /* @__PURE__ */ new Map();
3032
+ let midText = false;
3033
+ let thinkingShown = false;
3034
+ const breakText = () => {
3035
+ if (midText) process.stdout.write("\n");
3036
+ midText = false;
3037
+ };
3038
+ for await (const chunk of stream) {
3039
+ switch (chunk.type) {
3040
+ case "reasoning-start":
3041
+ if (!thinkingShown) {
3042
+ console.log(dim("\u2026"));
3043
+ thinkingShown = true;
3044
+ }
3045
+ break;
3046
+ case "text-delta":
3047
+ process.stdout.write(chunk.delta);
3048
+ midText = true;
3049
+ break;
3050
+ case "text-end":
3051
+ breakText();
3052
+ break;
3053
+ case "tool-input-available":
3054
+ toolNames.set(chunk.toolCallId, chunk.toolName);
3055
+ breakText();
3056
+ console.log(dim(describeToolCall(chunk.toolName, chunk.input)));
3057
+ break;
3058
+ case "tool-output-error":
3059
+ breakText();
3060
+ console.log(
3061
+ red(
3062
+ `\u2717 ${toolNames.get(chunk.toolCallId) ?? "tool"}: ${oneLine(chunk.errorText)}`
3063
+ )
3064
+ );
3065
+ break;
3066
+ case "error":
3067
+ breakText();
3068
+ console.log(red(`\u2717 ${oneLine(chunk.errorText)}`));
3069
+ break;
3070
+ case "abort":
3071
+ breakText();
3072
+ console.log(dim("\xB7 turn aborted"));
3073
+ break;
3074
+ }
3075
+ }
3076
+ breakText();
3077
+ }
3078
+
2133
3079
  // packages/experimental/src/zukhruf/sandbox/define.ts
2134
3080
  import {
2135
3081
  createBashTool
@@ -2138,75 +3084,11 @@ function defineSandbox(createBackend, options) {
2138
3084
  return async (context) => createBashTool({ sandbox: await createBackend(context), ...options });
2139
3085
  }
2140
3086
 
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
- `);
2160
- }
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 {
2180
- }
2181
- throw error;
2182
- }
2183
- } finally {
2184
- release();
2185
- }
2186
- }
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
- };
2207
-
2208
3087
  // packages/experimental/src/zukhruf/tool.ts
2209
- import { tool as tool4 } from "ai";
3088
+ import { tool as tool6 } from "ai";
3089
+ function defineTool(definition) {
3090
+ return tool6(definition);
3091
+ }
2210
3092
  export {
2211
3093
  coding_agent_reminders_exports as codingAgentReminders,
2212
3094
  zukhruf_exports as zukhruf