@capybara-hq/kernel 0.1.0-rc.22 → 0.1.0-rc.24

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 (234) hide show
  1. package/bootstrap.json +25 -25
  2. package/dist/admin/admin.controller.d.ts +3 -3
  3. package/dist/admin/admin.controller.js +6 -2
  4. package/dist/admin/admin.module.d.ts +2 -1
  5. package/dist/admin/admin.module.js +7 -3
  6. package/dist/admin/admin.schemas.d.ts +13 -0
  7. package/dist/admin/outbox-dead.controller.d.ts +23 -0
  8. package/dist/admin/outbox-dead.controller.js +62 -0
  9. package/dist/admin/outbox-dead.schemas.d.ts +8 -0
  10. package/dist/admin/outbox-dead.schemas.js +18 -0
  11. package/dist/admin/outbox-dead.service.d.ts +66 -0
  12. package/dist/admin/outbox-dead.service.js +179 -0
  13. package/dist/admin/overview.service.d.ts +40 -5
  14. package/dist/admin/overview.service.js +41 -7
  15. package/dist/agents/from-template.js +1 -1
  16. package/dist/background/finish.d.ts +5 -2
  17. package/dist/background/finish.js +14 -3
  18. package/dist/background/launch.d.ts +44 -5
  19. package/dist/background/launch.js +92 -9
  20. package/dist/background/session.d.ts +14 -2
  21. package/dist/background/session.js +26 -4
  22. package/dist/background/status.d.ts +1 -1
  23. package/dist/background/status.js +3 -3
  24. package/dist/background/stop.d.ts +0 -2
  25. package/dist/background/stop.js +1 -21
  26. package/dist/background/store.d.ts +8 -0
  27. package/dist/background/store.js +24 -0
  28. package/dist/catalog/admin-catalog.controller.d.ts +21 -2
  29. package/dist/catalog/admin-catalog.controller.js +45 -6
  30. package/dist/catalog/admin-catalog.schemas.d.ts +5 -0
  31. package/dist/catalog/admin-catalog.schemas.js +8 -0
  32. package/dist/catalog/catalog-content.d.ts +5 -0
  33. package/dist/catalog/catalog-content.js +1 -0
  34. package/dist/catalog/catalog.module.d.ts +2 -1
  35. package/dist/catalog/catalog.module.js +5 -1
  36. package/dist/catalog/marketplaces.service.d.ts +1 -1
  37. package/dist/catalog/platform-import-update.d.ts +50 -0
  38. package/dist/catalog/platform-import-update.js +116 -0
  39. package/dist/catalog/plugin-import.d.ts +36 -1
  40. package/dist/catalog/plugin-import.js +23 -1
  41. package/dist/catalog/plugin-upgrade.d.ts +18 -0
  42. package/dist/catalog/plugin-upgrade.js +19 -0
  43. package/dist/catalog/requests.service.js +2 -2
  44. package/dist/channels/channels.module.d.ts +5 -2
  45. package/dist/channels/channels.module.js +9 -2
  46. package/dist/channels/deliver-job.d.ts +25 -0
  47. package/dist/channels/deliver-job.js +25 -0
  48. package/dist/channels/inbound.d.ts +1 -1
  49. package/dist/channels/inbound.js +2 -15
  50. package/dist/channels/jobs.d.ts +28 -18
  51. package/dist/channels/jobs.js +63 -26
  52. package/dist/config/schema.d.ts +3 -6
  53. package/dist/config/schema.js +20 -27
  54. package/dist/conversations/agent-tree.d.ts +16 -0
  55. package/dist/conversations/agent-tree.js +36 -0
  56. package/dist/conversations/conversations.service.d.ts +44 -14
  57. package/dist/conversations/conversations.service.js +52 -38
  58. package/dist/conversations/event-log.d.ts +7 -10
  59. package/dist/conversations/event-log.js +24 -15
  60. package/dist/conversations/events.js +2 -1
  61. package/dist/conversations/queue.service.d.ts +8 -3
  62. package/dist/conversations/queue.service.js +37 -13
  63. package/dist/conversations/titles.d.ts +21 -8
  64. package/dist/conversations/titles.js +42 -15
  65. package/dist/db/kernel-schema.d.ts +26 -8
  66. package/dist/devices/devices.service.d.ts +12 -3
  67. package/dist/devices/devices.service.js +30 -9
  68. package/dist/errors.d.ts +15 -0
  69. package/dist/errors.js +15 -0
  70. package/dist/evals/run-replay.js +14 -8
  71. package/dist/extensions/extensions.module.js +3 -0
  72. package/dist/extensions/lifecycle.d.ts +6 -1
  73. package/dist/extensions/lifecycle.js +9 -2
  74. package/dist/extensions/usage-subscribers.d.ts +43 -0
  75. package/dist/extensions/usage-subscribers.js +108 -0
  76. package/dist/http/api.module.js +2 -0
  77. package/dist/identity/settings.d.ts +53 -3
  78. package/dist/identity/settings.js +92 -9
  79. package/dist/index.d.ts +1 -0
  80. package/dist/index.js +1 -0
  81. package/dist/infra/cli/kernel-cli.module.js +5 -0
  82. package/dist/infra/config/kernel-config.service.d.ts +7 -0
  83. package/dist/infra/config/kernel-config.service.js +20 -0
  84. package/dist/infra/events/kernel-events.d.ts +9 -35
  85. package/dist/infra/outbox/outbox-relay.module.d.ts +6 -0
  86. package/dist/infra/outbox/outbox-relay.module.js +18 -0
  87. package/dist/infra/outbox/outbox.dispatcher.d.ts +103 -0
  88. package/dist/infra/outbox/outbox.dispatcher.js +310 -0
  89. package/dist/infra/outbox/outbox.module.d.ts +24 -0
  90. package/dist/infra/outbox/outbox.module.js +50 -0
  91. package/dist/infra/outbox/outbox.relay.d.ts +31 -0
  92. package/dist/infra/outbox/outbox.relay.js +76 -0
  93. package/dist/infra/outbox/outbox.service.d.ts +51 -0
  94. package/dist/infra/outbox/outbox.service.js +131 -0
  95. package/dist/infra/outbox/registry.d.ts +120 -0
  96. package/dist/infra/outbox/registry.js +108 -0
  97. package/dist/infra/queue/queue-names.d.ts +8 -0
  98. package/dist/infra/queue/queue-names.js +16 -0
  99. package/dist/kernel.module.js +3 -0
  100. package/dist/local-devices/device-policy.service.d.ts +4 -0
  101. package/dist/local-devices/device-policy.service.js +61 -3
  102. package/dist/local-devices/local-device-gateway.d.ts +4 -2
  103. package/dist/local-devices/local-device-gateway.js +39 -14
  104. package/dist/local-devices/machines.d.ts +25 -1
  105. package/dist/local-devices/machines.js +91 -15
  106. package/dist/local-devices/policy-summary.d.ts +44 -1
  107. package/dist/local-devices/policy-summary.js +69 -0
  108. package/dist/models/embeddings.d.ts +9 -9
  109. package/dist/models/embeddings.js +11 -18
  110. package/dist/models/models.module.js +3 -0
  111. package/dist/orgs/orgs.service.js +7 -0
  112. package/dist/orgs/settings.controller.js +2 -2
  113. package/dist/orgs/settings.service.d.ts +11 -5
  114. package/dist/orgs/settings.service.js +28 -14
  115. package/dist/overrides.d.ts +20 -3
  116. package/dist/overrides.js +10 -2
  117. package/dist/platform/exclusions.js +5 -0
  118. package/dist/platform/ops/admin.ops.js +50 -9
  119. package/dist/platform/ops/catalog-admin.ops.d.ts +3 -1
  120. package/dist/platform/ops/catalog-admin.ops.js +32 -4
  121. package/dist/platform/ops/org-settings.ops.js +3 -3
  122. package/dist/platform/ops/orgs.ops.js +1 -0
  123. package/dist/platform/ops/outbox.ops.d.ts +21 -0
  124. package/dist/platform/ops/outbox.ops.js +125 -0
  125. package/dist/platform/ops/platform.ops.js +1 -1
  126. package/dist/platform/ops/schedules.ops.js +40 -1
  127. package/dist/platform/platform-ops.module.d.ts +2 -1
  128. package/dist/platform/platform-ops.module.js +3 -0
  129. package/dist/platform/route-schemas.js +3 -0
  130. package/dist/roles/worker.module.js +9 -4
  131. package/dist/runtime/langgraph-loop.js +13 -5
  132. package/dist/runtime/limits.d.ts +15 -0
  133. package/dist/runtime/limits.js +25 -0
  134. package/dist/runtime/loop.d.ts +8 -3
  135. package/dist/runtime/loop.js +2 -1
  136. package/dist/runtime/maintenance.d.ts +4 -2
  137. package/dist/runtime/maintenance.js +17 -2
  138. package/dist/runtime/model-call.d.ts +14 -16
  139. package/dist/runtime/model-call.js +14 -24
  140. package/dist/runtime/queue-lost-jobs.d.ts +24 -0
  141. package/dist/runtime/queue-lost-jobs.js +51 -0
  142. package/dist/runtime/run-control.d.ts +42 -5
  143. package/dist/runtime/run-control.js +66 -12
  144. package/dist/runtime/run-finish.d.ts +39 -12
  145. package/dist/runtime/run-finish.js +97 -14
  146. package/dist/runtime/run-jobs.d.ts +95 -13
  147. package/dist/runtime/run-jobs.js +199 -28
  148. package/dist/runtime/run-orphan-check.job.d.ts +142 -0
  149. package/dist/runtime/run-orphan-check.job.js +339 -0
  150. package/dist/runtime/run-processors.d.ts +16 -9
  151. package/dist/runtime/run-processors.js +1 -1
  152. package/dist/runtime/run-queue.d.ts +64 -55
  153. package/dist/runtime/run-queue.js +147 -284
  154. package/dist/runtime/run-steps.d.ts +1 -2
  155. package/dist/runtime/run-steps.js +8 -11
  156. package/dist/runtime/run-worker.d.ts +6 -17
  157. package/dist/runtime/run-worker.js +32 -34
  158. package/dist/runtime/runtime.module.d.ts +2 -3
  159. package/dist/runtime/runtime.module.js +5 -6
  160. package/dist/runtime/step-log.d.ts +16 -4
  161. package/dist/runtime/step-log.js +26 -6
  162. package/dist/runtime/stream.controller.d.ts +2 -4
  163. package/dist/runtime/stream.controller.js +5 -11
  164. package/dist/runtime/subagents/child.js +1 -1
  165. package/dist/runtime/subagents/definition.d.ts +2 -1
  166. package/dist/runtime/subagents/definition.js +4 -2
  167. package/dist/runtime/subagents/deliveries.d.ts +6 -3
  168. package/dist/runtime/subagents/deliveries.js +16 -7
  169. package/dist/runtime/subagents/dispatch.d.ts +12 -12
  170. package/dist/runtime/subagents/dispatch.js +13 -38
  171. package/dist/runtime/subagents/messages.d.ts +5 -1
  172. package/dist/runtime/subagents/messages.js +11 -3
  173. package/dist/runtime/subagents/skill-fork.d.ts +3 -3
  174. package/dist/runtime/subagents/skill-fork.js +5 -5
  175. package/dist/runtime/subagents/subagents.service.js +1 -1
  176. package/dist/runtime/subagents/tree-jobs.d.ts +61 -0
  177. package/dist/runtime/subagents/tree-jobs.js +86 -0
  178. package/dist/runtime/usage-report-jobs.d.ts +23 -48
  179. package/dist/runtime/usage-report-jobs.js +67 -119
  180. package/dist/runtime/usage-report.d.ts +28 -77
  181. package/dist/runtime/usage-report.js +35 -213
  182. package/dist/runtime/waits.d.ts +48 -198
  183. package/dist/runtime/waits.js +103 -805
  184. package/dist/sandbox/platform-tiers.d.ts +86 -0
  185. package/dist/sandbox/platform-tiers.js +97 -0
  186. package/dist/sandbox/sandbox.service.d.ts +18 -5
  187. package/dist/sandbox/sandbox.service.js +75 -20
  188. package/dist/sandbox/tiers.d.ts +14 -2
  189. package/dist/sandbox/tiers.js +8 -0
  190. package/dist/schedules/calendar.d.ts +134 -0
  191. package/dist/schedules/calendar.js +410 -0
  192. package/dist/schedules/fire.d.ts +1 -3
  193. package/dist/schedules/fire.js +5 -10
  194. package/dist/schedules/run-tracker.d.ts +0 -5
  195. package/dist/schedules/run-tracker.js +0 -13
  196. package/dist/schedules/scan.job.js +15 -20
  197. package/dist/schedules/schedule-math.d.ts +42 -0
  198. package/dist/schedules/schedule-math.js +52 -0
  199. package/dist/schedules/scheduled-tasks.service.d.ts +16 -0
  200. package/dist/schedules/scheduled-tasks.service.js +53 -0
  201. package/dist/schedules/schedules.controller.d.ts +5 -1
  202. package/dist/schedules/schedules.controller.js +15 -1
  203. package/dist/schedules/schedules.schemas.d.ts +35 -0
  204. package/dist/schedules/schedules.schemas.js +27 -0
  205. package/dist/schedules/store.d.ts +5 -0
  206. package/dist/schedules/store.js +20 -0
  207. package/dist/tools/approvals.service.d.ts +26 -7
  208. package/dist/tools/approvals.service.js +88 -10
  209. package/dist/tools/builtin-names.d.ts +5 -3
  210. package/dist/tools/builtin-names.js +12 -4
  211. package/dist/tools/builtins/builtin-tools.d.ts +1 -2
  212. package/dist/tools/builtins/builtin-tools.js +21 -17
  213. package/dist/tools/builtins/sandbox/bash.js +9 -3
  214. package/dist/tools/builtins/sandbox/common.d.ts +18 -1
  215. package/dist/tools/builtins/sandbox/common.js +14 -1
  216. package/dist/tools/builtins/sandbox/index.d.ts +2 -1
  217. package/dist/tools/builtins/sandbox/index.js +4 -1
  218. package/dist/tools/builtins/sandbox/task-list.d.ts +12 -0
  219. package/dist/tools/builtins/sandbox/task-list.js +130 -0
  220. package/dist/tools/builtins/sandbox/task-output.d.ts +8 -1
  221. package/dist/tools/builtins/sandbox/task-output.js +21 -3
  222. package/dist/tools/builtins/web/extract.d.ts +2 -4
  223. package/dist/tools/builtins/web/extract.js +2 -5
  224. package/dist/tools/pipeline.d.ts +1 -1
  225. package/dist/tools/pipeline.js +1 -1
  226. package/dist/tools/questions.service.d.ts +15 -6
  227. package/dist/tools/questions.service.js +20 -8
  228. package/dist/tools/registry.d.ts +4 -2
  229. package/dist/tools/registry.js +4 -3
  230. package/dist/tools/tools.module.js +4 -3
  231. package/package.json +3 -3
  232. package/src/migrations/0118_device_policy_ops.sql +6 -0
  233. package/src/migrations/0119_outbox.sql +22 -0
  234. package/src/migrations/0120_drop_usage_report_sweep.sql +7 -0
@@ -610,6 +610,8 @@ let PluginImport = class PluginImport {
610
610
  * whether the item exists (a new version of the org's own plugin) or the version is imported
611
611
  * already (F4), and the target as the platform updater reads it: the staged manifest and files,
612
612
  * or the imported version's for a retry. Another org's staging -> 404 `plugin.staging_not_found`.
613
+ * Without `owner`: a platform staging, and `existing` means a live platform-owned item (the
614
+ * platform's import and update, `PlatformImportUpdate`).
613
615
  */
614
616
  async stagedTarget(stagingId, owner) {
615
617
  if (!UUID_RE.test(stagingId))
@@ -630,7 +632,7 @@ let PluginImport = class PluginImport {
630
632
  .select(["id", "awaiting_confirmation"])
631
633
  .where("id", "=", staged.itemId)
632
634
  .where("deleted_at", "is", null)
633
- .where("owner_org_id", "=", owner.orgId)
635
+ .where((eb) => owner === undefined ? eb("owner_org_id", "is", null) : eb("owner_org_id", "=", owner.orgId))
634
636
  .executeTakeFirst();
635
637
  const imported = staged.retry === true
636
638
  ? await this.db
@@ -753,6 +755,19 @@ let PluginImport = class PluginImport {
753
755
  // update. After the commit: it copies files in object storage
754
756
  if (committed.firstVersion)
755
757
  await this.syncPlatform(committed.itemId, staged.version);
758
+ if (input.deploy === false) {
759
+ return {
760
+ item: await this.itemView(committed.itemId),
761
+ created: committed.created,
762
+ deploy: null,
763
+ pending: false,
764
+ firstVersion: committed.firstVersion,
765
+ ...(now &&
766
+ committed.previous !== undefined && {
767
+ approval: { review, extension: now, previous: committed.previous },
768
+ }),
769
+ };
770
+ }
756
771
  const deploy = now && now.action !== "keep"
757
772
  ? await this.deploy(actor, review, committed.itemId, now, committed.previous, opts, input.enable ?? true)
758
773
  : null;
@@ -1184,6 +1199,13 @@ let PluginImport = class PluginImport {
1184
1199
  return { ...base, result: "failed", ...failure(e) };
1185
1200
  }
1186
1201
  }
1202
+ /**
1203
+ * Puts back the approval a confirm with `deploy: false` wrote, after the step that was to deploy
1204
+ * the extension failed (see {@link restoreSnapshot}; false when someone changed it meanwhile).
1205
+ */
1206
+ async restoreApproval(actor, held, opts = {}) {
1207
+ return this.restoreSnapshot(actor, held.review, held.extension, held.previous, opts);
1208
+ }
1187
1209
  /**
1188
1210
  * Restores the snapshot overwritten at confirm (deletes it when there was none before), audits
1189
1211
  * `extension.permissions_restored`. Compare-and-write (row locked): restores only while the
@@ -230,6 +230,13 @@ export declare class PlatformPluginUpdater {
230
230
  private get db();
231
231
  /** The update preview (see the class comment); writes nothing. */
232
232
  preview(itemId: string, version: string): Promise<PlatformUpdatePreview>;
233
+ /**
234
+ * The update preview of a version staged for import, not imported yet (the platform's import and
235
+ * update, `PlatformImportUpdate`): the same diff as {@link preview}, with the target read from the
236
+ * staging (`target`, whose files are where the import's version row will point), so the
237
+ * `diffHash` is the one {@link updateHeld} recomputes after the import. Writes nothing.
238
+ */
239
+ previewStaged(itemId: string, version: string, target: UpdateTarget): Promise<PlatformUpdatePreview>;
233
240
  /** The preview of a diff with the template guides it changes. */
234
241
  private withGuideChanges;
235
242
  /**
@@ -292,6 +299,17 @@ export declare class PlatformPluginUpdater {
292
299
  * upload runs every step under it (ruling P3-35).
293
300
  */
294
301
  withItemLock<T>(itemId: string, f: () => Promise<T>): Promise<T>;
302
+ /**
303
+ * {@link update} for a caller already holding the item's update lock ({@link withItemLock}):
304
+ * the platform's import and update runs its import and this update under one hold.
305
+ */
306
+ updateHeld(actor: string, itemId: string, input: {
307
+ version: string;
308
+ diffHash: string;
309
+ }, opts?: {
310
+ actorTokenId?: string;
311
+ auditDetail?: Record<string, unknown>;
312
+ }): Promise<PlatformUpdateResult>;
295
313
  /**
296
314
  * Runs an update confirmed with the preview's `diffHash` (see the class comment). A version an
297
315
  * org upload waits with, or an item whose first version waits, -> 409 `catalog.item_pending`
@@ -176,6 +176,18 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
176
176
  async preview(itemId, version) {
177
177
  return this.withGuideChanges(await this.diff(itemId, version));
178
178
  }
179
+ /**
180
+ * The update preview of a version staged for import, not imported yet (the platform's import and
181
+ * update, `PlatformImportUpdate`): the same diff as {@link preview}, with the target read from the
182
+ * staging (`target`, whose files are where the import's version row will point), so the
183
+ * `diffHash` is the one {@link updateHeld} recomputes after the import. Writes nothing.
184
+ */
185
+ async previewStaged(itemId, version, target) {
186
+ if (target.version !== version) {
187
+ throw new Error(`internal: previewStaged got the staged target of version ${target.version} for version ${version}`);
188
+ }
189
+ return this.withGuideChanges(await this.diff(itemId, version, { target }));
190
+ }
179
191
  /** The preview of a diff with the template guides it changes. */
180
192
  async withGuideChanges(d) {
181
193
  return {
@@ -335,6 +347,13 @@ let PlatformPluginUpdater = class PlatformPluginUpdater {
335
347
  throw itemNotFound();
336
348
  return this.locked(itemId, f);
337
349
  }
350
+ /**
351
+ * {@link update} for a caller already holding the item's update lock ({@link withItemLock}):
352
+ * the platform's import and update runs its import and this update under one hold.
353
+ */
354
+ async updateHeld(actor, itemId, input, opts = {}) {
355
+ return this.updateLocked(actor, itemId, input, opts);
356
+ }
338
357
  /**
339
358
  * Runs an update confirmed with the preview's `diffHash` (see the class comment). A version an
340
359
  * org upload waits with, or an item whose first version waits, -> 409 `catalog.item_pending`
@@ -201,7 +201,7 @@ let CatalogRequestsService = class CatalogRequestsService {
201
201
  const t = this.db;
202
202
  await this.orgLock.lockAndAuthorize(orgId, actor, "catalog.request");
203
203
  const hosts = [...new Set(input.hosts.map((h) => h.toLowerCase()))].sort();
204
- const deployment = this.orgSettings.deployment().sandboxEgress;
204
+ const deployment = (await this.orgSettings.deployment()).sandboxEgress;
205
205
  if (deployment.mode === "none")
206
206
  throw deploymentEgressNone();
207
207
  const settings = await readOrgSettings(t, orgId);
@@ -621,7 +621,7 @@ let CatalogRequestsService = class CatalogRequestsService {
621
621
  */
622
622
  async approveNetwork(orgId, actor, requestId, detail, opts) {
623
623
  const hosts = detail?.hosts ?? [];
624
- const deployment = this.orgSettings.deployment().sandboxEgress;
624
+ const deployment = (await this.orgSettings.deployment()).sandboxEgress;
625
625
  if (deployment.mode === "none")
626
626
  throw deploymentEgressNone();
627
627
  const current = (await readOrgSettings(this.db, orgId)).sandboxEgress;
@@ -1,6 +1,6 @@
1
1
  import { WorkerHost } from "@nestjs/bullmq";
2
2
  import { type DynamicModule } from "@nestjs/common";
3
- import type { Job, Worker } from "bullmq";
3
+ import { type Job, type Worker } from "bullmq";
4
4
  import type { KernelConfig } from "../config/schema.js";
5
5
  import { type ProcessorWorkerOptions } from "../infra/queue/configured-processor.js";
6
6
  import { type ChannelJobData } from "./jobs.js";
@@ -14,7 +14,10 @@ import { ChannelOutbound } from "./outbound.js";
14
14
  */
15
15
  export declare class ChannelsModule {
16
16
  }
17
- /** The consumer of `cap-kernel-channels` (deliveries and inbound jobs): {@link ChannelOutbound}. */
17
+ /**
18
+ * The consumer of `cap-kernel-channels`: deliveries (`DELIVER_JOB`, owed through the outbox or
19
+ * hinted) and inbound jobs (`INBOUND_JOB`), both handled by {@link ChannelOutbound}.
20
+ */
18
21
  export declare class ChannelsProcessor extends WorkerHost<Worker<ChannelJobData>> {
19
22
  private readonly outbound;
20
23
  constructor(outbound: ChannelOutbound);
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  var ChannelWorkersModule_1;
11
11
  import { OnWorkerEvent, WorkerHost } from "@nestjs/bullmq";
12
12
  import { Inject, Injectable, Module } from "@nestjs/common";
13
+ import { UnrecoverableError } from "bullmq";
13
14
  import { ConversationsModule } from "../conversations/conversations.module.js";
14
15
  import { EventLogModule } from "../conversations/event-log.js";
15
16
  import { DevicesModule } from "../devices/devices.module.js";
@@ -25,7 +26,7 @@ import { SchedulesModule } from "../schedules/schedules.module.js";
25
26
  import { ToolsModule } from "../tools/tools.module.js";
26
27
  import { ChannelConnections } from "./connections.service.js";
27
28
  import { ChannelInbound } from "./inbound.js";
28
- import { CHANNEL_QUEUE_NAME, ChannelJobs } from "./jobs.js";
29
+ import { CHANNEL_QUEUE_NAME, ChannelJobs, DELIVER_JOB, INBOUND_JOB, } from "./jobs.js";
29
30
  import { ChannelOutbound, deliverBackoff } from "./outbound.js";
30
31
  import { AnonymousGuestLock, AnonymousGuests } from "./threads.js";
31
32
  /** The channel queue's registration (its producer here; the admin health reads its counts). */
@@ -74,7 +75,10 @@ ChannelsModule = __decorate([
74
75
  })
75
76
  ], ChannelsModule);
76
77
  export { ChannelsModule };
77
- /** The consumer of `cap-kernel-channels` (deliveries and inbound jobs): {@link ChannelOutbound}. */
78
+ /**
79
+ * The consumer of `cap-kernel-channels`: deliveries (`DELIVER_JOB`, owed through the outbox or
80
+ * hinted) and inbound jobs (`INBOUND_JOB`), both handled by {@link ChannelOutbound}.
81
+ */
78
82
  let ChannelsProcessor = class ChannelsProcessor extends WorkerHost {
79
83
  outbound;
80
84
  constructor(outbound) {
@@ -82,6 +86,9 @@ let ChannelsProcessor = class ChannelsProcessor extends WorkerHost {
82
86
  this.outbound = outbound;
83
87
  }
84
88
  process(job, token) {
89
+ if (job.name !== DELIVER_JOB && job.name !== INBOUND_JOB) {
90
+ return Promise.reject(new UnrecoverableError(`unknown channel job "${job.name}"`));
91
+ }
85
92
  return runJob(CHANNEL_QUEUE_NAME, job, () => this.outbound.process(job, token));
86
93
  }
87
94
  failed(job, err) {
@@ -0,0 +1,25 @@
1
+ import type { OutboxService } from "../infra/outbox/outbox.service.js";
2
+ /**
3
+ * The channel delivery job as the outbox owes it (transactional outbox spec §8.1): a leaf module
4
+ * with no BullMQ and no Nest class, so the event log can owe it without importing the channels
5
+ * domain. `jobs.ts` (the producer) re-exports these names.
6
+ */
7
+ /** 渠道队列(出站投递与入站任务,不含 `:`),只在 worker 角色上消费。 */
8
+ export declare const CHANNEL_QUEUE_NAME = "cap-kernel-channels";
9
+ /** 投递任务名。 */
10
+ export declare const DELIVER_JOB = "deliver";
11
+ /** 投递任务 id(不含 `:`):同一会话、同一日志位置只排一个任务。 */
12
+ export declare const deliverJobId: (conversationId: string, seq: number) => string;
13
+ export interface DeliverJobData {
14
+ conversationId: string;
15
+ }
16
+ /**
17
+ * Owes the conversation's delivery job for the log position `seq` in the transaction in context:
18
+ * the caller knows the conversation has a channel target. Shares the job id of
19
+ * `ChannelJobs.enqueue`, so a hint for the same position is deduped by BullMQ.
20
+ */
21
+ export declare function oweDelivery(outbox: Pick<OutboxService, "add">, d: {
22
+ conversationId: string;
23
+ orgId: string;
24
+ seq: number;
25
+ }): Promise<boolean>;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The channel delivery job as the outbox owes it (transactional outbox spec §8.1): a leaf module
3
+ * with no BullMQ and no Nest class, so the event log can owe it without importing the channels
4
+ * domain. `jobs.ts` (the producer) re-exports these names.
5
+ */
6
+ /** 渠道队列(出站投递与入站任务,不含 `:`),只在 worker 角色上消费。 */
7
+ export const CHANNEL_QUEUE_NAME = "cap-kernel-channels";
8
+ /** 投递任务名。 */
9
+ export const DELIVER_JOB = "deliver";
10
+ /** 投递任务 id(不含 `:`):同一会话、同一日志位置只排一个任务。 */
11
+ export const deliverJobId = (conversationId, seq) => `deliver-${conversationId}-${seq}`;
12
+ /**
13
+ * Owes the conversation's delivery job for the log position `seq` in the transaction in context:
14
+ * the caller knows the conversation has a channel target. Shares the job id of
15
+ * `ChannelJobs.enqueue`, so a hint for the same position is deduped by BullMQ.
16
+ */
17
+ export function oweDelivery(outbox, d) {
18
+ return outbox.add({
19
+ queue: CHANNEL_QUEUE_NAME,
20
+ name: DELIVER_JOB,
21
+ jobId: deliverJobId(d.conversationId, d.seq),
22
+ data: { conversationId: d.conversationId },
23
+ orgId: d.orgId,
24
+ });
25
+ }
@@ -72,7 +72,7 @@ export declare class ChannelInbound {
72
72
  /** 通讯录同步的投递(按 (组织, 插件) 每分钟去重的维护队列任务)。 */
73
73
  directorySync: Pick<DirectorySync, "enqueue">,
74
74
  /** The channel queue: inbound jobs (`onEvent` only dedupes and enqueues) and deliveries. */
75
- jobs: Pick<ChannelJobs, "enqueue" | "enqueueInbound">,
75
+ jobs: Pick<ChannelJobs, "enqueue" | "enqueueInbound" | "bind">,
76
76
  /** 卡片操作:审批决定与提问回答(授权由这两个服务按点击者映射到的账号判定)。 */
77
77
  approvals: Pick<ApprovalsService, "decide">, questions: Pick<QuestionsService, "answer">, guests: Pick<AnonymousGuests, "ensure">, devices: Pick<DevicesService, "list" | "imDefault" | "setImDefault">, log: Pick<Logger, "warn" | "info">);
78
78
  /**
@@ -277,21 +277,8 @@ let ChannelInbound = class ChannelInbound {
277
277
  }
278
278
  throw err;
279
279
  }
280
- await db
281
- .insertInto("channel_deliveries")
282
- .values({
283
- conversation_id: conversationId,
284
- connection_id: connectionId,
285
- target: JSON.stringify(replyTarget),
286
- last_seq: seq,
287
- })
288
- .onConflict((oc) => oc.column("conversation_id").doUpdateSet({
289
- connection_id: connectionId,
290
- target: JSON.stringify(replyTarget),
291
- updated_at: new Date(),
292
- }))
293
- .execute();
294
- await this.jobs.enqueue(conversationId);
280
+ // the reply target and its delivery, owed in one transaction (transactional outbox spec §8.1)
281
+ await this.jobs.bind(row.orgId, conversationId, connectionId, replyTarget, seq);
295
282
  }
296
283
  /**
297
284
  * Direct-message `/device` (environments spec §4.2 item 8): lists the person's usable devices,
@@ -1,14 +1,12 @@
1
- import type { InboundEvent, Logger } from "@capybara-hq/plugin-sdk";
1
+ import type { ChannelTarget, InboundEvent, Logger } from "@capybara-hq/plugin-sdk";
2
2
  import { type OnApplicationShutdown } from "@nestjs/common";
3
3
  import type { Queue } from "bullmq";
4
4
  import { KernelDb } from "../infra/database/kernel-db.js";
5
+ import { TransactionHost } from "../infra/database/transaction-host.js";
5
6
  import { KernelEvents } from "../infra/events/kernel-events.js";
6
- /** 渠道队列(出站投递与入站任务,不含 `:`),只在 worker 角色上消费。 */
7
- export declare const CHANNEL_QUEUE_NAME = "cap-kernel-channels";
8
- /** 投递任务名。 */
9
- export declare const DELIVER_JOB = "deliver";
10
- /** 投递任务 id(不含 `:`):同一会话、同一日志位置只排一个任务。 */
11
- export declare const deliverJobId: (conversationId: string, seq: number) => string;
7
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
8
+ import { type DeliverJobData } from "./deliver-job.js";
9
+ export { CHANNEL_QUEUE_NAME, DELIVER_JOB, type DeliverJobData, deliverJobId, oweDelivery, } from "./deliver-job.js";
12
10
  /**
13
11
  * 结束后复核排的任务 id:每次唯一(带随机后缀,不含 `:`)。不能复用 `deliver-<会话>-<seq>`——同 id 的任务
14
12
  * 可能正因锁被占而即将直接结束,BullMQ 会把新任务去重进它,于是没人投递。
@@ -20,10 +18,7 @@ export declare const followUpJobId: (conversationId: string, seq: number) => str
20
18
  */
21
19
  export declare function idempotencyKey(raw: string): string;
22
20
  /** 可重试失败(限流、5xx、网络、超时)的总尝试次数。 */
23
- export declare const DELIVER_ATTEMPTS = 8;
24
- export interface DeliverJobData {
25
- conversationId: string;
26
- }
21
+ export declare const DELIVER_ATTEMPTS: 8;
27
22
  /** 入站任务(Ruling A21):插件 `onEvent` 收到的事件,原样排进队列由 worker 处理。 */
28
23
  export interface InboundJobData {
29
24
  connectionId: string;
@@ -37,7 +32,7 @@ export declare const INBOUND_JOB = "inbound";
37
32
  * 用户发来的消息不能排在它们后面。
38
33
  */
39
34
  export declare const INBOUND_PRIORITY = 1;
40
- export declare const DELIVER_PRIORITY = 10;
35
+ export declare const DELIVER_PRIORITY: 10;
41
36
  /** 入站任务的总尝试次数(处理失败由 BullMQ 指数退避重试:1s、2s、4s、8s)。 */
42
37
  export declare const INBOUND_ATTEMPTS = 5;
43
38
  /**
@@ -49,24 +44,39 @@ export declare const inboundJobId: (connectionId: string, messageId: string) =>
49
44
  * The producer side of the channel queue `cap-kernel-channels` (any role): delivery jobs for a
50
45
  * conversation with an IM target, inbound jobs (Ruling A21), and the catch-up of a connection that
51
46
  * can deliver again. Its consumer is {@link ChannelOutbound} through the `@Processor` of the worker
52
- * role. Delivery jobs follow the kernel's domain events (spec §3b): every published log advance
53
- * (`conversation.event-appended`), a run starting here (`run.started`), a stopped wait
54
- * (`run.wait-stopped`), a decided approval and an answered question (their cards change). Each is
55
- * lost-tolerant: the next append enqueues again, and a finished delivery job re-checks the log.
47
+ * role. A delivery is owed (transactional outbox spec §8.1): every event append of a conversation
48
+ * with a channel target adds its deliver job to the outbox in the append's transaction (a reply, an
49
+ * approval decision, a question answer, a wait stop all append), and {@link bind} owes the first
50
+ * one with the target. The direct {@link enqueue} is left for hints and catch-ups: a run starting
51
+ * here (`run.started`, so its streaming drafts start at once), a finished delivery job's re-check,
52
+ * a card click's thread and a connection that can deliver again.
56
53
  */
57
54
  export declare class ChannelJobs implements OnApplicationShutdown {
58
55
  private readonly db;
59
56
  private readonly queue;
60
57
  private readonly log;
58
+ private readonly outbox;
59
+ readonly txHost: TransactionHost;
61
60
  /** Stopped (the stop's channel-outbound phase): enqueues do nothing, inbound enqueues throw. */
62
61
  private closed;
63
62
  private readonly unsubscribe;
64
- constructor(db: KernelDb, queue: Queue<ChannelJobData>, events: Pick<KernelEvents, "on">, log: Pick<Logger, "warn" | "error">);
63
+ constructor(db: KernelDb, queue: Queue<ChannelJobData>, events: Pick<KernelEvents, "on">, log: Pick<Logger, "warn" | "error">, outbox: Pick<OutboxService, "add">, txHost: TransactionHost);
65
64
  /** Unsubscribes after the stop phases: events emitted while they drain are still handled. */
66
65
  onApplicationShutdown(): void;
66
+ /**
67
+ * Makes `target` (on `connectionId`) the conversation's delivery target and owes its delivery
68
+ * from the current log position, in one transaction. A new target starts delivering after
69
+ * `seq` (the message that bound it); a known one keeps its progress. The conversation row is
70
+ * locked first, as an append locks it: an append either committed before (its events are below
71
+ * the owed position) or reads the target (and owes its own job).
72
+ */
73
+ bind(orgId: string, conversationId: string, connectionId: string, target: ChannelTarget, seq: number): Promise<void>;
67
74
  /** 会话有 IM 投递目标时排一个出站任务,不等入队完成;失败只记日志。 */
68
75
  private enqueueSoon;
69
- /** 会话有 IM 投递目标时投递一个出站任务(同一日志位置重复调用只排一个);已关闭时什么都不做。 */
76
+ /**
77
+ * A hint (not owed work, see the class): a delivery job for a conversation with an IM target (one
78
+ * per log position; `followUp` gets a fresh id); does nothing once closed.
79
+ */
70
80
  enqueue(conversationId: string, opts?: {
71
81
  followUp?: boolean;
72
82
  }): Promise<void>;
@@ -11,14 +11,14 @@ import { createHash, randomUUID } from "node:crypto";
11
11
  import { getQueueToken } from "@nestjs/bullmq";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { KernelDb } from "../infra/database/kernel-db.js";
14
+ import { TransactionHost } from "../infra/database/transaction-host.js";
15
+ import { Transactional } from "../infra/database/transactional.decorator.js";
14
16
  import { KernelEvents } from "../infra/events/kernel-events.js";
17
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
18
+ import { OUTBOX_JOBS } from "../infra/outbox/registry.js";
15
19
  import { KERNEL_LOGGER } from "../infra/tokens.js";
16
- /** 渠道队列(出站投递与入站任务,不含 `:`),只在 worker 角色上消费。 */
17
- export const CHANNEL_QUEUE_NAME = "cap-kernel-channels";
18
- /** 投递任务名。 */
19
- export const DELIVER_JOB = "deliver";
20
- /** 投递任务 id(不含 `:`):同一会话、同一日志位置只排一个任务。 */
21
- export const deliverJobId = (conversationId, seq) => `deliver-${conversationId}-${seq}`;
20
+ import { CHANNEL_QUEUE_NAME, DELIVER_JOB, deliverJobId, oweDelivery, } from "./deliver-job.js";
21
+ export { CHANNEL_QUEUE_NAME, DELIVER_JOB, deliverJobId, oweDelivery, } from "./deliver-job.js";
22
22
  /**
23
23
  * 结束后复核排的任务 id:每次唯一(带随机后缀,不含 `:`)。不能复用 `deliver-<会话>-<seq>`——同 id 的任务
24
24
  * 可能正因锁被占而即将直接结束,BullMQ 会把新任务去重进它,于是没人投递。
@@ -32,7 +32,7 @@ export function idempotencyKey(raw) {
32
32
  return createHash("sha256").update(raw).digest("base64url").slice(0, 32);
33
33
  }
34
34
  /** 可重试失败(限流、5xx、网络、超时)的总尝试次数。 */
35
- export const DELIVER_ATTEMPTS = 8;
35
+ export const DELIVER_ATTEMPTS = OUTBOX_JOBS.deliver.opts.attempts;
36
36
  /** 入站任务名。 */
37
37
  export const INBOUND_JOB = "inbound";
38
38
  /**
@@ -40,7 +40,7 @@ export const INBOUND_JOB = "inbound";
40
40
  * 用户发来的消息不能排在它们后面。
41
41
  */
42
42
  export const INBOUND_PRIORITY = 1;
43
- export const DELIVER_PRIORITY = 10;
43
+ export const DELIVER_PRIORITY = OUTBOX_JOBS.deliver.opts.priority;
44
44
  /** 入站任务的总尝试次数(处理失败由 BullMQ 指数退避重试:1s、2s、4s、8s)。 */
45
45
  export const INBOUND_ATTEMPTS = 5;
46
46
  const INBOUND_BACKOFF_MS = 1000;
@@ -53,30 +53,31 @@ export const inboundJobId = (connectionId, messageId) => `inbound-${connectionId
53
53
  * The producer side of the channel queue `cap-kernel-channels` (any role): delivery jobs for a
54
54
  * conversation with an IM target, inbound jobs (Ruling A21), and the catch-up of a connection that
55
55
  * can deliver again. Its consumer is {@link ChannelOutbound} through the `@Processor` of the worker
56
- * role. Delivery jobs follow the kernel's domain events (spec §3b): every published log advance
57
- * (`conversation.event-appended`), a run starting here (`run.started`), a stopped wait
58
- * (`run.wait-stopped`), a decided approval and an answered question (their cards change). Each is
59
- * lost-tolerant: the next append enqueues again, and a finished delivery job re-checks the log.
56
+ * role. A delivery is owed (transactional outbox spec §8.1): every event append of a conversation
57
+ * with a channel target adds its deliver job to the outbox in the append's transaction (a reply, an
58
+ * approval decision, a question answer, a wait stop all append), and {@link bind} owes the first
59
+ * one with the target. The direct {@link enqueue} is left for hints and catch-ups: a run starting
60
+ * here (`run.started`, so its streaming drafts start at once), a finished delivery job's re-check,
61
+ * a card click's thread and a connection that can deliver again.
60
62
  */
61
63
  let ChannelJobs = class ChannelJobs {
62
64
  db;
63
65
  queue;
64
66
  log;
67
+ outbox;
68
+ txHost;
65
69
  /** Stopped (the stop's channel-outbound phase): enqueues do nothing, inbound enqueues throw. */
66
70
  closed = false;
67
71
  unsubscribe;
68
- constructor(db, queue, events, log) {
72
+ constructor(db, queue, events, log, outbox, txHost) {
69
73
  this.db = db;
70
74
  this.queue = queue;
71
75
  this.log = log;
76
+ this.outbox = outbox;
77
+ this.txHost = txHost;
72
78
  queue.on("error", (err) => this.log.error("channel outbound queue error", { err }));
73
- const soon = ({ conversationId }) => this.enqueueSoon(conversationId);
74
79
  this.unsubscribe = [
75
- events.on("conversation.event-appended", soon),
76
- events.on("run.started", soon),
77
- events.on("run.wait-stopped", soon),
78
- events.on("approval.decided", soon),
79
- events.on("question.answered", soon),
80
+ events.on("run.started", ({ conversationId }) => this.enqueueSoon(conversationId)),
80
81
  ];
81
82
  }
82
83
  /** Unsubscribes after the stop phases: events emitted while they drain are still handled. */
@@ -84,11 +85,46 @@ let ChannelJobs = class ChannelJobs {
84
85
  for (const off of this.unsubscribe)
85
86
  off();
86
87
  }
88
+ /**
89
+ * Makes `target` (on `connectionId`) the conversation's delivery target and owes its delivery
90
+ * from the current log position, in one transaction. A new target starts delivering after
91
+ * `seq` (the message that bound it); a known one keeps its progress. The conversation row is
92
+ * locked first, as an append locks it: an append either committed before (its events are below
93
+ * the owed position) or reads the target (and owes its own job).
94
+ */
95
+ async bind(orgId, conversationId, connectionId, target, seq) {
96
+ const conv = await this.db
97
+ .selectFrom("conversations")
98
+ .select("last_seq")
99
+ .where("id", "=", conversationId)
100
+ .forUpdate()
101
+ .executeTakeFirst();
102
+ if (!conv)
103
+ return;
104
+ await this.db
105
+ .insertInto("channel_deliveries")
106
+ .values({
107
+ conversation_id: conversationId,
108
+ connection_id: connectionId,
109
+ target: JSON.stringify(target),
110
+ last_seq: seq,
111
+ })
112
+ .onConflict((oc) => oc.column("conversation_id").doUpdateSet({
113
+ connection_id: connectionId,
114
+ target: JSON.stringify(target),
115
+ updated_at: new Date(),
116
+ }))
117
+ .execute();
118
+ await oweDelivery(this.outbox, { conversationId, orgId, seq: Number(conv.last_seq) });
119
+ }
87
120
  /** 会话有 IM 投递目标时排一个出站任务,不等入队完成;失败只记日志。 */
88
121
  enqueueSoon(conversationId) {
89
122
  this.enqueue(conversationId).catch((err) => this.log.warn("cannot enqueue channel delivery", { conversationId, err }));
90
123
  }
91
- /** 会话有 IM 投递目标时投递一个出站任务(同一日志位置重复调用只排一个);已关闭时什么都不做。 */
124
+ /**
125
+ * A hint (not owed work, see the class): a delivery job for a conversation with an IM target (one
126
+ * per log position; `followUp` gets a fresh id); does nothing once closed.
127
+ */
92
128
  async enqueue(conversationId, opts = {}) {
93
129
  if (this.closed)
94
130
  return;
@@ -101,14 +137,10 @@ let ChannelJobs = class ChannelJobs {
101
137
  if (!row || this.closed)
102
138
  return;
103
139
  await this.queue.add(DELIVER_JOB, { conversationId }, {
140
+ ...OUTBOX_JOBS.deliver.opts,
104
141
  jobId: opts.followUp
105
142
  ? followUpJobId(conversationId, Number(row.last_seq))
106
143
  : deliverJobId(conversationId, Number(row.last_seq)),
107
- attempts: DELIVER_ATTEMPTS,
108
- backoff: { type: "deliver" },
109
- priority: DELIVER_PRIORITY,
110
- removeOnComplete: true,
111
- removeOnFail: true,
112
144
  });
113
145
  }
114
146
  /**
@@ -147,11 +179,16 @@ let ChannelJobs = class ChannelJobs {
147
179
  this.closed = true;
148
180
  }
149
181
  };
182
+ __decorate([
183
+ Transactional()
184
+ ], ChannelJobs.prototype, "bind", null);
150
185
  ChannelJobs = __decorate([
151
186
  Injectable(),
152
187
  __param(0, Inject(KernelDb)),
153
188
  __param(1, Inject(getQueueToken(CHANNEL_QUEUE_NAME))),
154
189
  __param(2, Inject(KernelEvents)),
155
- __param(3, Inject(KERNEL_LOGGER))
190
+ __param(3, Inject(KERNEL_LOGGER)),
191
+ __param(4, Inject(OutboxService)),
192
+ __param(5, Inject(TransactionHost))
156
193
  ], ChannelJobs);
157
194
  export { ChannelJobs };
@@ -11,8 +11,6 @@ export interface FieldMeta {
11
11
  * 用法:`z.string().meta(meta({ secret: true, description: "..." }))`。
12
12
  */
13
13
  export declare function meta(opts: FieldMeta): FieldMeta;
14
- /** `runtime.maxRunSeconds` 的默认值。 */
15
- export declare const DEFAULT_MAX_RUN_SECONDS = 900;
16
14
  /** `sandbox.limits.maxCommandSeconds` 的默认值。 */
17
15
  export declare const DEFAULT_MAX_COMMAND_SECONDS = 7200;
18
16
  /** access token 寿命上限(秒);会话吊销标记的 TTL 按它计算,与实例当前配置无关。 */
@@ -228,17 +226,17 @@ export declare const KernelConfigSchema: z.ZodObject<{
228
226
  devHosts: z.ZodDefault<z.ZodArray<z.ZodString>>;
229
227
  }, z.core.$strip>>;
230
228
  tiers: z.ZodPrefault<z.ZodObject<{
231
- max: z.ZodDefault<z.ZodEnum<{
229
+ max: z.ZodOptional<z.ZodEnum<{
232
230
  dev: "dev";
233
231
  open: "open";
234
232
  strict: "strict";
235
233
  }>>;
236
- default: z.ZodDefault<z.ZodEnum<{
234
+ default: z.ZodOptional<z.ZodEnum<{
237
235
  dev: "dev";
238
236
  open: "open";
239
237
  strict: "strict";
240
238
  }>>;
241
- allowUnsandboxed: z.ZodDefault<z.ZodBoolean>;
239
+ allowUnsandboxed: z.ZodOptional<z.ZodBoolean>;
242
240
  }, z.core.$strip>>;
243
241
  }, z.core.$strip>>;
244
242
  devices: z.ZodPrefault<z.ZodObject<{
@@ -268,7 +266,6 @@ export declare const KernelConfigSchema: z.ZodObject<{
268
266
  hooks: z.ZodPrefault<z.ZodObject<{
269
267
  timeoutMs: z.ZodDefault<z.ZodNumber>;
270
268
  usageReportConcurrency: z.ZodDefault<z.ZodNumber>;
271
- usageReportKeepHours: z.ZodDefault<z.ZodNumber>;
272
269
  }, z.core.$strip>>;
273
270
  log: z.ZodPrefault<z.ZodObject<{
274
271
  level: z.ZodDefault<z.ZodEnum<{