@capybara-hq/kernel 0.1.0-rc.36 → 0.1.0-rc.37

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 (309) hide show
  1. package/bootstrap.json +5 -5
  2. package/dist/admin/admin.module.d.ts +3 -3
  3. package/dist/admin/admin.module.js +6 -6
  4. package/dist/admin/audit-log.service.d.ts +51 -0
  5. package/dist/admin/{platform-audit.service.js → audit-log.service.js} +20 -12
  6. package/dist/admin/audit.controller.d.ts +18 -6
  7. package/dist/admin/audit.controller.js +36 -6
  8. package/dist/admin/audit.schemas.d.ts +9 -1
  9. package/dist/admin/audit.schemas.js +22 -2
  10. package/dist/admin/outbox-dead.controller.d.ts +4 -6
  11. package/dist/admin/outbox-dead.controller.js +9 -6
  12. package/dist/admin/outbox-dead.schemas.d.ts +16 -0
  13. package/dist/admin/outbox-dead.schemas.js +25 -1
  14. package/dist/admin/outbox-dead.service.d.ts +16 -7
  15. package/dist/admin/outbox-dead.service.js +34 -10
  16. package/dist/admin/overview.service.d.ts +3 -3
  17. package/dist/admin/overview.service.js +0 -1
  18. package/dist/agents/agent-lookup.js +2 -10
  19. package/dist/agents/agents.service.js +9 -20
  20. package/dist/agents/definition.d.ts +3 -51
  21. package/dist/agents/definition.js +4 -254
  22. package/dist/agents/org-templates.js +2 -6
  23. package/dist/agents/readiness.controller.d.ts +4 -12
  24. package/dist/agents/readiness.controller.js +4 -12
  25. package/dist/agents/readiness.service.d.ts +23 -11
  26. package/dist/agents/readiness.service.js +31 -14
  27. package/dist/agents/templates.d.ts +0 -6
  28. package/dist/agents/templates.js +8 -34
  29. package/dist/background/store.d.ts +2 -0
  30. package/dist/background/store.js +3 -1
  31. package/dist/background/wake-rules.js +2 -1
  32. package/dist/catalog/admin-catalog.controller.d.ts +1 -2
  33. package/dist/catalog/admin-catalog.controller.js +1 -2
  34. package/dist/catalog/appearance.service.js +1 -3
  35. package/dist/catalog/catalog-content.d.ts +1 -1
  36. package/dist/catalog/catalog-content.js +1 -4
  37. package/dist/catalog/catalog-items.js +3 -3
  38. package/dist/catalog/catalog-scope.service.d.ts +10 -28
  39. package/dist/catalog/catalog-scope.service.js +22 -73
  40. package/dist/catalog/cli.d.ts +0 -11
  41. package/dist/catalog/cli.js +0 -20
  42. package/dist/catalog/component-scope.service.js +0 -2
  43. package/dist/catalog/component-state.js +2 -2
  44. package/dist/catalog/install-status.d.ts +6 -0
  45. package/dist/catalog/install-status.js +6 -0
  46. package/dist/catalog/job-ids.d.ts +0 -4
  47. package/dist/catalog/job-ids.js +0 -4
  48. package/dist/catalog/marketplaces.service.d.ts +1 -1
  49. package/dist/catalog/org-catalog.service.d.ts +2 -0
  50. package/dist/catalog/org-catalog.service.js +8 -3
  51. package/dist/catalog/org-extension-switch.d.ts +7 -2
  52. package/dist/catalog/org-extension-switch.js +56 -9
  53. package/dist/catalog/org-plugin-uploads.d.ts +6 -15
  54. package/dist/catalog/org-plugin-uploads.js +9 -27
  55. package/dist/catalog/owned-items.js +1 -3
  56. package/dist/catalog/platform-import-update.js +1 -1
  57. package/dist/catalog/plugin-import.d.ts +15 -13
  58. package/dist/catalog/plugin-import.js +21 -30
  59. package/dist/catalog/plugin-install.d.ts +3 -43
  60. package/dist/catalog/plugin-install.js +8 -150
  61. package/dist/catalog/plugin-package.d.ts +5 -10
  62. package/dist/catalog/plugin-package.js +12 -33
  63. package/dist/catalog/plugin-upgrade.js +5 -4
  64. package/dist/catalog/scope-jobs.d.ts +34 -34
  65. package/dist/catalog/scope-jobs.js +50 -37
  66. package/dist/catalog/scope-orgs.d.ts +1 -1
  67. package/dist/catalog/scope-orgs.js +1 -2
  68. package/dist/catalog/scope-sync-workers.d.ts +4 -3
  69. package/dist/catalog/scope-sync-workers.js +18 -6
  70. package/dist/catalog/scope-sync.d.ts +56 -59
  71. package/dist/catalog/scope-sync.js +96 -166
  72. package/dist/catalog/unshare.d.ts +3 -4
  73. package/dist/catalog/unshare.js +5 -8
  74. package/dist/channels/job-ids.d.ts +2 -6
  75. package/dist/channels/job-ids.js +2 -6
  76. package/dist/channels/outbound.d.ts +1 -1
  77. package/dist/channels/outbound.js +1 -1
  78. package/dist/channels/supervisor.d.ts +2 -3
  79. package/dist/channels/supervisor.js +2 -3
  80. package/dist/client/client-access.service.js +1 -1
  81. package/dist/config/env.js +19 -1
  82. package/dist/config/load.d.ts +0 -6
  83. package/dist/config/load.js +8 -27
  84. package/dist/config/schema.d.ts +53 -47
  85. package/dist/config/schema.js +190 -40
  86. package/dist/conversations/attachments.service.d.ts +10 -3
  87. package/dist/conversations/attachments.service.js +49 -16
  88. package/dist/conversations/conversations.controller.d.ts +0 -39
  89. package/dist/conversations/conversations.controller.js +0 -39
  90. package/dist/conversations/events.d.ts +71 -46
  91. package/dist/conversations/events.js +124 -112
  92. package/dist/conversations/media-types.d.ts +25 -0
  93. package/dist/conversations/media-types.js +38 -0
  94. package/dist/conversations/queue.d.ts +3 -1
  95. package/dist/conversations/queue.service.js +9 -2
  96. package/dist/conversations/titles.js +6 -0
  97. package/dist/ctx/create-ctx.js +1 -2
  98. package/dist/ctx/secrets.d.ts +24 -7
  99. package/dist/ctx/secrets.js +97 -30
  100. package/dist/db/kernel-schema.d.ts +17 -6
  101. package/dist/errors.d.ts +5 -2
  102. package/dist/errors.js +5 -2
  103. package/dist/evals/reconstruct.d.ts +4 -17
  104. package/dist/evals/reconstruct.js +13 -53
  105. package/dist/evals/recorded-tools.d.ts +0 -27
  106. package/dist/evals/recorded-tools.js +2 -92
  107. package/dist/evals/run-replay.d.ts +1 -6
  108. package/dist/evals/run-replay.js +10 -17
  109. package/dist/evals/sets.service.d.ts +17 -5
  110. package/dist/evals/sets.service.js +33 -12
  111. package/dist/evals/snapshot.d.ts +1 -2
  112. package/dist/evals/snapshot.js +4 -17
  113. package/dist/extensions/admin-ops.d.ts +6 -1
  114. package/dist/extensions/admin-ops.js +17 -4
  115. package/dist/extensions/admin-view.d.ts +7 -4
  116. package/dist/extensions/admin-view.js +27 -21
  117. package/dist/extensions/bootstrap.js +0 -1
  118. package/dist/extensions/cli.js +0 -1
  119. package/dist/extensions/host.d.ts +2 -3
  120. package/dist/extensions/host.js +1 -5
  121. package/dist/extensions/installs.d.ts +1 -3
  122. package/dist/extensions/instance.d.ts +0 -2
  123. package/dist/extensions/instance.js +0 -3
  124. package/dist/extensions/org-config.d.ts +4 -4
  125. package/dist/extensions/org-config.js +13 -22
  126. package/dist/extensions/package.d.ts +6 -6
  127. package/dist/extensions/package.js +3 -7
  128. package/dist/extensions/permission-view.d.ts +2 -4
  129. package/dist/extensions/plugin-items.d.ts +21 -1
  130. package/dist/extensions/plugin-items.js +28 -0
  131. package/dist/extensions/sync.js +5 -10
  132. package/dist/extensions/unavailable.js +0 -1
  133. package/dist/http/api.module.js +2 -1
  134. package/dist/identity/audit.d.ts +0 -12
  135. package/dist/identity/audit.js +0 -27
  136. package/dist/identity/auth.controller.js +5 -9
  137. package/dist/identity/cookies.d.ts +4 -9
  138. package/dist/identity/cookies.js +8 -32
  139. package/dist/identity/initial-passwords.d.ts +1 -1
  140. package/dist/identity/initial-passwords.js +1 -2
  141. package/dist/identity/sessions.d.ts +0 -6
  142. package/dist/identity/sessions.js +0 -18
  143. package/dist/inbox/platform-inbox.service.d.ts +33 -1
  144. package/dist/inbox/platform-inbox.service.js +56 -6
  145. package/dist/index.d.ts +4 -2
  146. package/dist/index.js +4 -2
  147. package/dist/infra/cli/master-key-rewrap.d.ts +15 -0
  148. package/dist/infra/cli/master-key-rewrap.js +24 -0
  149. package/dist/infra/config/kernel-config.service.js +0 -17
  150. package/dist/infra/health/health.controller.js +8 -0
  151. package/dist/infra/health/process-fault.d.ts +16 -0
  152. package/dist/infra/health/process-fault.js +49 -0
  153. package/dist/infra/lifecycle/process-guards.d.ts +8 -2
  154. package/dist/infra/lifecycle/process-guards.js +12 -3
  155. package/dist/infra/lifecycle/shutdown-signals.d.ts +10 -1
  156. package/dist/infra/lifecycle/shutdown-signals.js +28 -13
  157. package/dist/infra/outbox/outbox.service.d.ts +12 -9
  158. package/dist/infra/outbox/outbox.service.js +22 -26
  159. package/dist/infra/outbox/registry.d.ts +15 -7
  160. package/dist/infra/outbox/registry.js +39 -23
  161. package/dist/lifecycle/kernel-lifecycle.js +1 -7
  162. package/dist/models/enablement.d.ts +5 -6
  163. package/dist/models/enablement.js +7 -14
  164. package/dist/orgs/orgs.module.d.ts +2 -2
  165. package/dist/orgs/orgs.module.js +2 -2
  166. package/dist/orgs/settings.controller.d.ts +3 -2
  167. package/dist/orgs/settings.service.d.ts +59 -14
  168. package/dist/orgs/settings.service.js +102 -20
  169. package/dist/overrides.d.ts +3 -7
  170. package/dist/overrides.js +2 -4
  171. package/dist/packages/tgz.d.ts +0 -2
  172. package/dist/packages/tgz.js +0 -2
  173. package/dist/platform/exclusions.js +0 -5
  174. package/dist/platform/operation.js +1 -1
  175. package/dist/platform/ops/admin.ops.d.ts +2 -2
  176. package/dist/platform/ops/admin.ops.js +9 -6
  177. package/dist/platform/ops/agents.ops.js +1 -1
  178. package/dist/platform/ops/connectors.ops.js +46 -1
  179. package/dist/platform/ops/evals.ops.js +1 -64
  180. package/dist/platform/ops/extensions-admin.ops.js +1 -1
  181. package/dist/platform/ops/inbox.ops.js +16 -3
  182. package/dist/platform/ops/org-plugins.ops.js +1 -1
  183. package/dist/platform/ops/orgs.ops.d.ts +5 -3
  184. package/dist/platform/ops/orgs.ops.js +19 -4
  185. package/dist/platform/ops/outbox.ops.js +5 -5
  186. package/dist/roles/worker-role.d.ts +2 -3
  187. package/dist/roles/worker-role.js +3 -13
  188. package/dist/runtime/context/build.d.ts +56 -18
  189. package/dist/runtime/context/build.js +143 -50
  190. package/dist/runtime/context/compaction.d.ts +1 -3
  191. package/dist/runtime/context/compaction.js +42 -8
  192. package/dist/runtime/context/run-context.js +1 -2
  193. package/dist/runtime/context/skills.d.ts +27 -56
  194. package/dist/runtime/context/skills.js +42 -114
  195. package/dist/runtime/context/tool-changes.d.ts +3 -3
  196. package/dist/runtime/context/tool-changes.js +6 -16
  197. package/dist/runtime/hook-calls.d.ts +6 -6
  198. package/dist/runtime/hook-calls.js +7 -7
  199. package/dist/runtime/langgraph-loop.js +1 -0
  200. package/dist/runtime/maintenance.d.ts +3 -11
  201. package/dist/runtime/maintenance.js +5 -20
  202. package/dist/runtime/model-call.d.ts +5 -0
  203. package/dist/runtime/model-call.js +48 -36
  204. package/dist/runtime/providers.d.ts +33 -35
  205. package/dist/runtime/providers.js +64 -109
  206. package/dist/runtime/run-context.service.js +7 -22
  207. package/dist/runtime/run-deletion.d.ts +6 -0
  208. package/dist/runtime/run-deletion.js +39 -16
  209. package/dist/runtime/run-execution.js +4 -3
  210. package/dist/runtime/run-finish.js +2 -1
  211. package/dist/runtime/run-liveness.d.ts +11 -0
  212. package/dist/runtime/run-liveness.js +19 -0
  213. package/dist/runtime/run-orphan-check.job.js +2 -1
  214. package/dist/runtime/run-queue.js +8 -16
  215. package/dist/runtime/run-worker.d.ts +2 -2
  216. package/dist/runtime/run-worker.js +8 -6
  217. package/dist/runtime/subagents/definition.d.ts +16 -20
  218. package/dist/runtime/subagents/definition.js +27 -27
  219. package/dist/runtime/subagents/dispatch.d.ts +6 -2
  220. package/dist/runtime/subagents/dispatch.js +17 -3
  221. package/dist/runtime/subagents/org-agents.js +1 -2
  222. package/dist/runtime/subagents/preamble.d.ts +3 -2
  223. package/dist/runtime/subagents/preamble.js +3 -2
  224. package/dist/runtime/subagents/render.d.ts +1 -2
  225. package/dist/runtime/subagents/render.js +1 -2
  226. package/dist/runtime/subagents/skill-fork.d.ts +2 -4
  227. package/dist/runtime/subagents/template-skills.d.ts +47 -0
  228. package/dist/runtime/subagents/template-skills.js +76 -0
  229. package/dist/schedules/effective-settings.d.ts +9 -3
  230. package/dist/schedules/effective-settings.js +5 -4
  231. package/dist/schedules/fire.js +11 -0
  232. package/dist/schedules/scheduled-tasks.service.js +5 -0
  233. package/dist/schedules/unattended.d.ts +2 -0
  234. package/dist/schedules/unattended.js +6 -1
  235. package/dist/skills/agent-skills.service.js +1 -2
  236. package/dist/skills/catalog.d.ts +1 -3
  237. package/dist/skills/catalog.js +1 -3
  238. package/dist/skills/conversation-catalog.d.ts +1 -2
  239. package/dist/skills/conversation-catalog.js +1 -2
  240. package/dist/skills/usable.js +2 -3
  241. package/dist/storage/storage.service.js +9 -1
  242. package/dist/tools/approvals.service.js +2 -4
  243. package/dist/tools/builtin-names.d.ts +2 -9
  244. package/dist/tools/builtin-names.js +4 -13
  245. package/dist/tools/builtins/sandbox/bash.js +3 -3
  246. package/dist/tools/builtins/sandbox/common.d.ts +7 -13
  247. package/dist/tools/builtins/sandbox/common.js +8 -115
  248. package/dist/tools/builtins/sandbox/fetch-attachment.d.ts +10 -0
  249. package/dist/tools/builtins/sandbox/fetch-attachment.js +119 -0
  250. package/dist/tools/builtins/sandbox/glob.js +1 -3
  251. package/dist/tools/builtins/sandbox/grep.js +3 -5
  252. package/dist/tools/builtins/sandbox/index.d.ts +8 -5
  253. package/dist/tools/builtins/sandbox/index.js +10 -5
  254. package/dist/tools/builtins/sandbox/read.js +3 -2
  255. package/dist/tools/builtins/tool-search.d.ts +4 -7
  256. package/dist/tools/builtins/tool-search.js +6 -10
  257. package/dist/tools/connector-account-policies.d.ts +30 -3
  258. package/dist/tools/connector-account-policies.js +54 -7
  259. package/dist/tools/connectors.controller.d.ts +24 -11
  260. package/dist/tools/connectors.controller.js +35 -6
  261. package/dist/tools/connectors.schemas.d.ts +14 -1
  262. package/dist/tools/connectors.schemas.js +14 -2
  263. package/dist/tools/connectors.service.d.ts +22 -0
  264. package/dist/tools/connectors.service.js +56 -0
  265. package/dist/tools/drift.d.ts +1 -1
  266. package/dist/tools/drift.js +1 -1
  267. package/dist/tools/git-push-policy.d.ts +4 -1
  268. package/dist/tools/git-push-policy.js +3 -1
  269. package/dist/tools/info.d.ts +1 -7
  270. package/dist/tools/info.js +5 -18
  271. package/dist/tools/job-ids.d.ts +0 -4
  272. package/dist/tools/job-ids.js +1 -6
  273. package/dist/tools/pipeline.d.ts +4 -10
  274. package/dist/tools/pipeline.js +16 -62
  275. package/dist/tools/policy.d.ts +6 -2
  276. package/dist/tools/policy.js +14 -12
  277. package/dist/tools/registry.js +1 -5
  278. package/dist/ui/views.d.ts +5 -5
  279. package/dist/ui/views.js +10 -16
  280. package/package.json +3 -3
  281. package/src/migrations/0137_audit_org_idx.sql +5 -0
  282. package/src/migrations/0138_plugin_install_status_no_upgrading.sql +18 -0
  283. package/src/migrations/0139_retire_legacy_forms.sql +183 -0
  284. package/src/migrations/0140_retire_history_forms.sql +148 -0
  285. package/src/migrations/0141_install_ledger_promoted_rows.sql +36 -0
  286. package/src/migrations/0142_backfill_event_fields.sql +74 -0
  287. package/src/migrations/0143_backfill_model_call_fields.sql +105 -0
  288. package/src/migrations/0144_retire_frozen_definition_keys.sql +163 -0
  289. package/dist/admin/platform-audit.service.d.ts +0 -41
  290. package/dist/conversations/job-ids.d.ts +0 -6
  291. package/dist/conversations/job-ids.js +0 -6
  292. package/dist/extensions/job-ids.d.ts +0 -6
  293. package/dist/extensions/job-ids.js +0 -6
  294. package/dist/infra/queue/retired-schedulers.d.ts +0 -7
  295. package/dist/infra/queue/retired-schedulers.js +0 -9
  296. package/dist/orgs/job-ids.d.ts +0 -8
  297. package/dist/orgs/job-ids.js +0 -8
  298. package/dist/runtime/context/legacy-text.d.ts +0 -22
  299. package/dist/runtime/context/legacy-text.js +0 -37
  300. package/dist/runtime/job-ids.d.ts +0 -10
  301. package/dist/runtime/job-ids.js +0 -10
  302. package/dist/runtime/retired-schedulers.d.ts +0 -7
  303. package/dist/runtime/retired-schedulers.js +0 -31
  304. package/dist/storage/job-ids.d.ts +0 -6
  305. package/dist/storage/job-ids.js +0 -6
  306. package/dist/tools/legacy-data.d.ts +0 -34
  307. package/dist/tools/legacy-data.js +0 -76
  308. package/dist/tools/legacy-keys.d.ts +0 -51
  309. package/dist/tools/legacy-keys.js +0 -114
@@ -1,4 +1,4 @@
1
- import { type EmbedRequest, type EmbedResult, type ExtensionManifest, type ExtensionPointRef, type Logger, type ModelInfo, type ModelKind, type ModelProvider, type ModelProviderV1, type ModelRequest, type ModelStreamEvent } from "@capybara-hq/plugin-sdk";
1
+ import { type EmbedRequest, type EmbedResult, type ExtensionManifest, type ExtensionPointRef, type Logger, type ModelInfo, type ModelKind, type ModelRequest, type ModelStreamEvent } from "@capybara-hq/plugin-sdk";
2
2
  import type { Redis } from "ioredis";
3
3
  import type { ModelRef } from "../agents/definition.js";
4
4
  import { ApiError } from "../errors.js";
@@ -91,24 +91,15 @@ export declare class ProviderListError extends ApiError {
91
91
  constructor(provider: string, cause: unknown);
92
92
  }
93
93
  /**
94
- * 把 `model-provider@1` 实现包成 `@2`:
95
- * - `listModels`:`parameters` 由 `capabilities.effort` 推导(为真时只有 effort 旋钮,否则为空);
96
- * an `@1` model is always a chat model: `kind` and `embedding` are dropped (an `@1` provider has
97
- * no `embed`); the per-call options are not passed (an `@1` provider reads `ctx.config`);
98
- * - `stream`:`params.effort` 映射为 `req.effort`,其余参数丢弃(`@1` 没有对应字段);
99
- * 没有 `params.effort` 时保留请求自带的 `effort`;only the signal is passed.
100
- */
101
- export declare function adaptModelProviderV1(impl: ModelProviderV1): ModelProvider;
102
- /**
103
- * 模型供应商注册表:供应商即提供 `model-provider` 能力的插件(以插件名为供应商名)。
104
- * 同时支持 `model-provider@1`(经 {@link adaptModelProviderV1} 适配)与 `@2`;
105
- * 同一插件两者都提供时用 `@2`。
94
+ * The model provider registry: a provider is an extension that provides `model-provider@2` (the
95
+ * provider's name is the plugin's name).
106
96
  *
107
97
  * Org-bound (spec B §5.5, A §6): every list and call is made for an org with the provider's
108
- * effective config there (`EffectiveConfigs.get`), passed as `{ orgId, config }`; a provider whose
109
- * effective config is not valid in the org offers no models there, and neither does one the org
110
- * explicitly turned off (its own extension switch row off, spec A §8; a provider with no switch row
111
- * stays usable). The admin view (no org) lists with the platform config.
98
+ * effective config there (`EffectiveConfigs.get`), passed as `{ orgId, config }`. A provider is on
99
+ * in an org only when the org enabled it, like every other extension (`enabledExtensionsQuery`: the
100
+ * org's switch on, or a required bootstrap plugin); one not enabled there, or whose effective
101
+ * config is not valid there, offers no models there. The admin view (no org) lists with the
102
+ * platform config.
112
103
  *
113
104
  * Each list is validated per model (spec B §5.1): kinds are normalised (absent = `chat`, unknown =
114
105
  * `other`); a chat model failing `assertValidDeclarations`, or an `embedding` model without
@@ -116,7 +107,7 @@ export declare function adaptModelProviderV1(impl: ModelProviderV1): ModelProvid
116
107
  * provider stays usable. Only `chat` and `embedding` models resolve.
117
108
  *
118
109
  * Each list (`@2`-shaped) is cached in Redis (`@Cacheable`, key
119
- * `cache:capk:models:<provider>:v<major>:<plugin version>:<config digest>`, 600 s), never in
110
+ * `cache:capk:models:<provider>:f<format>:<plugin version>:<config digest>`, 600 s), never in
120
111
  * process memory: every replica shares it. The digest is the platform config's for every org that
121
112
  * follows the platform (one shared list), and a per-org digest for an org's own copy.
122
113
  */
@@ -130,26 +121,30 @@ export declare class ProviderRegistry {
130
121
  private readonly log?;
131
122
  /** Overrides `models.listTimeoutMs` (tests). */
132
123
  private readonly listTimeoutOverride?;
133
- constructor(host: ProviderHost, effective: Pick<EffectiveConfigs, "get">, cacheService: CacheService, kv: Redis, config: Pick<KernelConfigService, "get">, enablement: Pick<ModelEnablement, "disabled" | "switchedOff">, log?: Pick<Logger, "warn"> | undefined,
124
+ constructor(host: ProviderHost, effective: Pick<EffectiveConfigs, "get">, cacheService: CacheService, kv: Redis, config: Pick<KernelConfigService, "get">, enablement: Pick<ModelEnablement, "disabled" | "enabledIn">, log?: Pick<Logger, "warn"> | undefined,
134
125
  /** Overrides `models.listTimeoutMs` (tests). */
135
126
  listTimeoutOverride?: number | undefined);
136
- /** `listModels()` 加时限(到时按失败处理,供应商的调用留在后台、结果丢弃)。 */
127
+ /**
128
+ * `listModels()` with a time limit: a timeout counts as a failure; the provider's call runs on in
129
+ * the background and its result is dropped.
130
+ */
137
131
  private listModelsWithTimeout;
138
132
  /**
139
- * Whether at least one model-provider extension is loaded on this replica (enabled, configured,
140
- * set up) with a valid effective config in `orgId`. Read from extension state and the org's
141
- * config only: never calls a vendor, so a provider whose vendor is down still counts (org
142
- * readiness, web-order spec §3.8).
133
+ * Whether a model provider is usable in `orgId` (org readiness, web-order spec §3.8,
134
+ * `ReadinessService`), from extension state, the org's switches and its config only: never calls
135
+ * a vendor, so a provider whose vendor is down still counts. True when a provider loaded on this
136
+ * replica is enabled in `orgId` with a valid effective config there.
143
137
  */
144
138
  hasProvider(orgId: string): Promise<boolean>;
145
- /** 每个插件取一个实现(`@2` 优先),按插件首次出现的顺序;不支持的主版本记 warn 后忽略。 */
139
+ /** One implementation per plugin, in the order plugins first appear; another major is ignored. */
146
140
  private providers;
147
141
  /**
148
142
  * The call options and list digest of `p` for `orgId`, or for the platform when `orgId` is
149
143
  * undefined (the admin view). An org: its effective config (not valid -> `needs_config`); the
150
144
  * platform's digest while it follows the platform, a per-org one for its copy. The platform: its
151
- * own config (a required overridable field left empty -> `org_configured`). `off`: the
152
- * extensions the org explicitly turned off (`ModelEnablement.switchedOff`) -> `switched_off`.
145
+ * own config (a required overridable field left empty -> `org_configured`). `on`: the
146
+ * extensions enabled in the org (`ModelEnablement.enabledIn`); a provider not in it ->
147
+ * `not_enabled`. Unused for the platform.
153
148
  */
154
149
  private target;
155
150
  private models;
@@ -175,18 +170,21 @@ export declare class ProviderRegistry {
175
170
  */
176
171
  catalog(orgId: string): Promise<ProviderStatus[]>;
177
172
  /**
178
- * 每个已安装供应商及其状态(按插件加载顺序),for `orgId` (enabled models only), or the platform
179
- * view when undefined (`/admin/models`: every model, `disabled` from the platform's list only).
173
+ * Every installed provider with its status (in plugin load order), for `orgId` (the providers it enabled, their enabled
174
+ * models only), or the platform view when undefined (`/admin/models`: every model, `disabled`
175
+ * from the platform's list only).
180
176
  * See {@link statuses} for the statuses.
181
177
  */
182
178
  listWithStatus(orgId?: string): Promise<ProviderStatus[]>;
183
179
  /**
184
- * 每个已安装供应商的完整列表与状态,for `orgId` or the platform: 列模型失败(含超过
185
- * `models.listTimeoutMs`)的标 `error`、`models` 为空,不影响其他供应商;列模型失败的在
186
- * {@link LIST_FAILURE_TTL_SECONDS} 秒内不再请求。An org where the provider needs configuration gets
187
- * `error`; the platform view of a provider whose platform config leaves a required overridable
188
- * field empty gets `org_configured`. `error` 只是内核自己的英文说明(不透出上游错误原文,原文记 warn
189
- * 日志)。No disabled list applied.
180
+ * Every installed provider's full list and status, for `orgId` or the platform: a provider whose
181
+ * model listing fails (including passing `models.listTimeoutMs`) gets `error` with empty
182
+ * `models` without affecting the others, and is not asked again for
183
+ * {@link LIST_FAILURE_TTL_SECONDS} seconds. For an org only the providers it enabled are
184
+ * listed (one it did not enable is absent); one that needs configuration there gets `error`. The
185
+ * platform view of a provider whose platform config leaves a required overridable field empty
186
+ * gets `org_configured`. `error` is only the kernel's own English message (the upstream error
187
+ * text is never exposed; it goes to a warn log). No disabled list applied.
190
188
  */
191
189
  private statuses;
192
190
  /**
@@ -8,7 +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 { createHash } from "node:crypto";
11
- import { assertValidDeclarations, EFFORT_VALUES, parseExtensionPoint, } from "@capybara-hq/plugin-sdk";
11
+ import { assertValidDeclarations, parseExtensionPoint, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable, Module, Optional } from "@nestjs/common";
13
13
  import { ApiError } from "../errors.js";
14
14
  import { deploymentConfigHash } from "../extensions/config-hash.js";
@@ -44,9 +44,7 @@ const DROPPED_WARN_TTL_SECONDS = 24 * 3600;
44
44
  */
45
45
  const MODELS_CACHE_FORMAT = 2;
46
46
  /**
47
- * The model list's cache key (`@Cacheable` stores it as `cache:<key>`). It carries the provider's
48
- * contract major: after a plugin moves from `@1` to `@2` it never reads the list written through
49
- * the `@1` adapter (both are `@2`-shaped, the shape cannot tell them apart). It also carries the
47
+ * The model list's cache key (`@Cacheable` stores it as `cache:<key>`). It carries the
50
48
  * plugin version and the digest of the effective config the list was read with (see
51
49
  * {@link ProviderRegistry}): after an upgrade (the parameter declarations may have changed) or a
52
50
  * config change (models added or removed) every replica validates the new list at once instead of
@@ -55,9 +53,9 @@ const MODELS_CACHE_FORMAT = 2;
55
53
  * `f<n>` is the shape of the cached entry ({@link MODELS_CACHE_FORMAT}): a kernel that changes what
56
54
  * it caches bumps it, so during a rolling upgrade it never reads a list an older kernel wrote.
57
55
  */
58
- const modelsKey = (p, hash) => `capk:models:${p.plugin}:v${p.major}:f${MODELS_CACHE_FORMAT}:${p.version ?? "-"}:${hash ?? "-"}`;
56
+ const modelsKey = (p, hash) => `capk:models:${p.plugin}:f${MODELS_CACHE_FORMAT}:${p.version ?? "-"}:${hash ?? "-"}`;
59
57
  /** 列表视图的失败标记({@link LIST_FAILURE_TTL_SECONDS}),与模型列表同样按版本与配置摘要区分。 */
60
- const listFailedKey = (p, hash) => `capk:models-failed:${p.plugin}:v${p.major}:${p.version ?? "-"}:${hash ?? "-"}`;
58
+ const listFailedKey = (p, hash) => `capk:models-failed:${p.plugin}:${p.version ?? "-"}:${hash ?? "-"}`;
61
59
  const droppedKey = (plugin, hash, model) => `capk:models-dropped:${plugin}:${hash ?? "-"}:${model}`;
62
60
  /**
63
61
  * The digest of an org's own copy of the config. `deploymentConfigHash` masks secrets, and a copy
@@ -118,54 +116,15 @@ export class ProviderListError extends ApiError {
118
116
  }
119
117
  }
120
118
  /**
121
- * `@1` 适配层为 `capabilities.effort` 为真的模型补的 effort 旋钮:五档,不给默认值
122
- * (各家 API 的默认值不同;给了默认值会让未设置 effort 的 agent 每次都静默发送它)。
123
- */
124
- const V1_EFFORT_KNOB = {
125
- key: "effort",
126
- standard: "effort",
127
- schema: { type: "string", enum: [...EFFORT_VALUES] },
128
- label: { zh: "思考深度", en: "Effort" },
129
- };
130
- /**
131
- * 把 `model-provider@1` 实现包成 `@2`:
132
- * - `listModels`:`parameters` 由 `capabilities.effort` 推导(为真时只有 effort 旋钮,否则为空);
133
- * an `@1` model is always a chat model: `kind` and `embedding` are dropped (an `@1` provider has
134
- * no `embed`); the per-call options are not passed (an `@1` provider reads `ctx.config`);
135
- * - `stream`:`params.effort` 映射为 `req.effort`,其余参数丢弃(`@1` 没有对应字段);
136
- * 没有 `params.effort` 时保留请求自带的 `effort`;only the signal is passed.
137
- */
138
- export function adaptModelProviderV1(impl) {
139
- return {
140
- async listModels() {
141
- const models = await impl.listModels();
142
- return models.map(({ kind: _kind, embedding: _embedding, ...m }) => ({
143
- ...m,
144
- parameters: m.capabilities.effort ? [structuredClone(V1_EFFORT_KNOB)] : [],
145
- }));
146
- },
147
- stream(req, opts) {
148
- // `@1` 没有 toolChoice:不传(旧插件按自己的默认处理)
149
- const { params, toolChoice: _toolChoice, ...rest } = req;
150
- const out = rest;
151
- const effort = params?.effort;
152
- if (typeof effort === "string" && EFFORT_VALUES.includes(effort)) {
153
- out.effort = effort;
154
- }
155
- return impl.stream(out, { signal: opts.signal });
156
- },
157
- };
158
- }
159
- /**
160
- * 模型供应商注册表:供应商即提供 `model-provider` 能力的插件(以插件名为供应商名)。
161
- * 同时支持 `model-provider@1`(经 {@link adaptModelProviderV1} 适配)与 `@2`;
162
- * 同一插件两者都提供时用 `@2`。
119
+ * The model provider registry: a provider is an extension that provides `model-provider@2` (the
120
+ * provider's name is the plugin's name).
163
121
  *
164
122
  * Org-bound (spec B §5.5, A §6): every list and call is made for an org with the provider's
165
- * effective config there (`EffectiveConfigs.get`), passed as `{ orgId, config }`; a provider whose
166
- * effective config is not valid in the org offers no models there, and neither does one the org
167
- * explicitly turned off (its own extension switch row off, spec A §8; a provider with no switch row
168
- * stays usable). The admin view (no org) lists with the platform config.
123
+ * effective config there (`EffectiveConfigs.get`), passed as `{ orgId, config }`. A provider is on
124
+ * in an org only when the org enabled it, like every other extension (`enabledExtensionsQuery`: the
125
+ * org's switch on, or a required bootstrap plugin); one not enabled there, or whose effective
126
+ * config is not valid there, offers no models there. The admin view (no org) lists with the
127
+ * platform config.
169
128
  *
170
129
  * Each list is validated per model (spec B §5.1): kinds are normalised (absent = `chat`, unknown =
171
130
  * `other`); a chat model failing `assertValidDeclarations`, or an `embedding` model without
@@ -173,7 +132,7 @@ export function adaptModelProviderV1(impl) {
173
132
  * provider stays usable. Only `chat` and `embedding` models resolve.
174
133
  *
175
134
  * Each list (`@2`-shaped) is cached in Redis (`@Cacheable`, key
176
- * `cache:capk:models:<provider>:v<major>:<plugin version>:<config digest>`, 600 s), never in
135
+ * `cache:capk:models:<provider>:f<format>:<plugin version>:<config digest>`, 600 s), never in
177
136
  * process memory: every replica shares it. The digest is the platform config's for every org that
178
137
  * follows the platform (one shared list), and a per-org digest for an org's own copy.
179
138
  */
@@ -198,7 +157,10 @@ let ProviderRegistry = class ProviderRegistry {
198
157
  this.log = log;
199
158
  this.listTimeoutOverride = listTimeoutOverride;
200
159
  }
201
- /** `listModels()` 加时限(到时按失败处理,供应商的调用留在后台、结果丢弃)。 */
160
+ /**
161
+ * `listModels()` with a time limit: a timeout counts as a failure; the provider's call runs on in
162
+ * the background and its result is dropped.
163
+ */
202
164
  async listModelsWithTimeout(impl, call) {
203
165
  const ms = this.listTimeoutOverride ?? this.config.get().models.listTimeoutMs;
204
166
  let timer;
@@ -217,57 +179,50 @@ let ProviderRegistry = class ProviderRegistry {
217
179
  }
218
180
  }
219
181
  /**
220
- * Whether at least one model-provider extension is loaded on this replica (enabled, configured,
221
- * set up) with a valid effective config in `orgId`. Read from extension state and the org's
222
- * config only: never calls a vendor, so a provider whose vendor is down still counts (org
223
- * readiness, web-order spec §3.8).
182
+ * Whether a model provider is usable in `orgId` (org readiness, web-order spec §3.8,
183
+ * `ReadinessService`), from extension state, the org's switches and its config only: never calls
184
+ * a vendor, so a provider whose vendor is down still counts. True when a provider loaded on this
185
+ * replica is enabled in `orgId` with a valid effective config there.
224
186
  */
225
187
  async hasProvider(orgId) {
226
- const off = await this.enablement.switchedOff(orgId);
188
+ const on = await this.enablement.enabledIn(orgId);
227
189
  for (const p of this.providers()) {
228
- if ((await this.target(p, orgId, off)).ok)
190
+ if (on.has(p.plugin) && (await this.target(p, orgId, on)).ok)
229
191
  return true;
230
192
  }
231
193
  return false;
232
194
  }
233
- /** 每个插件取一个实现(`@2` 优先),按插件首次出现的顺序;不支持的主版本记 warn 后忽略。 */
195
+ /** One implementation per plugin, in the order plugins first appear; another major is ignored. */
234
196
  providers() {
235
197
  const chosen = new Map();
236
198
  for (const p of this.host.list(CAPABILITY)) {
237
- const { major } = parseExtensionPoint(p.capability);
238
- if (major !== 1 && major !== 2) {
199
+ if (parseExtensionPoint(p.capability).major !== 2) {
239
200
  this.log?.warn("unsupported model-provider major version; ignored", {
240
201
  provider: p.plugin,
241
202
  capability: p.capability,
242
203
  });
243
204
  continue;
244
205
  }
245
- const prev = chosen.get(p.plugin);
246
- if (!prev || major > prev.major) {
247
- chosen.set(p.plugin, {
248
- major,
249
- impl: p.impl,
250
- version: p.version,
251
- configHash: p.configHash,
252
- });
253
- }
206
+ if (chosen.has(p.plugin))
207
+ continue;
208
+ chosen.set(p.plugin, {
209
+ plugin: p.plugin,
210
+ impl: p.impl,
211
+ version: p.version,
212
+ configHash: p.configHash,
213
+ });
254
214
  }
255
- return [...chosen].map(([plugin, { major, impl, version, configHash }]) => ({
256
- plugin,
257
- major,
258
- version,
259
- configHash,
260
- impl: major === 2 ? impl : adaptModelProviderV1(impl),
261
- }));
215
+ return [...chosen.values()];
262
216
  }
263
217
  /**
264
218
  * The call options and list digest of `p` for `orgId`, or for the platform when `orgId` is
265
219
  * undefined (the admin view). An org: its effective config (not valid -> `needs_config`); the
266
220
  * platform's digest while it follows the platform, a per-org one for its copy. The platform: its
267
- * own config (a required overridable field left empty -> `org_configured`). `off`: the
268
- * extensions the org explicitly turned off (`ModelEnablement.switchedOff`) -> `switched_off`.
221
+ * own config (a required overridable field left empty -> `org_configured`). `on`: the
222
+ * extensions enabled in the org (`ModelEnablement.enabledIn`); a provider not in it ->
223
+ * `not_enabled`. Unused for the platform.
269
224
  */
270
- async target(p, orgId, off = new Set()) {
225
+ async target(p, orgId, on = new Set()) {
271
226
  const inst = this.host.current?.(p.plugin);
272
227
  const schema = inst?.manifest.config?.deployment;
273
228
  if (orgId === undefined) {
@@ -276,15 +231,11 @@ let ProviderRegistry = class ProviderRegistry {
276
231
  }
277
232
  return { ok: true, call: { config: inst?.config }, hash: p.configHash };
278
233
  }
279
- if (off.has(p.plugin))
280
- return { ok: false, reason: "switched_off" };
234
+ if (!on.has(p.plugin))
235
+ return { ok: false, reason: "not_enabled" };
281
236
  const eff = await this.effective.get(orgId, p.plugin);
282
237
  if (!eff.ok)
283
238
  return { ok: false, reason: "needs_config" };
284
- // an `@1` provider ignores the per-call options (it reads `ctx.config`): the org's own copy
285
- // could not be honoured, its calls would go out with the platform's config
286
- if (eff.source === "copy" && p.major === 1)
287
- return { ok: false, reason: "needs_config" };
288
239
  return {
289
240
  ok: true,
290
241
  call: { orgId, config: eff.config },
@@ -382,8 +333,9 @@ let ProviderRegistry = class ProviderRegistry {
382
333
  }));
383
334
  }
384
335
  /**
385
- * 每个已安装供应商及其状态(按插件加载顺序),for `orgId` (enabled models only), or the platform
386
- * view when undefined (`/admin/models`: every model, `disabled` from the platform's list only).
336
+ * Every installed provider with its status (in plugin load order), for `orgId` (the providers it enabled, their enabled
337
+ * models only), or the platform view when undefined (`/admin/models`: every model, `disabled`
338
+ * from the platform's list only).
387
339
  * See {@link statuses} for the statuses.
388
340
  */
389
341
  async listWithStatus(orgId) {
@@ -403,22 +355,29 @@ let ProviderRegistry = class ProviderRegistry {
403
355
  }));
404
356
  }
405
357
  /**
406
- * 每个已安装供应商的完整列表与状态,for `orgId` or the platform: 列模型失败(含超过
407
- * `models.listTimeoutMs`)的标 `error`、`models` 为空,不影响其他供应商;列模型失败的在
408
- * {@link LIST_FAILURE_TTL_SECONDS} 秒内不再请求。An org where the provider needs configuration gets
409
- * `error`; the platform view of a provider whose platform config leaves a required overridable
410
- * field empty gets `org_configured`. `error` 只是内核自己的英文说明(不透出上游错误原文,原文记 warn
411
- * 日志)。No disabled list applied.
358
+ * Every installed provider's full list and status, for `orgId` or the platform: a provider whose
359
+ * model listing fails (including passing `models.listTimeoutMs`) gets `error` with empty
360
+ * `models` without affecting the others, and is not asked again for
361
+ * {@link LIST_FAILURE_TTL_SECONDS} seconds. For an org only the providers it enabled are
362
+ * listed (one it did not enable is absent); one that needs configuration there gets `error`. The
363
+ * platform view of a provider whose platform config leaves a required overridable field empty
364
+ * gets `org_configured`. `error` is only the kernel's own English message (the upstream error
365
+ * text is never exposed; it goes to a warn log). No disabled list applied.
412
366
  */
413
367
  async statuses(orgId) {
414
- const providers = this.providers();
415
- const off = orgId === undefined ? new Set() : await this.enablement.switchedOff(orgId);
368
+ const on = orgId === undefined ? new Set() : await this.enablement.enabledIn(orgId);
369
+ const providers = this.providers().filter((p) => orgId === undefined || on.has(p.plugin));
416
370
  const settled = await Promise.allSettled(providers.map(async (p) => {
417
- const t = await this.target(p, orgId, off);
418
- if (!t.ok)
371
+ const t = await this.target(p, orgId, on);
372
+ if (!t.ok) {
373
+ // an org's providers are filtered to the enabled ones above
374
+ if (t.reason === "not_enabled")
375
+ throw new Error(`${p.plugin} is not enabled here`);
419
376
  return t.reason;
377
+ }
420
378
  const failed = listFailedKey(p, t.hash);
421
- // 刚失败过的供应商:短时间内直接标 error,不再等它(每个供应商另有时限)
379
+ // a provider that failed just now: mark it error for a while without waiting on it (each
380
+ // provider has its own time limit too)
422
381
  if ((await this.kv.get(failed)) !== null) {
423
382
  throw new ProviderListError(p.plugin, new Error("listModels failed recently"));
424
383
  }
@@ -442,10 +401,6 @@ let ProviderRegistry = class ProviderRegistry {
442
401
  const error = `Model provider ${provider} needs configuration in this organization`;
443
402
  return { provider, plugin: provider, status: "error", error, models: [] };
444
403
  }
445
- if (r.value === "switched_off") {
446
- const error = `Model provider ${provider} is turned off in this organization`;
447
- return { provider, plugin: provider, status: "error", error, models: [] };
448
- }
449
404
  return { provider, plugin: provider, status: "ok", models: r.value };
450
405
  }
451
406
  this.log?.warn("model provider listModels failed; skipped", { provider, err: r.reason });
@@ -479,13 +434,13 @@ let ProviderRegistry = class ProviderRegistry {
479
434
  const p = this.providers().find((x) => x.plugin === ref.provider);
480
435
  if (!p)
481
436
  throw unavailable();
482
- const off = orgId === undefined ? new Set() : await this.enablement.switchedOff(orgId);
483
- const t = await this.target(p, orgId, off);
437
+ const on = orgId === undefined ? new Set() : await this.enablement.enabledIn(orgId);
438
+ const t = await this.target(p, orgId, on);
484
439
  if (!t.ok) {
485
440
  throw new ApiError("agent.model_unavailable", t.reason === "org_configured"
486
441
  ? `Model provider ${ref.provider} is configured by each organization`
487
- : t.reason === "switched_off"
488
- ? `Model provider ${ref.provider} is turned off in this organization`
442
+ : t.reason === "not_enabled"
443
+ ? `Model provider ${ref.provider} is not enabled in this organization`
489
444
  : `Model provider ${ref.provider} needs configuration in this organization`);
490
445
  }
491
446
  const info = (await this.models(p, t)).find((m) => m.id === ref.model);
@@ -11,7 +11,6 @@ import { Inject, Injectable, Optional } from "@nestjs/common";
11
11
  import { sql } from "kysely";
12
12
  import { conversationLink, effectiveAttribution, readPlatformAttribution, } from "../attribution/platform-attribution.js";
13
13
  import { EventLog } from "../conversations/event-log.js";
14
- import { latestWebLocale } from "../conversations/message-context.js";
15
14
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
16
15
  import { KernelDb } from "../infra/database/kernel-db.js";
17
16
  import { TransactionHost } from "../infra/database/transaction-host.js";
@@ -111,15 +110,14 @@ let RunContextService = class RunContextService {
111
110
  .executeTakeFirst();
112
111
  const settings = await readOrgSettings(t, input.orgId);
113
112
  // the person whose message started the run: the latest message at or before the trigger (a
114
- // wake run has no message of its own). New messages record the zone and language used at send
115
- // time (IM-provided, account, browser, web language, org: message-context.ts); a message
116
- // without them (older logs) falls back to the author's own settings, then the org's (§3.4).
113
+ // wake run has no message of its own). Messages record the zone and language used at send time
114
+ // (IM-provided, account, browser, web language, org: message-context.ts); without a message,
115
+ // the org's (§3.4).
117
116
  const person = await t
118
117
  .selectFrom("conversation_events")
119
118
  .select([
120
119
  sql `payload->>'timeZone'`.as("timeZone"),
121
120
  sql `payload->>'locale'`.as("locale"),
122
- sql `payload->>'authorAccountId'`.as("author"),
123
121
  ])
124
122
  .where("conversation_id", "=", input.conversationId)
125
123
  .where("type", "=", "user_message")
@@ -127,23 +125,10 @@ let RunContextService = class RunContextService {
127
125
  .orderBy("seq", "desc")
128
126
  .limit(1)
129
127
  .executeTakeFirst();
130
- const author = person?.author ?? null;
131
- let zone = person?.timeZone != null && isTimeZone(person.timeZone) ? person.timeZone : undefined;
132
- if (zone === undefined && author !== null) {
133
- const own = await t
134
- .selectFrom("accounts")
135
- .select("time_zone")
136
- .where("id", "=", author)
137
- .executeTakeFirst();
138
- if (own?.time_zone != null && isTimeZone(own.time_zone))
139
- zone = own.time_zone;
140
- }
141
- zone ??= settings.timeZone ?? "UTC";
142
- let locale = person?.locale === "zh" || person?.locale === "en" ? person.locale : undefined;
143
- if (locale === undefined && author !== null) {
144
- locale = await latestWebLocale(t, input.orgId, author);
145
- }
146
- locale ??= settings.locale;
128
+ const zone = person?.timeZone != null && isTimeZone(person.timeZone)
129
+ ? person.timeZone
130
+ : (settings.timeZone ?? "UTC");
131
+ const locale = person?.locale === "zh" || person?.locale === "en" ? person.locale : settings.locale;
147
132
  const description = snapshotDescription(input.agent.description);
148
133
  return {
149
134
  agent: { name: input.agent.name, ...(description !== undefined && { description }) },
@@ -17,6 +17,12 @@ export declare class RunDeletion {
17
17
  private readonly background;
18
18
  constructor(db: KernelDb, txHost: TransactionHost, outbox: OutboxService, finisher: RunFinish, background: BackgroundTaskStopper);
19
19
  stopOrg(data: StopDeletedOrgData): Promise<void>;
20
+ /**
21
+ * One page of the org's conversations that still have live work: an active run (queued, running
22
+ * or waiting on an open wait) or a running background task (owned by its sandbox root). Idle
23
+ * conversations are skipped: there is nothing to stop in them.
24
+ */
25
+ private liveConversationsIn;
20
26
  stopTree(conversationId: string, byAccountId: string | null): Promise<void>;
21
27
  stopDeletedConversation(conversationId: string, byAccountId: string | null): Promise<void>;
22
28
  private stopConversationIn;
@@ -9,6 +9,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { Inject, Injectable } from "@nestjs/common";
11
11
  import { BackgroundTaskStopper } from "../background/stop.js";
12
+ import { RUNNING_TASK_STATUS } from "../background/store.js";
12
13
  import { conversationTree } from "../conversations/tree.js";
13
14
  import { KernelDb } from "../infra/database/kernel-db.js";
14
15
  import { TransactionHost } from "../infra/database/transaction-host.js";
@@ -16,6 +17,8 @@ import { Transactional } from "../infra/database/transactional.decorator.js";
16
17
  import { OutboxService } from "../infra/outbox/outbox.service.js";
17
18
  import { MAINTENANCE_QUEUE_NAME } from "./maintenance-queue.js";
18
19
  import { RunFinish } from "./run-finish.js";
20
+ import { ACTIVE_RUN_STATUSES } from "./run-jobs.js";
21
+ import { isLive } from "./run-liveness.js";
19
22
  export const STOP_DELETED_ORG_JOB = "stop-deleted-org";
20
23
  /** Platform-owned deletion work: it survives the org's outbox purge and process death. */
21
24
  let RunDeletion = class RunDeletion {
@@ -37,21 +40,13 @@ let RunDeletion = class RunDeletion {
37
40
  .select("deleted_at")
38
41
  .where("id", "=", data.orgId)
39
42
  .executeTakeFirst();
40
- if (!org || org.deleted_at === null)
43
+ if (!org || isLive(org.deleted_at))
41
44
  return;
42
45
  let after = "";
43
46
  for (;;) {
44
- const rows = await this.db
45
- .selectFrom("conversations")
46
- .select("id")
47
- .where("org_id", "=", data.orgId)
48
- .where("kind", "in", ["chat", "subagent"])
49
- .where("id", ">", after)
50
- .orderBy("id")
51
- .limit(100)
52
- .execute();
47
+ const rows = await this.liveConversationsIn(data.orgId, after);
53
48
  for (const row of rows) {
54
- await this.stopConversationIn(row.id, data.byAccountId);
49
+ await this.stopConversationIn(row.id, data.byAccountId, "org_deleted");
55
50
  await this.background.stopForDeletedConversation(row.id);
56
51
  }
57
52
  if (rows.length < 100)
@@ -59,13 +54,41 @@ let RunDeletion = class RunDeletion {
59
54
  after = rows[rows.length - 1]?.id ?? after;
60
55
  }
61
56
  }
57
+ /**
58
+ * One page of the org's conversations that still have live work: an active run (queued, running
59
+ * or waiting on an open wait) or a running background task (owned by its sandbox root). Idle
60
+ * conversations are skipped: there is nothing to stop in them.
61
+ */
62
+ async liveConversationsIn(orgId, after) {
63
+ return this.db
64
+ .selectFrom("conversations as c")
65
+ .select("c.id")
66
+ .where("c.org_id", "=", orgId)
67
+ .where("c.kind", "in", ["chat", "subagent"])
68
+ .where("c.id", ">", after)
69
+ .where((eb) => eb.or([
70
+ eb.exists(eb
71
+ .selectFrom("runs as r")
72
+ .select("r.id")
73
+ .whereRef("r.conversation_id", "=", "c.id")
74
+ .where("r.status", "in", ACTIVE_RUN_STATUSES)),
75
+ eb.exists(eb
76
+ .selectFrom("background_tasks as b")
77
+ .select("b.id")
78
+ .whereRef("b.sandbox_conversation_id", "=", "c.id")
79
+ .where("b.status", "=", RUNNING_TASK_STATUS)),
80
+ ]))
81
+ .orderBy("c.id")
82
+ .limit(100)
83
+ .execute();
84
+ }
62
85
  async stopTree(conversationId, byAccountId) {
63
86
  const root = await this.db
64
87
  .selectFrom("conversations")
65
88
  .select("deleted_at")
66
89
  .where("id", "=", conversationId)
67
90
  .executeTakeFirst();
68
- if (!root || root.deleted_at === null)
91
+ if (!root || isLive(root.deleted_at))
69
92
  return;
70
93
  for (const conv of await conversationTree(this.db.db, conversationId)) {
71
94
  await this.stopConversationIn(conv.id, byAccountId);
@@ -79,12 +102,12 @@ let RunDeletion = class RunDeletion {
79
102
  .select(["c.deleted_at as conversation_deleted", "o.deleted_at as org_deleted"])
80
103
  .where("c.id", "=", conversationId)
81
104
  .executeTakeFirst();
82
- if (!deleted || (deleted.conversation_deleted === null && deleted.org_deleted === null))
105
+ if (!deleted || isLive(deleted.conversation_deleted, deleted.org_deleted))
83
106
  return;
84
107
  await this.stopConversationIn(conversationId, byAccountId);
85
108
  await this.background.stopForDeletedConversation(conversationId);
86
109
  }
87
- async stopConversationIn(conversationId, byAccountId) {
110
+ async stopConversationIn(conversationId, byAccountId, reason = "user") {
88
111
  await this.db
89
112
  .selectFrom("conversations")
90
113
  .select("id")
@@ -95,7 +118,7 @@ let RunDeletion = class RunDeletion {
95
118
  .selectFrom("runs")
96
119
  .select("id")
97
120
  .where("conversation_id", "=", conversationId)
98
- .where("status", "in", ["queued", "running", "waiting"])
121
+ .where("status", "in", ACTIVE_RUN_STATUSES)
99
122
  .orderBy("id")
100
123
  .execute();
101
124
  for (const run of runs) {
@@ -104,7 +127,7 @@ let RunDeletion = class RunDeletion {
104
127
  runId: run.id,
105
128
  status: "aborted",
106
129
  consumed: null,
107
- event: { type: "run_aborted", payload: { byAccountId, reason: "user" } },
130
+ event: { type: "run_aborted", payload: { byAccountId, reason } },
108
131
  });
109
132
  // Cancellation must still be delivered after the terminal commit revoked its claim.
110
133
  await this.outbox.add({
@@ -11,6 +11,7 @@ import { Inject, Injectable } from "@nestjs/common";
11
11
  import { KernelDb } from "../infra/database/kernel-db.js";
12
12
  import { TransactionHost, withTransactionFence } from "../infra/database/transaction-host.js";
13
13
  import { Transactional } from "../infra/database/transactional.decorator.js";
14
+ import { isLive } from "./run-liveness.js";
14
15
  import { rootConversationOf } from "./subagents/child.js";
15
16
  /** Internal interruption: a revoked execution must never write its own terminal failure. */
16
17
  export class ExecutionRevoked extends Error {
@@ -72,7 +73,7 @@ let RunExecution = class RunExecution {
72
73
  .where("id", "=", claim.orgId)
73
74
  .forNoKeyUpdate()
74
75
  .executeTakeFirst();
75
- if (!org || org.deleted_at !== null)
76
+ if (!org || !isLive(org.deleted_at))
76
77
  return false;
77
78
  const root = await this.db
78
79
  .selectFrom("conversations")
@@ -80,7 +81,7 @@ let RunExecution = class RunExecution {
80
81
  .where("id", "=", claim.rootId)
81
82
  .forNoKeyUpdate()
82
83
  .executeTakeFirst();
83
- if (!root || root.deleted_at !== null)
84
+ if (!root || !isLive(root.deleted_at))
84
85
  return false;
85
86
  if (claim.rootId === claim.conversationId)
86
87
  return true;
@@ -91,7 +92,7 @@ let RunExecution = class RunExecution {
91
92
  .where("org_id", "=", claim.orgId)
92
93
  .forNoKeyUpdate()
93
94
  .executeTakeFirst();
94
- return conv !== undefined && conv.deleted_at === null;
95
+ return conv !== undefined && isLive(conv.deleted_at);
95
96
  }
96
97
  };
97
98
  __decorate([