@pensar/apex 2.7.0-canary.c5791908 → 2.7.0-canary.dc4eeb73

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 (283) hide show
  1. package/README.md +13 -0
  2. package/build/agent-02pnejnw.js +14 -0
  3. package/build/{agent-x8nf3k1v.js → agent-5k6qd29v.js} +7 -7
  4. package/build/agent-7k53k922.js +14 -0
  5. package/build/{agent-q85c8mrh.js → agent-gbz5rygq.js} +6 -6
  6. package/build/{agent-runs-cqa7xz7d.js → agent-runs-4krbrfbz.js} +20 -20
  7. package/build/{apps-pxdathp4.js → apps-pfv0zdbc.js} +17 -17
  8. package/build/{auth-dcmykx6e.js → auth-yf8h2pcm.js} +17 -17
  9. package/build/blackboxAgent-zfvw66gx.js +14 -0
  10. package/build/{blackboxPentest-pbh960ms.js → blackboxPentest-drx2dh8q.js} +12 -12
  11. package/build/{cli-se8ae8z3.js → cli-0rhfexax.js} +3 -3
  12. package/build/{cli-ps5hmkhw.js → cli-2kxz8wct.js} +24 -13
  13. package/build/cli-4fkaes4s.js +1199 -0
  14. package/build/{cli-78pm8byz.js → cli-4mmtfeyq.js} +1 -1
  15. package/build/{cli-vb4den7a.js → cli-5c420jyh.js} +3 -1
  16. package/build/{cli-mfgsx6hc.js → cli-6kgf7d6q.js} +1 -1
  17. package/build/{cli-am8b7hr4.js → cli-6pa9g38w.js} +2 -2
  18. package/build/{cli-gsaf4jk3.js → cli-7898kznf.js} +2 -2
  19. package/build/{cli-jvhswf25.js → cli-91xbw8s1.js} +2 -2
  20. package/build/{cli-xcy2vxj2.js → cli-ak23knae.js} +1 -1
  21. package/build/{cli-kr28rrsa.js → cli-bxaessv4.js} +2 -2
  22. package/build/{cli-jpjj10xv.js → cli-c70xpef4.js} +5 -1
  23. package/build/{cli-pepjaeek.js → cli-cthffb4f.js} +12 -11
  24. package/build/{cli-40gstjf7.js → cli-d5zzvezc.js} +14 -8
  25. package/build/{cli-xpfw29g5.js → cli-dzs7b8qg.js} +5 -4
  26. package/build/{cli-m57v3wm9.js → cli-e6gwq7a9.js} +2 -2
  27. package/build/{cli-b8jmzd32.js → cli-h7y81bkg.js} +1 -1
  28. package/build/{cli-xb0pqkbk.js → cli-hr8cdrm9.js} +4 -4
  29. package/build/{cli-ygcbxb1m.js → cli-hrb1gb3f.js} +4 -4
  30. package/build/{cli-3gt761d2.js → cli-j0wfj2kw.js} +6 -0
  31. package/build/{cli-b3hef9fp.js → cli-k72gvna3.js} +4358 -982
  32. package/build/{cli-7nrpp1ks.js → cli-pthzx104.js} +1 -1
  33. package/build/{cli-8wkays8e.js → cli-pyrrf4ms.js} +13 -49
  34. package/build/{cli-v084p264.js → cli-r9kjgdr6.js} +1 -1
  35. package/build/{cli-6g5p7cfd.js → cli-twtnm4ms.js} +388 -260
  36. package/build/{cli-z41890cy.js → cli-ww29nrnd.js} +1 -1
  37. package/build/{cli-pwm29ks7.js → cli-ychebg4z.js} +16 -16
  38. package/build/cli.js +47 -42
  39. package/build/{config-d9mdqs9w.js → config-kyzwb0kw.js} +4 -4
  40. package/build/{doctor-z94afr10.js → doctor-srja68wr.js} +1 -0
  41. package/build/emscripten-module-kzkvkeqz.js +503 -0
  42. package/build/{export-trajectory-rt4tf07k.js → export-trajectory-ex317s0n.js} +1 -1
  43. package/build/{fastStrike-z096431v.js → fastStrike-f5h0bwrp.js} +6 -6
  44. package/build/ffi-pf145jhd.js +78 -0
  45. package/build/{fixes-9ppnsazw.js → fixes-6ew73pvs.js} +17 -17
  46. package/build/{index-pxhc0cbs.js → index-5yww2gt7.js} +2 -2
  47. package/build/{index-t8ncgcc9.js → index-ez32src5.js} +1 -1
  48. package/build/{index-qnyevb6q.js → index-ffe5c30s.js} +13 -13
  49. package/build/{index-cn1pgs79.js → index-h41d5ahy.js} +5 -4
  50. package/build/{index-vq0132nv.js → index-p1en670g.js} +7 -7
  51. package/build/{index-4gfq7kzj.js → index-q4rvvcjm.js} +9 -9
  52. package/build/{index-1j283k20.js → index-rzc981b7.js} +21 -17
  53. package/build/{index-f0v1bbhs.js → index-vymh03hj.js} +65 -26
  54. package/build/{index-y5t6w61g.js → index-x5ta620q.js} +1 -1
  55. package/build/{index-pvb4d38m.js → index-x9w3tzx7.js} +5 -5
  56. package/build/{issues-hnw2wt5k.js → issues-e956aq7d.js} +52 -25
  57. package/build/{knowledge-66kn0fwh.js → knowledge-1hat8sct.js} +17 -17
  58. package/build/{lance-qyph9jw1.js → lance-g8wtg17c.js} +8 -8
  59. package/build/lib/{chunk-10p58fqe.js → chunk-0fthn5vv.js} +8 -7
  60. package/build/lib/chunk-188my1pm.js +112 -0
  61. package/build/lib/{chunk-98gxfne9.js → chunk-2zvreyrw.js} +2 -2
  62. package/build/lib/{chunk-y9pm3xqv.js → chunk-3jz6jqxd.js} +1 -1
  63. package/build/lib/{chunk-rcneqwt6.js → chunk-3kpdgtve.js} +12 -48
  64. package/build/lib/{chunk-rh6fz13n.js → chunk-5veg292g.js} +2 -2
  65. package/build/lib/{chunk-7syrjsr5.js → chunk-75yfsj0q.js} +2 -1
  66. package/build/lib/{chunk-7350h8ab.js → chunk-8cbwztjg.js} +11 -11
  67. package/build/lib/{chunk-zntm5p3b.js → chunk-91jtnq4d.js} +33 -18
  68. package/build/lib/{chunk-bq643vks.js → chunk-9gkjbdzc.js} +1 -1
  69. package/build/lib/{chunk-pr63gfsd.js → chunk-aw579bmb.js} +1 -1
  70. package/build/lib/{chunk-5avnedwm.js → chunk-dhpxjgd5.js} +589 -97
  71. package/build/lib/{chunk-2svje0df.js → chunk-gyv3p1c4.js} +9 -3
  72. package/build/lib/{chunk-00jhhedd.js → chunk-hv8fgz23.js} +193 -343
  73. package/build/lib/{chunk-qpewr18w.js → chunk-jfekc6hy.js} +1 -1
  74. package/build/lib/{chunk-ptp3er5d.js → chunk-npq9ftzp.js} +4 -1
  75. package/build/lib/{chunk-y82jpv2x.js → chunk-p3ghsa83.js} +11 -10
  76. package/build/lib/{chunk-486zwtmg.js → chunk-p4pt2x7b.js} +1126 -51
  77. package/build/lib/{chunk-c5w6byvf.js → chunk-q7j8wy3a.js} +1 -1
  78. package/build/lib/{chunk-q3f1tjdx.js → chunk-qz91fj8n.js} +1 -1
  79. package/build/lib/{chunk-w9cs2h48.js → chunk-rcmken1g.js} +5 -5
  80. package/build/lib/{chunk-6vhf2dvv.js → chunk-sm1q467w.js} +1 -1
  81. package/build/lib/{chunk-0hqjfqxb.js → chunk-sqt67cq5.js} +137 -119
  82. package/build/lib/{chunk-dj7bk5xm.js → chunk-szr3nyqa.js} +10 -9
  83. package/build/lib/{chunk-tcdd68ax.js → chunk-xh9yr9y0.js} +5 -1
  84. package/build/lib/{chunk-qn9512q7.js → chunk-zdvz6e1v.js} +1 -1
  85. package/build/lib/core/agents/agentRuntime.d.ts +4 -0
  86. package/build/lib/core/agents/offSecAgent/index.js +11 -10
  87. package/build/lib/core/agents/offSecAgent/offensiveSecurityAgent.d.ts +1 -0
  88. package/build/lib/core/agents/offSecAgent/runtimeContext.d.ts +1 -0
  89. package/build/lib/core/agents/offSecAgent/subagentSpawner.d.ts +1 -0
  90. package/build/lib/core/agents/offSecAgent/subagentSpawner.js +6 -5
  91. package/build/lib/core/agents/offSecAgent/tools/browserHeaderRouting.d.ts +2 -0
  92. package/build/lib/core/agents/offSecAgent/tools/getPage.d.ts +1 -2
  93. package/build/lib/core/agents/offSecAgent/tools/httpRequest.d.ts +1 -1
  94. package/build/lib/core/agents/offSecAgent/tools/index.js +10 -9
  95. package/build/lib/core/agents/offSecAgent/tools/scopeGuard.d.ts +7 -18
  96. package/build/lib/core/agents/offSecAgent/tools/types.d.ts +2 -1
  97. package/build/lib/core/agents/offSecAgent/tools/webSearch.d.ts +8 -0
  98. package/build/lib/core/agents/offSecAgent/types.d.ts +9 -1
  99. package/build/lib/core/agents/specialized/attackSurface/blackboxAgent.js +11 -10
  100. package/build/lib/core/agents/specialized/attackSurface/prompts.d.ts +1 -1
  101. package/build/lib/core/agents/specialized/attackSurface/schemas.js +11 -10
  102. package/build/lib/core/agents/specialized/authenticationAgent/index.js +12 -11
  103. package/build/lib/core/agents/specialized/codeAgent/agent.js +11 -10
  104. package/build/lib/core/agents/specialized/findingJudge/agent.js +10 -9
  105. package/build/lib/core/agents/specialized/findingJudge/index.d.ts +1 -1
  106. package/build/lib/core/agents/specialized/findingJudge/index.js +4 -3
  107. package/build/lib/core/agents/specialized/patching/index.js +12 -11
  108. package/build/lib/core/agents/specialized/pentest/agent.js +11 -10
  109. package/build/lib/core/agents/specialized/whiteboxAttackSurface/index.js +11 -10
  110. package/build/lib/core/ai/ai.d.ts +5 -2
  111. package/build/lib/core/ai/ai.js +3 -2
  112. package/build/lib/core/ai/index.d.ts +2 -0
  113. package/build/lib/core/ai/index.js +6 -3
  114. package/build/lib/core/ai/modelRuntime.d.ts +10 -0
  115. package/build/lib/core/ai/models/inference.d.ts +2 -0
  116. package/build/lib/core/ai/utils.d.ts +2 -0
  117. package/build/lib/core/ai/utils.js +3 -2
  118. package/build/lib/core/api/index.d.ts +2 -2
  119. package/build/lib/core/api/index.js +27 -21
  120. package/build/lib/core/api/issues.d.ts +125 -16
  121. package/build/lib/core/api/targetedPentest.js +12 -11
  122. package/build/lib/core/code-mode/capabilityInvoker.d.ts +53 -0
  123. package/build/lib/core/code-mode/index.d.ts +3 -0
  124. package/build/lib/core/code-mode/runtime.d.ts +42 -0
  125. package/build/lib/core/code-mode/tools.d.ts +16 -0
  126. package/build/lib/core/config/config.d.ts +2 -0
  127. package/build/lib/core/config/index.js +1 -1
  128. package/build/lib/core/findings/registry.js +4 -3
  129. package/build/lib/core/http/researchFetchToken.d.ts +2 -0
  130. package/build/lib/core/http/targetHeaders.d.ts +2 -0
  131. package/build/lib/core/http/targetScope.d.ts +3 -0
  132. package/build/lib/core/providers/types.d.ts +1 -1
  133. package/build/lib/core/providers/utils.d.ts +1 -1
  134. package/build/lib/core/session/index.js +3 -2
  135. package/build/lib/core/session/persistence.js +4 -3
  136. package/build/lib/core/tools/backends/index.js +3 -1
  137. package/build/lib/core/tools/backends/types.d.ts +2 -0
  138. package/build/lib/core/workflows/pentest.js +17 -16
  139. package/build/lib/core/workflows/seams.js +5 -4
  140. package/build/lib/core/workflows/whiteboxAttackSurface.d.ts +3 -3
  141. package/build/lib/core/workflows/whiteboxAttackSurface.js +13 -12
  142. package/build/lib/index.js +24 -23
  143. package/build/{logs-h3rxtq6w.js → logs-r1ene0wa.js} +17 -17
  144. package/build/module-ES6BEMUI-6ewavg9p.js +12 -0
  145. package/build/{native-rollout-evidence-kt4rd2bp.js → native-rollout-evidence-ddaypcmp.js} +4 -4
  146. package/build/{offesecAgent-e3ea8mr6.js → offesecAgent-g95mjx3s.js} +6 -6
  147. package/build/pentest-341705d4.js +23 -0
  148. package/build/{pentests-39hy0dre.js → pentests-tj609s19.js} +17 -17
  149. package/build/recordedRunClient-k9pqxwvp.js +11 -0
  150. package/build/{subagentSpawner-2sx2edxp.js → subagentSpawner-086t0dyq.js} +4 -4
  151. package/build/{targetedPentest-ttafan4t.js → targetedPentest-42vx9fxg.js} +8 -8
  152. package/build/{targets-fzte2kq9.js → targets-yt5mgbx2.js} +17 -17
  153. package/build/threatModel-d8mesare.js +24 -0
  154. package/build/{uninstall-0m52nyc0.js → uninstall-z7mexzkf.js} +1 -1
  155. package/build/{upload-cnnhkzgt.js → upload-sr2fekpm.js} +4 -4
  156. package/build/{utils-pq6pdv6p.js → utils-3m9rnw7g.js} +8 -4
  157. package/package.json +3 -1
  158. package/src/cli/agent-runs.test.ts +1 -4
  159. package/src/cli/issues.test.ts +234 -12
  160. package/src/cli/issues.ts +49 -9
  161. package/src/cli.ts +1 -0
  162. package/src/core/agents/agentRuntime.test.ts +16 -0
  163. package/src/core/agents/agentRuntime.ts +8 -0
  164. package/src/core/agents/offSecAgent/offensiveSecurityAgent.codeMode.test.ts +435 -0
  165. package/src/core/agents/offSecAgent/offensiveSecurityAgent.runtimeContext.test.ts +1 -0
  166. package/src/core/agents/offSecAgent/offensiveSecurityAgent.test.ts +6 -1
  167. package/src/core/agents/offSecAgent/offensiveSecurityAgent.ts +94 -8
  168. package/src/core/agents/offSecAgent/prompt.ts +2 -2
  169. package/src/core/agents/offSecAgent/recordedTools.test.ts +6 -1
  170. package/src/core/agents/offSecAgent/runtimeContext.test.ts +19 -0
  171. package/src/core/agents/offSecAgent/runtimeContext.ts +9 -2
  172. package/src/core/agents/offSecAgent/selectiveConstruction.publicPath.test.ts +2 -0
  173. package/src/core/agents/offSecAgent/selectiveConstruction.test.ts +6 -1
  174. package/src/core/agents/offSecAgent/subagentSpawner.hooks.test.ts +3 -0
  175. package/src/core/agents/offSecAgent/subagentSpawner.ts +7 -0
  176. package/src/core/agents/offSecAgent/tools/browserHeaderRouting.redirect.test.ts +141 -0
  177. package/src/core/agents/offSecAgent/tools/browserHeaderRouting.test.ts +106 -8
  178. package/src/core/agents/offSecAgent/tools/browserHeaderRouting.ts +56 -16
  179. package/src/core/agents/offSecAgent/tools/delegateAuth.ts +5 -0
  180. package/src/core/agents/offSecAgent/tools/documentFinding.ts +1 -0
  181. package/src/core/agents/offSecAgent/tools/executeCommand.test.ts +2 -1
  182. package/src/core/agents/offSecAgent/tools/getPage.test.ts +120 -0
  183. package/src/core/agents/offSecAgent/tools/getPage.ts +24 -19
  184. package/src/core/agents/offSecAgent/tools/httpBackends.test.ts +18 -25
  185. package/src/core/agents/offSecAgent/tools/httpRequest.body.test.ts +214 -0
  186. package/src/core/agents/offSecAgent/tools/httpRequest.test.ts +54 -0
  187. package/src/core/agents/offSecAgent/tools/httpRequest.ts +20 -11
  188. package/src/core/agents/offSecAgent/tools/playwrightMcp.test.ts +5 -0
  189. package/src/core/agents/offSecAgent/tools/playwrightMcp.ts +5 -2
  190. package/src/core/agents/offSecAgent/tools/runAttackSurface.ts +2 -0
  191. package/src/core/agents/offSecAgent/tools/runPentestWorkflow.ts +1 -0
  192. package/src/core/agents/offSecAgent/tools/sandboxPlaywright.test.ts +47 -0
  193. package/src/core/agents/offSecAgent/tools/sandboxPlaywright.ts +65 -2
  194. package/src/core/agents/offSecAgent/tools/scopeGuard.test.ts +121 -52
  195. package/src/core/agents/offSecAgent/tools/scopeGuard.ts +50 -30
  196. package/src/core/agents/offSecAgent/tools/spawnCodingAgent.ts +1 -0
  197. package/src/core/agents/offSecAgent/tools/spawnPentestAgent.test.ts +4 -3
  198. package/src/core/agents/offSecAgent/tools/spawnPentestAgent.ts +1 -0
  199. package/src/core/agents/offSecAgent/tools/spawnPentestSwarm.ts +1 -0
  200. package/src/core/agents/offSecAgent/tools/threatModelGenerator.ts +1 -0
  201. package/src/core/agents/offSecAgent/tools/types.ts +2 -0
  202. package/src/core/agents/offSecAgent/tools/webSearch.test.ts +154 -0
  203. package/src/core/agents/offSecAgent/tools/webSearch.ts +119 -87
  204. package/src/core/agents/offSecAgent/types.ts +10 -0
  205. package/src/core/agents/specialized/attackSurface/blackboxAgent.ts +3 -3
  206. package/src/core/agents/specialized/attackSurface/prompts.ts +9 -45
  207. package/src/core/agents/specialized/findingJudge/index.ts +2 -0
  208. package/src/core/agents/specialized/pentest/agent.ts +1 -1
  209. package/src/core/ai/ai.effective-tools.test.ts +27 -2
  210. package/src/core/ai/ai.test.ts +34 -6
  211. package/src/core/ai/ai.ts +22 -2
  212. package/src/core/ai/compactionTelemetry.test.ts +167 -5
  213. package/src/core/ai/index.ts +6 -0
  214. package/src/core/ai/inference.test.ts +292 -0
  215. package/src/core/ai/modelRuntime.test.ts +58 -0
  216. package/src/core/ai/modelRuntime.ts +63 -0
  217. package/src/core/ai/models/concentrate.ts +13 -0
  218. package/src/core/ai/models/index.ts +10 -7
  219. package/src/core/ai/models/inference.ts +11 -0
  220. package/src/core/ai/models/models.test.ts +28 -0
  221. package/src/core/ai/models/openai.ts +6 -0
  222. package/src/core/ai/providers/concentrate.ts +1 -0
  223. package/src/core/ai/providers/openai-models.test.ts +5 -0
  224. package/src/core/ai/providers/pensarResponsesStream.test.ts +117 -0
  225. package/src/core/ai/providers/pensarResponsesStream.ts +20 -1
  226. package/src/core/ai/reasoning.test.ts +4 -0
  227. package/src/core/ai/reasoning.ts +2 -0
  228. package/src/core/ai/utils.ts +47 -12
  229. package/src/core/api/index.ts +4 -0
  230. package/src/core/api/issues.test.ts +80 -6
  231. package/src/core/api/issues.ts +137 -16
  232. package/src/core/api/recordedRun.loop.test.ts +67 -0
  233. package/src/core/code-mode/capabilityInvoker.test.ts +424 -0
  234. package/src/core/code-mode/capabilityInvoker.ts +383 -0
  235. package/src/core/code-mode/index.ts +8 -0
  236. package/src/core/code-mode/runtime.setup.test.ts +157 -0
  237. package/src/core/code-mode/runtime.test.ts +664 -0
  238. package/src/core/code-mode/runtime.ts +700 -0
  239. package/src/core/code-mode/tools.test.ts +375 -0
  240. package/src/core/code-mode/tools.ts +281 -0
  241. package/src/core/config/config.test.ts +7 -0
  242. package/src/core/config/config.ts +3 -0
  243. package/src/core/doctor.ts +1 -0
  244. package/src/core/http/agentNetworkPolicyFixture.test.ts +39 -0
  245. package/src/core/http/headers.contract.test.ts +100 -2
  246. package/src/core/http/researchFetchToken.test.ts +50 -0
  247. package/src/core/http/researchFetchToken.ts +63 -0
  248. package/src/core/http/targetHeaders.ts +26 -8
  249. package/src/core/http/targetScope.ts +47 -11
  250. package/src/core/providers/types.ts +7 -0
  251. package/src/core/providers/utils.ts +6 -1
  252. package/src/core/providers/verify.test.ts +54 -0
  253. package/src/core/providers/verify.ts +28 -0
  254. package/src/core/runtime/runRecoveryPlan.test.ts +18 -0
  255. package/src/core/runtime/runRecoveryPlan.ts +5 -0
  256. package/src/core/runtime/runTools.test.ts +2 -0
  257. package/src/core/runtime/runTools.ts +4 -1
  258. package/src/core/runtime/sqliteControlStore.test.ts +21 -0
  259. package/src/core/runtime/sqliteControlStore.ts +6 -1
  260. package/src/core/runtime/sqliteRecoveryStore.test.ts +24 -5
  261. package/src/core/tools/backends/local.test.ts +126 -0
  262. package/src/core/tools/backends/local.ts +256 -59
  263. package/src/core/tools/backends/policy.test.ts +36 -1
  264. package/src/core/tools/backends/policy.ts +9 -4
  265. package/src/core/tools/backends/types.ts +2 -0
  266. package/src/core/workflows/whiteboxAttackSurface.test.ts +40 -0
  267. package/src/core/workflows/whiteboxAttackSurface.ts +9 -4
  268. package/src/test-fixtures/agent-network-policy-v2.json +80 -0
  269. package/src/tui/components/chat/input-area.tsx +1 -0
  270. package/src/tui/components/commands/api-key-input.tsx +2 -0
  271. package/src/tui/components/commands/operator-wizard.tsx +2 -0
  272. package/src/tui/components/commands/provider-manager.tsx +3 -0
  273. package/src/tui/components/model-picker/ModelPicker.tsx +1 -0
  274. package/src/tui/components/model-picker/__tests__/reasoning-control.tsx +41 -14
  275. package/src/tui/components/model-picker/model-search.test.ts +11 -0
  276. package/src/tui/components/model-picker/model-search.ts +1 -0
  277. package/src/tui/components/model-picker/reasoning-control.test.ts +8 -2
  278. package/build/agent-htj3ww3e.js +0 -14
  279. package/build/agent-km3wss0b.js +0 -14
  280. package/build/blackboxAgent-g18ps9hs.js +0 -14
  281. package/build/pentest-qx9c8wtg.js +0 -23
  282. package/build/recordedRunClient-gra1x1y6.js +0 -11
  283. package/build/threatModel-nm449g6b.js +0 -24
@@ -0,0 +1,700 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import RELEASE_SYNC from "@jitl/quickjs-singlefile-cjs-release-sync";
3
+ import type { ModelMessage } from "ai";
4
+ import { newQuickJSWASMModule, Scope } from "quickjs-emscripten";
5
+ import type {
6
+ CanonicalCapabilityInvoker,
7
+ CodeModeCellMetrics,
8
+ CodeModeEvidenceReference,
9
+ } from "./capabilityInvoker";
10
+
11
+ const DEFAULT_YIELD_MS = 10_000;
12
+ const MAX_YIELD_MS = 60_000;
13
+ const MAX_CELL_RUNTIME_MS = 30 * 60 * 1000;
14
+ const MAX_CPU_SLICE_MS = 2_000;
15
+ const DISPOSE_GRACE_MS = 5_000;
16
+ const MEMORY_LIMIT_BYTES = 64 * 1024 * 1024;
17
+ const MAX_OUTPUT_CHARS = 30_000;
18
+ const MAX_STORED_VALUE_CHARS = 1_000_000;
19
+ const MAX_NESTED_RESULT_CHARS = 1_000_000;
20
+ const MAX_STORED_TOTAL_CHARS = 8_000_000;
21
+ const MAX_NESTED_CALLS = 1_000;
22
+
23
+ // Embed WASM so Bun bundles and standalone binaries need no adjacent asset.
24
+ let quickJS: ReturnType<typeof newQuickJSWASMModule> | undefined;
25
+
26
+ export type CodeCellStatus = "completed" | "failed" | "running" | "terminated";
27
+
28
+ export type CodeCellResult = {
29
+ cellId: string;
30
+ status: CodeCellStatus;
31
+ output: string;
32
+ metrics?: CodeModeCellMetrics & { durationMs: number };
33
+ evidence?: CodeModeEvidenceReference[];
34
+ guidance?: string[];
35
+ };
36
+
37
+ type ExecutionContext = {
38
+ parentToolCallId: string;
39
+ messages: ModelMessage[];
40
+ abortSignal?: AbortSignal;
41
+ experimental_context?: unknown;
42
+ };
43
+
44
+ type Cell = {
45
+ controller: AbortController;
46
+ promise: Promise<CodeCellResult>;
47
+ };
48
+
49
+ function truncateOutput(value: string): string {
50
+ if (value.length <= MAX_OUTPUT_CHARS) return value;
51
+ return `${value.slice(0, MAX_OUTPUT_CHARS)}\n...[code-mode output truncated]`;
52
+ }
53
+
54
+ function serializeOutput(value: unknown): string {
55
+ if (typeof value === "string") return value;
56
+ if (value === undefined) return "";
57
+ try {
58
+ return JSON.stringify(value);
59
+ } catch {
60
+ return String(value);
61
+ }
62
+ }
63
+
64
+ function combineSignals(local: AbortSignal, parent?: AbortSignal): AbortSignal {
65
+ return parent ? AbortSignal.any([local, parent]) : local;
66
+ }
67
+
68
+ const GUEST_PRELUDE = `
69
+ (() => {
70
+ const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
71
+ const bytesToBase64 = (bytes) => {
72
+ let output = "";
73
+ for (let i = 0; i < bytes.length; i += 3) {
74
+ const a = bytes[i];
75
+ const b = i + 1 < bytes.length ? bytes[i + 1] : 0;
76
+ const c = i + 2 < bytes.length ? bytes[i + 2] : 0;
77
+ output += BASE64[a >> 2];
78
+ output += BASE64[((a & 3) << 4) | (b >> 4)];
79
+ output += i + 1 < bytes.length ? BASE64[((b & 15) << 2) | (c >> 6)] : "=";
80
+ output += i + 2 < bytes.length ? BASE64[c & 63] : "=";
81
+ }
82
+ return output;
83
+ };
84
+ const base64ToBytes = (value) => {
85
+ const clean = String(value).replace(/\\s+/g, "").replace(/=+$/, "");
86
+ const bytes = [];
87
+ let bits = 0;
88
+ let bitCount = 0;
89
+ for (const char of clean) {
90
+ const index = BASE64.indexOf(char);
91
+ if (index < 0) throw new TypeError("Invalid base64 input");
92
+ bits = (bits << 6) | index;
93
+ bitCount += 6;
94
+ if (bitCount >= 8) {
95
+ bitCount -= 8;
96
+ bytes.push((bits >> bitCount) & 255);
97
+ }
98
+ }
99
+ return bytes;
100
+ };
101
+ const utf8ToBytes = (value) => {
102
+ const encoded = unescape(encodeURIComponent(String(value)));
103
+ return Array.from(encoded, (char) => char.charCodeAt(0));
104
+ };
105
+ const bytesToUtf8 = (bytes) => {
106
+ const binary = Array.from(bytes, (byte) => String.fromCharCode(byte)).join("");
107
+ return decodeURIComponent(escape(binary));
108
+ };
109
+ class ApexBuffer extends Uint8Array {
110
+ static from(value, encoding = "utf8") {
111
+ if (value instanceof Uint8Array || Array.isArray(value)) return new ApexBuffer(value);
112
+ const normalized = String(encoding).toLowerCase();
113
+ if (normalized === "base64") return new ApexBuffer(base64ToBytes(value));
114
+ if (normalized === "hex") {
115
+ const input = String(value);
116
+ if (!/^(?:[0-9a-f]{2})*$/i.test(input)) throw new TypeError("Invalid hex input");
117
+ return new ApexBuffer(input.match(/../g)?.map((part) => parseInt(part, 16)) || []);
118
+ }
119
+ return new ApexBuffer(utf8ToBytes(value));
120
+ }
121
+ toString(encoding = "utf8") {
122
+ const normalized = String(encoding).toLowerCase();
123
+ if (normalized === "base64") return bytesToBase64(this);
124
+ if (normalized === "hex") return Array.from(this, (byte) => byte.toString(16).padStart(2, "0")).join("");
125
+ return bytesToUtf8(this);
126
+ }
127
+ }
128
+ const sleep = (ms) => __apexSleep(ms);
129
+ globalThis.Buffer = ApexBuffer;
130
+ globalThis.btoa = (value) => bytesToBase64(Array.from(String(value), (char) => char.charCodeAt(0) & 255));
131
+ globalThis.atob = (value) => Array.from(base64ToBytes(value), (byte) => String.fromCharCode(byte)).join("");
132
+ globalThis.sleep = sleep;
133
+ globalThis.setTimeout = (callback, ms, ...args) => sleep(ms).then(() => callback(...args));
134
+ globalThis.require = (name) => {
135
+ if (name === "buffer") return { Buffer: ApexBuffer };
136
+ if (name === "timers/promises") return { setTimeout: sleep };
137
+ throw new Error("require(" + JSON.stringify(name) + ") is unavailable in the isolated runtime; use JavaScript globals for computation and tools.call with an allowed capability for host operations");
138
+ };
139
+ const laneFor = (name) => {
140
+ if (name === "execute_command") return "shell";
141
+ if (name.startsWith("browser_")) return "browser";
142
+ return undefined;
143
+ };
144
+ const activeLanes = new Set();
145
+ const invoke = async (name, input = {}) => {
146
+ const lane = laneFor(name);
147
+ if (lane && activeLanes.has(lane)) {
148
+ const hint = lane === "shell"
149
+ ? "execute_command is single-lane. Await each command before starting the next; use JavaScript in exec to compose other independent capabilities."
150
+ : "Browser operations are single-lane and stateful; await each mutation before starting the next.";
151
+ const error = new Error(hint);
152
+ error.toJSON = () => ({ name: "Error", message: hint });
153
+ throw error;
154
+ }
155
+ if (lane) activeLanes.add(lane);
156
+ try {
157
+ const normalizedInput = name === "execute_command" && input && typeof input === "object" && !Array.isArray(input) && input.timeout == null && input.timeoutSeconds == null
158
+ ? { ...input, timeout: 120 }
159
+ : input;
160
+ const encoded = await __apexInvoke(name, JSON.stringify(normalizedInput));
161
+ return JSON.parse(encoded);
162
+ } finally {
163
+ if (lane) activeLanes.delete(lane);
164
+ }
165
+ };
166
+ const describe = async (name) => JSON.parse(await __apexDescribe(String(name)));
167
+ const browser = Object.freeze({
168
+ navigate: (input) => invoke("browser_navigate", input),
169
+ snapshot: (input) => invoke("browser_snapshot", input),
170
+ click: (input) => invoke("browser_click", input),
171
+ fill: (input) => invoke("browser_fill", input),
172
+ evaluate: (input) => invoke("browser_evaluate", input),
173
+ console: (input) => invoke("browser_console", input),
174
+ getCookies: (input) => invoke("browser_get_cookies", input),
175
+ });
176
+ globalThis.tools = Object.freeze({
177
+ call: invoke,
178
+ describe,
179
+ browser,
180
+ });
181
+ globalThis.ALL_TOOLS = Object.freeze(__APEX_ALL_TOOLS__);
182
+ globalThis.text = (value) => __apexText(JSON.stringify(value) ?? "null");
183
+ globalThis.store = (key, value) => {
184
+ const encoded = JSON.stringify(value);
185
+ if (encoded === undefined) throw new TypeError("Stored values must be JSON serializable");
186
+ if (encoded.length > 1000000) {
187
+ throw new Error("Stored code-mode values are limited to 1000000 characters; persist large artifacts with create_file instead");
188
+ }
189
+ return __apexStore(key, encoded);
190
+ };
191
+ globalThis.load = (key) => {
192
+ const value = __apexLoad(key);
193
+ return value === undefined ? undefined : JSON.parse(value);
194
+ };
195
+ const runLimited = async (items, concurrency, worker, settle) => {
196
+ if (!Array.isArray(items)) throw new TypeError("items must be an array");
197
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
198
+ throw new TypeError("concurrency must be a positive integer");
199
+ }
200
+ const results = new Array(items.length);
201
+ let nextIndex = 0;
202
+ let stopped = false;
203
+ const lane = async () => {
204
+ while (!stopped && nextIndex < items.length) {
205
+ const index = nextIndex++;
206
+ if (settle) {
207
+ try {
208
+ results[index] = {
209
+ status: "fulfilled",
210
+ value: await worker(items[index], index),
211
+ };
212
+ } catch (reason) {
213
+ results[index] = { status: "rejected", reason: String(reason) };
214
+ }
215
+ } else {
216
+ try {
217
+ results[index] = await worker(items[index], index);
218
+ } catch (error) {
219
+ stopped = true;
220
+ throw error;
221
+ }
222
+ }
223
+ }
224
+ };
225
+ await Promise.all(
226
+ Array.from(
227
+ { length: Math.min(concurrency, items.length) },
228
+ () => lane(),
229
+ ),
230
+ );
231
+ return results;
232
+ };
233
+ globalThis.mapLimit = (items, concurrency, worker) =>
234
+ runLimited(items, concurrency, worker, false);
235
+ globalThis.mapLimitSettled = (items, concurrency, worker) =>
236
+ runLimited(items, concurrency, worker, true);
237
+ })();
238
+ `;
239
+
240
+ export class CodeModeRuntime {
241
+ private readonly cells = new Map<string, Cell>();
242
+ private readonly storedValues = new Map<string, string>();
243
+ private storedChars = 0;
244
+ private disposePromise?: Promise<void>;
245
+ private disposed = false;
246
+
247
+ private readonly guestPrelude: string;
248
+
249
+ constructor(
250
+ private readonly invoker: CanonicalCapabilityInvoker,
251
+ availableTools: Iterable<string> = [],
252
+ private readonly onCellComplete?: (result: CodeCellResult) => void,
253
+ ) {
254
+ this.guestPrelude = GUEST_PRELUDE.replace(
255
+ "__APEX_ALL_TOOLS__",
256
+ JSON.stringify([...availableTools]),
257
+ );
258
+ }
259
+
260
+ async execute(
261
+ code: string,
262
+ context: ExecutionContext,
263
+ yieldTimeMs = DEFAULT_YIELD_MS,
264
+ ): Promise<CodeCellResult> {
265
+ if (this.disposed) throw new Error("Code-mode runtime is disposed");
266
+ if (!code.trim()) throw new Error("exec requires non-empty JavaScript");
267
+
268
+ const cellId = `cell_${randomUUID()}`;
269
+ const controller = new AbortController();
270
+ const signal = combineSignals(controller.signal, context.abortSignal);
271
+ const timer = setTimeout(
272
+ () => controller.abort("Code-mode execution deadline exceeded"),
273
+ MAX_CELL_RUNTIME_MS,
274
+ );
275
+ const promise = this.runCell(cellId, code, {
276
+ ...context,
277
+ abortSignal: signal,
278
+ }).finally(() => clearTimeout(timer));
279
+ this.cells.set(cellId, { controller, promise });
280
+
281
+ return this.yieldCell(cellId, promise, yieldTimeMs);
282
+ }
283
+
284
+ async wait(
285
+ cellId: string,
286
+ options: {
287
+ yieldTimeMs?: number;
288
+ terminate?: boolean;
289
+ abortSignal?: AbortSignal;
290
+ } = {},
291
+ ): Promise<CodeCellResult> {
292
+ options.abortSignal?.throwIfAborted();
293
+ const cell = this.cells.get(cellId);
294
+ if (!cell) throw new Error(`Unknown or completed code cell: ${cellId}`);
295
+ if (options.terminate) cell.controller.abort("Terminated by wait");
296
+ return this.yieldCell(
297
+ cellId,
298
+ cell.promise,
299
+ options.terminate ? null : (options.yieldTimeMs ?? DEFAULT_YIELD_MS),
300
+ options.abortSignal,
301
+ );
302
+ }
303
+
304
+ async dispose(): Promise<void> {
305
+ this.disposePromise ??= this.disposeCells();
306
+ return this.disposePromise;
307
+ }
308
+
309
+ private async disposeCells(): Promise<void> {
310
+ this.disposed = true;
311
+ const cells = [...this.cells.values()];
312
+ for (const cell of cells)
313
+ cell.controller.abort("Code-mode runtime disposed");
314
+ let timer: ReturnType<typeof setTimeout> | undefined;
315
+ await Promise.race([
316
+ Promise.allSettled(cells.map((cell) => cell.promise)),
317
+ new Promise<void>((resolve) => {
318
+ timer = setTimeout(resolve, DISPOSE_GRACE_MS);
319
+ }),
320
+ ]);
321
+ if (timer) clearTimeout(timer);
322
+ this.cells.clear();
323
+ this.storedValues.clear();
324
+ this.storedChars = 0;
325
+ }
326
+
327
+ private async yieldCell(
328
+ cellId: string,
329
+ promise: Promise<CodeCellResult>,
330
+ requestedYieldMs: number | null,
331
+ abortSignal?: AbortSignal,
332
+ ): Promise<CodeCellResult> {
333
+ abortSignal?.throwIfAborted();
334
+ let timer: ReturnType<typeof setTimeout> | undefined;
335
+ const running = new Promise<CodeCellResult>((resolve) => {
336
+ if (requestedYieldMs === null) return;
337
+ const yieldTimeMs = Math.min(Math.max(0, requestedYieldMs), MAX_YIELD_MS);
338
+ timer = setTimeout(
339
+ () => resolve({ cellId, status: "running", output: "" }),
340
+ yieldTimeMs,
341
+ );
342
+ });
343
+ let onAbort: (() => void) | undefined;
344
+ const cancelled = new Promise<never>((_, reject) => {
345
+ if (!abortSignal) return;
346
+ onAbort = () => reject(abortSignal.reason);
347
+ abortSignal.addEventListener("abort", onAbort, { once: true });
348
+ });
349
+ try {
350
+ const result = await Promise.race([promise, running, cancelled]);
351
+ if (result.status !== "running") this.cells.delete(cellId);
352
+ return result;
353
+ } finally {
354
+ if (timer) clearTimeout(timer);
355
+ if (onAbort) abortSignal?.removeEventListener("abort", onAbort);
356
+ }
357
+ }
358
+
359
+ private async runCell(
360
+ cellId: string,
361
+ code: string,
362
+ context: ExecutionContext,
363
+ ): Promise<CodeCellResult> {
364
+ const startedAt = Date.now();
365
+ let output = "";
366
+ const appendOutput = (value: unknown) => {
367
+ if (output.length > MAX_OUTPUT_CHARS) return;
368
+ const serialized = serializeOutput(value);
369
+ if (serialized)
370
+ output = truncateOutput(
371
+ output ? `${output}\n${serialized}` : serialized,
372
+ );
373
+ };
374
+ const hostCalls = new Set<Promise<void>>();
375
+ let nestedResultChars = 0;
376
+ let nestedCalls = 0;
377
+ let loadedValueChars = 0;
378
+ const deadline = Date.now() + MAX_CELL_RUNTIME_MS;
379
+ let cpuDeadline = Date.now() + MAX_CPU_SLICE_MS;
380
+ const scope = new Scope();
381
+ let onAbort: (() => void) | undefined;
382
+ let drainHostCalls = async () => {};
383
+ try {
384
+ quickJS ??= newQuickJSWASMModule(RELEASE_SYNC).catch((error) => {
385
+ quickJS = undefined;
386
+ throw error;
387
+ });
388
+ const QuickJS = await quickJS;
389
+ context.abortSignal?.throwIfAborted();
390
+ const runtime = scope.manage(QuickJS.newRuntime());
391
+ runtime.setMemoryLimit(MEMORY_LIMIT_BYTES);
392
+ runtime.setInterruptHandler(
393
+ () =>
394
+ context.abortSignal?.aborted === true ||
395
+ Date.now() > deadline ||
396
+ Date.now() > cpuDeadline,
397
+ );
398
+ const vm = scope.manage(runtime.newContext());
399
+ let pendingJobs = Promise.resolve();
400
+ const pumpJobs = () => {
401
+ pendingJobs = pendingJobs.then(() => {
402
+ cpuDeadline = Date.now() + MAX_CPU_SLICE_MS;
403
+ const result = runtime.executePendingJobs();
404
+ if (result.error) {
405
+ const error = vm.dump(result.error);
406
+ result.error.dispose();
407
+ throw new Error(serializeOutput(error));
408
+ }
409
+ });
410
+ return pendingJobs;
411
+ };
412
+
413
+ const bridgePromise = <T>(
414
+ deferred: ReturnType<typeof vm.newPromise>,
415
+ operation: Promise<T>,
416
+ serialize: (value: T) => string | undefined,
417
+ onAbort?: () => void,
418
+ ) => {
419
+ let settled = false;
420
+ const operationState: {
421
+ finish?: (kind: "resolve" | "reject", value?: unknown) => void;
422
+ } = {};
423
+ let completeBridge: () => void = () => {};
424
+ const bridge = new Promise<void>((resolve) => {
425
+ completeBridge = resolve;
426
+ });
427
+ hostCalls.add(bridge);
428
+
429
+ const finish = (kind: "resolve" | "reject", value?: unknown) => {
430
+ if (settled) return;
431
+ settled = true;
432
+ operationState.finish = undefined;
433
+ context.abortSignal?.removeEventListener("abort", abort);
434
+
435
+ const encoded =
436
+ kind === "resolve"
437
+ ? serialize(value as T)
438
+ : value instanceof Error
439
+ ? value.message
440
+ : String(value);
441
+ const handle =
442
+ encoded === undefined ? vm.undefined : vm.newString(encoded);
443
+ if (kind === "resolve") deferred.resolve(handle);
444
+ else deferred.reject(handle);
445
+ if (handle !== vm.undefined) handle.dispose();
446
+
447
+ void pumpJobs()
448
+ .catch(() => undefined)
449
+ .finally(() => {
450
+ hostCalls.delete(bridge);
451
+ completeBridge();
452
+ });
453
+ };
454
+ operationState.finish = finish;
455
+ const abort = () => {
456
+ onAbort?.();
457
+ finish(
458
+ "reject",
459
+ context.abortSignal?.reason ?? "Code-mode execution aborted",
460
+ );
461
+ };
462
+
463
+ if (context.abortSignal?.aborted) abort();
464
+ else
465
+ context.abortSignal?.addEventListener("abort", abort, { once: true });
466
+
467
+ void operation.then(
468
+ (value) => operationState.finish?.("resolve", value),
469
+ (error) => operationState.finish?.("reject", error),
470
+ );
471
+ return deferred.handle;
472
+ };
473
+ drainHostCalls = async () => {
474
+ while (hostCalls.size > 0) {
475
+ await Promise.allSettled([...hostCalls]);
476
+ await pendingJobs.catch(() => undefined);
477
+ }
478
+ await pendingJobs.catch(() => undefined);
479
+ };
480
+
481
+ const invokeHandle = scope.manage(
482
+ vm.newFunction("__apexInvoke", (nameHandle, inputHandle) => {
483
+ if (++nestedCalls > MAX_NESTED_CALLS) {
484
+ throw new Error(
485
+ `Code-mode cells are limited to ${MAX_NESTED_CALLS} nested calls`,
486
+ );
487
+ }
488
+ const name = vm.getString(nameHandle);
489
+ const input = JSON.parse(vm.getString(inputHandle)) as unknown;
490
+ const deferred = vm.newPromise();
491
+ const call = this.invoker
492
+ .invoke(name, input, {
493
+ parentToolCallId: context.parentToolCallId,
494
+ messages: context.messages,
495
+ abortSignal: context.abortSignal,
496
+ experimental_context: context.experimental_context,
497
+ })
498
+ .then((result) => {
499
+ const encoded = JSON.stringify(result ?? null);
500
+ if (
501
+ nestedResultChars + encoded.length >
502
+ MAX_NESTED_RESULT_CHARS
503
+ ) {
504
+ throw new Error(
505
+ `Code-mode nested results are limited to ${MAX_NESTED_RESULT_CHARS} characters per cell; split large reads across cells and persist only compact state or artifacts with create_file`,
506
+ );
507
+ }
508
+ nestedResultChars += encoded.length;
509
+ return encoded;
510
+ });
511
+ return bridgePromise(deferred, call, (result) => result);
512
+ }),
513
+ );
514
+ vm.setProp(vm.global, "__apexInvoke", invokeHandle);
515
+ invokeHandle.dispose();
516
+
517
+ const describeHandle = scope.manage(
518
+ vm.newFunction("__apexDescribe", (nameHandle) => {
519
+ const deferred = vm.newPromise();
520
+ return bridgePromise(
521
+ deferred,
522
+ this.invoker.describe(vm.getString(nameHandle)),
523
+ (result) => JSON.stringify(result),
524
+ );
525
+ }),
526
+ );
527
+ vm.setProp(vm.global, "__apexDescribe", describeHandle);
528
+ describeHandle.dispose();
529
+
530
+ const sleepHandle = scope.manage(
531
+ vm.newFunction("__apexSleep", (durationHandle) => {
532
+ const durationMs = Math.min(
533
+ 30_000,
534
+ Math.max(0, Math.floor(vm.getNumber(durationHandle))),
535
+ );
536
+ const deferred = vm.newPromise();
537
+ let timer: ReturnType<typeof setTimeout> | undefined;
538
+ let finishSleep: () => void = () => {};
539
+ const sleep = new Promise<void>((resolve) => {
540
+ finishSleep = resolve;
541
+ timer = setTimeout(resolve, durationMs);
542
+ });
543
+ return bridgePromise(
544
+ deferred,
545
+ sleep,
546
+ () => undefined,
547
+ () => {
548
+ if (timer) clearTimeout(timer);
549
+ finishSleep();
550
+ },
551
+ );
552
+ }),
553
+ );
554
+ vm.setProp(vm.global, "__apexSleep", sleepHandle);
555
+ sleepHandle.dispose();
556
+
557
+ const textHandle = scope.manage(
558
+ vm.newFunction("__apexText", (valueHandle) => {
559
+ const value = JSON.parse(vm.getString(valueHandle)) as unknown;
560
+ appendOutput(value);
561
+ }),
562
+ );
563
+ vm.setProp(vm.global, "__apexText", textHandle);
564
+ textHandle.dispose();
565
+
566
+ const storeHandle = scope.manage(
567
+ vm.newFunction("__apexStore", (keyHandle, valueHandle) => {
568
+ const value = vm.getString(valueHandle);
569
+ if (value.length > MAX_STORED_VALUE_CHARS) {
570
+ throw new Error(
571
+ `Stored code-mode values are limited to ${MAX_STORED_VALUE_CHARS} characters; persist large artifacts with create_file instead`,
572
+ );
573
+ }
574
+ const key = vm.getString(keyHandle);
575
+ const previous = this.storedValues.get(key);
576
+ const total =
577
+ this.storedChars -
578
+ (previous?.length ?? 0) +
579
+ value.length +
580
+ (previous === undefined ? key.length : 0);
581
+ if (total > MAX_STORED_TOTAL_CHARS) {
582
+ throw new Error(
583
+ `Stored code-mode state is limited to ${MAX_STORED_TOTAL_CHARS} characters in total; persist large artifacts with create_file instead`,
584
+ );
585
+ }
586
+ this.storedValues.set(key, value);
587
+ this.storedChars = total;
588
+ }),
589
+ );
590
+ vm.setProp(vm.global, "__apexStore", storeHandle);
591
+ storeHandle.dispose();
592
+
593
+ const loadHandle = scope.manage(
594
+ vm.newFunction("__apexLoad", (keyHandle) => {
595
+ const value = this.storedValues.get(vm.getString(keyHandle));
596
+ if (value === undefined) return vm.undefined;
597
+ if (loadedValueChars + value.length > MAX_STORED_VALUE_CHARS) {
598
+ throw new Error(
599
+ `Loaded code-mode values are limited to ${MAX_STORED_VALUE_CHARS} characters per cell; load compact state and page large artifacts with read_file`,
600
+ );
601
+ }
602
+ loadedValueChars += value.length;
603
+ return vm.newString(value);
604
+ }),
605
+ );
606
+ vm.setProp(vm.global, "__apexLoad", loadHandle);
607
+ loadHandle.dispose();
608
+
609
+ cpuDeadline = Date.now() + MAX_CPU_SLICE_MS;
610
+ vm.unwrapResult(
611
+ vm.evalCode(this.guestPrelude, "apex-code-mode.js"),
612
+ ).dispose();
613
+ cpuDeadline = Date.now() + MAX_CPU_SLICE_MS;
614
+ const evaluated = vm.evalCode(
615
+ `(async () => {\n${code}\n})()`,
616
+ "apex-exec.js",
617
+ );
618
+ const promiseHandle = scope.manage(vm.unwrapResult(evaluated));
619
+ const resolution = vm.resolvePromise(promiseHandle);
620
+ // Register the resolver first; even pure guest promises need a job pump.
621
+ await pumpJobs();
622
+ // Interrupts cannot wake an idle guest promise, so also cancel the host wait.
623
+ const cancelled = new Promise<never>((_, reject) => {
624
+ onAbort = () =>
625
+ reject(
626
+ new Error(
627
+ String(
628
+ context.abortSignal?.reason ?? "Code-mode execution aborted",
629
+ ),
630
+ ),
631
+ );
632
+ if (context.abortSignal?.aborted) onAbort();
633
+ else
634
+ context.abortSignal?.addEventListener("abort", onAbort, {
635
+ once: true,
636
+ });
637
+ });
638
+ const resolved = await Promise.race([resolution, cancelled]);
639
+ const resultHandle = vm.unwrapResult(resolved);
640
+ const returned = vm.dump(resultHandle);
641
+ resultHandle.dispose();
642
+ await drainHostCalls();
643
+ await pumpJobs();
644
+ if (returned !== undefined) appendOutput(returned);
645
+ const observation = this.invoker.completeCell(context.parentToolCallId);
646
+ const result: CodeCellResult = {
647
+ cellId,
648
+ status: "completed",
649
+ output,
650
+ metrics: {
651
+ ...observation.metrics,
652
+ durationMs: Date.now() - startedAt,
653
+ },
654
+ ...(observation.evidence.length > 0
655
+ ? { evidence: observation.evidence }
656
+ : {}),
657
+ ...(observation.guidance.length > 0
658
+ ? { guidance: observation.guidance }
659
+ : {}),
660
+ };
661
+ this.notifyCellComplete(result);
662
+ return result;
663
+ } catch (error) {
664
+ // Drain sibling calls after rejection so no callback touches a freed VM.
665
+ await drainHostCalls();
666
+ const terminated = context.abortSignal?.aborted === true;
667
+ const observation = this.invoker.completeCell(context.parentToolCallId);
668
+ const result: CodeCellResult = {
669
+ cellId,
670
+ status: terminated ? "terminated" : "failed",
671
+ output: truncateOutput(
672
+ error instanceof Error ? error.message : String(error),
673
+ ),
674
+ metrics: {
675
+ ...observation.metrics,
676
+ durationMs: Date.now() - startedAt,
677
+ },
678
+ ...(observation.evidence.length > 0
679
+ ? { evidence: observation.evidence }
680
+ : {}),
681
+ ...(observation.guidance.length > 0
682
+ ? { guidance: observation.guidance }
683
+ : {}),
684
+ };
685
+ this.notifyCellComplete(result);
686
+ return result;
687
+ } finally {
688
+ if (onAbort) context.abortSignal?.removeEventListener("abort", onAbort);
689
+ scope.dispose();
690
+ }
691
+ }
692
+
693
+ private notifyCellComplete(result: CodeCellResult): void {
694
+ try {
695
+ this.onCellComplete?.(result);
696
+ } catch {
697
+ // Metrics callbacks must not change the execution result or VM teardown.
698
+ }
699
+ }
700
+ }