@capybara-hq/kernel 0.1.0-rc.41 → 0.1.0-rc.43

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 (359) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/admin/admin.schemas.d.ts +6 -0
  3. package/dist/admin/org-network.service.d.ts +3 -1
  4. package/dist/admin/org-network.service.js +10 -2
  5. package/dist/app.d.ts +4 -0
  6. package/dist/app.js +2 -0
  7. package/dist/background/finish.d.ts +9 -1
  8. package/dist/background/finish.js +57 -4
  9. package/dist/background/launch.d.ts +23 -0
  10. package/dist/background/launch.js +55 -1
  11. package/dist/background/managed-output.d.ts +110 -0
  12. package/dist/background/managed-output.js +219 -0
  13. package/dist/background/managed.d.ts +52 -0
  14. package/dist/background/managed.js +128 -0
  15. package/dist/background/poll.job.d.ts +35 -1
  16. package/dist/background/poll.job.js +174 -9
  17. package/dist/background/render.js +1 -0
  18. package/dist/background/retire-legacy-tasks.job.d.ts +57 -0
  19. package/dist/background/retire-legacy-tasks.job.js +149 -0
  20. package/dist/background/session.d.ts +15 -5
  21. package/dist/background/session.js +22 -6
  22. package/dist/background/stop.d.ts +35 -5
  23. package/dist/background/stop.js +94 -8
  24. package/dist/background/store.d.ts +110 -3
  25. package/dist/background/store.js +205 -3
  26. package/dist/background/tasks.service.d.ts +18 -1
  27. package/dist/background/tasks.service.js +99 -9
  28. package/dist/catalog/marketplaces.service.d.ts +1 -1
  29. package/dist/channels/cards.js +1 -1
  30. package/dist/channels/inbound.js +2 -0
  31. package/dist/channels/phrases.d.ts +4 -0
  32. package/dist/channels/phrases.js +4 -0
  33. package/dist/config/load.d.ts +18 -0
  34. package/dist/config/load.js +39 -1
  35. package/dist/config/permission-migration.d.ts +26 -0
  36. package/dist/config/permission-migration.js +64 -0
  37. package/dist/config/schema.d.ts +4 -1
  38. package/dist/config/schema.js +41 -10
  39. package/dist/conversations/conversations.controller.d.ts +1 -1
  40. package/dist/conversations/conversations.controller.js +1 -1
  41. package/dist/conversations/conversations.module.js +12 -0
  42. package/dist/conversations/conversations.service.d.ts +11 -2
  43. package/dist/conversations/conversations.service.js +97 -27
  44. package/dist/conversations/event-log.d.ts +1 -1
  45. package/dist/conversations/event-log.js +10 -2
  46. package/dist/conversations/events.d.ts +307 -4
  47. package/dist/conversations/events.js +286 -32
  48. package/dist/conversations/permission-profile-store.d.ts +50 -0
  49. package/dist/conversations/permission-profile-store.js +67 -0
  50. package/dist/conversations/permission-profile-store.module.d.ts +2 -0
  51. package/dist/conversations/permission-profile-store.module.js +19 -0
  52. package/dist/conversations/permission-profiles.controller.d.ts +84 -0
  53. package/dist/conversations/permission-profiles.controller.js +105 -0
  54. package/dist/conversations/permission-profiles.schemas.d.ts +31 -0
  55. package/dist/conversations/permission-profiles.schemas.js +23 -0
  56. package/dist/conversations/permission-profiles.service.d.ts +56 -0
  57. package/dist/conversations/permission-profiles.service.js +179 -0
  58. package/dist/ctx/create-ctx.d.ts +12 -5
  59. package/dist/ctx/create-ctx.js +21 -5
  60. package/dist/db/kernel-schema.d.ts +248 -3
  61. package/dist/devices/access.js +1 -1
  62. package/dist/devices/access.module.d.ts +2 -0
  63. package/dist/devices/access.module.js +19 -0
  64. package/dist/devices/conversation-devices.d.ts +8 -29
  65. package/dist/devices/conversation-devices.js +37 -73
  66. package/dist/devices/device-projects.service.d.ts +26 -28
  67. package/dist/devices/device-projects.service.js +123 -127
  68. package/dist/devices/devices.controller.js +3 -1
  69. package/dist/devices/devices.module.js +11 -9
  70. package/dist/devices/devices.service.d.ts +116 -8
  71. package/dist/devices/devices.service.js +252 -20
  72. package/dist/devices/dto.d.ts +16 -0
  73. package/dist/devices/dto.js +34 -6
  74. package/dist/devices/errors.d.ts +8 -0
  75. package/dist/devices/errors.js +10 -0
  76. package/dist/devices/project-rules.d.ts +44 -0
  77. package/dist/devices/project-rules.js +27 -0
  78. package/dist/devices/working-root.d.ts +6 -0
  79. package/dist/devices/working-root.js +12 -1
  80. package/dist/errors.d.ts +31 -0
  81. package/dist/errors.js +31 -0
  82. package/dist/evals/reconstruct.d.ts +19 -2
  83. package/dist/evals/reconstruct.js +40 -2
  84. package/dist/evals/recorded-permission-context.d.ts +77 -0
  85. package/dist/evals/recorded-permission-context.js +151 -0
  86. package/dist/evals/recorded-tools.d.ts +10 -1
  87. package/dist/evals/recorded-tools.js +27 -3
  88. package/dist/evals/run-replay.d.ts +8 -2
  89. package/dist/evals/run-replay.js +18 -2
  90. package/dist/evals/trajectory.d.ts +1 -1
  91. package/dist/evals/worker.d.ts +10 -1
  92. package/dist/evals/worker.js +23 -14
  93. package/dist/extensions/host.d.ts +4 -1
  94. package/dist/extensions/host.js +10 -6
  95. package/dist/http/api.module.js +2 -0
  96. package/dist/identity/accounts.d.ts +14 -1
  97. package/dist/identity/accounts.js +61 -5
  98. package/dist/identity/identity.module.js +2 -0
  99. package/dist/identity/settings.d.ts +28 -12
  100. package/dist/identity/settings.js +89 -33
  101. package/dist/index.d.ts +6 -0
  102. package/dist/index.js +5 -0
  103. package/dist/infra/cli/kernel-cli.module.d.ts +2 -2
  104. package/dist/infra/cli/kernel-cli.module.js +5 -2
  105. package/dist/infra/cli/permission-cutover.d.ts +59 -0
  106. package/dist/infra/cli/permission-cutover.js +107 -0
  107. package/dist/infra/config/kernel-config.service.d.ts +2 -2
  108. package/dist/infra/config/kernel-config.service.js +35 -11
  109. package/dist/infra/database/startup-activation-transaction.d.ts +36 -0
  110. package/dist/infra/database/startup-activation-transaction.js +242 -0
  111. package/dist/infra/database/transaction-host.d.ts +47 -0
  112. package/dist/infra/database/transaction-host.js +119 -0
  113. package/dist/infra/database/xact-lock.d.ts +1 -0
  114. package/dist/infra/database/xact-lock.js +6 -0
  115. package/dist/infra/outbox/registry.d.ts +39 -0
  116. package/dist/infra/outbox/registry.js +18 -0
  117. package/dist/kernel.module.js +2 -0
  118. package/dist/lifecycle/kernel-lifecycle.d.ts +3 -1
  119. package/dist/lifecycle/kernel-lifecycle.js +55 -28
  120. package/dist/local-devices/device-auth.js +1 -1
  121. package/dist/local-devices/device-policy.service.d.ts +35 -5
  122. package/dist/local-devices/device-policy.service.js +188 -13
  123. package/dist/local-devices/instance-bindings.d.ts +82 -0
  124. package/dist/local-devices/instance-bindings.js +304 -0
  125. package/dist/local-devices/keys.d.ts +5 -0
  126. package/dist/local-devices/keys.js +5 -0
  127. package/dist/local-devices/local-device-gateway.d.ts +19 -4
  128. package/dist/local-devices/local-device-gateway.js +185 -17
  129. package/dist/local-devices/local-device-provider.d.ts +42 -7
  130. package/dist/local-devices/local-device-provider.js +185 -10
  131. package/dist/local-devices/local-devices.module.d.ts +17 -2
  132. package/dist/local-devices/local-devices.module.js +49 -8
  133. package/dist/local-devices/machines.d.ts +35 -12
  134. package/dist/local-devices/machines.js +203 -8
  135. package/dist/local-devices/network-grants.js +3 -3
  136. package/dist/local-devices/network-grants.module.d.ts +2 -0
  137. package/dist/local-devices/network-grants.module.js +14 -0
  138. package/dist/local-devices/owner-report.d.ts +79 -0
  139. package/dist/local-devices/owner-report.js +155 -0
  140. package/dist/local-devices/owner-reports.d.ts +48 -0
  141. package/dist/local-devices/owner-reports.js +190 -0
  142. package/dist/local-devices/policy-summary.d.ts +24 -1
  143. package/dist/local-devices/policy-summary.js +48 -0
  144. package/dist/local-devices/relay.d.ts +82 -6
  145. package/dist/local-devices/relay.js +187 -16
  146. package/dist/local-devices/targets.d.ts +16 -1
  147. package/dist/local-devices/targets.js +35 -2
  148. package/dist/models/image-usable.d.ts +22 -0
  149. package/dist/models/image-usable.js +29 -0
  150. package/dist/models/images.d.ts +125 -0
  151. package/dist/models/images.js +440 -0
  152. package/dist/models/models.module.d.ts +3 -2
  153. package/dist/models/models.module.js +16 -5
  154. package/dist/models/org-models.schemas.js +1 -0
  155. package/dist/models/purposes.controller.d.ts +7 -0
  156. package/dist/models/purposes.controller.js +9 -0
  157. package/dist/models/purposes.d.ts +28 -3
  158. package/dist/models/purposes.js +40 -13
  159. package/dist/orgs/cloud-network-setting.d.ts +33 -0
  160. package/dist/orgs/cloud-network-setting.js +47 -0
  161. package/dist/orgs/offboarding.d.ts +3 -1
  162. package/dist/orgs/offboarding.js +8 -2
  163. package/dist/orgs/org-lock.d.ts +10 -4
  164. package/dist/orgs/org-lock.js +10 -4
  165. package/dist/orgs/orgs.service.d.ts +3 -1
  166. package/dist/orgs/orgs.service.js +8 -2
  167. package/dist/orgs/settings.controller.d.ts +4 -1
  168. package/dist/orgs/settings.controller.js +3 -3
  169. package/dist/orgs/settings.service.d.ts +48 -56
  170. package/dist/orgs/settings.service.js +144 -101
  171. package/dist/overrides.d.ts +6 -1
  172. package/dist/overrides.js +2 -0
  173. package/dist/platform/exclusions.js +20 -0
  174. package/dist/platform/ops/admin.ops.js +14 -11
  175. package/dist/platform/ops/agent-skills.ops.js +2 -0
  176. package/dist/platform/ops/devices.ops.js +10 -2
  177. package/dist/platform/ops/models.ops.js +10 -0
  178. package/dist/platform/ops/org-settings.ops.js +6 -6
  179. package/dist/platform/ops/orgs.ops.js +1 -0
  180. package/dist/roles/worker.module.js +4 -0
  181. package/dist/runtime/context/build.d.ts +3 -1
  182. package/dist/runtime/context/build.js +19 -3
  183. package/dist/runtime/context/compaction.js +5 -0
  184. package/dist/runtime/context/device-paths.d.ts +9 -2
  185. package/dist/runtime/context/device-paths.js +20 -0
  186. package/dist/runtime/context/permission-profile.d.ts +46 -0
  187. package/dist/runtime/context/permission-profile.js +194 -0
  188. package/dist/runtime/hook-calls.d.ts +11 -1
  189. package/dist/runtime/hook-calls.js +24 -1
  190. package/dist/runtime/maintenance.d.ts +7 -1
  191. package/dist/runtime/maintenance.js +43 -15
  192. package/dist/runtime/model-call.d.ts +32 -0
  193. package/dist/runtime/model-call.js +67 -0
  194. package/dist/runtime/permission-context-errors.d.ts +39 -0
  195. package/dist/runtime/permission-context-errors.js +67 -0
  196. package/dist/runtime/permission-context.service.d.ts +60 -0
  197. package/dist/runtime/permission-context.service.js +286 -0
  198. package/dist/runtime/project/knowledge.d.ts +7 -2
  199. package/dist/runtime/project/knowledge.js +5 -2
  200. package/dist/runtime/project/knowledge.service.d.ts +17 -2
  201. package/dist/runtime/project/knowledge.service.js +76 -12
  202. package/dist/runtime/providers.d.ts +9 -5
  203. package/dist/runtime/providers.js +22 -3
  204. package/dist/runtime/run-execution.d.ts +4 -1
  205. package/dist/runtime/run-execution.js +14 -5
  206. package/dist/runtime/run-steps.d.ts +11 -3
  207. package/dist/runtime/run-steps.js +27 -4
  208. package/dist/runtime/runtime.module.js +11 -0
  209. package/dist/runtime/usage-report.d.ts +10 -6
  210. package/dist/runtime/usage-report.js +31 -11
  211. package/dist/sandbox/attachments-path.d.ts +15 -0
  212. package/dist/sandbox/attachments-path.js +15 -0
  213. package/dist/sandbox/cloud-permission-snapshot.d.ts +159 -0
  214. package/dist/sandbox/cloud-permission-snapshot.js +407 -0
  215. package/dist/sandbox/cloud-permission-snapshot.module.d.ts +8 -0
  216. package/dist/sandbox/cloud-permission-snapshot.module.js +34 -0
  217. package/dist/sandbox/held-operations.d.ts +39 -0
  218. package/dist/sandbox/held-operations.js +119 -0
  219. package/dist/sandbox/jobs.d.ts +14 -3
  220. package/dist/sandbox/jobs.js +20 -2
  221. package/dist/sandbox/kernel-read.d.ts +55 -0
  222. package/dist/sandbox/kernel-read.js +57 -0
  223. package/dist/sandbox/legacy-retirement.d.ts +336 -0
  224. package/dist/sandbox/legacy-retirement.js +1063 -0
  225. package/dist/sandbox/legacy-retirement.module.d.ts +8 -0
  226. package/dist/sandbox/legacy-retirement.module.js +25 -0
  227. package/dist/sandbox/managed-device-context.d.ts +94 -0
  228. package/dist/sandbox/managed-device-context.js +308 -0
  229. package/dist/sandbox/managed-device-context.module.d.ts +6 -0
  230. package/dist/sandbox/managed-device-context.module.js +33 -0
  231. package/dist/sandbox/modes.d.ts +56 -8
  232. package/dist/sandbox/modes.js +92 -8
  233. package/dist/sandbox/operation-authority-types.d.ts +8 -0
  234. package/dist/sandbox/operation-authority-types.js +32 -0
  235. package/dist/sandbox/operation-authority.d.ts +145 -0
  236. package/dist/sandbox/operation-authority.js +783 -0
  237. package/dist/sandbox/operation-authority.module.d.ts +2 -0
  238. package/dist/sandbox/operation-authority.module.js +29 -0
  239. package/dist/sandbox/operation-intents.d.ts +206 -0
  240. package/dist/sandbox/operation-intents.js +1252 -0
  241. package/dist/sandbox/operation-intents.module.d.ts +2 -0
  242. package/dist/sandbox/operation-intents.module.js +21 -0
  243. package/dist/sandbox/operation-payloads.d.ts +33 -0
  244. package/dist/sandbox/operation-payloads.js +332 -0
  245. package/dist/sandbox/operation-reconcile.job.d.ts +49 -0
  246. package/dist/sandbox/operation-reconcile.job.js +247 -0
  247. package/dist/sandbox/permission-authority-epochs.d.ts +18 -0
  248. package/dist/sandbox/permission-authority-epochs.js +83 -0
  249. package/dist/sandbox/permission-authority-lock.d.ts +38 -0
  250. package/dist/sandbox/permission-authority-lock.js +147 -0
  251. package/dist/sandbox/permission-authority.module.d.ts +9 -0
  252. package/dist/sandbox/permission-authority.module.js +55 -0
  253. package/dist/sandbox/permission-availability.d.ts +18 -0
  254. package/dist/sandbox/permission-availability.js +19 -0
  255. package/dist/sandbox/permission-call-grants.d.ts +34 -0
  256. package/dist/sandbox/permission-call-grants.js +349 -0
  257. package/dist/sandbox/permission-call-grants.module.d.ts +2 -0
  258. package/dist/sandbox/permission-call-grants.module.js +21 -0
  259. package/dist/sandbox/permission-call-types.d.ts +82 -0
  260. package/dist/sandbox/permission-call-types.js +1 -0
  261. package/dist/sandbox/permission-ceiling-writes.d.ts +47 -0
  262. package/dist/sandbox/permission-ceiling-writes.js +223 -0
  263. package/dist/sandbox/permission-config-publication.d.ts +76 -0
  264. package/dist/sandbox/permission-config-publication.js +339 -0
  265. package/dist/sandbox/permission-context-types.d.ts +64 -0
  266. package/dist/sandbox/permission-context-types.js +24 -0
  267. package/dist/sandbox/permission-facts.d.ts +206 -0
  268. package/dist/sandbox/permission-facts.js +627 -0
  269. package/dist/sandbox/permission-facts.module.d.ts +2 -0
  270. package/dist/sandbox/permission-facts.module.js +20 -0
  271. package/dist/sandbox/permission-instance-writes.d.ts +90 -0
  272. package/dist/sandbox/permission-instance-writes.js +305 -0
  273. package/dist/sandbox/permission-runtime-reports.d.ts +83 -0
  274. package/dist/sandbox/permission-runtime-reports.js +354 -0
  275. package/dist/sandbox/permission-transitions.d.ts +31 -0
  276. package/dist/sandbox/permission-transitions.js +155 -0
  277. package/dist/sandbox/platform-full-access.d.ts +128 -0
  278. package/dist/sandbox/platform-full-access.js +210 -0
  279. package/dist/sandbox/providers.d.ts +22 -0
  280. package/dist/sandbox/providers.js +10 -2
  281. package/dist/sandbox/providers.module.d.ts +2 -0
  282. package/dist/sandbox/providers.module.js +19 -0
  283. package/dist/sandbox/request-not-sent.d.ts +13 -0
  284. package/dist/sandbox/request-not-sent.js +13 -0
  285. package/dist/sandbox/review/classifier.d.ts +2 -0
  286. package/dist/sandbox/review/classifier.js +8 -0
  287. package/dist/sandbox/review/permission-candidate.d.ts +12 -0
  288. package/dist/sandbox/review/permission-candidate.js +145 -0
  289. package/dist/sandbox/review/review.service.d.ts +5 -2
  290. package/dist/sandbox/review/review.service.js +60 -15
  291. package/dist/sandbox/sandbox-file-reader.d.ts +18 -1
  292. package/dist/sandbox/sandbox-file-reader.js +51 -7
  293. package/dist/sandbox/sandbox.module.js +26 -6
  294. package/dist/sandbox/sandbox.service.d.ts +230 -34
  295. package/dist/sandbox/sandbox.service.js +1368 -199
  296. package/dist/sandbox/unreachable.js +17 -3
  297. package/dist/sandbox/use-context.d.ts +17 -0
  298. package/dist/sandbox/use-context.js +1 -0
  299. package/dist/skills/invoke.d.ts +27 -4
  300. package/dist/skills/invoke.js +72 -7
  301. package/dist/tools/approvals.controller.d.ts +1 -0
  302. package/dist/tools/approvals.schemas.d.ts +1 -0
  303. package/dist/tools/approvals.schemas.js +3 -1
  304. package/dist/tools/approvals.service.d.ts +23 -10
  305. package/dist/tools/approvals.service.js +104 -26
  306. package/dist/tools/builtin-names.d.ts +3 -1
  307. package/dist/tools/builtin-names.js +5 -1
  308. package/dist/tools/builtins/artifacts.d.ts +43 -0
  309. package/dist/tools/builtins/artifacts.js +67 -0
  310. package/dist/tools/builtins/builtin-tools.d.ts +20 -2
  311. package/dist/tools/builtins/builtin-tools.js +61 -10
  312. package/dist/tools/builtins/image/generate.d.ts +59 -0
  313. package/dist/tools/builtins/image/generate.js +535 -0
  314. package/dist/tools/builtins/image/index.d.ts +2 -0
  315. package/dist/tools/builtins/image/index.js +2 -0
  316. package/dist/tools/builtins/image/paths.d.ts +12 -0
  317. package/dist/tools/builtins/image/paths.js +26 -0
  318. package/dist/tools/builtins/sandbox/bash.d.ts +25 -1
  319. package/dist/tools/builtins/sandbox/bash.js +201 -5
  320. package/dist/tools/builtins/sandbox/common.d.ts +92 -20
  321. package/dist/tools/builtins/sandbox/common.js +201 -17
  322. package/dist/tools/builtins/sandbox/deliver.js +9 -51
  323. package/dist/tools/builtins/sandbox/edit.js +2 -2
  324. package/dist/tools/builtins/sandbox/fetch-attachment.js +11 -4
  325. package/dist/tools/builtins/sandbox/glob.js +2 -2
  326. package/dist/tools/builtins/sandbox/grep.js +2 -2
  327. package/dist/tools/builtins/sandbox/read.js +2 -2
  328. package/dist/tools/builtins/sandbox/task-list.js +7 -1
  329. package/dist/tools/builtins/sandbox/task-output.d.ts +1 -1
  330. package/dist/tools/builtins/sandbox/task-output.js +172 -0
  331. package/dist/tools/builtins/sandbox/task-stop.js +25 -3
  332. package/dist/tools/builtins/sandbox/write.js +2 -2
  333. package/dist/tools/builtins/skill-load.js +9 -6
  334. package/dist/tools/device-op-resolver.d.ts +1 -1
  335. package/dist/tools/device-op-resolver.js +13 -3
  336. package/dist/tools/permission-approval-jobs.d.ts +18 -0
  337. package/dist/tools/permission-approval-jobs.js +92 -0
  338. package/dist/tools/pipeline.d.ts +17 -2
  339. package/dist/tools/pipeline.js +315 -26
  340. package/dist/tools/registry.d.ts +9 -0
  341. package/dist/tools/tools.module.js +15 -0
  342. package/package.json +4 -3
  343. package/src/migrations/0146_permission_authority_epochs.sql +6 -0
  344. package/src/migrations/0147_conversation_permission_profiles.sql +4 -0
  345. package/src/migrations/0148_first_message_request_hash.sql +2 -0
  346. package/src/migrations/0149_sandbox_operation_intents.sql +66 -0
  347. package/src/migrations/0150_permission_call_grants_and_approvals.sql +36 -0
  348. package/src/migrations/0151_starting_execution_grants.sql +8 -0
  349. package/src/migrations/0152_background_launch_identity.sql +66 -0
  350. package/src/migrations/0153_background_cancel_requester.sql +13 -0
  351. package/src/migrations/0154_cloud_owner_ceiling.sql +14 -0
  352. package/src/migrations/0155_device_instance_generations.sql +30 -0
  353. package/src/migrations/0156_device_owner_report.sql +7 -0
  354. package/src/migrations/0157_legacy_retirement.sql +116 -0
  355. package/src/migrations/0158_legacy_freeze_enumerated.sql +5 -0
  356. package/src/migrations/0159_retirement_exact_cancel.sql +9 -0
  357. package/src/migrations/0160_model_usage_image_kind.sql +10 -0
  358. package/dist/sandbox/platform-auto-mode.d.ts +0 -63
  359. package/dist/sandbox/platform-auto-mode.js +0 -63
@@ -0,0 +1,440 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { IMAGE_ASPECT_RATIOS, IMAGE_MEDIA_TYPES, isModelError, MEDIA_LIMITS, ModelError, pickImageSize, sanitizeParams, validateImageGenerateResult, } from "@capybara-hq/plugin-sdk";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
+ import { ApiError } from "../errors.js";
13
+ import { isExtensionEnabled } from "../extensions/enabled.js";
14
+ import { audit } from "../identity/audit.js";
15
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
16
+ import { KernelDb } from "../infra/database/kernel-db.js";
17
+ import { TransactionHost } from "../infra/database/transaction-host.js";
18
+ import { Transactional } from "../infra/database/transactional.decorator.js";
19
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
20
+ import { base64Bytes, fireObserve, imageDeniedAudit, } from "../runtime/hook-calls.js";
21
+ import { modelDeniedText } from "../runtime/model-call.js";
22
+ import { ProviderRegistry } from "../runtime/providers.js";
23
+ import { UsageReportJobs } from "../runtime/usage-report-jobs.js";
24
+ import { ModelPurposesService } from "./purposes.js";
25
+ /** Standard padded base64 (the check `validateImageGenerateResult` applies to results). */
26
+ const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
27
+ /** `MEDIA_LIMITS.imageBytes` in MB, for the reference-image error text. */
28
+ const IMAGE_LIMIT_MB = MEDIA_LIMITS.imageBytes / 1_048_576;
29
+ /** A `model.request` policy hook denied the call; nothing was sent. The caller records it. */
30
+ export class ImageCallDenied extends Error {
31
+ verdict;
32
+ constructor(verdict) {
33
+ super(modelDeniedText(verdict.plugin, verdict.reason));
34
+ this.verdict = verdict;
35
+ this.name = "ImageCallDenied";
36
+ }
37
+ }
38
+ /**
39
+ * Image generation calls (image generation spec §5.1, §5.2, §5.6, §6), shared by the
40
+ * `GenerateImage` tool and `ctx.models.generateImage`:
41
+ * - {@link prepare} resolves the org's target for a purpose of kind `image_generation` (no
42
+ * fallback: unmapped is `model.unconfigured`), checks the prompt (code points, at most
43
+ * `models.imagePromptMaxChars`), the count (at most `models.imageMaxPerCall` and the model's
44
+ * `maxImages`), the reference images (count, media type, `MEDIA_LIMITS.imageBytes`), picks the
45
+ * size ({@link pickImageSize}) and sanitizes the mapping's params against the model's
46
+ * declarations. Every refusal is `ApiError("validation_failed")` with an actionable text.
47
+ * - {@link run} fires `model.request` (placeholders for references; a denial throws
48
+ * {@link ImageCallDenied} and sends nothing), calls `generateImage` within
49
+ * `models.imageTimeoutMs`, checks the result ({@link validateImageGenerateResult}: invalid is a
50
+ * `ModelError("server")`) and fires `model.response` (observe; media types and byte sizes, never
51
+ * bytes), also when the call failed, but not when the caller's signal aborted it.
52
+ * They store nothing and record no usage: the callers do. For extensions (spec §5.5, §8, §9),
53
+ * {@link generateForExtension} is `ctx.models.generateImage`: the admission of `ctx.models.embed`
54
+ * for kind `image_generation` (a purpose the extension declared with that kind, otherwise
55
+ * `model.purpose_unknown`; an org that enabled the extension, otherwise `extension.not_enabled`),
56
+ * then {@link prepare} and {@link run}; a policy denial writes one `hook.denied` audit row and
57
+ * rejects with `ApiError("model.hook_denied")`; a successful call writes one `model_usage` row
58
+ * (`kind = 'image_generation'`, its input tokens and images) and owes its `usage.report` delivery
59
+ * in the same transaction ({@link recordExtensionUsage}). A call that fails or is denied records
60
+ * no usage. The kernel stores no image of an extension call: the extension gets the bytes.
61
+ */
62
+ let ModelImages = class ModelImages {
63
+ purposes;
64
+ providers;
65
+ log;
66
+ config;
67
+ kdb;
68
+ txHost;
69
+ usage;
70
+ constructor(purposes, providers, log,
71
+ /** `models.imageTimeoutMs`, `imageMaxPerCall`, `imagePromptMaxChars` (hot, read per call). */
72
+ config, kdb, txHost,
73
+ /** An extension call's `usage.report` delivery, owed with its `model_usage` row. */
74
+ usage) {
75
+ this.purposes = purposes;
76
+ this.providers = providers;
77
+ this.log = log;
78
+ this.config = config;
79
+ this.kdb = kdb;
80
+ this.txHost = txHost;
81
+ this.usage = usage;
82
+ }
83
+ /** Refuses a purpose `plugin` did not declare with kind `image_generation`, or an org it is off in. */
84
+ async admit(plugin, declared, orgId, purpose) {
85
+ if (!declared.some((d) => d.purpose === purpose && d.kind === "image_generation")) {
86
+ throw new ApiError("model.purpose_unknown", `Extension ${plugin} declared no image generation purpose "${purpose}" in permissions.models`);
87
+ }
88
+ if (!(await isExtensionEnabled(this.kdb.db, orgId, plugin))) {
89
+ throw new ApiError("extension.not_enabled", `Extension ${plugin} is not enabled in organization ${orgId}`);
90
+ }
91
+ }
92
+ /**
93
+ * `ctx.models.generateImage` for `plugin` (its declared purposes), aborted by `signal` (the
94
+ * instance's) and the request's own signal; `hooks` is the host's hook registry
95
+ * (`model.request`, `model.response`), absent only for a ctx built without a host (tests).
96
+ */
97
+ async generateForExtension(plugin, declared, request, signal, hooks) {
98
+ checkExtensionRequest(request);
99
+ // a copy, read once: what the hooks see is what is sent, whatever the extension does with its
100
+ // own request object meanwhile
101
+ const { orgId, purpose } = request;
102
+ const input = {
103
+ prompt: request.prompt,
104
+ ...(request.size !== undefined && {
105
+ size: { width: request.size.width, height: request.size.height },
106
+ }),
107
+ ...(request.aspectRatio !== undefined && { aspectRatio: request.aspectRatio }),
108
+ ...(request.n !== undefined && { n: request.n }),
109
+ ...(request.referenceImages !== undefined && {
110
+ referenceImages: request.referenceImages.map((r) => ({
111
+ mediaType: r?.mediaType,
112
+ data: r?.data,
113
+ })),
114
+ }),
115
+ };
116
+ await this.admit(plugin, declared, orgId, purpose);
117
+ const prepared = await this.prepare(orgId, purpose, input);
118
+ const callSignal = request.signal ? AbortSignal.any([signal, request.signal]) : signal;
119
+ const who = { kind: "extension", extension: plugin, imagePurpose: purpose };
120
+ let res;
121
+ try {
122
+ res = await this.run(orgId, prepared, who, callSignal, hooks);
123
+ }
124
+ catch (err) {
125
+ if (!(err instanceof ImageCallDenied))
126
+ throw err;
127
+ const call = {
128
+ orgId,
129
+ extension: plugin,
130
+ imagePurpose: purpose,
131
+ provider: prepared.ref.provider,
132
+ model: prepared.ref.model,
133
+ };
134
+ await audit(this.kdb.db, imageDeniedAudit(call, err.verdict));
135
+ this.log.warn("image generation call blocked by a policy hook", {
136
+ plugin,
137
+ orgId,
138
+ hookPlugin: err.verdict.plugin,
139
+ cause: err.verdict.cause,
140
+ });
141
+ throw new ApiError("model.hook_denied", err.message);
142
+ }
143
+ await this.recordExtensionUsage(plugin, orgId, purpose, prepared.ref, res);
144
+ return {
145
+ images: res.images.map((i) => ({ mediaType: i.mediaType, data: i.data })),
146
+ ...(typeof res.revisedPrompt === "string" && { revisedPrompt: res.revisedPrompt }),
147
+ model: { provider: prepared.ref.provider, id: prepared.ref.model },
148
+ size: { width: prepared.request.size.width, height: prepared.request.size.height },
149
+ };
150
+ }
151
+ /**
152
+ * `ctx.models.describe` of an image generation purpose for `plugin`: the org's effective target
153
+ * with its `imageGeneration` facts, or null when the purpose maps to no model the org can use.
154
+ */
155
+ async describeForExtension(plugin, declared, req) {
156
+ if (typeof req?.orgId !== "string" || typeof req.purpose !== "string") {
157
+ throw new ApiError("validation_failed", "describe needs orgId and purpose strings");
158
+ }
159
+ await this.admit(plugin, declared, req.orgId, req.purpose);
160
+ try {
161
+ const target = await this.purposes.resolve(req.orgId, req.purpose);
162
+ const { info } = await this.providers.resolve(req.orgId, target.model, {
163
+ kind: "image_generation",
164
+ });
165
+ if (info.imageGeneration === undefined)
166
+ return null;
167
+ return {
168
+ provider: target.model.provider,
169
+ id: target.model.model,
170
+ kind: "image_generation",
171
+ imageGeneration: structuredClone(info.imageGeneration),
172
+ };
173
+ }
174
+ catch (e) {
175
+ if (e instanceof ApiError && e.code === "model.unconfigured")
176
+ return null;
177
+ throw e;
178
+ }
179
+ }
180
+ /**
181
+ * One `model_usage` row of an extension call (`kind = 'image_generation'`, the result's tokens
182
+ * and images) with its owed `usage.report` delivery, in one transaction.
183
+ */
184
+ async recordExtensionUsage(plugin, orgId, purpose, ref, res) {
185
+ const row = await this.kdb.db
186
+ .insertInto("model_usage")
187
+ .values({
188
+ org_id: orgId,
189
+ extension: plugin,
190
+ purpose,
191
+ kind: "image_generation",
192
+ provider: ref.provider,
193
+ model: ref.model,
194
+ // `run` validated the answer's usage (validateImageGenerateResult): whole counts
195
+ input_tokens: res.usage.inputTokens,
196
+ output_tokens: res.usage.outputTokens,
197
+ cache_read_tokens: res.usage.cacheReadTokens,
198
+ cache_write_tokens: res.usage.cacheWriteTokens,
199
+ output_images: billedImages(res),
200
+ })
201
+ .returning("id")
202
+ .executeTakeFirstOrThrow();
203
+ await this.usage.oweModelUsage(row.id, orgId);
204
+ }
205
+ async prepare(orgId, purpose, input) {
206
+ const limits = this.config.get().models;
207
+ const bad = (text) => {
208
+ throw new ApiError("validation_failed", text);
209
+ };
210
+ const prompt = typeof input.prompt === "string" ? input.prompt : "";
211
+ if (prompt.trim() === "")
212
+ bad("prompt must not be empty");
213
+ const chars = [...prompt].length;
214
+ if (chars > limits.imagePromptMaxChars) {
215
+ bad(`prompt has ${chars} characters; the limit is ${limits.imagePromptMaxChars}`);
216
+ }
217
+ const target = await this.purposes.resolve(orgId, purpose);
218
+ const { info } = await this.providers.resolve(orgId, target.model, {
219
+ kind: "image_generation",
220
+ });
221
+ const gen = info.imageGeneration;
222
+ if (gen === undefined) {
223
+ // the registry refuses such models; kept as a guard
224
+ throw new ApiError("model.unconfigured", `The model configured for the "${purpose}" purpose cannot generate images`);
225
+ }
226
+ const cap = Math.min(limits.imageMaxPerCall, gen.maxImages);
227
+ const n = input.n ?? 1;
228
+ if (!Number.isInteger(n) || n < 1)
229
+ bad(`n must be a whole number from 1 to ${cap}`);
230
+ if (n > cap)
231
+ bad(`n must be at most ${cap} for this model`);
232
+ const refs = input.referenceImages ?? [];
233
+ if (refs.length > gen.maxReferenceImages) {
234
+ bad(gen.maxReferenceImages === 0
235
+ ? "this model takes no reference images"
236
+ : `this model takes at most ${gen.maxReferenceImages} reference images`);
237
+ }
238
+ refs.forEach((r, i) => {
239
+ const okType = IMAGE_MEDIA_TYPES.includes(r?.mediaType);
240
+ const okData = typeof r?.data === "string" && BASE64.test(r.data);
241
+ if (!okType || !okData || base64Bytes(r.data) > MEDIA_LIMITS.imageBytes) {
242
+ bad(`reference image ${i} must be PNG, JPEG, GIF or WebP up to ${IMAGE_LIMIT_MB} MB`);
243
+ }
244
+ });
245
+ const size = pickImageSize(gen, {
246
+ ...(input.size !== undefined && { size: input.size }),
247
+ ...(input.aspectRatio !== undefined && { aspectRatio: input.aspectRatio }),
248
+ });
249
+ if (!size.ok)
250
+ return bad(size.error);
251
+ const params = sanitizeParams(info.parameters ?? [], target.params).value;
252
+ return {
253
+ ref: { provider: target.model.provider, model: target.model.model },
254
+ info: structuredClone(gen),
255
+ request: {
256
+ model: target.model.model,
257
+ prompt,
258
+ size: size.size,
259
+ n,
260
+ ...(refs.length > 0 && {
261
+ referenceImages: refs.map((r) => ({ mediaType: r.mediaType, data: r.data })),
262
+ }),
263
+ params,
264
+ },
265
+ };
266
+ }
267
+ async run(orgId, prepared, who, signal, hooks) {
268
+ const { ref, info, request } = prepared;
269
+ const { provider } = await this.providers.resolve(orgId, ref, { kind: "image_generation" });
270
+ if (provider.generateImage === undefined) {
271
+ throw new ApiError("model.unconfigured", `Model ${ref.provider}/${ref.model} cannot generate images`);
272
+ }
273
+ const generate = provider.generateImage.bind(provider);
274
+ const identity = identityFields(who);
275
+ const base = { purpose: "image", orgId, provider: ref.provider, model: ref.model };
276
+ if (hooks?.has("model.request")) {
277
+ const payload = {
278
+ ...base,
279
+ prompt: request.prompt,
280
+ size: { ...request.size },
281
+ n: request.n,
282
+ referenceImages: (request.referenceImages ?? []).map((r) => ({
283
+ type: "media_omitted",
284
+ kind: "image",
285
+ mediaType: r.mediaType,
286
+ size: base64Bytes(r.data),
287
+ })),
288
+ ...identity,
289
+ };
290
+ // an abort while the hooks run rejects with the caller's reason (never a deny)
291
+ const verdict = await hooks.run("model.request", payload, signal);
292
+ if (!verdict.allowed)
293
+ throw new ImageCallDenied(verdict);
294
+ }
295
+ signal.throwIfAborted();
296
+ const sentAt = Date.now();
297
+ const respond = (r) => {
298
+ if (!hooks)
299
+ return;
300
+ fireObserve(hooks, "model.response", { ...base, ...identity, ...r, latencyMs: Date.now() - sentAt }, signal, this.log);
301
+ };
302
+ let res;
303
+ try {
304
+ res = await this.callWithTimeout(generate, request, signal, ref);
305
+ const problem = validateImageGenerateResult(request, info, res);
306
+ if (problem !== null) {
307
+ throw new ModelError("server", `Model ${ref.provider}/${ref.model} returned an invalid image result: ${problem}`);
308
+ }
309
+ }
310
+ catch (err) {
311
+ // a call the caller aborted gets no model.response (as a chat call the user stopped)
312
+ if (!signal.aborted) {
313
+ respond({
314
+ outcome: "failed",
315
+ images: [],
316
+ usage: null,
317
+ errorCode: isModelError(err) ? `model.${err.kind}` : "model.unknown",
318
+ });
319
+ }
320
+ throw err;
321
+ }
322
+ const latencyMs = Date.now() - sentAt;
323
+ respond({
324
+ outcome: "ok",
325
+ images: res.images.map((i) => ({ mediaType: i.mediaType, size: base64Bytes(i.data) })),
326
+ ...(typeof res.revisedPrompt === "string" && { revisedPrompt: res.revisedPrompt }),
327
+ usage: res.usage ?? null,
328
+ });
329
+ return { ...res, latencyMs };
330
+ }
331
+ /**
332
+ * One `generateImage` call, limited by `models.imageTimeoutMs` (hot, read per call): at the limit
333
+ * the call's signal aborts and the call fails with `ModelError("timeout")`, even when the
334
+ * provider ignores the signal (its late answer is dropped).
335
+ */
336
+ async callWithTimeout(generate, request, signal, ref) {
337
+ const ms = this.config.get().models.imageTimeoutMs;
338
+ const timer = new AbortController();
339
+ const both = AbortSignal.any([signal, timer.signal]);
340
+ let handle;
341
+ let onAbort;
342
+ const call = Promise.resolve().then(() => generate(request, { signal: both }));
343
+ call.catch(() => { });
344
+ try {
345
+ return await Promise.race([
346
+ call,
347
+ new Promise((_, reject) => {
348
+ handle = setTimeout(() => {
349
+ const err = new ModelError("timeout", `Model ${ref.provider}/${ref.model} did not finish generating images within ${ms} ms`);
350
+ timer.abort(err);
351
+ reject(err);
352
+ }, ms);
353
+ onAbort = () => reject(signal.reason);
354
+ signal.addEventListener("abort", onAbort, { once: true });
355
+ }),
356
+ ]);
357
+ }
358
+ finally {
359
+ clearTimeout(handle);
360
+ // the caller's signal may outlive the call (an extension's ctx.signal): drop the listener
361
+ if (onAbort)
362
+ signal.removeEventListener("abort", onAbort);
363
+ }
364
+ }
365
+ };
366
+ __decorate([
367
+ Transactional()
368
+ ], ModelImages.prototype, "recordExtensionUsage", null);
369
+ ModelImages = __decorate([
370
+ Injectable(),
371
+ __param(0, Inject(ModelPurposesService)),
372
+ __param(1, Inject(ProviderRegistry)),
373
+ __param(2, Inject(KERNEL_LOGGER)),
374
+ __param(3, Inject(KernelConfigService)),
375
+ __param(4, Inject(KernelDb)),
376
+ __param(5, Inject(TransactionHost)),
377
+ __param(6, Inject(UsageReportJobs))
378
+ ], ModelImages);
379
+ export { ModelImages };
380
+ /** The identity fields of the hook payloads: conversation fields or the extension's. */
381
+ function identityFields(who) {
382
+ if (who.kind === "extension") {
383
+ return { extension: who.extension, imagePurpose: who.imagePurpose };
384
+ }
385
+ const s = who.scope;
386
+ return {
387
+ accountId: s.accountId,
388
+ agentId: s.agentId,
389
+ agentVersion: s.agentVersion,
390
+ conversationId: s.conversationId,
391
+ runId: s.runId,
392
+ ...(s.parent !== undefined && { parent: { ...s.parent } }),
393
+ step: who.step,
394
+ callId: who.callId,
395
+ };
396
+ }
397
+ /**
398
+ * The images a validated answer is billed for: the answer's own `usage.outputImages`, else the
399
+ * images it carries, never more than it carries (a vendor count above them is not trusted). The
400
+ * one rule of the tool's `usage` event and an extension call's `model_usage` row.
401
+ */
402
+ export function billedImages(res) {
403
+ return Math.min(res.usage.outputImages ?? res.images.length, res.images.length);
404
+ }
405
+ /**
406
+ * The shape of a `ctx.models.generateImage` request (an extension is untyped JavaScript at run
407
+ * time); the values themselves (prompt, size, count, references) are checked by `prepare`.
408
+ */
409
+ function checkExtensionRequest(req) {
410
+ const bad = (why) => {
411
+ throw new ApiError("validation_failed", `Invalid generateImage request: ${why}`);
412
+ };
413
+ if (typeof req !== "object" || req === null)
414
+ bad("expected an object");
415
+ if (typeof req.orgId !== "string" || req.orgId === "")
416
+ bad("orgId must be a string");
417
+ if (typeof req.purpose !== "string" || req.purpose === "")
418
+ bad("purpose must be a string");
419
+ if (typeof req.prompt !== "string")
420
+ bad("prompt must be a string");
421
+ if (req.size !== undefined &&
422
+ (typeof req.size !== "object" ||
423
+ req.size === null ||
424
+ !Number.isInteger(req.size.width) ||
425
+ !Number.isInteger(req.size.height))) {
426
+ bad("size must be { width, height } in whole pixels");
427
+ }
428
+ if (req.aspectRatio !== undefined &&
429
+ !IMAGE_ASPECT_RATIOS.includes(req.aspectRatio)) {
430
+ bad(`aspectRatio must be one of ${IMAGE_ASPECT_RATIOS.join(", ")}`);
431
+ }
432
+ if (req.n !== undefined && typeof req.n !== "number")
433
+ bad("n must be a number");
434
+ if (req.referenceImages !== undefined && !Array.isArray(req.referenceImages)) {
435
+ bad("referenceImages must be an array");
436
+ }
437
+ if (req.signal !== undefined && !(req.signal instanceof AbortSignal)) {
438
+ bad("signal must be an AbortSignal");
439
+ }
440
+ }
@@ -1,6 +1,7 @@
1
1
  /**
2
- * Model prices, model purposes, the model disabled lists and the `ctx.models` embeddings broker.
3
- * Below the extension host (the host injects {@link ModelEmbeddings} for `ctx.models`): it must not
2
+ * Model prices, model purposes, the model disabled lists, the `ctx.models` embeddings broker and
3
+ * the image generation calls ({@link ModelImages}).
4
+ * Below the extension host (the host injects both brokers for `ctx.models`): it must not
4
5
  * import `ExtensionsModule`.
5
6
  */
6
7
  export declare class ModelsModule {
@@ -10,13 +10,16 @@ import { IdentityModule } from "../identity/identity.module.js";
10
10
  import { OrgLockModule } from "../orgs/org-lock.js";
11
11
  import { ProvidersModule } from "../runtime/providers.js";
12
12
  import { UsageReportJobsModule } from "../runtime/usage-report-jobs.js";
13
+ import { StorageModule } from "../storage/storage.module.js";
13
14
  import { ModelEmbeddings } from "./embeddings.js";
14
15
  import { ModelEnablementModule } from "./enablement.js";
16
+ import { ModelImages } from "./images.js";
15
17
  import { PricesService } from "./prices.js";
16
18
  import { ModelPurposesService } from "./purposes.js";
17
19
  /**
18
- * Model prices, model purposes, the model disabled lists and the `ctx.models` embeddings broker.
19
- * Below the extension host (the host injects {@link ModelEmbeddings} for `ctx.models`): it must not
20
+ * Model prices, model purposes, the model disabled lists, the `ctx.models` embeddings broker and
21
+ * the image generation calls ({@link ModelImages}).
22
+ * Below the extension host (the host injects both brokers for `ctx.models`): it must not
20
23
  * import `ExtensionsModule`.
21
24
  */
22
25
  let ModelsModule = class ModelsModule {
@@ -29,11 +32,19 @@ ModelsModule = __decorate([
29
32
  OrgLockModule,
30
33
  ProvidersModule,
31
34
  ModelEnablementModule,
32
- // an embed call's `usage.report` delivery, owed with its `model_usage` row (no queue)
35
+ // an extension model call's `usage.report` delivery, owed with its `model_usage` row (no queue)
33
36
  UsageReportJobsModule,
37
+ // the `image` purpose's availability needs an object store (GenerateImage delivers there)
38
+ StorageModule,
39
+ ],
40
+ providers: [PricesService, ModelPurposesService, ModelEmbeddings, ModelImages],
41
+ exports: [
42
+ PricesService,
43
+ ModelPurposesService,
44
+ ModelEnablementModule,
45
+ ModelEmbeddings,
46
+ ModelImages,
34
47
  ],
35
- providers: [PricesService, ModelPurposesService, ModelEmbeddings],
36
- exports: [PricesService, ModelPurposesService, ModelEnablementModule, ModelEmbeddings],
37
48
  })
38
49
  ], ModelsModule);
39
50
  export { ModelsModule };
@@ -9,6 +9,7 @@ export const ORG_MODEL_ROUTES = [
9
9
  { route: "GET /api/v1/orgs/:orgId/models", query: ModelsQuery },
10
10
  { route: "GET /api/v1/orgs/:orgId/models/catalog" },
11
11
  { route: "GET /api/v1/orgs/:orgId/model-purposes" },
12
+ { route: "GET /api/v1/orgs/:orgId/model-purposes/available" },
12
13
  {
13
14
  route: "PUT /api/v1/orgs/:orgId/model-purposes/:purpose",
14
15
  params: ModelPurposePathParams,
@@ -15,6 +15,13 @@ export declare class ModelPurposesController {
15
15
  list(principal: Principal, org: OrgContext): Promise<{
16
16
  purposes: PurposeListing[];
17
17
  }>;
18
+ /** Whether each purpose has a usable model in the org now, no model names (any member). */
19
+ available(org: OrgContext): Promise<{
20
+ purposes: {
21
+ purpose: string;
22
+ available: boolean;
23
+ }[];
24
+ }>;
18
25
  put(principal: Principal, org: OrgContext, purpose: string, body: PurposePut): Promise<{
19
26
  purpose: PurposeListing;
20
27
  }>;
@@ -32,6 +32,10 @@ let ModelPurposesController = class ModelPurposesController {
32
32
  purposes: await withDeclaredByNames(await this.purposes.list(org.orgId), this.displayNames),
33
33
  };
34
34
  }
35
+ /** Whether each purpose has a usable model in the org now, no model names (any member). */
36
+ async available(org) {
37
+ return { purposes: await this.purposes.availability(org.orgId) };
38
+ }
35
39
  async put(principal, org, purpose, body) {
36
40
  const p = requireUser(principal);
37
41
  const view = await this.purposes.setOrg(org.orgId, purpose, purposeTargetOf(body), p.account.id, patTokenId(p));
@@ -45,6 +49,11 @@ __decorate([
45
49
  __param(0, CurrentPrincipal()),
46
50
  __param(1, CurrentOrg())
47
51
  ], ModelPurposesController.prototype, "list", null);
52
+ __decorate([
53
+ Get("available"),
54
+ OrgAction("agents.use"),
55
+ __param(0, CurrentOrg())
56
+ ], ModelPurposesController.prototype, "available", null);
48
57
  __decorate([
49
58
  Put(":purpose"),
50
59
  OrgAction("org.models.manage"),
@@ -1,4 +1,4 @@
1
- import { type ContentBlock, type LocalizedName, type ModelRequest, type ModelUsage, type ParamValue, type StopReason } from "@capybara-hq/plugin-sdk";
1
+ import { type ContentBlock, type LocalizedName, type Logger, type ModelRequest, type ModelUsage, type ParamValue, type StopReason } from "@capybara-hq/plugin-sdk";
2
2
  import { z } from "zod";
3
3
  import { ModelRef } from "../agents/definition.js";
4
4
  import { ExtensionRegistry } from "../extensions/registry.js";
@@ -8,6 +8,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
10
  import { ProviderRegistry } from "../runtime/providers.js";
11
+ import { StorageService } from "../storage/storage.service.js";
11
12
  /**
12
13
  * 模型用途映射(C9):内核与插件按「用途」取模型,不在代码里写死模型。
13
14
  * - 用途 = 内核用途 {@link KERNEL_PURPOSES}(目前只有评委 `eval`),或已加载插件 `permissions.models` 声明的;
@@ -18,6 +19,8 @@ import { ProviderRegistry } from "../runtime/providers.js";
18
19
  * the org (by either layer) counts as unconfigured there (spec B §5.3);参数按目标模型自己的声明严格校验;
19
20
  * - 每次都查 PG,不在进程内缓存(多副本下改映射立即生效)。`ctx.models` 仍预留,插件暂不能调用。
20
21
  */
22
+ /** The kinds a purpose can need: the callable model kinds. */
23
+ export type PurposeKind = "chat" | "embedding" | "image_generation";
21
24
  /**
22
25
  * Purposes the kernel declares: the eval judge, and the three sub-agent model tiers (phase C,
23
26
  * spec §5.4: `fast` / `standard` / `capable` → `subagent_<tier>`; an unmapped tier runs on the
@@ -72,6 +75,13 @@ export declare const KERNEL_PURPOSES: readonly [{
72
75
  readonly zh: "子智能体:最强";
73
76
  readonly en: "Sub-agent: capable";
74
77
  };
78
+ }, {
79
+ readonly purpose: "image";
80
+ readonly kind: "image_generation";
81
+ readonly label: {
82
+ readonly zh: "图片生成";
83
+ readonly en: "Image generation";
84
+ };
75
85
  }];
76
86
  /** 一个用途映射到的模型与参数。 */
77
87
  export interface PurposeTarget {
@@ -80,7 +90,7 @@ export interface PurposeTarget {
80
90
  }
81
91
  export interface PurposeView {
82
92
  purpose: string;
83
- kind: "chat" | "embedding";
93
+ kind: PurposeKind;
84
94
  label: {
85
95
  zh: string;
86
96
  en: string;
@@ -148,7 +158,12 @@ export declare class ModelPurposesService {
148
158
  readonly txHost: TransactionHost;
149
159
  private readonly adminLock;
150
160
  private readonly orgLock;
151
- constructor(db: KernelDb, extensions: ExtensionRegistry, config: KernelConfigService, providers: Pick<ProviderRegistry, "resolve" | "platformInfo">, txHost: TransactionHost, adminLock: SuperAdminLock, orgLock: OrgLock);
161
+ /** The `image` purpose's availability needs an object store (`GenerateImage` delivers there). */
162
+ private readonly storage;
163
+ private readonly log;
164
+ constructor(db: KernelDb, extensions: ExtensionRegistry, config: KernelConfigService, providers: Pick<ProviderRegistry, "resolve" | "platformInfo">, txHost: TransactionHost, adminLock: SuperAdminLock, orgLock: OrgLock,
165
+ /** The `image` purpose's availability needs an object store (`GenerateImage` delivers there). */
166
+ storage: Pick<StorageService, "available">, log: Pick<Logger, "warn">);
152
167
  /** 全部已声明的用途:内核的在前,其后按插件加载顺序。 */
153
168
  private declared;
154
169
  private find;
@@ -156,6 +171,16 @@ export declare class ModelPurposesService {
156
171
  private views;
157
172
  /** 全部用途与映射;不给 `orgId` = 部署级视图(`override` 一律为 null)。 */
158
173
  list(orgId?: string): Promise<PurposeView[]>;
174
+ /**
175
+ * Whether each purpose (kernel and extension-declared) resolves to a usable model for the org
176
+ * now, as {@link resolve} decides, without naming the model (the agent form's gate for
177
+ * `GenerateImage`, readable by every member). The `image` purpose reads `GenerateImage`'s own
178
+ * predicate ({@link imagePurposeUsable}: an image model callable now and an object store).
179
+ */
180
+ availability(orgId: string): Promise<{
181
+ purpose: string;
182
+ available: boolean;
183
+ }[]>;
159
184
  /**
160
185
  * 校验目标:模型可解析且启用(an org's override for the org, a deployment default in the
161
186
  * platform view)、its kind is the purpose's `kind`、参数按它的声明严格通过。