@capybara-hq/kernel 0.1.0-rc.120 → 0.1.0-rc.122

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/dist/background/finish.d.ts +5 -1
  2. package/dist/background/finish.js +29 -18
  3. package/dist/background/launch.d.ts +0 -5
  4. package/dist/background/launch.js +1 -6
  5. package/dist/background/managed.js +1 -4
  6. package/dist/background/poll.job.d.ts +3 -25
  7. package/dist/background/poll.job.js +20 -112
  8. package/dist/background/render.d.ts +2 -8
  9. package/dist/background/render.js +3 -17
  10. package/dist/background/stop.d.ts +15 -16
  11. package/dist/background/stop.js +39 -76
  12. package/dist/background/store.d.ts +17 -45
  13. package/dist/background/store.js +60 -94
  14. package/dist/background/tasks.service.d.ts +2 -5
  15. package/dist/background/tasks.service.js +9 -20
  16. package/dist/background/wake.js +3 -2
  17. package/dist/catalog/admin-catalog.controller.d.ts +2 -18
  18. package/dist/catalog/admin-catalog.controller.js +2 -28
  19. package/dist/catalog/catalog-content.d.ts +1 -5
  20. package/dist/catalog/catalog-items.d.ts +2 -6
  21. package/dist/catalog/catalog-items.js +5 -26
  22. package/dist/catalog/catalog-scope.service.d.ts +1 -121
  23. package/dist/catalog/catalog-scope.service.js +12 -552
  24. package/dist/catalog/catalog.service.d.ts +4 -15
  25. package/dist/catalog/catalog.service.js +7 -35
  26. package/dist/catalog/job-ids.d.ts +0 -18
  27. package/dist/catalog/job-ids.js +0 -20
  28. package/dist/catalog/marketplaces.service.d.ts +1 -1
  29. package/dist/catalog/org-catalog.service.js +6 -20
  30. package/dist/catalog/org-plugin-uploads.controller.d.ts +4 -19
  31. package/dist/catalog/org-plugin-uploads.controller.js +6 -34
  32. package/dist/catalog/org-plugin-uploads.d.ts +3 -10
  33. package/dist/catalog/org-plugin-uploads.js +4 -18
  34. package/dist/catalog/org-plugin-uploads.schemas.js +0 -1
  35. package/dist/catalog/owned-items.d.ts +6 -11
  36. package/dist/catalog/owned-items.js +10 -20
  37. package/dist/catalog/ownership.d.ts +3 -29
  38. package/dist/catalog/ownership.js +4 -54
  39. package/dist/catalog/platform-components.d.ts +5 -11
  40. package/dist/catalog/platform-components.js +8 -15
  41. package/dist/catalog/plugin-import.d.ts +3 -42
  42. package/dist/catalog/plugin-import.js +26 -195
  43. package/dist/catalog/plugin-install.js +1 -6
  44. package/dist/catalog/plugin-package.d.ts +1 -0
  45. package/dist/catalog/plugin-package.js +5 -0
  46. package/dist/catalog/plugin-upgrade.d.ts +3 -26
  47. package/dist/catalog/plugin-upgrade.js +20 -103
  48. package/dist/catalog/request-rules.js +4 -6
  49. package/dist/catalog/scope-sync.js +2 -4
  50. package/dist/catalog/scope.d.ts +2 -5
  51. package/dist/channels/jobs.d.ts +3 -3
  52. package/dist/channels/jobs.js +4 -3
  53. package/dist/channels/outbound.d.ts +1 -0
  54. package/dist/channels/outbound.js +32 -8
  55. package/dist/config/load.d.ts +0 -25
  56. package/dist/config/load.js +0 -57
  57. package/dist/config/schema.js +2 -3
  58. package/dist/conversations/attachments.service.js +3 -5
  59. package/dist/conversations/conversations.service.d.ts +3 -3
  60. package/dist/conversations/conversations.service.js +3 -3
  61. package/dist/conversations/job-org.d.ts +3 -0
  62. package/dist/conversations/job-org.js +11 -0
  63. package/dist/conversations/prompt-suggestions.d.ts +2 -7
  64. package/dist/conversations/prompt-suggestions.js +29 -27
  65. package/dist/conversations/titles.d.ts +3 -4
  66. package/dist/conversations/titles.js +19 -30
  67. package/dist/db/kernel-schema.d.ts +6 -16
  68. package/dist/db/pool.js +7 -2
  69. package/dist/devices/devices.controller.d.ts +0 -5
  70. package/dist/devices/devices.controller.js +2 -20
  71. package/dist/devices/devices.service.d.ts +1 -17
  72. package/dist/devices/devices.service.js +0 -22
  73. package/dist/errors.d.ts +1 -5
  74. package/dist/errors.js +1 -5
  75. package/dist/evals/judge.d.ts +3 -0
  76. package/dist/evals/judge.js +1 -1
  77. package/dist/evals/run-replay.d.ts +1 -1
  78. package/dist/evals/run-replay.js +26 -29
  79. package/dist/evals/step-replay.d.ts +3 -1
  80. package/dist/evals/step-replay.js +10 -1
  81. package/dist/evals/worker.d.ts +3 -1
  82. package/dist/evals/worker.js +53 -21
  83. package/dist/extensions/deployment-config-store.js +18 -14
  84. package/dist/extensions/effective-config.d.ts +1 -5
  85. package/dist/extensions/effective-config.js +1 -5
  86. package/dist/extensions/hooks.d.ts +3 -1
  87. package/dist/extensions/hooks.js +7 -2
  88. package/dist/extensions/installs.d.ts +2 -14
  89. package/dist/extensions/installs.js +10 -32
  90. package/dist/extensions/org-config.d.ts +3 -4
  91. package/dist/extensions/org-config.js +3 -4
  92. package/dist/extensions/plugin-guides.d.ts +0 -1
  93. package/dist/extensions/plugin-guides.js +0 -1
  94. package/dist/extensions/plugin-icons.d.ts +0 -1
  95. package/dist/extensions/plugin-icons.js +0 -3
  96. package/dist/files/blob-sweep.job.d.ts +2 -11
  97. package/dist/files/blob-sweep.job.js +7 -21
  98. package/dist/files/hash-job.d.ts +5 -15
  99. package/dist/files/hash-job.js +14 -33
  100. package/dist/files/library-jobs.module.d.ts +1 -6
  101. package/dist/files/library-jobs.module.js +3 -9
  102. package/dist/identity/api-tokens.js +54 -40
  103. package/dist/identity/auth.guard.js +2 -2
  104. package/dist/identity/sessions.js +7 -3
  105. package/dist/identity/settings.js +5 -21
  106. package/dist/inbox/inbox.service.d.ts +2 -3
  107. package/dist/inbox/org-notices.d.ts +0 -14
  108. package/dist/inbox/platform-inbox.service.d.ts +1 -8
  109. package/dist/inbox/platform-inbox.service.js +2 -6
  110. package/dist/inbox/platform-notices.d.ts +3 -3
  111. package/dist/index.d.ts +0 -4
  112. package/dist/index.js +0 -3
  113. package/dist/infra/database/database.module.js +2 -1
  114. package/dist/infra/database/org-scope.d.ts +5 -3
  115. package/dist/infra/database/org-scope.js +7 -1
  116. package/dist/infra/database/scoped-dialect.d.ts +3 -1
  117. package/dist/infra/database/scoped-dialect.js +17 -5
  118. package/dist/infra/events/kernel-events.d.ts +2 -0
  119. package/dist/infra/outbox/outbox.service.d.ts +2 -0
  120. package/dist/infra/outbox/outbox.service.js +10 -0
  121. package/dist/infra/outbox/registry.d.ts +0 -41
  122. package/dist/infra/outbox/registry.js +0 -37
  123. package/dist/models/embeddings.d.ts +0 -5
  124. package/dist/models/embeddings.js +28 -35
  125. package/dist/models/images.d.ts +3 -8
  126. package/dist/models/images.js +19 -37
  127. package/dist/models/purposes.d.ts +7 -2
  128. package/dist/models/purposes.js +16 -3
  129. package/dist/orgs/device-network-setting.d.ts +0 -44
  130. package/dist/orgs/device-network-setting.js +0 -83
  131. package/dist/orgs/invitations.service.js +34 -30
  132. package/dist/orgs/offboarding.d.ts +2 -2
  133. package/dist/orgs/offboarding.js +2 -2
  134. package/dist/orgs/orgs.service.d.ts +1 -1
  135. package/dist/orgs/orgs.service.js +19 -15
  136. package/dist/orgs/settings.service.d.ts +19 -14
  137. package/dist/orgs/settings.service.js +12 -37
  138. package/dist/platform/exclusions.js +0 -11
  139. package/dist/platform/ops/catalog-admin.ops.js +0 -8
  140. package/dist/platform/ops/devices.ops.js +0 -28
  141. package/dist/platform/ops/extensions-admin.ops.js +3 -3
  142. package/dist/platform/ops/inbox.ops.js +5 -22
  143. package/dist/platform/ops/org-plugins.ops.d.ts +1 -3
  144. package/dist/platform/ops/org-plugins.ops.js +11 -67
  145. package/dist/plugin-reads/plugin-reads.service.js +2 -1
  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
@@ -46,19 +46,6 @@ export declare const OUTBOX_JOBS: {
46
46
  readonly removeOnFail: true;
47
47
  };
48
48
  };
49
- readonly "share-object-delete": {
50
- readonly queue: "cap-kernel-maintenance";
51
- readonly idempotent: "Deletes one object key; deleting a missing object is a no-op";
52
- readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
53
- readonly opts: {
54
- readonly attempts: 10;
55
- readonly backoff: {
56
- readonly type: "exponential";
57
- readonly delay: 5000;
58
- };
59
- readonly removeOnComplete: true;
60
- };
61
- };
62
49
  readonly "blob-delete": {
63
50
  readonly queue: "cap-kernel-maintenance";
64
51
  readonly idempotent: "Deletes the object and row only of a blob still in deleting status that no file or share points at; deleting a missing object is a no-op";
@@ -101,20 +88,6 @@ export declare const OUTBOX_JOBS: {
101
88
  readonly removeOnFail: true;
102
89
  };
103
90
  };
104
- readonly "file-library-backfill": {
105
- readonly queue: "cap-kernel-maintenance";
106
- readonly idempotent: "Does nothing once the settled marker exists; the copy itself is idempotent and writes the marker in its own transaction";
107
- readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
108
- readonly opts: {
109
- readonly attempts: 5;
110
- readonly backoff: {
111
- readonly type: "exponential";
112
- readonly delay: 30000;
113
- };
114
- readonly removeOnComplete: true;
115
- readonly removeOnFail: true;
116
- };
117
- };
118
91
  readonly "file-release": {
119
92
  readonly queue: "cap-kernel-maintenance";
120
93
  readonly idempotent: "Re-reads the deleted file under its row lock and releases its blob only while nothing else points at it, or deletes its own staging key; a second run finds nothing to do";
@@ -435,20 +408,6 @@ export declare const OUTBOX_JOBS: {
435
408
  readonly removeOnFail: true;
436
409
  };
437
410
  };
438
- readonly "owned-plugin-cleanup": {
439
- readonly queue: "cap-kernel-maintenance";
440
- readonly idempotent: "the cleanup takes the extension out only while no live item uses it, and a missing install or a released claim changes nothing";
441
- readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
442
- readonly opts: {
443
- readonly attempts: 3;
444
- readonly backoff: {
445
- readonly type: "exponential";
446
- readonly delay: 5000;
447
- };
448
- readonly removeOnComplete: true;
449
- readonly removeOnFail: true;
450
- };
451
- };
452
411
  readonly "automation-fire": {
453
412
  readonly queue: "cap-kernel-maintenance";
454
413
  readonly idempotent: "a fire acts only on a pending task run, under its row lock; a retried start reuses what the first one made";
@@ -44,15 +44,6 @@ export const OUTBOX_JOBS = {
44
44
  removeOnFail: true,
45
45
  },
46
46
  },
47
- // `shares/share-objects.ts` SHARE_OBJECT_DELETE_JOB: owed before the file library by a share's
48
- // refresh and revoke (`shareObjectDeleteJobId`); no longer owed, handled for rows owed before the
49
- // deploy (a key a blob uses is never deleted)
50
- "share-object-delete": {
51
- queue: "cap-kernel-maintenance",
52
- idempotent: "Deletes one object key; deleting a missing object is a no-op",
53
- processedIn: "packages/kernel/src/runtime/maintenance.ts",
54
- opts: { attempts: 10, backoff: { type: "exponential", delay: 5000 }, removeOnComplete: true },
55
- },
56
47
  // `files/blob-objects.ts` BLOB_DELETE_JOB: owed with a blob turned `deleting` (an upload dropped
57
48
  // before use whose own blob nothing else points at; the blob sweep; a hashing merge's
58
49
  // duplicate), under `blobDeleteJobId`
@@ -95,19 +86,6 @@ export const OUTBOX_JOBS = {
95
86
  removeOnFail: true,
96
87
  },
97
88
  },
98
- // `files/library-backfill.ts` FILE_LIBRARY_BACKFILL_JOB: the one-off catch-up copy, owed by the
99
- // kickoff until it settled, under its own name as id
100
- "file-library-backfill": {
101
- queue: "cap-kernel-maintenance",
102
- idempotent: "Does nothing once the settled marker exists; the copy itself is idempotent and writes the marker in its own transaction",
103
- processedIn: "packages/kernel/src/runtime/maintenance.ts",
104
- opts: {
105
- attempts: 5,
106
- backoff: { type: "exponential", delay: 30000 },
107
- removeOnComplete: true,
108
- removeOnFail: true,
109
- },
110
- },
111
89
  // `files/blob-objects.ts` FILE_RELEASE_JOB: owed, deferred, by every discard and draft cleanup
112
90
  // of an upload, under `fileReleaseJobId`
113
91
  "file-release": {
@@ -381,21 +359,6 @@ export const OUTBOX_JOBS = {
381
359
  // as a chunk job: retried while one of its items' extensions is not loaded on the replica
382
360
  opts: SCOPE_JOB_OPTS,
383
361
  },
384
- // `catalog/job-ids.ts` OWNED_PLUGIN_CLEANUP_JOB: owed by the removal of an org-owned plugin
385
- // (and by a confirmation that took out the extension of an item removed meanwhile), under
386
- // `ownedPluginCleanupJobId` (spec §8.1)
387
- "owned-plugin-cleanup": {
388
- queue: "cap-kernel-maintenance",
389
- idempotent: "the cleanup takes the extension out only while no live item uses it, and a missing install or a released claim changes nothing",
390
- processedIn: "packages/kernel/src/runtime/maintenance.ts",
391
- // a few retries while PG is briefly unavailable; removed once done
392
- opts: {
393
- attempts: 3,
394
- backoff: { type: "exponential", delay: 5_000 },
395
- removeOnComplete: true,
396
- removeOnFail: true,
397
- },
398
- },
399
362
  // `automations/job-ids.ts` AUTOMATION_FIRE_JOB: owed by the transaction that writes a pending task run
400
363
  // (the scan's tick, a person's "run now"), under `automationFireJobId` (spec §8.1)
401
364
  "automation-fire": {
@@ -67,11 +67,6 @@ export declare class ModelEmbeddings {
67
67
  * host's hook registry (`model.request`), absent only for a ctx built without a host (tests).
68
68
  */
69
69
  embed(plugin: string, declared: DeclaredModelPurposes, request: ExtensionEmbedRequest, signal: AbortSignal, hooks: HookRunner | undefined): Promise<ExtensionEmbedResult>;
70
- /**
71
- * `model.request` for an embed call (policy hooks may deny it). Rejects with the caller's abort
72
- * reason when `signal` aborts while the hooks run (an abort is never a deny).
73
- */
74
- private checkHooks;
75
70
  /** `ctx.models.describe` for `plugin`: null when the purpose maps to no model the org can use. */
76
71
  describe(plugin: string, declared: DeclaredModelPurposes, req: {
77
72
  orgId: string;
@@ -19,7 +19,7 @@ import { Transactional } from "../infra/database/transactional.decorator.js";
19
19
  import { KERNEL_LOGGER } from "../infra/tokens.js";
20
20
  import { embeddingDeniedAudit } from "../runtime/hook-calls.js";
21
21
  import { modelDeniedText } from "../runtime/model-call.js";
22
- import { ProviderRegistry } from "../runtime/providers.js";
22
+ import { ModelRequestDenied, ProviderRegistry, prepareEmbedding, supportsEmbedding, } from "../runtime/providers.js";
23
23
  import { UsageReportJobs } from "../runtime/usage-report-jobs.js";
24
24
  import { ModelPurposesService } from "./purposes.js";
25
25
  /** Most texts one `ctx.models.embed` call may carry (the kernel splits them by `maxBatch`). */
@@ -87,14 +87,14 @@ let ModelEmbeddings = class ModelEmbeddings {
87
87
  const { provider, info } = await this.providers.resolve(orgId, target.model, {
88
88
  kind: "embedding",
89
89
  });
90
- if (info.embedding === undefined || provider.embed === undefined) {
90
+ if (info.embedding === undefined || !supportsEmbedding(provider)) {
91
91
  // the registry drops such models from the list; kept as a guard
92
92
  throw new ApiError("model.unconfigured", `The model configured for the "${purpose}" purpose cannot embed`);
93
93
  }
94
94
  return {
95
95
  ref: target.model,
96
96
  info: info.embedding,
97
- embed: provider.embed.bind(provider),
97
+ provider,
98
98
  };
99
99
  }
100
100
  /**
@@ -156,7 +156,30 @@ let ModelEmbeddings = class ModelEmbeddings {
156
156
  const size = Math.max(1, t.info.maxBatch);
157
157
  // the instance's signal (revocation) and the caller's own (e.g. its tool call aborted)
158
158
  const callSignal = req.signal ? AbortSignal.any([signal, req.signal]) : signal;
159
- await this.checkHooks(hooks, plugin, req, model, callSignal);
159
+ const payload = {
160
+ purpose: "embedding",
161
+ orgId: req.orgId,
162
+ extension: plugin,
163
+ embeddingPurpose: req.purpose,
164
+ provider: model.provider,
165
+ model: model.id,
166
+ input: req.input,
167
+ ...(req.dimensions !== undefined && { dimensions: req.dimensions }),
168
+ ...(req.inputType !== undefined && { inputType: req.inputType }),
169
+ };
170
+ const embed = await prepareEmbedding(t.provider, payload, hooks, callSignal).catch(async (err) => {
171
+ if (!(err instanceof ModelRequestDenied))
172
+ throw err;
173
+ const { verdict } = err;
174
+ await audit(this.kdb.db, embeddingDeniedAudit(payload, verdict));
175
+ this.log.warn("embed call blocked by a policy hook", {
176
+ plugin,
177
+ orgId: req.orgId,
178
+ hookPlugin: verdict.plugin,
179
+ cause: verdict.cause,
180
+ });
181
+ throw new ApiError("model.hook_denied", modelDeniedText(verdict.plugin, verdict.reason));
182
+ });
160
183
  try {
161
184
  for (let i = 0; i < req.input.length; i += size) {
162
185
  callSignal.throwIfAborted();
@@ -166,7 +189,7 @@ let ModelEmbeddings = class ModelEmbeddings {
166
189
  ...(req.dimensions !== undefined && { dimensions: req.dimensions }),
167
190
  ...(req.inputType !== undefined && { inputType: req.inputType }),
168
191
  };
169
- const res = await this.callWithTimeout(t.embed, batch, callSignal, model);
192
+ const res = await this.callWithTimeout(embed, batch, callSignal, model);
170
193
  answered++;
171
194
  inputTokens += tokensOf(res);
172
195
  const problem = checkResult(batch, t.info, res);
@@ -191,36 +214,6 @@ let ModelEmbeddings = class ModelEmbeddings {
191
214
  await this.record(plugin, req.orgId, req.purpose, model, inputTokens);
192
215
  return { vectors, model, dimensions };
193
216
  }
194
- /**
195
- * `model.request` for an embed call (policy hooks may deny it). Rejects with the caller's abort
196
- * reason when `signal` aborts while the hooks run (an abort is never a deny).
197
- */
198
- async checkHooks(hooks, plugin, req, model, signal) {
199
- if (!hooks?.has("model.request"))
200
- return;
201
- const call = {
202
- purpose: "embedding",
203
- orgId: req.orgId,
204
- extension: plugin,
205
- embeddingPurpose: req.purpose,
206
- provider: model.provider,
207
- model: model.id,
208
- input: req.input,
209
- ...(req.dimensions !== undefined && { dimensions: req.dimensions }),
210
- ...(req.inputType !== undefined && { inputType: req.inputType }),
211
- };
212
- const verdict = await hooks.run("model.request", call, signal);
213
- if (verdict.allowed)
214
- return;
215
- await audit(this.kdb.db, embeddingDeniedAudit(call, verdict));
216
- this.log.warn("embed call blocked by a policy hook", {
217
- plugin,
218
- orgId: req.orgId,
219
- hookPlugin: verdict.plugin,
220
- cause: verdict.cause,
221
- });
222
- throw new ApiError("model.hook_denied", modelDeniedText(verdict.plugin, verdict.reason));
223
- }
224
217
  /** `ctx.models.describe` for `plugin`: null when the purpose maps to no model the org can use. */
225
218
  async describe(plugin, declared, req) {
226
219
  if (typeof req?.orgId !== "string" || typeof req.purpose !== "string") {
@@ -2,7 +2,7 @@ import { type ExtensionImageGenerateRequest, type ExtensionImageGenerateResult,
2
2
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
3
3
  import { KernelDb } from "../infra/database/kernel-db.js";
4
4
  import { TransactionHost } from "../infra/database/transaction-host.js";
5
- import { type HookDenial, type HookRunner } from "../runtime/hook-calls.js";
5
+ import { type HookRunner } from "../runtime/hook-calls.js";
6
6
  import { ProviderRegistry } from "../runtime/providers.js";
7
7
  import { UsageReportJobs } from "../runtime/usage-report-jobs.js";
8
8
  import type { DeclaredModelPurposes } from "./embeddings.js";
@@ -35,7 +35,7 @@ export interface PreparedImageCall {
35
35
  /** Who makes the call, as the hook payloads name it. */
36
36
  export type ImageHookIdentity = {
37
37
  kind: "conversation";
38
- scope: HookScope;
38
+ scope: HookScope | null;
39
39
  step: number;
40
40
  callId: string;
41
41
  } | {
@@ -43,11 +43,6 @@ export type ImageHookIdentity = {
43
43
  extension: string;
44
44
  imagePurpose: string;
45
45
  };
46
- /** A `model.request` policy hook denied the call; nothing was sent. The caller records it. */
47
- export declare class ImageCallDenied extends Error {
48
- readonly verdict: HookDenial;
49
- constructor(verdict: HookDenial);
50
- }
51
46
  /**
52
47
  * Image generation calls (image generation spec §5.1, §5.2, §5.6, §6), shared by the
53
48
  * `GenerateImage` tool and `ctx.models.generateImage`:
@@ -58,7 +53,7 @@ export declare class ImageCallDenied extends Error {
58
53
  * size ({@link pickImageSize}) and sanitizes the mapping's params against the model's
59
54
  * declarations. Every refusal is `ApiError("validation_failed")` with an actionable text.
60
55
  * - {@link run} fires `model.request` (placeholders for references; a denial throws
61
- * {@link ImageCallDenied} and sends nothing), calls `generateImage` within
56
+ * {@link ModelRequestDenied} and sends nothing), calls `generateImage` within
62
57
  * `models.imageTimeoutMs`, checks the result ({@link validateImageGenerateResult}: invalid is a
63
58
  * `ModelError("server")`) and fires `model.response` (observe; media types and byte sizes, never
64
59
  * bytes), also when the call failed, but not when the caller's signal aborted it.
@@ -19,7 +19,7 @@ import { Transactional } from "../infra/database/transactional.decorator.js";
19
19
  import { KERNEL_LOGGER } from "../infra/tokens.js";
20
20
  import { base64Bytes, fireObserve, imageDeniedAudit, } from "../runtime/hook-calls.js";
21
21
  import { modelDeniedText, trustedUsage } from "../runtime/model-call.js";
22
- import { ProviderRegistry } from "../runtime/providers.js";
22
+ import { ModelRequestDenied, ProviderRegistry, prepareImageGeneration, } from "../runtime/providers.js";
23
23
  import { UsageReportJobs } from "../runtime/usage-report-jobs.js";
24
24
  import { imageInputCaps } from "./image-usable.js";
25
25
  import { ModelPurposesService } from "./purposes.js";
@@ -27,15 +27,6 @@ import { ModelPurposesService } from "./purposes.js";
27
27
  const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
28
28
  /** `MEDIA_LIMITS.imageBytes` in MB, for the reference-image error text. */
29
29
  const IMAGE_LIMIT_MB = MEDIA_LIMITS.imageBytes / 1_048_576;
30
- /** A `model.request` policy hook denied the call; nothing was sent. The caller records it. */
31
- export class ImageCallDenied extends Error {
32
- verdict;
33
- constructor(verdict) {
34
- super(modelDeniedText(verdict.plugin, verdict.reason));
35
- this.verdict = verdict;
36
- this.name = "ImageCallDenied";
37
- }
38
- }
39
30
  /**
40
31
  * Image generation calls (image generation spec §5.1, §5.2, §5.6, §6), shared by the
41
32
  * `GenerateImage` tool and `ctx.models.generateImage`:
@@ -46,7 +37,7 @@ export class ImageCallDenied extends Error {
46
37
  * size ({@link pickImageSize}) and sanitizes the mapping's params against the model's
47
38
  * declarations. Every refusal is `ApiError("validation_failed")` with an actionable text.
48
39
  * - {@link run} fires `model.request` (placeholders for references; a denial throws
49
- * {@link ImageCallDenied} and sends nothing), calls `generateImage` within
40
+ * {@link ModelRequestDenied} and sends nothing), calls `generateImage` within
50
41
  * `models.imageTimeoutMs`, checks the result ({@link validateImageGenerateResult}: invalid is a
51
42
  * `ModelError("server")`) and fires `model.response` (observe; media types and byte sizes, never
52
43
  * bytes), also when the call failed, but not when the caller's signal aborted it.
@@ -123,7 +114,7 @@ let ModelImages = class ModelImages {
123
114
  res = await this.run(orgId, prepared, who, callSignal, hooks);
124
115
  }
125
116
  catch (err) {
126
- if (!(err instanceof ImageCallDenied))
117
+ if (!(err instanceof ModelRequestDenied))
127
118
  throw err;
128
119
  const call = {
129
120
  orgId,
@@ -139,7 +130,7 @@ let ModelImages = class ModelImages {
139
130
  hookPlugin: err.verdict.plugin,
140
131
  cause: err.verdict.cause,
141
132
  });
142
- throw new ApiError("model.hook_denied", err.message);
133
+ throw new ApiError("model.hook_denied", modelDeniedText(err.verdict.plugin, err.verdict.reason));
143
134
  }
144
135
  await this.recordExtensionUsage(plugin, orgId, purpose, prepared.ref, res);
145
136
  return {
@@ -274,32 +265,21 @@ let ModelImages = class ModelImages {
274
265
  async run(orgId, prepared, who, signal, hooks) {
275
266
  const { ref, info, request } = prepared;
276
267
  const { provider } = await this.providers.resolve(orgId, ref, { kind: "image_generation" });
277
- if (provider.generateImage === undefined) {
278
- throw new ApiError("model.unconfigured", `Model ${ref.provider}/${ref.model} cannot generate images`);
279
- }
280
- const generate = provider.generateImage.bind(provider);
281
268
  const identity = identityFields(who);
282
269
  const base = { purpose: "image", orgId, provider: ref.provider, model: ref.model };
283
- if (hooks?.has("model.request")) {
284
- const payload = {
285
- ...base,
286
- prompt: request.prompt,
287
- size: { ...request.size },
288
- n: request.n,
289
- referenceImages: (request.referenceImages ?? []).map((r) => ({
290
- type: "media_omitted",
291
- kind: "image",
292
- mediaType: r.mediaType,
293
- size: base64Bytes(r.data),
294
- })),
295
- ...identity,
296
- };
297
- // an abort while the hooks run rejects with the caller's reason (never a deny)
298
- const verdict = await hooks.run("model.request", payload, signal);
299
- if (!verdict.allowed)
300
- throw new ImageCallDenied(verdict);
301
- }
302
- signal.throwIfAborted();
270
+ const generate = await prepareImageGeneration(provider, () => ({
271
+ ...base,
272
+ prompt: request.prompt,
273
+ size: { ...request.size },
274
+ n: request.n,
275
+ referenceImages: (request.referenceImages ?? []).map((r) => ({
276
+ type: "media_omitted",
277
+ kind: "image",
278
+ mediaType: r.mediaType,
279
+ size: base64Bytes(r.data),
280
+ })),
281
+ ...identity,
282
+ }), hooks, signal, ref);
303
283
  const sentAt = Date.now();
304
284
  // the caller measures the latency once, so the hook payload and the result report the same value
305
285
  const respond = (r, latencyMs) => {
@@ -392,6 +372,8 @@ function identityFields(who) {
392
372
  return { extension: who.extension, imagePurpose: who.imagePurpose };
393
373
  }
394
374
  const s = who.scope;
375
+ if (!s)
376
+ return {};
395
377
  return {
396
378
  accountId: s.accountId,
397
379
  agentId: s.agentId,
@@ -7,7 +7,8 @@ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
7
7
  import { KernelDb } from "../infra/database/kernel-db.js";
8
8
  import { TransactionHost } from "../infra/database/transaction-host.js";
9
9
  import { OrgLock } from "../orgs/org-lock.js";
10
- import { ProviderRegistry } from "../runtime/providers.js";
10
+ import type { HookDenial } from "../runtime/hook-calls.js";
11
+ import { type ChatRequestSite, ProviderRegistry } from "../runtime/providers.js";
11
12
  import { StorageService } from "../storage/storage.service.js";
12
13
  /**
13
14
  * 模型用途映射(C9):内核与插件按「用途」取模型,不在代码里写死模型。
@@ -197,8 +198,12 @@ export declare class ModelPurposesService {
197
198
  * `opts.paramDefaults`: values for parameters the target does not set, kept only where the
198
199
  * target model declares the key and the value fits it (e.g. `thinking: "off"` for a short call).
199
200
  */
200
- chat(orgId: string, purpose: string, req: Omit<ModelRequest, "model" | "params">, signal: AbortSignal, opts?: {
201
+ chat(orgId: string, purpose: ChatRequestSite["purpose"], req: Omit<ModelRequest, "model" | "params">, signal: AbortSignal, opts: {
201
202
  fallback?: PurposeTarget;
203
+ hooks: ChatRequestSite["hooks"];
204
+ scope?: ChatRequestSite["scope"];
205
+ step?: number;
206
+ onDenied?: (verdict: HookDenial) => Promise<void>;
202
207
  beforeSend?: (target: ModelRef, request: ModelRequest) => Promise<void>;
203
208
  paramDefaults?: Record<string, ParamValue>;
204
209
  }): Promise<{
@@ -24,7 +24,7 @@ import { createZodDto } from "../infra/validation/create-zod-dto.js";
24
24
  import { OrgLock } from "../orgs/org-lock.js";
25
25
  import { estimateTokens } from "../runtime/context/tokens.js";
26
26
  import { consumeModelStream, deltaChars } from "../runtime/model-call.js";
27
- import { ProviderListError, ProviderRegistry } from "../runtime/providers.js";
27
+ import { ModelRequestDenied, ProviderListError, ProviderRegistry, prepareModelStream, } from "../runtime/providers.js";
28
28
  import { StorageService } from "../storage/storage.service.js";
29
29
  import { IMAGE_PURPOSE, imagePurposeState } from "./image-usable.js";
30
30
  /**
@@ -412,7 +412,7 @@ let ModelPurposesService = class ModelPurposesService {
412
412
  * `opts.paramDefaults`: values for parameters the target does not set, kept only where the
413
413
  * target model declares the key and the value fits it (e.g. `thinking: "off"` for a short call).
414
414
  */
415
- async chat(orgId, purpose, req, signal, opts = {}) {
415
+ async chat(orgId, purpose, req, signal, opts) {
416
416
  const target = await this.chatTarget(orgId, purpose, opts.fallback);
417
417
  const { provider, info } = await this.providers.resolve(orgId, target.model);
418
418
  const request = {
@@ -424,10 +424,23 @@ let ModelPurposesService = class ModelPurposesService {
424
424
  maxOutputTokens: Math.min(req.maxOutputTokens, info.maxOutputTokens),
425
425
  };
426
426
  const idleMs = info.streamIdleTimeoutMs ?? this.config.get().runtime.streamIdleMs;
427
+ const stream = await prepareModelStream(provider, request, {
428
+ ...target.model,
429
+ orgId,
430
+ purpose,
431
+ hooks: opts.hooks,
432
+ scope: opts.scope,
433
+ step: opts.step ?? 0,
434
+ attempt: 1,
435
+ }, signal, this.log).catch(async (error) => {
436
+ if (error instanceof ModelRequestDenied)
437
+ await opts.onDenied?.(error.verdict);
438
+ throw error;
439
+ });
427
440
  await opts.beforeSend?.(target.model, request);
428
441
  let chars = 0;
429
442
  try {
430
- const out = await consumeModelStream(provider, request, idleMs, signal, (ev) => {
443
+ const out = await consumeModelStream(stream, request.model, idleMs, signal, (ev) => {
431
444
  chars += deltaChars(ev);
432
445
  }, this.log);
433
446
  return {
@@ -36,47 +36,3 @@ export declare const DeviceNetworkSettingSchema: z.ZodObject<{
36
36
  export type DeviceNetworkSetting = z.infer<typeof DeviceNetworkSettingSchema>;
37
37
  /** What an invalid stored `deviceNetwork` reads as: the allowlist with no host (never wider). */
38
38
  export declare const invalidDeviceNetwork: () => DeviceNetworkSetting;
39
- /**
40
- * The org network shape before the approval-only profiles design (`cloudNetwork`), read only to
41
- * convert it ({@link convertLegacyCloudNetwork}) and to keep it in step for replicas of the
42
- * previous version until the permission configuration publication converts it.
43
- */
44
- export declare const LegacyCloudNetworkSchema: z.ZodObject<{
45
- mode: z.ZodOptional<z.ZodEnum<{
46
- allowlist: "allowlist";
47
- open: "open";
48
- }>>;
49
- base: z.ZodOptional<z.ZodEnum<{
50
- none: "none";
51
- platform: "platform";
52
- }>>;
53
- extraHosts: z.ZodOptional<z.ZodArray<z.ZodString>>;
54
- excludedHosts: z.ZodOptional<z.ZodArray<z.ZodString>>;
55
- }, z.core.$strict>;
56
- export type LegacyCloudNetwork = z.infer<typeof LegacyCloudNetworkSchema>;
57
- /**
58
- * The stored-key conversion of an org's old `cloudNetwork` (design, "Migration"): `mode:
59
- * "allowlist"` becomes `ceiling: "allowlist"`, keeping `base`, `extraHosts` and `excludedHosts`;
60
- * `mode: "open"` or absent becomes absent. An invalid old value converts to
61
- * {@link invalidDeviceNetwork}, as it read before (never wider). `undefined` stays `undefined`.
62
- */
63
- export declare function convertLegacyCloudNetwork(raw: unknown): DeviceNetworkSetting | undefined;
64
- /**
65
- * The old `cloudNetwork` that says no more than `n`, written next to `deviceNetwork` while the old
66
- * key is still stored (replicas of the previous version read it): `mode: "allowlist"` when either
67
- * the default or the ceiling is the allowlist (never wider for an old reader). `undefined` when `n`
68
- * says nothing the old shape holds.
69
- */
70
- export declare function legacyCloudNetworkOf(n: DeviceNetworkSetting | undefined): LegacyCloudNetwork | undefined;
71
- /**
72
- * `n` with the ceiling (and an open default) narrowed to the allowlist: what an old `fullAccess:
73
- * "off"` adds, since it kept every device of the org on the allowlist (never wider).
74
- */
75
- export declare const withAllowlistCeiling: (n: DeviceNetworkSetting | undefined) => DeviceNetworkSetting;
76
- /**
77
- * A delta never wider than either `a` or `b` (absent: follow the platform), for two stored values
78
- * that disagree (fail closed): the narrower default and ceiling, base `none` when either is, only
79
- * the extra hosts both hold (each covering the other's exactly), and every exclusion of either.
80
- * It may be narrower than both; it is only read while an old replica's write diverges.
81
- */
82
- export declare function narrowerDeviceNetwork(a: DeviceNetworkSetting | undefined, b: DeviceNetworkSetting | undefined): DeviceNetworkSetting | undefined;
@@ -57,86 +57,3 @@ export const invalidDeviceNetwork = () => ({
57
57
  ceiling: "allowlist",
58
58
  base: "none",
59
59
  });
60
- /**
61
- * The org network shape before the approval-only profiles design (`cloudNetwork`), read only to
62
- * convert it ({@link convertLegacyCloudNetwork}) and to keep it in step for replicas of the
63
- * previous version until the permission configuration publication converts it.
64
- */
65
- export const LegacyCloudNetworkSchema = z
66
- .object({
67
- mode: Mode.optional(),
68
- base: z.enum(["platform", "none"]).optional(),
69
- extraHosts: orgHostList("extraHosts"),
70
- excludedHosts: orgHostList("excludedHosts"),
71
- })
72
- .strict();
73
- /** Drops absent fields; an object with none left is `undefined` (follow the platform). */
74
- function compact(n) {
75
- const out = Object.fromEntries(Object.entries(n).filter(([, v]) => v !== undefined));
76
- return Object.keys(out).length === 0 ? undefined : out;
77
- }
78
- /**
79
- * The stored-key conversion of an org's old `cloudNetwork` (design, "Migration"): `mode:
80
- * "allowlist"` becomes `ceiling: "allowlist"`, keeping `base`, `extraHosts` and `excludedHosts`;
81
- * `mode: "open"` or absent becomes absent. An invalid old value converts to
82
- * {@link invalidDeviceNetwork}, as it read before (never wider). `undefined` stays `undefined`.
83
- */
84
- export function convertLegacyCloudNetwork(raw) {
85
- if (raw === undefined)
86
- return undefined;
87
- const parsed = LegacyCloudNetworkSchema.safeParse(raw);
88
- if (!parsed.success)
89
- return invalidDeviceNetwork();
90
- const { mode, ...hosts } = parsed.data;
91
- return compact({ ...(mode === "allowlist" && { ceiling: "allowlist" }), ...hosts });
92
- }
93
- /**
94
- * The old `cloudNetwork` that says no more than `n`, written next to `deviceNetwork` while the old
95
- * key is still stored (replicas of the previous version read it): `mode: "allowlist"` when either
96
- * the default or the ceiling is the allowlist (never wider for an old reader). `undefined` when `n`
97
- * says nothing the old shape holds.
98
- */
99
- export function legacyCloudNetworkOf(n) {
100
- if (n === undefined)
101
- return undefined;
102
- const { default: def, ceiling, ...hosts } = n;
103
- const out = {
104
- ...((def === "allowlist" || ceiling === "allowlist") && { mode: "allowlist" }),
105
- ...hosts,
106
- };
107
- return Object.keys(out).length === 0 ? undefined : out;
108
- }
109
- /**
110
- * `n` with the ceiling (and an open default) narrowed to the allowlist: what an old `fullAccess:
111
- * "off"` adds, since it kept every device of the org on the allowlist (never wider).
112
- */
113
- export const withAllowlistCeiling = (n) => ({
114
- ...n,
115
- ...(n?.default !== undefined && { default: "allowlist" }),
116
- ceiling: "allowlist",
117
- });
118
- const narrowerMode = (a, b) => a === "allowlist" || b === "allowlist" ? "allowlist" : (a ?? b);
119
- /**
120
- * A delta never wider than either `a` or `b` (absent: follow the platform), for two stored values
121
- * that disagree (fail closed): the narrower default and ceiling, base `none` when either is, only
122
- * the extra hosts both hold (each covering the other's exactly), and every exclusion of either.
123
- * It may be narrower than both; it is only read while an old replica's write diverges.
124
- */
125
- export function narrowerDeviceNetwork(a, b) {
126
- if (a === undefined && b === undefined)
127
- return undefined;
128
- const ceiling = narrowerMode(a?.ceiling, b?.ceiling);
129
- let def = narrowerMode(a?.default, b?.default);
130
- if (ceiling === "allowlist" && def === "open")
131
- def = "allowlist";
132
- const extraA = new Set(a?.extraHosts ?? []);
133
- const extra = (b?.extraHosts ?? []).filter((h) => extraA.has(h));
134
- const excluded = [...new Set([...(a?.excludedHosts ?? []), ...(b?.excludedHosts ?? [])])];
135
- return compact({
136
- default: def,
137
- ceiling,
138
- base: a?.base === "none" || b?.base === "none" ? "none" : (a?.base ?? b?.base),
139
- extraHosts: extra.length > 0 ? extra : undefined,
140
- excludedHosts: excluded.length > 0 ? excluded : undefined,
141
- });
142
- }