@deepagents/experimental 7.1.1 → 7.1.3

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 +252 -290
  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 +252 -290
  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 +14 -1
  28. package/dist/zukhruf/plugins/schedules/index.js.map +3 -3
  29. package/dist/zukhruf/plugins/schedules/scheduled-tasks.d.ts.map +1 -1
  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 +29 -13
  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
@@ -188,6 +188,7 @@ function defineInstructions(...fragments) {
188
188
  }
189
189
 
190
190
  // packages/experimental/src/zukhruf/mailbox/sqlite.store.ts
191
+ import { transaction } from "@zukhruf/sqlite-transaction";
191
192
  import { DatabaseSync } from "node:sqlite";
192
193
  import { z } from "zod";
193
194
 
@@ -299,59 +300,70 @@ var mailboxItemRowsSchema = z.array(
299
300
  );
300
301
  var SqliteMailboxStore = class extends MailboxStore {
301
302
  #database;
302
- #closed = false;
303
303
  constructor(path3) {
304
304
  super();
305
305
  this.#database = new DatabaseSync(path3, { timeout: BUSY_TIMEOUT_MS });
306
306
  this.#database.exec(DDL);
307
307
  }
308
308
  async beginTurn(recipient, turnId) {
309
- this.#transaction(() => {
310
- this.#database.prepare(
311
- `INSERT INTO zukhruf_mailbox_activity (
309
+ transaction(
310
+ this.#database,
311
+ () => {
312
+ this.#database.prepare(
313
+ `INSERT INTO zukhruf_mailbox_activity (
312
314
  recipient_chat_id,
313
315
  recipient_user_id,
314
316
  turn_id
315
317
  ) VALUES (?, ?, ?)
316
318
  ON CONFLICT (recipient_chat_id, recipient_user_id)
317
319
  DO UPDATE SET turn_id = excluded.turn_id`
318
- ).run(recipient.chatId, recipient.userId, turnId);
319
- });
320
+ ).run(recipient.chatId, recipient.userId, turnId);
321
+ },
322
+ { mode: "immediate" }
323
+ );
320
324
  }
321
325
  async enqueue(communication) {
322
- return this.#transaction(() => {
323
- const consumedTerminal = communication.type === InterAgentCommunicationTypes.FinalAnswer && this.#hasConsumedTerminal(communication.id);
324
- if (!consumedTerminal) {
325
- this.#database.prepare(
326
- `INSERT OR IGNORE INTO zukhruf_mailbox_items (
326
+ return transaction(
327
+ this.#database,
328
+ () => {
329
+ const consumedTerminal = communication.type === InterAgentCommunicationTypes.FinalAnswer && this.#hasConsumedTerminal(communication.id);
330
+ if (!consumedTerminal) {
331
+ this.#database.prepare(
332
+ `INSERT OR IGNORE INTO zukhruf_mailbox_items (
327
333
  recipient_chat_id,
328
334
  recipient_user_id,
329
335
  communication
330
336
  ) VALUES (?, ?, ?)`
331
- ).run(
332
- communication.recipient.chatId,
333
- communication.recipient.userId,
334
- JSON.stringify(communication)
335
- );
336
- }
337
- return {
338
- recipientActive: this.#isTurnActive(communication.recipient)
339
- };
340
- });
337
+ ).run(
338
+ communication.recipient.chatId,
339
+ communication.recipient.userId,
340
+ JSON.stringify(communication)
341
+ );
342
+ }
343
+ return {
344
+ recipientActive: this.#isTurnActive(communication.recipient)
345
+ };
346
+ },
347
+ { mode: "immediate" }
348
+ );
341
349
  }
342
350
  async endTurn(recipient, turnId) {
343
- return this.#transaction(() => {
344
- const result = this.#database.prepare(
345
- `DELETE FROM zukhruf_mailbox_activity
351
+ return transaction(
352
+ this.#database,
353
+ () => {
354
+ const result = this.#database.prepare(
355
+ `DELETE FROM zukhruf_mailbox_activity
346
356
  WHERE recipient_chat_id = ?
347
357
  AND recipient_user_id = ?
348
358
  AND turn_id = ?`
349
- ).run(recipient.chatId, recipient.userId, turnId);
350
- return {
351
- hasPending: this.#hasPending(recipient),
352
- turnEnded: result.changes > 0
353
- };
354
- });
359
+ ).run(recipient.chatId, recipient.userId, turnId);
360
+ return {
361
+ hasPending: this.#hasPending(recipient),
362
+ turnEnded: result.changes > 0
363
+ };
364
+ },
365
+ { mode: "immediate" }
366
+ );
355
367
  }
356
368
  async hasPending(recipient) {
357
369
  return this.#hasPending(recipient);
@@ -392,57 +404,46 @@ var SqliteMailboxStore = class extends MailboxStore {
392
404
  return this.#drain(recipient, true);
393
405
  }
394
406
  #drain(recipient, leadingQueueOnly) {
395
- return this.#transaction(() => {
396
- const items = mailboxItemRowsSchema.parse(
397
- this.#database.prepare(
398
- `SELECT sequence, communication
407
+ return transaction(
408
+ this.#database,
409
+ () => {
410
+ const items = mailboxItemRowsSchema.parse(
411
+ this.#database.prepare(
412
+ `SELECT sequence, communication
399
413
  FROM zukhruf_mailbox_items
400
414
  WHERE recipient_chat_id = ?
401
415
  AND recipient_user_id = ?
402
416
  ORDER BY sequence`
403
- ).all(recipient.chatId, recipient.userId)
404
- );
405
- const firstTrigger = leadingQueueOnly ? items.findIndex(({ communication }) => communication.triggerTurn) : -1;
406
- const consumed = firstTrigger === -1 ? items : items.slice(0, firstTrigger);
407
- const lastConsumed = consumed.at(-1);
408
- if (lastConsumed) {
409
- const tombstone = this.#database.prepare(
410
- `INSERT OR IGNORE
417
+ ).all(recipient.chatId, recipient.userId)
418
+ );
419
+ const firstTrigger = leadingQueueOnly ? items.findIndex(({ communication }) => communication.triggerTurn) : -1;
420
+ const consumed = firstTrigger === -1 ? items : items.slice(0, firstTrigger);
421
+ const lastConsumed = consumed.at(-1);
422
+ if (lastConsumed) {
423
+ const tombstone = this.#database.prepare(
424
+ `INSERT OR IGNORE
411
425
  INTO zukhruf_mailbox_consumed_terminal_ids (communication_id)
412
426
  VALUES (?)`
413
- );
414
- for (const { communication } of consumed) {
415
- if (communication.type === InterAgentCommunicationTypes.FinalAnswer) {
416
- tombstone.run(communication.id);
427
+ );
428
+ for (const { communication } of consumed) {
429
+ if (communication.type === InterAgentCommunicationTypes.FinalAnswer) {
430
+ tombstone.run(communication.id);
431
+ }
417
432
  }
418
- }
419
- this.#database.prepare(
420
- `DELETE FROM zukhruf_mailbox_items
433
+ this.#database.prepare(
434
+ `DELETE FROM zukhruf_mailbox_items
421
435
  WHERE recipient_chat_id = ?
422
436
  AND recipient_user_id = ?
423
437
  AND sequence <= ?`
424
- ).run(recipient.chatId, recipient.userId, lastConsumed.sequence);
425
- }
426
- return consumed.map(({ communication }) => communication);
427
- });
428
- }
429
- #transaction(operation) {
430
- this.#database.exec("BEGIN IMMEDIATE");
431
- try {
432
- const result = operation();
433
- this.#database.exec("COMMIT");
434
- return result;
435
- } catch (error) {
436
- try {
437
- this.#database.exec("ROLLBACK");
438
- } catch {
439
- }
440
- throw error;
441
- }
438
+ ).run(recipient.chatId, recipient.userId, lastConsumed.sequence);
439
+ }
440
+ return consumed.map(({ communication }) => communication);
441
+ },
442
+ { mode: "immediate" }
443
+ );
442
444
  }
443
445
  close() {
444
- if (this.#closed) return;
445
- this.#closed = true;
446
+ if (!this.#database.isOpen) return;
446
447
  this.#database.close();
447
448
  }
448
449
  [Symbol.dispose]() {
@@ -462,87 +463,115 @@ var TurnQueue = class {
462
463
  // packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
463
464
  var MAX_TIMEOUT_MS = 2147483647;
464
465
  var queueCatalogRowSchema = z2.object({ table: z2.string() });
466
+ function deadLetterQueueOf(queue) {
467
+ return `${queue}-dead`;
468
+ }
465
469
  var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
466
470
  #boss;
467
471
  #queue;
468
472
  #schema;
469
- #schemaConfigurationError;
470
473
  #table;
471
- #expireInSeconds;
472
474
  #cancelIntentTtlMs;
473
- #heartbeatSeconds;
474
475
  #pollingIntervalSeconds;
475
476
  #active = /* @__PURE__ */ new Map();
477
+ /** Cancels that arrived before a local worker runs the turn; each expires on its own timer. */
476
478
  #cancelIntents = /* @__PURE__ */ new Map();
477
- #cancelIntentExpiryTimer;
478
- constructor(boss, options = {}) {
479
+ constructor(boss, settings, table) {
479
480
  super();
480
481
  this.#boss = boss;
481
- this.#queue = options.queue ?? "zukhruf-turns";
482
+ this.#queue = settings.queue;
483
+ this.#schema = settings.schema;
484
+ this.#table = table;
485
+ this.#cancelIntentTtlMs = settings.expireInSeconds * 1e3;
486
+ this.#pollingIntervalSeconds = settings.pollingIntervalSeconds;
487
+ }
488
+ /**
489
+ * Opens the queue: creates the turn queue and its dead-letter queue when
490
+ * they are missing, and checks that the schema is the PgBoss schema.
491
+ */
492
+ static async create(boss, options = {}) {
493
+ const settings = _PgBossTurnQueue.#settings(boss, options);
494
+ const table = await _PgBossTurnQueue.#openQueue(boss, settings);
495
+ return new _PgBossTurnQueue(boss, settings, table);
496
+ }
497
+ static #settings(boss, options) {
482
498
  const db = boss.getDb();
483
499
  const configuredSchema = "config" in db && isRecord(db.config) ? db.config.schema : void 0;
484
500
  const bossSchema = typeof configuredSchema === "string" ? configuredSchema : void 0;
485
- this.#schema = options.schema ?? bossSchema ?? "pgboss";
501
+ const expireInSeconds = options.expireInSeconds ?? 3600;
502
+ const cancelIntentTtlMs = expireInSeconds * 1e3;
503
+ if (!Number.isFinite(expireInSeconds) || expireInSeconds <= 0 || !Number.isSafeInteger(cancelIntentTtlMs) || cancelIntentTtlMs > Number.MAX_SAFE_INTEGER - Date.now()) {
504
+ throw new Error(
505
+ "PgBossTurnQueue expireInSeconds must be a finite positive duration"
506
+ );
507
+ }
486
508
  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}"`;
509
+ throw new Error(
510
+ "PgBossTurnQueue cannot read the schema from a custom PgBoss database adapter; pass the PgBoss schema in options.schema"
511
+ );
490
512
  }
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()) {
513
+ if (options.schema !== void 0 && bossSchema !== void 0 && options.schema !== bossSchema) {
494
514
  throw new Error(
495
- "PgBossTurnQueue expireInSeconds must be a finite positive duration"
515
+ `PgBossTurnQueue schema "${options.schema}" does not match the PgBoss schema "${bossSchema}"`
496
516
  );
497
517
  }
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`;
518
+ return {
519
+ queue: options.queue ?? "zukhruf-turns",
520
+ schema: options.schema ?? bossSchema ?? "pgboss",
521
+ expireInSeconds,
522
+ heartbeatSeconds: options.heartbeatSeconds ?? 30,
523
+ pollingIntervalSeconds: options.pollingIntervalSeconds ?? 1
524
+ };
506
525
  }
507
- async initialize() {
508
- if (this.#schemaConfigurationError) {
509
- throw new Error(this.#schemaConfigurationError);
526
+ /** Creates the queues when they are missing; returns the turn queue's job table. */
527
+ static async #openQueue(boss, settings) {
528
+ const deadLetterQueue = deadLetterQueueOf(settings.queue);
529
+ if (!await boss.getQueue(deadLetterQueue)) {
530
+ await boss.createQueue(deadLetterQueue);
510
531
  }
511
- if (!await this.#boss.getQueue(this.deadLetterQueue)) {
512
- await this.#boss.createQueue(this.deadLetterQueue);
513
- }
514
- let queue = await this.#boss.getQueue(this.#queue);
532
+ let queue = await boss.getQueue(settings.queue);
515
533
  if (!queue) {
516
- await this.#boss.createQueue(this.#queue, {
534
+ await boss.createQueue(settings.queue, {
517
535
  policy: "key_strict_fifo",
518
536
  retryLimit: 0,
519
- expireInSeconds: this.#expireInSeconds,
520
- heartbeatSeconds: this.#heartbeatSeconds,
537
+ expireInSeconds: settings.expireInSeconds,
538
+ heartbeatSeconds: settings.heartbeatSeconds,
521
539
  deleteAfterSeconds: 0,
522
- deadLetter: this.deadLetterQueue
540
+ deadLetter: deadLetterQueue
523
541
  });
524
- queue = await this.#boss.getQueue(this.#queue);
542
+ queue = await boss.getQueue(settings.queue);
543
+ }
544
+ if (!queue) {
545
+ throw new Error(`Queue "${settings.queue}" was not initialized`);
525
546
  }
526
- if (!queue) throw new Error(`Queue "${this.#queue}" was not initialized`);
527
- this.#table = queue.table;
547
+ const { table } = queue;
528
548
  try {
529
- const catalog = await this.#boss.getDb().executeSql(
549
+ const catalog = await boss.getDb().executeSql(
530
550
  `SELECT table_name AS "table"
531
- FROM ${_PgBossTurnQueue.#quoteIdentifier(this.#schema)}."queue"
551
+ FROM ${_PgBossTurnQueue.#quoteIdentifier(settings.schema)}."queue"
532
552
  WHERE name = $1`,
533
- [this.#queue]
553
+ [settings.queue]
534
554
  );
535
555
  const catalogRow = queueCatalogRowSchema.safeParse(catalog.rows[0]);
536
- if (catalog.rows.length !== 1 || !catalogRow.success || catalogRow.data.table !== this.#table) {
556
+ if (catalog.rows.length !== 1 || !catalogRow.success || catalogRow.data.table !== table) {
537
557
  throw new Error("queue catalog does not match");
538
558
  }
539
- await this.#boss.getDb().executeSql(`SELECT 1 FROM ${this.#relation()} WHERE false`);
559
+ await boss.getDb().executeSql(
560
+ `SELECT 1 FROM ${_PgBossTurnQueue.#relationOf(settings.schema, table)} WHERE false`
561
+ );
540
562
  } catch (cause) {
541
563
  throw new Error(
542
- `PgBossTurnQueue schema "${this.#schema}" does not match the PgBoss queue; pass the PgBoss schema in options.schema`,
564
+ `PgBossTurnQueue schema "${settings.schema}" does not match the PgBoss queue; pass the PgBoss schema in options.schema`,
543
565
  { cause }
544
566
  );
545
567
  }
568
+ return table;
569
+ }
570
+ get queue() {
571
+ return this.#queue;
572
+ }
573
+ get deadLetterQueue() {
574
+ return deadLetterQueueOf(this.#queue);
546
575
  }
547
576
  async push(turn) {
548
577
  const jobId = uuidv7();
@@ -591,6 +620,7 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
591
620
  }
592
621
  }
593
622
  async consume(handler, options) {
623
+ const disposal = new AbortController();
594
624
  const turnWorkerId = await this.#boss.work(
595
625
  this.#queue,
596
626
  {
@@ -598,6 +628,10 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
598
628
  pollingIntervalSeconds: this.#pollingIntervalSeconds
599
629
  },
600
630
  async ([job]) => {
631
+ if (disposal.signal.aborted) {
632
+ await this.#handBack(this.#queue, job.id);
633
+ return;
634
+ }
601
635
  let parked = false;
602
636
  const localAbort = new AbortController();
603
637
  const active = this.#active.get(job.data.streamId) ?? /* @__PURE__ */ new Set();
@@ -639,6 +673,10 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
639
673
  pollingIntervalSeconds: this.#pollingIntervalSeconds
640
674
  },
641
675
  async ([job]) => {
676
+ if (disposal.signal.aborted) {
677
+ await this.#handBack(this.deadLetterQueue, job.id);
678
+ return;
679
+ }
642
680
  try {
643
681
  await options.onOrphaned(
644
682
  job.data,
@@ -654,6 +692,7 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
654
692
  );
655
693
  return {
656
694
  [Symbol.asyncDispose]: async () => {
695
+ disposal.abort();
657
696
  await this.#boss.offWork(this.#queue, {
658
697
  id: turnWorkerId,
659
698
  wait: options.waitForActive
@@ -685,50 +724,40 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
685
724
  }
686
725
  }
687
726
  #rememberCancelIntent(streamId) {
688
- this.#pruneCancelIntents();
689
- this.#cancelIntents.set(streamId, Date.now() + this.#cancelIntentTtlMs);
690
- this.#scheduleCancelIntentExpiry();
691
- }
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();
727
+ this.#forgetCancelIntent(streamId);
728
+ this.#armCancelIntent(streamId, Date.now() + this.#cancelIntentTtlMs);
706
729
  }
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;
730
+ #armCancelIntent(streamId, expiresAt) {
717
731
  const timer = globalThis.setTimeout(
718
732
  () => {
719
- if (this.#cancelIntentExpiryTimer !== timer) return;
720
- this.#cancelIntentExpiryTimer = void 0;
721
- this.#pruneCancelIntents();
733
+ if (Date.now() < expiresAt) this.#armCancelIntent(streamId, expiresAt);
734
+ else this.#cancelIntents.delete(streamId);
722
735
  },
723
- Math.min(MAX_TIMEOUT_MS, Math.max(1, nextExpiry - Date.now()))
736
+ Math.min(MAX_TIMEOUT_MS, Math.max(1, expiresAt - Date.now()))
724
737
  );
725
- this.#cancelIntentExpiryTimer = timer;
726
738
  timer.unref();
739
+ this.#cancelIntents.set(streamId, { expiresAt, timer });
740
+ }
741
+ #hasCancelIntent(streamId) {
742
+ const intent = this.#cancelIntents.get(streamId);
743
+ return intent !== void 0 && intent.expiresAt > Date.now();
744
+ }
745
+ #forgetCancelIntent(streamId) {
746
+ globalThis.clearTimeout(this.#cancelIntents.get(streamId)?.timer);
747
+ this.#cancelIntents.delete(streamId);
748
+ }
749
+ /**
750
+ * Returns a claimed job to its queue unrun, in its original order: cancel
751
+ * releases its strict-FIFO key, as parking does, and resume makes it
752
+ * fetchable again with its id, created_on and retry count unchanged.
753
+ * pg-boss's later completion of the job finds it no longer active and
754
+ * changes nothing.
755
+ */
756
+ async #handBack(queue, id) {
757
+ await this.#boss.cancel(queue, id);
758
+ await this.#boss.resume(queue, id);
727
759
  }
728
760
  async #deleteIfStillQueued(ids) {
729
- if (!this.#table) {
730
- throw new Error("PgBossTurnQueue.initialize() must run before cancel()");
731
- }
732
761
  await this.#boss.getDb().executeSql(
733
762
  `DELETE FROM ${this.#relation()}
734
763
  WHERE name = $1
@@ -738,12 +767,10 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
738
767
  );
739
768
  }
740
769
  #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)}`;
770
+ return _PgBossTurnQueue.#relationOf(this.#schema, this.#table);
771
+ }
772
+ static #relationOf(schema, table) {
773
+ return `${_PgBossTurnQueue.#quoteIdentifier(schema)}.${_PgBossTurnQueue.#quoteIdentifier(table)}`;
747
774
  }
748
775
  static #quoteIdentifier(identifier) {
749
776
  return `"${identifier.replaceAll('"', '""')}"`;
@@ -773,79 +800,6 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
773
800
  }
774
801
  };
775
802
 
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
803
  // packages/experimental/src/zukhruf/runtime/agent-runtime.ts
850
804
  import {
851
805
  ContextEngine as ContextEngine5
@@ -1153,7 +1107,7 @@ var AgentHistoryForker = class {
1153
1107
  await this.#store.updateChat(child.conversation.chatId, (chat2) => {
1154
1108
  const metadata = chat2.metadata;
1155
1109
  const zukhruf = metadata?.zukhruf;
1156
- if (!isRecord3(zukhruf)) {
1110
+ if (!isRecord2(zukhruf)) {
1157
1111
  throw new Error(
1158
1112
  `spawn_agent: child chat "${child.conversation.chatId}" is missing Zukhruf metadata`
1159
1113
  );
@@ -1259,7 +1213,7 @@ var AgentHistoryForker = class {
1259
1213
  await this.#store.updateChat(child.conversation.chatId, (chat2) => {
1260
1214
  const metadata = chat2.metadata;
1261
1215
  const zukhruf = metadata?.zukhruf;
1262
- if (!isRecord3(zukhruf)) {
1216
+ if (!isRecord2(zukhruf)) {
1263
1217
  throw new Error(
1264
1218
  `spawn_agent: child chat "${child.conversation.chatId}" is missing Zukhruf metadata`
1265
1219
  );
@@ -1351,12 +1305,12 @@ function isForkTurnBoundary(message) {
1351
1305
  return interAgentCommunication(message)?.triggerTurn ?? true;
1352
1306
  }
1353
1307
  function interAgentCommunication(message) {
1354
- if (!isRecord3(message.metadata)) return void 0;
1308
+ if (!isRecord2(message.metadata)) return void 0;
1355
1309
  if (!Object.hasOwn(message.metadata, "interAgentCommunication")) {
1356
1310
  return void 0;
1357
1311
  }
1358
1312
  const communication = message.metadata.interAgentCommunication;
1359
- if (!isRecord3(communication) || typeof communication.triggerTurn !== "boolean") {
1313
+ if (!isRecord2(communication) || typeof communication.triggerTurn !== "boolean") {
1360
1314
  throw new Error(
1361
1315
  `spawn_agent: message "${message.id}" has invalid inter-agent metadata`
1362
1316
  );
@@ -1364,7 +1318,7 @@ function interAgentCommunication(message) {
1364
1318
  return { triggerTurn: communication.triggerTurn };
1365
1319
  }
1366
1320
  function parseHistoryForkRecord(value) {
1367
- if (!isRecord3(value)) {
1321
+ if (!isRecord2(value)) {
1368
1322
  throw new Error("spawn_agent: invalid persisted history-fork metadata");
1369
1323
  }
1370
1324
  const { forkTurns, parentChatId, parentHeadMessageId, sourceMessageIds } = value;
@@ -1383,11 +1337,11 @@ function parseHistoryForkRecord(value) {
1383
1337
  function isForkTurns(value) {
1384
1338
  return value === "none" || value === "all" || typeof value === "number" && Number.isSafeInteger(value) && value > 0;
1385
1339
  }
1386
- function isRecord3(value) {
1340
+ function isRecord2(value) {
1387
1341
  return typeof value === "object" && value !== null && !Array.isArray(value);
1388
1342
  }
1389
1343
  function isEmptyAssistantPlaceholder(value) {
1390
- return isRecord3(value) && typeof value.id === "string" && value.role === "assistant" && Array.isArray(value.parts) && value.parts.length === 0;
1344
+ return isRecord2(value) && typeof value.id === "string" && value.role === "assistant" && Array.isArray(value.parts) && value.parts.length === 0;
1391
1345
  }
1392
1346
  function arraysEqual(left, right) {
1393
1347
  return left.length === right.length && left.every((value, index) => value === right[index]);
@@ -1833,12 +1787,12 @@ var AgentControlPlane = class _AgentControlPlane {
1833
1787
 
1834
1788
  // packages/experimental/src/zukhruf/mailbox/coordinator.ts
1835
1789
  import { setTimeout as delay } from "node:timers/promises";
1790
+ import pMemoize from "p-memoize";
1836
1791
  var WAIT_POLL_INTERVAL_MS = 50;
1837
1792
  var MailboxCoordinator = class {
1838
1793
  #store;
1839
1794
  #queue;
1840
1795
  #streams;
1841
- #wakeRequests = /* @__PURE__ */ new Map();
1842
1796
  constructor(options) {
1843
1797
  this.#store = options.store;
1844
1798
  this.#queue = options.queue;
@@ -1886,11 +1840,12 @@ var MailboxCoordinator = class {
1886
1840
  });
1887
1841
  }
1888
1842
  }
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 () => {
1843
+ /**
1844
+ * Coalesces only concurrent wake requests in this process. A settled request
1845
+ * is not kept, because another process may consume the wake.
1846
+ */
1847
+ #scheduleWake = pMemoize(
1848
+ async (target) => {
1894
1849
  const wakeId = AgentTurnId.random(target).toString();
1895
1850
  await this.#streams.register(wakeId);
1896
1851
  try {
@@ -1906,19 +1861,12 @@ var MailboxCoordinator = class {
1906
1861
  });
1907
1862
  throw error;
1908
1863
  }
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
- }
1864
+ },
1865
+ {
1866
+ cacheKey: ([target]) => JSON.stringify([target.chatId, target.userId]),
1867
+ cache: false
1868
+ }
1869
+ );
1922
1870
  };
1923
1871
 
1924
1872
  // packages/experimental/src/zukhruf/multi-agent-config.ts
@@ -2148,6 +2096,8 @@ function replacementRange(messages, keepLastMessages) {
2148
2096
  case "tool-approval-response":
2149
2097
  link(`approval:${part.approvalId}`, index, false);
2150
2098
  break;
2099
+ default:
2100
+ break;
2151
2101
  }
2152
2102
  }
2153
2103
  }
@@ -2303,7 +2253,7 @@ var inputUsageSchema = cacheObservationSchema.pick({ scope: true, prefixLength:
2303
2253
  function hash(value) {
2304
2254
  return createHash("sha256").update(JSON.stringify(value)).digest("hex");
2305
2255
  }
2306
- function isRecord4(value) {
2256
+ function isRecord3(value) {
2307
2257
  return typeof value === "object" && value !== null && !Array.isArray(value);
2308
2258
  }
2309
2259
  function cacheRetentionMs(step) {
@@ -2315,14 +2265,14 @@ function cacheRetentionMs(step) {
2315
2265
  return void 0;
2316
2266
  }
2317
2267
  }
2318
- if (!isRecord4(body)) return void 0;
2268
+ if (!isRecord3(body)) return void 0;
2319
2269
  const provider = step.model.provider;
2320
2270
  const routed = provider === "openrouter" || provider === "openrouter.chat";
2321
2271
  const upstream = routed ? step.providerMetadata?.openrouter?.provider : void 0;
2322
2272
  if (provider === "openai.responses" || provider === "openai.chat" || routed && upstream === "OpenAI") {
2323
2273
  const options = body.prompt_cache_options;
2324
- if (options !== void 0 && !isRecord4(options)) return void 0;
2325
- if (isRecord4(options) && options.ttl !== void 0) {
2274
+ if (options !== void 0 && !isRecord3(options)) return void 0;
2275
+ if (isRecord3(options) && options.ttl !== void 0) {
2326
2276
  return options.ttl === "30m" ? 30 * 6e4 : void 0;
2327
2277
  }
2328
2278
  const version = /^(?:openai\/)?gpt-(\d+)(?:\.(\d+))?(?:-|$)/.exec(
@@ -2342,18 +2292,18 @@ function cacheRetentionMs(step) {
2342
2292
  }
2343
2293
  const windows = [];
2344
2294
  for (const block of blocks) {
2345
- if (!isRecord4(block)) continue;
2295
+ if (!isRecord3(block)) continue;
2346
2296
  if (Array.isArray(block.content)) blocks.push(...block.content);
2347
2297
  const control = block.cache_control;
2348
2298
  if (control === void 0) continue;
2349
- if (!isRecord4(control) || control.type !== "ephemeral") return void 0;
2299
+ if (!isRecord3(control) || control.type !== "ephemeral") return void 0;
2350
2300
  if (control.ttl === void 0 || control.ttl === "5m")
2351
2301
  windows.push(5 * 6e4);
2352
2302
  else if (control.ttl === "1h") windows.push(60 * 6e4);
2353
2303
  else return void 0;
2354
2304
  }
2355
2305
  const creation = step.usage.raw?.cache_creation;
2356
- if (isRecord4(creation)) {
2306
+ if (isRecord3(creation)) {
2357
2307
  if (typeof creation.ephemeral_1h_input_tokens === "number" && creation.ephemeral_1h_input_tokens > 0)
2358
2308
  return 60 * 6e4;
2359
2309
  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 +2379,10 @@ function createCompaction(config, engine, store, signal, onEvent) {
2429
2379
  if (!initialized) {
2430
2380
  const chat2 = await store.getChat(engine.chatId);
2431
2381
  const metadata = chat2?.metadata?.zukhruf;
2432
- const saved = isRecord4(metadata) ? metadata.compaction : void 0;
2433
- const savedCache = isRecord4(metadata) ? metadata.promptCache : void 0;
2382
+ const saved = isRecord3(metadata) ? metadata.compaction : void 0;
2383
+ const savedCache = isRecord3(metadata) ? metadata.promptCache : void 0;
2434
2384
  baseline = inputUsageSchema.safeParse(
2435
- isRecord4(metadata) ? metadata.inputUsage : void 0
2385
+ isRecord3(metadata) ? metadata.inputUsage : void 0
2436
2386
  ).data ?? null;
2437
2387
  if (savedCache !== void 0) {
2438
2388
  cache = cacheObservationSchema.nullable().parse(savedCache);
@@ -2539,7 +2489,7 @@ function createCompaction(config, engine, store, signal, onEvent) {
2539
2489
  metadata: {
2540
2490
  ...metadata,
2541
2491
  zukhruf: {
2542
- ...isRecord4(metadata?.zukhruf) ? metadata.zukhruf : {},
2492
+ ...isRecord3(metadata?.zukhruf) ? metadata.zukhruf : {},
2543
2493
  compaction: checkpoint,
2544
2494
  inputUsage: null
2545
2495
  }
@@ -2574,7 +2524,7 @@ function createCompaction(config, engine, store, signal, onEvent) {
2574
2524
  const onStepEnd = async (step) => {
2575
2525
  if (signal.aborted || step.finishReason === "error") return;
2576
2526
  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(
2527
+ const ambiguous = iterations != null && (!Array.isArray(iterations) || iterations.length !== 1 || !isRecord3(iterations[0]) || iterations[0].type !== "message") || step.content.some(
2578
2528
  (part) => part.type === "custom" && part.kind === "openai.compaction" || part.type === "text" && part.providerMetadata?.anthropic?.type === "compaction"
2579
2529
  );
2580
2530
  const nextBaseline = ambiguous ? null : inputUsageSchema.safeParse({
@@ -2589,7 +2539,7 @@ function createCompaction(config, engine, store, signal, onEvent) {
2589
2539
  metadata: {
2590
2540
  ...metadata,
2591
2541
  zukhruf: {
2592
- ...isRecord4(metadata?.zukhruf) ? metadata.zukhruf : {},
2542
+ ...isRecord3(metadata?.zukhruf) ? metadata.zukhruf : {},
2593
2543
  promptCache: next,
2594
2544
  inputUsage: nextBaseline
2595
2545
  }
@@ -3040,7 +2990,7 @@ var AgentTurnExecutor = class {
3040
2990
  if (turn.kind === "message" && turn.elements !== void 0) {
3041
2991
  const declared = turn.elements;
3042
2992
  await this.#store.updateChat(turn.chatId, ({ metadata }) => {
3043
- const zukhruf = isRecord5(metadata?.zukhruf) ? metadata.zukhruf : {};
2993
+ const zukhruf = isRecord4(metadata?.zukhruf) ? metadata.zukhruf : {};
3044
2994
  if (isDeepStrictEqual(zukhruf.elements, declared)) return void 0;
3045
2995
  return {
3046
2996
  metadata: {
@@ -3070,7 +3020,7 @@ var AgentTurnExecutor = class {
3070
3020
  available = persisted;
3071
3021
  return void 0;
3072
3022
  }
3073
- const zukhruf = isRecord5(metadata?.zukhruf) ? metadata.zukhruf : {};
3023
+ const zukhruf = isRecord4(metadata?.zukhruf) ? metadata.zukhruf : {};
3074
3024
  return {
3075
3025
  metadata: {
3076
3026
  ...metadata,
@@ -3140,7 +3090,7 @@ ${communication.content}`;
3140
3090
  };
3141
3091
  function readElements(metadata) {
3142
3092
  const zukhruf = metadata?.zukhruf;
3143
- if (!isRecord5(zukhruf) || !Object.hasOwn(zukhruf, "elements")) {
3093
+ if (!isRecord4(zukhruf) || !Object.hasOwn(zukhruf, "elements")) {
3144
3094
  return void 0;
3145
3095
  }
3146
3096
  const parsed = elementsSchema.safeParse(zukhruf.elements);
@@ -3151,7 +3101,7 @@ function readElements(metadata) {
3151
3101
  }
3152
3102
  function readSkills(metadata) {
3153
3103
  const zukhruf = metadata?.zukhruf;
3154
- if (!isRecord5(zukhruf) || !Object.hasOwn(zukhruf, "skills")) {
3104
+ if (!isRecord4(zukhruf) || !Object.hasOwn(zukhruf, "skills")) {
3155
3105
  return void 0;
3156
3106
  }
3157
3107
  if (!Array.isArray(zukhruf.skills) || !zukhruf.skills.every(isSkill)) {
@@ -3160,9 +3110,9 @@ function readSkills(metadata) {
3160
3110
  return zukhruf.skills;
3161
3111
  }
3162
3112
  function isSkill(value) {
3163
- return isRecord5(value) && typeof value.name === "string" && typeof value.description === "string" && typeof value.path === "string";
3113
+ return isRecord4(value) && typeof value.name === "string" && typeof value.description === "string" && typeof value.path === "string";
3164
3114
  }
3165
- function isRecord5(value) {
3115
+ function isRecord4(value) {
3166
3116
  return typeof value === "object" && value !== null && !Array.isArray(value);
3167
3117
  }
3168
3118
 
@@ -3321,6 +3271,7 @@ var ApprovalController = class _ApprovalController {
3321
3271
  };
3322
3272
 
3323
3273
  // packages/experimental/src/zukhruf/runtime/conversation-status/projector.ts
3274
+ import { Latch } from "@zukhruf/async";
3324
3275
  import { MemoryStore, Mutex } from "@zukhruf/mutex";
3325
3276
  import { EventEmitter, on } from "node:events";
3326
3277
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
@@ -3354,6 +3305,19 @@ var ProjectorEventDelivery = class {
3354
3305
  this.event = event;
3355
3306
  }
3356
3307
  };
3308
+ var Detached = class {
3309
+ // A private member keeps the type nominal: an empty class would also
3310
+ // describe RemoteAttachment, and `instanceof` could not narrow the union.
3311
+ #detached = true;
3312
+ };
3313
+ var DETACHED = new Detached();
3314
+ var RemoteAttachment = class {
3315
+ abort = new AbortController();
3316
+ /** Opens when the source subscribes: with nothing, or with the error that stopped it. */
3317
+ connected = new Latch();
3318
+ /** Opens when the consume loop has stopped. */
3319
+ ended = new Latch();
3320
+ };
3357
3321
  var ConversationStatusProjector = class _ConversationStatusProjector {
3358
3322
  #store;
3359
3323
  #streams;
@@ -3364,7 +3328,7 @@ var ConversationStatusProjector = class _ConversationStatusProjector {
3364
3328
  #last = /* @__PURE__ */ new Map();
3365
3329
  #publishing = new Mutex(new MemoryStore());
3366
3330
  #subscribers = 0;
3367
- #remote;
3331
+ #remote = DETACHED;
3368
3332
  constructor(options) {
3369
3333
  this.#store = options.store;
3370
3334
  this.#streams = options.streams;
@@ -3528,34 +3492,32 @@ var ConversationStatusProjector = class _ConversationStatusProjector {
3528
3492
  this.#subscribers += 1;
3529
3493
  const source = this.#changeSource;
3530
3494
  if (!source) return;
3531
- if (!this.#remote) {
3532
- const abort = new AbortController();
3533
- const ready = Promise.withResolvers();
3534
- const remote = { abort, ready: ready.promise, done: Promise.resolve() };
3495
+ let remote = this.#remote;
3496
+ if (!(remote instanceof RemoteAttachment)) {
3497
+ remote = new RemoteAttachment();
3535
3498
  this.#remote = remote;
3536
- remote.done = this.#consumeRemote(source, remote, ready);
3499
+ void this.#consumeRemote(source, remote);
3537
3500
  }
3538
- try {
3539
- await this.#remote.ready;
3540
- } catch (error) {
3501
+ const failure = await remote.connected.wait();
3502
+ if (failure) {
3541
3503
  await this.#detachRemote();
3542
- throw error;
3504
+ throw failure.error;
3543
3505
  }
3544
3506
  }
3545
3507
  async #detachRemote() {
3546
3508
  this.#subscribers -= 1;
3547
- if (this.#subscribers > 0 || !this.#remote) return;
3548
3509
  const remote = this.#remote;
3510
+ if (this.#subscribers > 0 || !(remote instanceof RemoteAttachment)) return;
3549
3511
  remote.abort.abort();
3550
- this.#remote = void 0;
3551
- await remote.done;
3512
+ this.#remote = DETACHED;
3513
+ await remote.ended.wait();
3552
3514
  }
3553
- async #consumeRemote(source, remote, ready) {
3515
+ async #consumeRemote(source, remote) {
3554
3516
  let connected = false;
3555
3517
  try {
3556
3518
  const events = await source.subscribe(remote.abort.signal);
3557
3519
  connected = true;
3558
- ready.resolve();
3520
+ remote.connected.open(void 0);
3559
3521
  for await (const event of events) {
3560
3522
  if (event.type === "reset") {
3561
3523
  this.#emit(event);
@@ -3570,12 +3532,13 @@ var ConversationStatusProjector = class _ConversationStatusProjector {
3570
3532
  });
3571
3533
  }
3572
3534
  } catch (error) {
3573
- if (!connected) ready.reject(error);
3535
+ if (!connected) remote.connected.open({ error });
3574
3536
  if (connected && !(error instanceof Error && error.name === "AbortError")) {
3575
3537
  this.#emit({ type: "error", error });
3576
3538
  }
3577
3539
  } finally {
3578
- if (this.#remote === remote) this.#remote = void 0;
3540
+ if (this.#remote === remote) this.#remote = DETACHED;
3541
+ remote.ended.open();
3579
3542
  }
3580
3543
  }
3581
3544
  #emit(event) {
@@ -4807,7 +4770,6 @@ export {
4807
4770
  defineInstructions,
4808
4771
  defineSandbox,
4809
4772
  defineStack,
4810
- defineTool,
4811
- renderTurn
4773
+ defineTool
4812
4774
  };
4813
4775
  //# sourceMappingURL=index.js.map