@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,59 @@
1
+ import { type ImageMediaType, type Logger, type ToolSpec } from "@capybara-hq/plugin-sdk";
2
+ import type { AttachmentsService } from "../../../conversations/attachments.service.js";
3
+ import type { EventLog } from "../../../conversations/event-log.js";
4
+ import type { KernelSchemaDb } from "../../../db/kernel-schema.js";
5
+ import type { KernelConfigService } from "../../../infra/config/kernel-config.service.js";
6
+ import { type ModelImages } from "../../../models/images.js";
7
+ import type { ModelPurposesService } from "../../../models/purposes.js";
8
+ import { type HookRunner } from "../../../runtime/hook-calls.js";
9
+ import { type ProviderRegistry } from "../../../runtime/providers.js";
10
+ import type { StepLog } from "../../../runtime/step-log.js";
11
+ import type { StorageService } from "../../../storage/storage.service.js";
12
+ import type { BuiltinTool } from "../../registry.js";
13
+ import { type SandboxToolDeps } from "../sandbox/common.js";
14
+ export declare const GENERATE_IMAGE_SPEC: ToolSpec;
15
+ /** Why the tool is not listed: the org's `image` purpose has no usable model (spec §5.3). */
16
+ export declare const NO_IMAGE_MODEL_REASON = "No image model is configured for this organization";
17
+ /** The tool error when the purpose's model went away after the listing. */
18
+ export declare const NO_IMAGE_MODEL_TEXT = "No image model is configured for this organization; ask an org admin to set a model for the image purpose, or continue without the image.";
19
+ /** The tool error when a `model.request` policy hook denies the call. */
20
+ export declare const GENERATE_IMAGE_DENIED_TEXT = "An org policy blocked this image request; continue without it or ask the user.";
21
+ /** The device line of a call whose conversation has no device to write to. */
22
+ export declare const NO_DEVICE_LINE = "Not written to the device: this conversation has no device.";
23
+ /** What the `GenerateImage` builtin needs (everything read per call: no process state). */
24
+ export interface GenerateImageDeps {
25
+ images: Pick<ModelImages, "prepare" | "run">;
26
+ /** Availability: the org's `image` purpose target, and its model resolved as an image model. */
27
+ purposes: Pick<ModelPurposesService, "resolve">;
28
+ providers: Pick<ProviderRegistry, "resolve">;
29
+ storage: Pick<StorageService, "kernel" | "available">;
30
+ eventLog: Pick<EventLog, "append" | "notify"> & Partial<Pick<EventLog, "publishChanged">>;
31
+ stepLog: Pick<StepLog, "appendCounted" | "appendReported" | "appendAudited">;
32
+ config: Pick<KernelConfigService, "get">;
33
+ log: Pick<Logger, "warn">;
34
+ /** Extension hooks (absent: none fire). */
35
+ hooks?: HookRunner | undefined;
36
+ /** The artifact lookup of `reference_images`. */
37
+ db: () => KernelSchemaDb;
38
+ attachments: Pick<AttachmentsService, "openForConversation">;
39
+ /** The device copy of `file_path` (the sandbox tools' own dependencies). */
40
+ sandbox: SandboxToolDeps;
41
+ }
42
+ /**
43
+ * The builtin `GenerateImage` (image generation spec §5.3): generates images with the org's
44
+ * `image` purpose model ({@link ModelImages}), stores them as artifacts of the conversation as
45
+ * `Deliver` stores a file (all or none, {@link storeArtifacts}), records the call's `usage` event
46
+ * (purpose `image`, the call id, `outputImages`) and, with `file_path`, also writes the images
47
+ * into the device through `Write`'s path checks (the command review covers such a call as a
48
+ * write). Listed only while the purpose resolves to a callable image model and an object store
49
+ * is there. A `model.request` policy denial is logged as any hook denial and sends nothing; a
50
+ * refusal or a failure is an actionable tool error, never retried. The model sees only the result
51
+ * text, so replays never call an image model.
52
+ */
53
+ export declare function generateImageTool(deps: GenerateImageDeps): BuiltinTool;
54
+ /**
55
+ * A written path as the device line names it: the path, followed by the image's media type when
56
+ * the path's extension is not one of that type's (`out/a.jpg (image/png)`), so the model knows
57
+ * what the file holds whatever it was called.
58
+ */
59
+ export declare function deviceEntry(path: string, mediaType: ImageMediaType): string;
@@ -0,0 +1,535 @@
1
+ import { IMAGE_ASPECT_RATIOS, IMAGE_MEDIA_TYPES, isModelError, MEDIA_LIMITS, ToolError, } from "@capybara-hq/plugin-sdk";
2
+ import { sql } from "kysely";
3
+ import { isValidArtifactName } from "../../../conversations/events.js";
4
+ import { ApiError } from "../../../errors.js";
5
+ import { IMAGE_PURPOSE, imagePurposeUsable } from "../../../models/image-usable.js";
6
+ import { billedImages, ImageCallDenied, } from "../../../models/images.js";
7
+ import { hookDeniedAudit, hookDeniedEvent, hookScope, } from "../../../runtime/hook-calls.js";
8
+ import { appendCounted } from "../../../runtime/model-call.js";
9
+ import { ProviderListError } from "../../../runtime/providers.js";
10
+ import { NO_STORAGE, NO_STORAGE_REASON, storeArtifacts, } from "../artifacts.js";
11
+ import { checkFilePathShape, checkToolWritable, clip, display, inToolSandbox, sandboxConversationOf, sandboxUsable, withNotices, withPathLease, } from "../sandbox/common.js";
12
+ import { assertReadAndUnchanged, FileGuardError, fileStateOf } from "../sandbox/file-state.js";
13
+ import { READ_MAX_BYTES } from "../sandbox/read.js";
14
+ import { generateImagePaths } from "./paths.js";
15
+ /** The model purpose the tool calls (image generation spec §5.4; no fallback). */
16
+ const PURPOSE = IMAGE_PURPOSE;
17
+ /** The most reference images one call names (the schema's `maxItems`). */
18
+ const MAX_REFERENCES = 4;
19
+ /** The most images one call asks for (the schema's maximum; the kernel cap may be lower). */
20
+ const MAX_IMAGES = 4;
21
+ /** The longest base name (`name`). */
22
+ const NAME_MAX_CHARS = 100;
23
+ export const GENERATE_IMAGE_SPEC = {
24
+ name: "GenerateImage",
25
+ // Display only (the tool row; not in the fingerprint, never sent to the model).
26
+ keyArgs: ["prompt"],
27
+ description: "Generate images from a text prompt with this organization's image model, and deliver them to " +
28
+ "the user in the conversation. Write a specific prompt: subject, composition, style, lighting, " +
29
+ "any text that must appear. Optionally pass reference images (attachment or earlier generated " +
30
+ "image ids) to guide the result. Each call costs money: generate only what the user asked for.",
31
+ inputSchema: {
32
+ type: "object",
33
+ properties: {
34
+ prompt: {
35
+ type: "string",
36
+ minLength: 1,
37
+ description: "What to draw: subject, composition, style, lighting, any text to include.",
38
+ },
39
+ aspect_ratio: {
40
+ type: "string",
41
+ enum: [...IMAGE_ASPECT_RATIOS],
42
+ description: "Shape of the images; the closest size the model supports is used. Default: the model's default size.",
43
+ },
44
+ n: {
45
+ type: "integer",
46
+ minimum: 1,
47
+ maximum: MAX_IMAGES,
48
+ description: "How many images to generate (default 1).",
49
+ },
50
+ reference_images: {
51
+ type: "array",
52
+ maxItems: MAX_REFERENCES,
53
+ items: { type: "string", minLength: 1 },
54
+ description: "Ids of images that guide the result: attachment ids of this conversation, or artifact ids of images generated earlier in it.",
55
+ },
56
+ name: {
57
+ type: "string",
58
+ minLength: 1,
59
+ maxLength: NAME_MAX_CHARS,
60
+ pattern: "^[^/\\\\]+$",
61
+ description: 'Base file name shown to the user, without extension, e.g. "poster" (gives poster-1.png, poster-2.png). Default: image.',
62
+ },
63
+ file_path: {
64
+ type: "string",
65
+ minLength: 1,
66
+ description: "Also write the images into the device at this path, e.g. out/poster.png in the workspace directory; several images get -1, -2 suffixes before the extension.",
67
+ },
68
+ },
69
+ required: ["prompt"],
70
+ additionalProperties: false,
71
+ },
72
+ };
73
+ /** Why the tool is not listed: the org's `image` purpose has no usable model (spec §5.3). */
74
+ export const NO_IMAGE_MODEL_REASON = "No image model is configured for this organization";
75
+ /** The tool error when the purpose's model went away after the listing. */
76
+ export const NO_IMAGE_MODEL_TEXT = `${NO_IMAGE_MODEL_REASON}; ask an org admin to set a model for the image purpose, or continue without the image.`;
77
+ /** The tool error when a `model.request` policy hook denies the call. */
78
+ export const GENERATE_IMAGE_DENIED_TEXT = "An org policy blocked this image request; continue without it or ask the user.";
79
+ const refusedText = (message) => `The image model refused this prompt: ${message}. Rephrase it or ask the user.`;
80
+ const failedText = (message) => `Image generation failed: ${message}. Retry once, or continue without the image.`;
81
+ /** A refused argument (the request building's text names it and the allowed values). */
82
+ const invalidText = (message) => `${message}; fix the argument and retry.`;
83
+ const unknownReferenceText = (k) => `reference_images[${k}] is not an attachment or generated image of this conversation; pass an attachment id or the artifact id of an image generated earlier in it.`;
84
+ const badReferenceText = (k) => `reference_images[${k}] is not a PNG, JPEG, GIF or WebP image up to ${MEDIA_LIMITS.imageBytes / 1_048_576} MB; pass another image, or call without it.`;
85
+ const BAD_NAME = "name must not contain control characters, / or \\; pass a plain base name such as poster.";
86
+ const BLANK_NAME = 'name must not be blank; pass a short file name such as "poster", or omit it.';
87
+ /** The request building's refusal of too many references (checked before any is read). */
88
+ const tooManyReferencesText = (max) => invalidText(max === 0
89
+ ? "this model takes no reference images"
90
+ : `this model takes at most ${max} reference images`);
91
+ /** Why a device write failed for a reason the device did not explain (its error stays in the log). */
92
+ const copyFailedText = (path) => `the device could not write ${clip(path, 200)}; retry the call, or pass another file_path.`;
93
+ /** `Write`'s refusals of a target, worded for `file_path` (the images are already delivered). */
94
+ const isDirectoryText = (path) => `${clip(path, 200)} is a directory; pass the path of a file inside it as file_path.`;
95
+ const notReadText = (path) => `${clip(path, 200)} already exists and this conversation has not read it; Read it first to replace it, or pass another file_path.`;
96
+ const modifiedText = (path) => `${clip(path, 200)} has changed since this conversation read it; Read it again to replace it, or pass another file_path.`;
97
+ const vanishedText = (path) => `${clip(path, 200)} disappeared while it was being written; retry the call.`;
98
+ /** The device line of a call whose conversation has no device to write to. */
99
+ export const NO_DEVICE_LINE = "Not written to the device: this conversation has no device.";
100
+ /** Lower-case UUIDs: attachment and artifact ids. */
101
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
102
+ /** The file extension of each image media type. */
103
+ const EXTENSIONS = {
104
+ "image/png": "png",
105
+ "image/jpeg": "jpg",
106
+ "image/gif": "gif",
107
+ "image/webp": "webp",
108
+ };
109
+ /**
110
+ * The builtin `GenerateImage` (image generation spec §5.3): generates images with the org's
111
+ * `image` purpose model ({@link ModelImages}), stores them as artifacts of the conversation as
112
+ * `Deliver` stores a file (all or none, {@link storeArtifacts}), records the call's `usage` event
113
+ * (purpose `image`, the call id, `outputImages`) and, with `file_path`, also writes the images
114
+ * into the device through `Write`'s path checks (the command review covers such a call as a
115
+ * write). Listed only while the purpose resolves to a callable image model and an object store
116
+ * is there. A `model.request` policy denial is logged as any hook denial and sends nothing; a
117
+ * refusal or a failure is an actionable tool error, never retried. The model sees only the result
118
+ * text, so replays never call an image model.
119
+ */
120
+ export function generateImageTool(deps) {
121
+ return {
122
+ spec: GENERATE_IMAGE_SPEC,
123
+ // the admins mapped a model to the purpose on purpose: that is the opt-in (spec §5.3)
124
+ defaultPolicy: "allow",
125
+ // the predicate the agent form's purpose availability reads too (one rule, no drift)
126
+ unavailable: async (scope) => {
127
+ const usable = await imagePurposeUsable(deps, scope.orgId);
128
+ if (usable === "no-model")
129
+ return NO_IMAGE_MODEL_REASON;
130
+ return usable === "no-storage" ? NO_STORAGE_REASON : null;
131
+ },
132
+ timeoutMs: () => deps.config.get().models.imageTimeoutMs + 60_000,
133
+ async run(raw, ctx) {
134
+ const input = raw;
135
+ if (!deps.storage.available)
136
+ throw new ToolError(NO_STORAGE);
137
+ const base = input.name?.trim();
138
+ if (base === "")
139
+ throw new ToolError(BLANK_NAME);
140
+ if (base !== undefined && (!isValidArtifactName(base) || /[/\\]/.test(base))) {
141
+ throw new ToolError(BAD_NAME);
142
+ }
143
+ if (input.file_path !== undefined)
144
+ checkFilePathShape(input.file_path);
145
+ const call = {
146
+ prompt: input.prompt,
147
+ ...(input.aspect_ratio !== undefined && { aspectRatio: input.aspect_ratio }),
148
+ ...(input.n !== undefined && { n: input.n }),
149
+ };
150
+ // the cheap checks (prompt, count, size, the model) before any reference is read
151
+ let prepared = await prepare(deps, ctx, call);
152
+ const refs = input.reference_images ?? [];
153
+ if (refs.length > prepared.info.maxReferenceImages) {
154
+ throw new ToolError(tooManyReferencesText(prepared.info.maxReferenceImages));
155
+ }
156
+ if (refs.length > 0) {
157
+ // the bytes are checked (type, size) and sent by the request building
158
+ const referenceImages = await resolveReferences(deps, ctx, refs);
159
+ prepared = await prepare(deps, ctx, { ...call, referenceImages });
160
+ }
161
+ const result = await generate(deps, ctx, prepared);
162
+ // a valid answer is billed whatever happens to its images afterwards (ruling R11)
163
+ await logUsage(deps, ctx, prepared, result);
164
+ // images a late answer carries after an abort are dropped: nothing is stored
165
+ ctx.signal.throwIfAborted();
166
+ const max = deps.config.get().sandbox.deliverMaxBytes;
167
+ const files = result.images.map((img, i) => {
168
+ const data = Buffer.from(img.data, "base64");
169
+ if (data.byteLength > max) {
170
+ // a server failure of the call (spec §6), with no partial delivery: nothing is stored
171
+ throw new ToolError(failedText(`the model returned an image of ${data.byteLength} bytes, over the artifact limit of ${max} bytes`));
172
+ }
173
+ const ext = EXTENSIONS[img.mediaType];
174
+ const stem = base ?? "image";
175
+ return {
176
+ name: result.images.length === 1 ? `${stem}.${ext}` : `${stem}-${i + 1}.${ext}`,
177
+ contentType: img.mediaType,
178
+ data: new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
179
+ };
180
+ });
181
+ // each call's images are their own files, never versions of an earlier call's (R13)
182
+ const stored = await storeArtifacts(deps, ctx, files.map((f) => ({ ...f, sourcePath: `generated/${ctx.callId}/${f.name}` })));
183
+ let deviceLine = null;
184
+ let notices = [];
185
+ if (input.file_path !== undefined) {
186
+ const copied = await copyToDevice(deps, ctx, input.file_path, files);
187
+ deviceLine = copied.line;
188
+ notices = copied.notices;
189
+ }
190
+ const text = resultText(prepared, stored, files, result.revisedPrompt, deviceLine);
191
+ return {
192
+ content: [{ type: "text", text: withNotices(notices, text) }],
193
+ display: display(`生成图片 ${clip(input.prompt, 160)}`, `Generated images: ${clip(input.prompt, 160)}`),
194
+ };
195
+ },
196
+ };
197
+ }
198
+ /** {@link ModelImages.prepare} with its refusals as tool errors. */
199
+ async function prepare(deps, ctx, call) {
200
+ try {
201
+ return await deps.images.prepare(ctx.orgId, PURPOSE, call);
202
+ }
203
+ catch (e) {
204
+ throw toolErrorOf(e) ?? e;
205
+ }
206
+ }
207
+ /**
208
+ * The tool error of a refusal of the image call, or null for an error the pipeline reports
209
+ * itself (an abort, a kernel fault).
210
+ */
211
+ function toolErrorOf(e) {
212
+ if (e instanceof ToolError)
213
+ return e;
214
+ if (e instanceof ApiError) {
215
+ if (e.code === "validation_failed")
216
+ return new ToolError(invalidText(e.message));
217
+ // a transient list error of the provider: the call may succeed on a retry
218
+ if (e instanceof ProviderListError)
219
+ return new ToolError(failedText(e.message));
220
+ if (e.code === "model.unconfigured" || e.code === "agent.model_unavailable") {
221
+ return new ToolError(NO_IMAGE_MODEL_TEXT);
222
+ }
223
+ return null;
224
+ }
225
+ if (isModelError(e) && e.kind === "refusal")
226
+ return new ToolError(refusedText(e.message));
227
+ if (isModelError(e))
228
+ return new ToolError(failedText(e.message));
229
+ return null;
230
+ }
231
+ /**
232
+ * Reads the reference images as bytes, each an id of the conversation: an attachment of the
233
+ * conversation whose device the call uses (a sub-agent: its root's, as `FetchAttachment`
234
+ * resolves), else an `artifact_created` of the calling conversation or its root. Anything else
235
+ * names its index; a file that is not an image within `MEDIA_LIMITS.imageBytes` is refused before
236
+ * it is read.
237
+ */
238
+ async function resolveReferences(deps, ctx, ids) {
239
+ const root = sandboxConversationOf(ctx);
240
+ const out = [];
241
+ for (const [k, id] of ids.entries()) {
242
+ if (!UUID.test(id))
243
+ throw new ToolError(unknownReferenceText(k));
244
+ const found = await openReference(deps, ctx, root, id.toLowerCase());
245
+ if (found === null)
246
+ throw new ToolError(unknownReferenceText(k));
247
+ const mediaType = found.contentType.split(";")[0]?.trim().toLowerCase() ?? "";
248
+ if (!IMAGE_MEDIA_TYPES.includes(mediaType) ||
249
+ found.size > MEDIA_LIMITS.imageBytes) {
250
+ await found.body.cancel().catch(() => { });
251
+ throw new ToolError(badReferenceText(k));
252
+ }
253
+ const bytes = new Uint8Array(await new Response(found.body).arrayBuffer());
254
+ if (bytes.byteLength > MEDIA_LIMITS.imageBytes)
255
+ throw new ToolError(badReferenceText(k));
256
+ out.push({
257
+ mediaType: mediaType,
258
+ data: Buffer.from(bytes).toString("base64"),
259
+ });
260
+ }
261
+ return out;
262
+ }
263
+ /** One reference by id: its declared type and size and its bytes, or null when it is not one. */
264
+ async function openReference(deps, ctx, root, id) {
265
+ try {
266
+ const attachment = await deps.attachments.openForConversation(ctx.orgId, root, id);
267
+ if (attachment !== null)
268
+ return attachment;
269
+ const row = await deps
270
+ .db()
271
+ .selectFrom("conversation_events")
272
+ .select("payload")
273
+ .where("conversation_id", "in", [...new Set([ctx.conversationId, root])])
274
+ .where("type", "=", "artifact_created")
275
+ .where(sql `payload->>'artifactId'`, "=", id)
276
+ .limit(1)
277
+ .executeTakeFirst();
278
+ if (!row)
279
+ return null;
280
+ const a = row.payload;
281
+ const got = await deps.storage.kernel(ctx.orgId).get(a.objectKey);
282
+ if (got === null)
283
+ return null;
284
+ return { contentType: a.contentType, size: got.head.size, body: got.body };
285
+ }
286
+ catch (e) {
287
+ if (e instanceof ApiError && e.code === "storage.unavailable")
288
+ throw new ToolError(NO_STORAGE);
289
+ throw e;
290
+ }
291
+ }
292
+ /**
293
+ * Runs the prepared call (the hooks fire for a `chat` or `subagent` conversation only). A policy
294
+ * denial is recorded (`hook_denied` with its audit row) and becomes the denial tool error.
295
+ */
296
+ async function generate(deps, ctx, prepared) {
297
+ const runId = ctx.runId ?? "";
298
+ const scope = hookScope(deps.hooks, {
299
+ ...(ctx.conversationKind !== undefined && { conversationKind: ctx.conversationKind }),
300
+ orgId: ctx.orgId,
301
+ accountId: ctx.accountId,
302
+ agentId: ctx.agentId,
303
+ agentVersion: ctx.agentVersion ?? 1,
304
+ conversationId: ctx.conversationId,
305
+ runId,
306
+ parent: ctx.parent,
307
+ });
308
+ try {
309
+ return await deps.images.run(ctx.orgId, prepared, {
310
+ kind: "conversation",
311
+ // without a scope no hook fires (the runner is not passed), so the fields are unused
312
+ scope: scope ?? {
313
+ orgId: ctx.orgId,
314
+ accountId: ctx.accountId,
315
+ agentId: ctx.agentId,
316
+ agentVersion: ctx.agentVersion ?? 1,
317
+ conversationId: ctx.conversationId,
318
+ runId,
319
+ },
320
+ step: ctx.step ?? 0,
321
+ callId: ctx.callId,
322
+ }, ctx.signal, scope ? deps.hooks : undefined);
323
+ }
324
+ catch (e) {
325
+ if (e instanceof ImageCallDenied) {
326
+ await recordDenial(deps, ctx, runId, e.verdict);
327
+ throw new ToolError(GENERATE_IMAGE_DENIED_TEXT);
328
+ }
329
+ // an abort is the pipeline's (the run stopped or the call timed out)
330
+ if (ctx.signal.aborted)
331
+ throw e;
332
+ const mapped = toolErrorOf(e);
333
+ if (mapped === null)
334
+ throw e;
335
+ deps.log.warn("GenerateImage call failed", {
336
+ conversationId: ctx.conversationId,
337
+ callId: ctx.callId,
338
+ err: e,
339
+ });
340
+ throw mapped;
341
+ }
342
+ }
343
+ /**
344
+ * Appends the call's `usage` event (the tool call's run and step, `callId`, `outputImages`;
345
+ * idempotent per call) and owes its `usage.report` delivery in the same transaction; a
346
+ * sub-agent's call also counts on its budget run ({@link appendCounted}).
347
+ */
348
+ async function logUsage(deps, ctx, prepared, result) {
349
+ const runId = ctx.runId ?? "";
350
+ const event = {
351
+ type: "usage",
352
+ ...(runId !== "" && { runId }),
353
+ idemKey: `usage_image:${runId}:${ctx.callId}`,
354
+ payload: {
355
+ step: ctx.step ?? 0,
356
+ provider: prepared.ref.provider,
357
+ model: prepared.ref.model,
358
+ inputTokens: result.usage.inputTokens,
359
+ outputTokens: result.usage.outputTokens,
360
+ cacheReadTokens: result.usage.cacheReadTokens,
361
+ cacheWriteTokens: result.usage.cacheWriteTokens,
362
+ outputImages: billedImages(result),
363
+ purpose: PURPOSE,
364
+ callId: ctx.callId,
365
+ },
366
+ };
367
+ await appendCounted(deps, {
368
+ conversationId: ctx.conversationId,
369
+ parentRunId: ctx.parentRunId,
370
+ budgetRunId: ctx.budgetRunId,
371
+ }, [event]);
372
+ }
373
+ /**
374
+ * Records a `model.request` denial of the call: the `hook_denied` event (the tool call's step and
375
+ * `callId`) with its `hook.denied` audit row (`detail.purpose: "image"`), in one transaction.
376
+ */
377
+ async function recordDenial(deps, ctx, runId, verdict) {
378
+ const site = {
379
+ orgId: ctx.orgId,
380
+ conversationId: ctx.conversationId,
381
+ runId,
382
+ accountId: ctx.accountId,
383
+ agentId: ctx.agentId,
384
+ idemKey: `hook_denied_image:${runId}:${ctx.callId}`,
385
+ };
386
+ const event = hookDeniedEvent(site, "model.request", verdict, {
387
+ step: ctx.step ?? 0,
388
+ attempt: 1,
389
+ callId: ctx.callId,
390
+ });
391
+ const entry = hookDeniedAudit(site, event.payload, verdict);
392
+ entry.detail = { ...entry.detail, purpose: PURPOSE };
393
+ deps.log.warn("GenerateImage blocked by a policy hook", {
394
+ conversationId: ctx.conversationId,
395
+ callId: ctx.callId,
396
+ plugin: verdict.plugin,
397
+ cause: verdict.cause,
398
+ });
399
+ const written = await deps.stepLog.appendAudited(ctx.conversationId, [event], entry);
400
+ if (written.length > 0) {
401
+ await deps.eventLog.notify(ctx.conversationId, Math.max(...written.map((e) => e.seq)));
402
+ }
403
+ }
404
+ /**
405
+ * Writes the images into the call's device at `filePath` (several: `-1`, `-2`… before the
406
+ * extension, {@link generateImagePaths}) with `Write`'s checks (spec §5.3): the device entry every
407
+ * builtin takes ({@link inToolSandbox}: the managed route and its marked device paths once
408
+ * activated), each path checked as `Write` checks it, and under its path lease a directory refused
409
+ * and an existing file replaced only when this conversation read it and it is unchanged
410
+ * ({@link assertReadAndUnchanged}). The images are already delivered, so a copy that cannot be made
411
+ * is a line of the result, not a tool error: no device, or the reason the copy stopped, after the
412
+ * paths written before it. A path whose extension does not match the image's media type names the
413
+ * type ({@link deviceEntry}). An abort still ends the call.
414
+ */
415
+ async function copyToDevice(deps, ctx, filePath, files) {
416
+ const sb = deps.sandbox;
417
+ const conv = sandboxConversationOf(ctx);
418
+ if (!(await hasDevice(sb, ctx.orgId, conv)))
419
+ return { line: NO_DEVICE_LINE, notices: [] };
420
+ const targets = generateImagePaths({ file_path: filePath, n: files.length });
421
+ // the paths written so far (a rebuilt instance runs the copy again from the start)
422
+ let written = [];
423
+ let current = targets[0];
424
+ try {
425
+ const { notices } = await inToolSandbox(sb, ctx, async (s) => {
426
+ written = [];
427
+ for (const [i, f] of files.entries()) {
428
+ current = targets[i];
429
+ const path = checkToolWritable(current, s);
430
+ current = path;
431
+ // stat, read the existing file, write: one holder at a time per file (as `Write`)
432
+ await withPathLease(sb, { deviceId: s.deviceId }, path, s.signal, async (signal) => {
433
+ const st = await s.p.stat(s.h, path, signal);
434
+ if (st?.isDir)
435
+ throw new ToolError(isDirectoryText(path));
436
+ if (st !== null) {
437
+ const got = await s.p.readFile(s.h, path, { maxBytes: READ_MAX_BYTES, signal });
438
+ if (got === null)
439
+ throw new ToolError(vanishedText(path));
440
+ try {
441
+ await assertReadAndUnchanged(sb, ctx.conversationId, path, fileStateOf(got.data, st.size));
442
+ }
443
+ catch (e) {
444
+ if (!(e instanceof FileGuardError))
445
+ throw e;
446
+ if (e.reason === "not_read")
447
+ throw new ToolError(notReadText(path));
448
+ throw new ToolError(modifiedText(path));
449
+ }
450
+ }
451
+ await s.p.writeFile(s.h, path, f.data, signal);
452
+ });
453
+ written.push(deviceEntry(path, f.contentType));
454
+ }
455
+ });
456
+ return { line: `Written to the device: ${written.join(", ")}`, notices };
457
+ }
458
+ catch (e) {
459
+ if (ctx.signal.aborted)
460
+ throw e;
461
+ // a device's own error is not shown to the model (it may name provider internals)
462
+ if (!(e instanceof ToolError)) {
463
+ deps.log.warn("GenerateImage device copy failed", {
464
+ conversationId: ctx.conversationId,
465
+ callId: ctx.callId,
466
+ err: e,
467
+ });
468
+ }
469
+ const failed = `Not written to the device: ${e instanceof ToolError ? e.message : copyFailedText(current)}`;
470
+ // a partial copy says which files are there before the failure
471
+ return {
472
+ line: written.length === 0 ? failed : `Written to the device: ${written.join(", ")}\n${failed}`,
473
+ notices: [],
474
+ };
475
+ }
476
+ }
477
+ /**
478
+ * A written path as the device line names it: the path, followed by the image's media type when
479
+ * the path's extension is not one of that type's (`out/a.jpg (image/png)`), so the model knows
480
+ * what the file holds whatever it was called.
481
+ */
482
+ export function deviceEntry(path, mediaType) {
483
+ const name = path.slice(path.lastIndexOf("/") + 1);
484
+ const dot = name.lastIndexOf(".");
485
+ const ext = dot > 0 ? name.slice(dot + 1).toLowerCase() : "";
486
+ return MEDIA_EXTENSIONS[mediaType].includes(ext) ? path : `${path} (${mediaType})`;
487
+ }
488
+ /** The extensions that name each image media type ({@link deviceEntry}). */
489
+ const MEDIA_EXTENSIONS = {
490
+ "image/png": ["png"],
491
+ "image/jpeg": ["jpg", "jpeg"],
492
+ "image/gif": ["gif"],
493
+ "image/webp": ["webp"],
494
+ };
495
+ /**
496
+ * Whether the conversation tree has a device to write to: a provider it can run on, and a device
497
+ * its owner has (an anonymous IM sender or a deployment without a cloud provider has none).
498
+ */
499
+ async function hasDevice(sb, orgId, conv) {
500
+ if (!(await sandboxUsable(sb, orgId, conv)))
501
+ return false;
502
+ try {
503
+ await sb.devices.forTool(orgId, conv);
504
+ return true;
505
+ }
506
+ catch (e) {
507
+ if (e instanceof ApiError && e.code === "sandbox.unavailable")
508
+ return false;
509
+ // any other refusal (a gone or forbidden device) is reported by the copy itself
510
+ return true;
511
+ }
512
+ }
513
+ /** A byte count as the result shows it. */
514
+ function sizeText(bytes) {
515
+ if (bytes < 1024)
516
+ return `${bytes} B`;
517
+ if (bytes < 1_048_576)
518
+ return `${(bytes / 1024).toFixed(1)} KB`;
519
+ return `${(bytes / 1_048_576).toFixed(1)} MB`;
520
+ }
521
+ /** The model-visible result (spec §5.3): what was generated, where it went, the revised prompt. */
522
+ function resultText(prepared, stored, files, revisedPrompt, deviceLine) {
523
+ const n = stored.length;
524
+ const { width, height } = prepared.request.size;
525
+ const lines = [
526
+ `Generated ${n} ${n === 1 ? "image" : "images"} with ${prepared.ref.provider}/${prepared.ref.model} at ${width}x${height} and delivered ${n === 1 ? "it" : "them"} to the user:`,
527
+ ...stored.map((a, i) => `- ${a.name} (artifact ${a.artifactId}, ${files[i]?.contentType ?? ""}, ${sizeText(a.size)})`),
528
+ ];
529
+ if (typeof revisedPrompt === "string" && revisedPrompt !== "") {
530
+ lines.push(`Revised prompt: ${revisedPrompt}`);
531
+ }
532
+ if (deviceLine !== null)
533
+ lines.push(deviceLine);
534
+ return lines.join("\n");
535
+ }
@@ -0,0 +1,2 @@
1
+ export { GENERATE_IMAGE_DENIED_TEXT, GENERATE_IMAGE_SPEC, type GenerateImageDeps, generateImageTool, NO_DEVICE_LINE, NO_IMAGE_MODEL_REASON, NO_IMAGE_MODEL_TEXT, } from "./generate.js";
2
+ export { generateImagePaths, suffixedPath } from "./paths.js";
@@ -0,0 +1,2 @@
1
+ export { GENERATE_IMAGE_DENIED_TEXT, GENERATE_IMAGE_SPEC, generateImageTool, NO_DEVICE_LINE, NO_IMAGE_MODEL_REASON, NO_IMAGE_MODEL_TEXT, } from "./generate.js";
2
+ export { generateImagePaths, suffixedPath } from "./paths.js";
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The device paths a `GenerateImage` call writes (image generation spec §5.3), shared by the tool
3
+ * and the command review so the review judges exactly the files the tool writes.
4
+ */
5
+ /** `path` with `-<i>` before the extension of its last segment (or at its end without one). */
6
+ export declare function suffixedPath(path: string, i: number): string;
7
+ /**
8
+ * The paths a `GenerateImage` input writes into the device, in image order: none without
9
+ * `file_path`, `file_path` itself for one image, `-1`, `-2`… before the extension for several
10
+ * ({@link suffixedPath}). `n` absent or not a whole number above 1 is one image.
11
+ */
12
+ export declare function generateImagePaths(input: unknown): string[];
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The device paths a `GenerateImage` call writes (image generation spec §5.3), shared by the tool
3
+ * and the command review so the review judges exactly the files the tool writes.
4
+ */
5
+ /** `path` with `-<i>` before the extension of its last segment (or at its end without one). */
6
+ export function suffixedPath(path, i) {
7
+ const slash = path.lastIndexOf("/");
8
+ const dot = path.lastIndexOf(".");
9
+ // a dot that starts the file name (`.env`) is not an extension
10
+ if (dot <= slash + 1)
11
+ return `${path}-${i}`;
12
+ return `${path.slice(0, dot)}-${i}${path.slice(dot)}`;
13
+ }
14
+ /**
15
+ * The paths a `GenerateImage` input writes into the device, in image order: none without
16
+ * `file_path`, `file_path` itself for one image, `-1`, `-2`… before the extension for several
17
+ * ({@link suffixedPath}). `n` absent or not a whole number above 1 is one image.
18
+ */
19
+ export function generateImagePaths(input) {
20
+ const o = (input ?? {});
21
+ if (typeof o.file_path !== "string")
22
+ return [];
23
+ const n = typeof o.n === "number" && Number.isInteger(o.n) && o.n > 1 ? o.n : 1;
24
+ const path = o.file_path;
25
+ return n === 1 ? [path] : Array.from({ length: n }, (_, i) => suffixedPath(path, i + 1));
26
+ }