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

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 (351) hide show
  1. package/bootstrap.json +5 -5
  2. package/dist/admin/admin.module.d.ts +3 -2
  3. package/dist/admin/admin.module.js +9 -5
  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/org-network.controller.d.ts +30 -0
  11. package/dist/admin/org-network.controller.js +77 -0
  12. package/dist/admin/org-network.schemas.d.ts +16 -0
  13. package/dist/admin/org-network.schemas.js +27 -0
  14. package/dist/admin/org-network.service.d.ts +41 -0
  15. package/dist/admin/org-network.service.js +101 -0
  16. package/dist/admin/outbox-dead.controller.d.ts +4 -6
  17. package/dist/admin/outbox-dead.controller.js +9 -6
  18. package/dist/admin/outbox-dead.schemas.d.ts +16 -0
  19. package/dist/admin/outbox-dead.schemas.js +25 -1
  20. package/dist/admin/outbox-dead.service.d.ts +16 -7
  21. package/dist/admin/outbox-dead.service.js +34 -10
  22. package/dist/admin/overview.service.d.ts +3 -3
  23. package/dist/admin/overview.service.js +0 -1
  24. package/dist/agents/agent-lookup.js +2 -10
  25. package/dist/agents/agents.service.js +9 -20
  26. package/dist/agents/definition.d.ts +3 -51
  27. package/dist/agents/definition.js +4 -254
  28. package/dist/agents/org-templates.js +2 -6
  29. package/dist/agents/readiness.controller.d.ts +4 -12
  30. package/dist/agents/readiness.controller.js +4 -12
  31. package/dist/agents/readiness.service.d.ts +23 -11
  32. package/dist/agents/readiness.service.js +31 -14
  33. package/dist/agents/templates.d.ts +0 -6
  34. package/dist/agents/templates.js +8 -34
  35. package/dist/background/store.d.ts +2 -0
  36. package/dist/background/store.js +3 -1
  37. package/dist/background/wake-rules.js +2 -1
  38. package/dist/catalog/admin-catalog.controller.d.ts +1 -2
  39. package/dist/catalog/admin-catalog.controller.js +1 -2
  40. package/dist/catalog/appearance.service.js +1 -3
  41. package/dist/catalog/catalog-content.d.ts +1 -1
  42. package/dist/catalog/catalog-content.js +1 -4
  43. package/dist/catalog/catalog-items.js +3 -3
  44. package/dist/catalog/catalog-scope.service.d.ts +10 -28
  45. package/dist/catalog/catalog-scope.service.js +22 -73
  46. package/dist/catalog/cli.d.ts +0 -11
  47. package/dist/catalog/cli.js +0 -20
  48. package/dist/catalog/component-scope.service.js +0 -2
  49. package/dist/catalog/component-state.js +2 -2
  50. package/dist/catalog/install-status.d.ts +6 -0
  51. package/dist/catalog/install-status.js +6 -0
  52. package/dist/catalog/job-ids.d.ts +0 -4
  53. package/dist/catalog/job-ids.js +0 -4
  54. package/dist/catalog/marketplaces.service.d.ts +1 -1
  55. package/dist/catalog/org-catalog.service.d.ts +2 -0
  56. package/dist/catalog/org-catalog.service.js +8 -3
  57. package/dist/catalog/org-extension-switch.d.ts +7 -2
  58. package/dist/catalog/org-extension-switch.js +56 -9
  59. package/dist/catalog/org-plugin-uploads.d.ts +6 -15
  60. package/dist/catalog/org-plugin-uploads.js +9 -27
  61. package/dist/catalog/owned-items.js +1 -3
  62. package/dist/catalog/platform-import-update.js +1 -1
  63. package/dist/catalog/plugin-import.d.ts +15 -13
  64. package/dist/catalog/plugin-import.js +21 -30
  65. package/dist/catalog/plugin-install.d.ts +3 -43
  66. package/dist/catalog/plugin-install.js +8 -150
  67. package/dist/catalog/plugin-package.d.ts +5 -10
  68. package/dist/catalog/plugin-package.js +12 -33
  69. package/dist/catalog/plugin-upgrade.js +5 -4
  70. package/dist/catalog/scope-jobs.d.ts +34 -34
  71. package/dist/catalog/scope-jobs.js +50 -37
  72. package/dist/catalog/scope-orgs.d.ts +1 -1
  73. package/dist/catalog/scope-orgs.js +1 -2
  74. package/dist/catalog/scope-sync-workers.d.ts +4 -3
  75. package/dist/catalog/scope-sync-workers.js +18 -6
  76. package/dist/catalog/scope-sync.d.ts +56 -59
  77. package/dist/catalog/scope-sync.js +96 -166
  78. package/dist/catalog/unshare.d.ts +3 -4
  79. package/dist/catalog/unshare.js +5 -8
  80. package/dist/channels/job-ids.d.ts +2 -6
  81. package/dist/channels/job-ids.js +2 -6
  82. package/dist/channels/outbound.d.ts +1 -1
  83. package/dist/channels/outbound.js +1 -1
  84. package/dist/channels/supervisor.d.ts +2 -3
  85. package/dist/channels/supervisor.js +2 -3
  86. package/dist/client/client-access.service.js +1 -1
  87. package/dist/config/env.js +19 -1
  88. package/dist/config/load.d.ts +0 -6
  89. package/dist/config/load.js +8 -27
  90. package/dist/config/schema.d.ts +54 -47
  91. package/dist/config/schema.js +198 -42
  92. package/dist/conversations/attachments.service.d.ts +10 -3
  93. package/dist/conversations/attachments.service.js +49 -16
  94. package/dist/conversations/conversations.controller.d.ts +0 -39
  95. package/dist/conversations/conversations.controller.js +0 -39
  96. package/dist/conversations/event-log.js +4 -1
  97. package/dist/conversations/events.d.ts +71 -46
  98. package/dist/conversations/events.js +124 -112
  99. package/dist/conversations/media-types.d.ts +25 -0
  100. package/dist/conversations/media-types.js +38 -0
  101. package/dist/conversations/queue.d.ts +3 -1
  102. package/dist/conversations/queue.service.js +9 -2
  103. package/dist/conversations/titles.js +6 -0
  104. package/dist/ctx/create-ctx.d.ts +8 -1
  105. package/dist/ctx/create-ctx.js +13 -3
  106. package/dist/ctx/net.d.ts +50 -0
  107. package/dist/ctx/net.js +67 -0
  108. package/dist/ctx/secrets.d.ts +24 -7
  109. package/dist/ctx/secrets.js +97 -30
  110. package/dist/db/kernel-schema.d.ts +27 -6
  111. package/dist/devices/devices.service.js +2 -1
  112. package/dist/errors.d.ts +10 -2
  113. package/dist/errors.js +10 -2
  114. package/dist/evals/reconstruct.d.ts +4 -17
  115. package/dist/evals/reconstruct.js +13 -53
  116. package/dist/evals/recorded-tools.d.ts +0 -27
  117. package/dist/evals/recorded-tools.js +2 -92
  118. package/dist/evals/run-replay.d.ts +1 -6
  119. package/dist/evals/run-replay.js +10 -17
  120. package/dist/evals/sets.service.d.ts +17 -5
  121. package/dist/evals/sets.service.js +33 -12
  122. package/dist/evals/snapshot.d.ts +1 -2
  123. package/dist/evals/snapshot.js +4 -17
  124. package/dist/extensions/admin-ops.d.ts +6 -1
  125. package/dist/extensions/admin-ops.js +17 -4
  126. package/dist/extensions/admin-view.d.ts +7 -4
  127. package/dist/extensions/admin-view.js +27 -21
  128. package/dist/extensions/bootstrap.js +0 -1
  129. package/dist/extensions/cli.js +0 -1
  130. package/dist/extensions/extensions.module.js +3 -0
  131. package/dist/extensions/host.d.ts +9 -4
  132. package/dist/extensions/host.js +14 -8
  133. package/dist/extensions/installs.d.ts +1 -3
  134. package/dist/extensions/instance.d.ts +0 -2
  135. package/dist/extensions/instance.js +0 -3
  136. package/dist/extensions/org-config.d.ts +4 -4
  137. package/dist/extensions/org-config.js +13 -22
  138. package/dist/extensions/package.d.ts +6 -6
  139. package/dist/extensions/package.js +3 -7
  140. package/dist/extensions/permission-view.d.ts +2 -4
  141. package/dist/extensions/plugin-items.d.ts +21 -1
  142. package/dist/extensions/plugin-items.js +28 -0
  143. package/dist/extensions/sync.js +5 -10
  144. package/dist/extensions/unavailable.js +0 -1
  145. package/dist/http/api.module.js +4 -1
  146. package/dist/identity/audit.d.ts +0 -12
  147. package/dist/identity/audit.js +0 -27
  148. package/dist/identity/auth.controller.js +5 -9
  149. package/dist/identity/cookies.d.ts +4 -9
  150. package/dist/identity/cookies.js +8 -32
  151. package/dist/identity/initial-passwords.d.ts +1 -1
  152. package/dist/identity/initial-passwords.js +1 -2
  153. package/dist/identity/sessions.d.ts +0 -6
  154. package/dist/identity/sessions.js +0 -18
  155. package/dist/inbox/platform-inbox.service.d.ts +33 -1
  156. package/dist/inbox/platform-inbox.service.js +56 -6
  157. package/dist/index.d.ts +4 -2
  158. package/dist/index.js +4 -2
  159. package/dist/infra/cli/master-key-rewrap.d.ts +15 -0
  160. package/dist/infra/cli/master-key-rewrap.js +24 -0
  161. package/dist/infra/config/kernel-config.service.js +0 -17
  162. package/dist/infra/database/transaction-host.d.ts +32 -1
  163. package/dist/infra/database/transaction-host.js +30 -4
  164. package/dist/infra/database/xact-lock.d.ts +16 -0
  165. package/dist/infra/database/xact-lock.js +28 -1
  166. package/dist/infra/health/health.controller.js +8 -0
  167. package/dist/infra/health/process-fault.d.ts +16 -0
  168. package/dist/infra/health/process-fault.js +49 -0
  169. package/dist/infra/lifecycle/process-guards.d.ts +8 -2
  170. package/dist/infra/lifecycle/process-guards.js +12 -3
  171. package/dist/infra/lifecycle/shutdown-signals.d.ts +10 -1
  172. package/dist/infra/lifecycle/shutdown-signals.js +28 -13
  173. package/dist/infra/outbox/outbox.service.d.ts +12 -9
  174. package/dist/infra/outbox/outbox.service.js +22 -26
  175. package/dist/infra/outbox/registry.d.ts +15 -7
  176. package/dist/infra/outbox/registry.js +39 -23
  177. package/dist/lifecycle/kernel-lifecycle.js +1 -7
  178. package/dist/models/enablement.d.ts +5 -6
  179. package/dist/models/enablement.js +7 -14
  180. package/dist/net/public-address.d.ts +21 -1
  181. package/dist/net/public-address.js +56 -10
  182. package/dist/net/safe-fetch.d.ts +4 -1
  183. package/dist/net/safe-fetch.js +15 -4
  184. package/dist/orgs/directory-sync.js +2 -0
  185. package/dist/orgs/members.service.js +5 -0
  186. package/dist/orgs/network-allowances.service.d.ts +79 -0
  187. package/dist/orgs/network-allowances.service.js +371 -0
  188. package/dist/orgs/offboarding.d.ts +3 -1
  189. package/dist/orgs/offboarding.js +9 -2
  190. package/dist/orgs/org-lock.d.ts +28 -2
  191. package/dist/orgs/org-lock.js +59 -4
  192. package/dist/orgs/orgs.controller.d.ts +11 -2
  193. package/dist/orgs/orgs.controller.js +19 -3
  194. package/dist/orgs/orgs.module.d.ts +3 -2
  195. package/dist/orgs/orgs.module.js +6 -2
  196. package/dist/orgs/orgs.schemas.d.ts +12 -0
  197. package/dist/orgs/orgs.schemas.js +5 -0
  198. package/dist/orgs/orgs.service.js +6 -1
  199. package/dist/orgs/settings.controller.d.ts +3 -2
  200. package/dist/orgs/settings.service.d.ts +59 -14
  201. package/dist/orgs/settings.service.js +102 -20
  202. package/dist/overrides.d.ts +7 -7
  203. package/dist/overrides.js +4 -4
  204. package/dist/packages/tgz.d.ts +0 -2
  205. package/dist/packages/tgz.js +0 -2
  206. package/dist/platform/exclusions.js +0 -5
  207. package/dist/platform/operation.js +1 -1
  208. package/dist/platform/ops/admin.ops.d.ts +2 -2
  209. package/dist/platform/ops/admin.ops.js +9 -6
  210. package/dist/platform/ops/agents.ops.js +1 -1
  211. package/dist/platform/ops/connectors.ops.js +46 -1
  212. package/dist/platform/ops/evals.ops.js +1 -64
  213. package/dist/platform/ops/extensions-admin.ops.js +1 -1
  214. package/dist/platform/ops/inbox.ops.js +16 -3
  215. package/dist/platform/ops/org-plugins.ops.js +1 -1
  216. package/dist/platform/ops/orgs.ops.d.ts +11 -3
  217. package/dist/platform/ops/orgs.ops.js +139 -5
  218. package/dist/platform/ops/outbox.ops.js +5 -5
  219. package/dist/platform/route-schemas.js +3 -0
  220. package/dist/roles/worker-role.d.ts +2 -3
  221. package/dist/roles/worker-role.js +3 -13
  222. package/dist/runtime/checkpointer.d.ts +3 -0
  223. package/dist/runtime/checkpointer.js +7 -4
  224. package/dist/runtime/context/build.d.ts +56 -18
  225. package/dist/runtime/context/build.js +143 -50
  226. package/dist/runtime/context/compaction.d.ts +1 -3
  227. package/dist/runtime/context/compaction.js +42 -8
  228. package/dist/runtime/context/run-context.js +1 -2
  229. package/dist/runtime/context/skills.d.ts +27 -56
  230. package/dist/runtime/context/skills.js +42 -114
  231. package/dist/runtime/context/tool-changes.d.ts +3 -3
  232. package/dist/runtime/context/tool-changes.js +6 -16
  233. package/dist/runtime/hook-calls.d.ts +6 -6
  234. package/dist/runtime/hook-calls.js +7 -7
  235. package/dist/runtime/langgraph-loop.js +9 -3
  236. package/dist/runtime/maintenance.d.ts +3 -11
  237. package/dist/runtime/maintenance.js +5 -20
  238. package/dist/runtime/model-call.d.ts +5 -0
  239. package/dist/runtime/model-call.js +48 -36
  240. package/dist/runtime/providers.d.ts +33 -35
  241. package/dist/runtime/providers.js +64 -109
  242. package/dist/runtime/run-context.service.js +7 -22
  243. package/dist/runtime/run-deletion.d.ts +6 -0
  244. package/dist/runtime/run-deletion.js +39 -16
  245. package/dist/runtime/run-execution.d.ts +56 -3
  246. package/dist/runtime/run-execution.js +81 -11
  247. package/dist/runtime/run-finish.js +2 -1
  248. package/dist/runtime/run-liveness.d.ts +11 -0
  249. package/dist/runtime/run-liveness.js +19 -0
  250. package/dist/runtime/run-orphan-check.job.js +2 -1
  251. package/dist/runtime/run-queue.js +8 -16
  252. package/dist/runtime/run-worker.d.ts +2 -2
  253. package/dist/runtime/run-worker.js +8 -6
  254. package/dist/runtime/step-log.d.ts +5 -0
  255. package/dist/runtime/step-log.js +9 -4
  256. package/dist/runtime/subagents/definition.d.ts +16 -20
  257. package/dist/runtime/subagents/definition.js +27 -27
  258. package/dist/runtime/subagents/dispatch.d.ts +6 -2
  259. package/dist/runtime/subagents/dispatch.js +17 -3
  260. package/dist/runtime/subagents/org-agents.js +1 -2
  261. package/dist/runtime/subagents/preamble.d.ts +3 -2
  262. package/dist/runtime/subagents/preamble.js +3 -2
  263. package/dist/runtime/subagents/render.d.ts +1 -2
  264. package/dist/runtime/subagents/render.js +1 -2
  265. package/dist/runtime/subagents/skill-fork.d.ts +2 -4
  266. package/dist/runtime/subagents/template-skills.d.ts +47 -0
  267. package/dist/runtime/subagents/template-skills.js +76 -0
  268. package/dist/runtime/waits.js +3 -1
  269. package/dist/schedules/effective-settings.d.ts +9 -3
  270. package/dist/schedules/effective-settings.js +5 -4
  271. package/dist/schedules/fire.js +11 -0
  272. package/dist/schedules/scheduled-tasks.service.js +5 -0
  273. package/dist/schedules/unattended.d.ts +2 -0
  274. package/dist/schedules/unattended.js +6 -1
  275. package/dist/skills/agent-skills.service.js +1 -2
  276. package/dist/skills/catalog.d.ts +1 -3
  277. package/dist/skills/catalog.js +1 -3
  278. package/dist/skills/conversation-catalog.d.ts +1 -2
  279. package/dist/skills/conversation-catalog.js +1 -2
  280. package/dist/skills/usable.js +2 -3
  281. package/dist/storage/storage.service.js +9 -1
  282. package/dist/tools/approvals.service.js +2 -4
  283. package/dist/tools/builtin-names.d.ts +2 -9
  284. package/dist/tools/builtin-names.js +4 -13
  285. package/dist/tools/builtins/sandbox/bash.js +3 -3
  286. package/dist/tools/builtins/sandbox/common.d.ts +7 -13
  287. package/dist/tools/builtins/sandbox/common.js +8 -115
  288. package/dist/tools/builtins/sandbox/fetch-attachment.d.ts +10 -0
  289. package/dist/tools/builtins/sandbox/fetch-attachment.js +119 -0
  290. package/dist/tools/builtins/sandbox/glob.js +1 -3
  291. package/dist/tools/builtins/sandbox/grep.js +3 -5
  292. package/dist/tools/builtins/sandbox/index.d.ts +8 -5
  293. package/dist/tools/builtins/sandbox/index.js +10 -5
  294. package/dist/tools/builtins/sandbox/read.js +3 -2
  295. package/dist/tools/builtins/tool-search.d.ts +4 -7
  296. package/dist/tools/builtins/tool-search.js +6 -10
  297. package/dist/tools/connector-account-policies.d.ts +30 -3
  298. package/dist/tools/connector-account-policies.js +54 -7
  299. package/dist/tools/connector-content.js +1 -0
  300. package/dist/tools/connectors.controller.d.ts +24 -11
  301. package/dist/tools/connectors.controller.js +35 -6
  302. package/dist/tools/connectors.schemas.d.ts +14 -1
  303. package/dist/tools/connectors.schemas.js +14 -2
  304. package/dist/tools/connectors.service.d.ts +22 -0
  305. package/dist/tools/connectors.service.js +65 -6
  306. package/dist/tools/drift.d.ts +6 -2
  307. package/dist/tools/drift.js +10 -5
  308. package/dist/tools/git-push-policy.d.ts +4 -1
  309. package/dist/tools/git-push-policy.js +3 -1
  310. package/dist/tools/info.d.ts +1 -7
  311. package/dist/tools/info.js +5 -18
  312. package/dist/tools/job-ids.d.ts +0 -4
  313. package/dist/tools/job-ids.js +1 -6
  314. package/dist/tools/pipeline.d.ts +4 -10
  315. package/dist/tools/pipeline.js +17 -62
  316. package/dist/tools/policy.d.ts +6 -2
  317. package/dist/tools/policy.js +14 -12
  318. package/dist/tools/registry.js +1 -5
  319. package/dist/ui/views.d.ts +5 -5
  320. package/dist/ui/views.js +10 -16
  321. package/package.json +3 -3
  322. package/src/migrations/0137_audit_org_idx.sql +5 -0
  323. package/src/migrations/0138_plugin_install_status_no_upgrading.sql +18 -0
  324. package/src/migrations/0139_retire_legacy_forms.sql +183 -0
  325. package/src/migrations/0140_retire_history_forms.sql +148 -0
  326. package/src/migrations/0141_install_ledger_promoted_rows.sql +36 -0
  327. package/src/migrations/0142_backfill_event_fields.sql +74 -0
  328. package/src/migrations/0143_backfill_model_call_fields.sql +105 -0
  329. package/src/migrations/0144_retire_frozen_definition_keys.sql +163 -0
  330. package/src/migrations/0145_org_network_allowances.sql +12 -0
  331. package/dist/admin/platform-audit.service.d.ts +0 -41
  332. package/dist/conversations/job-ids.d.ts +0 -6
  333. package/dist/conversations/job-ids.js +0 -6
  334. package/dist/extensions/job-ids.d.ts +0 -6
  335. package/dist/extensions/job-ids.js +0 -6
  336. package/dist/infra/queue/retired-schedulers.d.ts +0 -7
  337. package/dist/infra/queue/retired-schedulers.js +0 -9
  338. package/dist/orgs/job-ids.d.ts +0 -8
  339. package/dist/orgs/job-ids.js +0 -8
  340. package/dist/runtime/context/legacy-text.d.ts +0 -22
  341. package/dist/runtime/context/legacy-text.js +0 -37
  342. package/dist/runtime/job-ids.d.ts +0 -10
  343. package/dist/runtime/job-ids.js +0 -10
  344. package/dist/runtime/retired-schedulers.d.ts +0 -7
  345. package/dist/runtime/retired-schedulers.js +0 -31
  346. package/dist/storage/job-ids.d.ts +0 -6
  347. package/dist/storage/job-ids.js +0 -6
  348. package/dist/tools/legacy-data.d.ts +0 -34
  349. package/dist/tools/legacy-data.js +0 -76
  350. package/dist/tools/legacy-keys.d.ts +0 -51
  351. package/dist/tools/legacy-keys.js +0 -114
@@ -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({
@@ -1,5 +1,6 @@
1
1
  import { KernelDb } from "../infra/database/kernel-db.js";
2
2
  import { TransactionHost } from "../infra/database/transaction-host.js";
3
+ import { XactLock } from "../infra/database/xact-lock.js";
3
4
  export interface ExecutionClaim {
4
5
  runId: string;
5
6
  conversationId: string;
@@ -7,17 +8,69 @@ export interface ExecutionClaim {
7
8
  rootId: string;
8
9
  executionId: string;
9
10
  }
11
+ /**
12
+ * Runs `fn` (a tool step, a sub-agent dispatch) with every fenced transaction it opens admitted
13
+ * exclusively, even one that asks for shared admission (an event append made by a tool). Tool code
14
+ * takes org-level locks (`OrgLock`, agents, memberships, devices) after the conversation rows,
15
+ * which only the exclusive admission (the org row first) keeps in the global lock order; a
16
+ * transaction asking for shared admission takes none (an org-level lock in one throws,
17
+ * `assertNotSharedAdmission`), so this scope is not what keeps the order: it keeps tool steps
18
+ * serialized per org as the design states, and is defence in depth for a write a tool makes
19
+ * through a path marked shared.
20
+ */
21
+ export declare function withExclusiveAdmission<T>(fn: () => Promise<T>): Promise<T>;
22
+ /**
23
+ * Whether the caller runs inside {@link withExclusiveAdmission} (a tool step, a dispatch). A test
24
+ * seam: the kernel never reads it (the fence reads the scope directly); tests use it to prove which
25
+ * loop steps run under exclusive admission (`langgraph-loop.test.ts`).
26
+ */
27
+ export declare function inExclusiveAdmission(): boolean;
10
28
  /** Internal interruption: a revoked execution must never write its own terminal failure. */
11
29
  export declare class ExecutionRevoked extends Error {
12
30
  constructor();
13
31
  }
14
- /** Claims serialize on the same conversation lock as the event log and all fenced writes. */
32
+ /**
33
+ * Claims serialize on the same conversation lock as the event log and all fenced writes.
34
+ *
35
+ * The fence admits every writable transaction of a claimed run in one of two modes, then locks the
36
+ * root and the current conversation rows `FOR NO KEY UPDATE` and compares `runs.execution_id`:
37
+ * - **exclusive** (the default, and every transaction inside a tool step,
38
+ * {@link withExclusiveAdmission}: conformance with the design and defence in depth): the org row
39
+ * `FOR NO KEY UPDATE`, `OrgLock`'s mode. These
40
+ * transactions serialize per org with each other and with org admin writes, so whatever they
41
+ * lock after the conversation rows (`OrgLock`, agents, memberships, the default device) stays in
42
+ * the order org row → conversations that offboarding and the decisions take.
43
+ * - **shared** (a transaction opened with `admission: "shared"`: the run loop's event appends,
44
+ * checkpoint writes and suspend): the org admission lock shared
45
+ * (`XactLock.admitOrgShared`), and the org row read without a lock. These transactions lock
46
+ * nothing org-level after the conversation rows (enforced: `OrgLock`, the membership locks and
47
+ * `XactLock.lock` throw in one, `assertNotSharedAdmission`; only READ COMMITTED), so the runs of
48
+ * one org append in parallel.
49
+ * Org deletion and offboarding take the admission lock exclusively first
50
+ * (`OrgLock.lockForRemoval`): they wait for the admitted writes, keep new ones out (a later one
51
+ * then sees the org deleted), and are not starved by a stream of them (the lock queues fairly).
52
+ *
53
+ * Global order: org admission lock → org row → root conversation → conversation; a writer that
54
+ * locks several conversation or run rows of one tree locks the tree's root first (the fence
55
+ * does, so every fenced write of a tree serializes on its root). A claim never
56
+ * opens a nested fenced `requires_new` transaction (shared or not) and waits for it while its
57
+ * outer fenced transaction is open: the inner one waits for the outer's root row (and, behind a
58
+ * queued deletion, for the admission lock) on another connection, which PostgreSQL cannot see as
59
+ * a deadlock.
60
+ */
15
61
  export declare class RunExecution {
16
62
  private readonly db;
63
+ private readonly xactLock;
17
64
  readonly txHost: TransactionHost;
18
- constructor(db: KernelDb, txHost: TransactionHost);
65
+ constructor(db: KernelDb, xactLock: XactLock, txHost: TransactionHost);
19
66
  claim(conversationId: string, runId: string, executionId: string, live?: () => boolean): Promise<ExecutionClaim | null>;
20
67
  withClaim<T>(claim: ExecutionClaim, live: () => boolean, fn: () => Promise<T>): Promise<T>;
21
- /** Org, root, current conversation; allow FK references while excluding deletion and writes. */
68
+ /**
69
+ * The admission (see the class), then the root and the current conversation; NO KEY UPDATE
70
+ * allows foreign key references while excluding deletion and other writers. The root stays
71
+ * `FOR NO KEY UPDATE` in both modes: a sub-agent's handback appends to its parent (the root at
72
+ * depth 1) under `FOR UPDATE`, so two siblings holding the root only shared would deadlock
73
+ * upgrading it.
74
+ */
22
75
  private lockLiveConversation;
23
76
  }