@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
@@ -226,10 +226,9 @@ let KernelLifecycle = class KernelLifecycle {
226
226
  await sql `select 1`.execute(this.pool);
227
227
  this.checkpoint();
228
228
  if (cfg().db.rls === "enforce") {
229
- // never fails the start: enforcement is a backstop, and the operator decides
230
- const problem = await rlsEnforceProblem(this.pool);
229
+ const problem = await rlsEnforceProblem(this.pool, cfg().db.rlsOwnerRole);
231
230
  if (problem !== undefined) {
232
- this.log.error(`db.rls is enforce, but ${problem}: PostgreSQL filters nothing by the org scope there`);
231
+ throw new Error(`Cannot start with db.rls=enforce: ${problem}. Prepare separate database logins and run capybara migrate before enabling enforcement.`);
233
232
  }
234
233
  }
235
234
  // In flight for the stop: aborted when the shutdown begins, which then waits for its session to end
@@ -24,6 +24,16 @@ export const PLATFORM_EXCLUSIONS = [
24
24
  category: "human-only",
25
25
  reason: "Interactive owner session permission selection and device-bound consent",
26
26
  },
27
+ {
28
+ route: "GET /api/v1/orgs/:orgId/conversation-targets",
29
+ category: "human-only",
30
+ reason: "lists the person's local agents for the web new conversation page",
31
+ },
32
+ {
33
+ route: "POST /api/v1/orgs/:orgId/conversations/:id/external-requests/:requestId",
34
+ category: "human-only",
35
+ reason: "the person decides a local agent's request",
36
+ },
27
37
  {
28
38
  route: "POST /api/v1/admin/accounts/:accountId/erasure",
29
39
  category: "human-only",
@@ -1,6 +1,7 @@
1
1
  import { type OnModuleInit } from "@nestjs/common";
2
2
  import { ConversationsService } from "../../conversations/conversations.service.js";
3
3
  import { ConversationDeviceStatus } from "../../conversations/device-status.js";
4
+ import { ExternalConversationsService } from "../../conversations/external/external-conversations.service.js";
4
5
  import { ConversationFiles } from "../../conversations/files.js";
5
6
  import { KernelDb } from "../../infra/database/kernel-db.js";
6
7
  import { PlatformOperations } from "../registry.js";
@@ -16,7 +17,11 @@ export declare class ConversationsOperations implements OnModuleInit {
16
17
  private readonly files;
17
18
  private readonly device;
18
19
  private readonly kdb;
19
- constructor(registry: PlatformOperations, conversations: ConversationsService, files: ConversationFiles, device: ConversationDeviceStatus, kdb: KernelDb);
20
+ /** An external conversation's stop (local agents spec Part 2). */
21
+ private readonly external;
22
+ constructor(registry: PlatformOperations, conversations: ConversationsService, files: ConversationFiles, device: ConversationDeviceStatus, kdb: KernelDb,
23
+ /** An external conversation's stop (local agents spec Part 2). */
24
+ external: Pick<ExternalConversationsService, "find" | "stop">);
20
25
  /**
21
26
  * Whether `id` is the conversation this run belongs to: its ROOT (the Platform tool also runs in
22
27
  * sub-agents, whose own id is not the person's conversation). Stopping or deleting it would end
@@ -25,6 +30,8 @@ export declare class ConversationsOperations implements OnModuleInit {
25
30
  private isRunsRoot;
26
31
  private titleOf;
27
32
  private precheckWritable;
33
+ /** A change of the conversation itself (rename, archive, delete): external ones included. */
34
+ private precheckOwned;
28
35
  private setArchived;
29
36
  onModuleInit(): void;
30
37
  }
@@ -9,9 +9,10 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { z } from "zod";
12
- import { EventsQuery, FilesQuery, IdParams, ListQuery, PatchBody, SubagentsQuery, } from "../../conversations/conversations.schemas.js";
12
+ import { EventsQuery, FilesQuery, IdParams, ListQuery, PatchBody, SubagentsQuery, targetRefOf, } from "../../conversations/conversations.schemas.js";
13
13
  import { ConversationsService, } from "../../conversations/conversations.service.js";
14
14
  import { ConversationDeviceStatus } from "../../conversations/device-status.js";
15
+ import { ExternalConversationsService } from "../../conversations/external/external-conversations.service.js";
15
16
  import { ConversationFiles } from "../../conversations/files.js";
16
17
  import { KernelDb } from "../../infra/database/kernel-db.js";
17
18
  import { rootConversationOf } from "../../runtime/subagents/child.js";
@@ -23,13 +24,24 @@ const PAGE = 50;
23
24
  const ConversationId = IdParams.shape.id;
24
25
  const Id = z.object({ conversationId: ConversationId }).strict();
25
26
  const EVENTS_PAGE_MAX = 100;
26
- /** A list row: the compact form (`state` is what the run is doing, else archived or idle). */
27
+ /**
28
+ * A list row: the compact form (`state` is what the run is doing, else archived or idle; an
29
+ * external conversation has no agent and names its local agent in `target`).
30
+ */
27
31
  const row = (c) => ({
28
32
  id: c.id,
29
33
  name: c.title ?? "Untitled",
34
+ kind: c.kind,
30
35
  state: c.activity ?? (c.archivedAt === null ? "idle" : "archived"),
31
36
  agentId: c.agentId,
32
37
  agent: c.agent,
38
+ target: c.external === null
39
+ ? null
40
+ : {
41
+ extension: c.external.extension,
42
+ targetKey: c.external.targetKey,
43
+ label: c.external.label,
44
+ },
33
45
  updatedAt: c.updatedAt,
34
46
  });
35
47
  /**
@@ -44,12 +56,16 @@ let ConversationsOperations = class ConversationsOperations {
44
56
  files;
45
57
  device;
46
58
  kdb;
47
- constructor(registry, conversations, files, device, kdb) {
59
+ external;
60
+ constructor(registry, conversations, files, device, kdb,
61
+ /** An external conversation's stop (local agents spec Part 2). */
62
+ external) {
48
63
  this.registry = registry;
49
64
  this.conversations = conversations;
50
65
  this.files = files;
51
66
  this.device = device;
52
67
  this.kdb = kdb;
68
+ this.external = external;
53
69
  }
54
70
  /**
55
71
  * Whether `id` is the conversation this run belongs to: its ROOT (the Platform tool also runs in
@@ -66,6 +82,10 @@ let ConversationsOperations = class ConversationsOperations {
66
82
  precheckWritable(id, ctx) {
67
83
  return precheckBy(() => this.conversations.writable(ctx.orgId, id, ctx.actorAccountId));
68
84
  }
85
+ /** A change of the conversation itself (rename, archive, delete): external ones included. */
86
+ precheckOwned(id, ctx) {
87
+ return precheckBy(() => this.conversations.owned(ctx.orgId, id, ctx.actorAccountId));
88
+ }
69
89
  async setArchived(id, archived, ctx) {
70
90
  return {
71
91
  conversation: await this.conversations.setArchived(ctx.orgId, id, ctx.actorAccountId, archived),
@@ -75,12 +95,13 @@ let ConversationsOperations = class ConversationsOperations {
75
95
  this.registry.register([
76
96
  defineOperation({
77
97
  id: "conversations.list",
78
- description: "List your own conversations, most recently updated first: id, name, state (running, waiting, idle or archived), agent (id, name, profile; null when no longer visible) and update time. Pages by 50: pass the returned next as params.after; the first page (no after) also returns total, the count of all matches. Filter by title text q, by agentId, by state (running or waiting), or pass archived 1 for the archived ones.",
98
+ description: "List your own conversations, most recently updated first: id, name, kind (chat, or external: held with a local agent on your device, which has no agentId and names it in target), state (running, waiting, idle or archived), agentId and agent (id, name, profile; null when no longer visible), target (extension, targetKey, label; null for a chat) and update time. Pages by 50: pass the returned next as params.after; the first page (no after) also returns total, the count of all matches. Filter by title text q, by agentId, by target (extension/targetKey), by state (running or waiting), or pass archived 1 for the archived ones.",
79
99
  input: ListQuery.pick({
80
100
  q: true,
81
101
  state: true,
82
102
  archived: true,
83
103
  agentId: true,
104
+ target: true,
84
105
  after: true,
85
106
  }).strict(),
86
107
  example: { q: "report" },
@@ -95,6 +116,7 @@ let ConversationsOperations = class ConversationsOperations {
95
116
  total: input.after === undefined,
96
117
  ...(input.after !== undefined && { after: input.after }),
97
118
  ...(input.agentId !== undefined && { agentId: input.agentId }),
119
+ ...(input.target !== undefined && { target: targetRefOf(input.target) }),
98
120
  ...(input.q !== undefined && { q: input.q }),
99
121
  ...(input.state !== undefined && { state: input.state }),
100
122
  ...(input.archived !== undefined && { archived: true }),
@@ -188,7 +210,7 @@ let ConversationsOperations = class ConversationsOperations {
188
210
  },
189
211
  ],
190
212
  confirm: "personal",
191
- precheck: (i, ctx) => precheckBy(() => this.conversations.writable(ctx.orgId, i.conversationId, ctx.actorAccountId)),
213
+ precheck: (i, ctx) => this.precheckOwned(i.conversationId, ctx),
192
214
  summary: async (i, ctx) => {
193
215
  const old = await this.titleOf(ctx, i.conversationId);
194
216
  return {
@@ -221,7 +243,7 @@ let ConversationsOperations = class ConversationsOperations {
221
243
  },
222
244
  ],
223
245
  confirm: "personal",
224
- precheck: (i, ctx) => this.precheckWritable(i.conversationId, ctx),
246
+ precheck: (i, ctx) => this.precheckOwned(i.conversationId, ctx),
225
247
  summary: async (i, ctx) => {
226
248
  const t = await this.titleOf(ctx, i.conversationId);
227
249
  return { zh: `归档对话「${t}」`, en: `Archive conversation "${t}"` };
@@ -248,7 +270,7 @@ let ConversationsOperations = class ConversationsOperations {
248
270
  },
249
271
  ],
250
272
  confirm: "personal",
251
- precheck: (i, ctx) => this.precheckWritable(i.conversationId, ctx),
273
+ precheck: (i, ctx) => this.precheckOwned(i.conversationId, ctx),
252
274
  summary: async (i, ctx) => {
253
275
  const t = await this.titleOf(ctx, i.conversationId);
254
276
  return { zh: `取消归档对话「${t}」`, en: `Unarchive conversation "${t}"` };
@@ -372,7 +394,7 @@ let ConversationsOperations = class ConversationsOperations {
372
394
  }),
373
395
  defineOperation({
374
396
  id: "conversations.abort",
375
- description: "Stop the run that is active in one of your other conversations (its sub-agents stop with it; stopping a sub-agent's conversation stops it and those below it). Nothing happens if no run is active. The conversation you are working in cannot be stopped.",
397
+ description: "Stop the run that is active in one of your other conversations (its sub-agents stop with it; stopping a sub-agent's conversation stops it and those below it). Nothing happens if no run is active. For an external conversation (kind external) its local agent is asked to stop its current turn (runId null). The conversation you are working in cannot be stopped.",
376
398
  input: Id,
377
399
  example: { conversationId: "3f2b8a40-6c1d-4e0b-9a77-5d1e2c8b9f10" },
378
400
  authz: { orgAction: "agents.use" },
@@ -383,6 +405,10 @@ let ConversationsOperations = class ConversationsOperations {
383
405
  code: "conversation.not_found",
384
406
  next: "Check the id with conversations.list: only your own conversations can be read or changed.",
385
407
  },
408
+ {
409
+ code: "conversation.target_unavailable",
410
+ next: "The local agent of that conversation is not available in this organization now; ask the person to check its plugin.",
411
+ },
386
412
  {
387
413
  code: "run.not_active",
388
414
  next: "No run is active in that conversation: nothing to stop; check conversations.list for its state.",
@@ -411,10 +437,17 @@ let ConversationsOperations = class ConversationsOperations {
411
437
  en: `Stop the active run in conversation "${t}"`,
412
438
  };
413
439
  },
414
- run: async (input, ctx) => ({
415
- stopped: true,
416
- runId: await this.conversations.abort(ctx.orgId, input.conversationId, ctx.actorAccountId),
417
- }),
440
+ run: async (input, ctx) => {
441
+ // an external conversation has no runs: its local agent is asked to stop (owed)
442
+ if (await this.external.find(ctx.orgId, input.conversationId, ctx.actorAccountId)) {
443
+ await this.external.stop(ctx.orgId, input.conversationId, ctx.actorAccountId);
444
+ return { stopped: true, runId: null };
445
+ }
446
+ return {
447
+ stopped: true,
448
+ runId: await this.conversations.abort(ctx.orgId, input.conversationId, ctx.actorAccountId),
449
+ };
450
+ },
418
451
  }),
419
452
  defineOperation({
420
453
  id: "conversations.compact",
@@ -439,6 +472,10 @@ let ConversationsOperations = class ConversationsOperations {
439
472
  code: "conversation.read_only",
440
473
  next: "That is a sub-agent's conversation and is compacted by its own runs; compact the conversation it belongs to.",
441
474
  },
475
+ {
476
+ code: "conversation.external_read_only",
477
+ next: "That conversation is with a local agent and does not run here: Capybara does not compact it.",
478
+ },
442
479
  ],
443
480
  confirm: "personal",
444
481
  precheck: (i, ctx) => this.precheckWritable(i.conversationId, ctx),
@@ -483,7 +520,7 @@ let ConversationsOperations = class ConversationsOperations {
483
520
  message: "The conversation you are running in cannot be deleted from here.",
484
521
  };
485
522
  }
486
- return precheckBy(() => this.conversations.writable(ctx.orgId, i.conversationId, ctx.actorAccountId));
523
+ return this.precheckOwned(i.conversationId, ctx);
487
524
  },
488
525
  summary: async (i, ctx) => {
489
526
  const t = await this.titleOf(ctx, i.conversationId);
@@ -503,6 +540,7 @@ ConversationsOperations = __decorate([
503
540
  __param(1, Inject(ConversationsService)),
504
541
  __param(2, Inject(ConversationFiles)),
505
542
  __param(3, Inject(ConversationDeviceStatus)),
506
- __param(4, Inject(KernelDb))
543
+ __param(4, Inject(KernelDb)),
544
+ __param(5, Inject(ExternalConversationsService))
507
545
  ], ConversationsOperations);
508
546
  export { ConversationsOperations };
@@ -11,6 +11,7 @@ import { CONVERSATIONS_BY_SUBJECT_MAX, CtxReadError, PEOPLE_GET_MAX, PEOPLE_SEAR
11
11
  import { Inject, Injectable, Module } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import { AgentLookup, AgentLookupModule } from "../agents/agent-lookup.js";
14
+ import { agentIdOf } from "../conversations/conversation-agent.js";
14
15
  import { isExtensionEnabled } from "../extensions/enabled.js";
15
16
  import { avatarColumns, personAvatarUrl } from "../identity/account-avatar.js";
16
17
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -64,6 +65,8 @@ let PluginReadsService = class PluginReadsService {
64
65
  .select(["id", "title", "account_id", "agent_id", "updated_at"])
65
66
  .where("org_id", "=", orgId)
66
67
  .where("deleted_at", "is", null)
68
+ // an external conversation has no agent (and never a subject)
69
+ .where("kind", "<>", "external")
67
70
  .where(sql `subject->>'source'`, "=", plugin)
68
71
  .where(sql `subject->>'kind'`, "=", subject.kind)
69
72
  .where(sql `subject->>'id'`, "=", subject.id)
@@ -94,7 +97,7 @@ let PluginReadsService = class PluginReadsService {
94
97
  id: c.id,
95
98
  title: c.title,
96
99
  ownerAccountId: c.account_id,
97
- agentId: c.agent_id,
100
+ agentId: agentIdOf(c),
98
101
  state,
99
102
  lastActivityAt: c.updated_at.toISOString(),
100
103
  };
@@ -1,3 +1,4 @@
1
+ import { agentIdOf } from "../conversations/conversation-agent.js";
1
2
  import { resolveConversationOrg } from "../conversations/job-org.js";
2
3
  import { isExtensionEnabled } from "../extensions/enabled.js";
3
4
  import { asPlatform } from "../infra/database/org-scope.js";
@@ -89,8 +90,10 @@ async function resolveConversation(db, orgId, conversationId, seq) {
89
90
  .where("id", "=", conversationId)
90
91
  .where("org_id", "=", orgId)
91
92
  .executeTakeFirst();
92
- if (!conv || conv.kind === "eval" || conv.deleted_at !== null)
93
+ // an external conversation pushes nothing: its events are no push triggers and it has no agent
94
+ if (!conv || conv.kind === "eval" || conv.kind === "external" || conv.deleted_at !== null) {
93
95
  return null;
96
+ }
94
97
  // org-filter: conversationId was verified in orgId above
95
98
  const event = await db
96
99
  .selectFrom("conversation_events")
@@ -217,7 +220,7 @@ async function resolveConversation(db, orgId, conversationId, seq) {
217
220
  category: trigger.category,
218
221
  path,
219
222
  threadId: rootId,
220
- title: await agentName(db, orgId, rootRow.agent_id),
223
+ title: await agentName(db, orgId, agentIdOf(rootRow)),
221
224
  conversationTitle: rootRow.title,
222
225
  text: trigger.text,
223
226
  };
@@ -177,7 +177,8 @@ let RetentionWorker = class RetentionWorker {
177
177
  .select("id")
178
178
  .where("org_id", "=", orgId)
179
179
  .where("deleted_at", "is", null)
180
- .where("kind", "=", "chat")
180
+ // an external conversation expires as a chat does (local agents spec Part 2)
181
+ .where("kind", "in", ["chat", "external"])
181
182
  .where("parent_conversation_id", "is", null);
182
183
  if (work.cursor_id)
183
184
  candidates = candidates.where("id", ">", work.cursor_id);
@@ -2,6 +2,7 @@ import { PluginScopeSyncProcessor } from "../catalog/scope-sync-workers.js";
2
2
  import { TemplateConnectorsProcessor } from "../catalog/template-connectors.processor.js";
3
3
  import { ChannelsProcessor } from "../channels/channels.module.js";
4
4
  import { ChannelOutbound } from "../channels/outbound.js";
5
+ import { ExternalCallsProcessor } from "../conversations/external/external-calls.processor.js";
5
6
  import { PromptSuggestionQueue } from "../conversations/prompt-suggestions.js";
6
7
  import { TitleQueue } from "../conversations/titles.js";
7
8
  import { ServiceEventProcessor } from "../device-access/service-events.js";
@@ -51,13 +52,14 @@ export declare class WorkerRole {
51
52
  private readonly templateConnectorsProcessor;
52
53
  private readonly toolWatchProcessor;
53
54
  private readonly serviceEventProcessor;
55
+ private readonly externalCallsProcessor;
54
56
  /** The startup config (the roles). */
55
57
  private readonly config;
56
58
  /** The run worker was started: the runs phase drains it. */
57
59
  private runsStarted;
58
60
  /** The eval worker was started: the runs phase drains it. */
59
61
  private evalsStarted;
60
- constructor(config: KernelConfigService, log: KernelLogger, intervals: LockedIntervalScheduler, scheduledRuns: ScheduledRuns, runWorker: RunWorker, evalWorker: EvalWorker, usageReport: UsageReporter, titles: TitleQueue, suggestions: PromptSuggestionQueue, channelOutbound: ChannelOutbound, runsProcessor: RunsProcessor, subagentRunsProcessor: SubagentRunsProcessor, usageProcessor: UsageReportProcessor, titleProcessor: TitleProcessor, suggestionProcessor: PromptSuggestionProcessor, channelsProcessor: ChannelsProcessor, evalsProcessor: EvalsProcessor, maintenanceProcessor: MaintenanceProcessor, scopeProcessor: PluginScopeSyncProcessor, lifecycleProcessor: LifecycleHooksProcessor, pushProcessor: PushProcessor, connectorToolsProcessor: ConnectorToolsProcessor, templateConnectorsProcessor: TemplateConnectorsProcessor, toolWatchProcessor: ToolWatchProcessor, serviceEventProcessor: ServiceEventProcessor);
62
+ constructor(config: KernelConfigService, log: KernelLogger, intervals: LockedIntervalScheduler, scheduledRuns: ScheduledRuns, runWorker: RunWorker, evalWorker: EvalWorker, usageReport: UsageReporter, titles: TitleQueue, suggestions: PromptSuggestionQueue, channelOutbound: ChannelOutbound, runsProcessor: RunsProcessor, subagentRunsProcessor: SubagentRunsProcessor, usageProcessor: UsageReportProcessor, titleProcessor: TitleProcessor, suggestionProcessor: PromptSuggestionProcessor, channelsProcessor: ChannelsProcessor, evalsProcessor: EvalsProcessor, maintenanceProcessor: MaintenanceProcessor, scopeProcessor: PluginScopeSyncProcessor, lifecycleProcessor: LifecycleHooksProcessor, pushProcessor: PushProcessor, connectorToolsProcessor: ConnectorToolsProcessor, templateConnectorsProcessor: TemplateConnectorsProcessor, toolWatchProcessor: ToolWatchProcessor, serviceEventProcessor: ServiceEventProcessor, externalCallsProcessor: ExternalCallsProcessor);
61
63
  /**
62
64
  * Starts the queue consumers (after the extension load), then opens the schedules' start gate:
63
65
  * the cron and interval timers were armed at application bootstrap, but every tick before this
@@ -12,6 +12,7 @@ import { PluginScopeSyncProcessor } from "../catalog/scope-sync-workers.js";
12
12
  import { TemplateConnectorsProcessor } from "../catalog/template-connectors.processor.js";
13
13
  import { ChannelsProcessor } from "../channels/channels.module.js";
14
14
  import { ChannelOutbound } from "../channels/outbound.js";
15
+ import { ExternalCallsProcessor } from "../conversations/external/external-calls.processor.js";
15
16
  import { PromptSuggestionQueue } from "../conversations/prompt-suggestions.js";
16
17
  import { TitleQueue } from "../conversations/titles.js";
17
18
  import { ServiceEventProcessor } from "../device-access/service-events.js";
@@ -61,13 +62,14 @@ let WorkerRole = class WorkerRole {
61
62
  templateConnectorsProcessor;
62
63
  toolWatchProcessor;
63
64
  serviceEventProcessor;
65
+ externalCallsProcessor;
64
66
  /** The startup config (the roles). */
65
67
  config;
66
68
  /** The run worker was started: the runs phase drains it. */
67
69
  runsStarted = false;
68
70
  /** The eval worker was started: the runs phase drains it. */
69
71
  evalsStarted = false;
70
- constructor(config, log, intervals, scheduledRuns, runWorker, evalWorker, usageReport, titles, suggestions, channelOutbound, runsProcessor, subagentRunsProcessor, usageProcessor, titleProcessor, suggestionProcessor, channelsProcessor, evalsProcessor, maintenanceProcessor, scopeProcessor, lifecycleProcessor, pushProcessor, connectorToolsProcessor, templateConnectorsProcessor, toolWatchProcessor, serviceEventProcessor) {
72
+ constructor(config, log, intervals, scheduledRuns, runWorker, evalWorker, usageReport, titles, suggestions, channelOutbound, runsProcessor, subagentRunsProcessor, usageProcessor, titleProcessor, suggestionProcessor, channelsProcessor, evalsProcessor, maintenanceProcessor, scopeProcessor, lifecycleProcessor, pushProcessor, connectorToolsProcessor, templateConnectorsProcessor, toolWatchProcessor, serviceEventProcessor, externalCallsProcessor) {
71
73
  this.log = log;
72
74
  this.intervals = intervals;
73
75
  this.scheduledRuns = scheduledRuns;
@@ -92,6 +94,7 @@ let WorkerRole = class WorkerRole {
92
94
  this.templateConnectorsProcessor = templateConnectorsProcessor;
93
95
  this.toolWatchProcessor = toolWatchProcessor;
94
96
  this.serviceEventProcessor = serviceEventProcessor;
97
+ this.externalCallsProcessor = externalCallsProcessor;
95
98
  this.config = config.get();
96
99
  }
97
100
  /**
@@ -117,6 +120,7 @@ let WorkerRole = class WorkerRole {
117
120
  this.templateConnectorsProcessor.start();
118
121
  // device service events, after the extensions registered their handlers
119
122
  this.serviceEventProcessor.start();
123
+ this.externalCallsProcessor.start();
120
124
  this.channelOutbound.startWorker(this.channelsProcessor.worker);
121
125
  this.usageReport.startWorker(this.usageProcessor.worker);
122
126
  this.titles.startWorker(this.titleProcessor.worker);
@@ -160,6 +164,7 @@ let WorkerRole = class WorkerRole {
160
164
  this.toolWatchProcessor.close(),
161
165
  this.templateConnectorsProcessor.close(),
162
166
  this.serviceEventProcessor.close(),
167
+ this.externalCallsProcessor.close(),
163
168
  ]);
164
169
  }
165
170
  };
@@ -189,6 +194,7 @@ WorkerRole = __decorate([
189
194
  __param(21, Inject(ConnectorToolsProcessor)),
190
195
  __param(22, Inject(TemplateConnectorsProcessor)),
191
196
  __param(23, Inject(ToolWatchProcessor)),
192
- __param(24, Inject(ServiceEventProcessor))
197
+ __param(24, Inject(ServiceEventProcessor)),
198
+ __param(25, Inject(ExternalCallsProcessor))
193
199
  ], WorkerRole);
194
200
  export { WorkerRole };
@@ -21,6 +21,7 @@ import { ClientReportsCron } from "../client/client-reports.cron.js";
21
21
  import { AttachmentsModule } from "../conversations/attachments.module.js";
22
22
  import { AttachmentCleanupJob } from "../conversations/attachments.service.js";
23
23
  import { EventLogModule } from "../conversations/event-log.js";
24
+ import { ExternalCallWorkersModule } from "../conversations/external/external-calls.processor.js";
24
25
  import { PromptSuggestionsModule } from "../conversations/prompt-suggestions.js";
25
26
  import { TitlesModule } from "../conversations/titles.js";
26
27
  import { ExtensionEffectRelay } from "../ctx/durable-relay.js";
@@ -107,6 +108,8 @@ let WorkerModule = WorkerModule_1 = class WorkerModule {
107
108
  TemplateConnectorsWorkersModule,
108
109
  // device service event deliveries (`cap-device-service-events`) and their 5-minute sweep
109
110
  DeviceServiceEventWorkersModule,
111
+ // owed conversation target calls (`cap-external-calls`)
112
+ ExternalCallWorkersModule,
110
113
  // the domains the fixed-period jobs call
111
114
  RuntimeModule,
112
115
  RunJobsModule,
@@ -1088,6 +1088,14 @@ export function buildModelRequest(input) {
1088
1088
  // an automatic decision of a person's ask is display and audit only; the model sees the
1089
1089
  // call's tool result
1090
1090
  case "tool_ask_decided":
1091
+ // the mirror of an external conversation (local agents spec Part 2): such a conversation has
1092
+ // no runs, so no request is ever built from these
1093
+ case "external_user_message":
1094
+ case "external_message":
1095
+ case "external_activity":
1096
+ case "external_request":
1097
+ case "external_request_answered":
1098
+ case "external_turn":
1091
1099
  break;
1092
1100
  default: {
1093
1101
  const unrendered = e;
@@ -527,6 +527,13 @@ function transcriptLine(e, notes) {
527
527
  case "permission_reviewed":
528
528
  // an automatic decision of a person's ask is display and audit only
529
529
  case "tool_ask_decided":
530
+ // an external conversation's mirror: such a conversation has no runs and is never compacted
531
+ case "external_user_message":
532
+ case "external_message":
533
+ case "external_activity":
534
+ case "external_request":
535
+ case "external_request_answered":
536
+ case "external_turn":
530
537
  return null;
531
538
  default: {
532
539
  const unrendered = e;
@@ -8,6 +8,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
+ import { agentKindOf } from "../conversations/conversation-agent.js";
11
12
  import { AccountsService } from "../identity/accounts.js";
12
13
  import { COMPACTION_SETTINGS } from "../identity/settings.js";
13
14
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -119,7 +120,8 @@ let IdleArm = class IdleArm {
119
120
  }
120
121
  async decideOrSkip(runId, conv, outcome) {
121
122
  const t = this.kdb.db;
122
- const known = { conversationKind: conv.kind, outcome };
123
+ // a finished run makes it an agent conversation (an external one has no runs)
124
+ const known = { conversationKind: agentKindOf(conv.kind), outcome };
123
125
  const skip = (reason) => {
124
126
  this.log.debug("idle compaction not armed", {
125
127
  context: "IdleCompaction",
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { visibleTo } from "../agents/agent-lookup.js";
12
12
  import { normalizeStoredDefinition } from "../agents/definition.js";
13
+ import { agentIdOf } from "../conversations/conversation-agent.js";
13
14
  import { effectiveDefinition, readSelection, sameModel } from "../conversations/selection.js";
14
15
  import { AccountsService } from "../identity/accounts.js";
15
16
  import { COMPACTION_SETTINGS } from "../identity/settings.js";
@@ -258,7 +259,7 @@ let IdleCompactionJob = class IdleCompactionJob {
258
259
  const probe = await this.compactions.probeIdle({
259
260
  orgId,
260
261
  conversationId,
261
- agentId: conv.agent_id,
262
+ agentId: agentIdOf(conv),
262
263
  agent: definition,
263
264
  agentVersion: agent.current_version,
264
265
  source: conv.source,
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { sql } from "kysely";
12
12
  import { AutomationRunTracker } from "../automations/run-tracker.js";
13
+ import { agentIdOf } from "../conversations/conversation-agent.js";
13
14
  import { EventLog } from "../conversations/event-log.js";
14
15
  import { pauseQueueIn } from "../conversations/queue.js";
15
16
  import { oweRunLifecycleFor } from "../extensions/run-lifecycle-owe.js";
@@ -155,7 +156,7 @@ let RunFinish = class RunFinish {
155
156
  orgId: conv.org_id,
156
157
  conversationId: a.conversationId,
157
158
  runId: a.runId,
158
- agentId: conv.agent_id,
159
+ agentId: agentIdOf(conv),
159
160
  agentVersion: run.agent_version,
160
161
  accountId: run.trigger_account_id,
161
162
  subject: conv.subject,
@@ -11,6 +11,7 @@ import { getQueueToken } from "@nestjs/bullmq";
11
11
  import { Inject, Injectable, Module } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import { BG_WAKE_JOB, bgWakeJobId } from "../background/wake-rules.js";
14
+ import { agentIdOf } from "../conversations/conversation-agent.js";
14
15
  import { oweRunLifecycleFor } from "../extensions/run-lifecycle-owe.js";
15
16
  import { KernelDb } from "../infra/database/kernel-db.js";
16
17
  import { TransactionHost } from "../infra/database/transaction-host.js";
@@ -279,7 +280,7 @@ let RunResume = class RunResume {
279
280
  orgId: conv.org_id,
280
281
  conversationId: row.conversation_id,
281
282
  runId,
282
- agentId: conv.agent_id,
283
+ agentId: agentIdOf(conv),
283
284
  agentVersion: run.agent_version,
284
285
  accountId: run.trigger_account_id,
285
286
  subject: conv.subject,
@@ -14,6 +14,7 @@ import { visibleTo } from "../agents/agent-lookup.js";
14
14
  import { linkStartedRunIn } from "../automations/run-tracker.js";
15
15
  import { automationRunAt } from "../automations/unattended.js";
16
16
  import { wakeDecisionIn } from "../background/wake-rules.js";
17
+ import { agentIdOf } from "../conversations/conversation-agent.js";
17
18
  import { EventLog } from "../conversations/event-log.js";
18
19
  import { dispatchQueuedIn, pauseQueueWith } from "../conversations/queue.js";
19
20
  import { conversationTree } from "../conversations/tree.js";
@@ -334,7 +335,7 @@ let RunQueue = class RunQueue {
334
335
  // the org, or an owed outbox job); the conversation's own org is read under its row lock
335
336
  async ensureRunIn(conversationId, st) {
336
337
  const t = this.db;
337
- const conv = await t
338
+ const found = await t
338
339
  .selectFrom("conversations")
339
340
  .select([
340
341
  "consumed_seq",
@@ -351,8 +352,9 @@ let RunQueue = class RunQueue {
351
352
  .forUpdate()
352
353
  .executeTakeFirst();
353
354
  // 评测回放的隐藏对话:运行由评测 worker 在里面直接驱动(工具只回放记录),绝不为它起真实运行
354
- if (conv?.kind !== "chat" && conv?.kind !== "subagent")
355
+ if (found?.kind !== "chat" && found?.kind !== "subagent")
355
356
  return null;
357
+ const conv = { ...found, agent_id: agentIdOf(found) };
356
358
  // A deleted conversation starts no run, whatever is still unconsumed or queued
357
359
  if (!isLive(conv.deleted_at))
358
360
  return null;
@@ -11,6 +11,7 @@ import { Inject, Injectable, Optional } from "@nestjs/common";
11
11
  import { DelayedError } from "bullmq";
12
12
  import { sql } from "kysely";
13
13
  import { normalizeStoredDefinition } from "../agents/definition.js";
14
+ import { agentIdOf, agentKindOf, } from "../conversations/conversation-agent.js";
14
15
  import { EventLog } from "../conversations/event-log.js";
15
16
  import { isAbsorbable, } from "../conversations/events.js";
16
17
  import { resolveConversationOrg, resolveRunOrg } from "../conversations/job-org.js";
@@ -463,7 +464,7 @@ let RunWorker = class RunWorker {
463
464
  if (run.status === "waiting")
464
465
  return;
465
466
  await this.hooks?.afterRunRead?.(runId, conversationId);
466
- const conv = await this.db
467
+ const found = await this.db
467
468
  .selectFrom("conversations")
468
469
  .innerJoin("orgs", "orgs.id", "conversations.org_id")
469
470
  .select([
@@ -477,8 +478,10 @@ let RunWorker = class RunWorker {
477
478
  ])
478
479
  .where("conversations.id", "=", conversationId)
479
480
  .executeTakeFirst();
480
- if (!conv)
481
+ if (!found)
481
482
  return;
483
+ // the run makes it an agent conversation (an external one has no runs)
484
+ const conv = { ...found, agent_id: agentIdOf(found), kind: agentKindOf(found.kind) };
482
485
  // 会话锁 TTL 与任务锁一致:持有者崩溃后,任务被判定 stalled 时会话锁也差不多同时过期。
483
486
  const lease = await this.lock.acquire(conversationId, runId, this.hooks?.lockTtlMs ?? this.config.get().runtime.jobLockMs);
484
487
  if (!lease)
@@ -72,6 +72,10 @@ function isBusMessage(m) {
72
72
  typeof x.afterSeq === "number" &&
73
73
  Number.isInteger(x.afterSeq));
74
74
  }
75
+ if (k === "external_delta") {
76
+ const x = m;
77
+ return typeof x.messageId === "string" && typeof x.text === "string";
78
+ }
75
79
  return k === "delta" && typeof m.runId === "string";
76
80
  }
77
81
  const eventFrame = (e) => `id: ${e.seq}\nevent: event\ndata: ${JSON.stringify(e)}\n\n`;
@@ -297,6 +301,12 @@ class Connection {
297
301
  this.enqueue(() => this.write(frame));
298
302
  return;
299
303
  }
304
+ if (m.kind === "external_delta") {
305
+ // an external conversation's partial message (local agents spec Part 2): a hint, not stored
306
+ const frame = `event: external_draft\ndata: ${JSON.stringify({ messageId: m.messageId, text: m.text })}\n\n`;
307
+ this.enqueue(() => this.write(frame));
308
+ return;
309
+ }
300
310
  if (m.kind === PROMPT_SUGGESTION_BUS_KIND) {
301
311
  // a new prompt suggestion for this conversation: display-only, never in the log
302
312
  // (the switch is checked by the job at write time; a frame racing a switch-off is harmless)
@@ -371,7 +371,8 @@ let UsageReporter = class UsageReporter {
371
371
  purpose: p.purpose ?? "step",
372
372
  orgId: row.org_id,
373
373
  accountId: row.trigger_account_id ?? row.account_id,
374
- agentId: row.agent_id,
374
+ // an external conversation has no agent (and records no usage: it never calls a model)
375
+ ...(row.agent_id !== null && { agentId: row.agent_id }),
375
376
  conversationId,
376
377
  // a sub-agent's calls report "chat" (spec §11: the SDK union is not widened)
377
378
  conversationKind: row.kind === "eval" ? "eval" : "chat",
@@ -11,6 +11,7 @@ import { Inject, Injectable } from "@nestjs/common";
11
11
  import { DelayedError } from "bullmq";
12
12
  import { sql } from "kysely";
13
13
  import { BackgroundTaskStopper } from "../background/stop.js";
14
+ import { agentIdOf } from "../conversations/conversation-agent.js";
14
15
  import { EventLog } from "../conversations/event-log.js";
15
16
  import { conversationTree } from "../conversations/tree.js";
16
17
  import { oweRunLifecycleFor } from "../extensions/run-lifecycle-owe.js";
@@ -191,7 +192,7 @@ let Waits = class Waits {
191
192
  orgId: row.org_id,
192
193
  conversationId: row.conversation_id,
193
194
  runId,
194
- agentId: row.agent_id,
195
+ agentId: agentIdOf(row),
195
196
  agentVersion: row.agent_version,
196
197
  accountId: row.trigger_account_id,
197
198
  subject: row.subject,