@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
@@ -1,5 +1,6 @@
1
1
  import { type ModelUsage } from "@capybara-hq/plugin-sdk";
2
2
  import { type ModelPurposesService } from "../models/purposes.js";
3
+ import type { HookDenial, HookRunner } from "../runtime/hook-calls.js";
3
4
  import { textTokens } from "./plan.js";
4
5
  export { textTokens };
5
6
  /**
@@ -44,6 +45,8 @@ export declare const JUDGE_PROVIDER_UNAVAILABLE = "run.provider_unavailable";
44
45
  */
45
46
  export declare function judge(d: {
46
47
  purposes: Pick<ModelPurposesService, "chat">;
48
+ hooks?: HookRunner | undefined;
49
+ onDenied?: (verdict: HookDenial) => Promise<void>;
47
50
  maxOutputTokens?: number;
48
51
  }, orgId: string, input: {
49
52
  userRequest: string;
@@ -119,7 +119,7 @@ export async function judge(d, orgId, input, signal) {
119
119
  tools: [],
120
120
  toolChoice: "none",
121
121
  maxOutputTokens: d.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS,
122
- }, signal);
122
+ }, signal, { hooks: d.hooks, ...(d.onDenied && { onDenied: d.onDenied }) });
123
123
  }
124
124
  catch (err) {
125
125
  // 中止(停机):交给调用方(任务回到队列);已发出的请求由调用方按 PurposeAttemptError 的估算计费
@@ -9,7 +9,7 @@ import type { KyselyCheckpointSaver } from "../runtime/checkpointer.js";
9
9
  import type { LoopDeps } from "../runtime/langgraph-loop.js";
10
10
  import type { AgentLoop, LoopOutcome } from "../runtime/loop.js";
11
11
  import { type MediaSourceDeps } from "../runtime/model-call.js";
12
- import type { ProviderRegistry } from "../runtime/providers.js";
12
+ import { type ProviderRegistry } from "../runtime/providers.js";
13
13
  import type { RunFinish } from "../runtime/run-finish.js";
14
14
  import { type CaseSnapshot, type SnapshotEvent } from "./snapshot.js";
15
15
  import type { ResolvedCandidate } from "./step-replay.js";
@@ -23,6 +23,7 @@ import { estimateTokens } from "../runtime/context/tokens.js";
23
23
  import { runDeadline, tightestLimit } from "../runtime/limits.js";
24
24
  import { deltaChars, RunError } from "../runtime/model-call.js";
25
25
  import { projectRootIdemKey } from "../runtime/project/knowledge.js";
26
+ import { mapProviderStream, } from "../runtime/providers.js";
26
27
  import { runContextIdemKey } from "../runtime/run-context.service.js";
27
28
  import { recordedSkillForks } from "../runtime/subagents/skill-fork.js";
28
29
  import { skillsCatalogIdemKey } from "../skills/catalog.js";
@@ -453,38 +454,34 @@ export async function replayRun(d, s, candidate, evalRunId, signal) {
453
454
  void p.finally(() => charges.delete(p));
454
455
  return p;
455
456
  };
456
- const meter = (provider) => {
457
- const metered = Object.create(provider);
458
- metered.stream = (req, opts) => (async function* () {
459
- if (!(await allowedSafe())) {
460
- stopper.abort();
461
- throw new ModelError("aborted", "The eval run stopped before this request");
462
- }
463
- let chars = 0;
464
- let charged = false;
465
- try {
466
- for await (const ev of provider.stream(req, opts)) {
467
- if (ev.type === "message_complete") {
468
- charged = true;
469
- await charge(usageTokens(ev.usage));
470
- }
471
- else {
472
- chars += deltaChars(ev);
473
- }
474
- yield ev;
457
+ const meter = (provider) => mapProviderStream(provider, async function* (req, stream) {
458
+ if (!(await allowedSafe())) {
459
+ stopper.abort();
460
+ throw new ModelError("aborted", "The eval run stopped before this request");
461
+ }
462
+ let chars = 0;
463
+ let charged = false;
464
+ try {
465
+ for await (const ev of stream()) {
466
+ if (ev.type === "message_complete") {
467
+ charged = true;
468
+ await charge(usageTokens(ev.usage));
475
469
  }
476
- }
477
- finally {
478
- // 请求已发出但没有正常收完(出错、超时、中止):按估算计费(与单步回放一致),计完再把错误交给 loop——
479
- // loop 的重试 / 兜底请求在下一次检查前就能看到这笔用量(越限即停)。请求里的媒体块已解析成字节,
480
- // `estimateTokens` 逐块计入(图片 1600、文档按大小,与构建请求时的 mediaTokens 同一套估算)
481
- if (!charged) {
482
- await charge(estimateTokens(req.messages, req.system, req.tools) + Math.ceil(chars / 4));
470
+ else {
471
+ chars += deltaChars(ev);
483
472
  }
473
+ yield ev;
484
474
  }
485
- })();
486
- return metered;
487
- };
475
+ }
476
+ finally {
477
+ // Charge the estimated usage for an incomplete request before the loop can retry it.
478
+ // The request already contains resolved media. estimateTokens applies the same media
479
+ // accounting used to construct the request.
480
+ if (!charged) {
481
+ await charge(estimateTokens(req.messages, req.system, req.tools) + Math.ceil(chars / 4));
482
+ }
483
+ }
484
+ });
488
485
  const registry = {
489
486
  // the case's org (its effective provider config), whatever the replayed step passes
490
487
  // (and its disabled lists: a candidate disabled there is refused, spec B §5.3)
@@ -3,8 +3,9 @@ import type { AgentDefinition, ModelRef } from "../agents/definition.js";
3
3
  import { type Selection } from "../conversations/selection.js";
4
4
  import type { KernelConfigService } from "../infra/config/kernel-config.service.js";
5
5
  import type { CompactionSettingsService } from "../runtime/compaction-settings.service.js";
6
+ import type { HookRunner } from "../runtime/hook-calls.js";
6
7
  import { type MediaSourceDeps } from "../runtime/model-call.js";
7
- import type { ProviderRegistry } from "../runtime/providers.js";
8
+ import { type ProviderRegistry } from "../runtime/providers.js";
8
9
  import { type DriftReason, type SubagentTemplateRef } from "./reconstruct.js";
9
10
  import type { CaseSnapshot } from "./snapshot.js";
10
11
  /**
@@ -54,6 +55,7 @@ export interface ReplayOutput {
54
55
  }
55
56
  export interface StepReplayDeps {
56
57
  registry: Pick<ProviderRegistry, "resolve">;
58
+ hooks?: HookRunner;
57
59
  config: Pick<KernelConfigService, "get">;
58
60
  /** 附件来源(与运行时同一个,按组织 + 对话取);不给时媒体一律按「不再可用」占位。 */
59
61
  media?: MediaSourceDeps;
@@ -2,6 +2,7 @@ import { sanitizeParams, } from "@capybara-hq/plugin-sdk";
2
2
  import { effectiveDefinition, NO_SELECTION, sameModel, } from "../conversations/selection.js";
3
3
  import { estimateTokens } from "../runtime/context/tokens.js";
4
4
  import { consumeModelStream, deltaChars, MediaUnavailableError, } from "../runtime/model-call.js";
5
+ import { prepareModelStream } from "../runtime/providers.js";
5
6
  import { loadSnapshotMedia, reconstructRequest, } from "./reconstruct.js";
6
7
  /** 键排序后的 JSON(比较参数是否相同)。 */
7
8
  const canonical = (v) => JSON.stringify(Object.keys(v)
@@ -164,11 +165,19 @@ export async function replayStep(d, s, call, candidate, signal) {
164
165
  ...(media !== undefined && { mediaInfo: media.mediaInfo, media: media.media }),
165
166
  });
166
167
  const idleMs = info.streamIdleTimeoutMs ?? d.config.get().runtime.streamIdleMs;
168
+ const stream = await prepareModelStream(provider, request, {
169
+ ...candidate.model,
170
+ orgId: s.orgId,
171
+ purpose: "eval",
172
+ hooks: d.hooks,
173
+ step: call.step,
174
+ attempt: 1,
175
+ }, signal);
167
176
  const started = Date.now();
168
177
  let streamedChars = 0;
169
178
  let out;
170
179
  try {
171
- out = await consumeModelStream(provider, request, idleMs, signal, (ev) => {
180
+ out = await consumeModelStream(stream, request.model, idleMs, signal, (ev) => {
172
181
  streamedChars += deltaChars(ev);
173
182
  });
174
183
  }
@@ -44,7 +44,7 @@ export declare const EVAL_MAX_STALLED_COUNT = 3;
44
44
  export declare const EVAL_REPLAY_HOOKS: unique symbol;
45
45
  /**
46
46
  * The loop deps of a full-run replay: the run's own step deps without anything live that a replay
47
- * must never trigger, then the replay's overrides. Removed: plugin hooks (P-18), sub-agent and
47
+ * must never trigger, then the replay's overrides. Model-request hooks are retained. Removed: other hooks, sub-agent and
48
48
  * compaction progress on a live stream, fork dispatch (run-replay passes the recorded reports), the
49
49
  * in-context summary's live snapshot and the live permission context recorder (permission context
50
50
  * replay spec B4): a replay gets only the recorded feeder `overrides.permissionContext`, and none
@@ -79,6 +79,7 @@ export declare class EvalWorker {
79
79
  * 看到运行不活跃也会跳过)。返回 true 表示本用例应停下(熔断或失去认领)。
80
80
  */
81
81
  private resultError;
82
+ private writeResultErrorIn;
82
83
  /** 回放一个用例的全部未结束结果(按调用顺序)。 */
83
84
  private runCase;
84
85
  /**
@@ -96,6 +97,7 @@ export declare class EvalWorker {
96
97
  * 评委失败不计入熔断(结果本身是 done)。返回 `capped` 表示评委的用量让运行达到上限。
97
98
  */
98
99
  private judgeResult;
100
+ private writeJudgeResultIn;
99
101
  /**
100
102
  * 整轮回放一个用例(一条结果)。认领结果后先删掉上一次执行留下的评测对话(崩溃重跑从头开始,C6),
101
103
  * 再 {@link replayRun};计费在每次模型请求上完成(含失败与失去认领的请求)。
@@ -16,6 +16,7 @@ import { loadTemplates } from "../agents/templates.js";
16
16
  import { EventLog } from "../conversations/event-log.js";
17
17
  import { ApiError } from "../errors.js";
18
18
  import { ExtensionUnloadedError } from "../extensions/inflight.js";
19
+ import { audit } from "../identity/audit.js";
19
20
  import { waitWithin } from "../infra/close-within.js";
20
21
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
21
22
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -24,8 +25,9 @@ import { Transactional } from "../infra/database/transactional.decorator.js";
24
25
  import { KERNEL_LOGGER } from "../infra/tokens.js";
25
26
  import { ModelPurposesService, PurposeAttemptError } from "../models/purposes.js";
26
27
  import { KyselyCheckpointSaver } from "../runtime/checkpointer.js";
28
+ import { evalDeniedAudit } from "../runtime/hook-calls.js";
27
29
  import { MediaUnavailableError, RunError } from "../runtime/model-call.js";
28
- import { ProviderListError, ProviderRegistry } from "../runtime/providers.js";
30
+ import { ModelRequestDenied, ProviderListError, ProviderRegistry } from "../runtime/providers.js";
29
31
  import { EVAL_QUOTA, ORG_QUOTA_LEASE_MS } from "../runtime/quota.js";
30
32
  import { RunFinish } from "../runtime/run-finish.js";
31
33
  import { AgentLoops, RunSteps } from "../runtime/run-steps.js";
@@ -72,14 +74,14 @@ const isPluginUnloaded = (err) => err instanceof ExtensionUnloadedError ||
72
74
  (err instanceof Error && err.cause instanceof ExtensionUnloadedError);
73
75
  /**
74
76
  * The loop deps of a full-run replay: the run's own step deps without anything live that a replay
75
- * must never trigger, then the replay's overrides. Removed: plugin hooks (P-18), sub-agent and
77
+ * must never trigger, then the replay's overrides. Model-request hooks are retained. Removed: other hooks, sub-agent and
76
78
  * compaction progress on a live stream, fork dispatch (run-replay passes the recorded reports), the
77
79
  * in-context summary's live snapshot and the live permission context recorder (permission context
78
80
  * replay spec B4): a replay gets only the recorded feeder `overrides.permissionContext`, and none
79
81
  * at all for a recording without markers.
80
82
  */
81
83
  export function replayLoopDeps(stepDeps, overrides) {
82
- const { db: _snapshot, hooks: _noHooks, subagentProgress: _noProgress, compactionProgress: _noCompactionProgress, skillForks: _noForks, permissionContext: _noLivePermissionContext,
84
+ const { db: _snapshot, hooks, subagentProgress: _noProgress, compactionProgress: _noCompactionProgress, skillForks: _noForks, permissionContext: _noLivePermissionContext,
83
85
  // a replay never reads a device for a streaming Write's base
84
86
  writeBase: _noWriteBase,
85
87
  // a replayed compaction summarizes the transcript (idle compaction spec §9.4): the replay
@@ -89,6 +91,7 @@ export function replayLoopDeps(stepDeps, overrides) {
89
91
  // instead, so the loop always resolves the context-aware handle
90
92
  return {
91
93
  ...replayDeps,
94
+ ...(hooks !== undefined && { modelRequestHooks: hooks }),
92
95
  get db() {
93
96
  return stepDeps.db;
94
97
  },
@@ -97,6 +100,9 @@ export function replayLoopDeps(stepDeps, overrides) {
97
100
  }
98
101
  /** 回放出错的分类(与运行时的降级梯子同一套码)。 */
99
102
  function classify(err) {
103
+ if (err instanceof ModelRequestDenied) {
104
+ return { retryable: false, code: err.code, message: err.message, denial: err.verdict };
105
+ }
100
106
  if (isModelError(err)) {
101
107
  return {
102
108
  retryable: isRetryableKind(err.kind),
@@ -208,6 +214,7 @@ let EvalWorker = class EvalWorker {
208
214
  registry,
209
215
  config,
210
216
  compactionSettings: stepDeps.compactionSettings,
217
+ ...(stepDeps.hooks !== undefined && { hooks: stepDeps.hooks }),
211
218
  ...(stepDeps.media !== undefined && { media: stepDeps.media }),
212
219
  },
213
220
  // 整轮回放(C6):同一个 loop 工厂(同一 LangGraphLoop),只换工具管线(RecordedToolPipeline,
@@ -224,8 +231,7 @@ let EvalWorker = class EvalWorker {
224
231
  registry,
225
232
  ...(stepDeps.media !== undefined && { media: stepDeps.media }),
226
233
  checkpoints,
227
- // explicitly without plugin hooks: eval replays never fire them (P-18); nor do they
228
- // publish sub-agent progress on a live conversation's stream
234
+ // Replays run model-request hooks without publishing progress on a live conversation.
229
235
  loop: (d) => loops.create(replayLoopDeps(stepDeps, d)),
230
236
  ...(hooks !== undefined && { hooks }),
231
237
  },
@@ -340,16 +346,9 @@ let EvalWorker = class EvalWorker {
340
346
  * 一条结果出错:只在仍由本次执行认领时写入,然后计入熔断;熔断 → 该用例剩下的结果 skipped(其他用例的任务
341
347
  * 看到运行不活跃也会跳过)。返回 true 表示本用例应停下(熔断或失去认领)。
342
348
  */
343
- async resultError(data, resultId, claim, error) {
349
+ async resultError(data, resultId, claim, error, denial) {
344
350
  const db = this.d.db;
345
- const w = await db
346
- .updateTable("eval_results")
347
- .set({ status: "error", error: JSON.stringify(error), updated_at: sql `now()` })
348
- .where("id", "=", resultId)
349
- .where("status", "=", "running")
350
- .where("claimed_by", "=", claim)
351
- .executeTakeFirst();
352
- if (Number(w.numUpdatedRows) === 0)
351
+ if (!(await this.writeResultErrorIn(resultId, claim, error, denial)))
353
352
  return true;
354
353
  const { tripped } = await recordOutcome(db, data.runId, false, this.d.config.get().evals.maxConsecutiveErrors);
355
354
  if (tripped) {
@@ -359,6 +358,21 @@ let EvalWorker = class EvalWorker {
359
358
  }
360
359
  return false;
361
360
  }
361
+ async writeResultErrorIn(resultId, claim, error, denial) {
362
+ const db = this.d.db;
363
+ const w = await db
364
+ .updateTable("eval_results")
365
+ .set({ status: "error", error: JSON.stringify(error), updated_at: sql `now()` })
366
+ .where("id", "=", resultId)
367
+ .where("status", "=", "running")
368
+ .where("claimed_by", "=", claim)
369
+ .executeTakeFirst();
370
+ if (Number(w.numUpdatedRows) === 0)
371
+ return false;
372
+ if (denial)
373
+ await audit(db, denial);
374
+ return true;
375
+ }
362
376
  /** 回放一个用例的全部未结束结果(按调用顺序)。 */
363
377
  async runCase(data, claim, signal) {
364
378
  const { runId, caseId } = data;
@@ -486,7 +500,8 @@ let EvalWorker = class EvalWorker {
486
500
  }
487
501
  if (!out) {
488
502
  const f = failure;
489
- if (await this.resultError(data, r.id, claim, { code: f.code, message: f.message })) {
503
+ const entry = f.denial && evalDeniedAudit({ ...data, resultId: r.id, evaluation: "step" }, f.denial);
504
+ if (await this.resultError(data, r.id, claim, { code: f.code, message: f.message }, entry)) {
490
505
  return;
491
506
  }
492
507
  continue;
@@ -553,10 +568,15 @@ let EvalWorker = class EvalWorker {
553
568
  }
554
569
  await this.d.runReplay.hooks?.beforeJudge?.(data.runId);
555
570
  let v;
571
+ let denial;
556
572
  for (let attempt = 0;; attempt++) {
557
573
  try {
558
574
  v = await judge({
559
575
  purposes: this.d.purposes,
576
+ hooks: this.d.replay.hooks,
577
+ onDenied: async (verdict) => {
578
+ denial = verdict;
579
+ },
560
580
  maxOutputTokens: this.d.config.get().evals.judgeMaxOutputTokens,
561
581
  }, data.orgId, input, signal);
562
582
  }
@@ -595,21 +615,27 @@ let EvalWorker = class EvalWorker {
595
615
  ...(v.model !== undefined && { model: v.model }),
596
616
  }
597
617
  : v;
598
- await db
618
+ const entry = denial && evalDeniedAudit({ ...data, resultId, evaluation: "judge" }, denial);
619
+ await this.writeJudgeResultIn(resultId, claim, stored, "error" in v ? "error" : "done", entry);
620
+ if (signal.aborted)
621
+ throw new Aborted();
622
+ return capped ? "capped" : "ok";
623
+ }
624
+ async writeJudgeResultIn(resultId, claim, stored, status, denial) {
625
+ const written = await this.d.db
599
626
  .updateTable("eval_results")
600
627
  .set({
601
628
  judge: JSON.stringify(stored),
602
- judge_status: "error" in v ? "error" : "done",
629
+ judge_status: status,
603
630
  updated_at: sql `now()`,
604
631
  })
605
632
  .where("id", "=", resultId)
606
633
  .where("status", "=", "done")
607
634
  .where("judge_status", "=", "pending")
608
635
  .where("claimed_by", "=", claim)
609
- .execute();
610
- if (signal.aborted)
611
- throw new Aborted();
612
- return capped ? "capped" : "ok";
636
+ .executeTakeFirst();
637
+ if (denial && Number(written.numUpdatedRows) > 0)
638
+ await audit(this.d.db, denial);
613
639
  }
614
640
  /**
615
641
  * 整轮回放一个用例(一条结果)。认领结果后先删掉上一次执行留下的评测对话(崩溃重跑从头开始,C6),
@@ -868,6 +894,12 @@ let EvalWorker = class EvalWorker {
868
894
  await this.d.budget.recountCases(data.runId);
869
895
  }
870
896
  };
897
+ __decorate([
898
+ Transactional({ propagation: "requires_new" })
899
+ ], EvalWorker.prototype, "writeResultErrorIn", null);
900
+ __decorate([
901
+ Transactional({ propagation: "requires_new" })
902
+ ], EvalWorker.prototype, "writeJudgeResultIn", null);
871
903
  __decorate([
872
904
  Transactional({ propagation: "requires_new" })
873
905
  ], EvalWorker.prototype, "writeStepResultIn", null);
@@ -1,5 +1,6 @@
1
1
  import { configFields, getPath } from "../config/fields.js";
2
2
  import { createSecrets } from "../ctx/secrets.js";
3
+ import { asPlatform } from "../infra/database/org-scope.js";
3
4
  /**
4
5
  * The stored half of the deployment-level extension config (C10): where PG keeps it, how it is read
5
6
  * back and merged under the startup config. Pure helpers shared by the extension installs (the
@@ -113,20 +114,23 @@ export async function readStoredDeploymentConfig(db, keyring, plugin, opts) {
113
114
  const wanted = new Set(opts.secretPaths);
114
115
  if (wanted.size === 0)
115
116
  return out;
116
- const keys = await db
117
- .selectFrom("secrets")
118
- .select("key")
119
- .where("namespace", "=", SECRETS_NAMESPACE)
120
- .where("org_id", "=", DEPLOYMENT_SECRETS_ORG)
121
- .execute();
122
- const secrets = createSecrets(db, keyring, SECRETS_NAMESPACE);
123
- for (const { key } of keys) {
124
- if (!key.startsWith(prefix) || !wanted.has(key.slice(prefix.length)))
125
- continue;
126
- const v = await secrets.get(DEPLOYMENT_SECRETS_ORG, key);
127
- if (v !== null)
128
- setDeep(out, key.slice(prefix.length), JSON.parse(v));
129
- }
117
+ // org-filter: deployment-wide secrets under the reserved deployment scope.
118
+ await asPlatform("Read secrets stored under the deployment's reserved scope", async () => {
119
+ const keys = await db
120
+ .selectFrom("secrets")
121
+ .select("key")
122
+ .where("namespace", "=", SECRETS_NAMESPACE)
123
+ .where("org_id", "=", DEPLOYMENT_SECRETS_ORG)
124
+ .execute();
125
+ const secrets = createSecrets(db, keyring, SECRETS_NAMESPACE);
126
+ for (const { key } of keys) {
127
+ if (!key.startsWith(prefix) || !wanted.has(key.slice(prefix.length)))
128
+ continue;
129
+ const v = await secrets.get(DEPLOYMENT_SECRETS_ORG, key);
130
+ if (v !== null)
131
+ setDeep(out, key.slice(prefix.length), JSON.parse(v));
132
+ }
133
+ });
130
134
  return out;
131
135
  }
132
136
  /** 字段清单里的密钥字段路径。 */
@@ -17,11 +17,7 @@ type Obj = Record<string, unknown>;
17
17
  export declare const NEEDS_CONFIG_REASON = "needs configuration in this organization";
18
18
  /** The kernel's own secrets namespace (`kernel` is a reserved plugin name). */
19
19
  export declare const OVERRIDE_SECRETS_NAMESPACE = "kernel";
20
- /**
21
- * Where a copy's secret field lives in `capybara.secrets` (under the org): a key prefix of its
22
- * own, distinct from the retired org config secrets `plugin-config:<plugin>:<path>` (spec A §5.8;
23
- * no longer read, purged by a later contract migration).
24
- */
20
+ /** Key for an org override's encrypted secret in the kernel namespace. */
25
21
  export declare const overrideSecretKey: (plugin: string, path: string) => string;
26
22
  /**
27
23
  * The effective deployment config of an extension for an org (spec A §6): `ok` with the config
@@ -32,11 +32,7 @@ export const NEEDS_CONFIG_REASON = "needs configuration in this organization";
32
32
  /** The kernel's own secrets namespace (`kernel` is a reserved plugin name). */
33
33
  export const OVERRIDE_SECRETS_NAMESPACE = "kernel";
34
34
  const OVERRIDE_KEY_PREFIX = "plugin-override:";
35
- /**
36
- * Where a copy's secret field lives in `capybara.secrets` (under the org): a key prefix of its
37
- * own, distinct from the retired org config secrets `plugin-config:<plugin>:<path>` (spec A §5.8;
38
- * no longer read, purged by a later contract migration).
39
- */
35
+ /** Key for an org override's encrypted secret in the kernel namespace. */
40
36
  export const overrideSecretKey = (plugin, path) => `${OVERRIDE_KEY_PREFIX}${plugin}:${path}`;
41
37
  const notRunning = () => ({
42
38
  ok: false,
@@ -189,7 +189,9 @@ export declare class HookRegistry {
189
189
  handler: HookHandler<K>;
190
190
  }[];
191
191
  /** Runs the hooks of a mount point (see the class comment); queue-delivered mounts excluded. */
192
- run<K extends Exclude<AvailableHook, QueuedHook>>(mount: K, payload: HookPayloads[K], signal: AbortSignal): Promise<HookOutcome>;
192
+ run<K extends Exclude<AvailableHook, QueuedHook>>(mount: K, payload: HookPayloads[K], signal: AbortSignal, options?: {
193
+ policyOnly?: boolean;
194
+ }): Promise<HookOutcome>;
193
195
  /**
194
196
  * The M-1 denial: `missing` (sorted) are enabled policy plugins that are not loaded on this replica.
195
197
  * The model-visible reason is generic; the detail and a throttled warning name the plugin for the
@@ -205,10 +205,13 @@ export class HookRegistry {
205
205
  }));
206
206
  }
207
207
  /** Runs the hooks of a mount point (see the class comment); queue-delivered mounts excluded. */
208
- async run(mount, payload, signal) {
208
+ async run(mount, payload, signal, options = {}) {
209
209
  if (signal.aborted)
210
210
  throw signal.reason;
211
- const all = this.entries(mount);
211
+ const entries = this.entries(mount);
212
+ const all = options.policyOnly
213
+ ? entries.filter((entry) => entry.hook.mode === "policy")
214
+ : entries;
212
215
  const unloaded = this.unloadedPolicy(mount);
213
216
  if (all.length === 0 && unloaded.length === 0)
214
217
  return { allowed: true };
@@ -312,6 +315,8 @@ export class HookRegistry {
312
315
  break;
313
316
  }
314
317
  }
318
+ if (options.policyOnly)
319
+ return outcome;
315
320
  // observe hooks are resolved again now: if the plugin was upgraded while the policy hooks ran,
316
321
  // the current generation observes (the retiring one no longer accepts calls)
317
322
  for (const e of this.entries(mount)) {
@@ -5,7 +5,6 @@ import { SuperAdminLock } from "../identity/super-admin.js";
5
5
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
6
6
  import { KernelDb } from "../infra/database/kernel-db.js";
7
7
  import { TransactionHost } from "../infra/database/transaction-host.js";
8
- import { OrgLock } from "../orgs/org-lock.js";
9
8
  import { type ProvenanceResult } from "../packages/provenance.js";
10
9
  import { ExtensionApprovals } from "./approvals.js";
11
10
  import { ExtensionBlobs } from "./blobs.js";
@@ -90,15 +89,11 @@ export declare class ExtensionInstalls {
90
89
  private readonly registry;
91
90
  private readonly config;
92
91
  private readonly keyring;
93
- /** The owner org's lock: an org upload re-checks its org admin instead (ruling P3-10). */
94
- private readonly orgLock;
95
92
  constructor(db: KernelDb, txHost: TransactionHost,
96
93
  /** The super admin lock (identity/super-admin.ts): joins the transaction. */
97
94
  adminLock: SuperAdminLock, blobs: ExtensionBlobs, approvals: ExtensionApprovals,
98
95
  /** The config-declared extension names (an install cannot take them, C15). */
99
- registry: ExtensionRegistry, config: KernelConfigService, keyring: Keyring,
100
- /** The owner org's lock: an org upload re-checks its org admin instead (ruling P3-10). */
101
- orgLock: OrgLock);
96
+ registry: ExtensionRegistry, config: KernelConfigService, keyring: Keyring);
102
97
  /**
103
98
  * An extension's effective deployment config, not validated yet (C10): the startup config
104
99
  * (`fileValue`, file / Nacos merged with env) completed by the fields stored in PG; merged by
@@ -120,17 +115,12 @@ export declare class ExtensionInstalls {
120
115
  * - extension name equal to a config-declared one -> `extension.config_declared`;
121
116
  * - an install record of the same name comes from another npm package -> `extension.name_conflict`
122
117
  * (a new version of the same package is an upgrade, handled elsewhere).
123
- * `actor` null means the CLI (no super admin re-check, audit without an actor). `owner`: an org
124
- * upload (spec §14, P3-10): the actor is re-checked as an org admin of that org (`catalog.upload`)
125
- * instead of a super admin; the package is only stored, as always (nothing runs, no install).
118
+ * A null actor means the CLI, which audits without an actor.
126
119
  */
127
120
  ingest(actor: string | null, bytes: Uint8Array, src: IngestSource, opts?: {
128
121
  actorTokenId?: string;
129
122
  store?: "object" | "pg";
130
123
  expectPackageName?: string;
131
- owner?: {
132
- orgId: string;
133
- };
134
124
  /** Merged into the audit detail (a write made through the Platform tool: `via`, …). */
135
125
  auditDetail?: Record<string, unknown>;
136
126
  }): Promise<PackageReview>;
@@ -140,8 +130,6 @@ export declare class ExtensionInstalls {
140
130
  * transaction holding the lock.
141
131
  */
142
132
  private authorize;
143
- /** The super admin, or for an org upload the owner org's admin, re-checked under its lock. */
144
- private authorizeIn;
145
133
  /**
146
134
  * The `extension.package_uploaded` audit, re-checking the actor under the lock, committed on its
147
135
  * own (`requires_new`): the stored package it records is not rolled back by a caller either.