@deepagents/experimental 7.0.2 → 7.1.1

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 (76) hide show
  1. package/README.md +8 -4
  2. package/dist/coding-agent-reminders/evaluate.d.ts.map +1 -1
  3. package/dist/coding-agent-reminders/index.js +2 -2
  4. package/dist/coding-agent-reminders/index.js.map +2 -2
  5. package/dist/index.js +233 -180
  6. package/dist/index.js.map +3 -3
  7. package/dist/providers/account-tokens.d.ts +45 -0
  8. package/dist/providers/account-tokens.d.ts.map +1 -0
  9. package/dist/providers/claude/accounts.d.ts +59 -0
  10. package/dist/providers/claude/accounts.d.ts.map +1 -0
  11. package/dist/providers/claude/errors.d.ts +7 -0
  12. package/dist/providers/claude/errors.d.ts.map +1 -0
  13. package/dist/providers/claude/index.d.ts +2 -0
  14. package/dist/providers/claude/index.d.ts.map +1 -1
  15. package/dist/providers/claude/index.js +540 -52
  16. package/dist/providers/claude/index.js.map +4 -4
  17. package/dist/providers/claude/local-credentials.d.ts.map +1 -1
  18. package/dist/providers/claude/oauth.d.ts +3 -0
  19. package/dist/providers/claude/oauth.d.ts.map +1 -0
  20. package/dist/providers/claude/provider.d.ts +4 -0
  21. package/dist/providers/claude/provider.d.ts.map +1 -0
  22. package/dist/providers/codex/accounts.d.ts +39 -0
  23. package/dist/providers/codex/accounts.d.ts.map +1 -0
  24. package/dist/providers/codex/errors.d.ts +7 -0
  25. package/dist/providers/codex/errors.d.ts.map +1 -0
  26. package/dist/providers/codex/index.d.ts +2 -0
  27. package/dist/providers/codex/index.d.ts.map +1 -1
  28. package/dist/providers/codex/index.js +472 -168
  29. package/dist/providers/codex/index.js.map +4 -4
  30. package/dist/providers/codex/local-credentials.d.ts.map +1 -1
  31. package/dist/providers/codex/provider.d.ts +3 -0
  32. package/dist/providers/codex/provider.d.ts.map +1 -0
  33. package/dist/providers/request-signal.d.ts +2 -0
  34. package/dist/providers/request-signal.d.ts.map +1 -0
  35. package/dist/zukhruf/control-plane/agent-control-plane.d.ts.map +1 -1
  36. package/dist/zukhruf/control-plane/agent-history-forker.d.ts.map +1 -1
  37. package/dist/zukhruf/index.js +231 -178
  38. package/dist/zukhruf/index.js.map +3 -3
  39. package/dist/zukhruf/mailbox/coordinator.d.ts.map +1 -1
  40. package/dist/zukhruf/mailbox/sqlite.store.d.ts.map +1 -1
  41. package/dist/zukhruf/mailbox/types.d.ts +4 -4
  42. package/dist/zukhruf/mailbox/types.d.ts.map +1 -1
  43. package/dist/zukhruf/plugins/conversation-scheduling/conversation-scheduler.d.ts.map +1 -1
  44. package/dist/zukhruf/plugins/conversation-scheduling/index.js +18 -2
  45. package/dist/zukhruf/plugins/conversation-scheduling/index.js.map +2 -2
  46. package/dist/zukhruf/plugins/http/index.js +16 -17
  47. package/dist/zukhruf/plugins/http/index.js.map +3 -3
  48. package/dist/zukhruf/plugins/http/validator.d.ts +14 -44
  49. package/dist/zukhruf/plugins/http/validator.d.ts.map +1 -1
  50. package/dist/zukhruf/plugins/schedules/http.d.ts.map +1 -1
  51. package/dist/zukhruf/plugins/schedules/http.js +22 -22
  52. package/dist/zukhruf/plugins/schedules/http.js.map +3 -3
  53. package/dist/zukhruf/plugins/schedules/index.d.ts.map +1 -1
  54. package/dist/zukhruf/plugins/schedules/index.js +173 -51
  55. package/dist/zukhruf/plugins/schedules/index.js.map +3 -3
  56. package/dist/zukhruf/plugins/schedules/scheduled-tasks.d.ts +3 -0
  57. package/dist/zukhruf/plugins/schedules/scheduled-tasks.d.ts.map +1 -1
  58. package/dist/zukhruf/plugins/uploads/http.js +17 -20
  59. package/dist/zukhruf/plugins/uploads/http.js.map +3 -3
  60. package/dist/zukhruf/plugins/uploads/index.d.ts.map +1 -1
  61. package/dist/zukhruf/plugins/uploads/index.js +1 -3
  62. package/dist/zukhruf/plugins/uploads/index.js.map +2 -2
  63. package/dist/zukhruf/queue/pg-boss-notifications.d.ts.map +1 -1
  64. package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts.map +1 -1
  65. package/dist/zukhruf/render-turn.d.ts.map +1 -1
  66. package/dist/zukhruf/runtime/agent-runtime.d.ts +3 -0
  67. package/dist/zukhruf/runtime/agent-runtime.d.ts.map +1 -1
  68. package/dist/zukhruf/runtime/agent-turn-executor.d.ts.map +1 -1
  69. package/dist/zukhruf/runtime/compaction.d.ts +4 -4
  70. package/dist/zukhruf/runtime/compaction.d.ts.map +1 -1
  71. package/dist/zukhruf/runtime/conversation-status/projector.d.ts.map +1 -1
  72. package/dist/zukhruf/runtime/plugin/plugin-bindings.d.ts.map +1 -1
  73. package/dist/zukhruf/runtime/plugin/plugin-manager.d.ts.map +1 -1
  74. package/dist/zukhruf/tool.d.ts +1 -1
  75. package/dist/zukhruf/tool.d.ts.map +1 -1
  76. package/package.json +10 -10
package/dist/index.js CHANGED
@@ -76,7 +76,7 @@ async function firstMatchingGuard(input, guards) {
76
76
  async function matchingReminders(input, reminders) {
77
77
  const matched = [];
78
78
  for (const rule of reminders) {
79
- if (!rule.events.includes(input.hook_event_name)) continue;
79
+ if (!rule.events.some((event) => event === input.hook_event_name)) continue;
80
80
  try {
81
81
  if (!await rule.when(input)) continue;
82
82
  matched.push(
@@ -262,7 +262,7 @@ function checkCount(count, spec) {
262
262
  var envFlag = (name) => () => process.env[name] === "1" || process.env[name] === "true";
263
263
 
264
264
  // packages/experimental/src/coding-agent-reminders/predicates/event.ts
265
- var eventIs = (...events) => (ctx) => events.includes(ctx.hook_event_name);
265
+ var eventIs = (...events) => (ctx) => events.some((event) => event === ctx.hook_event_name);
266
266
 
267
267
  // packages/experimental/src/coding-agent-reminders/predicates/tool.ts
268
268
  var toolIs = (name) => (ctx) => ctx.tool_name === name;
@@ -326,9 +326,9 @@ __export(zukhruf_exports, {
326
326
  AgentRuntime: () => AgentRuntime,
327
327
  AgentThread: () => AgentThread,
328
328
  DEFAULT_CONVERSATION_STATUS_CHANNEL: () => DEFAULT_CONVERSATION_STATUS_CHANNEL,
329
- InterAgentCommunicationType: () => InterAgentCommunicationType,
329
+ InterAgentCommunicationTypes: () => InterAgentCommunicationTypes,
330
330
  MailboxStore: () => MailboxStore,
331
- MessageDeliveryMode: () => MessageDeliveryMode,
331
+ MessageDeliveryModes: () => MessageDeliveryModes,
332
332
  PgBossConversationStatusChangeSource: () => PgBossConversationStatusChangeSource,
333
333
  PgBossTurnQueue: () => PgBossTurnQueue,
334
334
  SqliteMailboxStore: () => SqliteMailboxStore,
@@ -534,6 +534,7 @@ function defineInstructions(...fragments) {
534
534
 
535
535
  // packages/experimental/src/zukhruf/mailbox/sqlite.store.ts
536
536
  import { DatabaseSync } from "node:sqlite";
537
+ import { z } from "zod";
537
538
 
538
539
  // packages/experimental/src/zukhruf/mailbox/store.ts
539
540
  var MailboxStore = class {
@@ -541,11 +542,11 @@ var MailboxStore = class {
541
542
 
542
543
  // packages/experimental/src/zukhruf/mailbox/types.ts
543
544
  import { randomUUID } from "node:crypto";
544
- var MessageDeliveryMode = {
545
+ var MessageDeliveryModes = {
545
546
  QueueOnly: "queue-only",
546
547
  TriggerTurn: "trigger-turn"
547
548
  };
548
- var InterAgentCommunicationType = {
549
+ var InterAgentCommunicationTypes = {
549
550
  Message: "MESSAGE",
550
551
  NewTask: "NEW_TASK",
551
552
  FinalAnswer: "FINAL_ANSWER"
@@ -554,7 +555,7 @@ function createInterAgentCommunication(communication) {
554
555
  const value = {
555
556
  ...communication,
556
557
  id: communication.id ?? randomUUID(),
557
- type: communication.type ?? InterAgentCommunicationType.Message,
558
+ type: communication.type ?? InterAgentCommunicationTypes.Message,
558
559
  otherRecipients: communication.otherRecipients ?? [],
559
560
  triggerTurn: false
560
561
  };
@@ -565,7 +566,7 @@ function assertCommunication(communication) {
565
566
  if (!communication.id.trim()) {
566
567
  throw new Error("inter-agent communication id cannot be empty");
567
568
  }
568
- if (!Object.values(InterAgentCommunicationType).includes(communication.type)) {
569
+ if (!Object.values(InterAgentCommunicationTypes).includes(communication.type)) {
569
570
  throw new Error("inter-agent communication type is invalid");
570
571
  }
571
572
  assertConversationId(communication.author, "author");
@@ -621,6 +622,26 @@ var DDL = `
621
622
  );
622
623
  `;
623
624
  var BUSY_TIMEOUT_MS = 5e3;
625
+ var conversationIdSchema = z.object({
626
+ chatId: z.string(),
627
+ userId: z.string()
628
+ });
629
+ var communicationSchema = z.object({
630
+ id: z.string(),
631
+ type: z.enum(InterAgentCommunicationTypes),
632
+ author: conversationIdSchema,
633
+ recipient: conversationIdSchema,
634
+ otherRecipients: z.array(conversationIdSchema),
635
+ content: z.string(),
636
+ metadata: z.record(z.string(), z.unknown()).optional(),
637
+ triggerTurn: z.boolean()
638
+ });
639
+ var mailboxItemRowsSchema = z.array(
640
+ z.object({
641
+ sequence: z.number(),
642
+ communication: z.string().transform((text) => JSON.parse(text)).pipe(communicationSchema)
643
+ })
644
+ );
624
645
  var SqliteMailboxStore = class extends MailboxStore {
625
646
  #database;
626
647
  #closed = false;
@@ -644,7 +665,7 @@ var SqliteMailboxStore = class extends MailboxStore {
644
665
  }
645
666
  async enqueue(communication) {
646
667
  return this.#transaction(() => {
647
- const consumedTerminal = communication.type === InterAgentCommunicationType.FinalAnswer && this.#hasConsumedTerminal(communication.id);
668
+ const consumedTerminal = communication.type === InterAgentCommunicationTypes.FinalAnswer && this.#hasConsumedTerminal(communication.id);
648
669
  if (!consumedTerminal) {
649
670
  this.#database.prepare(
650
671
  `INSERT OR IGNORE INTO zukhruf_mailbox_items (
@@ -717,17 +738,15 @@ var SqliteMailboxStore = class extends MailboxStore {
717
738
  }
718
739
  #drain(recipient, leadingQueueOnly) {
719
740
  return this.#transaction(() => {
720
- const rows = this.#database.prepare(
721
- `SELECT sequence, communication
722
- FROM zukhruf_mailbox_items
723
- WHERE recipient_chat_id = ?
724
- AND recipient_user_id = ?
725
- ORDER BY sequence`
726
- ).all(recipient.chatId, recipient.userId);
727
- const items = rows.map((row) => ({
728
- sequence: row.sequence,
729
- communication: JSON.parse(row.communication)
730
- }));
741
+ const items = mailboxItemRowsSchema.parse(
742
+ this.#database.prepare(
743
+ `SELECT sequence, communication
744
+ FROM zukhruf_mailbox_items
745
+ WHERE recipient_chat_id = ?
746
+ AND recipient_user_id = ?
747
+ ORDER BY sequence`
748
+ ).all(recipient.chatId, recipient.userId)
749
+ );
731
750
  const firstTrigger = leadingQueueOnly ? items.findIndex(({ communication }) => communication.triggerTurn) : -1;
732
751
  const consumed = firstTrigger === -1 ? items : items.slice(0, firstTrigger);
733
752
  const lastConsumed = consumed.at(-1);
@@ -738,7 +757,7 @@ var SqliteMailboxStore = class extends MailboxStore {
738
757
  VALUES (?)`
739
758
  );
740
759
  for (const { communication } of consumed) {
741
- if (communication.type === InterAgentCommunicationType.FinalAnswer) {
760
+ if (communication.type === InterAgentCommunicationTypes.FinalAnswer) {
742
761
  tombstone.run(communication.id);
743
762
  }
744
763
  }
@@ -778,6 +797,8 @@ var SqliteMailboxStore = class extends MailboxStore {
778
797
 
779
798
  // packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
780
799
  import { v7 as uuidv7 } from "uuid";
800
+ import { z as z2 } from "zod";
801
+ import { isRecord } from "@deepagents/context";
781
802
 
782
803
  // packages/experimental/src/zukhruf/queue/turn-queue.ts
783
804
  var TurnQueue = class {
@@ -785,6 +806,7 @@ var TurnQueue = class {
785
806
 
786
807
  // packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
787
808
  var MAX_TIMEOUT_MS = 2147483647;
809
+ var queueCatalogRowSchema = z2.object({ table: z2.string() });
788
810
  var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
789
811
  #boss;
790
812
  #queue;
@@ -802,7 +824,8 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
802
824
  super();
803
825
  this.#boss = boss;
804
826
  this.#queue = options.queue ?? "zukhruf-turns";
805
- const configuredSchema = boss.getDb().config?.schema;
827
+ const db = boss.getDb();
828
+ const configuredSchema = "config" in db && isRecord(db.config) ? db.config.schema : void 0;
806
829
  const bossSchema = typeof configuredSchema === "string" ? configuredSchema : void 0;
807
830
  this.#schema = options.schema ?? bossSchema ?? "pgboss";
808
831
  if (options.schema === void 0 && bossSchema === void 0) {
@@ -854,7 +877,8 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
854
877
  WHERE name = $1`,
855
878
  [this.#queue]
856
879
  );
857
- if (catalog.rows.length !== 1 || catalog.rows[0].table !== this.#table) {
880
+ const catalogRow = queueCatalogRowSchema.safeParse(catalog.rows[0]);
881
+ if (catalog.rows.length !== 1 || !catalogRow.success || catalogRow.data.table !== this.#table) {
858
882
  throw new Error("queue catalog does not match");
859
883
  }
860
884
  await this.#boss.getDb().executeSql(`SELECT 1 FROM ${this.#relation()} WHERE false`);
@@ -1044,7 +1068,7 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
1044
1068
  Math.min(MAX_TIMEOUT_MS, Math.max(1, nextExpiry - Date.now()))
1045
1069
  );
1046
1070
  this.#cancelIntentExpiryTimer = timer;
1047
- timer.unref?.();
1071
+ timer.unref();
1048
1072
  }
1049
1073
  async #deleteIfStillQueued(ids) {
1050
1074
  if (!this.#table) {
@@ -1096,6 +1120,7 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
1096
1120
 
1097
1121
  // packages/experimental/src/zukhruf/render-turn.ts
1098
1122
  import { styleText } from "node:util";
1123
+ import { isRecord as isRecord2 } from "@deepagents/context";
1099
1124
  var dim = (text) => styleText("dim", text);
1100
1125
  var red = (text) => styleText("red", text);
1101
1126
  function oneLine(value, max = 88) {
@@ -1103,7 +1128,7 @@ function oneLine(value, max = 88) {
1103
1128
  return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
1104
1129
  }
1105
1130
  function describeToolCall(toolName, input) {
1106
- const args = input ?? {};
1131
+ const args = isRecord2(input) ? input : {};
1107
1132
  switch (toolName) {
1108
1133
  case "spawn_agent":
1109
1134
  return `\u21C4 spawn ${args.agent_type} "${args.task_name}" \u2014 ${args.message}`;
@@ -1473,7 +1498,7 @@ var AgentHistoryForker = class {
1473
1498
  await this.#store.updateChat(child.conversation.chatId, (chat2) => {
1474
1499
  const metadata = chat2.metadata;
1475
1500
  const zukhruf = metadata?.zukhruf;
1476
- if (!isRecord(zukhruf)) {
1501
+ if (!isRecord3(zukhruf)) {
1477
1502
  throw new Error(
1478
1503
  `spawn_agent: child chat "${child.conversation.chatId}" is missing Zukhruf metadata`
1479
1504
  );
@@ -1550,14 +1575,14 @@ var AgentHistoryForker = class {
1550
1575
  const storedMessages = await Promise.all(
1551
1576
  sourceMessageIds.map((id) => this.#store.getMessage(id))
1552
1577
  );
1553
- if (storedMessages.some(
1554
- (message) => message === void 0 || message.chatId !== parent.conversation.chatId
1555
- )) {
1556
- throw new Error(
1557
- "spawn_agent: persisted parent-history snapshot is unavailable"
1558
- );
1559
- }
1560
- const stored = storedMessages;
1578
+ const stored = storedMessages.map((message) => {
1579
+ if (message === void 0 || message.chatId !== parent.conversation.chatId) {
1580
+ throw new Error(
1581
+ "spawn_agent: persisted parent-history snapshot is unavailable"
1582
+ );
1583
+ }
1584
+ return message;
1585
+ });
1561
1586
  const messages = await validateUIMessages({
1562
1587
  messages: stored.map((message) => message.data)
1563
1588
  });
@@ -1579,7 +1604,7 @@ var AgentHistoryForker = class {
1579
1604
  await this.#store.updateChat(child.conversation.chatId, (chat2) => {
1580
1605
  const metadata = chat2.metadata;
1581
1606
  const zukhruf = metadata?.zukhruf;
1582
- if (!isRecord(zukhruf)) {
1607
+ if (!isRecord3(zukhruf)) {
1583
1608
  throw new Error(
1584
1609
  `spawn_agent: child chat "${child.conversation.chatId}" is missing Zukhruf metadata`
1585
1610
  );
@@ -1671,12 +1696,12 @@ function isForkTurnBoundary(message) {
1671
1696
  return interAgentCommunication(message)?.triggerTurn ?? true;
1672
1697
  }
1673
1698
  function interAgentCommunication(message) {
1674
- if (!isRecord(message.metadata)) return void 0;
1699
+ if (!isRecord3(message.metadata)) return void 0;
1675
1700
  if (!Object.hasOwn(message.metadata, "interAgentCommunication")) {
1676
1701
  return void 0;
1677
1702
  }
1678
1703
  const communication = message.metadata.interAgentCommunication;
1679
- if (!isRecord(communication) || typeof communication.triggerTurn !== "boolean") {
1704
+ if (!isRecord3(communication) || typeof communication.triggerTurn !== "boolean") {
1680
1705
  throw new Error(
1681
1706
  `spawn_agent: message "${message.id}" has invalid inter-agent metadata`
1682
1707
  );
@@ -1684,7 +1709,7 @@ function interAgentCommunication(message) {
1684
1709
  return { triggerTurn: communication.triggerTurn };
1685
1710
  }
1686
1711
  function parseHistoryForkRecord(value) {
1687
- if (!isRecord(value)) {
1712
+ if (!isRecord3(value)) {
1688
1713
  throw new Error("spawn_agent: invalid persisted history-fork metadata");
1689
1714
  }
1690
1715
  const { forkTurns, parentChatId, parentHeadMessageId, sourceMessageIds } = value;
@@ -1703,11 +1728,11 @@ function parseHistoryForkRecord(value) {
1703
1728
  function isForkTurns(value) {
1704
1729
  return value === "none" || value === "all" || typeof value === "number" && Number.isSafeInteger(value) && value > 0;
1705
1730
  }
1706
- function isRecord(value) {
1731
+ function isRecord3(value) {
1707
1732
  return typeof value === "object" && value !== null && !Array.isArray(value);
1708
1733
  }
1709
1734
  function isEmptyAssistantPlaceholder(value) {
1710
- return isRecord(value) && typeof value.id === "string" && value.role === "assistant" && Array.isArray(value.parts) && value.parts.length === 0;
1735
+ return isRecord3(value) && typeof value.id === "string" && value.role === "assistant" && Array.isArray(value.parts) && value.parts.length === 0;
1711
1736
  }
1712
1737
  function arraysEqual(left, right) {
1713
1738
  return left.length === right.length && left.every((value, index) => value === right[index]);
@@ -1715,17 +1740,17 @@ function arraysEqual(left, right) {
1715
1740
 
1716
1741
  // packages/experimental/src/zukhruf/control-plane/agent-status-projector.ts
1717
1742
  import { isTextUIPart } from "ai";
1718
- import { z } from "zod";
1743
+ import { z as z3 } from "zod";
1719
1744
  import {
1720
1745
  ContextEngine
1721
1746
  } from "@deepagents/context";
1722
- var listedAgentStatusSchema = z.union([
1723
- z.enum(["pending_init", "running", "interrupted", "shutdown", "not_found"]),
1724
- z.object({ completed: z.string().nullable() }).strict(),
1725
- z.object({ errored: z.string() }).strict()
1747
+ var listedAgentStatusSchema = z3.union([
1748
+ z3.enum(["pending_init", "running", "interrupted", "shutdown", "not_found"]),
1749
+ z3.object({ completed: z3.string().nullable() }).strict(),
1750
+ z3.object({ errored: z3.string() }).strict()
1726
1751
  ]);
1727
- var listedAgentSchema = z.object({
1728
- agent_name: z.string(),
1752
+ var listedAgentSchema = z3.object({
1753
+ agent_name: z3.string(),
1729
1754
  agent_status: listedAgentStatusSchema
1730
1755
  }).strict();
1731
1756
  var AgentStatusProjector = class _AgentStatusProjector {
@@ -1792,7 +1817,7 @@ var AgentStatusProjector = class _AgentStatusProjector {
1792
1817
  await this.#mailbox.deliver(
1793
1818
  createInterAgentCommunication({
1794
1819
  id: `zukhruf:child-terminal:${turn.streamId}`,
1795
- type: InterAgentCommunicationType.FinalAnswer,
1820
+ type: InterAgentCommunicationTypes.FinalAnswer,
1796
1821
  author: thread.conversation,
1797
1822
  recipient: {
1798
1823
  chatId: thread.parentChatId,
@@ -1806,7 +1831,7 @@ var AgentStatusProjector = class _AgentStatusProjector {
1806
1831
  status: stream.status
1807
1832
  }
1808
1833
  }),
1809
- MessageDeliveryMode.QueueOnly
1834
+ MessageDeliveryModes.QueueOnly
1810
1835
  );
1811
1836
  return { finishedAt: stream.finishedAt, status: stream.status };
1812
1837
  }
@@ -2026,15 +2051,15 @@ var AgentControlPlane = class _AgentControlPlane {
2026
2051
  }
2027
2052
  async sendMessage(actor, input) {
2028
2053
  return this.#deliverAgentMessage(actor, input, {
2029
- type: InterAgentCommunicationType.Message,
2030
- mode: MessageDeliveryMode.QueueOnly,
2054
+ type: InterAgentCommunicationTypes.Message,
2055
+ mode: MessageDeliveryModes.QueueOnly,
2031
2056
  rejectRoot: false
2032
2057
  });
2033
2058
  }
2034
2059
  async followupTask(actor, input) {
2035
2060
  return this.#deliverAgentMessage(actor, input, {
2036
- type: InterAgentCommunicationType.NewTask,
2037
- mode: MessageDeliveryMode.TriggerTurn,
2061
+ type: InterAgentCommunicationTypes.NewTask,
2062
+ mode: MessageDeliveryModes.TriggerTurn,
2038
2063
  rejectRoot: true
2039
2064
  });
2040
2065
  }
@@ -2109,7 +2134,7 @@ var AgentControlPlane = class _AgentControlPlane {
2109
2134
  "followup_task: the root agent cannot receive a follow-up"
2110
2135
  );
2111
2136
  }
2112
- if (options.mode === MessageDeliveryMode.TriggerTurn && await this.#queue.getTurnActivity(target.conversation) !== "running" && !await this.#hasExecutionCapacity(actor.thread)) {
2137
+ if (options.mode === MessageDeliveryModes.TriggerTurn && await this.#queue.getTurnActivity(target.conversation) !== "running" && !await this.#hasExecutionCapacity(actor.thread)) {
2113
2138
  throw new Error("collab tool failed: agent thread limit reached");
2114
2139
  }
2115
2140
  const message = createInterAgentCommunication({
@@ -2125,7 +2150,7 @@ var AgentControlPlane = class _AgentControlPlane {
2125
2150
  await this.#mailbox.deliver(message, options.mode);
2126
2151
  await this.#recordActivity(target.path.isRoot ? actor.thread : target, {
2127
2152
  id: message.id,
2128
- type: options.mode === MessageDeliveryMode.TriggerTurn ? "followup" : "message",
2153
+ type: options.mode === MessageDeliveryModes.TriggerTurn ? "followup" : "message",
2129
2154
  at: Date.now(),
2130
2155
  actorPath: actor.thread.path.toString(),
2131
2156
  targetPath: target.path.toString(),
@@ -2167,8 +2192,8 @@ var MailboxCoordinator = class {
2167
2192
  async deliver(communication, mode) {
2168
2193
  const delivered = {
2169
2194
  ...communication,
2170
- type: mode === MessageDeliveryMode.TriggerTurn ? InterAgentCommunicationType.NewTask : communication.type,
2171
- triggerTurn: mode === MessageDeliveryMode.TriggerTurn
2195
+ type: mode === MessageDeliveryModes.TriggerTurn ? InterAgentCommunicationTypes.NewTask : communication.type,
2196
+ triggerTurn: mode === MessageDeliveryModes.TriggerTurn
2172
2197
  };
2173
2198
  assertCommunication(delivered);
2174
2199
  const { recipientActive } = await this.#store.enqueue(delivered);
@@ -2302,7 +2327,7 @@ function resolveMultiAgentHostConfig(input = {}) {
2302
2327
  }
2303
2328
  if (toolNamespace !== void 0) validateToolNamespace(toolNamespace);
2304
2329
  const codeMode = input.nonCodeModeOnly === false;
2305
- const tool8 = (name) => codeMode ? `tools.${name}` : toolNamespace === void 0 ? name : `${toolNamespace}.${name}`;
2330
+ const tool7 = (name) => codeMode ? `tools.${name}` : toolNamespace === void 0 ? name : `${toolNamespace}.${name}`;
2306
2331
  const collaborationTools = [
2307
2332
  "spawn_agent",
2308
2333
  "send_message",
@@ -2310,7 +2335,7 @@ function resolveMultiAgentHostConfig(input = {}) {
2310
2335
  "wait_agent",
2311
2336
  "interrupt_agent",
2312
2337
  "list_agents"
2313
- ].map((name) => `\`${tool8(name)}\``).join(", ");
2338
+ ].map((name) => `\`${tool7(name)}\``).join(", ");
2314
2339
  const shared = codeMode ? `Call ${collaborationTools} from \`code_mode\`.
2315
2340
 
2316
2341
  All agents share the same workspace, current working directory, and filesystem.` : `Call ${collaborationTools} directly. They are intentionally unavailable inside nested code execution.
@@ -2322,8 +2347,8 @@ All agents share the same workspace, current working directory, and filesystem.`
2322
2347
  maxWaitTimeoutMs,
2323
2348
  maxConcurrentThreadsPerSession,
2324
2349
  usageHintText: nonEmptyText(input.usageHintText),
2325
- rootAgentUsageHintText: input.rootAgentUsageHintText === void 0 ? defaultRootUsageHint(tool8, shared, maxConcurrentThreadsPerSession) : nonEmptyText(input.rootAgentUsageHintText),
2326
- subagentUsageHintText: input.subagentUsageHintText === void 0 ? defaultSubagentUsageHint(tool8, shared, maxConcurrentThreadsPerSession) : nonEmptyText(input.subagentUsageHintText),
2350
+ rootAgentUsageHintText: input.rootAgentUsageHintText === void 0 ? defaultRootUsageHint(tool7, shared, maxConcurrentThreadsPerSession) : nonEmptyText(input.rootAgentUsageHintText),
2351
+ subagentUsageHintText: input.subagentUsageHintText === void 0 ? defaultSubagentUsageHint(tool7, shared, maxConcurrentThreadsPerSession) : nonEmptyText(input.subagentUsageHintText),
2327
2352
  toolNamespace,
2328
2353
  codeMode
2329
2354
  };
@@ -2346,12 +2371,12 @@ function nonEmptyText(value) {
2346
2371
  if (value === void 0) return void 0;
2347
2372
  return value.length === 0 ? void 0 : value;
2348
2373
  }
2349
- function defaultRootUsageHint(tool8, shared, maxConcurrency) {
2374
+ function defaultRootUsageHint(tool7, shared, maxConcurrency) {
2350
2375
  return `You are \`/root\`, the primary agent in a team of agents collaborating to fulfill the user's goals.
2351
2376
 
2352
2377
  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.
2353
2378
 
2354
- Use \`${tool8("spawn_agent")}\` to create an agent, \`${tool8("followup_task")}\` to assign a new task and trigger a turn, and \`${tool8("send_message")}\` to queue a message without triggering a turn. Every spawn must set \`fork_turns\` to \`none\`, \`all\`, or a positive count of recent turns.
2379
+ 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. Every spawn must set \`fork_turns\` to \`none\`, \`all\`, or a positive count of recent turns.
2355
2380
 
2356
2381
  Child messages arrive as \`MESSAGE\` or \`FINAL_ANSWER\` mailbox envelopes with their task name, sender, and payload preserved.
2357
2382
 
@@ -2361,10 +2386,10 @@ ${WAIT_AGENT_USAGE_HINT_TEXT}
2361
2386
 
2362
2387
  ${concurrencySlotsText(maxConcurrency)}`;
2363
2388
  }
2364
- function defaultSubagentUsageHint(tool8, shared, maxConcurrency) {
2389
+ function defaultSubagentUsageHint(tool7, shared, maxConcurrency) {
2365
2390
  return `You are an agent in a team collaborating to complete a task.
2366
2391
 
2367
- You can spawn declared sub-agents recursively. All agents are equally capable and receive the tools declared for their agent type. Use \`${tool8("spawn_agent")}\` to create one, \`${tool8("followup_task")}\` to assign a new task and trigger a turn, and \`${tool8("send_message")}\` to queue a message for another agent.
2392
+ 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.
2368
2393
 
2369
2394
  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.
2370
2395
 
@@ -2403,7 +2428,7 @@ import {
2403
2428
  modelMessageSchema as modelMessageSchema2
2404
2429
  } from "ai";
2405
2430
  import { createHash, randomUUID as randomUUID2 } from "node:crypto";
2406
- import { z as z2 } from "zod";
2431
+ import { z as z4 } from "zod";
2407
2432
 
2408
2433
  // packages/compaction/dist/index.js
2409
2434
  import {
@@ -2605,25 +2630,25 @@ ${options.instructions}` : SUMMARY_PROMPT,
2605
2630
  }
2606
2631
 
2607
2632
  // packages/experimental/src/zukhruf/runtime/compaction.ts
2608
- var checkpointSchema = z2.object({
2609
- sourceCount: z2.number().int().positive(),
2610
- sourceHash: z2.string(),
2611
- replacement: z2.array(z2.unknown()).transform(
2633
+ var checkpointSchema = z4.object({
2634
+ sourceCount: z4.number().int().positive(),
2635
+ sourceHash: z4.string(),
2636
+ replacement: z4.array(z4.unknown()).transform(
2612
2637
  (messages) => messages.map((message) => modelMessageSchema2.parse(message))
2613
2638
  )
2614
2639
  });
2615
- var cacheObservationSchema = z2.object({
2616
- scope: z2.string(),
2617
- prefixLength: z2.number().int().nonnegative(),
2618
- prefixHash: z2.string(),
2619
- startedAt: z2.number().int().nonnegative(),
2620
- retentionMs: z2.number().int().positive().optional()
2640
+ var cacheObservationSchema = z4.object({
2641
+ scope: z4.string(),
2642
+ prefixLength: z4.number().int().nonnegative(),
2643
+ prefixHash: z4.string(),
2644
+ startedAt: z4.number().int().nonnegative(),
2645
+ retentionMs: z4.number().int().positive().optional()
2621
2646
  });
2622
- var inputUsageSchema = cacheObservationSchema.pick({ scope: true, prefixLength: true, prefixHash: true }).extend({ inputTokens: z2.number().int().nonnegative() });
2647
+ var inputUsageSchema = cacheObservationSchema.pick({ scope: true, prefixLength: true, prefixHash: true }).extend({ inputTokens: z4.number().int().nonnegative() });
2623
2648
  function hash(value) {
2624
2649
  return createHash("sha256").update(JSON.stringify(value)).digest("hex");
2625
2650
  }
2626
- function isRecord2(value) {
2651
+ function isRecord4(value) {
2627
2652
  return typeof value === "object" && value !== null && !Array.isArray(value);
2628
2653
  }
2629
2654
  function cacheRetentionMs(step) {
@@ -2635,14 +2660,14 @@ function cacheRetentionMs(step) {
2635
2660
  return void 0;
2636
2661
  }
2637
2662
  }
2638
- if (!isRecord2(body)) return void 0;
2663
+ if (!isRecord4(body)) return void 0;
2639
2664
  const provider = step.model.provider;
2640
2665
  const routed = provider === "openrouter" || provider === "openrouter.chat";
2641
2666
  const upstream = routed ? step.providerMetadata?.openrouter?.provider : void 0;
2642
2667
  if (provider === "openai.responses" || provider === "openai.chat" || routed && upstream === "OpenAI") {
2643
2668
  const options = body.prompt_cache_options;
2644
- if (options !== void 0 && !isRecord2(options)) return void 0;
2645
- if (isRecord2(options) && options.ttl !== void 0) {
2669
+ if (options !== void 0 && !isRecord4(options)) return void 0;
2670
+ if (isRecord4(options) && options.ttl !== void 0) {
2646
2671
  return options.ttl === "30m" ? 30 * 6e4 : void 0;
2647
2672
  }
2648
2673
  const version = /^(?:openai\/)?gpt-(\d+)(?:\.(\d+))?(?:-|$)/.exec(
@@ -2662,18 +2687,18 @@ function cacheRetentionMs(step) {
2662
2687
  }
2663
2688
  const windows = [];
2664
2689
  for (const block of blocks) {
2665
- if (!isRecord2(block)) continue;
2690
+ if (!isRecord4(block)) continue;
2666
2691
  if (Array.isArray(block.content)) blocks.push(...block.content);
2667
2692
  const control = block.cache_control;
2668
2693
  if (control === void 0) continue;
2669
- if (!isRecord2(control) || control.type !== "ephemeral") return void 0;
2694
+ if (!isRecord4(control) || control.type !== "ephemeral") return void 0;
2670
2695
  if (control.ttl === void 0 || control.ttl === "5m")
2671
2696
  windows.push(5 * 6e4);
2672
2697
  else if (control.ttl === "1h") windows.push(60 * 6e4);
2673
2698
  else return void 0;
2674
2699
  }
2675
2700
  const creation = step.usage.raw?.cache_creation;
2676
- if (isRecord2(creation)) {
2701
+ if (isRecord4(creation)) {
2677
2702
  if (typeof creation.ephemeral_1h_input_tokens === "number" && creation.ephemeral_1h_input_tokens > 0)
2678
2703
  return 60 * 6e4;
2679
2704
  if (step.usage.inputTokenDetails.cacheReadTokens === 0 && creation.ephemeral_1h_input_tokens === 0 && typeof creation.ephemeral_5m_input_tokens === "number" && creation.ephemeral_5m_input_tokens > 0)
@@ -2696,20 +2721,21 @@ function createCompaction(config, engine, store, signal, onEvent) {
2696
2721
  settings = input;
2697
2722
  };
2698
2723
  const envelope = async (input) => {
2724
+ const toolsContext = input.toolsContext;
2699
2725
  const tools = settings.tools === void 0 ? [] : await Promise.all(
2700
2726
  Object.entries(settings.tools).filter(
2701
2727
  ([name]) => settings.activeTools === void 0 || settings.activeTools.includes(name)
2702
- ).map(async ([name, tool8]) => [
2728
+ ).map(async ([name, tool7]) => [
2703
2729
  name,
2704
- tool8.type === "provider" ? [tool8.id, tool8.args] : [
2705
- typeof tool8.description === "function" ? tool8.description({
2706
- context: input.toolsContext[name],
2730
+ tool7.type === "provider" ? [tool7.id, tool7.args] : [
2731
+ typeof tool7.description === "function" ? tool7.description({
2732
+ context: toolsContext[name],
2707
2733
  experimental_sandbox: input.experimental_sandbox
2708
- }) : tool8.description,
2709
- await asSchema(tool8.inputSchema).jsonSchema,
2710
- tool8.providerOptions,
2711
- tool8.inputExamples,
2712
- tool8.strict
2734
+ }) : tool7.description,
2735
+ await asSchema(tool7.inputSchema).jsonSchema,
2736
+ tool7.providerOptions,
2737
+ tool7.inputExamples,
2738
+ tool7.strict
2713
2739
  ]
2714
2740
  ])
2715
2741
  );
@@ -2748,10 +2774,10 @@ function createCompaction(config, engine, store, signal, onEvent) {
2748
2774
  if (!initialized) {
2749
2775
  const chat2 = await store.getChat(engine.chatId);
2750
2776
  const metadata = chat2?.metadata?.zukhruf;
2751
- const saved = isRecord2(metadata) ? metadata.compaction : void 0;
2752
- const savedCache = isRecord2(metadata) ? metadata.promptCache : void 0;
2777
+ const saved = isRecord4(metadata) ? metadata.compaction : void 0;
2778
+ const savedCache = isRecord4(metadata) ? metadata.promptCache : void 0;
2753
2779
  baseline = inputUsageSchema.safeParse(
2754
- isRecord2(metadata) ? metadata.inputUsage : void 0
2780
+ isRecord4(metadata) ? metadata.inputUsage : void 0
2755
2781
  ).data ?? null;
2756
2782
  if (savedCache !== void 0) {
2757
2783
  cache = cacheObservationSchema.nullable().parse(savedCache);
@@ -2858,7 +2884,7 @@ function createCompaction(config, engine, store, signal, onEvent) {
2858
2884
  metadata: {
2859
2885
  ...metadata,
2860
2886
  zukhruf: {
2861
- ...isRecord2(metadata?.zukhruf) ? metadata.zukhruf : {},
2887
+ ...isRecord4(metadata?.zukhruf) ? metadata.zukhruf : {},
2862
2888
  compaction: checkpoint,
2863
2889
  inputUsage: null
2864
2890
  }
@@ -2893,7 +2919,7 @@ function createCompaction(config, engine, store, signal, onEvent) {
2893
2919
  const onStepEnd = async (step) => {
2894
2920
  if (signal.aborted || step.finishReason === "error") return;
2895
2921
  const iterations = step.usage.raw?.iterations;
2896
- const ambiguous = iterations != null && (!Array.isArray(iterations) || iterations.length !== 1 || !isRecord2(iterations[0]) || iterations[0].type !== "message") || step.content.some(
2922
+ const ambiguous = iterations != null && (!Array.isArray(iterations) || iterations.length !== 1 || !isRecord4(iterations[0]) || iterations[0].type !== "message") || step.content.some(
2897
2923
  (part) => part.type === "custom" && part.kind === "openai.compaction" || part.type === "text" && part.providerMetadata?.anthropic?.type === "compaction"
2898
2924
  );
2899
2925
  const nextBaseline = ambiguous ? null : inputUsageSchema.safeParse({
@@ -2908,7 +2934,7 @@ function createCompaction(config, engine, store, signal, onEvent) {
2908
2934
  metadata: {
2909
2935
  ...metadata,
2910
2936
  zukhruf: {
2911
- ...isRecord2(metadata?.zukhruf) ? metadata.zukhruf : {},
2937
+ ...isRecord4(metadata?.zukhruf) ? metadata.zukhruf : {},
2912
2938
  promptCache: next,
2913
2939
  inputUsage: nextBaseline
2914
2940
  }
@@ -3359,7 +3385,7 @@ var AgentTurnExecutor = class {
3359
3385
  if (turn.kind === "message" && turn.elements !== void 0) {
3360
3386
  const declared = turn.elements;
3361
3387
  await this.#store.updateChat(turn.chatId, ({ metadata }) => {
3362
- const zukhruf = isRecord3(metadata?.zukhruf) ? metadata.zukhruf : {};
3388
+ const zukhruf = isRecord5(metadata?.zukhruf) ? metadata.zukhruf : {};
3363
3389
  if (isDeepStrictEqual(zukhruf.elements, declared)) return void 0;
3364
3390
  return {
3365
3391
  metadata: {
@@ -3389,7 +3415,7 @@ var AgentTurnExecutor = class {
3389
3415
  available = persisted;
3390
3416
  return void 0;
3391
3417
  }
3392
- const zukhruf = isRecord3(metadata?.zukhruf) ? metadata.zukhruf : {};
3418
+ const zukhruf = isRecord5(metadata?.zukhruf) ? metadata.zukhruf : {};
3393
3419
  return {
3394
3420
  metadata: {
3395
3421
  ...metadata,
@@ -3459,7 +3485,7 @@ ${communication.content}`;
3459
3485
  };
3460
3486
  function readElements(metadata) {
3461
3487
  const zukhruf = metadata?.zukhruf;
3462
- if (!isRecord3(zukhruf) || !Object.hasOwn(zukhruf, "elements")) {
3488
+ if (!isRecord5(zukhruf) || !Object.hasOwn(zukhruf, "elements")) {
3463
3489
  return void 0;
3464
3490
  }
3465
3491
  const parsed = elementsSchema.safeParse(zukhruf.elements);
@@ -3470,7 +3496,7 @@ function readElements(metadata) {
3470
3496
  }
3471
3497
  function readSkills(metadata) {
3472
3498
  const zukhruf = metadata?.zukhruf;
3473
- if (!isRecord3(zukhruf) || !Object.hasOwn(zukhruf, "skills")) {
3499
+ if (!isRecord5(zukhruf) || !Object.hasOwn(zukhruf, "skills")) {
3474
3500
  return void 0;
3475
3501
  }
3476
3502
  if (!Array.isArray(zukhruf.skills) || !zukhruf.skills.every(isSkill)) {
@@ -3479,9 +3505,9 @@ function readSkills(metadata) {
3479
3505
  return zukhruf.skills;
3480
3506
  }
3481
3507
  function isSkill(value) {
3482
- return isRecord3(value) && typeof value.name === "string" && typeof value.description === "string" && typeof value.path === "string";
3508
+ return isRecord5(value) && typeof value.name === "string" && typeof value.description === "string" && typeof value.path === "string";
3483
3509
  }
3484
- function isRecord3(value) {
3510
+ function isRecord5(value) {
3485
3511
  return typeof value === "object" && value !== null && !Array.isArray(value);
3486
3512
  }
3487
3513
 
@@ -3600,8 +3626,8 @@ var ApprovalController = class _ApprovalController {
3600
3626
  (part) => isToolUIPart(part) && part.state === "approval-responded" && part.approval.approved === true
3601
3627
  );
3602
3628
  const retryable = approved.length > 0 && approved.every((part) => {
3603
- const tool8 = tools[getToolName(part)];
3604
- return tool8?.recovery === "idempotent" && typeof tool8.execute === "function";
3629
+ const tool7 = tools[getToolName(part)];
3630
+ return tool7?.recovery === "idempotent" && typeof tool7.execute === "function";
3605
3631
  });
3606
3632
  if (!retryable) return false;
3607
3633
  await this.#queue.push({
@@ -3640,6 +3666,7 @@ var ApprovalController = class _ApprovalController {
3640
3666
  };
3641
3667
 
3642
3668
  // packages/experimental/src/zukhruf/runtime/conversation-status/projector.ts
3669
+ import { MemoryStore, Mutex } from "@zukhruf/mutex";
3643
3670
  import { EventEmitter, on } from "node:events";
3644
3671
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
3645
3672
  import {
@@ -3647,25 +3674,31 @@ import {
3647
3674
  } from "@deepagents/context";
3648
3675
 
3649
3676
  // packages/experimental/src/zukhruf/runtime/conversation-status/child-progress.ts
3650
- import { z as z3 } from "zod";
3651
- var childActivitySchema = z3.object({
3652
- id: z3.string(),
3653
- type: z3.enum(["spawn", "message", "followup", "interrupt", "completion"]),
3654
- at: z3.number(),
3655
- actorPath: z3.string(),
3656
- targetPath: z3.string(),
3657
- streamId: z3.string(),
3658
- outcome: z3.enum(["completed", "failed", "cancelled"]).optional()
3677
+ import { z as z5 } from "zod";
3678
+ var childActivitySchema = z5.object({
3679
+ id: z5.string(),
3680
+ type: z5.enum(["spawn", "message", "followup", "interrupt", "completion"]),
3681
+ at: z5.number(),
3682
+ actorPath: z5.string(),
3683
+ targetPath: z5.string(),
3684
+ streamId: z5.string(),
3685
+ outcome: z5.enum(["completed", "failed", "cancelled"]).optional()
3659
3686
  });
3660
- var childActivitiesSchema = z3.partialRecord(
3687
+ var childActivitiesSchema = z5.partialRecord(
3661
3688
  childActivitySchema.shape.type,
3662
3689
  childActivitySchema
3663
3690
  );
3664
- var childActivityMetadataSchema = z3.looseObject({
3691
+ var childActivityMetadataSchema = z5.looseObject({
3665
3692
  childActivities: childActivitiesSchema.default({})
3666
3693
  });
3667
3694
 
3668
3695
  // packages/experimental/src/zukhruf/runtime/conversation-status/projector.ts
3696
+ var ProjectorEventDelivery = class {
3697
+ event;
3698
+ constructor(event) {
3699
+ this.event = event;
3700
+ }
3701
+ };
3669
3702
  var ConversationStatusProjector = class _ConversationStatusProjector {
3670
3703
  #store;
3671
3704
  #streams;
@@ -3674,7 +3707,7 @@ var ConversationStatusProjector = class _ConversationStatusProjector {
3674
3707
  #changeSource;
3675
3708
  #emitter = new EventEmitter();
3676
3709
  #last = /* @__PURE__ */ new Map();
3677
- #publishing = /* @__PURE__ */ new Map();
3710
+ #publishing = new Mutex(new MemoryStore());
3678
3711
  #subscribers = 0;
3679
3712
  #remote;
3680
3713
  constructor(options) {
@@ -3790,10 +3823,12 @@ var ConversationStatusProjector = class _ConversationStatusProjector {
3790
3823
  return {
3791
3824
  async *[Symbol.asyncIterator]() {
3792
3825
  try {
3793
- for await (const [event] of events) {
3794
- const projected = event;
3795
- if (projected.type === "error") throw projected.error;
3796
- yield projected;
3826
+ for await (const args of events) {
3827
+ const [delivery] = args;
3828
+ if (!(delivery instanceof ProjectorEventDelivery)) continue;
3829
+ const { event } = delivery;
3830
+ if (event.type === "error") throw event.error;
3831
+ yield event;
3797
3832
  }
3798
3833
  } finally {
3799
3834
  await detach();
@@ -3809,13 +3844,7 @@ var ConversationStatusProjector = class _ConversationStatusProjector {
3809
3844
  }
3810
3845
  #serialize(conversation, step) {
3811
3846
  const key = _ConversationStatusProjector.#key(conversation);
3812
- const previous = this.#publishing.get(key) ?? Promise.resolve();
3813
- const next = previous.then(() => step(key));
3814
- this.#publishing.set(key, next);
3815
- void next.finally(() => {
3816
- if (this.#publishing.get(key) === next) this.#publishing.delete(key);
3817
- });
3818
- return next;
3847
+ return this.#publishing.acquire(key, () => step(key));
3819
3848
  }
3820
3849
  async #project(conversation, key) {
3821
3850
  let change;
@@ -3837,7 +3866,7 @@ var ConversationStatusProjector = class _ConversationStatusProjector {
3837
3866
  }
3838
3867
  if (isDeepStrictEqual2(this.#last.get(key), change)) return false;
3839
3868
  this.#last.set(key, change);
3840
- this.#emitter.emit("event", change);
3869
+ this.#emit(change);
3841
3870
  return true;
3842
3871
  }
3843
3872
  async #attachRemote() {
@@ -3874,13 +3903,13 @@ var ConversationStatusProjector = class _ConversationStatusProjector {
3874
3903
  ready.resolve();
3875
3904
  for await (const event of events) {
3876
3905
  if (event.type === "reset") {
3877
- this.#emitter.emit("event", event);
3906
+ this.#emit(event);
3878
3907
  } else {
3879
3908
  await this.#reconcile(event.conversation);
3880
3909
  }
3881
3910
  }
3882
3911
  if (!remote.abort.signal.aborted) {
3883
- this.#emitter.emit("event", {
3912
+ this.#emit({
3884
3913
  type: "error",
3885
3914
  error: new Error("Conversation status change source ended")
3886
3915
  });
@@ -3888,15 +3917,15 @@ var ConversationStatusProjector = class _ConversationStatusProjector {
3888
3917
  } catch (error) {
3889
3918
  if (!connected) ready.reject(error);
3890
3919
  if (connected && !(error instanceof Error && error.name === "AbortError")) {
3891
- this.#emitter.emit("event", {
3892
- type: "error",
3893
- error
3894
- });
3920
+ this.#emit({ type: "error", error });
3895
3921
  }
3896
3922
  } finally {
3897
3923
  if (this.#remote === remote) this.#remote = void 0;
3898
3924
  }
3899
3925
  }
3926
+ #emit(event) {
3927
+ this.#emitter.emit("event", new ProjectorEventDelivery(event));
3928
+ }
3900
3929
  static #key({ chatId, userId }) {
3901
3930
  return JSON.stringify([chatId, userId]);
3902
3931
  }
@@ -3940,13 +3969,13 @@ var StatusPublishingTurnQueue = class extends TurnQueue {
3940
3969
 
3941
3970
  // packages/experimental/src/zukhruf/collaboration/interrupt-agent.ts
3942
3971
  import { tool as tool2 } from "ai";
3943
- import { z as z4 } from "zod";
3944
- var interruptAgentInputSchema = z4.object({
3945
- target: z4.string().trim().min(1).describe(
3972
+ import { z as z6 } from "zod";
3973
+ var interruptAgentInputSchema = z6.object({
3974
+ target: z6.string().trim().min(1).describe(
3946
3975
  "The canonical /root/... path, or a descendant-relative target name."
3947
3976
  )
3948
3977
  });
3949
- var interruptAgentOutputSchema = z4.object({ previous_status: listedAgentStatusSchema }).strict();
3978
+ var interruptAgentOutputSchema = z6.object({ previous_status: listedAgentStatusSchema }).strict();
3950
3979
  var interruptAgentTool = tool2({
3951
3980
  description: "Interrupt an agent's current turn, if any, and return its previous status. The agent remains available for messages and follow-up tasks.",
3952
3981
  inputSchema: interruptAgentInputSchema,
@@ -3956,13 +3985,13 @@ var interruptAgentTool = tool2({
3956
3985
 
3957
3986
  // packages/experimental/src/zukhruf/collaboration/list-agents.ts
3958
3987
  import { tool as tool3 } from "ai";
3959
- import { z as z5 } from "zod";
3960
- var listAgentsInputSchema = z5.object({
3961
- path_prefix: z5.string().trim().min(1).describe(
3988
+ import { z as z7 } from "zod";
3989
+ var listAgentsInputSchema = z7.object({
3990
+ path_prefix: z7.string().trim().min(1).describe(
3962
3991
  "Task-path prefix without a trailing slash. Omit to list the whole tree."
3963
3992
  ).optional()
3964
3993
  });
3965
- var listAgentsOutputSchema = z5.object({ agents: z5.array(listedAgentSchema) }).strict();
3994
+ var listAgentsOutputSchema = z7.object({ agents: z7.array(listedAgentSchema) }).strict();
3966
3995
  var listAgentsTool = tool3({
3967
3996
  description: "List live agents in the current root thread tree. Optionally filter by task-path prefix.",
3968
3997
  inputSchema: listAgentsInputSchema,
@@ -3972,12 +4001,12 @@ var listAgentsTool = tool3({
3972
4001
 
3973
4002
  // packages/experimental/src/zukhruf/collaboration/message-tools.ts
3974
4003
  import { tool as tool4 } from "ai";
3975
- import { z as z6 } from "zod";
3976
- var agentMessageInputSchema = z6.object({
3977
- target: z6.string().trim().min(1).describe(
4004
+ import { z as z8 } from "zod";
4005
+ var agentMessageInputSchema = z8.object({
4006
+ target: z8.string().trim().min(1).describe(
3978
4007
  "The canonical /root/... path, or a descendant-relative target name."
3979
4008
  ),
3980
- message: z6.string().trim().min(1).describe("The message or follow-up task.")
4009
+ message: z8.string().trim().min(1).describe("The message or follow-up task.")
3981
4010
  });
3982
4011
  var sendMessageTool = tool4({
3983
4012
  description: "Queue a message for another agent. Address siblings with their canonical /root/... path.",
@@ -3998,7 +4027,7 @@ var followupTaskTool = tool4({
3998
4027
 
3999
4028
  // packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
4000
4029
  import { tool as tool5 } from "ai";
4001
- import { z as z7 } from "zod";
4030
+ import { z as z9 } from "zod";
4002
4031
 
4003
4032
  // packages/experimental/src/zukhruf/control-plane/fork-turns.ts
4004
4033
  var forkTurnsError = "fork_turns must be `none`, `all`, or a positive integer string";
@@ -4011,18 +4040,18 @@ function parseForkTurns(value) {
4011
4040
  }
4012
4041
 
4013
4042
  // packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
4014
- var spawnAgentInputSchema = z7.object({
4015
- agent_type: z7.string().trim().min(1).describe("The name of one available subagent declaration."),
4016
- task_name: z7.string().trim().min(1).refine(
4043
+ var spawnAgentInputSchema = z9.object({
4044
+ agent_type: z9.string().trim().min(1).describe("The name of one available subagent declaration."),
4045
+ task_name: z9.string().trim().min(1).refine(
4017
4046
  (value) => value !== "." && value !== ".." && !value.includes("/"),
4018
4047
  "task_name must be one non-empty path segment"
4019
4048
  ).describe("One path segment naming this independent agent task."),
4020
- message: z7.string().refine((value) => value.trim().length > 0, "message cannot be empty").describe("The initial task for the spawned agent."),
4021
- fork_turns: z7.string().trim().refine((value) => parseForkTurns(value) !== void 0, forkTurnsError).describe(
4049
+ message: z9.string().refine((value) => value.trim().length > 0, "message cannot be empty").describe("The initial task for the spawned agent."),
4050
+ fork_turns: z9.string().trim().refine((value) => parseForkTurns(value) !== void 0, forkTurnsError).describe(
4022
4051
  "Required number of parent turns to fork. Use `none`, `all`, or a positive integer string such as `3`."
4023
4052
  )
4024
4053
  });
4025
- var spawnAgentOutputSchema = z7.object({ task_name: z7.string() }).strict();
4054
+ var spawnAgentOutputSchema = z9.object({ task_name: z9.string() }).strict();
4026
4055
  function createSpawnAgentTool(options) {
4027
4056
  return tool5({
4028
4057
  description: ({ context }) => {
@@ -4051,11 +4080,11 @@ function createSpawnAgentTool(options) {
4051
4080
 
4052
4081
  // packages/experimental/src/zukhruf/collaboration/wait-agent.ts
4053
4082
  import { tool as tool6 } from "ai";
4054
- import { z as z8 } from "zod";
4055
- var waitAgentOutputSchema = z8.object({ message: z8.string(), timed_out: z8.boolean() }).strict();
4083
+ import { z as z10 } from "zod";
4084
+ var waitAgentOutputSchema = z10.object({ message: z10.string(), timed_out: z10.boolean() }).strict();
4056
4085
  function createWaitAgentTool(options) {
4057
- const waitAgentInputSchema = z8.object({
4058
- timeout_ms: z8.number().int().max(options.maxTimeoutMs).optional().describe("Maximum time to wait in milliseconds.")
4086
+ const waitAgentInputSchema = z10.object({
4087
+ timeout_ms: z10.number().int().max(options.maxTimeoutMs).optional().describe("Maximum time to wait in milliseconds.")
4059
4088
  });
4060
4089
  return tool6({
4061
4090
  description: "Wait for pending mail addressed to this agent without consuming it.",
@@ -4270,7 +4299,7 @@ var PluginAgentComposition = class {
4270
4299
 
4271
4300
  // packages/experimental/src/zukhruf/runtime/plugin/plugin-bindings.ts
4272
4301
  var PluginBindings = class {
4273
- #values;
4302
+ #bindings;
4274
4303
  constructor(definitions, bindings) {
4275
4304
  const pluginNames = /* @__PURE__ */ new Set();
4276
4305
  const capabilities = /* @__PURE__ */ new Map();
@@ -4324,7 +4353,7 @@ var PluginBindings = class {
4324
4353
  }
4325
4354
  }
4326
4355
  }
4327
- this.#values = /* @__PURE__ */ new Map();
4356
+ this.#bindings = /* @__PURE__ */ new Map();
4328
4357
  const bindingNames = /* @__PURE__ */ new Set();
4329
4358
  if (bindings) {
4330
4359
  for (const binding of bindings) {
@@ -4340,7 +4369,7 @@ var PluginBindings = class {
4340
4369
  `AgentRuntime: unused binding for capability "${binding.capability.name}"`
4341
4370
  );
4342
4371
  }
4343
- this.#values.set(binding.capability, binding.value);
4372
+ this.#bindings.set(binding.capability, binding);
4344
4373
  }
4345
4374
  }
4346
4375
  }
@@ -4348,7 +4377,7 @@ var PluginBindings = class {
4348
4377
  const declared = new Set(definition.capabilities);
4349
4378
  if (definition.capabilities) {
4350
4379
  for (const capability of definition.capabilities) {
4351
- if (!this.#values.has(capability)) {
4380
+ if (!this.#bindings.has(capability)) {
4352
4381
  throw new Error(
4353
4382
  `AgentRuntime: plugin "${definition.name}" requires missing capability "${capability.name}"`
4354
4383
  );
@@ -4362,7 +4391,13 @@ var PluginBindings = class {
4362
4391
  `AgentRuntime: plugin "${definition.name}" did not declare capability "${capability.name}"`
4363
4392
  );
4364
4393
  }
4365
- return this.#values.get(capability);
4394
+ const binding = this.#bindings.get(capability);
4395
+ if (!binding) {
4396
+ throw new Error(
4397
+ `AgentRuntime: plugin "${definition.name}" requires missing capability "${capability.name}"`
4398
+ );
4399
+ }
4400
+ return capability.read(binding);
4366
4401
  }
4367
4402
  };
4368
4403
  }
@@ -4394,7 +4429,7 @@ var PluginToolComposition = class {
4394
4429
  this.#owners = new Map(reservedNames.map((name) => [name, "the runtime"]));
4395
4430
  }
4396
4431
  add(plugin, tools) {
4397
- for (const [name, tool8] of Object.entries(tools)) {
4432
+ for (const [name, tool7] of Object.entries(tools)) {
4398
4433
  const owner = this.#owners.get(name);
4399
4434
  if (owner) {
4400
4435
  throw new Error(
@@ -4402,7 +4437,7 @@ var PluginToolComposition = class {
4402
4437
  );
4403
4438
  }
4404
4439
  this.#owners.set(name, `plugin "${plugin}"`);
4405
- this.#tools[name] = tool8;
4440
+ this.#tools[name] = tool7;
4406
4441
  }
4407
4442
  }
4408
4443
  compose(declarations) {
@@ -4422,6 +4457,9 @@ var PluginToolComposition = class {
4422
4457
  };
4423
4458
 
4424
4459
  // packages/experimental/src/zukhruf/runtime/plugin/plugin-manager.ts
4460
+ function createdFrom(plugin, definition) {
4461
+ return plugin.definition === definition;
4462
+ }
4425
4463
  var PluginManager = class {
4426
4464
  collaborationTools;
4427
4465
  declarations;
@@ -4485,7 +4523,7 @@ var PluginManager = class {
4485
4523
  }
4486
4524
  get(definition) {
4487
4525
  const plugin = this.#plugins.find(
4488
- ({ definition: candidate }) => candidate === definition
4526
+ (candidate) => createdFrom(candidate, definition)
4489
4527
  );
4490
4528
  if (!plugin) {
4491
4529
  throw new Error(
@@ -4546,11 +4584,25 @@ var PluginManager = class {
4546
4584
  // packages/experimental/src/zukhruf/runtime/agent-runtime.ts
4547
4585
  var AgentPluginCapability = class {
4548
4586
  name;
4587
+ /** Each value this capability bound, keyed by the binding that carries it. */
4588
+ #bound = /* @__PURE__ */ new WeakMap();
4549
4589
  constructor(name) {
4550
4590
  this.name = name;
4551
4591
  }
4552
4592
  bind(value) {
4553
- return { capability: this, value };
4593
+ const binding = { capability: this, value };
4594
+ this.#bound.set(binding, { value });
4595
+ return binding;
4596
+ }
4597
+ /** Reads the value of a binding this capability created with `bind`. */
4598
+ read(binding) {
4599
+ const bound = this.#bound.get(binding);
4600
+ if (!bound) {
4601
+ throw new Error(
4602
+ `AgentRuntime: binding for capability "${this.name}" was not created by its bind()`
4603
+ );
4604
+ }
4605
+ return bound.value;
4554
4606
  }
4555
4607
  };
4556
4608
  var AgentObservation = class {
@@ -4957,6 +5009,7 @@ var RuntimeHost = class {
4957
5009
 
4958
5010
  // packages/experimental/src/zukhruf/queue/pg-boss-notifications.ts
4959
5011
  import { EventEmitter as EventEmitter2, on as on2 } from "node:events";
5012
+ var RESET = /* @__PURE__ */ Symbol("reset");
4960
5013
  async function pgBossNotifications(boss, channel, parse, signal) {
4961
5014
  signal.throwIfAborted();
4962
5015
  const db = boss.getDb();
@@ -4970,13 +5023,10 @@ async function pgBossNotifications(boss, channel, parse, signal) {
4970
5023
  const handle = await listen(
4971
5024
  channel,
4972
5025
  (payload) => {
4973
- const value = parse(payload);
4974
- if (value !== void 0) {
4975
- emitter.emit("notification", { type: "change", value });
4976
- }
5026
+ emitter.emit("notification", payload);
4977
5027
  },
4978
5028
  () => {
4979
- if (ready) emitter.emit("notification", { type: "reset" });
5029
+ if (ready) emitter.emit("notification", RESET);
4980
5030
  }
4981
5031
  );
4982
5032
  ready = true;
@@ -4987,8 +5037,14 @@ async function pgBossNotifications(boss, channel, parse, signal) {
4987
5037
  return {
4988
5038
  async *[Symbol.asyncIterator]() {
4989
5039
  try {
4990
- for await (const [notification] of notifications) {
4991
- yield notification;
5040
+ for await (const event of notifications) {
5041
+ const [payload] = event;
5042
+ if (payload === RESET) {
5043
+ yield { type: "reset" };
5044
+ } else if (typeof payload === "string") {
5045
+ const value = parse(payload);
5046
+ if (value !== void 0) yield { type: "change", value };
5047
+ }
4992
5048
  }
4993
5049
  } finally {
4994
5050
  await handle.close();
@@ -5073,11 +5129,8 @@ function defineSandbox(createBackend, options) {
5073
5129
  }
5074
5130
 
5075
5131
  // packages/experimental/src/zukhruf/tool.ts
5076
- import {
5077
- tool as tool7
5078
- } from "ai";
5079
5132
  function defineTool(definition) {
5080
- return tool7(definition);
5133
+ return definition;
5081
5134
  }
5082
5135
  export {
5083
5136
  coding_agent_reminders_exports as codingAgentReminders,