@deepagents/experimental 7.7.2 → 7.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +16 -5
  2. package/dist/index.js +400 -177
  3. package/dist/index.js.map +4 -4
  4. package/dist/zukhruf/control-plane/agent-control-plane.d.ts.map +1 -1
  5. package/dist/zukhruf/control-plane/agent-thread-limit-error.d.ts +6 -0
  6. package/dist/zukhruf/control-plane/agent-thread-limit-error.d.ts.map +1 -0
  7. package/dist/zukhruf/control-plane/agent-turn-id.d.ts +3 -0
  8. package/dist/zukhruf/control-plane/agent-turn-id.d.ts.map +1 -1
  9. package/dist/zukhruf/control-plane/stale-turn-error.d.ts +7 -0
  10. package/dist/zukhruf/control-plane/stale-turn-error.d.ts.map +1 -0
  11. package/dist/zukhruf/control-plane/turn-not-found-error.d.ts +7 -0
  12. package/dist/zukhruf/control-plane/turn-not-found-error.d.ts.map +1 -0
  13. package/dist/zukhruf/index.d.ts +4 -0
  14. package/dist/zukhruf/index.d.ts.map +1 -1
  15. package/dist/zukhruf/index.js +400 -177
  16. package/dist/zukhruf/index.js.map +4 -4
  17. package/dist/zukhruf/is-named-error.d.ts +7 -0
  18. package/dist/zukhruf/is-named-error.d.ts.map +1 -0
  19. package/dist/zukhruf/mailbox/communication-schema.d.ts +26 -0
  20. package/dist/zukhruf/mailbox/communication-schema.d.ts.map +1 -0
  21. package/dist/zukhruf/mailbox/ddl.postgres.d.ts +2 -0
  22. package/dist/zukhruf/mailbox/ddl.postgres.d.ts.map +1 -0
  23. package/dist/zukhruf/mailbox/postgres.store.d.ts +23 -0
  24. package/dist/zukhruf/mailbox/postgres.store.d.ts.map +1 -0
  25. package/dist/zukhruf/mailbox/sqlite.store.d.ts.map +1 -1
  26. package/dist/zukhruf/plugins/conversation-scheduling/conversation-scheduler.d.ts +1 -1
  27. package/dist/zukhruf/plugins/conversation-scheduling/conversation-scheduler.d.ts.map +1 -1
  28. package/dist/zukhruf/plugins/conversation-scheduling/index.d.ts.map +1 -1
  29. package/dist/zukhruf/plugins/conversation-scheduling/index.js +142 -136
  30. package/dist/zukhruf/plugins/conversation-scheduling/index.js.map +3 -3
  31. package/dist/zukhruf/plugins/http/index.d.ts +2 -2
  32. package/dist/zukhruf/plugins/http/index.d.ts.map +1 -1
  33. package/dist/zukhruf/plugins/http/index.js +72 -17
  34. package/dist/zukhruf/plugins/http/index.js.map +4 -4
  35. package/dist/zukhruf/plugins/schedules/http.d.ts.map +1 -1
  36. package/dist/zukhruf/plugins/schedules/http.js +44 -32
  37. package/dist/zukhruf/plugins/schedules/http.js.map +4 -4
  38. package/dist/zukhruf/plugins/schedules/index.d.ts +2 -2
  39. package/dist/zukhruf/plugins/schedules/index.d.ts.map +1 -1
  40. package/dist/zukhruf/plugins/schedules/index.js +138 -143
  41. package/dist/zukhruf/plugins/schedules/index.js.map +3 -3
  42. package/dist/zukhruf/plugins/uploads/http.js +30 -19
  43. package/dist/zukhruf/plugins/uploads/http.js.map +4 -4
  44. package/dist/zukhruf/plugins/uploads/index.d.ts +2 -2
  45. package/dist/zukhruf/plugins/uploads/index.d.ts.map +1 -1
  46. package/dist/zukhruf/plugins/uploads/index.js +48 -55
  47. package/dist/zukhruf/plugins/uploads/index.js.map +2 -2
  48. package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts +4 -1
  49. package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts.map +1 -1
  50. package/dist/zukhruf/runtime/agent-runtime.d.ts +19 -11
  51. package/dist/zukhruf/runtime/agent-runtime.d.ts.map +1 -1
  52. package/dist/zukhruf/runtime/plugin/plugin-manager.d.ts +4 -4
  53. package/dist/zukhruf/runtime/plugin/plugin-manager.d.ts.map +1 -1
  54. package/package.json +20 -11
package/dist/index.js CHANGED
@@ -325,6 +325,7 @@ __export(zukhruf_exports, {
325
325
  AgentPluginCapability: () => AgentPluginCapability,
326
326
  AgentRuntime: () => AgentRuntime,
327
327
  AgentThread: () => AgentThread,
328
+ AgentThreadLimitError: () => AgentThreadLimitError,
328
329
  ConversationNotFoundError: () => ConversationNotFoundError,
329
330
  DEFAULT_CONVERSATION_STATUS_CHANNEL: () => DEFAULT_CONVERSATION_STATUS_CHANNEL,
330
331
  InterAgentCommunicationTypes: () => InterAgentCommunicationTypes,
@@ -332,7 +333,10 @@ __export(zukhruf_exports, {
332
333
  MessageDeliveryModes: () => MessageDeliveryModes,
333
334
  PgBossConversationStatusChangeSource: () => PgBossConversationStatusChangeSource,
334
335
  PgBossTurnQueue: () => PgBossTurnQueue,
336
+ PostgresMailboxStore: () => PostgresMailboxStore,
335
337
  SqliteMailboxStore: () => SqliteMailboxStore,
338
+ StaleTurnError: () => StaleTurnError,
339
+ TurnNotFoundError: () => TurnNotFoundError,
336
340
  TurnQueue: () => TurnQueue,
337
341
  assertCommunication: () => assertCommunication,
338
342
  createInterAgentCommunication: () => createInterAgentCommunication,
@@ -527,6 +531,14 @@ var AgentThread = class _AgentThread {
527
531
  }
528
532
  };
529
533
 
534
+ // packages/experimental/src/zukhruf/control-plane/agent-thread-limit-error.ts
535
+ var AgentThreadLimitError = class extends Error {
536
+ name = "AgentThreadLimitError";
537
+ constructor() {
538
+ super("agent thread limit reached");
539
+ }
540
+ };
541
+
530
542
  // packages/experimental/src/zukhruf/control-plane/conversation-not-found-error.ts
531
543
  var ConversationNotFoundError = class extends Error {
532
544
  name = "ConversationNotFoundError";
@@ -542,53 +554,37 @@ function assertConversationOwner(conversation, storedUserId) {
542
554
  }
543
555
  }
544
556
 
557
+ // packages/experimental/src/zukhruf/control-plane/stale-turn-error.ts
558
+ var StaleTurnError = class extends Error {
559
+ name = "StaleTurnError";
560
+ turnId;
561
+ constructor(turnId) {
562
+ super(`turn "${turnId}" is not the latest turn`);
563
+ this.turnId = turnId;
564
+ }
565
+ };
566
+
567
+ // packages/experimental/src/zukhruf/control-plane/turn-not-found-error.ts
568
+ var TurnNotFoundError = class extends Error {
569
+ name = "TurnNotFoundError";
570
+ turnId;
571
+ constructor(turnId) {
572
+ super(`turn "${turnId}" does not exist`);
573
+ this.turnId = turnId;
574
+ }
575
+ };
576
+
545
577
  // packages/experimental/src/zukhruf/instructions.ts
546
578
  function defineInstructions(...fragments) {
547
579
  return fragments;
548
580
  }
549
581
 
550
- // packages/experimental/src/zukhruf/mailbox/sqlite.store.ts
551
- import { Declaration } from "@zukhruf/sqlite-drift";
552
- import { open } from "@zukhruf/sqlite-open";
553
- import { transaction } from "@zukhruf/sqlite-transaction";
554
- import { z } from "zod";
555
-
556
- // packages/experimental/src/zukhruf/mailbox/ddl.sqlite.ts
557
- var SETUP = `
558
- PRAGMA synchronous = NORMAL;
559
- `;
560
- var statements = [
561
- `CREATE TABLE zukhruf_mailbox_items (
562
- sequence INTEGER PRIMARY KEY AUTOINCREMENT,
563
- recipient_chat_id TEXT NOT NULL,
564
- recipient_user_id TEXT NOT NULL,
565
- communication TEXT NOT NULL
566
- )`,
567
- `CREATE TABLE zukhruf_mailbox_activity (
568
- recipient_chat_id TEXT NOT NULL,
569
- recipient_user_id TEXT NOT NULL,
570
- turn_id TEXT NOT NULL,
571
- PRIMARY KEY (recipient_chat_id, recipient_user_id)
572
- )`,
573
- `CREATE TABLE zukhruf_mailbox_consumed_terminal_ids (
574
- communication_id TEXT PRIMARY KEY
575
- )`,
576
- `CREATE INDEX zukhruf_mailbox_recipient_sequence
577
- ON zukhruf_mailbox_items (
578
- recipient_chat_id,
579
- recipient_user_id,
580
- sequence
581
- )`,
582
- // enqueue relies on this index through INSERT OR IGNORE.
583
- `CREATE UNIQUE INDEX zukhruf_mailbox_communication_id
584
- ON zukhruf_mailbox_items (
585
- json_extract(communication, '$.id')
586
- )`
587
- ];
582
+ // packages/experimental/src/zukhruf/mailbox/postgres.store.ts
583
+ import { z as z2 } from "zod";
584
+ import { lockSchemaDDL, postgresTransaction } from "@deepagents/context";
588
585
 
589
- // packages/experimental/src/zukhruf/mailbox/store.ts
590
- var MailboxStore = class {
591
- };
586
+ // packages/experimental/src/zukhruf/mailbox/communication-schema.ts
587
+ import { z } from "zod";
592
588
 
593
589
  // packages/experimental/src/zukhruf/mailbox/types.ts
594
590
  import { randomUUID } from "node:crypto";
@@ -636,8 +632,7 @@ function assertConversationId(value, label) {
636
632
  }
637
633
  }
638
634
 
639
- // packages/experimental/src/zukhruf/mailbox/sqlite.store.ts
640
- var tables = new Declaration(statements, { rows: "keep" });
635
+ // packages/experimental/src/zukhruf/mailbox/communication-schema.ts
641
636
  var conversationIdSchema = z.object({
642
637
  chatId: z.string(),
643
638
  userId: z.string()
@@ -652,10 +647,249 @@ var communicationSchema = z.object({
652
647
  metadata: z.record(z.string(), z.unknown()).optional(),
653
648
  triggerTurn: z.boolean()
654
649
  });
655
- var mailboxItemRowsSchema = z.array(
656
- z.object({
657
- sequence: z.number(),
658
- communication: z.string().transform((text) => JSON.parse(text)).pipe(communicationSchema)
650
+
651
+ // packages/experimental/src/zukhruf/mailbox/ddl.postgres.ts
652
+ function mailboxDDL(schema) {
653
+ return `
654
+ CREATE SCHEMA IF NOT EXISTS "${schema}";
655
+
656
+ CREATE TABLE IF NOT EXISTS "${schema}"."zukhruf_mailbox_items" (
657
+ sequence BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
658
+ communication_id TEXT NOT NULL UNIQUE,
659
+ recipient_chat_id TEXT NOT NULL,
660
+ recipient_user_id TEXT NOT NULL,
661
+ communication JSONB NOT NULL
662
+ );
663
+
664
+ CREATE INDEX IF NOT EXISTS "zukhruf_mailbox_recipient_sequence"
665
+ ON "${schema}"."zukhruf_mailbox_items" (recipient_chat_id, recipient_user_id, sequence);
666
+
667
+ CREATE TABLE IF NOT EXISTS "${schema}"."zukhruf_mailbox_activity" (
668
+ recipient_chat_id TEXT NOT NULL,
669
+ recipient_user_id TEXT NOT NULL,
670
+ turn_id TEXT NOT NULL,
671
+ PRIMARY KEY (recipient_chat_id, recipient_user_id)
672
+ );
673
+
674
+ CREATE TABLE IF NOT EXISTS "${schema}"."zukhruf_mailbox_consumed_terminal_ids" (
675
+ communication_id TEXT PRIMARY KEY
676
+ );
677
+ `;
678
+ }
679
+
680
+ // packages/experimental/src/zukhruf/mailbox/store.ts
681
+ var MailboxStore = class {
682
+ };
683
+
684
+ // packages/experimental/src/zukhruf/mailbox/postgres.store.ts
685
+ var mailboxItemRowsSchema = z2.array(
686
+ z2.object({
687
+ sequence: z2.string(),
688
+ communication: communicationSchema
689
+ })
690
+ );
691
+ var existsRowsSchema = z2.tuple([z2.object({ exists: z2.boolean() })]);
692
+ var PostgresMailboxStore = class _PostgresMailboxStore extends MailboxStore {
693
+ #pool;
694
+ #schema;
695
+ constructor(pool, schema) {
696
+ super();
697
+ this.#pool = pool;
698
+ this.#schema = schema;
699
+ }
700
+ /** Opens the store: creates its schema objects before it returns. */
701
+ static async create(options) {
702
+ const schema = options.schema ?? "public";
703
+ await options.pool.query(lockSchemaDDL(mailboxDDL(schema), schema));
704
+ return new _PostgresMailboxStore(options.pool, schema);
705
+ }
706
+ #t(name) {
707
+ return `"${this.#schema}"."${name}"`;
708
+ }
709
+ /**
710
+ * Runs `fn` while holding the recipient's lock, so enqueue, drain and turn
711
+ * handoff on one mailbox take turns across every worker, as SQLite's
712
+ * immediate transactions do.
713
+ */
714
+ #forRecipient(recipient, fn) {
715
+ return postgresTransaction(this.#pool, async (client) => {
716
+ await client.query(
717
+ "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",
718
+ [
719
+ `zukhruf:mailbox:${JSON.stringify([this.#schema, recipient.chatId, recipient.userId])}`
720
+ ]
721
+ );
722
+ return fn(client);
723
+ });
724
+ }
725
+ async beginTurn(recipient, turnId) {
726
+ await this.#forRecipient(
727
+ recipient,
728
+ (client) => client.query(
729
+ `INSERT INTO ${this.#t("zukhruf_mailbox_activity")}
730
+ (recipient_chat_id, recipient_user_id, turn_id)
731
+ VALUES ($1, $2, $3)
732
+ ON CONFLICT (recipient_chat_id, recipient_user_id)
733
+ DO UPDATE SET turn_id = EXCLUDED.turn_id`,
734
+ [recipient.chatId, recipient.userId, turnId]
735
+ )
736
+ );
737
+ }
738
+ enqueue(communication) {
739
+ const { recipient } = communication;
740
+ return this.#forRecipient(recipient, async (client) => {
741
+ const consumedTerminal = communication.type === InterAgentCommunicationTypes.FinalAnswer && await this.#exists(
742
+ client,
743
+ `SELECT EXISTS (
744
+ SELECT 1 FROM ${this.#t("zukhruf_mailbox_consumed_terminal_ids")}
745
+ WHERE communication_id = $1)`,
746
+ [communication.id]
747
+ );
748
+ if (!consumedTerminal) {
749
+ await client.query(
750
+ `INSERT INTO ${this.#t("zukhruf_mailbox_items")}
751
+ (communication_id, recipient_chat_id, recipient_user_id, communication)
752
+ VALUES ($1, $2, $3, $4::jsonb)
753
+ ON CONFLICT (communication_id) DO NOTHING`,
754
+ [
755
+ communication.id,
756
+ recipient.chatId,
757
+ recipient.userId,
758
+ JSON.stringify(communication)
759
+ ]
760
+ );
761
+ }
762
+ return { recipientActive: await this.#isTurnActive(client, recipient) };
763
+ });
764
+ }
765
+ endTurn(recipient, turnId) {
766
+ return this.#forRecipient(recipient, async (client) => {
767
+ const ended = await client.query(
768
+ `DELETE FROM ${this.#t("zukhruf_mailbox_activity")}
769
+ WHERE recipient_chat_id = $1
770
+ AND recipient_user_id = $2
771
+ AND turn_id = $3`,
772
+ [recipient.chatId, recipient.userId, turnId]
773
+ );
774
+ return {
775
+ hasPending: await this.#hasPending(client, recipient),
776
+ turnEnded: ended.rowCount === 1
777
+ };
778
+ });
779
+ }
780
+ hasPending(recipient) {
781
+ return this.#hasPending(this.#pool, recipient);
782
+ }
783
+ drain(recipient) {
784
+ return this.#drain(recipient, false);
785
+ }
786
+ drainLeadingQueueOnly(recipient) {
787
+ return this.#drain(recipient, true);
788
+ }
789
+ #drain(recipient, leadingQueueOnly) {
790
+ return this.#forRecipient(recipient, async (client) => {
791
+ const items = mailboxItemRowsSchema.parse(
792
+ (await client.query(
793
+ `SELECT sequence, communication
794
+ FROM ${this.#t("zukhruf_mailbox_items")}
795
+ WHERE recipient_chat_id = $1
796
+ AND recipient_user_id = $2
797
+ ORDER BY sequence`,
798
+ [recipient.chatId, recipient.userId]
799
+ )).rows
800
+ );
801
+ const firstTrigger = leadingQueueOnly ? items.findIndex(({ communication }) => communication.triggerTurn) : -1;
802
+ const consumed = firstTrigger === -1 ? items : items.slice(0, firstTrigger);
803
+ if (consumed.length === 0) return [];
804
+ await client.query(
805
+ `INSERT INTO ${this.#t("zukhruf_mailbox_consumed_terminal_ids")} (communication_id)
806
+ SELECT unnest($1::text[])
807
+ ON CONFLICT (communication_id) DO NOTHING`,
808
+ [
809
+ consumed.flatMap(
810
+ ({ communication }) => communication.type === InterAgentCommunicationTypes.FinalAnswer ? [communication.id] : []
811
+ )
812
+ ]
813
+ );
814
+ await client.query(
815
+ `DELETE FROM ${this.#t("zukhruf_mailbox_items")}
816
+ WHERE sequence = ANY($1::bigint[])`,
817
+ [consumed.map(({ sequence }) => sequence)]
818
+ );
819
+ return consumed.map(({ communication }) => communication);
820
+ });
821
+ }
822
+ #hasPending(queryable, recipient) {
823
+ return this.#exists(
824
+ queryable,
825
+ `SELECT EXISTS (
826
+ SELECT 1 FROM ${this.#t("zukhruf_mailbox_items")}
827
+ WHERE recipient_chat_id = $1 AND recipient_user_id = $2)`,
828
+ [recipient.chatId, recipient.userId]
829
+ );
830
+ }
831
+ #isTurnActive(client, recipient) {
832
+ return this.#exists(
833
+ client,
834
+ `SELECT EXISTS (
835
+ SELECT 1 FROM ${this.#t("zukhruf_mailbox_activity")}
836
+ WHERE recipient_chat_id = $1 AND recipient_user_id = $2)`,
837
+ [recipient.chatId, recipient.userId]
838
+ );
839
+ }
840
+ async #exists(queryable, sql, params) {
841
+ const [{ exists }] = existsRowsSchema.parse(
842
+ (await queryable.query(sql, params)).rows
843
+ );
844
+ return exists;
845
+ }
846
+ };
847
+
848
+ // packages/experimental/src/zukhruf/mailbox/sqlite.store.ts
849
+ import { Declaration } from "@zukhruf/sqlite-drift";
850
+ import { open } from "@zukhruf/sqlite-open";
851
+ import { transaction } from "@zukhruf/sqlite-transaction";
852
+ import { z as z3 } from "zod";
853
+
854
+ // packages/experimental/src/zukhruf/mailbox/ddl.sqlite.ts
855
+ var SETUP = `
856
+ PRAGMA synchronous = NORMAL;
857
+ `;
858
+ var statements = [
859
+ `CREATE TABLE zukhruf_mailbox_items (
860
+ sequence INTEGER PRIMARY KEY AUTOINCREMENT,
861
+ recipient_chat_id TEXT NOT NULL,
862
+ recipient_user_id TEXT NOT NULL,
863
+ communication TEXT NOT NULL
864
+ )`,
865
+ `CREATE TABLE zukhruf_mailbox_activity (
866
+ recipient_chat_id TEXT NOT NULL,
867
+ recipient_user_id TEXT NOT NULL,
868
+ turn_id TEXT NOT NULL,
869
+ PRIMARY KEY (recipient_chat_id, recipient_user_id)
870
+ )`,
871
+ `CREATE TABLE zukhruf_mailbox_consumed_terminal_ids (
872
+ communication_id TEXT PRIMARY KEY
873
+ )`,
874
+ `CREATE INDEX zukhruf_mailbox_recipient_sequence
875
+ ON zukhruf_mailbox_items (
876
+ recipient_chat_id,
877
+ recipient_user_id,
878
+ sequence
879
+ )`,
880
+ // enqueue relies on this index through INSERT OR IGNORE.
881
+ `CREATE UNIQUE INDEX zukhruf_mailbox_communication_id
882
+ ON zukhruf_mailbox_items (
883
+ json_extract(communication, '$.id')
884
+ )`
885
+ ];
886
+
887
+ // packages/experimental/src/zukhruf/mailbox/sqlite.store.ts
888
+ var tables = new Declaration(statements, { rows: "keep" });
889
+ var mailboxItemRowsSchema2 = z3.array(
890
+ z3.object({
891
+ sequence: z3.number(),
892
+ communication: z3.string().transform((text) => JSON.parse(text)).pipe(communicationSchema)
659
893
  })
660
894
  );
661
895
  var SqliteMailboxStore = class extends MailboxStore {
@@ -768,7 +1002,7 @@ var SqliteMailboxStore = class extends MailboxStore {
768
1002
  return transaction(
769
1003
  this.#database,
770
1004
  () => {
771
- const items = mailboxItemRowsSchema.parse(
1005
+ const items = mailboxItemRowsSchema2.parse(
772
1006
  this.#database.prepare(
773
1007
  `SELECT sequence, communication
774
1008
  FROM zukhruf_mailbox_items
@@ -814,7 +1048,7 @@ var SqliteMailboxStore = class extends MailboxStore {
814
1048
 
815
1049
  // packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
816
1050
  import { v7 as uuidv7 } from "uuid";
817
- import { z as z2 } from "zod";
1051
+ import { z as z4 } from "zod";
818
1052
  import { isRecord } from "@deepagents/context";
819
1053
 
820
1054
  // packages/experimental/src/zukhruf/queue/turn-queue.ts
@@ -822,8 +1056,7 @@ var TurnQueue = class {
822
1056
  };
823
1057
 
824
1058
  // packages/experimental/src/zukhruf/queue/pg-boss.turn-queue.ts
825
- var MAX_TIMEOUT_MS = 2147483647;
826
- var queueCatalogRowSchema = z2.object({ table: z2.string() });
1059
+ var queueCatalogRowSchema = z4.object({ table: z4.string() });
827
1060
  function deadLetterQueueOf(queue) {
828
1061
  return `${queue}-dead`;
829
1062
  }
@@ -837,13 +1070,13 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
837
1070
  #active = /* @__PURE__ */ new Map();
838
1071
  /** Cancels that arrived before a local worker runs the turn; each expires on its own timer. */
839
1072
  #cancelIntents = /* @__PURE__ */ new Map();
840
- constructor(boss, settings, table) {
1073
+ constructor(boss, settings, opened) {
841
1074
  super();
842
1075
  this.#boss = boss;
843
1076
  this.#queue = settings.queue;
844
1077
  this.#schema = settings.schema;
845
- this.#table = table;
846
- this.#cancelIntentTtlMs = settings.expireInSeconds * 1e3;
1078
+ this.#table = opened.table;
1079
+ this.#cancelIntentTtlMs = opened.expireInSeconds * 1e3;
847
1080
  this.#pollingIntervalSeconds = settings.pollingIntervalSeconds;
848
1081
  }
849
1082
  /**
@@ -852,20 +1085,13 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
852
1085
  */
853
1086
  static async create(boss, options = {}) {
854
1087
  const settings = _PgBossTurnQueue.#settings(boss, options);
855
- const table = await _PgBossTurnQueue.#openQueue(boss, settings);
856
- return new _PgBossTurnQueue(boss, settings, table);
1088
+ const opened = await _PgBossTurnQueue.#openQueue(boss, settings);
1089
+ return new _PgBossTurnQueue(boss, settings, opened);
857
1090
  }
858
1091
  static #settings(boss, options) {
859
1092
  const db = boss.getDb();
860
1093
  const configuredSchema = "config" in db && isRecord(db.config) ? db.config.schema : void 0;
861
1094
  const bossSchema = typeof configuredSchema === "string" ? configuredSchema : void 0;
862
- const expireInSeconds = options.expireInSeconds ?? 3600;
863
- const cancelIntentTtlMs = expireInSeconds * 1e3;
864
- if (!Number.isFinite(expireInSeconds) || expireInSeconds <= 0 || !Number.isSafeInteger(cancelIntentTtlMs) || cancelIntentTtlMs > Number.MAX_SAFE_INTEGER - Date.now()) {
865
- throw new Error(
866
- "PgBossTurnQueue expireInSeconds must be a finite positive duration"
867
- );
868
- }
869
1095
  if (options.schema === void 0 && bossSchema === void 0) {
870
1096
  throw new Error(
871
1097
  "PgBossTurnQueue cannot read the schema from a custom PgBoss database adapter; pass the PgBoss schema in options.schema"
@@ -879,12 +1105,12 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
879
1105
  return {
880
1106
  queue: options.queue ?? "zukhruf-turns",
881
1107
  schema: options.schema ?? bossSchema ?? "pgboss",
882
- expireInSeconds,
1108
+ expireInSeconds: options.expireInSeconds ?? 3600,
883
1109
  heartbeatSeconds: options.heartbeatSeconds ?? 30,
884
1110
  pollingIntervalSeconds: options.pollingIntervalSeconds ?? 1
885
1111
  };
886
1112
  }
887
- /** Creates the queues when they are missing; returns the turn queue's job table. */
1113
+ /** Creates the queues when they are missing; returns the turn queue as stored. */
888
1114
  static async #openQueue(boss, settings) {
889
1115
  const deadLetterQueue = deadLetterQueueOf(settings.queue);
890
1116
  if (!await boss.getQueue(deadLetterQueue)) {
@@ -902,10 +1128,10 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
902
1128
  });
903
1129
  queue = await boss.getQueue(settings.queue);
904
1130
  }
905
- if (!queue) {
1131
+ if (!queue?.expireInSeconds) {
906
1132
  throw new Error(`Queue "${settings.queue}" was not initialized`);
907
1133
  }
908
- const { table } = queue;
1134
+ const { table, expireInSeconds } = queue;
909
1135
  try {
910
1136
  const catalog = await boss.getDb().executeSql(
911
1137
  `SELECT table_name AS "table"
@@ -926,7 +1152,7 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
926
1152
  { cause }
927
1153
  );
928
1154
  }
929
- return table;
1155
+ return { table, expireInSeconds };
930
1156
  }
931
1157
  get queue() {
932
1158
  return this.#queue;
@@ -967,10 +1193,10 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
967
1193
  async cancel(streamId) {
968
1194
  this.#rememberCancelIntent(streamId);
969
1195
  this.#abortLocal(streamId);
970
- const jobs = await this.#boss.findJobs(this.#queue, {
971
- data: { streamId }
972
- });
973
- const queued = jobs.filter((job) => job.state === "created" || job.state === "retry").map((job) => job.id);
1196
+ const queued = (await this.#boss.findJobs(this.#queue, {
1197
+ data: { streamId },
1198
+ queued: true
1199
+ })).map((job) => job.id);
974
1200
  if (queued.length > 0) await this.#deleteIfStillQueued(queued);
975
1201
  this.#abortLocal(streamId);
976
1202
  const remaining = await this.#boss.findJobs(this.#queue, {
@@ -1086,18 +1312,15 @@ var PgBossTurnQueue = class _PgBossTurnQueue extends TurnQueue {
1086
1312
  }
1087
1313
  #rememberCancelIntent(streamId) {
1088
1314
  this.#forgetCancelIntent(streamId);
1089
- this.#armCancelIntent(streamId, Date.now() + this.#cancelIntentTtlMs);
1090
- }
1091
- #armCancelIntent(streamId, expiresAt) {
1092
1315
  const timer = globalThis.setTimeout(
1093
- () => {
1094
- if (Date.now() < expiresAt) this.#armCancelIntent(streamId, expiresAt);
1095
- else this.#cancelIntents.delete(streamId);
1096
- },
1097
- Math.min(MAX_TIMEOUT_MS, Math.max(1, expiresAt - Date.now()))
1316
+ () => this.#cancelIntents.delete(streamId),
1317
+ this.#cancelIntentTtlMs
1098
1318
  );
1099
1319
  timer.unref();
1100
- this.#cancelIntents.set(streamId, { expiresAt, timer });
1320
+ this.#cancelIntents.set(streamId, {
1321
+ expiresAt: Date.now() + this.#cancelIntentTtlMs,
1322
+ timer
1323
+ });
1101
1324
  }
1102
1325
  #hasCancelIntent(streamId) {
1103
1326
  const intent = this.#cancelIntents.get(streamId);
@@ -1704,17 +1927,17 @@ function arraysEqual(left, right) {
1704
1927
 
1705
1928
  // packages/experimental/src/zukhruf/control-plane/agent-status-projector.ts
1706
1929
  import { isTextUIPart } from "ai";
1707
- import { z as z3 } from "zod";
1930
+ import { z as z5 } from "zod";
1708
1931
  import {
1709
1932
  ContextEngine
1710
1933
  } from "@deepagents/context";
1711
- var listedAgentStatusSchema = z3.union([
1712
- z3.enum(["pending_init", "running", "interrupted", "shutdown", "not_found"]),
1713
- z3.object({ completed: z3.string().nullable() }).strict(),
1714
- z3.object({ errored: z3.string() }).strict()
1934
+ var listedAgentStatusSchema = z5.union([
1935
+ z5.enum(["pending_init", "running", "interrupted", "shutdown", "not_found"]),
1936
+ z5.object({ completed: z5.string().nullable() }).strict(),
1937
+ z5.object({ errored: z5.string() }).strict()
1715
1938
  ]);
1716
- var listedAgentSchema = z3.object({
1717
- agent_name: z3.string(),
1939
+ var listedAgentSchema = z5.object({
1940
+ agent_name: z5.string(),
1718
1941
  agent_status: listedAgentStatusSchema
1719
1942
  }).strict();
1720
1943
  var AgentStatusProjector = class _AgentStatusProjector {
@@ -1830,9 +2053,14 @@ var AgentStatusProjector = class _AgentStatusProjector {
1830
2053
  };
1831
2054
 
1832
2055
  // packages/experimental/src/zukhruf/control-plane/agent-turn-id.ts
1833
- import { v5 as uuidv53 } from "uuid";
2056
+ import { v5 as uuidv53, validate as validateUuid } from "uuid";
2057
+ import { z as z6 } from "zod";
2058
+ var prefix = "zukhruf-turn";
2059
+ var agentTurnIdSchema = z6.string().refine((value) => {
2060
+ const [head, scope, turn, ...rest] = value.split(":");
2061
+ return head === prefix && rest.length === 0 && validateUuid(scope) && validateUuid(turn);
2062
+ });
1834
2063
  var AgentTurnId = class _AgentTurnId {
1835
- static #prefix = "zukhruf-turn";
1836
2064
  #value;
1837
2065
  constructor(value) {
1838
2066
  this.#value = value;
@@ -1842,19 +2070,15 @@ var AgentTurnId = class _AgentTurnId {
1842
2070
  throw new Error("turn id cannot be empty");
1843
2071
  }
1844
2072
  const scope = conversationNamespace(conversation);
1845
- return new _AgentTurnId(
1846
- `${_AgentTurnId.#prefix}:${scope}:${uuidv53(requestId, scope)}`
1847
- );
2073
+ return new _AgentTurnId(`${prefix}:${scope}:${uuidv53(requestId, scope)}`);
1848
2074
  }
1849
2075
  static random(conversation) {
1850
2076
  return _AgentTurnId.fromRequest(conversation, crypto.randomUUID());
1851
2077
  }
1852
2078
  static assertOwner(conversation, streamId) {
1853
- const expectedPrefix = `${_AgentTurnId.#prefix}:${conversationNamespace(conversation)}:`;
2079
+ const expectedPrefix = `${prefix}:${conversationNamespace(conversation)}:`;
1854
2080
  if (!streamId.startsWith(expectedPrefix)) {
1855
- throw new Error(
1856
- `stream "${streamId}" does not belong to conversation "${conversation.chatId}"`
1857
- );
2081
+ throw new TurnNotFoundError(streamId);
1858
2082
  }
1859
2083
  }
1860
2084
  toString() {
@@ -1914,13 +2138,12 @@ var AgentControlPlane = class _AgentControlPlane {
1914
2138
  await this.#directory.assertOwnerIfExists(conversation);
1915
2139
  const thread = await this.#directory.load(conversation);
1916
2140
  if (thread && !thread.path.isRoot && await this.#queue.getTurnActivity(conversation) !== "running" && !await this.#hasExecutionCapacity(thread)) {
1917
- throw new Error("agent thread limit reached");
2141
+ throw new AgentThreadLimitError();
1918
2142
  }
1919
2143
  const streamId = message.role === "assistant" ? await this.#continuationStreamId(conversation, message) : AgentTurnId.fromRequest(conversation, message.id).toString();
1920
2144
  if (message.role === "assistant" || turn.trigger === "regenerate-message") {
1921
2145
  const status = await this.#streams.store.getStreamStatus(streamId);
1922
- if (status === void 0)
1923
- throw new Error("enqueue: continuation stream does not exist");
2146
+ if (status === void 0) throw new TurnNotFoundError(streamId);
1924
2147
  if (status === "queued" || status === "running") return streamId;
1925
2148
  await this.#streams.reopen(streamId);
1926
2149
  } else {
@@ -1937,12 +2160,7 @@ var AgentControlPlane = class _AgentControlPlane {
1937
2160
  }
1938
2161
  async #continuationStreamId(conversation, message) {
1939
2162
  const streamId = (await this.#directory.load(conversation))?.lastTurnId;
1940
- if (!streamId)
1941
- throw new Error("enqueue: assistant continuation has no previous turn");
1942
- if (message.id !== streamId)
1943
- throw new Error(
1944
- "enqueue: assistant continuation must update the current assistant message"
1945
- );
2163
+ if (message.id !== streamId) throw new StaleTurnError(message.id);
1946
2164
  return streamId;
1947
2165
  }
1948
2166
  recordLatestTurn(conversation, streamId) {
@@ -2028,11 +2246,11 @@ var AgentControlPlane = class _AgentControlPlane {
2028
2246
  });
2029
2247
  }
2030
2248
  async listAgents(actor, pathPrefix) {
2031
- const prefix = pathPrefix ? actor.thread.path.resolve(pathPrefix) : void 0;
2249
+ const prefix2 = pathPrefix ? actor.thread.path.resolve(pathPrefix) : void 0;
2032
2250
  const threads = await this.#directory.listTree(actor.thread);
2033
2251
  const agents = await Promise.all(
2034
2252
  threads.flatMap((thread) => {
2035
- if (prefix && !prefix.contains(thread.path)) return [];
2253
+ if (prefix2 && !prefix2.contains(thread.path)) return [];
2036
2254
  return [this.#statusProjector.projectListedAgent(actor.turn, thread)];
2037
2255
  })
2038
2256
  );
@@ -2386,7 +2604,7 @@ import {
2386
2604
  modelMessageSchema as modelMessageSchema2
2387
2605
  } from "ai";
2388
2606
  import { hash, randomUUID as randomUUID2 } from "node:crypto";
2389
- import { z as z4 } from "zod";
2607
+ import { z as z7 } from "zod";
2390
2608
 
2391
2609
  // packages/compaction/dist/index.js
2392
2610
  import {
@@ -2590,21 +2808,21 @@ ${options.instructions}` : SUMMARY_PROMPT,
2590
2808
  }
2591
2809
 
2592
2810
  // packages/experimental/src/zukhruf/runtime/compaction.ts
2593
- var checkpointSchema = z4.object({
2594
- sourceCount: z4.number().int().positive(),
2595
- sourceHash: z4.string(),
2596
- replacement: z4.array(z4.unknown()).transform(
2811
+ var checkpointSchema = z7.object({
2812
+ sourceCount: z7.number().int().positive(),
2813
+ sourceHash: z7.string(),
2814
+ replacement: z7.array(z7.unknown()).transform(
2597
2815
  (messages) => messages.map((message) => modelMessageSchema2.parse(message))
2598
2816
  )
2599
2817
  });
2600
- var cacheObservationSchema = z4.object({
2601
- scope: z4.string(),
2602
- prefixLength: z4.number().int().nonnegative(),
2603
- prefixHash: z4.string(),
2604
- startedAt: z4.number().int().nonnegative(),
2605
- retentionMs: z4.number().int().positive().optional()
2818
+ var cacheObservationSchema = z7.object({
2819
+ scope: z7.string(),
2820
+ prefixLength: z7.number().int().nonnegative(),
2821
+ prefixHash: z7.string(),
2822
+ startedAt: z7.number().int().nonnegative(),
2823
+ retentionMs: z7.number().int().positive().optional()
2606
2824
  });
2607
- var inputUsageSchema = cacheObservationSchema.pick({ scope: true, prefixLength: true, prefixHash: true }).extend({ inputTokens: z4.number().int().nonnegative() });
2825
+ var inputUsageSchema = cacheObservationSchema.pick({ scope: true, prefixLength: true, prefixHash: true }).extend({ inputTokens: z7.number().int().nonnegative() });
2608
2826
  function jsonDigest(value) {
2609
2827
  return hash("sha256", JSON.stringify(value));
2610
2828
  }
@@ -2744,9 +2962,9 @@ function createCompaction(config, engine, store, signal, onEvent) {
2744
2962
  }
2745
2963
  if (saved !== void 0) {
2746
2964
  const checkpoint2 = checkpointSchema.parse(saved);
2747
- const prefix = messages.slice(0, checkpoint2.sourceCount);
2748
- if (prefix.length === checkpoint2.sourceCount && jsonDigest(prefix) === checkpoint2.sourceHash) {
2749
- source = prefix;
2965
+ const prefix2 = messages.slice(0, checkpoint2.sourceCount);
2966
+ if (prefix2.length === checkpoint2.sourceCount && jsonDigest(prefix2) === checkpoint2.sourceHash) {
2967
+ source = prefix2;
2750
2968
  replacement = checkpoint2.replacement;
2751
2969
  messages = [
2752
2970
  ...replacement,
@@ -3683,21 +3901,21 @@ import {
3683
3901
  } from "@deepagents/context";
3684
3902
 
3685
3903
  // packages/experimental/src/zukhruf/runtime/conversation-status/child-progress.ts
3686
- import { z as z5 } from "zod";
3687
- var childActivitySchema = z5.object({
3688
- id: z5.string(),
3689
- type: z5.enum(["spawn", "message", "followup", "interrupt", "completion"]),
3690
- at: z5.number(),
3691
- actorPath: z5.string(),
3692
- targetPath: z5.string(),
3693
- streamId: z5.string(),
3694
- outcome: z5.enum(["completed", "failed", "cancelled"]).optional()
3904
+ import { z as z8 } from "zod";
3905
+ var childActivitySchema = z8.object({
3906
+ id: z8.string(),
3907
+ type: z8.enum(["spawn", "message", "followup", "interrupt", "completion"]),
3908
+ at: z8.number(),
3909
+ actorPath: z8.string(),
3910
+ targetPath: z8.string(),
3911
+ streamId: z8.string(),
3912
+ outcome: z8.enum(["completed", "failed", "cancelled"]).optional()
3695
3913
  });
3696
- var childActivitiesSchema = z5.partialRecord(
3914
+ var childActivitiesSchema = z8.partialRecord(
3697
3915
  childActivitySchema.shape.type,
3698
3916
  childActivitySchema
3699
3917
  );
3700
- var childActivityMetadataSchema = z5.looseObject({
3918
+ var childActivityMetadataSchema = z8.looseObject({
3701
3919
  childActivities: childActivitiesSchema.default({})
3702
3920
  });
3703
3921
 
@@ -3991,13 +4209,13 @@ var StatusPublishingTurnQueue = class extends TurnQueue {
3991
4209
 
3992
4210
  // packages/experimental/src/zukhruf/collaboration/interrupt-agent.ts
3993
4211
  import { tool as tool2 } from "ai";
3994
- import { z as z6 } from "zod";
3995
- var interruptAgentInputSchema = z6.object({
3996
- target: z6.string().trim().min(1).describe(
4212
+ import { z as z9 } from "zod";
4213
+ var interruptAgentInputSchema = z9.object({
4214
+ target: z9.string().trim().min(1).describe(
3997
4215
  "The canonical /root/... path, or a descendant-relative target name."
3998
4216
  )
3999
4217
  });
4000
- var interruptAgentOutputSchema = z6.object({ previous_status: listedAgentStatusSchema }).strict();
4218
+ var interruptAgentOutputSchema = z9.object({ previous_status: listedAgentStatusSchema }).strict();
4001
4219
  var interruptAgentTool = tool2({
4002
4220
  description: "Interrupt an agent's current turn, if any, and return its previous status. The agent remains available for messages and follow-up tasks.",
4003
4221
  inputSchema: interruptAgentInputSchema,
@@ -4007,13 +4225,13 @@ var interruptAgentTool = tool2({
4007
4225
 
4008
4226
  // packages/experimental/src/zukhruf/collaboration/list-agents.ts
4009
4227
  import { tool as tool3 } from "ai";
4010
- import { z as z7 } from "zod";
4011
- var listAgentsInputSchema = z7.object({
4012
- path_prefix: z7.string().trim().min(1).describe(
4228
+ import { z as z10 } from "zod";
4229
+ var listAgentsInputSchema = z10.object({
4230
+ path_prefix: z10.string().trim().min(1).describe(
4013
4231
  "Task-path prefix without a trailing slash. Omit to list the whole tree."
4014
4232
  ).optional()
4015
4233
  });
4016
- var listAgentsOutputSchema = z7.object({ agents: z7.array(listedAgentSchema) }).strict();
4234
+ var listAgentsOutputSchema = z10.object({ agents: z10.array(listedAgentSchema) }).strict();
4017
4235
  var listAgentsTool = tool3({
4018
4236
  description: "List live agents in the current root thread tree. Optionally filter by task-path prefix.",
4019
4237
  inputSchema: listAgentsInputSchema,
@@ -4023,12 +4241,12 @@ var listAgentsTool = tool3({
4023
4241
 
4024
4242
  // packages/experimental/src/zukhruf/collaboration/message-tools.ts
4025
4243
  import { tool as tool4 } from "ai";
4026
- import { z as z8 } from "zod";
4027
- var agentMessageInputSchema = z8.object({
4028
- target: z8.string().trim().min(1).describe(
4244
+ import { z as z11 } from "zod";
4245
+ var agentMessageInputSchema = z11.object({
4246
+ target: z11.string().trim().min(1).describe(
4029
4247
  "The canonical /root/... path, or a descendant-relative target name."
4030
4248
  ),
4031
- message: z8.string().trim().min(1).describe("The message or follow-up task.")
4249
+ message: z11.string().trim().min(1).describe("The message or follow-up task.")
4032
4250
  });
4033
4251
  var sendMessageTool = tool4({
4034
4252
  description: "Queue a message for another agent. Address siblings with their canonical /root/... path.",
@@ -4049,7 +4267,7 @@ var followupTaskTool = tool4({
4049
4267
 
4050
4268
  // packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
4051
4269
  import { tool as tool5 } from "ai";
4052
- import { z as z9 } from "zod";
4270
+ import { z as z12 } from "zod";
4053
4271
 
4054
4272
  // packages/experimental/src/zukhruf/control-plane/fork-turns.ts
4055
4273
  var forkTurnsError = "fork_turns must be `none`, `all`, or a positive integer string";
@@ -4062,18 +4280,18 @@ function parseForkTurns(value) {
4062
4280
  }
4063
4281
 
4064
4282
  // packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
4065
- var spawnAgentInputSchema = z9.object({
4066
- agent_type: z9.string().trim().min(1).describe("The name of one available subagent declaration."),
4067
- task_name: z9.string().trim().min(1).refine(
4283
+ var spawnAgentInputSchema = z12.object({
4284
+ agent_type: z12.string().trim().min(1).describe("The name of one available subagent declaration."),
4285
+ task_name: z12.string().trim().min(1).refine(
4068
4286
  (value) => value !== "." && value !== ".." && !value.includes("/"),
4069
4287
  "task_name must be one non-empty path segment"
4070
4288
  ).describe("One path segment naming this independent agent task."),
4071
- message: z9.string().refine((value) => value.trim().length > 0, "message cannot be empty").describe("The initial task for the spawned agent."),
4072
- fork_turns: z9.string().trim().refine((value) => parseForkTurns(value) !== void 0, forkTurnsError).describe(
4289
+ message: z12.string().refine((value) => value.trim().length > 0, "message cannot be empty").describe("The initial task for the spawned agent."),
4290
+ fork_turns: z12.string().trim().refine((value) => parseForkTurns(value) !== void 0, forkTurnsError).describe(
4073
4291
  "Required number of parent turns to fork. Use `none`, `all`, or a positive integer string such as `3`."
4074
4292
  )
4075
4293
  });
4076
- var spawnAgentOutputSchema = z9.object({ task_name: z9.string() }).strict();
4294
+ var spawnAgentOutputSchema = z12.object({ task_name: z12.string() }).strict();
4077
4295
  function createSpawnAgentTool(options) {
4078
4296
  return tool5({
4079
4297
  description: ({ context }) => {
@@ -4102,11 +4320,11 @@ function createSpawnAgentTool(options) {
4102
4320
 
4103
4321
  // packages/experimental/src/zukhruf/collaboration/wait-agent.ts
4104
4322
  import { tool as tool6 } from "ai";
4105
- import { z as z10 } from "zod";
4106
- var waitAgentOutputSchema = z10.object({ message: z10.string(), timed_out: z10.boolean() }).strict();
4323
+ import { z as z13 } from "zod";
4324
+ var waitAgentOutputSchema = z13.object({ message: z13.string(), timed_out: z13.boolean() }).strict();
4107
4325
  function createWaitAgentTool(options) {
4108
- const waitAgentInputSchema = z10.object({
4109
- timeout_ms: z10.number().int().max(options.maxTimeoutMs).optional().describe("Maximum time to wait in milliseconds.")
4326
+ const waitAgentInputSchema = z13.object({
4327
+ timeout_ms: z13.number().int().max(options.maxTimeoutMs).optional().describe("Maximum time to wait in milliseconds.")
4110
4328
  });
4111
4329
  return tool6({
4112
4330
  description: "Wait for pending mail addressed to this agent without consuming it.",
@@ -4479,7 +4697,7 @@ var PluginToolComposition = class {
4479
4697
  };
4480
4698
 
4481
4699
  // packages/experimental/src/zukhruf/runtime/plugin/plugin-manager.ts
4482
- function createdFrom(plugin, definition) {
4700
+ function initializedFrom(plugin, definition) {
4483
4701
  return plugin.definition === definition;
4484
4702
  }
4485
4703
  var PluginManager = class {
@@ -4492,6 +4710,7 @@ var PluginManager = class {
4492
4710
  #plugins;
4493
4711
  #toolComposition;
4494
4712
  #resources = new AsyncDisposableStack();
4713
+ #running = [];
4495
4714
  constructor(root, bindings, multiAgent) {
4496
4715
  let configuredRoot = root;
4497
4716
  const pluginBindings = new PluginBindings(root.plugins, bindings);
@@ -4544,15 +4763,20 @@ var PluginManager = class {
4544
4763
  return this.#resources.disposeAsync();
4545
4764
  }
4546
4765
  get(definition) {
4547
- const plugin = this.#plugins.find(
4548
- (candidate) => createdFrom(candidate, definition)
4766
+ if (!this.#plugins.some((plugin2) => plugin2.definition === definition)) {
4767
+ throw new Error(
4768
+ `AgentRuntime: plugin "${definition.name}" does not belong to this runtime`
4769
+ );
4770
+ }
4771
+ const plugin = this.#running.find(
4772
+ (candidate) => initializedFrom(candidate, definition)
4549
4773
  );
4550
4774
  if (!plugin) {
4551
4775
  throw new Error(
4552
- `AgentRuntime: plugin "${definition.name}" does not belong to this runtime`
4776
+ `AgentRuntime: plugin "${definition.name}" has no running phase, since its initialize() returned nothing`
4553
4777
  );
4554
4778
  }
4555
- return plugin.instance;
4779
+ return plugin.running;
4556
4780
  }
4557
4781
  configureTelemetry(context, telemetry) {
4558
4782
  const integrations = [];
@@ -4562,20 +4786,21 @@ var PluginManager = class {
4562
4786
  return integrations.length === 0 ? telemetry : { ...telemetry, integrations };
4563
4787
  }
4564
4788
  get reconcilesAvailability() {
4565
- return this.#plugins.some(
4566
- ({ instance }) => Boolean(instance.conversationAvailable)
4789
+ return this.#running.some(
4790
+ ({ running }) => Boolean(running.conversationAvailable)
4567
4791
  );
4568
4792
  }
4569
- async startWorkers(host, workers, waitForActive) {
4570
- for (const { instance } of this.#plugins) {
4571
- if (instance.work) workers.use(await instance.work(host, waitForActive));
4793
+ async startWorkers(workers, waitForActive) {
4794
+ for (const { running } of this.#running) {
4795
+ if (running.work) workers.use(await running.work(waitForActive));
4572
4796
  }
4573
4797
  }
4574
4798
  async initialize(host) {
4575
4799
  for (const { definition, instance } of this.#plugins) {
4576
4800
  const initialized = await instance.initialize?.(host);
4577
4801
  if (!initialized) continue;
4578
- this.#resources.use(initialized);
4802
+ this.#running.push({ definition, running: initialized });
4803
+ this.#resources.defer(() => initialized[Symbol.asyncDispose]?.());
4579
4804
  if (initialized.tools) {
4580
4805
  this.#toolComposition.add(definition.name, initialized.tools);
4581
4806
  }
@@ -4585,11 +4810,11 @@ var PluginManager = class {
4585
4810
  this.#toolComposition.compose(this.declarations.values())
4586
4811
  );
4587
4812
  }
4588
- async conversationAvailable(host, conversation) {
4813
+ async conversationAvailable(conversation) {
4589
4814
  const errors = [];
4590
- for (const { instance } of this.#plugins) {
4815
+ for (const { running } of this.#running) {
4591
4816
  try {
4592
- await instance.conversationAvailable?.(host, conversation);
4817
+ await running.conversationAvailable?.(conversation);
4593
4818
  } catch (error) {
4594
4819
  errors.push(error);
4595
4820
  }
@@ -4847,6 +5072,7 @@ var RuntimeHost = class {
4847
5072
  [Symbol.asyncDispose]() {
4848
5073
  return this.#resources.disposeAsync();
4849
5074
  }
5075
+ /** The running phase `initialize(host)` returned for `definition`. */
4850
5076
  plugin(definition) {
4851
5077
  return this.#plugins.get(definition);
4852
5078
  }
@@ -4877,7 +5103,7 @@ var RuntimeHost = class {
4877
5103
  read: () => this.#conversationStatus.read(conversation),
4878
5104
  publish: () => this.#conversationStatus.publish(conversation)
4879
5105
  },
4880
- () => this.#plugins.conversationAvailable(this.#pluginHost, conversation)
5106
+ () => this.#plugins.conversationAvailable(conversation)
4881
5107
  );
4882
5108
  }
4883
5109
  /**
@@ -4945,7 +5171,7 @@ var RuntimeHost = class {
4945
5171
  }
4946
5172
  async #startWorkers(options) {
4947
5173
  await using workers = new AsyncDisposableStack();
4948
- await this.#plugins.startWorkers(this.#pluginHost, workers, true);
5174
+ await this.#plugins.startWorkers(workers, true);
4949
5175
  const reconcilesAvailability = this.#plugins.reconcilesAvailability;
4950
5176
  workers.use(
4951
5177
  await this.#queue.consume(this.#executor.execute.bind(this.#executor), {
@@ -4955,10 +5181,7 @@ var RuntimeHost = class {
4955
5181
  onSettled: async ({ chatId, userId }) => {
4956
5182
  await this.#conversationStatus.publish({ chatId, userId });
4957
5183
  if (reconcilesAvailability) {
4958
- await this.#plugins.conversationAvailable(this.#pluginHost, {
4959
- chatId,
4960
- userId
4961
- });
5184
+ await this.#plugins.conversationAvailable({ chatId, userId });
4962
5185
  }
4963
5186
  }
4964
5187
  })