okengine 0.21.1 → 0.23.0

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 (342) hide show
  1. package/AGENTS.md +11 -4
  2. package/LICENSE +202 -0
  3. package/NOTICE +2 -0
  4. package/README.md +15 -9
  5. package/manifest.v1.schema.json +54 -0
  6. package/package.json +53 -38
  7. package/site/content/docs/ai/mcp.mdx +13 -9
  8. package/site/content/docs/ai/skills.mdx +2 -2
  9. package/site/content/docs/client/calling.mdx +27 -19
  10. package/site/content/docs/client/index.mdx +1 -1
  11. package/site/content/docs/elements/ai/agents.mdx +61 -13
  12. package/site/content/docs/elements/ai/decide.mdx +536 -0
  13. package/site/content/docs/elements/ai/events.mdx +373 -0
  14. package/site/content/docs/elements/ai/index.mdx +9 -3
  15. package/site/content/docs/elements/ai/meta.json +1 -1
  16. package/site/content/docs/elements/ai/prompts.mdx +4 -2
  17. package/site/content/docs/elements/channel/email.mdx +1 -1
  18. package/site/content/docs/elements/channel/index.mdx +1 -1
  19. package/site/content/docs/elements/flow/http.mdx +4 -4
  20. package/site/content/docs/elements/flow/index.mdx +3 -3
  21. package/site/content/docs/elements/flow/meta.json +1 -1
  22. package/site/content/docs/elements/gate/auth.mdx +4 -1
  23. package/site/content/docs/elements/gate/tenancy.mdx +1 -1
  24. package/site/content/docs/elements/store/index.mdx +1 -1
  25. package/site/content/docs/elements/store/kv.mdx +5 -5
  26. package/site/content/docs/elements/vault/rotation.mdx +15 -0
  27. package/site/content/docs/plugins/otp.mdx +31 -31
  28. package/site/content/docs/recipes/dragonfly.mdx +5 -5
  29. package/site/content/docs/recipes/index.mdx +6 -6
  30. package/site/content/docs/recipes/mailpit.mdx +1 -1
  31. package/site/content/docs/recipes/meilisearch.mdx +1 -1
  32. package/site/content/docs/recipes/pgdog.mdx +1 -1
  33. package/site/content/docs/recipes/postgres.mdx +12 -8
  34. package/site/content/docs/recipes/redis.mdx +4 -4
  35. package/site/content/docs/reference/cli.mdx +2 -1
  36. package/site/content/docs/reference/configuration.mdx +11 -9
  37. package/site/content/docs/reference/errors.mdx +12 -2
  38. package/site/content/docs/reference/fx.mdx +35 -21
  39. package/site/content/docs/reference/idempotency.mdx +192 -0
  40. package/site/content/docs/reference/index.mdx +6 -1
  41. package/site/content/docs/reference/meta.json +2 -1
  42. package/site/content/docs/understand/meta.json +1 -1
  43. package/site/content/docs/{elements/flow → understand}/routing.mdx +11 -10
  44. package/site/content/docs/understand/the-architecture.mdx +14 -12
  45. package/site/content/docs/understand/try-it.mdx +3 -3
  46. package/src/auth/api-key-sql.test.ts +44 -0
  47. package/src/auth/api-key-sql.ts +1 -0
  48. package/src/auth/api-keys.ts +30 -12
  49. package/src/auth/config.ts +6 -2
  50. package/src/auth/gate-auth.test.ts +20 -0
  51. package/src/cli/agents-md.test.ts +25 -0
  52. package/src/cli/ask-vault-gaps.test.ts +38 -1
  53. package/src/cli/ask-vault-gaps.ts +35 -2
  54. package/src/cli/competitor-mention-removal.test.ts +3 -3
  55. package/src/cli/decide.ts +174 -0
  56. package/src/cli/decision-lock-watch.test.ts +45 -0
  57. package/src/cli/decision-lock-watch.ts +51 -0
  58. package/src/cli/dev-app-runner.ts +34 -8
  59. package/src/cli/dev-auth-secret.test.ts +49 -0
  60. package/src/cli/dev-auth-secret.ts +49 -0
  61. package/src/cli/dev-hot.test.ts +41 -0
  62. package/src/cli/dev-hot.ts +48 -0
  63. package/src/cli/dev.test.ts +1 -1
  64. package/src/cli/dev.ts +24 -6
  65. package/src/cli/docker-cli.test.ts +1 -1
  66. package/src/cli/eval.ts +142 -1
  67. package/src/cli/index.ts +14 -1
  68. package/src/cli/load-config.images.test.ts +12 -12
  69. package/src/cli/load-config.ts +2 -2
  70. package/src/cli/mcp-from-console.ts +48 -0
  71. package/src/cli/registry.ts +35 -1
  72. package/src/cli/vault-cmd.test.ts +23 -0
  73. package/src/cli/vault-cmd.ts +7 -0
  74. package/src/client/agent.ts +307 -0
  75. package/src/client/create.ts +18 -1
  76. package/src/client/transport.test.ts +245 -0
  77. package/src/client/transport.ts +133 -19
  78. package/src/client/types.ts +29 -3
  79. package/src/client-react/index.ts +7 -1
  80. package/src/client-react/use-agent-run.test.ts +271 -0
  81. package/src/client-react/use-agent-run.ts +193 -0
  82. package/src/compiler/ai-approval.test.ts +36 -0
  83. package/src/compiler/ai-repair.test.ts +22 -0
  84. package/src/compiler/decisions.extract.test.ts +164 -0
  85. package/src/compiler/effects-infer.ts +753 -17
  86. package/src/compiler/extract.test.ts +37 -0
  87. package/src/compiler/extract.ts +381 -24
  88. package/src/compiler/fixtures/skyport.expected.json +24 -0
  89. package/src/compiler/fx-follow.test.ts +164 -0
  90. package/src/compiler/fx-index.ts +399 -0
  91. package/src/compiler/response.ts +35 -2
  92. package/src/config/index.ts +21 -3
  93. package/src/console/server/ai-runs-flows.ts +269 -0
  94. package/src/console/server/ai-runs.test.ts +323 -0
  95. package/src/console/server/ai-runs.ts +562 -0
  96. package/src/console/server/ai.ts +12 -1
  97. package/src/console/server/app.ts +10 -1
  98. package/src/console/server/decisions-flows.ts +157 -0
  99. package/src/console/server/decisions.test.ts +66 -0
  100. package/src/console/server/decisions.ts +229 -0
  101. package/src/console/server/flows-invoke.test.ts +2 -2
  102. package/src/console/server/flows.ts +50 -2
  103. package/src/console/server/invoke-user-flow.ts +9 -0
  104. package/src/console/server/runs-ingest.ts +16 -0
  105. package/src/console/server/serve.ts +5 -0
  106. package/src/console/server/state.ts +25 -1
  107. package/src/console/server/store-stats.test.ts +47 -0
  108. package/src/console/server/store-stats.ts +92 -18
  109. package/src/console/ui-next/dist/assets/access-page-DDKkhT9v.js +4 -0
  110. package/src/console/ui-next/dist/assets/agent-disclosure-62Xts8Xi.js +1 -0
  111. package/src/console/ui-next/dist/assets/{cache-glyph-92uM5MO7.js → cache-glyph-DyeoKHKA.js} +1 -1
  112. package/src/console/ui-next/dist/assets/{call-pii-button-DtGVPtcs.js → call-pii-button-DvfpLXsU.js} +1 -1
  113. package/src/console/ui-next/dist/assets/{collapsible-DN7l6zmC.js → collapsible-BY03SeCg.js} +1 -1
  114. package/src/console/ui-next/dist/assets/confirm-sheet-DZfuJXP4.js +1 -0
  115. package/src/console/ui-next/dist/assets/copy-inline-button-BTjPVjRT.js +1 -0
  116. package/src/console/ui-next/dist/assets/decisions-page-CgkKlA56.js +1 -0
  117. package/src/console/ui-next/dist/assets/detail-header-Dk5LipF6.js +1 -0
  118. package/src/console/ui-next/dist/assets/dropdown-menu-CRGrj5JU.js +1 -0
  119. package/src/console/ui-next/dist/assets/duration-tone-Y6HLjyJ5.js +9 -0
  120. package/src/console/ui-next/dist/assets/element-icons-C6t8Vlml.js +1 -0
  121. package/src/console/ui-next/dist/assets/explorer-chrome-Dslh2yE8.js +1 -0
  122. package/src/console/ui-next/dist/assets/explorer-empty-CIVg7Jgb.js +1 -0
  123. package/src/console/ui-next/dist/assets/flows-page-DLPfNy-_.js +1 -0
  124. package/src/console/ui-next/dist/assets/{highlighted-json-BlAEVgNW.js → highlighted-json-D7nNzpgB.js} +1 -1
  125. package/src/console/ui-next/dist/assets/{http-method-BDf7OAHv.js → http-method-DdL19zzh.js} +1 -1
  126. package/src/console/ui-next/dist/assets/index-BlrN49Hs.css +2 -0
  127. package/src/console/ui-next/dist/assets/index-C0lc_s9d.js +58 -0
  128. package/src/console/ui-next/dist/assets/observability-page-CRlcyLCC.js +8 -0
  129. package/src/console/ui-next/dist/assets/{replica-lag-B3GLNVfF.js → replica-lag-Bb3FWUu9.js} +7 -7
  130. package/src/console/ui-next/dist/assets/request-meta-DYBMWhX8.js +1 -0
  131. package/src/console/ui-next/dist/assets/shortcut-keys-DTE1sjTC.js +1 -0
  132. package/src/console/ui-next/dist/assets/store-page-CcE-SXC8.js +41 -0
  133. package/src/console/ui-next/dist/assets/trace-detail-sheet-CKMSEQ4s.js +2 -0
  134. package/src/console/ui-next/dist/assets/tree-expand-toggle-QOfk0M0H.js +55 -0
  135. package/src/console/ui-next/dist/assets/units-page-DKC1CDDd.js +1 -0
  136. package/src/console/ui-next/dist/assets/use-vault-list-BAyQG8Re.js +1 -0
  137. package/src/console/ui-next/dist/assets/vault-page-B54v4Yit.js +2 -0
  138. package/src/console/ui-next/dist/index.html +4 -3
  139. package/src/console/ui-next/seed-parked-approval.ts +126 -0
  140. package/src/console/ui-next/src/client.ts +224 -1
  141. package/src/console/ui-next/src/components/explorer/detail-header.tsx +9 -0
  142. package/src/console/ui-next/src/components/explorer/explorer-start-toggle.tsx +5 -1
  143. package/src/console/ui-next/src/components/ui/sheet-form.tsx +21 -12
  144. package/src/console/ui-next/src/features/flows/decisions/decisions-page.tsx +216 -0
  145. package/src/console/ui-next/src/features/flows/decisions/resolve.test.ts +48 -0
  146. package/src/console/ui-next/src/features/flows/decisions/resolve.ts +111 -0
  147. package/src/console/ui-next/src/features/flows/flows-page.tsx +10 -0
  148. package/src/console/ui-next/src/features/flows/graph/element-map.ts +1 -0
  149. package/src/console/ui-next/src/features/flows/traces/effect-kind.ts +6 -0
  150. package/src/console/ui-next/src/features/flows/traces/effect-summary.test.ts +24 -0
  151. package/src/console/ui-next/src/features/flows/traces/effect-summary.ts +24 -0
  152. package/src/console/ui-next/src/features/flows/traces/http-status.ts +58 -0
  153. package/src/console/ui-next/src/features/flows/traces/request-client-card.tsx +355 -0
  154. package/src/console/ui-next/src/features/flows/traces/request-client.test.ts +114 -0
  155. package/src/console/ui-next/src/features/flows/traces/request-client.ts +423 -0
  156. package/src/console/ui-next/src/features/flows/traces/request-input-view.test.ts +52 -6
  157. package/src/console/ui-next/src/features/flows/traces/request-input-view.ts +85 -19
  158. package/src/console/ui-next/src/features/flows/traces/trace-detail-sheet.tsx +505 -80
  159. package/src/console/ui-next/src/features/flows/traces/trace-lanes.test.ts +61 -0
  160. package/src/console/ui-next/src/features/flows/traces/trace-lanes.ts +78 -0
  161. package/src/console/ui-next/src/features/flows/traces/trace-nav.test.ts +48 -0
  162. package/src/console/ui-next/src/features/flows/traces/trace-nav.ts +57 -0
  163. package/src/console/ui-next/src/features/flows/traces/trace-request-section.tsx +275 -96
  164. package/src/console/ui-next/src/features/flows/traces/traces-pane.tsx +16 -2
  165. package/src/console/ui-next/src/features/observability/detail/ai-runs.tsx +369 -0
  166. package/src/console/ui-next/src/features/observability/observability-page.tsx +31 -1
  167. package/src/console/ui-next/src/features/observability/state/observability-selection.ts +18 -3
  168. package/src/console/ui-next/src/features/store/performance/kv-performance-panel.tsx +12 -1
  169. package/src/console/ui-next/src/features/store/performance/performance-panel.tsx +14 -1
  170. package/src/console/ui-next/src/features/units/call/call-api-panel.tsx +1 -1
  171. package/src/console/ui-next/src/features/units/detail/flow-contract-panel.tsx +15 -2
  172. package/src/console/ui-next/src/features/units/explorer/units-tree.tsx +73 -18
  173. package/src/console/ui-next/src/features/units/lib/unit-tree.test.ts +21 -0
  174. package/src/console/ui-next/src/features/units/lib/unit-tree.ts +82 -0
  175. package/src/console/ui-next/src/features/units/units-page.tsx +25 -7
  176. package/src/console/ui-next/src/router.tsx +17 -0
  177. package/src/console/ui-next/ui-next-seed-runs.ts +23 -0
  178. package/src/console/ui-next/vite-console-kernel-plugin.ts +43 -3
  179. package/src/console/ui-next/vite.config.ts +9 -0
  180. package/src/docker/docker.test.ts +13 -13
  181. package/src/docker/images-config.test.ts +12 -12
  182. package/src/docker/recipes/dragonfly.ts +3 -2
  183. package/src/docker/recipes/redis.ts +1 -1
  184. package/src/docker/stack-id.test.ts +1 -1
  185. package/src/drivers/ai-anthropic.ts +212 -21
  186. package/src/drivers/ai-mock.ts +34 -1
  187. package/src/drivers/ai-openai-compatible.ts +67 -26
  188. package/src/drivers/ai-preconnect.ts +18 -0
  189. package/src/drivers/ai-stream.test.ts +62 -0
  190. package/src/drivers/ai-types.ts +20 -0
  191. package/src/drivers/journal-postgres.ts +455 -3
  192. package/src/drivers/meilisearch.ts +2 -0
  193. package/src/drivers/memory-ddl.test.ts +18 -0
  194. package/src/drivers/memory.ts +21 -1
  195. package/src/drivers/pg-rls.test.ts +31 -0
  196. package/src/drivers/pg-rls.ts +15 -0
  197. package/src/drivers/postgres.test.ts +9 -0
  198. package/src/drivers/postgres.ts +49 -11
  199. package/src/drivers/vault-builtin.test.ts +10 -0
  200. package/src/drivers/vault-builtin.ts +13 -1
  201. package/src/drivers/vault-remote-bag.ts +5 -1
  202. package/src/drivers/vault-types.ts +6 -1
  203. package/src/elements/ai/agent-event-slot.ts +27 -0
  204. package/src/elements/ai/approval-http.ts +207 -0
  205. package/src/elements/ai/approval.test.ts +741 -0
  206. package/src/elements/ai/approval.ts +228 -0
  207. package/src/elements/ai/decisions/bind.ts +163 -0
  208. package/src/elements/ai/decisions/certificate.test.ts +291 -0
  209. package/src/elements/ai/decisions/certificate.ts +377 -0
  210. package/src/elements/ai/decisions/certify.ts +314 -0
  211. package/src/elements/ai/decisions/decide.test.ts +953 -0
  212. package/src/elements/ai/decisions/e2e.test.ts +399 -0
  213. package/src/elements/ai/decisions/export.test.ts +120 -0
  214. package/src/elements/ai/decisions/export.ts +146 -0
  215. package/src/elements/ai/decisions/fixtures/openrouter-request.json +24 -0
  216. package/src/elements/ai/decisions/fixtures/openrouter-response.json +22 -0
  217. package/src/elements/ai/decisions/fixtures/typesafe-request.json +19 -0
  218. package/src/elements/ai/decisions/fixtures/typesafe-response.json +13 -0
  219. package/src/elements/ai/decisions/http.test.ts +154 -0
  220. package/src/elements/ai/decisions/http.ts +240 -0
  221. package/src/elements/ai/decisions/labels.test.ts +282 -0
  222. package/src/elements/ai/decisions/labels.ts +257 -0
  223. package/src/elements/ai/decisions/openrouter.live.test.ts +136 -0
  224. package/src/elements/ai/decisions/openrouter.ts +36 -0
  225. package/src/elements/ai/decisions/provider.ts +102 -0
  226. package/src/elements/ai/decisions/typesafe.ts +36 -0
  227. package/src/elements/ai/declare.ts +252 -1
  228. package/src/elements/ai/events.test.ts +379 -0
  229. package/src/elements/ai/events.ts +138 -0
  230. package/src/elements/ai/run-events.test.ts +461 -0
  231. package/src/elements/ai/run-events.ts +522 -0
  232. package/src/elements/ai/runtime.ts +1186 -105
  233. package/src/elements/ai/stream-turn.ts +214 -0
  234. package/src/elements/ai/stream.live.test.ts +76 -0
  235. package/src/elements/ai/subagent.test.ts +136 -0
  236. package/src/elements/ai.test.ts +497 -3
  237. package/src/elements/ai.ts +16 -1
  238. package/src/elements/clock/durable.ts +27 -1
  239. package/src/elements/store/emit-drizzle.ts +2 -2
  240. package/src/elements/store/live-default.test.ts +2 -0
  241. package/src/elements/store/live-http.test.ts +1 -0
  242. package/src/elements/store/resource-list-docs.test.ts +2 -2
  243. package/src/elements/store/resource.test.ts +3 -3
  244. package/src/elements/store/schema-decl.test.ts +1 -0
  245. package/src/elements/store/sql-condition.ts +24 -7
  246. package/src/elements/store/sql-session.test.ts +51 -0
  247. package/src/elements/store/sql-session.ts +111 -1
  248. package/src/elements/store/upsert-app.test.ts +1 -1
  249. package/src/elements/vault/audit.test.ts +137 -0
  250. package/src/elements/vault/audit.ts +106 -13
  251. package/src/elements/vault/boot-chain.ts +9 -1
  252. package/src/elements/vault/builtin-adapter.ts +33 -3
  253. package/src/i18n/catalogs/ar.ts +9 -0
  254. package/src/i18n/catalogs/en.ts +9 -0
  255. package/src/index.ts +2 -0
  256. package/src/kernel/abort-scope.ts +33 -2
  257. package/src/kernel/agent-event-store.ts +448 -0
  258. package/src/kernel/app.ts +294 -19
  259. package/src/kernel/auto-cache.test.ts +6 -6
  260. package/src/kernel/boot-bind/ai.ts +3 -0
  261. package/src/kernel/boot-bind/store.test.ts +26 -0
  262. package/src/kernel/boot-bind/store.ts +82 -6
  263. package/src/kernel/boot-bind/vault.ts +1 -0
  264. package/src/kernel/boot.ts +34 -5
  265. package/src/kernel/builtin-errors.ts +10 -0
  266. package/src/kernel/capability.ts +3 -0
  267. package/src/kernel/client-descriptor.ts +1 -0
  268. package/src/kernel/concurrency.test.ts +33 -0
  269. package/src/kernel/decision-label-store.ts +441 -0
  270. package/src/kernel/effects-stamping.test.ts +2 -2
  271. package/src/kernel/effects.test.ts +2 -1
  272. package/src/kernel/effects.ts +13 -1
  273. package/src/kernel/element-registries.ts +3 -0
  274. package/src/kernel/errors-compiler.ts +20 -0
  275. package/src/kernel/errors-text.ts +4 -0
  276. package/src/kernel/errors.ts +2 -0
  277. package/src/kernel/external-effects.test.ts +36 -0
  278. package/src/kernel/flow.test.ts +2 -3
  279. package/src/kernel/flow.ts +24 -0
  280. package/src/kernel/fx-decide.ts +761 -0
  281. package/src/kernel/fx-fetch.ts +5 -1
  282. package/src/kernel/fx.test.ts +12 -5
  283. package/src/kernel/fx.ts +316 -29
  284. package/src/kernel/http-frame.test.ts +94 -0
  285. package/src/kernel/http-frame.ts +203 -0
  286. package/src/kernel/idempotency-store.ts +578 -0
  287. package/src/kernel/idempotency.test.ts +556 -0
  288. package/src/kernel/idempotency.ts +304 -0
  289. package/src/kernel/index.ts +1 -0
  290. package/src/kernel/journal.ts +160 -0
  291. package/src/kernel/json-result.ts +10 -0
  292. package/src/kernel/pipeline.test.ts +45 -0
  293. package/src/kernel/sse-id.ts +32 -0
  294. package/src/manifest/diff.ts +1 -0
  295. package/src/manifest/types.ts +37 -2
  296. package/src/mcp/ai-tools.test.ts +202 -0
  297. package/src/mcp/authorization.ts +66 -0
  298. package/src/mcp/session.ts +3 -0
  299. package/src/mcp/tools.ts +168 -0
  300. package/src/plugins/auth-delivery.mailpit.integration.test.ts +1 -1
  301. package/src/plugins/otp.test.ts +65 -1
  302. package/src/plugins/otp.ts +59 -7
  303. package/src/release/absolute-regression.test.ts +63 -0
  304. package/src/release/http-graph.test.ts +27 -0
  305. package/src/release/http-graph.ts +95 -0
  306. package/src/release/index.ts +3 -0
  307. package/src/release/limits.ts +17 -2
  308. package/src/release/measure.ts +144 -28
  309. package/src/runs/collect.ts +4 -1
  310. package/src/runs/parquet.test.ts +27 -1
  311. package/src/runs/parquet.ts +19 -0
  312. package/src/runs/types.ts +31 -0
  313. package/src/runtime/json-code-block.test.ts +106 -47
  314. package/src/runtime/json-code-block.ts +1209 -46
  315. package/src/term.test.ts +13 -0
  316. package/src/term.ts +81 -49
  317. package/src/test/create-test-app.test.ts +3 -1
  318. package/src/test/create-test-app.ts +40 -0
  319. package/src/test/live-signals.test.ts +1 -0
  320. package/src/test/provisions.integration.test.ts +1 -0
  321. package/src/test/tenant-isolation.test.ts +1 -0
  322. package/src/console/ui-next/dist/assets/PlusSignIcon-CwG3nxfu.js +0 -1
  323. package/src/console/ui-next/dist/assets/access-page-Bgt9bq2r.js +0 -4
  324. package/src/console/ui-next/dist/assets/agent-disclosure-B43CXZZR.js +0 -1
  325. package/src/console/ui-next/dist/assets/copy-inline-button-CAYD18cr.js +0 -1
  326. package/src/console/ui-next/dist/assets/detail-header-DVWNjWjg.js +0 -1
  327. package/src/console/ui-next/dist/assets/dropdown-menu-4h2LOVXM.js +0 -1
  328. package/src/console/ui-next/dist/assets/duration-tone-BmIR9FV8.js +0 -9
  329. package/src/console/ui-next/dist/assets/element-icons-BI8cJgdh.js +0 -1
  330. package/src/console/ui-next/dist/assets/explorer-empty-CJs5A-wm.js +0 -1
  331. package/src/console/ui-next/dist/assets/flows-page-BMHs-IzK.js +0 -1
  332. package/src/console/ui-next/dist/assets/index-BKpaes3n.js +0 -63
  333. package/src/console/ui-next/dist/assets/index-VxoEz295.css +0 -2
  334. package/src/console/ui-next/dist/assets/observability-page-WnVLI-0j.js +0 -4
  335. package/src/console/ui-next/dist/assets/request-meta-DMbnAe3f.js +0 -1
  336. package/src/console/ui-next/dist/assets/shortcut-keys-3ILd8oGn.js +0 -1
  337. package/src/console/ui-next/dist/assets/store-page-KvFDingJ.js +0 -41
  338. package/src/console/ui-next/dist/assets/trace-detail-sheet-Htk8Cm9t.js +0 -2
  339. package/src/console/ui-next/dist/assets/tree-expand-toggle-CFMPWX4f.js +0 -55
  340. package/src/console/ui-next/dist/assets/units-page-C4NdNuxP.js +0 -1
  341. package/src/console/ui-next/dist/assets/use-vault-list-CT4-gajj.js +0 -1
  342. package/src/console/ui-next/dist/assets/vault-page-CBYl0LW_.js +0 -2
@@ -0,0 +1,269 @@
1
+ /**
2
+ * Operator routes for agent runs and the tool-approval queue.
3
+ *
4
+ * Resolve uses the journal lease. `Conflict` is a finished approval.
5
+ * `JournalLeaseBusy` carries `Retry-After` while another worker holds the run.
6
+ */
7
+
8
+ import { z } from "zod";
9
+ import { journalLeaseBusyResponse, resolveAgentApproval } from "../../elements/ai/approval.ts";
10
+ import { fail, flow, http, type Binding } from "../../kernel/index.ts";
11
+ import { bindHttp } from "./bind.ts";
12
+ import { loadApprovalQueue, loadConsoleAgentRun, loadConsoleAgentRuns } from "./ai-runs.ts";
13
+ import type { ConsoleState } from "./state.ts";
14
+
15
+ const AuthFailed = z.object({});
16
+
17
+ const StopReason = z.enum(["completed", "max_steps", "budget", "denied", "aborted", "error"]);
18
+
19
+ const TrailStep = z.object({
20
+ tool: z.string(),
21
+ status: z.enum(["ok", "denied"]),
22
+ effects: z.array(
23
+ z.object({
24
+ kind: z.enum([
25
+ "read",
26
+ "write",
27
+ "emit",
28
+ "send",
29
+ "ask",
30
+ "embed",
31
+ "secret",
32
+ "call",
33
+ "fetch",
34
+ "decide",
35
+ ]),
36
+ resource: z.string(),
37
+ }),
38
+ ),
39
+ denial: z
40
+ .object({
41
+ agent: z.string(),
42
+ tool: z.string(),
43
+ gate: z.string(),
44
+ reason: z.string(),
45
+ at: z.number(),
46
+ })
47
+ .nullable(),
48
+ approver: z.string().optional(),
49
+ at: z.number(),
50
+ });
51
+
52
+ const RunRow = z.object({
53
+ id: z.string(),
54
+ agent: z.string(),
55
+ status: z.enum(["running", "finished", "error", "interrupted"]),
56
+ stopReason: StopReason.optional(),
57
+ error: z.string().optional(),
58
+ steps: z.number(),
59
+ cost: z.number(),
60
+ inputTokens: z.number().optional(),
61
+ outputTokens: z.number().optional(),
62
+ threadId: z.string().optional(),
63
+ startedAt: z.number(),
64
+ finishedAt: z.number().optional(),
65
+ parentRunId: z.string().optional(),
66
+ tenant: z.string().nullable(),
67
+ });
68
+
69
+ const RunDetail = RunRow.extend({
70
+ message: z.string(),
71
+ trail: z.array(TrailStep),
72
+ denials: z.array(
73
+ z.object({
74
+ agent: z.string(),
75
+ tool: z.string(),
76
+ gate: z.string(),
77
+ reason: z.string(),
78
+ at: z.number(),
79
+ }),
80
+ ),
81
+ repairs: z.array(
82
+ z.object({
83
+ prompt: z.string(),
84
+ at: z.number(),
85
+ attempts: z.number(),
86
+ }),
87
+ ),
88
+ children: z.array(RunRow),
89
+ events: z.array(
90
+ z.object({
91
+ seq: z.number(),
92
+ event: z.record(z.string(), z.unknown()),
93
+ }),
94
+ ),
95
+ });
96
+
97
+ const RunsOut = z.object({ runs: z.array(RunDetail) });
98
+ const RunOut = z.object({ run: RunDetail });
99
+
100
+ const ApprovalsOut = z.object({
101
+ rows: z.array(
102
+ z.object({
103
+ id: z.string(),
104
+ agent: z.string(),
105
+ tool: z.string(),
106
+ args: z.unknown(),
107
+ requestedAt: z.number(),
108
+ ageMs: z.number(),
109
+ gate: z.string(),
110
+ tenant: z.string().nullable(),
111
+ runId: z.string(),
112
+ }),
113
+ ),
114
+ });
115
+
116
+ const ApproveIn = z.object({
117
+ id: z.string().min(1),
118
+ args: z.unknown().optional(),
119
+ });
120
+
121
+ const DenyIn = z.object({
122
+ id: z.string().min(1),
123
+ reason: z.string().optional(),
124
+ });
125
+
126
+ const ResolveOut = z.object({ ok: z.literal(true) });
127
+
128
+ /**
129
+ * Parse edited tool args. A string must be JSON. Other JSON values pass through.
130
+ *
131
+ * @param args - Body field
132
+ */
133
+ export function parseEditedArgs(
134
+ args: unknown,
135
+ ): { readonly ok: true; readonly value?: unknown } | { readonly ok: false } {
136
+ if (args === undefined) return { ok: true };
137
+ if (typeof args === "string") {
138
+ try {
139
+ return { ok: true, value: JSON.parse(args) as unknown };
140
+ } catch {
141
+ return { ok: false };
142
+ }
143
+ }
144
+ return { ok: true, value: args };
145
+ }
146
+
147
+ /**
148
+ * List, detail, and resolve bindings.
149
+ *
150
+ * @param state - Console state
151
+ */
152
+ export function agentConsoleBindings(state: ConsoleState): Binding[] {
153
+ const sources = () => ({
154
+ runtime: state.aiRuntime,
155
+ store: state.journalStore,
156
+ now: Date.now(),
157
+ });
158
+
159
+ const list = flow("console.ai.runs.list", {
160
+ plane: "operator",
161
+ do: async (_input, fx) => {
162
+ if (!fx.operator.id) return fail("AuthFailed", {});
163
+ return { runs: await loadConsoleAgentRuns(sources()) };
164
+ },
165
+ });
166
+ const get = flow("console.ai.runs.get", {
167
+ plane: "operator",
168
+ do: async (input: { runId?: string }, fx) => {
169
+ if (!fx.operator.id) return fail("AuthFailed", {});
170
+ const runId = typeof input.runId === "string" ? input.runId : "";
171
+ const run = await loadConsoleAgentRun(sources(), runId);
172
+ if (!run) return fx.fail.notFound();
173
+ return { run };
174
+ },
175
+ });
176
+ const queue = flow("console.ai.approvals.list", {
177
+ plane: "operator",
178
+ do: async (_input, fx) => {
179
+ if (!fx.operator.id) return fail("AuthFailed", {});
180
+ return { rows: await loadApprovalQueue(state.journalStore, Date.now()) };
181
+ },
182
+ });
183
+ const approve = flow("console.ai.approvals.approve", {
184
+ plane: "operator",
185
+ do: async (input: { id: string; args?: unknown }, fx) => {
186
+ const reviewer = fx.operator.id;
187
+ if (!reviewer) return fail("AuthFailed", {});
188
+ const edited = parseEditedArgs(input.args);
189
+ if (!edited.ok) {
190
+ return fail("ValidationError", {
191
+ issues: [{ message: "edited args must be JSON", path: ["args"] }],
192
+ });
193
+ }
194
+ return resolveApproval(state, input.id, reviewer, {
195
+ decision: "approve",
196
+ ...(edited.value !== undefined ? { args: edited.value } : {}),
197
+ });
198
+ },
199
+ });
200
+ const deny = flow("console.ai.approvals.deny", {
201
+ plane: "operator",
202
+ do: async (input: { id: string; reason?: string }, fx) => {
203
+ const reviewer = fx.operator.id;
204
+ if (!reviewer) return fail("AuthFailed", {});
205
+ return resolveApproval(state, input.id, reviewer, {
206
+ decision: "deny",
207
+ ...(input.reason !== undefined ? { reason: input.reason } : {}),
208
+ });
209
+ },
210
+ });
211
+
212
+ return [
213
+ bindHttp(http.get("/console/ai/runs", { out: RunsOut, errors: { AuthFailed } }), list),
214
+ bindHttp(http.get("/console/ai/runs/:runId", { out: RunOut, errors: { AuthFailed } }), get),
215
+ bindHttp(
216
+ http.get("/console/ai/approvals", { out: ApprovalsOut, errors: { AuthFailed } }),
217
+ queue,
218
+ ),
219
+ bindHttp(
220
+ http.post("/console/ai/approvals/approve", {
221
+ in: ApproveIn,
222
+ out: ResolveOut,
223
+ errors: { AuthFailed },
224
+ }),
225
+ approve,
226
+ ),
227
+ bindHttp(
228
+ http.post("/console/ai/approvals/deny", {
229
+ in: DenyIn,
230
+ out: ResolveOut,
231
+ errors: { AuthFailed },
232
+ }),
233
+ deny,
234
+ ),
235
+ ];
236
+ }
237
+
238
+ async function resolveApproval(
239
+ state: ConsoleState,
240
+ id: string,
241
+ reviewer: string,
242
+ decision: {
243
+ readonly decision: "approve" | "deny";
244
+ readonly args?: unknown;
245
+ readonly reason?: string;
246
+ },
247
+ ): Promise<unknown> {
248
+ const store = state.journalStore;
249
+ if (!store) return fail.notFound();
250
+ const { readAgentApproval } = await import("../../elements/ai/approval.ts");
251
+ const pending = await readAgentApproval(store, id);
252
+ const result = await resolveAgentApproval(store, id, {
253
+ decision: decision.decision,
254
+ tenant: pending?.tenant ?? null,
255
+ approver: reviewer,
256
+ ...(decision.args !== undefined ? { args: decision.args } : {}),
257
+ ...(decision.reason !== undefined ? { reason: decision.reason } : {}),
258
+ });
259
+ if (result.ok) {
260
+ await state.afterAgentApproval?.();
261
+ return { ok: true as const };
262
+ }
263
+ if (result.status === 409 && result.reason === "lease") {
264
+ return journalLeaseBusyResponse(result.retryAfterSeconds);
265
+ }
266
+ if (result.status === 409) return fail.conflict();
267
+ if (result.status === 403) return fail.forbidden();
268
+ return fail.notFound();
269
+ }
@@ -0,0 +1,323 @@
1
+ /**
2
+ * Console agent-run routes and the approval lease.
3
+ */
4
+
5
+ import { afterAll, describe, expect, test } from "bun:test";
6
+ import { mkdtemp } from "node:fs/promises";
7
+ import { tmpdir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { issueSession } from "../../auth/index.ts";
10
+ import { approvalId } from "../../elements/ai/approval.ts";
11
+ import { createMemoryJournalStore } from "../../kernel/journal.ts";
12
+ import { startConsoleApp } from "./serve.ts";
13
+ import { parseEditedArgs } from "./ai-runs-flows.ts";
14
+ import { loadConsoleAgentRuns, projectApprovalQueue } from "./ai-runs.ts";
15
+
16
+ const cwd = await mkdtemp(join(tmpdir(), "oke-console-ai-"));
17
+
18
+ describe("parseEditedArgs", () => {
19
+ test("a string must be JSON and an empty omission stays omitted", () => {
20
+ expect(parseEditedArgs(undefined)).toEqual({ ok: true });
21
+ expect(parseEditedArgs('{"amount":4}')).toEqual({ ok: true, value: { amount: 4 } });
22
+ expect(parseEditedArgs("{")).toEqual({ ok: false });
23
+ expect(parseEditedArgs({ amount: 4 })).toEqual({ ok: true, value: { amount: 4 } });
24
+ });
25
+ });
26
+
27
+ describe("console agent routes", () => {
28
+ const store = createMemoryJournalStore();
29
+ const id = approvalId("run-parked", "tc1");
30
+ const handlePromise = startConsoleApp({
31
+ cwd,
32
+ secret: "test-secret-console-ai",
33
+ silentClaim: true,
34
+ journalStore: store,
35
+ });
36
+ let token = "";
37
+ let claiming: Promise<void> | undefined;
38
+
39
+ afterAll(async () => {
40
+ const handle = await handlePromise;
41
+ await handle.app.stop();
42
+ });
43
+
44
+ async function operator(): Promise<Awaited<typeof handlePromise>> {
45
+ const handle = await handlePromise;
46
+ if (!claiming) {
47
+ claiming = (async () => {
48
+ const claim = await handle.app.fetch(
49
+ new Request("http://console.test/console/setup/claim", {
50
+ method: "POST",
51
+ headers: { "content-type": "application/json" },
52
+ body: JSON.stringify({
53
+ claimCode: handle.state.claim.code,
54
+ email: "ops@example.com",
55
+ name: "Ops",
56
+ password: "Password1234!",
57
+ }),
58
+ }),
59
+ );
60
+ const body = (await claim.json()) as { data?: { accessToken: string } };
61
+ token = body.data?.accessToken ?? "";
62
+ })();
63
+ }
64
+ await claiming;
65
+ return handle;
66
+ }
67
+
68
+ test("an application principal cannot list approvals", async () => {
69
+ const app = await operator();
70
+ const user = await issueSession(
71
+ app.state.sessions,
72
+ { secret: app.state.secret, now: app.state.now },
73
+ { id: "user-1", plane: "user", scopes: ["bookings:create"] },
74
+ );
75
+ const res = await app.app.fetch(
76
+ new Request("http://console.test/console/ai/approvals", {
77
+ headers: { authorization: `Bearer ${user.accessToken}` },
78
+ }),
79
+ );
80
+ expect(res.status).toBe(403);
81
+ });
82
+
83
+ test("the queue shows the tenant, the first approve wins, and the second is Conflict", async () => {
84
+ await store.put({
85
+ id: "run-parked",
86
+ flow: "assist",
87
+ input: {},
88
+ status: "sleeping",
89
+ entries: [
90
+ {
91
+ kind: "step",
92
+ name: `ai-approval:${id}`,
93
+ at: 1_000,
94
+ value: {
95
+ status: "pending",
96
+ agent: "support",
97
+ tool: "refund",
98
+ args: { amount: 10 },
99
+ gate: "ops",
100
+ tenant: "ws_keel",
101
+ requestedAt: 1_000,
102
+ },
103
+ },
104
+ ],
105
+ createdAt: 1_000,
106
+ updatedAt: 1_000,
107
+ wakeAt: Date.now() + 60_000,
108
+ });
109
+ const app = await operator();
110
+ const listed = await app.app.fetch(
111
+ new Request("http://console.test/console/ai/approvals", {
112
+ headers: { authorization: `Bearer ${token}` },
113
+ }),
114
+ );
115
+ expect(listed.status).toBe(200);
116
+ const queue = (await listed.json()) as {
117
+ data: { rows: { agent: string; tenant: string; tool: string }[] };
118
+ };
119
+ expect(queue.data.rows[0]).toMatchObject({
120
+ agent: "support",
121
+ tool: "refund",
122
+ tenant: "ws_keel",
123
+ });
124
+
125
+ const first = await app.app.fetch(
126
+ new Request("http://console.test/console/ai/approvals/approve", {
127
+ method: "POST",
128
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
129
+ body: JSON.stringify({ id, args: { amount: 4 } }),
130
+ }),
131
+ );
132
+ expect(first.status).toBe(200);
133
+
134
+ const second = await app.app.fetch(
135
+ new Request("http://console.test/console/ai/approvals/approve", {
136
+ method: "POST",
137
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
138
+ body: JSON.stringify({ id }),
139
+ }),
140
+ );
141
+ expect(second.status).toBe(409);
142
+ const conflict = (await second.json()) as { error: { code: string } };
143
+ expect(conflict.error.code).toBe("Conflict");
144
+ expect(second.headers.get("retry-after")).toBeNull();
145
+ });
146
+
147
+ test("a held lease is JournalLeaseBusy with Retry-After", async () => {
148
+ const busyId = approvalId("run-busy", "tc2");
149
+ await store.put({
150
+ id: "run-busy",
151
+ flow: "assist",
152
+ input: {},
153
+ status: "sleeping",
154
+ entries: [
155
+ {
156
+ kind: "step",
157
+ name: `ai-approval:${busyId}`,
158
+ at: 1_000,
159
+ value: {
160
+ status: "pending",
161
+ agent: "support",
162
+ tool: "refund",
163
+ args: { amount: 1 },
164
+ gate: "ops",
165
+ tenant: null,
166
+ requestedAt: 1_000,
167
+ },
168
+ },
169
+ ],
170
+ createdAt: 1_000,
171
+ updatedAt: 1_000,
172
+ wakeAt: Date.now() + 60_000,
173
+ });
174
+ await store.acquireLease?.("run-busy", "other", Date.now(), 30_000);
175
+ const app = await operator();
176
+ const res = await app.app.fetch(
177
+ new Request("http://console.test/console/ai/approvals/deny", {
178
+ method: "POST",
179
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
180
+ body: JSON.stringify({ id: busyId, reason: "no" }),
181
+ }),
182
+ );
183
+ expect(res.status).toBe(409);
184
+ expect(res.headers.get("retry-after")).not.toBeNull();
185
+ const body = (await res.json()) as { error: { code: string } };
186
+ expect(body.error.code).toBe("JournalLeaseBusy");
187
+ });
188
+ });
189
+
190
+ describe("projectApprovalQueue", () => {
191
+ test("age is now minus requestedAt and a foreign tenant is dropped", () => {
192
+ const id = approvalId("run", "tc");
193
+ const rows = projectApprovalQueue(
194
+ [
195
+ {
196
+ id: "run",
197
+ flow: "assist",
198
+ input: {},
199
+ status: "sleeping",
200
+ entries: [
201
+ {
202
+ kind: "step",
203
+ name: `ai-approval:${id}`,
204
+ at: 1_000,
205
+ value: {
206
+ status: "pending",
207
+ agent: "support",
208
+ tool: "refund",
209
+ args: {},
210
+ gate: "ops",
211
+ tenant: "a",
212
+ requestedAt: 1_000,
213
+ },
214
+ },
215
+ ],
216
+ createdAt: 1_000,
217
+ updatedAt: 1_000,
218
+ },
219
+ ],
220
+ 61_000,
221
+ "b",
222
+ );
223
+ expect(rows).toEqual([]);
224
+ const kept = projectApprovalQueue(
225
+ [
226
+ {
227
+ id: "run",
228
+ flow: "assist",
229
+ input: {},
230
+ status: "sleeping",
231
+ entries: [
232
+ {
233
+ kind: "step",
234
+ name: `ai-approval:${id}`,
235
+ at: 1_000,
236
+ value: {
237
+ status: "pending",
238
+ agent: "support",
239
+ tool: "refund",
240
+ args: {},
241
+ gate: "ops",
242
+ tenant: "a",
243
+ requestedAt: 1_000,
244
+ },
245
+ },
246
+ ],
247
+ createdAt: 1_000,
248
+ updatedAt: 1_000,
249
+ },
250
+ ],
251
+ 61_000,
252
+ "a",
253
+ );
254
+ expect(kept[0]?.ageMs).toBe(60_000);
255
+ expect(kept[0]?.tenant).toBe("a");
256
+ });
257
+ });
258
+
259
+ describe("loadConsoleAgentRuns", () => {
260
+ test("the follow-log header names the agent and the journal step is the trail", async () => {
261
+ const store = createMemoryJournalStore();
262
+ const agentEvents = store.agentEvents;
263
+ if (!agentEvents) throw new Error("agent event store missing");
264
+ const id = approvalId("journal-run", "tc1");
265
+ await agentEvents.writeHeader({
266
+ runId: "run-logged",
267
+ threadId: "thread-1",
268
+ agent: "support",
269
+ tenant: null,
270
+ gates: [],
271
+ userId: null,
272
+ operatorId: null,
273
+ openedAt: 1_000,
274
+ });
275
+ await agentEvents.append("run-logged", {
276
+ seq: 1,
277
+ event: {
278
+ type: "RUN_FINISHED",
279
+ threadId: "thread-1",
280
+ runId: "run-logged",
281
+ outcome: { type: "interrupt", interrupts: [{ id, reason: "approval" }] },
282
+ },
283
+ });
284
+ await agentEvents.append("run-logged", {
285
+ seq: 2,
286
+ event: { type: "TOOL_CALL_START", toolCallId: "tc1", toolCallName: "refund" },
287
+ });
288
+ await agentEvents.append("run-logged", {
289
+ seq: 3,
290
+ event: { type: "STEP_STARTED", stepName: "step-1" },
291
+ });
292
+ await store.put({
293
+ id: "journal-run",
294
+ flow: "assist",
295
+ input: {},
296
+ status: "sleeping",
297
+ entries: [
298
+ {
299
+ kind: "step",
300
+ name: `ai-approval:${id}`,
301
+ at: 1_000,
302
+ value: {
303
+ status: "pending",
304
+ agent: "support",
305
+ tool: "refund",
306
+ args: { amount: 10 },
307
+ gate: "ops",
308
+ tenant: null,
309
+ requestedAt: 1_000,
310
+ },
311
+ },
312
+ ],
313
+ createdAt: 1_000,
314
+ updatedAt: 1_000,
315
+ });
316
+ const runs = await loadConsoleAgentRuns({ runtime: null, store, now: 2_000 });
317
+ expect(runs[0]?.agent).toBe("support");
318
+ expect(runs[0]?.threadId).toBe("thread-1");
319
+ expect(runs[0]?.status).toBe("interrupted");
320
+ expect(runs[0]?.steps).toBe(1);
321
+ expect(runs[0]?.trail[0]).toMatchObject({ tool: "refund", status: "pending" });
322
+ });
323
+ });