@capybara-hq/kernel 0.1.0-rc.121 → 0.1.0-rc.123

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 (230) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/background/finish.d.ts +5 -1
  3. package/dist/background/finish.js +29 -18
  4. package/dist/background/launch.d.ts +0 -5
  5. package/dist/background/launch.js +1 -6
  6. package/dist/background/managed.js +1 -4
  7. package/dist/background/poll.job.d.ts +3 -25
  8. package/dist/background/poll.job.js +20 -112
  9. package/dist/background/render.d.ts +2 -8
  10. package/dist/background/render.js +3 -17
  11. package/dist/background/stop.d.ts +15 -16
  12. package/dist/background/stop.js +39 -76
  13. package/dist/background/store.d.ts +17 -45
  14. package/dist/background/store.js +60 -94
  15. package/dist/background/tasks.service.d.ts +2 -5
  16. package/dist/background/tasks.service.js +9 -20
  17. package/dist/background/wake.js +3 -2
  18. package/dist/catalog/admin-catalog.controller.d.ts +2 -18
  19. package/dist/catalog/admin-catalog.controller.js +2 -28
  20. package/dist/catalog/catalog-content.d.ts +1 -5
  21. package/dist/catalog/catalog-items.d.ts +2 -6
  22. package/dist/catalog/catalog-items.js +5 -26
  23. package/dist/catalog/catalog-scope.service.d.ts +1 -121
  24. package/dist/catalog/catalog-scope.service.js +12 -552
  25. package/dist/catalog/catalog.service.d.ts +4 -15
  26. package/dist/catalog/catalog.service.js +7 -35
  27. package/dist/catalog/job-ids.d.ts +0 -18
  28. package/dist/catalog/job-ids.js +0 -20
  29. package/dist/catalog/marketplaces.service.d.ts +1 -1
  30. package/dist/catalog/org-catalog.service.js +6 -20
  31. package/dist/catalog/org-plugin-uploads.controller.d.ts +4 -19
  32. package/dist/catalog/org-plugin-uploads.controller.js +6 -34
  33. package/dist/catalog/org-plugin-uploads.d.ts +3 -10
  34. package/dist/catalog/org-plugin-uploads.js +4 -18
  35. package/dist/catalog/org-plugin-uploads.schemas.js +0 -1
  36. package/dist/catalog/owned-items.d.ts +6 -11
  37. package/dist/catalog/owned-items.js +10 -20
  38. package/dist/catalog/ownership.d.ts +3 -29
  39. package/dist/catalog/ownership.js +4 -54
  40. package/dist/catalog/platform-components.d.ts +5 -11
  41. package/dist/catalog/platform-components.js +8 -15
  42. package/dist/catalog/plugin-import.d.ts +3 -42
  43. package/dist/catalog/plugin-import.js +26 -195
  44. package/dist/catalog/plugin-install.js +1 -6
  45. package/dist/catalog/plugin-package.d.ts +1 -0
  46. package/dist/catalog/plugin-package.js +5 -0
  47. package/dist/catalog/plugin-upgrade.d.ts +3 -26
  48. package/dist/catalog/plugin-upgrade.js +20 -103
  49. package/dist/catalog/request-rules.js +4 -6
  50. package/dist/catalog/scope-sync.js +2 -4
  51. package/dist/catalog/scope.d.ts +2 -5
  52. package/dist/channels/jobs.d.ts +3 -3
  53. package/dist/channels/jobs.js +4 -3
  54. package/dist/channels/outbound.d.ts +1 -0
  55. package/dist/channels/outbound.js +32 -8
  56. package/dist/config/load.d.ts +0 -25
  57. package/dist/config/load.js +0 -57
  58. package/dist/config/schema.js +2 -3
  59. package/dist/conversations/attachments.service.js +3 -5
  60. package/dist/conversations/conversations.service.d.ts +3 -3
  61. package/dist/conversations/conversations.service.js +3 -3
  62. package/dist/conversations/job-org.d.ts +3 -0
  63. package/dist/conversations/job-org.js +11 -0
  64. package/dist/conversations/prompt-suggestions.d.ts +2 -7
  65. package/dist/conversations/prompt-suggestions.js +29 -27
  66. package/dist/conversations/titles.d.ts +3 -4
  67. package/dist/conversations/titles.js +19 -30
  68. package/dist/db/kernel-schema.d.ts +6 -16
  69. package/dist/db/pool.js +7 -2
  70. package/dist/devices/devices.controller.d.ts +0 -5
  71. package/dist/devices/devices.controller.js +2 -20
  72. package/dist/devices/devices.service.d.ts +1 -17
  73. package/dist/devices/devices.service.js +0 -22
  74. package/dist/errors.d.ts +1 -5
  75. package/dist/errors.js +1 -5
  76. package/dist/evals/judge.d.ts +3 -0
  77. package/dist/evals/judge.js +1 -1
  78. package/dist/evals/run-replay.d.ts +1 -1
  79. package/dist/evals/run-replay.js +26 -29
  80. package/dist/evals/step-replay.d.ts +3 -1
  81. package/dist/evals/step-replay.js +10 -1
  82. package/dist/evals/worker.d.ts +3 -1
  83. package/dist/evals/worker.js +53 -21
  84. package/dist/extensions/deployment-config-store.js +18 -14
  85. package/dist/extensions/effective-config.d.ts +1 -5
  86. package/dist/extensions/effective-config.js +1 -5
  87. package/dist/extensions/hooks.d.ts +3 -1
  88. package/dist/extensions/hooks.js +7 -2
  89. package/dist/extensions/installs.d.ts +2 -14
  90. package/dist/extensions/installs.js +10 -32
  91. package/dist/extensions/org-config.d.ts +3 -4
  92. package/dist/extensions/org-config.js +3 -4
  93. package/dist/extensions/plugin-guides.d.ts +0 -1
  94. package/dist/extensions/plugin-guides.js +0 -1
  95. package/dist/extensions/plugin-icons.d.ts +0 -1
  96. package/dist/extensions/plugin-icons.js +0 -3
  97. package/dist/files/blob-sweep.job.d.ts +2 -11
  98. package/dist/files/blob-sweep.job.js +7 -21
  99. package/dist/files/hash-job.d.ts +5 -15
  100. package/dist/files/hash-job.js +14 -33
  101. package/dist/files/library-jobs.module.d.ts +1 -6
  102. package/dist/files/library-jobs.module.js +3 -9
  103. package/dist/identity/api-tokens.js +54 -40
  104. package/dist/identity/auth.guard.js +2 -2
  105. package/dist/identity/sessions.js +7 -3
  106. package/dist/identity/settings.js +5 -21
  107. package/dist/inbox/inbox.service.d.ts +2 -3
  108. package/dist/inbox/org-notices.d.ts +0 -14
  109. package/dist/inbox/platform-inbox.service.d.ts +1 -8
  110. package/dist/inbox/platform-inbox.service.js +2 -6
  111. package/dist/inbox/platform-notices.d.ts +3 -3
  112. package/dist/index.d.ts +0 -4
  113. package/dist/index.js +0 -3
  114. package/dist/infra/database/database.module.js +2 -1
  115. package/dist/infra/database/org-scope.d.ts +5 -3
  116. package/dist/infra/database/org-scope.js +7 -1
  117. package/dist/infra/database/scoped-dialect.d.ts +3 -1
  118. package/dist/infra/database/scoped-dialect.js +17 -5
  119. package/dist/infra/events/kernel-events.d.ts +2 -0
  120. package/dist/infra/outbox/outbox.service.d.ts +2 -0
  121. package/dist/infra/outbox/outbox.service.js +10 -0
  122. package/dist/infra/outbox/registry.d.ts +0 -41
  123. package/dist/infra/outbox/registry.js +0 -37
  124. package/dist/models/embeddings.d.ts +0 -5
  125. package/dist/models/embeddings.js +28 -35
  126. package/dist/models/images.d.ts +3 -8
  127. package/dist/models/images.js +19 -37
  128. package/dist/models/purposes.d.ts +7 -2
  129. package/dist/models/purposes.js +16 -3
  130. package/dist/orgs/device-network-setting.d.ts +0 -44
  131. package/dist/orgs/device-network-setting.js +0 -83
  132. package/dist/orgs/invitations.service.js +34 -30
  133. package/dist/orgs/offboarding.d.ts +2 -2
  134. package/dist/orgs/offboarding.js +2 -2
  135. package/dist/orgs/orgs.service.d.ts +1 -1
  136. package/dist/orgs/orgs.service.js +19 -15
  137. package/dist/orgs/settings.service.d.ts +19 -14
  138. package/dist/orgs/settings.service.js +12 -37
  139. package/dist/platform/exclusions.js +0 -11
  140. package/dist/platform/ops/catalog-admin.ops.js +0 -8
  141. package/dist/platform/ops/devices.ops.js +0 -28
  142. package/dist/platform/ops/extensions-admin.ops.js +3 -3
  143. package/dist/platform/ops/inbox.ops.js +5 -22
  144. package/dist/platform/ops/org-plugins.ops.d.ts +1 -3
  145. package/dist/platform/ops/org-plugins.ops.js +11 -67
  146. package/dist/roles/worker.module.js +0 -9
  147. package/dist/runtime/hook-calls.d.ts +13 -6
  148. package/dist/runtime/hook-calls.js +26 -4
  149. package/dist/runtime/maintenance.d.ts +3 -12
  150. package/dist/runtime/maintenance.js +25 -55
  151. package/dist/runtime/model-call.d.ts +4 -2
  152. package/dist/runtime/model-call.js +59 -58
  153. package/dist/runtime/providers.d.ts +27 -1
  154. package/dist/runtime/providers.js +57 -0
  155. package/dist/runtime/run-jobs.d.ts +1 -1
  156. package/dist/runtime/run-processors.d.ts +3 -9
  157. package/dist/runtime/run-worker.d.ts +2 -0
  158. package/dist/runtime/run-worker.js +23 -8
  159. package/dist/runtime/subagents/deliveries.js +6 -1
  160. package/dist/runtime/subagents/dispatch.d.ts +3 -3
  161. package/dist/runtime/write-base.service.d.ts +2 -3
  162. package/dist/runtime/write-base.service.js +3 -5
  163. package/dist/sandbox/device-sandbox-settings.d.ts +38 -92
  164. package/dist/sandbox/device-sandbox-settings.js +19 -325
  165. package/dist/sandbox/jobs.d.ts +3 -14
  166. package/dist/sandbox/jobs.js +2 -20
  167. package/dist/sandbox/modes.d.ts +5 -45
  168. package/dist/sandbox/modes.js +3 -60
  169. package/dist/sandbox/operation-authority.js +0 -11
  170. package/dist/sandbox/operation-intents.d.ts +32 -9
  171. package/dist/sandbox/operation-intents.js +241 -32
  172. package/dist/sandbox/operation-intents.module.js +2 -1
  173. package/dist/sandbox/operation-reconcile.job.d.ts +9 -11
  174. package/dist/sandbox/operation-reconcile.job.js +119 -33
  175. package/dist/sandbox/operation-revoke.d.ts +20 -0
  176. package/dist/sandbox/operation-revoke.js +3 -0
  177. package/dist/sandbox/permission-ceiling-writes.d.ts +1 -2
  178. package/dist/sandbox/permission-ceiling-writes.js +3 -6
  179. package/dist/sandbox/permission-config-publication.d.ts +1 -28
  180. package/dist/sandbox/permission-config-publication.js +14 -211
  181. package/dist/sandbox/permission-facts.d.ts +4 -15
  182. package/dist/sandbox/permission-facts.js +7 -29
  183. package/dist/sandbox/permission-instance-writes.d.ts +1 -4
  184. package/dist/sandbox/permission-instance-writes.js +1 -55
  185. package/dist/sandbox/providers.d.ts +1 -6
  186. package/dist/sandbox/providers.js +1 -15
  187. package/dist/sandbox/review/classifier.js +12 -13
  188. package/dist/sandbox/sandbox.module.js +3 -6
  189. package/dist/sandbox/sandbox.service.d.ts +17 -123
  190. package/dist/sandbox/sandbox.service.js +239 -998
  191. package/dist/shares/liveness.d.ts +1 -2
  192. package/dist/shares/liveness.js +1 -2
  193. package/dist/shares/shares.module.d.ts +1 -2
  194. package/dist/shares/shares.module.js +2 -5
  195. package/dist/shares/shares.service.js +1 -2
  196. package/dist/tools/builtins/image/generate.js +7 -15
  197. package/dist/tools/builtins/sandbox/common.d.ts +0 -2
  198. package/dist/tools/builtins/sandbox/common.js +1 -27
  199. package/dist/tools/builtins/sandbox/task-list.js +10 -10
  200. package/dist/tools/builtins/sandbox/task-output.d.ts +3 -10
  201. package/dist/tools/builtins/sandbox/task-output.js +13 -83
  202. package/dist/tools/builtins/sandbox/task-stop.js +18 -22
  203. package/dist/tools/builtins/vision/read-image.js +9 -10
  204. package/dist/tools/builtins/web/extract.js +9 -10
  205. package/package.json +3 -3
  206. package/src/migrations/0206_retire_org_extension_uploads.sql +125 -0
  207. package/src/migrations/0207_confirm_device_instance_destruction.sql +25 -0
  208. package/src/migrations/0208_convert_stored_permission_settings.sql +189 -0
  209. package/dist/background/retire-legacy-tasks.job.d.ts +0 -57
  210. package/dist/background/retire-legacy-tasks.job.js +0 -149
  211. package/dist/catalog/owned-plugin-cleanup.d.ts +0 -47
  212. package/dist/catalog/owned-plugin-cleanup.js +0 -140
  213. package/dist/config/permission-migration.d.ts +0 -34
  214. package/dist/config/permission-migration.js +0 -115
  215. package/dist/devices/legacy-cleanup.job.d.ts +0 -34
  216. package/dist/devices/legacy-cleanup.job.js +0 -147
  217. package/dist/files/library-backfill.d.ts +0 -63
  218. package/dist/files/library-backfill.js +0 -143
  219. package/dist/infra/cli/permission-cutover.d.ts +0 -59
  220. package/dist/infra/cli/permission-cutover.js +0 -107
  221. package/dist/sandbox/cloud-permission-snapshot.d.ts +0 -159
  222. package/dist/sandbox/cloud-permission-snapshot.js +0 -430
  223. package/dist/sandbox/cloud-permission-snapshot.module.d.ts +0 -8
  224. package/dist/sandbox/cloud-permission-snapshot.module.js +0 -34
  225. package/dist/sandbox/legacy-retirement.d.ts +0 -284
  226. package/dist/sandbox/legacy-retirement.js +0 -1165
  227. package/dist/sandbox/legacy-retirement.module.d.ts +0 -8
  228. package/dist/sandbox/legacy-retirement.module.js +0 -25
  229. package/dist/shares/share-objects.d.ts +0 -47
  230. package/dist/shares/share-objects.js +0 -93
@@ -15,10 +15,10 @@ import { hasProjectSkills, overlongProjectSkills } from "./context/project-root.
15
15
  import { TOOLS_UNSUPPORTED_REMINDER, turnLimitReminder } from "./context/reminders.js";
16
16
  import { calibrate, estimateTokens } from "./context/tokens.js";
17
17
  import { toolSetChange } from "./context/tool-changes.js";
18
- import { fireObserve, hookDeniedAudit, hookDeniedEvent, hookRequestOf, hookScope, recordHookDenial, } from "./hook-calls.js";
18
+ import { fireObserve, hookDeniedAudit, hookDeniedEvent, hookScope, recordHookDenial, } from "./hook-calls.js";
19
19
  import { MediaCache } from "./media-cache.js";
20
20
  import { PERMISSION_CONTEXT_RUN_ERRORS, permissionContextFailureKind, permissionContextKindOfCode, } from "./permission-context-errors.js";
21
- import { ProviderListError } from "./providers.js";
21
+ import { ModelRequestDenied, ProviderListError, prepareModelStream, } from "./providers.js";
22
22
  import { ExecutionRevoked } from "./run-execution.js";
23
23
  import { budgetRunOf, subagentBudgetUsedUp } from "./subagents/limits.js";
24
24
  import { writeBaseViewOf, writeBaseWatcher } from "./write-base.js";
@@ -1194,30 +1194,32 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
1194
1194
  retry,
1195
1195
  params: summarizer.params,
1196
1196
  });
1197
- if (hookBase && deps.hooks?.has("model.request")) {
1198
- let verdict;
1199
- try {
1200
- verdict = await deps.hooks.run("model.request", { ...hookBase, attempt: retry ? 2 : 1, request: hookRequestOf(request, deps.log) }, signal);
1201
- }
1202
- catch (e) {
1203
- // run() rejects only when the run's signal aborted: an abort, never a deny
1204
- if (signal.aborted) {
1205
- // an aborted attempt leaves no partial summary: drop the progress key now rather than
1206
- // leaving the writer-local throttle entry behind until the TTL (folded review Minor)
1207
- deps.compactionProgress?.clear(runId);
1208
- throw new StepAborted();
1209
- }
1210
- throw e;
1211
- }
1212
- if (!verdict.allowed) {
1213
- denial = { verdict, chunk: chunkNo };
1214
- break;
1197
+ let stream;
1198
+ try {
1199
+ stream = await prepareModelStream(provider, request, {
1200
+ ...ref,
1201
+ orgId: input.orgId,
1202
+ purpose: input.conversationKind === "eval" ? "eval" : "compaction",
1203
+ scope,
1204
+ step,
1205
+ attempt: retry ? 2 : 1,
1206
+ hooks: deps.modelRequestHooks ?? deps.hooks,
1207
+ }, signal, deps.log);
1208
+ }
1209
+ catch (err) {
1210
+ if (signal.aborted) {
1211
+ deps.compactionProgress?.clear(runId);
1212
+ throw new StepAborted();
1215
1213
  }
1214
+ if (!(err instanceof ModelRequestDenied))
1215
+ throw err;
1216
+ denial = { verdict: err.verdict, chunk: chunkNo };
1217
+ break;
1216
1218
  }
1217
1219
  const sentAt = Date.now();
1218
1220
  try {
1219
1221
  let partial = "";
1220
- const out = await consumeModelStream(provider, request, info.streamIdleTimeoutMs ?? runtime.streamIdleMs, signal, (ev) => {
1222
+ const out = await consumeModelStream(stream, request.model, info.streamIdleTimeoutMs ?? runtime.streamIdleMs, signal, (ev) => {
1221
1223
  if (ev.type !== "text_delta")
1222
1224
  return;
1223
1225
  partial += ev.text;
@@ -1344,7 +1346,10 @@ export async function runCompaction(deps, input, events, runtime, compaction, to
1344
1346
  };
1345
1347
  const denied = hookDeniedEvent(site, "model.request", verdict, { step, attempt: 1 });
1346
1348
  const entry = hookDeniedAudit(site, denied.payload, verdict);
1347
- entry.detail = { ...entry.detail, purpose: "compaction" };
1349
+ entry.detail = {
1350
+ ...entry.detail,
1351
+ purpose: input.conversationKind === "eval" ? "eval" : "compaction",
1352
+ };
1348
1353
  const failed = {
1349
1354
  type: "compaction_failed",
1350
1355
  runId,
@@ -1668,38 +1673,34 @@ longTtl, tools, wrapUpReason, streamed) {
1668
1673
  request.maxOutputTokens = sentOutputCap(info.contextWindow, output, sentEstimate, compaction.reserveTokens);
1669
1674
  const sentRequest = planned === null ? request : applyFit(request, planned);
1670
1675
  sentMedia = (meta.media ?? []).flatMap((m) => m.outcome === "bytes" ? [m.attachmentId] : []);
1671
- // model.request before model_call: a denied request is never logged as sent nor sent (a denial
1672
- // logged before a crash is sticky: runStep checks it before compaction)
1673
- if (scope && deps.hooks?.has("model.request")) {
1674
- let verdict;
1675
- try {
1676
- verdict = await deps.hooks.run("model.request", {
1677
- ...scope,
1678
- purpose: "step",
1679
- step,
1680
- attempt,
1681
- provider: rung.ref.provider,
1682
- model: rung.ref.model,
1683
- request: hookRequestOf(sentRequest, deps.log),
1684
- }, signal);
1685
- }
1686
- catch (e) {
1687
- // run() rejects only when the run's signal aborted: an abort, never a deny
1688
- if (signal.aborted)
1689
- throw new StepAborted();
1690
- throw e;
1691
- }
1692
- if (!verdict.allowed) {
1693
- await recordHookDenial(deps, {
1694
- orgId: input.orgId,
1695
- conversationId,
1696
- runId,
1697
- ...(input.accountId !== undefined && { accountId: input.accountId }),
1698
- ...(input.agentId !== undefined && { agentId: input.agentId }),
1699
- idemKey: idem.hookDenied(runId, step, attempt),
1700
- }, "model.request", verdict, { step, attempt });
1701
- throw new RunError("run.hook_denied", modelDeniedText(verdict.plugin, verdict.reason));
1702
- }
1676
+ // Record the request only after policy allowed it, before opening the provider stream.
1677
+ let stream;
1678
+ try {
1679
+ stream = await prepareModelStream(provider, sentRequest, {
1680
+ ...rung.ref,
1681
+ orgId: input.orgId,
1682
+ purpose: input.conversationKind === "eval" ? "eval" : "step",
1683
+ scope,
1684
+ step,
1685
+ attempt,
1686
+ hooks: deps.modelRequestHooks ?? deps.hooks,
1687
+ }, signal, deps.log);
1688
+ }
1689
+ catch (err) {
1690
+ if (signal.aborted)
1691
+ throw new StepAborted();
1692
+ if (!(err instanceof ModelRequestDenied))
1693
+ throw err;
1694
+ const { verdict } = err;
1695
+ await recordHookDenial(deps, {
1696
+ orgId: input.orgId,
1697
+ conversationId,
1698
+ runId,
1699
+ ...(input.accountId !== undefined && { accountId: input.accountId }),
1700
+ ...(input.agentId !== undefined && { agentId: input.agentId }),
1701
+ idemKey: idem.hookDenied(runId, step, attempt),
1702
+ }, "model.request", verdict, { step, attempt, ...(input.conversationKind === "eval" && { purpose: "eval" }) });
1703
+ throw new RunError("run.hook_denied", modelDeniedText(verdict.plugin, verdict.reason));
1703
1704
  }
1704
1705
  // 请求里的工具定义(含目录里的)按指纹存进 tool_specs,与 model_call 同一事务
1705
1706
  // (请求可由日志 + tool_specs 还原)
@@ -1733,7 +1734,7 @@ longTtl, tools, wrapUpReason, streamed) {
1733
1734
  const bases = baseWatcher(deps, input, tools, baseStop.signal, rung.ref);
1734
1735
  let outcome;
1735
1736
  try {
1736
- outcome = await consumeModelStream(provider, sentRequest, info.streamIdleTimeoutMs ?? runtime.streamIdleMs, signal, (ev) => {
1737
+ outcome = await consumeModelStream(stream, sentRequest.model, info.streamIdleTimeoutMs ?? runtime.streamIdleMs, signal, (ev) => {
1737
1738
  if (ev.type === "text_delta") {
1738
1739
  streamed.text += ev.text;
1739
1740
  sink({ kind: "text", runId, step, text: ev.text });
@@ -2080,7 +2081,7 @@ export function trustedUsage(usage, model, log) {
2080
2081
  * The usage goes through {@link trustedUsage}, so a malformed `cacheWriteByTtl` never fails a call
2081
2082
  * after the model replied.
2082
2083
  */
2083
- export async function consumeModelStream(provider, request, idleMs, signal, onDelta,
2084
+ export async function consumeModelStream(stream, model, idleMs, signal, onDelta,
2084
2085
  /** Where a dropped `cacheWriteByTtl` is reported. */
2085
2086
  log) {
2086
2087
  if (signal.aborted)
@@ -2110,7 +2111,7 @@ log) {
2110
2111
  let it;
2111
2112
  try {
2112
2113
  arm();
2113
- it = provider.stream(request, { signal: local.signal })[Symbol.asyncIterator]();
2114
+ it = stream(local.signal)[Symbol.asyncIterator]();
2114
2115
  for (;;) {
2115
2116
  const next = it.next();
2116
2117
  next.catch(() => { });
@@ -2123,7 +2124,7 @@ log) {
2123
2124
  return {
2124
2125
  content: ev.content,
2125
2126
  stopReason: ev.stopReason,
2126
- usage: trustedUsage(ev.usage, request.model, log),
2127
+ usage: trustedUsage(ev.usage, model, log),
2127
2128
  };
2128
2129
  }
2129
2130
  onDelta(ev);
@@ -1,4 +1,4 @@
1
- import { type EmbedRequest, type EmbedResult, type ExtensionManifest, type ExtensionPointRef, type ImageGenerateRequest, type ImageGenerateResult, type Logger, type ModelErrorKind, type ModelInfo, type ModelKind, type ModelRequest, type ModelStreamEvent } from "@capybara-hq/plugin-sdk";
1
+ import { type EmbeddingRequestHookPayload, type EmbedRequest, type EmbedResult, type ExtensionManifest, type ExtensionPointRef, type HookScope, type ImageGenerateRequest, type ImageGenerateResult, type ImageRequestHookPayload, type Logger, type ModelCallRequestHookPayload, type ModelErrorKind, 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";
@@ -6,6 +6,7 @@ import { EffectiveConfigs } from "../extensions/effective-config.js";
6
6
  import { CacheService } from "../infra/cache/cache.service.js";
7
7
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
8
8
  import { ModelEnablement } from "../models/enablement.js";
9
+ import { type HookDenial, type HookRunner } from "./hook-calls.js";
9
10
  /**
10
11
  * Optional provider: the `listModels()` time limit (ms) instead of the config's
11
12
  * `models.listTimeoutMs` (tests).
@@ -78,6 +79,30 @@ export interface BoundProvider {
78
79
  signal: AbortSignal;
79
80
  }): Promise<ImageGenerateResult>;
80
81
  }
82
+ export declare class ModelRequestDenied extends ApiError {
83
+ readonly verdict: HookDenial;
84
+ constructor(verdict: HookDenial);
85
+ }
86
+ interface RequestSite {
87
+ orgId: string;
88
+ provider: string;
89
+ model: string;
90
+ hooks: HookRunner | undefined;
91
+ }
92
+ export interface ChatRequestSite extends RequestSite {
93
+ purpose: ModelCallRequestHookPayload["purpose"] | "eval";
94
+ scope?: HookScope | null | undefined;
95
+ step: number;
96
+ attempt: number;
97
+ }
98
+ /** Opens one provider stream after the exact request has passed policy. */
99
+ export declare function prepareModelStream(provider: BoundProvider, request: ModelRequest, site: ChatRequestSite, signal: AbortSignal, log?: Pick<Logger, "warn">): Promise<(signal: AbortSignal) => AsyncIterable<ModelStreamEvent>>;
100
+ /** Wraps a stream for metering within the provider boundary. */
101
+ export declare function mapProviderStream(provider: BoundProvider, map: (request: ModelRequest, stream: () => AsyncIterable<ModelStreamEvent>) => AsyncIterable<ModelStreamEvent>): BoundProvider;
102
+ export declare function supportsEmbedding(provider: BoundProvider): boolean;
103
+ /** Authorizes all input texts before the caller splits them into provider batches. */
104
+ export declare function prepareEmbedding(provider: BoundProvider, payload: EmbeddingRequestHookPayload, hooks: HookRunner | undefined, signal: AbortSignal): Promise<NonNullable<BoundProvider["embed"]>>;
105
+ export declare function prepareImageGeneration(provider: BoundProvider, payload: () => ImageRequestHookPayload, hooks: HookRunner | undefined, signal: AbortSignal, ref: ModelRef): Promise<NonNullable<BoundProvider["generateImage"]>>;
81
106
  /**
82
107
  * 一个供应商在后台的视图:供应商名即插件名;`status: "error"` 时 `models` 为空、`error` 为内核的说明。
83
108
  * `org_configured` (the platform view only): the platform config leaves a required overridable
@@ -250,3 +275,4 @@ export declare class ProviderRegistry {
250
275
  /** The model provider registry (one instance; the models and agents domains read it). */
251
276
  export declare class ProvidersModule {
252
277
  }
278
+ export {};
@@ -21,6 +21,7 @@ import { Cacheable } from "../infra/cache/cacheable.decorator.js";
21
21
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
22
22
  import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
23
23
  import { ModelEnablement, ModelEnablementModule, modelKey } from "../models/enablement.js";
24
+ import { hookRequestOf } from "./hook-calls.js";
24
25
  /** 供应商模型列表在 Redis 中的缓存时长(秒)。 */
25
26
  const MODELS_TTL_SECONDS = 600;
26
27
  /**
@@ -112,6 +113,62 @@ function bindProvider(impl, call) {
112
113
  }
113
114
  return bound;
114
115
  }
116
+ export class ModelRequestDenied extends ApiError {
117
+ verdict;
118
+ constructor(verdict) {
119
+ super("model.hook_denied", verdict.reason);
120
+ this.verdict = verdict;
121
+ }
122
+ }
123
+ async function authorizeModelRequest(hooks, payload, signal, policyOnly = false) {
124
+ signal.throwIfAborted();
125
+ if (!hooks?.has("model.request"))
126
+ return;
127
+ const request = payload();
128
+ const verdict = policyOnly
129
+ ? await hooks.run("model.request", request, signal, { policyOnly: true })
130
+ : await hooks.run("model.request", request, signal);
131
+ if (!verdict.allowed)
132
+ throw new ModelRequestDenied(verdict);
133
+ signal.throwIfAborted();
134
+ }
135
+ /** Opens one provider stream after the exact request has passed policy. */
136
+ export async function prepareModelStream(provider, request, site, signal, log) {
137
+ const { hooks, scope, purpose, ...fields } = site;
138
+ await authorizeModelRequest(hooks, () => {
139
+ const payload = { ...fields, request: hookRequestOf(request, log) };
140
+ return scope && purpose !== "eval"
141
+ ? { ...scope, ...payload, purpose }
142
+ : { ...payload, purpose };
143
+ }, signal, purpose === "eval");
144
+ return (callSignal) => provider.stream(request, { signal: callSignal });
145
+ }
146
+ /** Wraps a stream for metering within the provider boundary. */
147
+ export function mapProviderStream(provider, map) {
148
+ return {
149
+ ...provider,
150
+ stream: (request, opts) => map(request, () => provider.stream(request, opts)),
151
+ };
152
+ }
153
+ export function supportsEmbedding(provider) {
154
+ return typeof provider.embed === "function";
155
+ }
156
+ /** Authorizes all input texts before the caller splits them into provider batches. */
157
+ export async function prepareEmbedding(provider, payload, hooks, signal) {
158
+ const embed = provider.embed?.bind(provider);
159
+ if (!embed)
160
+ throw new ApiError("model.unconfigured", "The model cannot embed");
161
+ await authorizeModelRequest(hooks, () => payload, signal);
162
+ return embed;
163
+ }
164
+ export async function prepareImageGeneration(provider, payload, hooks, signal, ref) {
165
+ const generate = provider.generateImage?.bind(provider);
166
+ if (!generate) {
167
+ throw new ApiError("model.unconfigured", `Model ${ref.provider}/${ref.model} cannot generate images`);
168
+ }
169
+ await authorizeModelRequest(hooks, payload, signal);
170
+ return generate;
171
+ }
115
172
  const positiveInt = (n) => typeof n === "number" && Number.isInteger(n) && n > 0;
116
173
  /**
117
174
  * Whether an embedding model's info is usable: at least one dimension, every dimension and the
@@ -27,7 +27,7 @@ export declare function lockWaitRowsIn(t: KernelSchemaDb, runId: string): Promis
27
27
  approvals: boolean;
28
28
  questions: boolean;
29
29
  }>;
30
- /** 运行任务的数据。 */
30
+ /** Run workers resolve the owning org from the conversation. */
31
31
  export interface RunJobData {
32
32
  runId: string;
33
33
  conversationId: string;
@@ -3,7 +3,7 @@ import { type DynamicModule } from "@nestjs/common";
3
3
  import type { Job, Worker } from "bullmq";
4
4
  import type { KernelConfig } from "../config/schema.js";
5
5
  import { type PromptSuggestionJob, PromptSuggestionQueue } from "../conversations/prompt-suggestions.js";
6
- import { TitleQueue } from "../conversations/titles.js";
6
+ import { type TitleJob, TitleQueue } from "../conversations/titles.js";
7
7
  import { type RUN_JOB, type RunJobData } from "./run-jobs.js";
8
8
  import { RunWorker } from "./run-worker.js";
9
9
  import { type USAGE_REPORT_JOB, UsageReporter, type UsageReportJob } from "./usage-report.js";
@@ -42,16 +42,10 @@ export declare class UsageReportProcessor extends WorkerHost<Worker<UsageReportJ
42
42
  error(err: Error): void;
43
43
  }
44
44
  /** The consumer of `cap-kernel-titles`: {@link TitleQueue}. */
45
- export declare class TitleProcessor extends WorkerHost<Worker<{
46
- conversationId: string;
47
- attempt: number;
48
- }>> {
45
+ export declare class TitleProcessor extends WorkerHost<Worker<TitleJob>> {
49
46
  private readonly titles;
50
47
  constructor(titles: TitleQueue);
51
- process(job: Job<{
52
- conversationId: string;
53
- attempt: number;
54
- }>): Promise<void>;
48
+ process(job: Job<TitleJob>): Promise<void>;
55
49
  error(err: Error): void;
56
50
  }
57
51
  /** The consumer of `cap-kernel-suggestions`: {@link PromptSuggestionQueue}. */
@@ -153,6 +153,7 @@ export declare class RunWorker {
153
153
  * R34 test).
154
154
  */
155
155
  onCompleted(job: Job<RunJobData>, result: ProcessResult): void;
156
+ private inConversationOrg;
156
157
  /** A job failed (the worker's `failed` event). */
157
158
  onFailed(job: Job<RunJobData> | undefined, err: Error): void;
158
159
  /**
@@ -199,6 +200,7 @@ export declare class RunWorker {
199
200
  close(budgetMs: number): Promise<void>;
200
201
  /** One run job (the `@Processor`s of both run queues call it). */
201
202
  process(job: Job<RunJobData>, token: string | undefined): Promise<ProcessResult>;
203
+ private processInOrg;
202
204
  private execute;
203
205
  /**
204
206
  * A compaction run (context compaction spec §4.7, a person's; idle compaction spec §5.1, the
@@ -13,6 +13,7 @@ import { sql } from "kysely";
13
13
  import { normalizeStoredDefinition } from "../agents/definition.js";
14
14
  import { EventLog } from "../conversations/event-log.js";
15
15
  import { isAbsorbable, } from "../conversations/events.js";
16
+ import { resolveConversationOrg } from "../conversations/job-org.js";
16
17
  import { PromptSuggestionQueue } from "../conversations/prompt-suggestions.js";
17
18
  import { effectiveDefinition, NO_SELECTION, readSelection, sameModel, sameSelection, } from "../conversations/selection.js";
18
19
  import { TitleQueue } from "../conversations/titles.js";
@@ -21,6 +22,7 @@ import { SettingsService } from "../identity/settings.js";
21
22
  import { waitWithin } from "../infra/close-within.js";
22
23
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
23
24
  import { KernelDb } from "../infra/database/kernel-db.js";
25
+ import { withOrgScope } from "../infra/database/org-scope.js";
24
26
  import { TransactionHost } from "../infra/database/transaction-host.js";
25
27
  import { Transactional } from "../infra/database/transactional.decorator.js";
26
28
  import { KernelEvents } from "../infra/events/kernel-events.js";
@@ -218,13 +220,18 @@ let RunWorker = class RunWorker {
218
220
  if (result !== "ensure")
219
221
  return;
220
222
  const { conversationId, runId } = job.data;
221
- this.track(this.ensureAfterRun(conversationId, runId));
223
+ this.track(this.inConversationOrg(conversationId, () => this.ensureAfterRun(conversationId, runId)).catch((err) => this.log.error("cannot run completion follow-up", { runId, err })));
224
+ }
225
+ async inConversationOrg(conversationId, handle) {
226
+ const orgId = await resolveConversationOrg(this.db, conversationId);
227
+ if (orgId !== undefined)
228
+ await withOrgScope(orgId, handle);
222
229
  }
223
230
  /** A job failed (the worker's `failed` event). */
224
231
  onFailed(job, err) {
225
232
  this.log.error("run job failed", { jobId: job?.id, runId: job?.data.runId, err });
226
233
  if (job) {
227
- this.track(this.onJobFailed(job.data, err).catch((e) => this.log.error("cannot mark failed run job", { runId: job.data.runId, err: e })));
234
+ this.track(this.inConversationOrg(job.data.conversationId, () => this.onJobFailed(job.data, err)).catch((e) => this.log.error("cannot mark failed run job", { runId: job.data.runId, err: e })));
228
235
  }
229
236
  }
230
237
  /**
@@ -406,9 +413,17 @@ let RunWorker = class RunWorker {
406
413
  }
407
414
  /** One run job (the `@Processor`s of both run queues call it). */
408
415
  async process(job, token) {
409
- const { runId, conversationId } = job.data;
410
416
  if (this.closing)
411
417
  return requeue(job, token, 0);
418
+ const orgId = await resolveConversationOrg(this.db, job.data.conversationId);
419
+ if (orgId === undefined) {
420
+ await this.dropCheckpoints(job.data.runId);
421
+ return;
422
+ }
423
+ return withOrgScope(orgId, () => this.processInOrg(job, token));
424
+ }
425
+ async processInOrg(job, token) {
426
+ const { runId, conversationId } = job.data;
412
427
  const run = await this.db
413
428
  .selectFrom("runs")
414
429
  .select([
@@ -439,7 +454,7 @@ let RunWorker = class RunWorker {
439
454
  if (run.status === "waiting")
440
455
  return;
441
456
  await this.hooks?.afterRunRead?.(runId, conversationId);
442
- // org-filter: the run job's kernel-written conversation id; reads the conversation's own org
457
+ // org-filter: kernel-written conversation id scoped to its resolved org
443
458
  const conv = await this.db
444
459
  .selectFrom("conversations")
445
460
  .select(["org_id", "agent_id", "kind", "subagent_depth", "source", "account_id"])
@@ -943,7 +958,7 @@ let RunWorker = class RunWorker {
943
958
  if (state.leaseLost)
944
959
  return "interrupted";
945
960
  await this.finish(conversationId, runId, "completed", consumed, { type: "run_finished", payload: { reason: outcome.kind, consumedUpToSeq: consumed } }, true, false, idleCompaction);
946
- this.completed(conversationId, runId, outcome.kind);
961
+ this.completed(conv.org_id, conversationId, runId, outcome.kind);
947
962
  break;
948
963
  }
949
964
  default: {
@@ -957,7 +972,7 @@ let RunWorker = class RunWorker {
957
972
  if (state.leaseLost)
958
973
  return "interrupted";
959
974
  await this.finish(conversationId, runId, "completed", consumed, { type: "run_finished", payload: { reason: outcome.kind, consumedUpToSeq: consumed } }, true, true, idleCompaction);
960
- this.completed(conversationId, runId, outcome.kind);
975
+ this.completed(conv.org_id, conversationId, runId, outcome.kind);
961
976
  }
962
977
  }
963
978
  return "finished";
@@ -1087,10 +1102,10 @@ let RunWorker = class RunWorker {
1087
1102
  });
1088
1103
  return "finished";
1089
1104
  }
1090
- completed(conversationId, runId, kind) {
1105
+ completed(orgId, conversationId, runId, kind) {
1091
1106
  // a completed run enqueues the conversation's title job and, for completed / max_steps, its
1092
1107
  // prompt suggestion job; both are hints after the commit and never throw
1093
- void this.titles.maybeEnqueue(conversationId);
1108
+ void this.titles.maybeEnqueue(orgId, conversationId);
1094
1109
  void this.suggestions.maybeEnqueue(conversationId, runId, kind);
1095
1110
  }
1096
1111
  /**
@@ -114,7 +114,12 @@ let SubagentDeliveries = class SubagentDeliveries {
114
114
  await oweEnsureRun(this.outbox, parent, event.seq, conv.org_id);
115
115
  afterCommit(async () => {
116
116
  await this.eventLog.notify(parent, event.seq);
117
- await this.events.emit("subagent.delivered", { conversationId: parent });
117
+ if (conv) {
118
+ await this.events.emit("subagent.delivered", {
119
+ orgId: conv.org_id,
120
+ conversationId: parent,
121
+ });
122
+ }
118
123
  });
119
124
  return event.seq;
120
125
  }
@@ -2,14 +2,14 @@ import type { Logger } from "@capybara-hq/plugin-sdk";
2
2
  import type { AgentDefinition } from "../../agents/definition.js";
3
3
  import type { EventLog } from "../../conversations/event-log.js";
4
4
  import type { ConversationEvent, EventPayload } from "../../conversations/events.js";
5
- import type { ConversationKind, KernelSchemaDb } from "../../db/kernel-schema.js";
5
+ import type { KernelSchemaDb } from "../../db/kernel-schema.js";
6
6
  import type { KernelConfigService } from "../../infra/config/kernel-config.service.js";
7
7
  import type { ModelPurposesService } from "../../models/purposes.js";
8
8
  import { type SkillInvoker } from "../../skills/invoke.js";
9
9
  import { AGENT_REFUSALS, type AgentToolInputT } from "../../tools/builtins/agent.js";
10
10
  import type { ToolStepContext } from "../../tools/pipeline.js";
11
11
  import type { ProviderRegistry } from "../providers.js";
12
- import { type RunJobData } from "../run-jobs.js";
12
+ import { type RunJobs } from "../run-jobs.js";
13
13
  import { type CheckedOrgAgent, type FollowUpNarrowing } from "./definition.js";
14
14
  import { type RosterEntry } from "./roster.js";
15
15
  export interface DispatchDeps {
@@ -23,7 +23,7 @@ export interface DispatchDeps {
23
23
  * Owes a child run's job in the dispatch's transaction (`RunJobs.owe`: on the sub-agent run
24
24
  * queue, `kind` is always `subagent`); false when the job id is already owed.
25
25
  */
26
- owe: (data: RunJobData, jobId: string, kind: ConversationKind, orgId: string) => Promise<boolean>;
26
+ owe: RunJobs["owe"];
27
27
  log: Pick<Logger, "error" | "warn">;
28
28
  /** Renders a template's skills into the child's first messages ({@link templateSkillMessages}). */
29
29
  invoker: Pick<SkillInvoker, "renderTask">;
@@ -47,9 +47,8 @@ export declare function normalizeWritePath(raw: string): string | null;
47
47
  /**
48
48
  * The failures that only mean "no base now": the device's instance is not running, the read was
49
49
  * not admitted (the run moved on, the authority refused it) or its runtime cannot enforce a
50
- * read-only read, the sandbox is busy, the device is gone, its provider off or an earlier instance
51
- * still awaits retirement, or the model's path is malformed (`Write` refuses it with the same
52
- * `ToolError`).
50
+ * read-only read, the sandbox is busy, the device is gone, its provider is off, or the model's
51
+ * path is malformed (`Write` refuses it with the same `ToolError`).
53
52
  */
54
53
  export declare function expectedNoBase(err: unknown): boolean;
55
54
  /**
@@ -15,7 +15,7 @@ import { ApiError } from "../errors.js";
15
15
  import { KernelDb } from "../infra/database/kernel-db.js";
16
16
  import { KERNEL_LOGGER } from "../infra/tokens.js";
17
17
  import { KernelReadInstanceNotRunning, KernelReadNotAdmitted, KernelReadUnsupported, } from "../sandbox/kernel-read.js";
18
- import { RetirementPendingError, SandboxService } from "../sandbox/sandbox.service.js";
18
+ import { SandboxService } from "../sandbox/sandbox.service.js";
19
19
  import { checkFilePathShape, checkToolPath, looksBinary, } from "../tools/builtins/sandbox/common.js";
20
20
  import { fileStateOf, lastFileState, normalizeSandboxPath, } from "../tools/builtins/sandbox/file-state.js";
21
21
  import { TOOL_VIEW_DIFF_MAX_BYTES, TOOL_VIEW_DIFF_MAX_TEXT_BYTES } from "../tools/view.js";
@@ -130,15 +130,13 @@ function utf8(data) {
130
130
  /**
131
131
  * The failures that only mean "no base now": the device's instance is not running, the read was
132
132
  * not admitted (the run moved on, the authority refused it) or its runtime cannot enforce a
133
- * read-only read, the sandbox is busy, the device is gone, its provider off or an earlier instance
134
- * still awaits retirement, or the model's path is malformed (`Write` refuses it with the same
135
- * `ToolError`).
133
+ * read-only read, the sandbox is busy, the device is gone, its provider is off, or the model's
134
+ * path is malformed (`Write` refuses it with the same `ToolError`).
136
135
  */
137
136
  export function expectedNoBase(err) {
138
137
  if (err instanceof KernelReadInstanceNotRunning ||
139
138
  err instanceof KernelReadNotAdmitted ||
140
139
  err instanceof KernelReadUnsupported ||
141
- err instanceof RetirementPendingError ||
142
140
  err instanceof ToolError)
143
141
  return true;
144
142
  return (err instanceof ApiError &&