@deepagents/experimental 7.1.0 → 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 (42) hide show
  1. package/README.md +0 -1
  2. package/dist/index.js +186 -232
  3. package/dist/index.js.map +4 -4
  4. package/dist/providers/account-tokens.d.ts +0 -2
  5. package/dist/providers/account-tokens.d.ts.map +1 -1
  6. package/dist/providers/claude/index.js +67 -78
  7. package/dist/providers/claude/index.js.map +3 -3
  8. package/dist/providers/claude/local-credentials.d.ts +1 -1
  9. package/dist/providers/claude/local-credentials.d.ts.map +1 -1
  10. package/dist/providers/codex/index.js +65 -76
  11. package/dist/providers/codex/index.js.map +3 -3
  12. package/dist/providers/codex/local-credentials.d.ts +1 -1
  13. package/dist/providers/codex/local-credentials.d.ts.map +1 -1
  14. package/dist/zukhruf/index.d.ts +0 -1
  15. package/dist/zukhruf/index.d.ts.map +1 -1
  16. package/dist/zukhruf/index.js +186 -232
  17. package/dist/zukhruf/index.js.map +4 -4
  18. package/dist/zukhruf/mailbox/coordinator.d.ts.map +1 -1
  19. package/dist/zukhruf/mailbox/sqlite.store.d.ts.map +1 -1
  20. package/dist/zukhruf/plugins/conversation-scheduling/index.js +13 -0
  21. package/dist/zukhruf/plugins/conversation-scheduling/index.js.map +3 -3
  22. package/dist/zukhruf/plugins/http/index.d.ts.map +1 -1
  23. package/dist/zukhruf/plugins/http/index.js +20 -164
  24. package/dist/zukhruf/plugins/http/index.js.map +4 -4
  25. package/dist/zukhruf/plugins/schedules/http.d.ts.map +1 -1
  26. package/dist/zukhruf/plugins/schedules/http.js +37 -180
  27. package/dist/zukhruf/plugins/schedules/http.js.map +4 -4
  28. package/dist/zukhruf/plugins/schedules/index.js +13 -0
  29. package/dist/zukhruf/plugins/schedules/index.js.map +3 -3
  30. package/dist/zukhruf/plugins/uploads/http.d.ts.map +1 -1
  31. package/dist/zukhruf/plugins/uploads/http.js +30 -173
  32. package/dist/zukhruf/plugins/uploads/http.js.map +4 -4
  33. package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts +6 -2
  34. package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts.map +1 -1
  35. package/dist/zukhruf/runtime/conversation-status/projector.d.ts.map +1 -1
  36. package/package.json +23 -9
  37. package/dist/zukhruf/plugins/http/parse.d.ts +0 -3
  38. package/dist/zukhruf/plugins/http/parse.d.ts.map +0 -1
  39. package/dist/zukhruf/plugins/http/validator.d.ts +0 -34
  40. package/dist/zukhruf/plugins/http/validator.d.ts.map +0 -1
  41. package/dist/zukhruf/render-turn.d.ts +0 -9
  42. package/dist/zukhruf/render-turn.d.ts.map +0 -1
@@ -299,7 +299,6 @@ var mailboxItemRowsSchema = z.array(
299
299
  );
300
300
  var SqliteMailboxStore = class extends MailboxStore {
301
301
  #database;
302
- #closed = false;
303
302
  constructor(path3) {
304
303
  super();
305
304
  this.#database = new DatabaseSync(path3, { timeout: BUSY_TIMEOUT_MS });
@@ -441,8 +440,7 @@ var SqliteMailboxStore = class extends MailboxStore {
441
440
  }
442
441
  }
443
442
  close() {
444
- if (this.#closed) return;
445
- this.#closed = true;
443
+ if (!this.#database.isOpen) return;
446
444
  this.#database.close();
447
445
  }
448
446
  [Symbol.dispose]() {
@@ -462,87 +460,115 @@ var TurnQueue = class {
462
460
  // packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
463
461
  var MAX_TIMEOUT_MS = 2147483647;
464
462
  var queueCatalogRowSchema = z2.object({ table: z2.string() });
463
+ function deadLetterQueueOf(queue) {
464
+ return `${queue}-dead`;
465
+ }
465
466
  var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
466
467
  #boss;
467
468
  #queue;
468
469
  #schema;
469
- #schemaConfigurationError;
470
470
  #table;
471
- #expireInSeconds;
472
471
  #cancelIntentTtlMs;
473
- #heartbeatSeconds;
474
472
  #pollingIntervalSeconds;
475
473
  #active = /* @__PURE__ */ new Map();
474
+ /** Cancels that arrived before a local worker runs the turn; each expires on its own timer. */
476
475
  #cancelIntents = /* @__PURE__ */ new Map();
477
- #cancelIntentExpiryTimer;
478
- constructor(boss, options = {}) {
476
+ constructor(boss, settings, table) {
479
477
  super();
480
478
  this.#boss = boss;
481
- this.#queue = options.queue ?? "zukhruf-turns";
479
+ this.#queue = settings.queue;
480
+ this.#schema = settings.schema;
481
+ this.#table = table;
482
+ this.#cancelIntentTtlMs = settings.expireInSeconds * 1e3;
483
+ this.#pollingIntervalSeconds = settings.pollingIntervalSeconds;
484
+ }
485
+ /**
486
+ * Opens the queue: creates the turn queue and its dead-letter queue when
487
+ * they are missing, and checks that the schema is the PgBoss schema.
488
+ */
489
+ static async create(boss, options = {}) {
490
+ const settings = _PgBossTurnQueue.#settings(boss, options);
491
+ const table = await _PgBossTurnQueue.#openQueue(boss, settings);
492
+ return new _PgBossTurnQueue(boss, settings, table);
493
+ }
494
+ static #settings(boss, options) {
482
495
  const db = boss.getDb();
483
496
  const configuredSchema = "config" in db && isRecord(db.config) ? db.config.schema : void 0;
484
497
  const bossSchema = typeof configuredSchema === "string" ? configuredSchema : void 0;
485
- this.#schema = options.schema ?? bossSchema ?? "pgboss";
498
+ const expireInSeconds = options.expireInSeconds ?? 3600;
499
+ const cancelIntentTtlMs = expireInSeconds * 1e3;
500
+ if (!Number.isFinite(expireInSeconds) || expireInSeconds <= 0 || !Number.isSafeInteger(cancelIntentTtlMs) || cancelIntentTtlMs > Number.MAX_SAFE_INTEGER - Date.now()) {
501
+ throw new Error(
502
+ "PgBossTurnQueue expireInSeconds must be a finite positive duration"
503
+ );
504
+ }
486
505
  if (options.schema === void 0 && bossSchema === void 0) {
487
- this.#schemaConfigurationError = "PgBossTurnQueue cannot read the schema from a custom PgBoss database adapter; pass the PgBoss schema in options.schema";
488
- } else if (options.schema !== void 0 && bossSchema !== void 0 && options.schema !== bossSchema) {
489
- this.#schemaConfigurationError = `PgBossTurnQueue schema "${options.schema}" does not match the PgBoss schema "${bossSchema}"`;
506
+ throw new Error(
507
+ "PgBossTurnQueue cannot read the schema from a custom PgBoss database adapter; pass the PgBoss schema in options.schema"
508
+ );
490
509
  }
491
- this.#expireInSeconds = options.expireInSeconds ?? 3600;
492
- this.#cancelIntentTtlMs = this.#expireInSeconds * 1e3;
493
- if (!Number.isFinite(this.#expireInSeconds) || this.#expireInSeconds <= 0 || !Number.isSafeInteger(this.#cancelIntentTtlMs) || this.#cancelIntentTtlMs > Number.MAX_SAFE_INTEGER - Date.now()) {
510
+ if (options.schema !== void 0 && bossSchema !== void 0 && options.schema !== bossSchema) {
494
511
  throw new Error(
495
- "PgBossTurnQueue expireInSeconds must be a finite positive duration"
512
+ `PgBossTurnQueue schema "${options.schema}" does not match the PgBoss schema "${bossSchema}"`
496
513
  );
497
514
  }
498
- this.#heartbeatSeconds = options.heartbeatSeconds ?? 30;
499
- this.#pollingIntervalSeconds = options.pollingIntervalSeconds ?? 1;
500
- }
501
- get queue() {
502
- return this.#queue;
503
- }
504
- get deadLetterQueue() {
505
- return `${this.#queue}-dead`;
515
+ return {
516
+ queue: options.queue ?? "zukhruf-turns",
517
+ schema: options.schema ?? bossSchema ?? "pgboss",
518
+ expireInSeconds,
519
+ heartbeatSeconds: options.heartbeatSeconds ?? 30,
520
+ pollingIntervalSeconds: options.pollingIntervalSeconds ?? 1
521
+ };
506
522
  }
507
- async initialize() {
508
- if (this.#schemaConfigurationError) {
509
- throw new Error(this.#schemaConfigurationError);
510
- }
511
- if (!await this.#boss.getQueue(this.deadLetterQueue)) {
512
- await this.#boss.createQueue(this.deadLetterQueue);
523
+ /** Creates the queues when they are missing; returns the turn queue's job table. */
524
+ static async #openQueue(boss, settings) {
525
+ const deadLetterQueue = deadLetterQueueOf(settings.queue);
526
+ if (!await boss.getQueue(deadLetterQueue)) {
527
+ await boss.createQueue(deadLetterQueue);
513
528
  }
514
- let queue = await this.#boss.getQueue(this.#queue);
529
+ let queue = await boss.getQueue(settings.queue);
515
530
  if (!queue) {
516
- await this.#boss.createQueue(this.#queue, {
531
+ await boss.createQueue(settings.queue, {
517
532
  policy: "key_strict_fifo",
518
533
  retryLimit: 0,
519
- expireInSeconds: this.#expireInSeconds,
520
- heartbeatSeconds: this.#heartbeatSeconds,
534
+ expireInSeconds: settings.expireInSeconds,
535
+ heartbeatSeconds: settings.heartbeatSeconds,
521
536
  deleteAfterSeconds: 0,
522
- deadLetter: this.deadLetterQueue
537
+ deadLetter: deadLetterQueue
523
538
  });
524
- queue = await this.#boss.getQueue(this.#queue);
539
+ queue = await boss.getQueue(settings.queue);
525
540
  }
526
- if (!queue) throw new Error(`Queue "${this.#queue}" was not initialized`);
527
- this.#table = queue.table;
541
+ if (!queue) {
542
+ throw new Error(`Queue "${settings.queue}" was not initialized`);
543
+ }
544
+ const { table } = queue;
528
545
  try {
529
- const catalog = await this.#boss.getDb().executeSql(
546
+ const catalog = await boss.getDb().executeSql(
530
547
  `SELECT table_name AS "table"
531
- FROM ${_PgBossTurnQueue.#quoteIdentifier(this.#schema)}."queue"
548
+ FROM ${_PgBossTurnQueue.#quoteIdentifier(settings.schema)}."queue"
532
549
  WHERE name = $1`,
533
- [this.#queue]
550
+ [settings.queue]
534
551
  );
535
552
  const catalogRow = queueCatalogRowSchema.safeParse(catalog.rows[0]);
536
- if (catalog.rows.length !== 1 || !catalogRow.success || catalogRow.data.table !== this.#table) {
553
+ if (catalog.rows.length !== 1 || !catalogRow.success || catalogRow.data.table !== table) {
537
554
  throw new Error("queue catalog does not match");
538
555
  }
539
- await this.#boss.getDb().executeSql(`SELECT 1 FROM ${this.#relation()} WHERE false`);
556
+ await boss.getDb().executeSql(
557
+ `SELECT 1 FROM ${_PgBossTurnQueue.#relationOf(settings.schema, table)} WHERE false`
558
+ );
540
559
  } catch (cause) {
541
560
  throw new Error(
542
- `PgBossTurnQueue schema "${this.#schema}" does not match the PgBoss queue; pass the PgBoss schema in options.schema`,
561
+ `PgBossTurnQueue schema "${settings.schema}" does not match the PgBoss queue; pass the PgBoss schema in options.schema`,
543
562
  { cause }
544
563
  );
545
564
  }
565
+ return table;
566
+ }
567
+ get queue() {
568
+ return this.#queue;
569
+ }
570
+ get deadLetterQueue() {
571
+ return deadLetterQueueOf(this.#queue);
546
572
  }
547
573
  async push(turn) {
548
574
  const jobId = uuidv7();
@@ -591,6 +617,7 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
591
617
  }
592
618
  }
593
619
  async consume(handler, options) {
620
+ const disposal = new AbortController();
594
621
  const turnWorkerId = await this.#boss.work(
595
622
  this.#queue,
596
623
  {
@@ -598,6 +625,10 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
598
625
  pollingIntervalSeconds: this.#pollingIntervalSeconds
599
626
  },
600
627
  async ([job]) => {
628
+ if (disposal.signal.aborted) {
629
+ await this.#handBack(this.#queue, job.id);
630
+ return;
631
+ }
601
632
  let parked = false;
602
633
  const localAbort = new AbortController();
603
634
  const active = this.#active.get(job.data.streamId) ?? /* @__PURE__ */ new Set();
@@ -639,6 +670,10 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
639
670
  pollingIntervalSeconds: this.#pollingIntervalSeconds
640
671
  },
641
672
  async ([job]) => {
673
+ if (disposal.signal.aborted) {
674
+ await this.#handBack(this.deadLetterQueue, job.id);
675
+ return;
676
+ }
642
677
  try {
643
678
  await options.onOrphaned(
644
679
  job.data,
@@ -654,6 +689,7 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
654
689
  );
655
690
  return {
656
691
  [Symbol.asyncDispose]: async () => {
692
+ disposal.abort();
657
693
  await this.#boss.offWork(this.#queue, {
658
694
  id: turnWorkerId,
659
695
  wait: options.waitForActive
@@ -685,50 +721,40 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
685
721
  }
686
722
  }
687
723
  #rememberCancelIntent(streamId) {
688
- this.#pruneCancelIntents();
689
- this.#cancelIntents.set(streamId, Date.now() + this.#cancelIntentTtlMs);
690
- this.#scheduleCancelIntentExpiry();
724
+ this.#forgetCancelIntent(streamId);
725
+ this.#armCancelIntent(streamId, Date.now() + this.#cancelIntentTtlMs);
691
726
  }
692
- #hasCancelIntent(streamId) {
693
- this.#pruneCancelIntents();
694
- return this.#cancelIntents.has(streamId);
695
- }
696
- #pruneCancelIntents() {
697
- const now = Date.now();
698
- for (const [streamId, expiresAt] of this.#cancelIntents) {
699
- if (expiresAt <= now) this.#cancelIntents.delete(streamId);
700
- }
701
- this.#scheduleCancelIntentExpiry();
702
- }
703
- #forgetCancelIntent(streamId) {
704
- this.#cancelIntents.delete(streamId);
705
- this.#scheduleCancelIntentExpiry();
706
- }
707
- #scheduleCancelIntentExpiry() {
708
- if (this.#cancelIntentExpiryTimer !== void 0) {
709
- globalThis.clearTimeout(this.#cancelIntentExpiryTimer);
710
- this.#cancelIntentExpiryTimer = void 0;
711
- }
712
- let nextExpiry = Number.POSITIVE_INFINITY;
713
- for (const expiresAt of this.#cancelIntents.values()) {
714
- nextExpiry = Math.min(nextExpiry, expiresAt);
715
- }
716
- if (!Number.isFinite(nextExpiry)) return;
727
+ #armCancelIntent(streamId, expiresAt) {
717
728
  const timer = globalThis.setTimeout(
718
729
  () => {
719
- if (this.#cancelIntentExpiryTimer !== timer) return;
720
- this.#cancelIntentExpiryTimer = void 0;
721
- this.#pruneCancelIntents();
730
+ if (Date.now() < expiresAt) this.#armCancelIntent(streamId, expiresAt);
731
+ else this.#cancelIntents.delete(streamId);
722
732
  },
723
- Math.min(MAX_TIMEOUT_MS, Math.max(1, nextExpiry - Date.now()))
733
+ Math.min(MAX_TIMEOUT_MS, Math.max(1, expiresAt - Date.now()))
724
734
  );
725
- this.#cancelIntentExpiryTimer = timer;
726
735
  timer.unref();
736
+ this.#cancelIntents.set(streamId, { expiresAt, timer });
737
+ }
738
+ #hasCancelIntent(streamId) {
739
+ const intent = this.#cancelIntents.get(streamId);
740
+ return intent !== void 0 && intent.expiresAt > Date.now();
741
+ }
742
+ #forgetCancelIntent(streamId) {
743
+ globalThis.clearTimeout(this.#cancelIntents.get(streamId)?.timer);
744
+ this.#cancelIntents.delete(streamId);
745
+ }
746
+ /**
747
+ * Returns a claimed job to its queue unrun, in its original order: cancel
748
+ * releases its strict-FIFO key, as parking does, and resume makes it
749
+ * fetchable again with its id, created_on and retry count unchanged.
750
+ * pg-boss's later completion of the job finds it no longer active and
751
+ * changes nothing.
752
+ */
753
+ async #handBack(queue, id) {
754
+ await this.#boss.cancel(queue, id);
755
+ await this.#boss.resume(queue, id);
727
756
  }
728
757
  async #deleteIfStillQueued(ids) {
729
- if (!this.#table) {
730
- throw new Error("PgBossTurnQueue.initialize() must run before cancel()");
731
- }
732
758
  await this.#boss.getDb().executeSql(
733
759
  `DELETE FROM ${this.#relation()}
734
760
  WHERE name = $1
@@ -738,12 +764,10 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
738
764
  );
739
765
  }
740
766
  #relation() {
741
- if (!this.#table) {
742
- throw new Error(
743
- "PgBossTurnQueue.initialize() must resolve its job table"
744
- );
745
- }
746
- return `${_PgBossTurnQueue.#quoteIdentifier(this.#schema)}.${_PgBossTurnQueue.#quoteIdentifier(this.#table)}`;
767
+ return _PgBossTurnQueue.#relationOf(this.#schema, this.#table);
768
+ }
769
+ static #relationOf(schema, table) {
770
+ return `${_PgBossTurnQueue.#quoteIdentifier(schema)}.${_PgBossTurnQueue.#quoteIdentifier(table)}`;
747
771
  }
748
772
  static #quoteIdentifier(identifier) {
749
773
  return `"${identifier.replaceAll('"', '""')}"`;
@@ -773,79 +797,6 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
773
797
  }
774
798
  };
775
799
 
776
- // packages/experimental/src/zukhruf/render-turn.ts
777
- import { styleText } from "node:util";
778
- import { isRecord as isRecord2 } from "@deepagents/context";
779
- var dim = (text) => styleText("dim", text);
780
- var red = (text) => styleText("red", text);
781
- function oneLine(value, max = 88) {
782
- const text = String(value ?? "").replaceAll(/\s+/g, " ").trim();
783
- return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
784
- }
785
- function describeToolCall(toolName, input) {
786
- const args = isRecord2(input) ? input : {};
787
- switch (toolName) {
788
- case "spawn_agent":
789
- return `\u21C4 spawn ${args.agent_type} "${args.task_name}" \u2014 ${args.message}`;
790
- case "send_message":
791
- return `\u21C4 mail ${args.target} \u2014 ${args.message}`;
792
- case "followup_task":
793
- return `\u21C4 follow-up ${args.target} \u2014 ${args.message}`;
794
- case "list_agents":
795
- return "\u21C4 list agents";
796
- default:
797
- return `\xB7 ${toolName}`;
798
- }
799
- }
800
- async function renderTurn(stream) {
801
- const toolNames = /* @__PURE__ */ new Map();
802
- let midText = false;
803
- let thinkingShown = false;
804
- const breakText = () => {
805
- if (midText) process.stdout.write("\n");
806
- midText = false;
807
- };
808
- for await (const chunk of stream) {
809
- switch (chunk.type) {
810
- case "reasoning-start":
811
- if (!thinkingShown) {
812
- console.log(dim("\u2026"));
813
- thinkingShown = true;
814
- }
815
- break;
816
- case "text-delta":
817
- process.stdout.write(chunk.delta);
818
- midText = true;
819
- break;
820
- case "text-end":
821
- breakText();
822
- break;
823
- case "tool-input-available":
824
- toolNames.set(chunk.toolCallId, chunk.toolName);
825
- breakText();
826
- console.log(dim(describeToolCall(chunk.toolName, chunk.input)));
827
- break;
828
- case "tool-output-error":
829
- breakText();
830
- console.log(
831
- red(
832
- `\u2717 ${toolNames.get(chunk.toolCallId) ?? "tool"}: ${oneLine(chunk.errorText)}`
833
- )
834
- );
835
- break;
836
- case "error":
837
- breakText();
838
- console.log(red(`\u2717 ${oneLine(chunk.errorText)}`));
839
- break;
840
- case "abort":
841
- breakText();
842
- console.log(dim("\xB7 turn aborted"));
843
- break;
844
- }
845
- }
846
- breakText();
847
- }
848
-
849
800
  // packages/experimental/src/zukhruf/runtime/agent-runtime.ts
850
801
  import {
851
802
  ContextEngine as ContextEngine5
@@ -1153,7 +1104,7 @@ var AgentHistoryForker = class {
1153
1104
  await this.#store.updateChat(child.conversation.chatId, (chat2) => {
1154
1105
  const metadata = chat2.metadata;
1155
1106
  const zukhruf = metadata?.zukhruf;
1156
- if (!isRecord3(zukhruf)) {
1107
+ if (!isRecord2(zukhruf)) {
1157
1108
  throw new Error(
1158
1109
  `spawn_agent: child chat "${child.conversation.chatId}" is missing Zukhruf metadata`
1159
1110
  );
@@ -1259,7 +1210,7 @@ var AgentHistoryForker = class {
1259
1210
  await this.#store.updateChat(child.conversation.chatId, (chat2) => {
1260
1211
  const metadata = chat2.metadata;
1261
1212
  const zukhruf = metadata?.zukhruf;
1262
- if (!isRecord3(zukhruf)) {
1213
+ if (!isRecord2(zukhruf)) {
1263
1214
  throw new Error(
1264
1215
  `spawn_agent: child chat "${child.conversation.chatId}" is missing Zukhruf metadata`
1265
1216
  );
@@ -1351,12 +1302,12 @@ function isForkTurnBoundary(message) {
1351
1302
  return interAgentCommunication(message)?.triggerTurn ?? true;
1352
1303
  }
1353
1304
  function interAgentCommunication(message) {
1354
- if (!isRecord3(message.metadata)) return void 0;
1305
+ if (!isRecord2(message.metadata)) return void 0;
1355
1306
  if (!Object.hasOwn(message.metadata, "interAgentCommunication")) {
1356
1307
  return void 0;
1357
1308
  }
1358
1309
  const communication = message.metadata.interAgentCommunication;
1359
- if (!isRecord3(communication) || typeof communication.triggerTurn !== "boolean") {
1310
+ if (!isRecord2(communication) || typeof communication.triggerTurn !== "boolean") {
1360
1311
  throw new Error(
1361
1312
  `spawn_agent: message "${message.id}" has invalid inter-agent metadata`
1362
1313
  );
@@ -1364,7 +1315,7 @@ function interAgentCommunication(message) {
1364
1315
  return { triggerTurn: communication.triggerTurn };
1365
1316
  }
1366
1317
  function parseHistoryForkRecord(value) {
1367
- if (!isRecord3(value)) {
1318
+ if (!isRecord2(value)) {
1368
1319
  throw new Error("spawn_agent: invalid persisted history-fork metadata");
1369
1320
  }
1370
1321
  const { forkTurns, parentChatId, parentHeadMessageId, sourceMessageIds } = value;
@@ -1383,11 +1334,11 @@ function parseHistoryForkRecord(value) {
1383
1334
  function isForkTurns(value) {
1384
1335
  return value === "none" || value === "all" || typeof value === "number" && Number.isSafeInteger(value) && value > 0;
1385
1336
  }
1386
- function isRecord3(value) {
1337
+ function isRecord2(value) {
1387
1338
  return typeof value === "object" && value !== null && !Array.isArray(value);
1388
1339
  }
1389
1340
  function isEmptyAssistantPlaceholder(value) {
1390
- return isRecord3(value) && typeof value.id === "string" && value.role === "assistant" && Array.isArray(value.parts) && value.parts.length === 0;
1341
+ return isRecord2(value) && typeof value.id === "string" && value.role === "assistant" && Array.isArray(value.parts) && value.parts.length === 0;
1391
1342
  }
1392
1343
  function arraysEqual(left, right) {
1393
1344
  return left.length === right.length && left.every((value, index) => value === right[index]);
@@ -1833,12 +1784,12 @@ var AgentControlPlane = class _AgentControlPlane {
1833
1784
 
1834
1785
  // packages/experimental/src/zukhruf/mailbox/coordinator.ts
1835
1786
  import { setTimeout as delay } from "node:timers/promises";
1787
+ import pMemoize from "p-memoize";
1836
1788
  var WAIT_POLL_INTERVAL_MS = 50;
1837
1789
  var MailboxCoordinator = class {
1838
1790
  #store;
1839
1791
  #queue;
1840
1792
  #streams;
1841
- #wakeRequests = /* @__PURE__ */ new Map();
1842
1793
  constructor(options) {
1843
1794
  this.#store = options.store;
1844
1795
  this.#queue = options.queue;
@@ -1886,11 +1837,12 @@ var MailboxCoordinator = class {
1886
1837
  });
1887
1838
  }
1888
1839
  }
1889
- #scheduleWake(target) {
1890
- const key = this.#conversationKey(target);
1891
- const existing = this.#wakeRequests.get(key);
1892
- if (existing) return existing;
1893
- const request = (async () => {
1840
+ /**
1841
+ * Coalesces only concurrent wake requests in this process. A settled request
1842
+ * is not kept, because another process may consume the wake.
1843
+ */
1844
+ #scheduleWake = pMemoize(
1845
+ async (target) => {
1894
1846
  const wakeId = AgentTurnId.random(target).toString();
1895
1847
  await this.#streams.register(wakeId);
1896
1848
  try {
@@ -1906,19 +1858,12 @@ var MailboxCoordinator = class {
1906
1858
  });
1907
1859
  throw error;
1908
1860
  }
1909
- })();
1910
- this.#wakeRequests.set(key, request);
1911
- const clearRequest = () => {
1912
- if (this.#wakeRequests.get(key) === request) {
1913
- this.#wakeRequests.delete(key);
1914
- }
1915
- };
1916
- void request.then(clearRequest, clearRequest);
1917
- return request;
1918
- }
1919
- #conversationKey(conversation) {
1920
- return JSON.stringify([conversation.chatId, conversation.userId]);
1921
- }
1861
+ },
1862
+ {
1863
+ cacheKey: ([target]) => JSON.stringify([target.chatId, target.userId]),
1864
+ cache: false
1865
+ }
1866
+ );
1922
1867
  };
1923
1868
 
1924
1869
  // packages/experimental/src/zukhruf/multi-agent-config.ts
@@ -2148,6 +2093,8 @@ function replacementRange(messages, keepLastMessages) {
2148
2093
  case "tool-approval-response":
2149
2094
  link(`approval:${part.approvalId}`, index, false);
2150
2095
  break;
2096
+ default:
2097
+ break;
2151
2098
  }
2152
2099
  }
2153
2100
  }
@@ -2303,7 +2250,7 @@ var inputUsageSchema = cacheObservationSchema.pick({ scope: true, prefixLength:
2303
2250
  function hash(value) {
2304
2251
  return createHash("sha256").update(JSON.stringify(value)).digest("hex");
2305
2252
  }
2306
- function isRecord4(value) {
2253
+ function isRecord3(value) {
2307
2254
  return typeof value === "object" && value !== null && !Array.isArray(value);
2308
2255
  }
2309
2256
  function cacheRetentionMs(step) {
@@ -2315,14 +2262,14 @@ function cacheRetentionMs(step) {
2315
2262
  return void 0;
2316
2263
  }
2317
2264
  }
2318
- if (!isRecord4(body)) return void 0;
2265
+ if (!isRecord3(body)) return void 0;
2319
2266
  const provider = step.model.provider;
2320
2267
  const routed = provider === "openrouter" || provider === "openrouter.chat";
2321
2268
  const upstream = routed ? step.providerMetadata?.openrouter?.provider : void 0;
2322
2269
  if (provider === "openai.responses" || provider === "openai.chat" || routed && upstream === "OpenAI") {
2323
2270
  const options = body.prompt_cache_options;
2324
- if (options !== void 0 && !isRecord4(options)) return void 0;
2325
- if (isRecord4(options) && options.ttl !== void 0) {
2271
+ if (options !== void 0 && !isRecord3(options)) return void 0;
2272
+ if (isRecord3(options) && options.ttl !== void 0) {
2326
2273
  return options.ttl === "30m" ? 30 * 6e4 : void 0;
2327
2274
  }
2328
2275
  const version = /^(?:openai\/)?gpt-(\d+)(?:\.(\d+))?(?:-|$)/.exec(
@@ -2342,18 +2289,18 @@ function cacheRetentionMs(step) {
2342
2289
  }
2343
2290
  const windows = [];
2344
2291
  for (const block of blocks) {
2345
- if (!isRecord4(block)) continue;
2292
+ if (!isRecord3(block)) continue;
2346
2293
  if (Array.isArray(block.content)) blocks.push(...block.content);
2347
2294
  const control = block.cache_control;
2348
2295
  if (control === void 0) continue;
2349
- if (!isRecord4(control) || control.type !== "ephemeral") return void 0;
2296
+ if (!isRecord3(control) || control.type !== "ephemeral") return void 0;
2350
2297
  if (control.ttl === void 0 || control.ttl === "5m")
2351
2298
  windows.push(5 * 6e4);
2352
2299
  else if (control.ttl === "1h") windows.push(60 * 6e4);
2353
2300
  else return void 0;
2354
2301
  }
2355
2302
  const creation = step.usage.raw?.cache_creation;
2356
- if (isRecord4(creation)) {
2303
+ if (isRecord3(creation)) {
2357
2304
  if (typeof creation.ephemeral_1h_input_tokens === "number" && creation.ephemeral_1h_input_tokens > 0)
2358
2305
  return 60 * 6e4;
2359
2306
  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)
@@ -2429,10 +2376,10 @@ function createCompaction(config, engine, store, signal, onEvent) {
2429
2376
  if (!initialized) {
2430
2377
  const chat2 = await store.getChat(engine.chatId);
2431
2378
  const metadata = chat2?.metadata?.zukhruf;
2432
- const saved = isRecord4(metadata) ? metadata.compaction : void 0;
2433
- const savedCache = isRecord4(metadata) ? metadata.promptCache : void 0;
2379
+ const saved = isRecord3(metadata) ? metadata.compaction : void 0;
2380
+ const savedCache = isRecord3(metadata) ? metadata.promptCache : void 0;
2434
2381
  baseline = inputUsageSchema.safeParse(
2435
- isRecord4(metadata) ? metadata.inputUsage : void 0
2382
+ isRecord3(metadata) ? metadata.inputUsage : void 0
2436
2383
  ).data ?? null;
2437
2384
  if (savedCache !== void 0) {
2438
2385
  cache = cacheObservationSchema.nullable().parse(savedCache);
@@ -2539,7 +2486,7 @@ function createCompaction(config, engine, store, signal, onEvent) {
2539
2486
  metadata: {
2540
2487
  ...metadata,
2541
2488
  zukhruf: {
2542
- ...isRecord4(metadata?.zukhruf) ? metadata.zukhruf : {},
2489
+ ...isRecord3(metadata?.zukhruf) ? metadata.zukhruf : {},
2543
2490
  compaction: checkpoint,
2544
2491
  inputUsage: null
2545
2492
  }
@@ -2574,7 +2521,7 @@ function createCompaction(config, engine, store, signal, onEvent) {
2574
2521
  const onStepEnd = async (step) => {
2575
2522
  if (signal.aborted || step.finishReason === "error") return;
2576
2523
  const iterations = step.usage.raw?.iterations;
2577
- const ambiguous = iterations != null && (!Array.isArray(iterations) || iterations.length !== 1 || !isRecord4(iterations[0]) || iterations[0].type !== "message") || step.content.some(
2524
+ const ambiguous = iterations != null && (!Array.isArray(iterations) || iterations.length !== 1 || !isRecord3(iterations[0]) || iterations[0].type !== "message") || step.content.some(
2578
2525
  (part) => part.type === "custom" && part.kind === "openai.compaction" || part.type === "text" && part.providerMetadata?.anthropic?.type === "compaction"
2579
2526
  );
2580
2527
  const nextBaseline = ambiguous ? null : inputUsageSchema.safeParse({
@@ -2589,7 +2536,7 @@ function createCompaction(config, engine, store, signal, onEvent) {
2589
2536
  metadata: {
2590
2537
  ...metadata,
2591
2538
  zukhruf: {
2592
- ...isRecord4(metadata?.zukhruf) ? metadata.zukhruf : {},
2539
+ ...isRecord3(metadata?.zukhruf) ? metadata.zukhruf : {},
2593
2540
  promptCache: next,
2594
2541
  inputUsage: nextBaseline
2595
2542
  }
@@ -3040,7 +2987,7 @@ var AgentTurnExecutor = class {
3040
2987
  if (turn.kind === "message" && turn.elements !== void 0) {
3041
2988
  const declared = turn.elements;
3042
2989
  await this.#store.updateChat(turn.chatId, ({ metadata }) => {
3043
- const zukhruf = isRecord5(metadata?.zukhruf) ? metadata.zukhruf : {};
2990
+ const zukhruf = isRecord4(metadata?.zukhruf) ? metadata.zukhruf : {};
3044
2991
  if (isDeepStrictEqual(zukhruf.elements, declared)) return void 0;
3045
2992
  return {
3046
2993
  metadata: {
@@ -3070,7 +3017,7 @@ var AgentTurnExecutor = class {
3070
3017
  available = persisted;
3071
3018
  return void 0;
3072
3019
  }
3073
- const zukhruf = isRecord5(metadata?.zukhruf) ? metadata.zukhruf : {};
3020
+ const zukhruf = isRecord4(metadata?.zukhruf) ? metadata.zukhruf : {};
3074
3021
  return {
3075
3022
  metadata: {
3076
3023
  ...metadata,
@@ -3140,7 +3087,7 @@ ${communication.content}`;
3140
3087
  };
3141
3088
  function readElements(metadata) {
3142
3089
  const zukhruf = metadata?.zukhruf;
3143
- if (!isRecord5(zukhruf) || !Object.hasOwn(zukhruf, "elements")) {
3090
+ if (!isRecord4(zukhruf) || !Object.hasOwn(zukhruf, "elements")) {
3144
3091
  return void 0;
3145
3092
  }
3146
3093
  const parsed = elementsSchema.safeParse(zukhruf.elements);
@@ -3151,7 +3098,7 @@ function readElements(metadata) {
3151
3098
  }
3152
3099
  function readSkills(metadata) {
3153
3100
  const zukhruf = metadata?.zukhruf;
3154
- if (!isRecord5(zukhruf) || !Object.hasOwn(zukhruf, "skills")) {
3101
+ if (!isRecord4(zukhruf) || !Object.hasOwn(zukhruf, "skills")) {
3155
3102
  return void 0;
3156
3103
  }
3157
3104
  if (!Array.isArray(zukhruf.skills) || !zukhruf.skills.every(isSkill)) {
@@ -3160,9 +3107,9 @@ function readSkills(metadata) {
3160
3107
  return zukhruf.skills;
3161
3108
  }
3162
3109
  function isSkill(value) {
3163
- return isRecord5(value) && typeof value.name === "string" && typeof value.description === "string" && typeof value.path === "string";
3110
+ return isRecord4(value) && typeof value.name === "string" && typeof value.description === "string" && typeof value.path === "string";
3164
3111
  }
3165
- function isRecord5(value) {
3112
+ function isRecord4(value) {
3166
3113
  return typeof value === "object" && value !== null && !Array.isArray(value);
3167
3114
  }
3168
3115
 
@@ -3321,6 +3268,8 @@ var ApprovalController = class _ApprovalController {
3321
3268
  };
3322
3269
 
3323
3270
  // packages/experimental/src/zukhruf/runtime/conversation-status/projector.ts
3271
+ import { Latch } from "@zukhruf/async";
3272
+ import { MemoryStore, Mutex } from "@zukhruf/mutex";
3324
3273
  import { EventEmitter, on } from "node:events";
3325
3274
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
3326
3275
  import {
@@ -3353,6 +3302,19 @@ var ProjectorEventDelivery = class {
3353
3302
  this.event = event;
3354
3303
  }
3355
3304
  };
3305
+ var Detached = class {
3306
+ // A private member keeps the type nominal: an empty class would also
3307
+ // describe RemoteAttachment, and `instanceof` could not narrow the union.
3308
+ #detached = true;
3309
+ };
3310
+ var DETACHED = new Detached();
3311
+ var RemoteAttachment = class {
3312
+ abort = new AbortController();
3313
+ /** Opens when the source subscribes: with nothing, or with the error that stopped it. */
3314
+ connected = new Latch();
3315
+ /** Opens when the consume loop has stopped. */
3316
+ ended = new Latch();
3317
+ };
3356
3318
  var ConversationStatusProjector = class _ConversationStatusProjector {
3357
3319
  #store;
3358
3320
  #streams;
@@ -3361,9 +3323,9 @@ var ConversationStatusProjector = class _ConversationStatusProjector {
3361
3323
  #changeSource;
3362
3324
  #emitter = new EventEmitter();
3363
3325
  #last = /* @__PURE__ */ new Map();
3364
- #publishing = /* @__PURE__ */ new Map();
3326
+ #publishing = new Mutex(new MemoryStore());
3365
3327
  #subscribers = 0;
3366
- #remote;
3328
+ #remote = DETACHED;
3367
3329
  constructor(options) {
3368
3330
  this.#store = options.store;
3369
3331
  this.#streams = options.streams;
@@ -3498,13 +3460,7 @@ var ConversationStatusProjector = class _ConversationStatusProjector {
3498
3460
  }
3499
3461
  #serialize(conversation, step) {
3500
3462
  const key = _ConversationStatusProjector.#key(conversation);
3501
- const previous = this.#publishing.get(key) ?? Promise.resolve();
3502
- const next = previous.then(() => step(key));
3503
- this.#publishing.set(key, next);
3504
- void next.finally(() => {
3505
- if (this.#publishing.get(key) === next) this.#publishing.delete(key);
3506
- });
3507
- return next;
3463
+ return this.#publishing.acquire(key, () => step(key));
3508
3464
  }
3509
3465
  async #project(conversation, key) {
3510
3466
  let change;
@@ -3533,34 +3489,32 @@ var ConversationStatusProjector = class _ConversationStatusProjector {
3533
3489
  this.#subscribers += 1;
3534
3490
  const source = this.#changeSource;
3535
3491
  if (!source) return;
3536
- if (!this.#remote) {
3537
- const abort = new AbortController();
3538
- const ready = Promise.withResolvers();
3539
- const remote = { abort, ready: ready.promise, done: Promise.resolve() };
3492
+ let remote = this.#remote;
3493
+ if (!(remote instanceof RemoteAttachment)) {
3494
+ remote = new RemoteAttachment();
3540
3495
  this.#remote = remote;
3541
- remote.done = this.#consumeRemote(source, remote, ready);
3496
+ void this.#consumeRemote(source, remote);
3542
3497
  }
3543
- try {
3544
- await this.#remote.ready;
3545
- } catch (error) {
3498
+ const failure = await remote.connected.wait();
3499
+ if (failure) {
3546
3500
  await this.#detachRemote();
3547
- throw error;
3501
+ throw failure.error;
3548
3502
  }
3549
3503
  }
3550
3504
  async #detachRemote() {
3551
3505
  this.#subscribers -= 1;
3552
- if (this.#subscribers > 0 || !this.#remote) return;
3553
3506
  const remote = this.#remote;
3507
+ if (this.#subscribers > 0 || !(remote instanceof RemoteAttachment)) return;
3554
3508
  remote.abort.abort();
3555
- this.#remote = void 0;
3556
- await remote.done;
3509
+ this.#remote = DETACHED;
3510
+ await remote.ended.wait();
3557
3511
  }
3558
- async #consumeRemote(source, remote, ready) {
3512
+ async #consumeRemote(source, remote) {
3559
3513
  let connected = false;
3560
3514
  try {
3561
3515
  const events = await source.subscribe(remote.abort.signal);
3562
3516
  connected = true;
3563
- ready.resolve();
3517
+ remote.connected.open(void 0);
3564
3518
  for await (const event of events) {
3565
3519
  if (event.type === "reset") {
3566
3520
  this.#emit(event);
@@ -3575,12 +3529,13 @@ var ConversationStatusProjector = class _ConversationStatusProjector {
3575
3529
  });
3576
3530
  }
3577
3531
  } catch (error) {
3578
- if (!connected) ready.reject(error);
3532
+ if (!connected) remote.connected.open({ error });
3579
3533
  if (connected && !(error instanceof Error && error.name === "AbortError")) {
3580
3534
  this.#emit({ type: "error", error });
3581
3535
  }
3582
3536
  } finally {
3583
- if (this.#remote === remote) this.#remote = void 0;
3537
+ if (this.#remote === remote) this.#remote = DETACHED;
3538
+ remote.ended.open();
3584
3539
  }
3585
3540
  }
3586
3541
  #emit(event) {
@@ -4812,7 +4767,6 @@ export {
4812
4767
  defineInstructions,
4813
4768
  defineSandbox,
4814
4769
  defineStack,
4815
- defineTool,
4816
- renderTurn
4770
+ defineTool
4817
4771
  };
4818
4772
  //# sourceMappingURL=index.js.map