@capybara-hq/kernel 0.1.0-rc.135 → 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 (92) hide show
  1. package/dist/admin/admin.module.js +3 -0
  2. package/dist/admin/health.service.d.ts +2 -2
  3. package/dist/admin/health.service.js +6 -2
  4. package/dist/catalog/marketplaces.service.d.ts +1 -1
  5. package/dist/conversations/access.d.ts +15 -7
  6. package/dist/conversations/access.js +59 -10
  7. package/dist/conversations/conversation-agent.d.ts +18 -0
  8. package/dist/conversations/conversation-agent.js +23 -0
  9. package/dist/conversations/conversation-ref.d.ts +3 -2
  10. package/dist/conversations/conversation-ref.js +6 -1
  11. package/dist/conversations/conversations.controller.d.ts +28 -5
  12. package/dist/conversations/conversations.controller.js +99 -10
  13. package/dist/conversations/conversations.module.js +10 -0
  14. package/dist/conversations/conversations.schemas.d.ts +6 -0
  15. package/dist/conversations/conversations.schemas.js +15 -0
  16. package/dist/conversations/conversations.service.d.ts +125 -21
  17. package/dist/conversations/conversations.service.js +260 -90
  18. package/dist/conversations/event-log.d.ts +9 -1
  19. package/dist/conversations/event-log.js +2 -0
  20. package/dist/conversations/events.d.ts +57 -0
  21. package/dist/conversations/events.js +73 -1
  22. package/dist/conversations/external/external-calls.d.ts +75 -0
  23. package/dist/conversations/external/external-calls.js +91 -0
  24. package/dist/conversations/external/external-calls.processor.d.ts +45 -0
  25. package/dist/conversations/external/external-calls.processor.js +144 -0
  26. package/dist/conversations/external/external-conversations.service.d.ts +266 -0
  27. package/dist/conversations/external/external-conversations.service.js +1138 -0
  28. package/dist/conversations/external/external.schemas.d.ts +63 -0
  29. package/dist/conversations/external/external.schemas.js +52 -0
  30. package/dist/conversations/external/token.d.ts +6 -0
  31. package/dist/conversations/external/token.js +6 -0
  32. package/dist/conversations/permission-profile-store.d.ts +4 -1
  33. package/dist/conversations/permission-profiles.controller.d.ts +33 -9
  34. package/dist/conversations/permission-profiles.controller.js +86 -6
  35. package/dist/conversations/prompt-suggestions.js +2 -1
  36. package/dist/conversations/queue.js +2 -1
  37. package/dist/conversations/titles.js +4 -3
  38. package/dist/ctx/create-ctx.d.ts +7 -0
  39. package/dist/ctx/create-ctx.js +45 -2
  40. package/dist/db/kernel-schema.d.ts +31 -4
  41. package/dist/device-access/host-services.js +3 -2
  42. package/dist/device-access/person-handles.d.ts +16 -7
  43. package/dist/device-access/person-handles.js +14 -9
  44. package/dist/devices/conversation-devices.d.ts +5 -0
  45. package/dist/devices/conversation-devices.js +16 -0
  46. package/dist/erasure/org-catalog.js +2 -2
  47. package/dist/errors.d.ts +34 -0
  48. package/dist/errors.js +34 -0
  49. package/dist/evals/snapshot.js +3 -1
  50. package/dist/evals/trajectory.service.d.ts +2 -2
  51. package/dist/evals/trajectory.service.js +11 -7
  52. package/dist/extensions/extensions.module.js +3 -0
  53. package/dist/extensions/host.d.ts +7 -0
  54. package/dist/extensions/host.js +11 -0
  55. package/dist/extensions/permission-view.d.ts +3 -1
  56. package/dist/extensions/permission-view.js +4 -1
  57. package/dist/extensions/point-defaults.d.ts +13 -21
  58. package/dist/extensions/point-defaults.js +32 -72
  59. package/dist/extensions/point-serving.d.ts +56 -0
  60. package/dist/extensions/point-serving.js +120 -0
  61. package/dist/inbox/inbox-items.service.d.ts +11 -0
  62. package/dist/inbox/inbox-items.service.js +39 -0
  63. package/dist/infra/outbox/registry.d.ts +70 -0
  64. package/dist/infra/outbox/registry.js +44 -0
  65. package/dist/infra/queue/queue-names.d.ts +1 -1
  66. package/dist/infra/queue/queue-names.js +1 -0
  67. package/dist/kernel.module.js +4 -0
  68. package/dist/platform/exclusions.js +10 -0
  69. package/dist/platform/ops/conversations.ops.d.ts +8 -1
  70. package/dist/platform/ops/conversations.ops.js +52 -14
  71. package/dist/plugin-reads/plugin-reads.service.js +4 -1
  72. package/dist/push/recipients.js +5 -2
  73. package/dist/retention/worker.js +2 -1
  74. package/dist/roles/worker-role.d.ts +3 -1
  75. package/dist/roles/worker-role.js +8 -2
  76. package/dist/roles/worker.module.js +3 -0
  77. package/dist/runtime/context/build.js +8 -0
  78. package/dist/runtime/context/compaction.js +7 -0
  79. package/dist/runtime/idle-arm.js +3 -1
  80. package/dist/runtime/idle-compaction.js +2 -1
  81. package/dist/runtime/run-finish.js +2 -1
  82. package/dist/runtime/run-jobs.js +2 -1
  83. package/dist/runtime/run-queue.js +4 -2
  84. package/dist/runtime/run-worker.js +5 -2
  85. package/dist/runtime/stream.js +10 -0
  86. package/dist/runtime/usage-report.js +2 -1
  87. package/dist/runtime/waits.js +2 -1
  88. package/dist/tools/approvals.service.js +6 -2
  89. package/dist/tools/builtins/skill-load.js +3 -2
  90. package/dist/tools/tool-watch.service.js +3 -1
  91. package/package.json +3 -3
  92. package/src/migrations/0227_external_conversations.sql +33 -0
@@ -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,
@@ -15,6 +15,7 @@ import { normalizeStoredDefinition } from "../agents/definition.js";
15
15
  import { GIT_GRANT_SPEC_HASH, gitGrantRefusal, gitPushGrantKey, grantRefusalOf, NETWORK_GRANT_PREFIX, NETWORK_GRANT_SPEC_HASH, networkGrantRefusal, normalizeGitRepo, } from "../automations/grant-rules.js";
16
16
  import { AutomationStore } from "../automations/store.js";
17
17
  import { unattendedRunOf, unattendedTaskRunOf } from "../automations/unattended.js";
18
+ import { agentIdOf } from "../conversations/conversation-agent.js";
18
19
  import { EventLog } from "../conversations/event-log.js";
19
20
  import { COMMAND_ASK_TEXT_MAX_CHARS, GIT_ASK_MAX_REFS, GIT_REF_MAX_CHARS, NETWORK_ASK_MAX_HOSTS, NETWORK_HOST_MAX_CHARS, SECURE_INPUT_MAX_FIELDS, } from "../conversations/events.js";
20
21
  import { ConversationLeakCheck } from "../conversations/leak-check.js";
@@ -1675,7 +1676,8 @@ let ApprovalsService = class ApprovalsService {
1675
1676
  .values({
1676
1677
  org_id: orgId,
1677
1678
  account_id: before.requestedFor,
1678
- agent_id: ctx.agent_id,
1679
+ // a run's conversation always has an agent (an external one has no runs)
1680
+ agent_id: agentIdOf(ctx),
1679
1681
  tool_key: before.toolKey,
1680
1682
  spec_hash: hash,
1681
1683
  connector_id: connectorId,
@@ -2432,7 +2434,9 @@ let ApprovalsService = class ApprovalsService {
2432
2434
  "conversations.parent_conversation_id",
2433
2435
  ])
2434
2436
  .where("runs.id", "in", [...new Set(recs.map((r) => r.runId))])
2435
- .execute();
2437
+ .execute()
2438
+ // a run's conversation always has an agent (an external one has no runs)
2439
+ .then((rows) => rows.map((r) => ({ ...r, agent_id: agentIdOf(r) })));
2436
2440
  const ctx = new Map(ctxRows.map((r) => [r.id, r]));
2437
2441
  // a sub-agent's approval links to the root conversation of its tree (agent map spec §7)
2438
2442
  const roots = new Map();
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { parseSkillMd, renderSkillBody, SKILL_ENTRY_FILE, SKILL_INVOCATION_LIMITS, SKILLS_SANDBOX_ROOT, skillDigest, skillInvocation, skillSandboxDir, skillSandboxPath, ToolError, validateSandboxPathShape, } from "@capybara-hq/plugin-sdk";
3
3
  import { sql } from "kysely";
4
4
  import { normalizeStoredDefinition } from "../../agents/definition.js";
5
+ import { agentIdOf } from "../../conversations/conversation-agent.js";
5
6
  import { ApiError } from "../../errors.js";
6
7
  import { callableProjectSkills, projectSkillName, projectSkillOf, } from "../../runtime/context/project-root.js";
7
8
  import { latestInvocation } from "../../runtime/context/skills.js";
@@ -292,7 +293,7 @@ async function runAgent(db, ctx) {
292
293
  .where("conversations.org_id", "=", ctx.orgId)
293
294
  .executeTakeFirst();
294
295
  return row
295
- ? { agentId: row.agent_id, definition: normalizeStoredDefinition(row.definition) }
296
+ ? { agentId: agentIdOf(row), definition: normalizeStoredDefinition(row.definition) }
296
297
  : undefined;
297
298
  }
298
299
  /**
@@ -323,7 +324,7 @@ async function invocationScope(db, ctx) {
323
324
  .executeTakeFirst();
324
325
  return row
325
326
  ? {
326
- agentId: row.agent_id,
327
+ agentId: agentIdOf(row),
327
328
  definition: normalizeStoredDefinition(row.definition),
328
329
  conversationId: dispatch.parentConversationId,
329
330
  }
@@ -11,6 +11,7 @@ import { parseToolKey } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable, Optional } from "@nestjs/common";
12
12
  import { DelayedError } from "bullmq";
13
13
  import { sql } from "kysely";
14
+ import { agentIdOf } from "../conversations/conversation-agent.js";
14
15
  import { EffectiveConfigs } from "../extensions/effective-config.js";
15
16
  import { isExtensionEnabled } from "../extensions/enabled.js";
16
17
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -151,7 +152,8 @@ let ToolWatchService = class ToolWatchService {
151
152
  ...extensionCallContext({
152
153
  orgId: row.org_id,
153
154
  accountId: row.trigger_account_id,
154
- agentId: row.agent_id,
155
+ // a question belongs to a run: its conversation has an agent (an external one has none)
156
+ agentId: agentIdOf(row),
155
157
  conversationId: row.conversation_id,
156
158
  rootConversationId,
157
159
  runId: row.run_id,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.135",
3
+ "version": "0.1.0-rc.136",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -70,7 +70,7 @@
70
70
  "yaml": "^2.9.1",
71
71
  "yauzl": "3.4.0",
72
72
  "zod": "^4.6.7",
73
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.99"
73
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.100"
74
74
  },
75
75
  "devDependencies": {
76
76
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",
@@ -82,7 +82,7 @@
82
82
  "@types/yauzl": "3.4.0",
83
83
  "pg-cursor": "^2.22.1",
84
84
  "ws": "^8.22.0",
85
- "@capybara-hq/testing": "0.1.0-rc.55"
85
+ "@capybara-hq/testing": "0.1.0-rc.56"
86
86
  },
87
87
  "scripts": {
88
88
  "build": "tsc -b"
@@ -0,0 +1,33 @@
1
+ -- External conversations (local agents spec 2026-12-01, Part 2): a conversation the person holds
2
+ -- with a `conversation-target@1` target (a local agent on their device). The kernel mirrors it and
3
+ -- never runs it, so it has no agent.
4
+ -- - kind gains 'external'; agent_id becomes nullable: null exactly for 'external', which names its
5
+ -- target in `external` ({ extension, targetKey, label }) instead (one CHECK).
6
+ -- - external_state: what the target last reported (running / waiting / idle / ended).
7
+ -- - external_delivered_seq: the highest `external_user_message.deliverySeq` handed to the target;
8
+ -- -1 (written only by the kernel) marks a conversation whose `start` was dropped after its retries.
9
+ -- Additive only: the new columns have a default or are nullable and the CHECKs admit every
10
+ -- existing row, so a running older version keeps working during a rolling upgrade (it never
11
+ -- writes 'external' and always writes an agent).
12
+ -- The widened kind CHECK is re-added NOT VALID: the old CHECK implies the new one, so existing
13
+ -- rows need no scan. The shape CHECK is new, so it is added NOT VALID and then validated: the scan
14
+ -- proves every existing row (all of them have an agent and no target) fits it.
15
+
16
+ -- capybara:allow-destructive the CHECK is re-added with one more allowed value in the same transaction
17
+ ALTER TABLE conversations DROP CONSTRAINT IF EXISTS conversations_kind_check;
18
+ ALTER TABLE conversations ADD CONSTRAINT conversations_kind_check
19
+ CHECK (kind IN ('chat', 'eval', 'subagent', 'external')) NOT VALID;
20
+
21
+ ALTER TABLE conversations ALTER COLUMN agent_id DROP NOT NULL;
22
+ ALTER TABLE conversations ADD COLUMN IF NOT EXISTS external jsonb;
23
+ ALTER TABLE conversations ADD COLUMN IF NOT EXISTS external_state text NOT NULL DEFAULT 'idle'
24
+ CONSTRAINT conversations_external_state_check
25
+ CHECK (external_state IN ('running', 'waiting', 'idle', 'ended'));
26
+ ALTER TABLE conversations ADD COLUMN IF NOT EXISTS external_delivered_seq bigint NOT NULL DEFAULT 0;
27
+
28
+ ALTER TABLE conversations DROP CONSTRAINT IF EXISTS conversations_external_shape;
29
+ ALTER TABLE conversations ADD CONSTRAINT conversations_external_shape CHECK (
30
+ kind = 'external' AND agent_id IS NULL AND external IS NOT NULL
31
+ OR kind <> 'external' AND agent_id IS NOT NULL AND external IS NULL
32
+ ) NOT VALID;
33
+ ALTER TABLE conversations VALIDATE CONSTRAINT conversations_external_shape;