@capybara-hq/kernel 0.1.0-rc.134 → 0.1.0-rc.136

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 (113) hide show
  1. package/bootstrap.json +1 -1
  2. package/dist/admin/admin.module.js +3 -0
  3. package/dist/admin/health.service.d.ts +2 -2
  4. package/dist/admin/health.service.js +6 -2
  5. package/dist/catalog/marketplaces.service.d.ts +1 -1
  6. package/dist/config/schema.d.ts +7 -0
  7. package/dist/config/schema.js +60 -2
  8. package/dist/conversations/access.d.ts +15 -7
  9. package/dist/conversations/access.js +59 -10
  10. package/dist/conversations/conversation-agent.d.ts +18 -0
  11. package/dist/conversations/conversation-agent.js +23 -0
  12. package/dist/conversations/conversation-ref.d.ts +3 -2
  13. package/dist/conversations/conversation-ref.js +6 -1
  14. package/dist/conversations/conversations.controller.d.ts +28 -5
  15. package/dist/conversations/conversations.controller.js +99 -10
  16. package/dist/conversations/conversations.module.js +10 -0
  17. package/dist/conversations/conversations.schemas.d.ts +6 -0
  18. package/dist/conversations/conversations.schemas.js +15 -0
  19. package/dist/conversations/conversations.service.d.ts +125 -21
  20. package/dist/conversations/conversations.service.js +260 -90
  21. package/dist/conversations/event-log.d.ts +9 -1
  22. package/dist/conversations/event-log.js +2 -0
  23. package/dist/conversations/events.d.ts +57 -0
  24. package/dist/conversations/events.js +73 -1
  25. package/dist/conversations/external/external-calls.d.ts +75 -0
  26. package/dist/conversations/external/external-calls.js +91 -0
  27. package/dist/conversations/external/external-calls.processor.d.ts +45 -0
  28. package/dist/conversations/external/external-calls.processor.js +144 -0
  29. package/dist/conversations/external/external-conversations.service.d.ts +266 -0
  30. package/dist/conversations/external/external-conversations.service.js +1138 -0
  31. package/dist/conversations/external/external.schemas.d.ts +63 -0
  32. package/dist/conversations/external/external.schemas.js +52 -0
  33. package/dist/conversations/external/token.d.ts +6 -0
  34. package/dist/conversations/external/token.js +6 -0
  35. package/dist/conversations/permission-profile-store.d.ts +4 -1
  36. package/dist/conversations/permission-profiles.controller.d.ts +33 -9
  37. package/dist/conversations/permission-profiles.controller.js +86 -6
  38. package/dist/conversations/prompt-suggestions.js +2 -1
  39. package/dist/conversations/queue.js +2 -1
  40. package/dist/conversations/titles.js +4 -3
  41. package/dist/ctx/create-ctx.d.ts +7 -0
  42. package/dist/ctx/create-ctx.js +45 -2
  43. package/dist/db/extension-db.d.ts +8 -3
  44. package/dist/db/extension-db.js +107 -7
  45. package/dist/db/extension-role-provision.d.ts +9 -0
  46. package/dist/db/extension-role-provision.js +89 -0
  47. package/dist/db/extension-schema-transfer.d.ts +2 -1
  48. package/dist/db/extension-schema-transfer.js +103 -19
  49. package/dist/db/kernel-schema.d.ts +31 -4
  50. package/dist/db/migrator.d.ts +2 -0
  51. package/dist/db/migrator.js +4 -3
  52. package/dist/device-access/host-services.js +3 -2
  53. package/dist/device-access/person-handles.d.ts +16 -7
  54. package/dist/device-access/person-handles.js +14 -9
  55. package/dist/devices/conversation-devices.d.ts +5 -0
  56. package/dist/devices/conversation-devices.js +16 -0
  57. package/dist/erasure/org-catalog.js +2 -2
  58. package/dist/errors.d.ts +34 -0
  59. package/dist/errors.js +34 -0
  60. package/dist/evals/snapshot.js +3 -1
  61. package/dist/evals/trajectory.service.d.ts +2 -2
  62. package/dist/evals/trajectory.service.js +11 -7
  63. package/dist/extensions/admin-ops.js +17 -1
  64. package/dist/extensions/extensions.module.js +3 -0
  65. package/dist/extensions/host.d.ts +9 -1
  66. package/dist/extensions/host.js +14 -2
  67. package/dist/extensions/migrate-lock.js +1 -0
  68. package/dist/extensions/permission-view.d.ts +3 -1
  69. package/dist/extensions/permission-view.js +4 -1
  70. package/dist/extensions/point-defaults.d.ts +13 -21
  71. package/dist/extensions/point-defaults.js +32 -72
  72. package/dist/extensions/point-serving.d.ts +56 -0
  73. package/dist/extensions/point-serving.js +120 -0
  74. package/dist/inbox/inbox-items.service.d.ts +11 -0
  75. package/dist/inbox/inbox-items.service.js +39 -0
  76. package/dist/index.d.ts +3 -1
  77. package/dist/index.js +3 -1
  78. package/dist/infra/database/rls-role.d.ts +4 -11
  79. package/dist/infra/database/rls-role.js +71 -27
  80. package/dist/infra/outbox/registry.d.ts +70 -0
  81. package/dist/infra/outbox/registry.js +44 -0
  82. package/dist/infra/queue/queue-names.d.ts +1 -1
  83. package/dist/infra/queue/queue-names.js +1 -0
  84. package/dist/kernel.d.ts +2 -0
  85. package/dist/kernel.js +12 -2
  86. package/dist/kernel.module.js +4 -0
  87. package/dist/lifecycle/kernel-lifecycle.js +2 -3
  88. package/dist/platform/exclusions.js +10 -0
  89. package/dist/platform/ops/conversations.ops.d.ts +8 -1
  90. package/dist/platform/ops/conversations.ops.js +52 -14
  91. package/dist/plugin-reads/plugin-reads.service.js +4 -1
  92. package/dist/push/recipients.js +5 -2
  93. package/dist/retention/worker.js +2 -1
  94. package/dist/roles/worker-role.d.ts +3 -1
  95. package/dist/roles/worker-role.js +8 -2
  96. package/dist/roles/worker.module.js +3 -0
  97. package/dist/runtime/context/build.js +8 -0
  98. package/dist/runtime/context/compaction.js +7 -0
  99. package/dist/runtime/idle-arm.js +3 -1
  100. package/dist/runtime/idle-compaction.js +2 -1
  101. package/dist/runtime/run-finish.js +2 -1
  102. package/dist/runtime/run-jobs.js +2 -1
  103. package/dist/runtime/run-queue.js +4 -2
  104. package/dist/runtime/run-worker.js +5 -2
  105. package/dist/runtime/stream.js +10 -0
  106. package/dist/runtime/usage-report.js +2 -1
  107. package/dist/runtime/waits.js +2 -1
  108. package/dist/tools/approvals.service.js +6 -2
  109. package/dist/tools/builtins/skill-load.js +3 -2
  110. package/dist/tools/tool-watch.service.js +3 -1
  111. package/package.json +3 -3
  112. package/src/migrations/0226_enable_kernel_rls.sql +30 -0
  113. package/src/migrations/0227_external_conversations.sql +33 -0
@@ -21,8 +21,10 @@ import { DeviceProjectsService } from "../devices/device-projects.service.js";
21
21
  import { projectFilePath } from "../devices/project-paths.js";
22
22
  import { clipped } from "../devices/project-rules.js";
23
23
  import { ApiError } from "../errors.js";
24
+ import { ExtensionPointDefaults } from "../extensions/point-defaults.js";
24
25
  import { LibraryFilesService } from "../files/library-files.service.js";
25
26
  import { loadPeople } from "../identity/account-avatar.js";
27
+ import { InboxItemsService } from "../inbox/inbox-items.service.js";
26
28
  import { afterCommit } from "../infra/database/after-commit.js";
27
29
  import { KernelDb } from "../infra/database/kernel-db.js";
28
30
  import { TransactionHost, withTransactionFencePrelude, } from "../infra/database/transaction-host.js";
@@ -49,10 +51,12 @@ import { QuestionsService } from "../tools/questions.service.js";
49
51
  import { READ_RESOURCE } from "../tools/resources.js";
50
52
  import { ConversationAccess, parentReachable } from "./access.js";
51
53
  import { readAgentTree } from "./agent-tree.js";
54
+ import { agentIdOf, agentIdOfView } from "./conversation-agent.js";
52
55
  import { conversationRefText, REF_TURN_MESSAGES, refMessageText } from "./conversation-ref.js";
53
56
  import { EventLog } from "./event-log.js";
54
57
  import { peopleOfEvents } from "./event-people.js";
55
58
  import { refFileId } from "./events.js";
59
+ import { externalCallJob, requestItemKey, TARGET_POINT } from "./external/external-calls.js";
56
60
  import { userMessageIdemKey } from "./idem-keys.js";
57
61
  import { connectorMentionText, fileLine, foldLabel, MENTION_LOAD_MAX_TOOLS, numberLabels, placeholder, renderInline, tokenEntityKey, } from "./inline-tokens.js";
58
62
  import { readMessageContext, } from "./message-context.js";
@@ -77,7 +81,7 @@ function projectStateSql(ref) {
77
81
  )`;
78
82
  }
79
83
  /** The columns of a single-conversation response: {@link COLUMNS} and its project state. */
80
- const viewColumns = () => [...COLUMNS, projectStateSql("conversations").as("project_state")];
84
+ export const viewColumns = () => [...COLUMNS, projectStateSql("conversations").as("project_state")];
81
85
  /** Escapes `\`, `%` and `_` so user text is matched literally by `LIKE … ESCAPE '\'`. */
82
86
  export function escapeLike(s) {
83
87
  return s.replace(/[\\%_]/g, (ch) => `\\${ch}`);
@@ -87,11 +91,15 @@ export function escapeLike(s) {
87
91
  * A run waiting on its sub-agents (status waiting with `wait_expires_at`, set only for a
88
92
  * `subagents` wait) is still working, so it reports `running`; only a wait for a person
89
93
  * (approval, input) reports `waiting`. An idle compact run is not activity (idle compaction spec
90
- * §6: quiet): the latest other run decides.
94
+ * §6: quiet): the latest other run decides. An external conversation has no runs: its target's
95
+ * reported `external_state` decides (`running` / `waiting`; `idle` and `ended` are no activity).
91
96
  */
92
97
  function activitySql(ref) {
93
98
  const id = sql.ref(`${ref}.id`);
94
- return sql `(
99
+ return sql `CASE WHEN ${sql.ref(`${ref}.kind`)} = 'external'
100
+ THEN CASE WHEN ${sql.ref(`${ref}.external_state`)} IN ('running', 'waiting')
101
+ THEN ${sql.ref(`${ref}.external_state`)} END
102
+ ELSE (
95
103
  SELECT CASE
96
104
  WHEN lr.status IN ('queued', 'running') THEN 'running'
97
105
  WHEN lr.status = 'waiting' AND lr.wait_expires_at IS NOT NULL THEN 'running'
@@ -99,7 +107,33 @@ function activitySql(ref) {
99
107
  FROM capybara.runs lr
100
108
  WHERE lr.conversation_id = ${id} AND lr.compact_origin IS DISTINCT FROM 'idle'
101
109
  ORDER BY lr.created_at DESC, lr.id DESC LIMIT 1
102
- )`;
110
+ ) END`;
111
+ }
112
+ /**
113
+ * SQL: the conversation row aliased/named `ref` is an external conversation of one of `serving`
114
+ * (the extensions serving `conversation-target@1` in the org); false when there are none.
115
+ */
116
+ function externalOf(serving, ref) {
117
+ if (serving.length === 0)
118
+ return sql `false`;
119
+ return sql `(${sql.ref(`${ref}.kind`)} = 'external'
120
+ AND ${sql.ref(`${ref}.external`)}->>'extension' = ANY(${[...serving]}::text[]))`;
121
+ }
122
+ /**
123
+ * SQL: the {@link ConversationGroup} key of the conversation row aliased/named `ref`: its agent id,
124
+ * or `target/<extension>/<targetKey>` for an external conversation.
125
+ */
126
+ function groupKeySql(ref) {
127
+ const ext = sql.ref(`${ref}.external`);
128
+ return sql `CASE WHEN ${sql.ref(`${ref}.kind`)} = 'external'
129
+ THEN 'target/' || (${ext}->>'extension') || '/' || (${ext}->>'targetKey')
130
+ ELSE ${sql.ref(`${ref}.agent_id`)} END`;
131
+ }
132
+ /** SQL: the conversation row aliased/named `ref` is an external conversation with target `t`. */
133
+ function targetIs(t, ref) {
134
+ const ext = sql.ref(`${ref}.external`);
135
+ return sql `(${sql.ref(`${ref}.kind`)} = 'external'
136
+ AND ${ext}->>'extension' = ${t.extension} AND ${ext}->>'targetKey' = ${t.targetKey})`;
103
137
  }
104
138
  /** A {@link ConversationAgent} from an agent row and its current definition's name. */
105
139
  function toConversationAgent(r) {
@@ -182,12 +216,25 @@ const COLUMNS = [
182
216
  "subject",
183
217
  "project_name",
184
218
  "project_path",
219
+ "kind",
220
+ "external",
221
+ "external_state",
185
222
  ];
186
- function toView(r) {
223
+ /** A conversation row (its {@link COLUMNS}) as the {@link ConversationView} the routes answer. */
224
+ export function toView(r) {
187
225
  return {
188
226
  id: r.id,
189
227
  orgId: r.org_id,
228
+ kind: r.kind,
190
229
  agentId: r.agent_id,
230
+ external: r.external === null
231
+ ? null
232
+ : {
233
+ extension: r.external.extension,
234
+ targetKey: r.external.targetKey,
235
+ label: r.external.label,
236
+ state: r.external_state,
237
+ },
191
238
  accountId: r.account_id,
192
239
  title: r.title,
193
240
  titleSource: r.title_source,
@@ -283,6 +330,8 @@ let ConversationsService = class ConversationsService {
283
330
  ceilings;
284
331
  outbox;
285
332
  mentions;
333
+ points;
334
+ inbox;
286
335
  constructor(permissions, db, eventLog, agents, access,
287
336
  /** Starts and stops the conversation's runs. */
288
337
  runs,
@@ -309,7 +358,11 @@ let ConversationsService = class ConversationsService {
309
358
  /** Owes the snapshot deletions of the shares a deletion revokes (file sharing spec §9). */
310
359
  outbox,
311
360
  /** The agent's tools for a message naming connectors or resources (inline tokens §3.4). */
312
- mentions) {
361
+ mentions,
362
+ /** Which extensions serve `conversation-target@1` in the org (external conversations). */
363
+ points,
364
+ /** A deleted external conversation's open request items are resolved with it. */
365
+ inbox) {
313
366
  this.permissions = permissions;
314
367
  this.db = db;
315
368
  this.eventLog = eventLog;
@@ -331,6 +384,8 @@ let ConversationsService = class ConversationsService {
331
384
  this.ceilings = ceilings;
332
385
  this.outbox = outbox;
333
386
  this.mentions = mentions;
387
+ this.points = points;
388
+ this.inbox = inbox;
334
389
  }
335
390
  /**
336
391
  * Creates an empty conversation bound to its device (`pick`, see
@@ -540,11 +595,11 @@ let ConversationsService = class ConversationsService {
540
595
  .executeTakeFirstOrThrow());
541
596
  }
542
597
  /**
543
- * Renames a conversation (owner only, as {@link get}): `title_source = 'manual'`, so the title
598
+ * Renames a conversation (owner only, as {@link owned}): `title_source = 'manual'`, so the title
544
599
  * job never overwrites it. Publishes `changed: title`. `title` is already trimmed and checked.
545
600
  */
546
601
  async rename(orgId, conversationId, accountId, title) {
547
- await this.writable(orgId, conversationId, accountId);
602
+ await this.owned(orgId, conversationId, accountId);
548
603
  const row = await this.db
549
604
  .updateTable("conversations")
550
605
  .set({ title, title_source: "manual" })
@@ -560,7 +615,7 @@ let ConversationsService = class ConversationsService {
560
615
  * conversation leaves the default lists but stays readable. Publishes `changed: archived`.
561
616
  */
562
617
  async setArchived(orgId, conversationId, accountId, archived) {
563
- await this.writable(orgId, conversationId, accountId);
618
+ await this.owned(orgId, conversationId, accountId);
564
619
  const row = await this.db
565
620
  .updateTable("conversations")
566
621
  .set({ archived_at: archived ? sql `now()` : null })
@@ -583,7 +638,9 @@ let ConversationsService = class ConversationsService {
583
638
  * log, runs and trajectory remain available during the product recovery hold.
584
639
  */
585
640
  async remove(orgId, conversationId, accountId) {
586
- await this.writable(orgId, conversationId, accountId);
641
+ // an external conversation is deleted by its owner while its target serves the org (local
642
+ // agents spec Part 2)
643
+ await this.owned(orgId, conversationId, accountId);
587
644
  const subject = await this.deletionSubject(orgId, conversationId);
588
645
  await this.tombstone(orgId, conversationId, accountId, subject);
589
646
  }
@@ -605,7 +662,8 @@ let ConversationsService = class ConversationsService {
605
662
  .where("org_id", "=", orgId)
606
663
  .where("id", "=", conversationId)
607
664
  .where("parent_conversation_id", "is", null)
608
- .where("kind", "=", "chat")
665
+ // an external conversation expires as a chat does (local agents spec Part 2)
666
+ .where("kind", "in", ["chat", "external"])
609
667
  .where("deleted_at", "is", null)
610
668
  .executeTakeFirst();
611
669
  if (!root)
@@ -688,7 +746,7 @@ let ConversationsService = class ConversationsService {
688
746
  await this.ceilings.lock(locked, "root");
689
747
  const row = await this.db
690
748
  .selectFrom("conversations")
691
- .select("id")
749
+ .select(["id", "kind", "last_seq"])
692
750
  .where("id", "=", conversationId)
693
751
  .where("org_id", "=", orgId)
694
752
  .where("account_id", "=", accountId)
@@ -738,6 +796,12 @@ let ConversationsService = class ConversationsService {
738
796
  deviceId: subject.deviceId,
739
797
  conversationId,
740
798
  });
799
+ // an external conversation's target releases what it holds for it, and its open request
800
+ // items leave the owner's inbox (local agents spec Part 2, call 8)
801
+ if (row.kind === "external") {
802
+ await this.outbox.add(externalCallJob({ orgId, conversationId, call: "deleted", seq: Number(row.last_seq) }));
803
+ await this.inbox.resolveKernelItems(orgId, accountId, requestItemKey(conversationId, ""));
804
+ }
741
805
  // a root's loopback port grants end with it and its services are refreshed without them (a
742
806
  // sub-agent's conversation holds none)
743
807
  await revokeLoopbackGrantsOfConversation(this.db.db, this.outbox, {
@@ -773,9 +837,25 @@ let ConversationsService = class ConversationsService {
773
837
  )) AS expired`.execute(this.db.db);
774
838
  return result.rows[0]?.expired === true;
775
839
  }
776
- /** 读会话:非所有者、或 agent 已对所有者不可用 → `conversation.not_found`。 */
840
+ /**
841
+ * Reads a conversation: another person's, or one whose agent the owner can no longer use →
842
+ * `conversation.not_found`. An external conversation (local agents spec Part 2) is read by its
843
+ * owner while its extension serves `conversation-target@1` in the org, else
844
+ * `conversation.not_found` too.
845
+ */
777
846
  async get(orgId, conversationId, viewerAccountId) {
778
- const { kind: _kind, ...row } = await this.readable(orgId, conversationId, viewerAccountId);
847
+ return toView(await this.readable(orgId, conversationId, viewerAccountId));
848
+ }
849
+ /**
850
+ * {@link get} for a change of the conversation itself by its owner (rename, archive, delete): a
851
+ * sub-agent's conversation is read-only (sub-agents spec §6.1) → `conversation.read_only`; an
852
+ * external conversation passes.
853
+ */
854
+ async owned(orgId, conversationId, accountId) {
855
+ const row = await this.readable(orgId, conversationId, accountId);
856
+ if (row.kind === "subagent") {
857
+ throw new ApiError("conversation.read_only", "A sub-agent's conversation takes no messages");
858
+ }
779
859
  return toView(row);
780
860
  }
781
861
  async getWithOwner(orgId, conversationId, viewerAccountId) {
@@ -783,21 +863,23 @@ let ConversationsService = class ConversationsService {
783
863
  return { ...conversation, owner: await this.person(conversation.accountId) };
784
864
  }
785
865
  /**
786
- * {@link get} for a change made by a person (a message, rename, queue, model switch): a
787
- * sub-agent's conversation is read-only (sub-agents spec §6.1) → `conversation.read_only`.
866
+ * {@link owned} for a change that works through Capybara's runs (a message, the queue, a model
867
+ * switch, compaction, an extension UI action): an external conversation is run by its local
868
+ * agent, not by Capybara (its messages and stop go through `ExternalConversationsService`) →
869
+ * `conversation.external_read_only`.
788
870
  */
789
871
  async writable(orgId, conversationId, accountId) {
790
- const { kind, ...row } = await this.readable(orgId, conversationId, accountId);
791
- if (kind === "subagent") {
792
- throw new ApiError("conversation.read_only", "A sub-agent's conversation takes no messages");
872
+ const view = await this.owned(orgId, conversationId, accountId);
873
+ if (view.kind === "external") {
874
+ throw new ApiError("conversation.external_read_only", "This conversation is with a local agent; it does not run here");
793
875
  }
794
- return toView(row);
876
+ return view;
795
877
  }
796
878
  /** {@link get}'s row, with the conversation's kind. */
797
879
  async readable(orgId, conversationId, viewerAccountId) {
798
880
  const row = await this.db
799
881
  .selectFrom("conversations")
800
- .select([...viewColumns(), "kind"])
882
+ .select(viewColumns())
801
883
  .where("id", "=", conversationId)
802
884
  .where("org_id", "=", orgId)
803
885
  .where("account_id", "=", viewerAccountId)
@@ -808,9 +890,9 @@ let ConversationsService = class ConversationsService {
808
890
  .where(parentReachable(viewerAccountId))
809
891
  .executeTakeFirst();
810
892
  if (!row)
811
- throw notFound();
893
+ return this.readableExternal(orgId, conversationId, viewerAccountId);
812
894
  try {
813
- await this.agents.get(orgId, row.agent_id, viewerAccountId);
895
+ await this.agents.get(orgId, agentIdOf(row), viewerAccountId);
814
896
  }
815
897
  catch (e) {
816
898
  if (e instanceof ApiError && e.code === "agent.not_found")
@@ -819,18 +901,51 @@ let ConversationsService = class ConversationsService {
819
901
  }
820
902
  return row;
821
903
  }
904
+ /**
905
+ * {@link readable} for an external conversation (local agents spec Part 2): the viewer's, while
906
+ * its extension serves `conversation-target@1` in the org (the org guard checked the
907
+ * membership); anything else → `conversation.not_found`.
908
+ */
909
+ async readableExternal(orgId, conversationId, viewerAccountId) {
910
+ const row = await this.db
911
+ .selectFrom("conversations")
912
+ .select(viewColumns())
913
+ .where("id", "=", conversationId)
914
+ .where("org_id", "=", orgId)
915
+ .where("account_id", "=", viewerAccountId)
916
+ .where("deleted_at", "is", null)
917
+ .where("kind", "=", "external")
918
+ .executeTakeFirst();
919
+ if (!row ||
920
+ row.external === null ||
921
+ !(await this.points.serves(orgId, TARGET_POINT, row.external.extension)))
922
+ throw notFound();
923
+ return row;
924
+ }
822
925
  /** The stream's visibility check ({@link ConversationAccess.isAccessible}). */
823
926
  isAccessible(orgId, conversationId, viewerAccountId) {
824
927
  return this.access.isAccessible(orgId, conversationId, viewerAccountId);
825
928
  }
826
929
  /**
827
- * My conversations, most recently updated first; only those whose agent is in this org, not
828
- * deleted and visible to me. `after` is the previous page's last conversation id, continued after
829
- * its current (updated_at, id); a cursor that no longer exists gives an empty page. Each row
830
- * carries its agent (one batch read for the page). With `total`, also counts every conversation
831
- * matching the same filters (the cursor aside) in the same statement.
930
+ * The extensions that serve `conversation-target@1` in the org now: the external conversations
931
+ * the lists show (local agents spec Part 2).
932
+ */
933
+ async servingTargets(orgId) {
934
+ const { providers } = await this.points.providersFor(orgId, TARGET_POINT);
935
+ return providers.map((p) => p.extension);
936
+ }
937
+ /**
938
+ * My conversations, most recently updated first: the chat conversations whose agent is in this
939
+ * org, not deleted and visible to me, and the external ones whose extension serves
940
+ * `conversation-target@1` in the org now (local agents spec Part 2). `after` is the previous
941
+ * page's last conversation id, continued after its current (updated_at, id); a cursor that no
942
+ * longer exists gives an empty page. Each row carries its agent (one batch read for the page;
943
+ * null for an external conversation). `agentId` keeps one agent's, `target` one target's. With
944
+ * `total`, also counts every conversation matching the same filters (the cursor aside) in the
945
+ * same statement.
832
946
  */
833
947
  async listMine(orgId, accountId, opts) {
948
+ const serving = await this.servingTargets(orgId);
834
949
  let q = this.db
835
950
  .selectFrom("conversations")
836
951
  .select(COLUMNS)
@@ -841,22 +956,33 @@ let ConversationsService = class ConversationsService {
841
956
  .$if(opts.total === true, (qb) => qb.select(sql `count(*) OVER ()`.as("total_count")))
842
957
  .where("org_id", "=", orgId)
843
958
  .where("account_id", "=", accountId)
844
- // Keep the fixed kind literal so generic plans can use the partial chat index.
845
- .where("kind", "=", sql.lit("chat"))
959
+ // hidden eval replay conversations (kind 'eval') are not among my conversations; external
960
+ // ones are while a target serves the org. Without one, keep the fixed kind literal so
961
+ // generic plans can use the partial chat index.
962
+ .where((eb) => serving.length === 0
963
+ ? eb("kind", "=", sql.lit("chat"))
964
+ : eb("kind", "in", ["chat", "external"]))
846
965
  .where("deleted_at", "is", null)
847
966
  .where("archived_at", opts.archived === true ? "is not" : "is", null)
848
- .where((eb) => eb.exists(eb
849
- .selectFrom("agents")
850
- .select(sql `1`.as("one"))
851
- .whereRef("agents.id", "=", "conversations.agent_id")
852
- .where("agents.org_id", "=", orgId)
853
- .where("agents.deleted_at", "is", null)
854
- .where(visibleTo(accountId))))
967
+ .where((eb) => {
968
+ const agentVisible = eb.exists(eb
969
+ .selectFrom("agents")
970
+ .select(sql `1`.as("one"))
971
+ .whereRef("agents.id", "=", "conversations.agent_id")
972
+ .where("agents.org_id", "=", orgId)
973
+ .where("agents.deleted_at", "is", null)
974
+ .where(visibleTo(accountId)));
975
+ return serving.length === 0
976
+ ? agentVisible
977
+ : eb.or([agentVisible, externalOf(serving, "conversations")]);
978
+ })
855
979
  .orderBy("updated_at", "desc")
856
980
  .orderBy("id", "desc")
857
981
  .limit(opts.limit);
858
982
  if (opts.agentId !== undefined)
859
983
  q = q.where("agent_id", "=", opts.agentId);
984
+ if (opts.target !== undefined)
985
+ q = q.where(targetIs(opts.target, "conversations"));
860
986
  if (opts.q !== undefined) {
861
987
  q = q.where(sql `conversations.title ILIKE ${`%${escapeLike(opts.q)}%`} ESCAPE '\\'`);
862
988
  }
@@ -872,11 +998,11 @@ let ConversationsService = class ConversationsService {
872
998
  }
873
999
  const rows = await q.execute();
874
1000
  const agents = await this.listAgents(orgId, accountId, [
875
- ...new Set(rows.map((r) => r.agent_id)),
1001
+ ...new Set(rows.flatMap((r) => (r.agent_id === null ? [] : [r.agent_id]))),
876
1002
  ]);
877
1003
  const conversations = rows.map((r) => ({
878
1004
  ...toView(r),
879
- agent: agents.get(r.agent_id) ?? null,
1005
+ agent: r.agent_id === null ? null : (agents.get(r.agent_id) ?? null),
880
1006
  }));
881
1007
  if (opts.total !== true)
882
1008
  return { conversations };
@@ -906,19 +1032,24 @@ let ConversationsService = class ConversationsService {
906
1032
  return new Map(rows.map((r) => [r.id, toConversationAgent(r)]));
907
1033
  }
908
1034
  /**
909
- * My chat conversations grouped by agent (the sidebar, UI refresh spec §5.9), in one statement.
910
- * Only agents that are not deleted and still visible to me (as {@link listMine}). Groups are
911
- * ordered by (latestAt DESC, agent id DESC); each holds up to `perGroup` conversations and says
912
- * whether it has more. `after` is the last group's agent id, re-evaluated against that group's
913
- * current latestAt; a cursor agent that is no longer listed gives an empty page.
1035
+ * My conversations grouped by agent (the sidebar, UI refresh spec §5.9), and my external
1036
+ * conversations by target (local agents spec Part 2), in one statement. Only agents that are not
1037
+ * deleted and still visible to me and targets whose extension serves `conversation-target@1` in
1038
+ * the org now (as {@link listMine}). Groups are ordered by (latestAt DESC, key DESC); each holds
1039
+ * up to `perGroup` conversations and says whether it has more. `after` is the last group's key,
1040
+ * re-evaluated against that group's current latestAt; a cursor group that is no longer listed
1041
+ * gives an empty page.
914
1042
  */
915
1043
  async listGroups(orgId, accountId, opts) {
1044
+ const serving = await this.servingTargets(orgId);
916
1045
  const visibleAgents = this.db
917
1046
  .selectFrom("agents")
918
1047
  .select("agents.id")
919
1048
  .where("agents.org_id", "=", orgId)
920
1049
  .where("agents.deleted_at", "is", null)
921
1050
  .where(visibleTo(accountId));
1051
+ // a chat conversation of a listed agent, or an external one of a serving target
1052
+ const listed = sql `((c.kind = 'chat' AND c.agent_id IN ${visibleAgents}) OR ${externalOf(serving, "c")})`;
922
1053
  const archivedFilter = opts.archived === true ? sql `c.archived_at IS NOT NULL` : sql `c.archived_at IS NULL`;
923
1054
  const searchFilter = opts.q === undefined
924
1055
  ? sql ``
@@ -926,56 +1057,74 @@ let ConversationsService = class ConversationsService {
926
1057
  const stateFilter = opts.state === undefined ? sql `` : sql `AND ${activitySql("c")} = ${opts.state}`;
927
1058
  const cursor = opts.after === undefined
928
1059
  ? sql ``
929
- : sql `WHERE (g.latest_at, g.agent_id) < (
930
- SELECT g2.latest_at, g2.agent_id FROM g g2 WHERE g2.agent_id = ${opts.after}
1060
+ : sql `WHERE (g.latest_at, g.group_key) < (
1061
+ SELECT g2.latest_at, g2.group_key FROM g g2 WHERE g2.group_key = ${opts.after}
931
1062
  )`;
932
1063
  const { rows } = await sql `
933
1064
  WITH g AS (
934
- SELECT c.agent_id, max(c.updated_at) AS latest_at
1065
+ SELECT c.agent_id, c.external->>'extension' AS extension,
1066
+ c.external->>'targetKey' AS target_key,
1067
+ ${groupKeySql("c")} AS group_key, max(c.updated_at) AS latest_at
935
1068
  FROM capybara.conversations c
936
- WHERE c.org_id = ${orgId} AND c.account_id = ${accountId} AND c.kind = 'chat'
1069
+ WHERE c.org_id = ${orgId} AND c.account_id = ${accountId}
937
1070
  AND c.deleted_at IS NULL AND ${archivedFilter} ${searchFilter} ${stateFilter}
938
- AND c.agent_id IN ${visibleAgents}
939
- GROUP BY c.agent_id
1071
+ AND ${listed}
1072
+ GROUP BY 1, 2, 3, 4
940
1073
  ), page AS (
941
- SELECT g.agent_id, g.latest_at FROM g
1074
+ SELECT g.agent_id, g.extension, g.target_key, g.group_key, g.latest_at FROM g
942
1075
  ${cursor}
943
- ORDER BY g.latest_at DESC, g.agent_id DESC
1076
+ ORDER BY g.latest_at DESC, g.group_key DESC
944
1077
  LIMIT ${opts.limit + 1}
945
1078
  )
946
- SELECT page.agent_id, page.latest_at, v.definition ->> 'name' AS agent_name,
1079
+ SELECT page.group_key, page.latest_at, page.agent_id, v.definition ->> 'name' AS agent_name,
947
1080
  a.profile_avatar, a.profile_updated_at, cs.id, cs.org_id, cs.account_id, cs.title, cs.title_source, cs.selection, cs.last_seq,
948
1081
  cs.created_at, cs.updated_at, cs.parent_conversation_id, cs.subagent_type,
949
1082
  cs.archived_at, cs.device_id, cs.automation_id, cs.subject, cs.project_name, cs.project_path,
950
- cs.activity
1083
+ cs.kind, cs.external, cs.external_state, cs.activity
951
1084
  FROM page
952
- JOIN capybara.agents a ON a.id = page.agent_id
953
- JOIN capybara.agent_versions v ON v.agent_id = a.id AND v.version = a.current_version
1085
+ LEFT JOIN capybara.agents a ON a.id = page.agent_id
1086
+ LEFT JOIN capybara.agent_versions v ON v.agent_id = a.id AND v.version = a.current_version
954
1087
  CROSS JOIN LATERAL (
955
1088
  SELECT c.id, c.org_id, c.account_id, c.title, c.title_source, c.selection, c.last_seq,
956
1089
  c.created_at, c.updated_at, c.parent_conversation_id, c.subagent_type,
957
1090
  c.archived_at, c.device_id, c.automation_id, c.subject, c.project_name, c.project_path,
958
- ${activitySql("c")} AS activity
1091
+ c.kind, c.external, c.external_state, ${activitySql("c")} AS activity
959
1092
  FROM capybara.conversations c
960
- WHERE c.org_id = ${orgId} AND c.account_id = ${accountId} AND c.kind = 'chat'
1093
+ WHERE c.org_id = ${orgId} AND c.account_id = ${accountId}
961
1094
  AND c.deleted_at IS NULL AND ${archivedFilter} ${searchFilter} ${stateFilter}
962
- AND c.agent_id = page.agent_id
1095
+ AND (
1096
+ (page.agent_id IS NOT NULL AND c.kind = 'chat' AND c.agent_id = page.agent_id)
1097
+ OR (page.agent_id IS NULL AND c.kind = 'external'
1098
+ AND c.external->>'extension' = page.extension
1099
+ AND c.external->>'targetKey' = page.target_key)
1100
+ )
963
1101
  ORDER BY c.updated_at DESC, c.id DESC
964
1102
  LIMIT ${opts.perGroup + 1}
965
1103
  ) cs
966
- ORDER BY page.latest_at DESC, page.agent_id DESC, cs.updated_at DESC, cs.id DESC
1104
+ ORDER BY page.latest_at DESC, page.group_key DESC, cs.updated_at DESC, cs.id DESC
967
1105
  `.execute(this.db.db);
968
1106
  const groups = [];
969
1107
  let current;
970
1108
  for (const r of rows) {
971
- if (current?.agent.id !== r.agent_id) {
1109
+ if (current?.key !== r.group_key) {
972
1110
  current = {
973
- agent: toConversationAgent({
974
- id: r.agent_id,
975
- name: r.agent_name,
976
- profile_avatar: r.profile_avatar,
977
- profile_updated_at: r.profile_updated_at,
978
- }),
1111
+ key: r.group_key,
1112
+ agent: r.agent_id === null || r.profile_updated_at === null
1113
+ ? null
1114
+ : toConversationAgent({
1115
+ id: r.agent_id,
1116
+ name: r.agent_name,
1117
+ profile_avatar: r.profile_avatar,
1118
+ profile_updated_at: r.profile_updated_at,
1119
+ }),
1120
+ // the newest conversation's label names its target (rows come newest first)
1121
+ target: r.agent_id === null && r.external !== null
1122
+ ? {
1123
+ extension: r.external.extension,
1124
+ targetKey: r.external.targetKey,
1125
+ label: r.external.label,
1126
+ }
1127
+ : null,
979
1128
  latestAt: r.latest_at,
980
1129
  conversations: [],
981
1130
  more: false,
@@ -989,13 +1138,13 @@ let ConversationsService = class ConversationsService {
989
1138
  current.more = true;
990
1139
  }
991
1140
  const page = groups.slice(0, opts.limit);
992
- const next = groups.length > opts.limit ? (page.at(-1)?.agent.id ?? null) : null;
1141
+ const next = groups.length > opts.limit ? (page.at(-1)?.key ?? null) : null;
993
1142
  // The archived entry's count ignores `q` and `state`
994
1143
  const counted = await sql `
995
1144
  SELECT count(*) AS n FROM capybara.conversations c
996
- WHERE c.org_id = ${orgId} AND c.account_id = ${accountId} AND c.kind = 'chat'
1145
+ WHERE c.org_id = ${orgId} AND c.account_id = ${accountId}
997
1146
  AND c.deleted_at IS NULL AND c.archived_at IS NOT NULL
998
- AND c.agent_id IN ${visibleAgents}
1147
+ AND ${listed}
999
1148
  `.execute(this.db.db);
1000
1149
  return { groups: page, next, archivedCount: Number(counted.rows[0]?.n ?? 0) };
1001
1150
  }
@@ -1200,7 +1349,7 @@ let ConversationsService = class ConversationsService {
1200
1349
  input.skill !== undefined ||
1201
1350
  namesConnectors;
1202
1351
  const agent = needsAgent
1203
- ? (await this.agents.get(orgId, conv.agentId, accountId)).definition
1352
+ ? (await this.agents.get(orgId, agentIdOfView(conv), accountId)).definition
1204
1353
  : undefined;
1205
1354
  const extra = await this.resolveExtra(orgId, accountId, input, { ...conv, conversationId, signal }, agent !== undefined && namesConnectors
1206
1355
  ? {
@@ -1211,7 +1360,7 @@ let ConversationsService = class ConversationsService {
1211
1360
  : undefined);
1212
1361
  const invoked = agent === undefined
1213
1362
  ? undefined
1214
- : await this.prepareSkill(orgId, accountId, conv.agentId, { conversationId, deviceId: conv.deviceId }, agent, {
1363
+ : await this.prepareSkill(orgId, accountId, agentIdOfView(conv), { conversationId, deviceId: conv.deviceId }, agent, {
1215
1364
  ...(input.skill !== undefined && { skill: input.skill }),
1216
1365
  text: extra.text ?? input.text,
1217
1366
  });
@@ -1318,7 +1467,7 @@ let ConversationsService = class ConversationsService {
1318
1467
  async checkPick(orgId, conv, accountId, pick) {
1319
1468
  if (pick.model === undefined && pick.effort === undefined)
1320
1469
  return;
1321
- const agent = await this.agents.get(orgId, conv.agentId, accountId);
1470
+ const agent = await this.agents.get(orgId, agentIdOfView(conv), accountId);
1322
1471
  await this.planSwitch(orgId, agent.definition, conv.selection, pick);
1323
1472
  }
1324
1473
  /**
@@ -1471,8 +1620,8 @@ let ConversationsService = class ConversationsService {
1471
1620
  async prepareQueuedSkill(orgId, conv, accountId, input) {
1472
1621
  if (input.skill === undefined)
1473
1622
  return undefined;
1474
- const agent = await this.agents.get(orgId, conv.agentId, accountId);
1475
- return this.prepareSkill(orgId, accountId, conv.agentId, { conversationId: conv.id, deviceId: conv.deviceId }, agent.definition, input);
1623
+ const agent = await this.agents.get(orgId, agentIdOfView(conv), accountId);
1624
+ return this.prepareSkill(orgId, accountId, agentIdOfView(conv), { conversationId: conv.id, deviceId: conv.deviceId }, agent.definition, input);
1476
1625
  }
1477
1626
  /** Resolves what a message's tokens reference before it is written ({@link resolveTokens}). */
1478
1627
  async resolveExtra(orgId, accountId, input, target,
@@ -1648,7 +1797,8 @@ let ConversationsService = class ConversationsService {
1648
1797
  /**
1649
1798
  * {@link resolveExtra}'s referenced conversations (@ conversations spec §1), read as the sender
1650
1799
  * outside any transaction, once each in the body's order. Each must be the sender's own chat in
1651
- * this org, not deleted, its agent still visible ({@link readable} plus `kind = 'chat'`); any
1800
+ * this org, not deleted, its agent still visible ({@link readable} plus `kind = 'chat'`), or
1801
+ * their external conversation whose extension serves the org (local agents spec Part 2); any
1652
1802
  * other → `conversation.reference_unavailable` (`details: [{ id }]`, the same for every case);
1653
1803
  * one with no `user_message` yet → the same code with `reason: "empty"`; the conversation
1654
1804
  * being written in → `conversation.reference_self`.
@@ -1684,26 +1834,42 @@ let ConversationsService = class ConversationsService {
1684
1834
  async readConversationRef(orgId, accountId, id) {
1685
1835
  const row = await this.db
1686
1836
  .selectFrom("conversations")
1687
- .select(["id", "title", "agent_id", "updated_at"])
1837
+ .select(["id", "kind", "title", "agent_id", "external", "external_state", "updated_at"])
1688
1838
  .select(activitySql("conversations").as("activity"))
1689
1839
  .where("id", "=", id)
1690
1840
  .where("org_id", "=", orgId)
1691
1841
  .where("account_id", "=", accountId)
1692
1842
  .where("deleted_at", "is", null)
1693
1843
  // a sub-agent's or an eval replay conversation is never referenced
1694
- .where("kind", "=", "chat")
1844
+ .where("kind", "in", ["chat", "external"])
1695
1845
  .executeTakeFirst();
1696
1846
  if (!row)
1697
1847
  return "unavailable";
1848
+ const external = row.kind === "external";
1698
1849
  let agentName;
1699
- try {
1700
- agentName = (await this.agents.get(orgId, row.agent_id, accountId)).definition.name;
1701
- }
1702
- catch (e) {
1703
- if (e instanceof ApiError && e.code === "agent.not_found")
1850
+ if (external) {
1851
+ // an external conversation is named by its target (local agents spec Part 2, call 10a), and
1852
+ // referenced while its extension serves the org
1853
+ if (row.external === null ||
1854
+ !(await this.points.serves(orgId, TARGET_POINT, row.external.extension)))
1704
1855
  return "unavailable";
1705
- throw e;
1856
+ agentName = row.external.label;
1857
+ }
1858
+ else {
1859
+ try {
1860
+ agentName = (await this.agents.get(orgId, agentIdOf(row), accountId)).definition.name;
1861
+ }
1862
+ catch (e) {
1863
+ if (e instanceof ApiError && e.code === "agent.not_found")
1864
+ return "unavailable";
1865
+ throw e;
1866
+ }
1706
1867
  }
1868
+ // an external conversation's turns are its mirrored messages (no summaries: never compacted)
1869
+ const userType = external ? "external_user_message" : "user_message";
1870
+ const turnTypes = external
1871
+ ? ["external_user_message", "external_message"]
1872
+ : ["user_message", "assistant_message"];
1707
1873
  // the latest summary (conversation_events_compaction_summary_idx), then the newest messages
1708
1874
  // after what it covers
1709
1875
  // org-filter: conversation id was verified in orgId above
@@ -1721,9 +1887,11 @@ let ConversationsService = class ConversationsService {
1721
1887
  .selectFrom("conversation_events")
1722
1888
  .select(["seq", "type", sql `payload`.as("payload")])
1723
1889
  .where("conversation_id", "=", id)
1724
- .where("type", "in", ["user_message", "assistant_message"])
1890
+ .where("type", "in", turnTypes)
1725
1891
  // only messages with text count toward the cap (a run's tool-only steps carry none)
1726
- .where(sql `payload -> 'content' @> '[{"type":"text"}]'::jsonb`)
1892
+ .where(external
1893
+ ? sql `payload ->> 'text' <> ''`
1894
+ : sql `payload -> 'content' @> '[{"type":"text"}]'::jsonb`)
1727
1895
  .where("seq", ">", String(summaryPayload?.coversUpToSeq ?? 0))
1728
1896
  .orderBy("seq", "desc")
1729
1897
  .limit(REF_TURN_MESSAGES)
@@ -1731,13 +1899,13 @@ let ConversationsService = class ConversationsService {
1731
1899
  // nothing to quote: no summary and no message of the person yet (a long run's text replies may
1732
1900
  // fill the newest rows, and a files-only message has no text, so the log is asked when they
1733
1901
  // hold none)
1734
- if (summary === undefined && !rows.some((r) => r.type === "user_message")) {
1902
+ if (summary === undefined && !rows.some((r) => r.type === userType)) {
1735
1903
  // org-filter: conversation id was verified in orgId above
1736
1904
  const anyUser = await this.db
1737
1905
  .selectFrom("conversation_events")
1738
1906
  .select("seq")
1739
1907
  .where("conversation_id", "=", id)
1740
- .where("type", "=", "user_message")
1908
+ .where("type", "=", userType)
1741
1909
  .limit(1)
1742
1910
  .executeTakeFirst();
1743
1911
  if (anyUser === undefined)
@@ -1747,7 +1915,7 @@ let ConversationsService = class ConversationsService {
1747
1915
  .slice()
1748
1916
  .reverse()
1749
1917
  .map((r) => ({
1750
- role: r.type === "user_message" ? "user" : "assistant",
1918
+ role: r.type === userType ? "user" : "assistant",
1751
1919
  text: refMessageText(r.type, r.payload),
1752
1920
  }))
1753
1921
  .filter((m) => m.text !== "");
@@ -2031,6 +2199,8 @@ ConversationsService = __decorate([
2031
2199
  __param(17, Inject(TransactionHost)),
2032
2200
  __param(18, Inject(PermissionCeilingWrites)),
2033
2201
  __param(19, Inject(OutboxService)),
2034
- __param(20, Inject(MentionableConnectorsService))
2202
+ __param(20, Inject(MentionableConnectorsService)),
2203
+ __param(21, Inject(ExtensionPointDefaults)),
2204
+ __param(22, Inject(InboxItemsService))
2035
2205
  ], ConversationsService);
2036
2206
  export { ConversationsService };