@deepagents/experimental 7.1.1 → 7.1.2

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 (41) hide show
  1. package/README.md +0 -1
  2. package/dist/index.js +183 -224
  3. package/dist/index.js.map +4 -4
  4. package/dist/providers/account-tokens.d.ts.map +1 -1
  5. package/dist/providers/claude/index.js +59 -51
  6. package/dist/providers/claude/index.js.map +2 -2
  7. package/dist/providers/claude/local-credentials.d.ts +1 -1
  8. package/dist/providers/claude/local-credentials.d.ts.map +1 -1
  9. package/dist/providers/codex/index.js +57 -49
  10. package/dist/providers/codex/index.js.map +2 -2
  11. package/dist/providers/codex/local-credentials.d.ts +1 -1
  12. package/dist/providers/codex/local-credentials.d.ts.map +1 -1
  13. package/dist/zukhruf/index.d.ts +0 -1
  14. package/dist/zukhruf/index.d.ts.map +1 -1
  15. package/dist/zukhruf/index.js +183 -224
  16. package/dist/zukhruf/index.js.map +4 -4
  17. package/dist/zukhruf/mailbox/coordinator.d.ts.map +1 -1
  18. package/dist/zukhruf/mailbox/sqlite.store.d.ts.map +1 -1
  19. package/dist/zukhruf/plugins/conversation-scheduling/index.js +12 -0
  20. package/dist/zukhruf/plugins/conversation-scheduling/index.js.map +3 -3
  21. package/dist/zukhruf/plugins/http/index.d.ts.map +1 -1
  22. package/dist/zukhruf/plugins/http/index.js +20 -164
  23. package/dist/zukhruf/plugins/http/index.js.map +4 -4
  24. package/dist/zukhruf/plugins/schedules/http.d.ts.map +1 -1
  25. package/dist/zukhruf/plugins/schedules/http.js +37 -180
  26. package/dist/zukhruf/plugins/schedules/http.js.map +4 -4
  27. package/dist/zukhruf/plugins/schedules/index.js +12 -0
  28. package/dist/zukhruf/plugins/schedules/index.js.map +3 -3
  29. package/dist/zukhruf/plugins/uploads/http.d.ts.map +1 -1
  30. package/dist/zukhruf/plugins/uploads/http.js +30 -173
  31. package/dist/zukhruf/plugins/uploads/http.js.map +4 -4
  32. package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts +6 -2
  33. package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts.map +1 -1
  34. package/dist/zukhruf/runtime/conversation-status/projector.d.ts.map +1 -1
  35. package/package.json +20 -5
  36. package/dist/zukhruf/plugins/http/parse.d.ts +0 -3
  37. package/dist/zukhruf/plugins/http/parse.d.ts.map +0 -1
  38. package/dist/zukhruf/plugins/http/validator.d.ts +0 -34
  39. package/dist/zukhruf/plugins/http/validator.d.ts.map +0 -1
  40. package/dist/zukhruf/render-turn.d.ts +0 -9
  41. package/dist/zukhruf/render-turn.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -339,8 +339,7 @@ __export(zukhruf_exports, {
339
339
  defineInstructions: () => defineInstructions,
340
340
  defineSandbox: () => defineSandbox,
341
341
  defineStack: () => defineStack,
342
- defineTool: () => defineTool,
343
- renderTurn: () => renderTurn
342
+ defineTool: () => defineTool
344
343
  });
345
344
 
346
345
  // packages/experimental/src/zukhruf/agent.ts
@@ -644,7 +643,6 @@ var mailboxItemRowsSchema = z.array(
644
643
  );
645
644
  var SqliteMailboxStore = class extends MailboxStore {
646
645
  #database;
647
- #closed = false;
648
646
  constructor(path3) {
649
647
  super();
650
648
  this.#database = new DatabaseSync(path3, { timeout: BUSY_TIMEOUT_MS });
@@ -786,8 +784,7 @@ var SqliteMailboxStore = class extends MailboxStore {
786
784
  }
787
785
  }
788
786
  close() {
789
- if (this.#closed) return;
790
- this.#closed = true;
787
+ if (!this.#database.isOpen) return;
791
788
  this.#database.close();
792
789
  }
793
790
  [Symbol.dispose]() {
@@ -807,87 +804,115 @@ var TurnQueue = class {
807
804
  // packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
808
805
  var MAX_TIMEOUT_MS = 2147483647;
809
806
  var queueCatalogRowSchema = z2.object({ table: z2.string() });
807
+ function deadLetterQueueOf(queue) {
808
+ return `${queue}-dead`;
809
+ }
810
810
  var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
811
811
  #boss;
812
812
  #queue;
813
813
  #schema;
814
- #schemaConfigurationError;
815
814
  #table;
816
- #expireInSeconds;
817
815
  #cancelIntentTtlMs;
818
- #heartbeatSeconds;
819
816
  #pollingIntervalSeconds;
820
817
  #active = /* @__PURE__ */ new Map();
818
+ /** Cancels that arrived before a local worker runs the turn; each expires on its own timer. */
821
819
  #cancelIntents = /* @__PURE__ */ new Map();
822
- #cancelIntentExpiryTimer;
823
- constructor(boss, options = {}) {
820
+ constructor(boss, settings, table) {
824
821
  super();
825
822
  this.#boss = boss;
826
- this.#queue = options.queue ?? "zukhruf-turns";
823
+ this.#queue = settings.queue;
824
+ this.#schema = settings.schema;
825
+ this.#table = table;
826
+ this.#cancelIntentTtlMs = settings.expireInSeconds * 1e3;
827
+ this.#pollingIntervalSeconds = settings.pollingIntervalSeconds;
828
+ }
829
+ /**
830
+ * Opens the queue: creates the turn queue and its dead-letter queue when
831
+ * they are missing, and checks that the schema is the PgBoss schema.
832
+ */
833
+ static async create(boss, options = {}) {
834
+ const settings = _PgBossTurnQueue.#settings(boss, options);
835
+ const table = await _PgBossTurnQueue.#openQueue(boss, settings);
836
+ return new _PgBossTurnQueue(boss, settings, table);
837
+ }
838
+ static #settings(boss, options) {
827
839
  const db = boss.getDb();
828
840
  const configuredSchema = "config" in db && isRecord(db.config) ? db.config.schema : void 0;
829
841
  const bossSchema = typeof configuredSchema === "string" ? configuredSchema : void 0;
830
- this.#schema = options.schema ?? bossSchema ?? "pgboss";
842
+ const expireInSeconds = options.expireInSeconds ?? 3600;
843
+ const cancelIntentTtlMs = expireInSeconds * 1e3;
844
+ if (!Number.isFinite(expireInSeconds) || expireInSeconds <= 0 || !Number.isSafeInteger(cancelIntentTtlMs) || cancelIntentTtlMs > Number.MAX_SAFE_INTEGER - Date.now()) {
845
+ throw new Error(
846
+ "PgBossTurnQueue expireInSeconds must be a finite positive duration"
847
+ );
848
+ }
831
849
  if (options.schema === void 0 && bossSchema === void 0) {
832
- this.#schemaConfigurationError = "PgBossTurnQueue cannot read the schema from a custom PgBoss database adapter; pass the PgBoss schema in options.schema";
833
- } else if (options.schema !== void 0 && bossSchema !== void 0 && options.schema !== bossSchema) {
834
- this.#schemaConfigurationError = `PgBossTurnQueue schema "${options.schema}" does not match the PgBoss schema "${bossSchema}"`;
850
+ throw new Error(
851
+ "PgBossTurnQueue cannot read the schema from a custom PgBoss database adapter; pass the PgBoss schema in options.schema"
852
+ );
835
853
  }
836
- this.#expireInSeconds = options.expireInSeconds ?? 3600;
837
- this.#cancelIntentTtlMs = this.#expireInSeconds * 1e3;
838
- if (!Number.isFinite(this.#expireInSeconds) || this.#expireInSeconds <= 0 || !Number.isSafeInteger(this.#cancelIntentTtlMs) || this.#cancelIntentTtlMs > Number.MAX_SAFE_INTEGER - Date.now()) {
854
+ if (options.schema !== void 0 && bossSchema !== void 0 && options.schema !== bossSchema) {
839
855
  throw new Error(
840
- "PgBossTurnQueue expireInSeconds must be a finite positive duration"
856
+ `PgBossTurnQueue schema "${options.schema}" does not match the PgBoss schema "${bossSchema}"`
841
857
  );
842
858
  }
843
- this.#heartbeatSeconds = options.heartbeatSeconds ?? 30;
844
- this.#pollingIntervalSeconds = options.pollingIntervalSeconds ?? 1;
845
- }
846
- get queue() {
847
- return this.#queue;
848
- }
849
- get deadLetterQueue() {
850
- return `${this.#queue}-dead`;
859
+ return {
860
+ queue: options.queue ?? "zukhruf-turns",
861
+ schema: options.schema ?? bossSchema ?? "pgboss",
862
+ expireInSeconds,
863
+ heartbeatSeconds: options.heartbeatSeconds ?? 30,
864
+ pollingIntervalSeconds: options.pollingIntervalSeconds ?? 1
865
+ };
851
866
  }
852
- async initialize() {
853
- if (this.#schemaConfigurationError) {
854
- throw new Error(this.#schemaConfigurationError);
867
+ /** Creates the queues when they are missing; returns the turn queue's job table. */
868
+ static async #openQueue(boss, settings) {
869
+ const deadLetterQueue = deadLetterQueueOf(settings.queue);
870
+ if (!await boss.getQueue(deadLetterQueue)) {
871
+ await boss.createQueue(deadLetterQueue);
855
872
  }
856
- if (!await this.#boss.getQueue(this.deadLetterQueue)) {
857
- await this.#boss.createQueue(this.deadLetterQueue);
858
- }
859
- let queue = await this.#boss.getQueue(this.#queue);
873
+ let queue = await boss.getQueue(settings.queue);
860
874
  if (!queue) {
861
- await this.#boss.createQueue(this.#queue, {
875
+ await boss.createQueue(settings.queue, {
862
876
  policy: "key_strict_fifo",
863
877
  retryLimit: 0,
864
- expireInSeconds: this.#expireInSeconds,
865
- heartbeatSeconds: this.#heartbeatSeconds,
878
+ expireInSeconds: settings.expireInSeconds,
879
+ heartbeatSeconds: settings.heartbeatSeconds,
866
880
  deleteAfterSeconds: 0,
867
- deadLetter: this.deadLetterQueue
881
+ deadLetter: deadLetterQueue
868
882
  });
869
- queue = await this.#boss.getQueue(this.#queue);
883
+ queue = await boss.getQueue(settings.queue);
884
+ }
885
+ if (!queue) {
886
+ throw new Error(`Queue "${settings.queue}" was not initialized`);
870
887
  }
871
- if (!queue) throw new Error(`Queue "${this.#queue}" was not initialized`);
872
- this.#table = queue.table;
888
+ const { table } = queue;
873
889
  try {
874
- const catalog = await this.#boss.getDb().executeSql(
890
+ const catalog = await boss.getDb().executeSql(
875
891
  `SELECT table_name AS "table"
876
- FROM ${_PgBossTurnQueue.#quoteIdentifier(this.#schema)}."queue"
892
+ FROM ${_PgBossTurnQueue.#quoteIdentifier(settings.schema)}."queue"
877
893
  WHERE name = $1`,
878
- [this.#queue]
894
+ [settings.queue]
879
895
  );
880
896
  const catalogRow = queueCatalogRowSchema.safeParse(catalog.rows[0]);
881
- if (catalog.rows.length !== 1 || !catalogRow.success || catalogRow.data.table !== this.#table) {
897
+ if (catalog.rows.length !== 1 || !catalogRow.success || catalogRow.data.table !== table) {
882
898
  throw new Error("queue catalog does not match");
883
899
  }
884
- await this.#boss.getDb().executeSql(`SELECT 1 FROM ${this.#relation()} WHERE false`);
900
+ await boss.getDb().executeSql(
901
+ `SELECT 1 FROM ${_PgBossTurnQueue.#relationOf(settings.schema, table)} WHERE false`
902
+ );
885
903
  } catch (cause) {
886
904
  throw new Error(
887
- `PgBossTurnQueue schema "${this.#schema}" does not match the PgBoss queue; pass the PgBoss schema in options.schema`,
905
+ `PgBossTurnQueue schema "${settings.schema}" does not match the PgBoss queue; pass the PgBoss schema in options.schema`,
888
906
  { cause }
889
907
  );
890
908
  }
909
+ return table;
910
+ }
911
+ get queue() {
912
+ return this.#queue;
913
+ }
914
+ get deadLetterQueue() {
915
+ return deadLetterQueueOf(this.#queue);
891
916
  }
892
917
  async push(turn) {
893
918
  const jobId = uuidv7();
@@ -936,6 +961,7 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
936
961
  }
937
962
  }
938
963
  async consume(handler, options) {
964
+ const disposal = new AbortController();
939
965
  const turnWorkerId = await this.#boss.work(
940
966
  this.#queue,
941
967
  {
@@ -943,6 +969,10 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
943
969
  pollingIntervalSeconds: this.#pollingIntervalSeconds
944
970
  },
945
971
  async ([job]) => {
972
+ if (disposal.signal.aborted) {
973
+ await this.#handBack(this.#queue, job.id);
974
+ return;
975
+ }
946
976
  let parked = false;
947
977
  const localAbort = new AbortController();
948
978
  const active = this.#active.get(job.data.streamId) ?? /* @__PURE__ */ new Set();
@@ -984,6 +1014,10 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
984
1014
  pollingIntervalSeconds: this.#pollingIntervalSeconds
985
1015
  },
986
1016
  async ([job]) => {
1017
+ if (disposal.signal.aborted) {
1018
+ await this.#handBack(this.deadLetterQueue, job.id);
1019
+ return;
1020
+ }
987
1021
  try {
988
1022
  await options.onOrphaned(
989
1023
  job.data,
@@ -999,6 +1033,7 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
999
1033
  );
1000
1034
  return {
1001
1035
  [Symbol.asyncDispose]: async () => {
1036
+ disposal.abort();
1002
1037
  await this.#boss.offWork(this.#queue, {
1003
1038
  id: turnWorkerId,
1004
1039
  wait: options.waitForActive
@@ -1030,50 +1065,40 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
1030
1065
  }
1031
1066
  }
1032
1067
  #rememberCancelIntent(streamId) {
1033
- this.#pruneCancelIntents();
1034
- this.#cancelIntents.set(streamId, Date.now() + this.#cancelIntentTtlMs);
1035
- this.#scheduleCancelIntentExpiry();
1036
- }
1037
- #hasCancelIntent(streamId) {
1038
- this.#pruneCancelIntents();
1039
- return this.#cancelIntents.has(streamId);
1040
- }
1041
- #pruneCancelIntents() {
1042
- const now = Date.now();
1043
- for (const [streamId, expiresAt] of this.#cancelIntents) {
1044
- if (expiresAt <= now) this.#cancelIntents.delete(streamId);
1045
- }
1046
- this.#scheduleCancelIntentExpiry();
1068
+ this.#forgetCancelIntent(streamId);
1069
+ this.#armCancelIntent(streamId, Date.now() + this.#cancelIntentTtlMs);
1047
1070
  }
1048
- #forgetCancelIntent(streamId) {
1049
- this.#cancelIntents.delete(streamId);
1050
- this.#scheduleCancelIntentExpiry();
1051
- }
1052
- #scheduleCancelIntentExpiry() {
1053
- if (this.#cancelIntentExpiryTimer !== void 0) {
1054
- globalThis.clearTimeout(this.#cancelIntentExpiryTimer);
1055
- this.#cancelIntentExpiryTimer = void 0;
1056
- }
1057
- let nextExpiry = Number.POSITIVE_INFINITY;
1058
- for (const expiresAt of this.#cancelIntents.values()) {
1059
- nextExpiry = Math.min(nextExpiry, expiresAt);
1060
- }
1061
- if (!Number.isFinite(nextExpiry)) return;
1071
+ #armCancelIntent(streamId, expiresAt) {
1062
1072
  const timer = globalThis.setTimeout(
1063
1073
  () => {
1064
- if (this.#cancelIntentExpiryTimer !== timer) return;
1065
- this.#cancelIntentExpiryTimer = void 0;
1066
- this.#pruneCancelIntents();
1074
+ if (Date.now() < expiresAt) this.#armCancelIntent(streamId, expiresAt);
1075
+ else this.#cancelIntents.delete(streamId);
1067
1076
  },
1068
- Math.min(MAX_TIMEOUT_MS, Math.max(1, nextExpiry - Date.now()))
1077
+ Math.min(MAX_TIMEOUT_MS, Math.max(1, expiresAt - Date.now()))
1069
1078
  );
1070
- this.#cancelIntentExpiryTimer = timer;
1071
1079
  timer.unref();
1080
+ this.#cancelIntents.set(streamId, { expiresAt, timer });
1081
+ }
1082
+ #hasCancelIntent(streamId) {
1083
+ const intent = this.#cancelIntents.get(streamId);
1084
+ return intent !== void 0 && intent.expiresAt > Date.now();
1085
+ }
1086
+ #forgetCancelIntent(streamId) {
1087
+ globalThis.clearTimeout(this.#cancelIntents.get(streamId)?.timer);
1088
+ this.#cancelIntents.delete(streamId);
1089
+ }
1090
+ /**
1091
+ * Returns a claimed job to its queue unrun, in its original order: cancel
1092
+ * releases its strict-FIFO key, as parking does, and resume makes it
1093
+ * fetchable again with its id, created_on and retry count unchanged.
1094
+ * pg-boss's later completion of the job finds it no longer active and
1095
+ * changes nothing.
1096
+ */
1097
+ async #handBack(queue, id) {
1098
+ await this.#boss.cancel(queue, id);
1099
+ await this.#boss.resume(queue, id);
1072
1100
  }
1073
1101
  async #deleteIfStillQueued(ids) {
1074
- if (!this.#table) {
1075
- throw new Error("PgBossTurnQueue.initialize() must run before cancel()");
1076
- }
1077
1102
  await this.#boss.getDb().executeSql(
1078
1103
  `DELETE FROM ${this.#relation()}
1079
1104
  WHERE name = $1
@@ -1083,12 +1108,10 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
1083
1108
  );
1084
1109
  }
1085
1110
  #relation() {
1086
- if (!this.#table) {
1087
- throw new Error(
1088
- "PgBossTurnQueue.initialize() must resolve its job table"
1089
- );
1090
- }
1091
- return `${_PgBossTurnQueue.#quoteIdentifier(this.#schema)}.${_PgBossTurnQueue.#quoteIdentifier(this.#table)}`;
1111
+ return _PgBossTurnQueue.#relationOf(this.#schema, this.#table);
1112
+ }
1113
+ static #relationOf(schema, table) {
1114
+ return `${_PgBossTurnQueue.#quoteIdentifier(schema)}.${_PgBossTurnQueue.#quoteIdentifier(table)}`;
1092
1115
  }
1093
1116
  static #quoteIdentifier(identifier) {
1094
1117
  return `"${identifier.replaceAll('"', '""')}"`;
@@ -1118,79 +1141,6 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
1118
1141
  }
1119
1142
  };
1120
1143
 
1121
- // packages/experimental/src/zukhruf/render-turn.ts
1122
- import { styleText } from "node:util";
1123
- import { isRecord as isRecord2 } from "@deepagents/context";
1124
- var dim = (text) => styleText("dim", text);
1125
- var red = (text) => styleText("red", text);
1126
- function oneLine(value, max = 88) {
1127
- const text = String(value ?? "").replaceAll(/\s+/g, " ").trim();
1128
- return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
1129
- }
1130
- function describeToolCall(toolName, input) {
1131
- const args = isRecord2(input) ? input : {};
1132
- switch (toolName) {
1133
- case "spawn_agent":
1134
- return `\u21C4 spawn ${args.agent_type} "${args.task_name}" \u2014 ${args.message}`;
1135
- case "send_message":
1136
- return `\u21C4 mail ${args.target} \u2014 ${args.message}`;
1137
- case "followup_task":
1138
- return `\u21C4 follow-up ${args.target} \u2014 ${args.message}`;
1139
- case "list_agents":
1140
- return "\u21C4 list agents";
1141
- default:
1142
- return `\xB7 ${toolName}`;
1143
- }
1144
- }
1145
- async function renderTurn(stream) {
1146
- const toolNames = /* @__PURE__ */ new Map();
1147
- let midText = false;
1148
- let thinkingShown = false;
1149
- const breakText = () => {
1150
- if (midText) process.stdout.write("\n");
1151
- midText = false;
1152
- };
1153
- for await (const chunk of stream) {
1154
- switch (chunk.type) {
1155
- case "reasoning-start":
1156
- if (!thinkingShown) {
1157
- console.log(dim("\u2026"));
1158
- thinkingShown = true;
1159
- }
1160
- break;
1161
- case "text-delta":
1162
- process.stdout.write(chunk.delta);
1163
- midText = true;
1164
- break;
1165
- case "text-end":
1166
- breakText();
1167
- break;
1168
- case "tool-input-available":
1169
- toolNames.set(chunk.toolCallId, chunk.toolName);
1170
- breakText();
1171
- console.log(dim(describeToolCall(chunk.toolName, chunk.input)));
1172
- break;
1173
- case "tool-output-error":
1174
- breakText();
1175
- console.log(
1176
- red(
1177
- `\u2717 ${toolNames.get(chunk.toolCallId) ?? "tool"}: ${oneLine(chunk.errorText)}`
1178
- )
1179
- );
1180
- break;
1181
- case "error":
1182
- breakText();
1183
- console.log(red(`\u2717 ${oneLine(chunk.errorText)}`));
1184
- break;
1185
- case "abort":
1186
- breakText();
1187
- console.log(dim("\xB7 turn aborted"));
1188
- break;
1189
- }
1190
- }
1191
- breakText();
1192
- }
1193
-
1194
1144
  // packages/experimental/src/zukhruf/runtime/agent-runtime.ts
1195
1145
  import {
1196
1146
  ContextEngine as ContextEngine5
@@ -1498,7 +1448,7 @@ var AgentHistoryForker = class {
1498
1448
  await this.#store.updateChat(child.conversation.chatId, (chat2) => {
1499
1449
  const metadata = chat2.metadata;
1500
1450
  const zukhruf = metadata?.zukhruf;
1501
- if (!isRecord3(zukhruf)) {
1451
+ if (!isRecord2(zukhruf)) {
1502
1452
  throw new Error(
1503
1453
  `spawn_agent: child chat "${child.conversation.chatId}" is missing Zukhruf metadata`
1504
1454
  );
@@ -1604,7 +1554,7 @@ var AgentHistoryForker = class {
1604
1554
  await this.#store.updateChat(child.conversation.chatId, (chat2) => {
1605
1555
  const metadata = chat2.metadata;
1606
1556
  const zukhruf = metadata?.zukhruf;
1607
- if (!isRecord3(zukhruf)) {
1557
+ if (!isRecord2(zukhruf)) {
1608
1558
  throw new Error(
1609
1559
  `spawn_agent: child chat "${child.conversation.chatId}" is missing Zukhruf metadata`
1610
1560
  );
@@ -1696,12 +1646,12 @@ function isForkTurnBoundary(message) {
1696
1646
  return interAgentCommunication(message)?.triggerTurn ?? true;
1697
1647
  }
1698
1648
  function interAgentCommunication(message) {
1699
- if (!isRecord3(message.metadata)) return void 0;
1649
+ if (!isRecord2(message.metadata)) return void 0;
1700
1650
  if (!Object.hasOwn(message.metadata, "interAgentCommunication")) {
1701
1651
  return void 0;
1702
1652
  }
1703
1653
  const communication = message.metadata.interAgentCommunication;
1704
- if (!isRecord3(communication) || typeof communication.triggerTurn !== "boolean") {
1654
+ if (!isRecord2(communication) || typeof communication.triggerTurn !== "boolean") {
1705
1655
  throw new Error(
1706
1656
  `spawn_agent: message "${message.id}" has invalid inter-agent metadata`
1707
1657
  );
@@ -1709,7 +1659,7 @@ function interAgentCommunication(message) {
1709
1659
  return { triggerTurn: communication.triggerTurn };
1710
1660
  }
1711
1661
  function parseHistoryForkRecord(value) {
1712
- if (!isRecord3(value)) {
1662
+ if (!isRecord2(value)) {
1713
1663
  throw new Error("spawn_agent: invalid persisted history-fork metadata");
1714
1664
  }
1715
1665
  const { forkTurns, parentChatId, parentHeadMessageId, sourceMessageIds } = value;
@@ -1728,11 +1678,11 @@ function parseHistoryForkRecord(value) {
1728
1678
  function isForkTurns(value) {
1729
1679
  return value === "none" || value === "all" || typeof value === "number" && Number.isSafeInteger(value) && value > 0;
1730
1680
  }
1731
- function isRecord3(value) {
1681
+ function isRecord2(value) {
1732
1682
  return typeof value === "object" && value !== null && !Array.isArray(value);
1733
1683
  }
1734
1684
  function isEmptyAssistantPlaceholder(value) {
1735
- return isRecord3(value) && typeof value.id === "string" && value.role === "assistant" && Array.isArray(value.parts) && value.parts.length === 0;
1685
+ return isRecord2(value) && typeof value.id === "string" && value.role === "assistant" && Array.isArray(value.parts) && value.parts.length === 0;
1736
1686
  }
1737
1687
  function arraysEqual(left, right) {
1738
1688
  return left.length === right.length && left.every((value, index) => value === right[index]);
@@ -2178,12 +2128,12 @@ var AgentControlPlane = class _AgentControlPlane {
2178
2128
 
2179
2129
  // packages/experimental/src/zukhruf/mailbox/coordinator.ts
2180
2130
  import { setTimeout as delay } from "node:timers/promises";
2131
+ import pMemoize from "p-memoize";
2181
2132
  var WAIT_POLL_INTERVAL_MS = 50;
2182
2133
  var MailboxCoordinator = class {
2183
2134
  #store;
2184
2135
  #queue;
2185
2136
  #streams;
2186
- #wakeRequests = /* @__PURE__ */ new Map();
2187
2137
  constructor(options) {
2188
2138
  this.#store = options.store;
2189
2139
  this.#queue = options.queue;
@@ -2231,11 +2181,12 @@ var MailboxCoordinator = class {
2231
2181
  });
2232
2182
  }
2233
2183
  }
2234
- #scheduleWake(target) {
2235
- const key = this.#conversationKey(target);
2236
- const existing = this.#wakeRequests.get(key);
2237
- if (existing) return existing;
2238
- const request = (async () => {
2184
+ /**
2185
+ * Coalesces only concurrent wake requests in this process. A settled request
2186
+ * is not kept, because another process may consume the wake.
2187
+ */
2188
+ #scheduleWake = pMemoize(
2189
+ async (target) => {
2239
2190
  const wakeId = AgentTurnId.random(target).toString();
2240
2191
  await this.#streams.register(wakeId);
2241
2192
  try {
@@ -2251,19 +2202,12 @@ var MailboxCoordinator = class {
2251
2202
  });
2252
2203
  throw error;
2253
2204
  }
2254
- })();
2255
- this.#wakeRequests.set(key, request);
2256
- const clearRequest = () => {
2257
- if (this.#wakeRequests.get(key) === request) {
2258
- this.#wakeRequests.delete(key);
2259
- }
2260
- };
2261
- void request.then(clearRequest, clearRequest);
2262
- return request;
2263
- }
2264
- #conversationKey(conversation) {
2265
- return JSON.stringify([conversation.chatId, conversation.userId]);
2266
- }
2205
+ },
2206
+ {
2207
+ cacheKey: ([target]) => JSON.stringify([target.chatId, target.userId]),
2208
+ cache: false
2209
+ }
2210
+ );
2267
2211
  };
2268
2212
 
2269
2213
  // packages/experimental/src/zukhruf/multi-agent-config.ts
@@ -2493,6 +2437,8 @@ function replacementRange(messages, keepLastMessages) {
2493
2437
  case "tool-approval-response":
2494
2438
  link(`approval:${part.approvalId}`, index, false);
2495
2439
  break;
2440
+ default:
2441
+ break;
2496
2442
  }
2497
2443
  }
2498
2444
  }
@@ -2648,7 +2594,7 @@ var inputUsageSchema = cacheObservationSchema.pick({ scope: true, prefixLength:
2648
2594
  function hash(value) {
2649
2595
  return createHash("sha256").update(JSON.stringify(value)).digest("hex");
2650
2596
  }
2651
- function isRecord4(value) {
2597
+ function isRecord3(value) {
2652
2598
  return typeof value === "object" && value !== null && !Array.isArray(value);
2653
2599
  }
2654
2600
  function cacheRetentionMs(step) {
@@ -2660,14 +2606,14 @@ function cacheRetentionMs(step) {
2660
2606
  return void 0;
2661
2607
  }
2662
2608
  }
2663
- if (!isRecord4(body)) return void 0;
2609
+ if (!isRecord3(body)) return void 0;
2664
2610
  const provider = step.model.provider;
2665
2611
  const routed = provider === "openrouter" || provider === "openrouter.chat";
2666
2612
  const upstream = routed ? step.providerMetadata?.openrouter?.provider : void 0;
2667
2613
  if (provider === "openai.responses" || provider === "openai.chat" || routed && upstream === "OpenAI") {
2668
2614
  const options = body.prompt_cache_options;
2669
- if (options !== void 0 && !isRecord4(options)) return void 0;
2670
- if (isRecord4(options) && options.ttl !== void 0) {
2615
+ if (options !== void 0 && !isRecord3(options)) return void 0;
2616
+ if (isRecord3(options) && options.ttl !== void 0) {
2671
2617
  return options.ttl === "30m" ? 30 * 6e4 : void 0;
2672
2618
  }
2673
2619
  const version = /^(?:openai\/)?gpt-(\d+)(?:\.(\d+))?(?:-|$)/.exec(
@@ -2687,18 +2633,18 @@ function cacheRetentionMs(step) {
2687
2633
  }
2688
2634
  const windows = [];
2689
2635
  for (const block of blocks) {
2690
- if (!isRecord4(block)) continue;
2636
+ if (!isRecord3(block)) continue;
2691
2637
  if (Array.isArray(block.content)) blocks.push(...block.content);
2692
2638
  const control = block.cache_control;
2693
2639
  if (control === void 0) continue;
2694
- if (!isRecord4(control) || control.type !== "ephemeral") return void 0;
2640
+ if (!isRecord3(control) || control.type !== "ephemeral") return void 0;
2695
2641
  if (control.ttl === void 0 || control.ttl === "5m")
2696
2642
  windows.push(5 * 6e4);
2697
2643
  else if (control.ttl === "1h") windows.push(60 * 6e4);
2698
2644
  else return void 0;
2699
2645
  }
2700
2646
  const creation = step.usage.raw?.cache_creation;
2701
- if (isRecord4(creation)) {
2647
+ if (isRecord3(creation)) {
2702
2648
  if (typeof creation.ephemeral_1h_input_tokens === "number" && creation.ephemeral_1h_input_tokens > 0)
2703
2649
  return 60 * 6e4;
2704
2650
  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)
@@ -2774,10 +2720,10 @@ function createCompaction(config, engine, store, signal, onEvent) {
2774
2720
  if (!initialized) {
2775
2721
  const chat2 = await store.getChat(engine.chatId);
2776
2722
  const metadata = chat2?.metadata?.zukhruf;
2777
- const saved = isRecord4(metadata) ? metadata.compaction : void 0;
2778
- const savedCache = isRecord4(metadata) ? metadata.promptCache : void 0;
2723
+ const saved = isRecord3(metadata) ? metadata.compaction : void 0;
2724
+ const savedCache = isRecord3(metadata) ? metadata.promptCache : void 0;
2779
2725
  baseline = inputUsageSchema.safeParse(
2780
- isRecord4(metadata) ? metadata.inputUsage : void 0
2726
+ isRecord3(metadata) ? metadata.inputUsage : void 0
2781
2727
  ).data ?? null;
2782
2728
  if (savedCache !== void 0) {
2783
2729
  cache = cacheObservationSchema.nullable().parse(savedCache);
@@ -2884,7 +2830,7 @@ function createCompaction(config, engine, store, signal, onEvent) {
2884
2830
  metadata: {
2885
2831
  ...metadata,
2886
2832
  zukhruf: {
2887
- ...isRecord4(metadata?.zukhruf) ? metadata.zukhruf : {},
2833
+ ...isRecord3(metadata?.zukhruf) ? metadata.zukhruf : {},
2888
2834
  compaction: checkpoint,
2889
2835
  inputUsage: null
2890
2836
  }
@@ -2919,7 +2865,7 @@ function createCompaction(config, engine, store, signal, onEvent) {
2919
2865
  const onStepEnd = async (step) => {
2920
2866
  if (signal.aborted || step.finishReason === "error") return;
2921
2867
  const iterations = step.usage.raw?.iterations;
2922
- const ambiguous = iterations != null && (!Array.isArray(iterations) || iterations.length !== 1 || !isRecord4(iterations[0]) || iterations[0].type !== "message") || step.content.some(
2868
+ const ambiguous = iterations != null && (!Array.isArray(iterations) || iterations.length !== 1 || !isRecord3(iterations[0]) || iterations[0].type !== "message") || step.content.some(
2923
2869
  (part) => part.type === "custom" && part.kind === "openai.compaction" || part.type === "text" && part.providerMetadata?.anthropic?.type === "compaction"
2924
2870
  );
2925
2871
  const nextBaseline = ambiguous ? null : inputUsageSchema.safeParse({
@@ -2934,7 +2880,7 @@ function createCompaction(config, engine, store, signal, onEvent) {
2934
2880
  metadata: {
2935
2881
  ...metadata,
2936
2882
  zukhruf: {
2937
- ...isRecord4(metadata?.zukhruf) ? metadata.zukhruf : {},
2883
+ ...isRecord3(metadata?.zukhruf) ? metadata.zukhruf : {},
2938
2884
  promptCache: next,
2939
2885
  inputUsage: nextBaseline
2940
2886
  }
@@ -3385,7 +3331,7 @@ var AgentTurnExecutor = class {
3385
3331
  if (turn.kind === "message" && turn.elements !== void 0) {
3386
3332
  const declared = turn.elements;
3387
3333
  await this.#store.updateChat(turn.chatId, ({ metadata }) => {
3388
- const zukhruf = isRecord5(metadata?.zukhruf) ? metadata.zukhruf : {};
3334
+ const zukhruf = isRecord4(metadata?.zukhruf) ? metadata.zukhruf : {};
3389
3335
  if (isDeepStrictEqual(zukhruf.elements, declared)) return void 0;
3390
3336
  return {
3391
3337
  metadata: {
@@ -3415,7 +3361,7 @@ var AgentTurnExecutor = class {
3415
3361
  available = persisted;
3416
3362
  return void 0;
3417
3363
  }
3418
- const zukhruf = isRecord5(metadata?.zukhruf) ? metadata.zukhruf : {};
3364
+ const zukhruf = isRecord4(metadata?.zukhruf) ? metadata.zukhruf : {};
3419
3365
  return {
3420
3366
  metadata: {
3421
3367
  ...metadata,
@@ -3485,7 +3431,7 @@ ${communication.content}`;
3485
3431
  };
3486
3432
  function readElements(metadata) {
3487
3433
  const zukhruf = metadata?.zukhruf;
3488
- if (!isRecord5(zukhruf) || !Object.hasOwn(zukhruf, "elements")) {
3434
+ if (!isRecord4(zukhruf) || !Object.hasOwn(zukhruf, "elements")) {
3489
3435
  return void 0;
3490
3436
  }
3491
3437
  const parsed = elementsSchema.safeParse(zukhruf.elements);
@@ -3496,7 +3442,7 @@ function readElements(metadata) {
3496
3442
  }
3497
3443
  function readSkills(metadata) {
3498
3444
  const zukhruf = metadata?.zukhruf;
3499
- if (!isRecord5(zukhruf) || !Object.hasOwn(zukhruf, "skills")) {
3445
+ if (!isRecord4(zukhruf) || !Object.hasOwn(zukhruf, "skills")) {
3500
3446
  return void 0;
3501
3447
  }
3502
3448
  if (!Array.isArray(zukhruf.skills) || !zukhruf.skills.every(isSkill)) {
@@ -3505,9 +3451,9 @@ function readSkills(metadata) {
3505
3451
  return zukhruf.skills;
3506
3452
  }
3507
3453
  function isSkill(value) {
3508
- return isRecord5(value) && typeof value.name === "string" && typeof value.description === "string" && typeof value.path === "string";
3454
+ return isRecord4(value) && typeof value.name === "string" && typeof value.description === "string" && typeof value.path === "string";
3509
3455
  }
3510
- function isRecord5(value) {
3456
+ function isRecord4(value) {
3511
3457
  return typeof value === "object" && value !== null && !Array.isArray(value);
3512
3458
  }
3513
3459
 
@@ -3666,6 +3612,7 @@ var ApprovalController = class _ApprovalController {
3666
3612
  };
3667
3613
 
3668
3614
  // packages/experimental/src/zukhruf/runtime/conversation-status/projector.ts
3615
+ import { Latch } from "@zukhruf/async";
3669
3616
  import { MemoryStore, Mutex } from "@zukhruf/mutex";
3670
3617
  import { EventEmitter, on } from "node:events";
3671
3618
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
@@ -3699,6 +3646,19 @@ var ProjectorEventDelivery = class {
3699
3646
  this.event = event;
3700
3647
  }
3701
3648
  };
3649
+ var Detached = class {
3650
+ // A private member keeps the type nominal: an empty class would also
3651
+ // describe RemoteAttachment, and `instanceof` could not narrow the union.
3652
+ #detached = true;
3653
+ };
3654
+ var DETACHED = new Detached();
3655
+ var RemoteAttachment = class {
3656
+ abort = new AbortController();
3657
+ /** Opens when the source subscribes: with nothing, or with the error that stopped it. */
3658
+ connected = new Latch();
3659
+ /** Opens when the consume loop has stopped. */
3660
+ ended = new Latch();
3661
+ };
3702
3662
  var ConversationStatusProjector = class _ConversationStatusProjector {
3703
3663
  #store;
3704
3664
  #streams;
@@ -3709,7 +3669,7 @@ var ConversationStatusProjector = class _ConversationStatusProjector {
3709
3669
  #last = /* @__PURE__ */ new Map();
3710
3670
  #publishing = new Mutex(new MemoryStore());
3711
3671
  #subscribers = 0;
3712
- #remote;
3672
+ #remote = DETACHED;
3713
3673
  constructor(options) {
3714
3674
  this.#store = options.store;
3715
3675
  this.#streams = options.streams;
@@ -3873,34 +3833,32 @@ var ConversationStatusProjector = class _ConversationStatusProjector {
3873
3833
  this.#subscribers += 1;
3874
3834
  const source = this.#changeSource;
3875
3835
  if (!source) return;
3876
- if (!this.#remote) {
3877
- const abort = new AbortController();
3878
- const ready = Promise.withResolvers();
3879
- const remote = { abort, ready: ready.promise, done: Promise.resolve() };
3836
+ let remote = this.#remote;
3837
+ if (!(remote instanceof RemoteAttachment)) {
3838
+ remote = new RemoteAttachment();
3880
3839
  this.#remote = remote;
3881
- remote.done = this.#consumeRemote(source, remote, ready);
3840
+ void this.#consumeRemote(source, remote);
3882
3841
  }
3883
- try {
3884
- await this.#remote.ready;
3885
- } catch (error) {
3842
+ const failure = await remote.connected.wait();
3843
+ if (failure) {
3886
3844
  await this.#detachRemote();
3887
- throw error;
3845
+ throw failure.error;
3888
3846
  }
3889
3847
  }
3890
3848
  async #detachRemote() {
3891
3849
  this.#subscribers -= 1;
3892
- if (this.#subscribers > 0 || !this.#remote) return;
3893
3850
  const remote = this.#remote;
3851
+ if (this.#subscribers > 0 || !(remote instanceof RemoteAttachment)) return;
3894
3852
  remote.abort.abort();
3895
- this.#remote = void 0;
3896
- await remote.done;
3853
+ this.#remote = DETACHED;
3854
+ await remote.ended.wait();
3897
3855
  }
3898
- async #consumeRemote(source, remote, ready) {
3856
+ async #consumeRemote(source, remote) {
3899
3857
  let connected = false;
3900
3858
  try {
3901
3859
  const events = await source.subscribe(remote.abort.signal);
3902
3860
  connected = true;
3903
- ready.resolve();
3861
+ remote.connected.open(void 0);
3904
3862
  for await (const event of events) {
3905
3863
  if (event.type === "reset") {
3906
3864
  this.#emit(event);
@@ -3915,12 +3873,13 @@ var ConversationStatusProjector = class _ConversationStatusProjector {
3915
3873
  });
3916
3874
  }
3917
3875
  } catch (error) {
3918
- if (!connected) ready.reject(error);
3876
+ if (!connected) remote.connected.open({ error });
3919
3877
  if (connected && !(error instanceof Error && error.name === "AbortError")) {
3920
3878
  this.#emit({ type: "error", error });
3921
3879
  }
3922
3880
  } finally {
3923
- if (this.#remote === remote) this.#remote = void 0;
3881
+ if (this.#remote === remote) this.#remote = DETACHED;
3882
+ remote.ended.open();
3924
3883
  }
3925
3884
  }
3926
3885
  #emit(event) {