@humain/humain-code 0.6.2 → 0.7.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 (792) hide show
  1. package/CHANGELOG.md +119 -0
  2. package/README.md +23 -6
  3. package/dist/agent-monitor/entry.lazy.d.ts +3 -0
  4. package/dist/agent-monitor/entry.lazy.d.ts.map +1 -0
  5. package/dist/agent-monitor/entry.lazy.js +3 -0
  6. package/dist/agent-monitor/entry.lazy.js.map +1 -0
  7. package/dist/bundle/agent-monitor.js +1 -1
  8. package/dist/bundle/chunks/adaptive-peer-worker-X2ZNZE3S.js +8 -0
  9. package/dist/bundle/chunks/adaptive-session-host-7KDSQV5I.js +162 -0
  10. package/dist/bundle/chunks/anthropic-messages-TQK3FUV3.js +68 -0
  11. package/dist/bundle/chunks/anthropic.js +13 -10
  12. package/dist/bundle/chunks/{azure-openai-responses-IV74M5OR.js → azure-openai-responses-JY7OSLH2.js} +6 -6
  13. package/dist/bundle/chunks/bedrock-converse-stream.js +79 -74
  14. package/dist/bundle/chunks/chunk-2FYYW6FY.js +2 -0
  15. package/dist/bundle/chunks/{chunk-A2VPLMF2.js → chunk-2G7YVAVF.js} +1 -1
  16. package/dist/bundle/chunks/chunk-32QLLD2P.js +1114 -0
  17. package/dist/bundle/chunks/{chunk-3LP543EX.js → chunk-3EDMWQ35.js} +17 -16
  18. package/dist/bundle/chunks/chunk-3HVHETMU.js +18 -0
  19. package/dist/bundle/chunks/{chunk-XMZGB3H4.js → chunk-4HTVBBJD.js} +11 -6
  20. package/dist/bundle/chunks/chunk-4JRER4XK.js +175 -0
  21. package/dist/bundle/chunks/{chunk-FHLLDO7U.js → chunk-4PRNKB6V.js} +5 -5
  22. package/dist/bundle/chunks/chunk-4QAXV5T6.js +49 -0
  23. package/dist/bundle/chunks/{chunk-JCTQQ3DX.js → chunk-4V5VL2BO.js} +1 -1
  24. package/dist/bundle/chunks/chunk-5B25YXF7.js +24 -0
  25. package/dist/bundle/chunks/chunk-5L4PBYC7.js +11 -0
  26. package/dist/bundle/chunks/chunk-66FZJO75.js +5146 -0
  27. package/dist/bundle/chunks/chunk-6P6GJPYB.js +4 -0
  28. package/dist/bundle/chunks/chunk-6PNQYO6A.js +10 -0
  29. package/dist/bundle/chunks/chunk-7NKUVTBL.js +76 -0
  30. package/dist/bundle/chunks/chunk-AEWYICBL.js +89 -0
  31. package/dist/bundle/chunks/chunk-AQ4EXORZ.js +14 -0
  32. package/dist/bundle/chunks/chunk-AZXVJN6E.js +19 -0
  33. package/dist/bundle/chunks/chunk-CRN54O4D.js +24 -0
  34. package/dist/bundle/chunks/chunk-CTU2ECLD.js +7 -0
  35. package/dist/bundle/chunks/{chunk-BQ3TMEWD.js → chunk-EIC7CQX3.js} +4 -3
  36. package/dist/bundle/chunks/chunk-F6ZAYLU2.js +59 -0
  37. package/dist/bundle/chunks/chunk-G4QPSFBF.js +493 -0
  38. package/dist/bundle/chunks/chunk-GME4AWDG.js +23 -0
  39. package/dist/bundle/chunks/{chunk-SFMDIVZ4.js → chunk-GRJUKEE3.js} +43 -30
  40. package/dist/bundle/chunks/chunk-GTILMMUF.js +12 -0
  41. package/dist/bundle/chunks/chunk-GUHNFZ2Q.js +51 -0
  42. package/dist/bundle/chunks/chunk-GY663MNP.js +11 -0
  43. package/dist/bundle/chunks/chunk-HTA325LJ.js +56 -0
  44. package/dist/bundle/chunks/{chunk-5L4JG6PO.js → chunk-I3NDOUHE.js} +8 -7
  45. package/dist/bundle/chunks/chunk-I5E7RQ5V.js +21 -0
  46. package/dist/bundle/chunks/chunk-IWZQ25I3.js +5 -0
  47. package/dist/bundle/chunks/chunk-IYGHKVUG.js +2 -0
  48. package/dist/bundle/chunks/chunk-J57HOSWD.js +21 -0
  49. package/dist/bundle/chunks/chunk-JF7FYXAI.js +288 -0
  50. package/dist/bundle/chunks/chunk-JSZBTGI6.js +10 -0
  51. package/dist/bundle/chunks/chunk-JYWUOKOI.js +1061 -0
  52. package/dist/bundle/chunks/{chunk-DLCBSLHW.js → chunk-KRCX3ZBA.js} +1 -1
  53. package/dist/bundle/chunks/chunk-KTSJYIYC.js +30 -0
  54. package/dist/bundle/chunks/{chunk-K7SDY3VJ.js → chunk-LB4CIS4F.js} +40 -165
  55. package/dist/bundle/chunks/{chunk-NN53K2QQ.js → chunk-LYZ37DJP.js} +2 -14
  56. package/dist/bundle/chunks/chunk-MD7K7RPN.js +20 -0
  57. package/dist/bundle/chunks/chunk-MX4Q4W6H.js +214 -0
  58. package/dist/bundle/chunks/{chunk-6PD3T2EF.js → chunk-N2SNMUD3.js} +1 -1
  59. package/dist/bundle/chunks/chunk-NXA6NEHE.js +54 -0
  60. package/dist/bundle/chunks/chunk-OB332KMV.js +300 -0
  61. package/dist/bundle/chunks/chunk-P6AXBESH.js +1883 -0
  62. package/dist/bundle/chunks/chunk-PPBDDQHP.js +11 -0
  63. package/dist/bundle/chunks/chunk-PWUDFU5V.js +51 -0
  64. package/dist/bundle/chunks/chunk-Q5RKNQ2T.js +73 -0
  65. package/dist/bundle/chunks/chunk-QT6ZHDMP.js +12 -0
  66. package/dist/bundle/chunks/chunk-R5OOX7RW.js +16 -0
  67. package/dist/bundle/chunks/chunk-R6YQR7TZ.js +25 -0
  68. package/dist/bundle/chunks/{chunk-4ZBGTJJM.js → chunk-RNBZBCH2.js} +1 -1
  69. package/dist/bundle/chunks/chunk-RQU722SY.js +1 -0
  70. package/dist/bundle/chunks/{chunk-RGUZULEE.js → chunk-RS6PZK35.js} +71 -72
  71. package/dist/bundle/chunks/{jiti-loader-6P33XTLC.js → chunk-RW7GT7L3.js} +1 -1
  72. package/dist/bundle/chunks/{chunk-PCTLFSQG.js → chunk-SCINMV4X.js} +1 -1
  73. package/dist/bundle/chunks/{chunk-NCC2FAJN.js → chunk-SSRCVJZK.js} +28 -28
  74. package/dist/bundle/chunks/chunk-T5A6T24H.js +93 -0
  75. package/dist/bundle/chunks/chunk-T7BXP46S.js +3367 -0
  76. package/dist/bundle/chunks/chunk-TGDPZCSW.js +9 -0
  77. package/dist/bundle/chunks/{chunk-4J6BGNX2.js → chunk-TWAHPPXN.js} +434 -429
  78. package/dist/bundle/chunks/chunk-UEW6TUSP.js +36 -0
  79. package/dist/bundle/chunks/chunk-UZNIPOGS.js +323 -0
  80. package/dist/bundle/chunks/{chunk-KM4GQ2BU.js → chunk-VFLVWPLZ.js} +5 -6
  81. package/dist/bundle/chunks/chunk-WAPZN4KP.js +74 -0
  82. package/dist/bundle/chunks/chunk-WCFHG6NO.js +16 -0
  83. package/dist/bundle/chunks/chunk-WQ7EJQIT.js +839 -0
  84. package/dist/bundle/chunks/chunk-WQOOJP7U.js +4 -0
  85. package/dist/bundle/chunks/chunk-XHDVDJM7.js +17 -0
  86. package/dist/bundle/chunks/chunk-YPZPCHNV.js +3 -0
  87. package/dist/bundle/chunks/chunk-Z5YLKK3S.js +41 -0
  88. package/dist/bundle/chunks/chunk-ZJUU6WOV.js +2052 -0
  89. package/dist/bundle/chunks/{cli-N7KOVPLB.js → cli-H4LJNE2V.js} +2 -2
  90. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-KRMHG2L3.js → cloudflare-workers-ai-system-one-T5R2RVFQ.js} +1 -1
  91. package/dist/bundle/chunks/codemode-worker.js +2 -0
  92. package/dist/bundle/chunks/compat-ZK2DIW3P.js +15 -0
  93. package/dist/bundle/chunks/dist-EY7YKQHB.js +11 -0
  94. package/dist/bundle/chunks/dist-FMWWM4H7.js +268 -0
  95. package/dist/bundle/chunks/dist-NHQTBDHT.js +1107 -0
  96. package/dist/bundle/chunks/{easter-egg-3d-O2GG2XIG.js → easter-egg-3d-BUEOC3NO.js} +1 -1
  97. package/dist/bundle/chunks/entry-A2CSLKHC.js +323 -0
  98. package/dist/bundle/chunks/entry-AL54ZGYO.js +2 -0
  99. package/dist/bundle/chunks/{execute-LMBACTKA.js → execute-MY5JSEPV.js} +18 -15
  100. package/dist/bundle/chunks/{extract-CXXLVFC5.js → extract-PTGACPGP.js} +3 -3
  101. package/dist/bundle/chunks/flow-implementer-APJFY4YI.js +21 -0
  102. package/dist/bundle/chunks/github-copilot.js +66 -62
  103. package/dist/bundle/chunks/{google-generative-ai-SBL77OXO.js → google-generative-ai-UL7YEQ6J.js} +2 -3
  104. package/dist/bundle/chunks/{google-vertex-NZBNNXMK.js → google-vertex-OTMSPUYH.js} +3 -3
  105. package/dist/bundle/chunks/host-75YAHLDR.js +3 -0
  106. package/dist/bundle/chunks/index.bundle-THL4EUSU.js +390 -0
  107. package/dist/bundle/chunks/inprocess-5NP5VJHZ.js +32 -0
  108. package/dist/bundle/chunks/interactive-mode-IW4PIVAQ.js +5 -0
  109. package/dist/bundle/chunks/jiti-bun-loader-VSLLRCSD.js +3459 -0
  110. package/dist/bundle/chunks/jiti-loader-TMJL6S2D.js +2 -0
  111. package/dist/bundle/chunks/{llama-cpp-classify-PP63BYDF.js → llama-cpp-classify-GJAXULWL.js} +1 -1
  112. package/dist/bundle/chunks/{mistral-conversations-DX4YKJSO.js → mistral-conversations-E72Y6OC3.js} +2 -2
  113. package/dist/bundle/chunks/{node-UGQUSQE6.js → node-ZFIIS5IM.js} +32 -32
  114. package/dist/bundle/chunks/openai-codex-responses-S7CMCAOY.js +101 -0
  115. package/dist/bundle/chunks/openai-completions-2Z57N7PC.js +87 -0
  116. package/dist/bundle/chunks/{openai-decisions-ALJROWBE.js → openai-decisions-JIOJDB4C.js} +1 -1
  117. package/dist/bundle/chunks/openai-responses-5VBZSTHL.js +27 -0
  118. package/dist/bundle/chunks/{openrouter-images-FCJT7C7I.js → openrouter-images-S6O7DBEJ.js} +1 -1
  119. package/dist/bundle/chunks/{pi-messages-NHTQQOPW.js → pi-messages-SMLN5J2W.js} +10 -7
  120. package/dist/bundle/chunks/runtime-OYTWXIUM.js +2 -0
  121. package/dist/bundle/chunks/session-picker-DM6S37IF.js +4 -0
  122. package/dist/bundle/chunks/startup-ui-4GGLWNSU.js +3 -0
  123. package/dist/bundle/chunks/trace-command-YLDYCL55.js +254 -0
  124. package/dist/bundle/chunks/typesafe-system-one-7BEL3H5N.js +3 -0
  125. package/dist/bundle/chunks/virtual-modules-TI3W24YL.js +28 -0
  126. package/dist/bundle/cli-runtime.js +5 -3
  127. package/dist/bundle/flow/agents/orch-implementation-fast.md +4 -4
  128. package/dist/bundle/flow/agents/orch-implementation-strong.md +5 -5
  129. package/dist/bundle/flow/package.json +35 -3
  130. package/dist/bundle/index.js +20 -17
  131. package/dist/bundle/orchestrate/README.md +37 -0
  132. package/dist/bundle/{flow → orchestrate}/agents/orch-qa-agent.md +1 -1
  133. package/dist/bundle/{flow → orchestrate}/agents/orch-worker.md +1 -1
  134. package/dist/bundle/{flow → orchestrate}/agents/orchestrator-lead.md +1 -1
  135. package/dist/bundle/orchestrate/package.json +29 -0
  136. package/dist/bundle/rpc-entry.js +5 -3
  137. package/dist/cli/args.d.ts +6 -0
  138. package/dist/cli/args.d.ts.map +1 -1
  139. package/dist/cli/args.js +69 -2
  140. package/dist/cli/args.js.map +1 -1
  141. package/dist/cli/auth-check.d.ts +3 -2
  142. package/dist/cli/auth-check.d.ts.map +1 -1
  143. package/dist/cli/auth-check.js +4 -3
  144. package/dist/cli/auth-check.js.map +1 -1
  145. package/dist/cli/config-selector.d.ts.map +1 -1
  146. package/dist/cli/config-selector.js +3 -1
  147. package/dist/cli/config-selector.js.map +1 -1
  148. package/dist/cli/file-processor.d.ts +2 -0
  149. package/dist/cli/file-processor.d.ts.map +1 -1
  150. package/dist/cli/file-processor.js +6 -6
  151. package/dist/cli/file-processor.js.map +1 -1
  152. package/dist/cli/metadata-disclosure.d.ts +4 -0
  153. package/dist/cli/metadata-disclosure.d.ts.map +1 -0
  154. package/dist/cli/metadata-disclosure.js +23 -0
  155. package/dist/cli/metadata-disclosure.js.map +1 -0
  156. package/dist/cli/project-trust.d.ts.map +1 -1
  157. package/dist/cli/project-trust.js +4 -1
  158. package/dist/cli/project-trust.js.map +1 -1
  159. package/dist/cli/session-picker.lazy.d.ts +3 -0
  160. package/dist/cli/session-picker.lazy.d.ts.map +1 -0
  161. package/dist/cli/session-picker.lazy.js +3 -0
  162. package/dist/cli/session-picker.lazy.js.map +1 -0
  163. package/dist/cli/startup-ui.d.ts +4 -4
  164. package/dist/cli/startup-ui.d.ts.map +1 -1
  165. package/dist/cli/startup-ui.js +38 -14
  166. package/dist/cli/startup-ui.js.map +1 -1
  167. package/dist/cli/startup-ui.lazy.d.ts +3 -0
  168. package/dist/cli/startup-ui.lazy.d.ts.map +1 -0
  169. package/dist/cli/startup-ui.lazy.js +3 -0
  170. package/dist/cli/startup-ui.lazy.js.map +1 -0
  171. package/dist/cli/trace-command.lazy.d.ts +3 -0
  172. package/dist/cli/trace-command.lazy.d.ts.map +1 -0
  173. package/dist/cli/trace-command.lazy.js +3 -0
  174. package/dist/cli/trace-command.lazy.js.map +1 -0
  175. package/dist/cli.js.map +1 -1
  176. package/dist/coordination/broker/entry.lazy.d.ts +3 -0
  177. package/dist/coordination/broker/entry.lazy.d.ts.map +1 -0
  178. package/dist/coordination/broker/entry.lazy.js +3 -0
  179. package/dist/coordination/broker/entry.lazy.js.map +1 -0
  180. package/dist/core/acceptance-command.d.ts +15 -0
  181. package/dist/core/acceptance-command.d.ts.map +1 -0
  182. package/dist/core/acceptance-command.js +150 -0
  183. package/dist/core/acceptance-command.js.map +1 -0
  184. package/dist/core/acceptance-ledger.d.ts +52 -0
  185. package/dist/core/acceptance-ledger.d.ts.map +1 -0
  186. package/dist/core/acceptance-ledger.js +341 -0
  187. package/dist/core/acceptance-ledger.js.map +1 -0
  188. package/dist/core/admission-types.d.ts +69 -0
  189. package/dist/core/admission-types.js +2 -0
  190. package/dist/core/admission-types.js.map +1 -0
  191. package/dist/core/agent-session-runtime.d.ts +7 -0
  192. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  193. package/dist/core/agent-session-runtime.js +43 -9
  194. package/dist/core/agent-session-runtime.js.map +1 -1
  195. package/dist/core/agent-session-services.d.ts +8 -0
  196. package/dist/core/agent-session-services.d.ts.map +1 -1
  197. package/dist/core/agent-session-services.js +13 -1
  198. package/dist/core/agent-session-services.js.map +1 -1
  199. package/dist/core/agent-session.d.ts +127 -10
  200. package/dist/core/agent-session.d.ts.map +1 -1
  201. package/dist/core/agent-session.js +1390 -145
  202. package/dist/core/agent-session.js.map +1 -1
  203. package/dist/core/anthropic-subscription-usage.d.ts +1 -1
  204. package/dist/core/anthropic-subscription-usage.d.ts.map +1 -1
  205. package/dist/core/anthropic-subscription-usage.js +31 -3
  206. package/dist/core/anthropic-subscription-usage.js.map +1 -1
  207. package/dist/core/auth-storage.d.ts +2 -1
  208. package/dist/core/auth-storage.d.ts.map +1 -1
  209. package/dist/core/auth-storage.js +13 -10
  210. package/dist/core/auth-storage.js.map +1 -1
  211. package/dist/core/auto-session-namer.d.ts.map +1 -1
  212. package/dist/core/auto-session-namer.js +3 -1
  213. package/dist/core/auto-session-namer.js.map +1 -1
  214. package/dist/core/bash-executor.d.ts.map +1 -1
  215. package/dist/core/bash-executor.js +3 -1
  216. package/dist/core/bash-executor.js.map +1 -1
  217. package/dist/core/bug-report-redaction.d.ts +4 -0
  218. package/dist/core/bug-report-redaction.d.ts.map +1 -0
  219. package/dist/core/bug-report-redaction.js +209 -0
  220. package/dist/core/bug-report-redaction.js.map +1 -0
  221. package/dist/core/bug-report.d.ts +26 -6
  222. package/dist/core/bug-report.d.ts.map +1 -1
  223. package/dist/core/bug-report.js +82 -9
  224. package/dist/core/bug-report.js.map +1 -1
  225. package/dist/core/cache-warmer.d.ts.map +1 -1
  226. package/dist/core/cache-warmer.js +5 -0
  227. package/dist/core/cache-warmer.js.map +1 -1
  228. package/dist/core/compaction/compaction.d.ts +6 -0
  229. package/dist/core/compaction/compaction.d.ts.map +1 -1
  230. package/dist/core/compaction/compaction.js +103 -71
  231. package/dist/core/compaction/compaction.js.map +1 -1
  232. package/dist/core/compaction/utils.d.ts.map +1 -1
  233. package/dist/core/compaction/utils.js +2 -1
  234. package/dist/core/compaction/utils.js.map +1 -1
  235. package/dist/core/extensions/jiti-bun-babel.d.ts +4 -0
  236. package/dist/core/extensions/jiti-bun-babel.d.ts.map +1 -0
  237. package/dist/core/extensions/jiti-bun-babel.js +4 -0
  238. package/dist/core/extensions/jiti-bun-babel.js.map +1 -0
  239. package/dist/core/extensions/jiti-bun-loader.d.ts +4 -0
  240. package/dist/core/extensions/jiti-bun-loader.d.ts.map +1 -0
  241. package/dist/core/extensions/jiti-bun-loader.js +13 -0
  242. package/dist/core/extensions/jiti-bun-loader.js.map +1 -0
  243. package/dist/core/extensions/jiti-bun-loader.lazy.d.ts +3 -0
  244. package/dist/core/extensions/jiti-bun-loader.lazy.d.ts.map +1 -0
  245. package/dist/core/extensions/jiti-bun-loader.lazy.js +3 -0
  246. package/dist/core/extensions/jiti-bun-loader.lazy.js.map +1 -0
  247. package/dist/core/extensions/loader.d.ts.map +1 -1
  248. package/dist/core/extensions/loader.js +9 -3
  249. package/dist/core/extensions/loader.js.map +1 -1
  250. package/dist/core/extensions/runner.d.ts.map +1 -1
  251. package/dist/core/extensions/runner.js +4 -0
  252. package/dist/core/extensions/runner.js.map +1 -1
  253. package/dist/core/extensions/types.d.ts +3 -0
  254. package/dist/core/extensions/types.d.ts.map +1 -1
  255. package/dist/core/extensions/types.js.map +1 -1
  256. package/dist/core/flow-implementer.d.ts +25 -0
  257. package/dist/core/flow-implementer.d.ts.map +1 -0
  258. package/dist/core/flow-implementer.js +301 -0
  259. package/dist/core/flow-implementer.js.map +1 -0
  260. package/dist/core/internal-process.d.ts +23 -0
  261. package/dist/core/internal-process.d.ts.map +1 -0
  262. package/dist/core/internal-process.js +88 -0
  263. package/dist/core/internal-process.js.map +1 -0
  264. package/dist/core/keybindings.d.ts +2 -2
  265. package/dist/core/keybindings.js +1 -1
  266. package/dist/core/keybindings.js.map +1 -1
  267. package/dist/core/model-config.d.ts +52 -0
  268. package/dist/core/model-config.d.ts.map +1 -1
  269. package/dist/core/model-config.js +4 -4
  270. package/dist/core/model-config.js.map +1 -1
  271. package/dist/core/model-registry.d.ts +4 -0
  272. package/dist/core/model-registry.d.ts.map +1 -1
  273. package/dist/core/model-registry.js +8 -0
  274. package/dist/core/model-registry.js.map +1 -1
  275. package/dist/core/model-request-admission.d.ts +51 -0
  276. package/dist/core/model-request-admission.d.ts.map +1 -0
  277. package/dist/core/model-request-admission.js +103 -0
  278. package/dist/core/model-request-admission.js.map +1 -0
  279. package/dist/core/model-resolver.d.ts +4 -0
  280. package/dist/core/model-resolver.d.ts.map +1 -1
  281. package/dist/core/model-resolver.js +109 -2
  282. package/dist/core/model-resolver.js.map +1 -1
  283. package/dist/core/model-runtime.d.ts +56 -1
  284. package/dist/core/model-runtime.d.ts.map +1 -1
  285. package/dist/core/model-runtime.js +482 -40
  286. package/dist/core/model-runtime.js.map +1 -1
  287. package/dist/core/model-selection-intent.d.ts +14 -0
  288. package/dist/core/model-selection-intent.d.ts.map +1 -0
  289. package/dist/core/model-selection-intent.js +15 -0
  290. package/dist/core/model-selection-intent.js.map +1 -0
  291. package/dist/core/oauth-account-pool.d.ts +4 -1
  292. package/dist/core/oauth-account-pool.d.ts.map +1 -1
  293. package/dist/core/oauth-account-pool.js +251 -228
  294. package/dist/core/oauth-account-pool.js.map +1 -1
  295. package/dist/core/os-secret-store.d.ts +25 -0
  296. package/dist/core/os-secret-store.d.ts.map +1 -0
  297. package/dist/core/os-secret-store.js +290 -0
  298. package/dist/core/os-secret-store.js.map +1 -0
  299. package/dist/core/output-guard.d.ts.map +1 -1
  300. package/dist/core/output-guard.js +62 -2
  301. package/dist/core/output-guard.js.map +1 -1
  302. package/dist/core/pi-ai-schemas.d.ts +4 -0
  303. package/dist/core/pi-ai-schemas.d.ts.map +1 -1
  304. package/dist/core/private-windows-path.d.ts +4 -0
  305. package/dist/core/private-windows-path.d.ts.map +1 -0
  306. package/dist/core/private-windows-path.js +44 -0
  307. package/dist/core/private-windows-path.js.map +1 -0
  308. package/dist/core/prompt-templates.d.ts.map +1 -1
  309. package/dist/core/prompt-templates.js +18 -2
  310. package/dist/core/prompt-templates.js.map +1 -1
  311. package/dist/core/provider-composer.d.ts.map +1 -1
  312. package/dist/core/provider-composer.js +1 -1
  313. package/dist/core/provider-composer.js.map +1 -1
  314. package/dist/core/resource-loader.d.ts.map +1 -1
  315. package/dist/core/resource-loader.js +6 -2
  316. package/dist/core/resource-loader.js.map +1 -1
  317. package/dist/core/run-outcome.d.ts +40 -0
  318. package/dist/core/run-outcome.d.ts.map +1 -0
  319. package/dist/core/run-outcome.js +91 -0
  320. package/dist/core/run-outcome.js.map +1 -0
  321. package/dist/core/run-preflight.d.ts +5 -0
  322. package/dist/core/run-preflight.d.ts.map +1 -0
  323. package/dist/core/run-preflight.js +96 -0
  324. package/dist/core/run-preflight.js.map +1 -0
  325. package/dist/core/runtime-credentials.d.ts +18 -2
  326. package/dist/core/runtime-credentials.d.ts.map +1 -1
  327. package/dist/core/runtime-credentials.js +65 -9
  328. package/dist/core/runtime-credentials.js.map +1 -1
  329. package/dist/core/sdk.d.ts +19 -3
  330. package/dist/core/sdk.d.ts.map +1 -1
  331. package/dist/core/sdk.js +115 -20
  332. package/dist/core/sdk.js.map +1 -1
  333. package/dist/core/settings-defaults.d.ts +2 -1
  334. package/dist/core/settings-defaults.d.ts.map +1 -1
  335. package/dist/core/settings-defaults.js +2 -1
  336. package/dist/core/settings-defaults.js.map +1 -1
  337. package/dist/core/settings-manager.d.ts +15 -4
  338. package/dist/core/settings-manager.d.ts.map +1 -1
  339. package/dist/core/settings-manager.js +114 -22
  340. package/dist/core/settings-manager.js.map +1 -1
  341. package/dist/core/settings-schema.d.ts +7 -2
  342. package/dist/core/settings-schema.d.ts.map +1 -1
  343. package/dist/core/settings-schema.js +12 -5
  344. package/dist/core/settings-schema.js.map +1 -1
  345. package/dist/core/skills.d.ts.map +1 -1
  346. package/dist/core/skills.js +11 -0
  347. package/dist/core/skills.js.map +1 -1
  348. package/dist/core/system-prompt.d.ts +3 -0
  349. package/dist/core/system-prompt.d.ts.map +1 -1
  350. package/dist/core/system-prompt.js +10 -2
  351. package/dist/core/system-prompt.js.map +1 -1
  352. package/dist/core/tools/bash-jobs.d.ts +109 -0
  353. package/dist/core/tools/bash-jobs.d.ts.map +1 -0
  354. package/dist/core/tools/bash-jobs.js +563 -0
  355. package/dist/core/tools/bash-jobs.js.map +1 -0
  356. package/dist/core/tools/bash.d.ts +68 -6
  357. package/dist/core/tools/bash.d.ts.map +1 -1
  358. package/dist/core/tools/bash.js +350 -37
  359. package/dist/core/tools/bash.js.map +1 -1
  360. package/dist/core/tools/edit-diff.d.ts +11 -1
  361. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  362. package/dist/core/tools/edit-diff.js +89 -20
  363. package/dist/core/tools/edit-diff.js.map +1 -1
  364. package/dist/core/tools/edit.d.ts.map +1 -1
  365. package/dist/core/tools/edit.js +15 -7
  366. package/dist/core/tools/edit.js.map +1 -1
  367. package/dist/core/tools/file-mutation-custody.d.ts +29 -0
  368. package/dist/core/tools/file-mutation-custody.d.ts.map +1 -0
  369. package/dist/core/tools/file-mutation-custody.js +173 -0
  370. package/dist/core/tools/file-mutation-custody.js.map +1 -0
  371. package/dist/core/tools/find.d.ts +6 -0
  372. package/dist/core/tools/find.d.ts.map +1 -1
  373. package/dist/core/tools/find.js +84 -38
  374. package/dist/core/tools/find.js.map +1 -1
  375. package/dist/core/tools/grep.d.ts +8 -2
  376. package/dist/core/tools/grep.d.ts.map +1 -1
  377. package/dist/core/tools/grep.js +121 -77
  378. package/dist/core/tools/grep.js.map +1 -1
  379. package/dist/core/tools/index.d.ts +3 -1
  380. package/dist/core/tools/index.d.ts.map +1 -1
  381. package/dist/core/tools/index.js +12 -0
  382. package/dist/core/tools/index.js.map +1 -1
  383. package/dist/core/tools/jobs.d.ts +24 -0
  384. package/dist/core/tools/jobs.d.ts.map +1 -0
  385. package/dist/core/tools/jobs.js +86 -0
  386. package/dist/core/tools/jobs.js.map +1 -0
  387. package/dist/core/tools/ls.d.ts.map +1 -1
  388. package/dist/core/tools/ls.js +2 -1
  389. package/dist/core/tools/ls.js.map +1 -1
  390. package/dist/core/tools/output-accumulator.d.ts +12 -1
  391. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  392. package/dist/core/tools/output-accumulator.js +88 -8
  393. package/dist/core/tools/output-accumulator.js.map +1 -1
  394. package/dist/core/tools/output-cleanup.d.ts +40 -0
  395. package/dist/core/tools/output-cleanup.d.ts.map +1 -0
  396. package/dist/core/tools/output-cleanup.js +273 -0
  397. package/dist/core/tools/output-cleanup.js.map +1 -0
  398. package/dist/core/tools/powershell.d.ts.map +1 -1
  399. package/dist/core/tools/powershell.js +15 -2
  400. package/dist/core/tools/powershell.js.map +1 -1
  401. package/dist/core/tools/read.d.ts +21 -0
  402. package/dist/core/tools/read.d.ts.map +1 -1
  403. package/dist/core/tools/read.js +162 -29
  404. package/dist/core/tools/read.js.map +1 -1
  405. package/dist/core/tools/renderers/bash.d.ts.map +1 -1
  406. package/dist/core/tools/renderers/bash.js +3 -1
  407. package/dist/core/tools/renderers/bash.js.map +1 -1
  408. package/dist/core/tools/renderers/index.d.ts.map +1 -1
  409. package/dist/core/tools/renderers/index.js +1 -0
  410. package/dist/core/tools/renderers/index.js.map +1 -1
  411. package/dist/core/tools/subagent.d.ts +5 -1
  412. package/dist/core/tools/subagent.d.ts.map +1 -1
  413. package/dist/core/tools/subagent.js +76 -19
  414. package/dist/core/tools/subagent.js.map +1 -1
  415. package/dist/core/tools/truncate.d.ts +4 -0
  416. package/dist/core/tools/truncate.d.ts.map +1 -1
  417. package/dist/core/tools/truncate.js +24 -1
  418. package/dist/core/tools/truncate.js.map +1 -1
  419. package/dist/core/tools/write.d.ts.map +1 -1
  420. package/dist/core/tools/write.js +6 -1
  421. package/dist/core/tools/write.js.map +1 -1
  422. package/dist/core/trace/config.js +3 -3
  423. package/dist/core/trace/config.js.map +1 -1
  424. package/dist/core/trace/redaction.d.ts.map +1 -1
  425. package/dist/core/trace/redaction.js +12 -9
  426. package/dist/core/trace/redaction.js.map +1 -1
  427. package/dist/core/trace-client/credential-store.d.ts +1 -1
  428. package/dist/core/trace-client/credential-store.d.ts.map +1 -1
  429. package/dist/core/trace-client/credential-store.js +20 -3
  430. package/dist/core/trace-client/credential-store.js.map +1 -1
  431. package/dist/core/usage-ledger.d.ts +35 -0
  432. package/dist/core/usage-ledger.d.ts.map +1 -0
  433. package/dist/core/usage-ledger.js +140 -0
  434. package/dist/core/usage-ledger.js.map +1 -0
  435. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  436. package/dist/extensions/codemode/execute.js +24 -15
  437. package/dist/extensions/codemode/execute.js.map +1 -1
  438. package/dist/extensions/codemode/index.d.ts +4 -2
  439. package/dist/extensions/codemode/index.d.ts.map +1 -1
  440. package/dist/extensions/codemode/index.js +8 -4
  441. package/dist/extensions/codemode/index.js.map +1 -1
  442. package/dist/extensions/codemode/tool.d.ts +4 -2
  443. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  444. package/dist/extensions/codemode/tool.js +34 -12
  445. package/dist/extensions/codemode/tool.js.map +1 -1
  446. package/dist/extensions/llama/client.d.ts +2 -0
  447. package/dist/extensions/llama/client.d.ts.map +1 -1
  448. package/dist/extensions/llama/client.js +23 -2
  449. package/dist/extensions/llama/client.js.map +1 -1
  450. package/dist/extensions/llama/ui.d.ts.map +1 -1
  451. package/dist/extensions/llama/ui.js +15 -3
  452. package/dist/extensions/llama/ui.js.map +1 -1
  453. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  454. package/dist/extensions/mcp/runtime.js +3 -2
  455. package/dist/extensions/mcp/runtime.js.map +1 -1
  456. package/dist/extensions/tool-search/tool.d.ts.map +1 -1
  457. package/dist/extensions/tool-search/tool.js +18 -6
  458. package/dist/extensions/tool-search/tool.js.map +1 -1
  459. package/dist/extensions/usage/hcode-overview.d.ts +23 -0
  460. package/dist/extensions/usage/hcode-overview.d.ts.map +1 -0
  461. package/dist/extensions/usage/hcode-overview.js +109 -0
  462. package/dist/extensions/usage/hcode-overview.js.map +1 -0
  463. package/dist/extensions/usage/index.d.ts +5 -0
  464. package/dist/extensions/usage/index.d.ts.map +1 -1
  465. package/dist/extensions/usage/index.js +194 -12
  466. package/dist/extensions/usage/index.js.map +1 -1
  467. package/dist/extensions/usage/overview.d.ts +5 -0
  468. package/dist/extensions/usage/overview.d.ts.map +1 -1
  469. package/dist/extensions/usage/overview.js +21 -1
  470. package/dist/extensions/usage/overview.js.map +1 -1
  471. package/dist/extensions/usage/popup.d.ts +14 -3
  472. package/dist/extensions/usage/popup.d.ts.map +1 -1
  473. package/dist/extensions/usage/popup.js +199 -25
  474. package/dist/extensions/usage/popup.js.map +1 -1
  475. package/dist/humain/adaptive-execution.d.ts +51 -0
  476. package/dist/humain/adaptive-execution.d.ts.map +1 -0
  477. package/dist/humain/adaptive-execution.js +100 -0
  478. package/dist/humain/adaptive-execution.js.map +1 -0
  479. package/dist/humain/adaptive-peer-process.d.ts +44 -0
  480. package/dist/humain/adaptive-peer-process.d.ts.map +1 -0
  481. package/dist/humain/adaptive-peer-process.js +159 -0
  482. package/dist/humain/adaptive-peer-process.js.map +1 -0
  483. package/dist/humain/adaptive-peer-worker.d.ts +3 -0
  484. package/dist/humain/adaptive-peer-worker.d.ts.map +1 -0
  485. package/dist/humain/adaptive-peer-worker.js +122 -0
  486. package/dist/humain/adaptive-peer-worker.js.map +1 -0
  487. package/dist/humain/adaptive-runtime-types.d.ts +621 -0
  488. package/dist/humain/adaptive-runtime-types.d.ts.map +1 -0
  489. package/dist/humain/adaptive-runtime-types.js +3 -0
  490. package/dist/humain/adaptive-runtime-types.js.map +1 -0
  491. package/dist/humain/adaptive-session-host.d.ts +113 -0
  492. package/dist/humain/adaptive-session-host.d.ts.map +1 -0
  493. package/dist/humain/adaptive-session-host.js +1838 -0
  494. package/dist/humain/adaptive-session-host.js.map +1 -0
  495. package/dist/humain/adhd/index.d.ts +2 -2
  496. package/dist/humain/adhd/index.d.ts.map +1 -1
  497. package/dist/humain/adhd/index.js +22 -13
  498. package/dist/humain/adhd/index.js.map +1 -1
  499. package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +162 -49
  500. package/dist/humain/caveman/index.d.ts +1 -1
  501. package/dist/humain/caveman/index.d.ts.map +1 -1
  502. package/dist/humain/caveman/index.js +21 -12
  503. package/dist/humain/caveman/index.js.map +1 -1
  504. package/dist/humain/classify-tool.d.ts +4 -0
  505. package/dist/humain/classify-tool.d.ts.map +1 -0
  506. package/dist/humain/classify-tool.js +50 -0
  507. package/dist/humain/classify-tool.js.map +1 -0
  508. package/dist/humain/flow-command.d.ts +1 -1
  509. package/dist/humain/flow-command.d.ts.map +1 -1
  510. package/dist/humain/flow-command.js +21 -3
  511. package/dist/humain/flow-command.js.map +1 -1
  512. package/dist/humain/flow-loader.d.ts +15 -10
  513. package/dist/humain/flow-loader.d.ts.map +1 -1
  514. package/dist/humain/flow-loader.js +72 -18
  515. package/dist/humain/flow-loader.js.map +1 -1
  516. package/dist/humain/fuse-provider.d.ts +5 -0
  517. package/dist/humain/fuse-provider.d.ts.map +1 -0
  518. package/dist/humain/fuse-provider.js +302 -0
  519. package/dist/humain/fuse-provider.js.map +1 -0
  520. package/dist/humain/gateway/provider.d.ts.map +1 -1
  521. package/dist/humain/gateway/provider.js +2 -0
  522. package/dist/humain/gateway/provider.js.map +1 -1
  523. package/dist/humain/gateway/secret-store.d.ts +3 -7
  524. package/dist/humain/gateway/secret-store.d.ts.map +1 -1
  525. package/dist/humain/gateway/secret-store.js +21 -249
  526. package/dist/humain/gateway/secret-store.js.map +1 -1
  527. package/dist/humain/hcode/account-store.d.ts +92 -0
  528. package/dist/humain/hcode/account-store.d.ts.map +1 -0
  529. package/dist/humain/hcode/account-store.js +720 -0
  530. package/dist/humain/hcode/account-store.js.map +1 -0
  531. package/dist/humain/hcode/account.d.ts +42 -0
  532. package/dist/humain/hcode/account.d.ts.map +1 -0
  533. package/dist/humain/hcode/account.js +552 -0
  534. package/dist/humain/hcode/account.js.map +1 -0
  535. package/dist/humain/hcode/catalog.d.ts +6 -0
  536. package/dist/humain/hcode/catalog.d.ts.map +1 -0
  537. package/dist/humain/hcode/catalog.js +47 -0
  538. package/dist/humain/hcode/catalog.js.map +1 -0
  539. package/dist/humain/hcode/contracts.d.ts +389 -0
  540. package/dist/humain/hcode/contracts.d.ts.map +1 -0
  541. package/dist/humain/hcode/contracts.js +1243 -0
  542. package/dist/humain/hcode/contracts.js.map +1 -0
  543. package/dist/humain/hcode/environment.d.ts +9 -0
  544. package/dist/humain/hcode/environment.d.ts.map +1 -0
  545. package/dist/humain/hcode/environment.js +24 -0
  546. package/dist/humain/hcode/environment.js.map +1 -0
  547. package/dist/humain/hcode/facade.d.ts +54 -0
  548. package/dist/humain/hcode/facade.d.ts.map +1 -0
  549. package/dist/humain/hcode/facade.js +326 -0
  550. package/dist/humain/hcode/facade.js.map +1 -0
  551. package/dist/humain/hcode/http.d.ts +10 -0
  552. package/dist/humain/hcode/http.d.ts.map +1 -0
  553. package/dist/humain/hcode/http.js +119 -0
  554. package/dist/humain/hcode/http.js.map +1 -0
  555. package/dist/humain/hcode/notices.d.ts +15 -0
  556. package/dist/humain/hcode/notices.d.ts.map +1 -0
  557. package/dist/humain/hcode/notices.js +69 -0
  558. package/dist/humain/hcode/notices.js.map +1 -0
  559. package/dist/humain/hcode/ports.d.ts +34 -0
  560. package/dist/humain/hcode/ports.d.ts.map +1 -0
  561. package/dist/humain/hcode/ports.js +2 -0
  562. package/dist/humain/hcode/ports.js.map +1 -0
  563. package/dist/humain/hcode/provider.d.ts +15 -0
  564. package/dist/humain/hcode/provider.d.ts.map +1 -0
  565. package/dist/humain/hcode/provider.js +200 -0
  566. package/dist/humain/hcode/provider.js.map +1 -0
  567. package/dist/humain/hcode/selection.d.ts +16 -0
  568. package/dist/humain/hcode/selection.d.ts.map +1 -0
  569. package/dist/humain/hcode/selection.js +37 -0
  570. package/dist/humain/hcode/selection.js.map +1 -0
  571. package/dist/humain/hcode/transport.d.ts +22 -0
  572. package/dist/humain/hcode/transport.d.ts.map +1 -0
  573. package/dist/humain/hcode/transport.js +368 -0
  574. package/dist/humain/hcode/transport.js.map +1 -0
  575. package/dist/humain/hcode/usage.d.ts +5 -0
  576. package/dist/humain/hcode/usage.d.ts.map +1 -0
  577. package/dist/humain/hcode/usage.js +66 -0
  578. package/dist/humain/hcode/usage.js.map +1 -0
  579. package/dist/humain/hcode/wire.d.ts +16 -0
  580. package/dist/humain/hcode/wire.d.ts.map +1 -0
  581. package/dist/humain/hcode/wire.js +104 -0
  582. package/dist/humain/hcode/wire.js.map +1 -0
  583. package/dist/humain/index.d.ts +1 -3
  584. package/dist/humain/index.d.ts.map +1 -1
  585. package/dist/humain/index.js +8 -60
  586. package/dist/humain/index.js.map +1 -1
  587. package/dist/humain/login-menu.d.ts.map +1 -1
  588. package/dist/humain/login-menu.js +8 -1
  589. package/dist/humain/login-menu.js.map +1 -1
  590. package/dist/humain/metadata/contracts.d.ts +82 -0
  591. package/dist/humain/metadata/contracts.d.ts.map +1 -0
  592. package/dist/humain/metadata/contracts.js +214 -0
  593. package/dist/humain/metadata/contracts.js.map +1 -0
  594. package/dist/humain/metadata/identity.d.ts +10 -0
  595. package/dist/humain/metadata/identity.d.ts.map +1 -0
  596. package/dist/humain/metadata/identity.js +209 -0
  597. package/dist/humain/metadata/identity.js.map +1 -0
  598. package/dist/humain/metadata/index.d.ts +41 -0
  599. package/dist/humain/metadata/index.d.ts.map +1 -0
  600. package/dist/humain/metadata/index.js +100 -0
  601. package/dist/humain/metadata/index.js.map +1 -0
  602. package/dist/humain/metadata/sender.d.ts +20 -0
  603. package/dist/humain/metadata/sender.d.ts.map +1 -0
  604. package/dist/humain/metadata/sender.js +302 -0
  605. package/dist/humain/metadata/sender.js.map +1 -0
  606. package/dist/humain/metadata/version.d.ts +8 -0
  607. package/dist/humain/metadata/version.d.ts.map +1 -0
  608. package/dist/humain/metadata/version.js +38 -0
  609. package/dist/humain/metadata/version.js.map +1 -0
  610. package/dist/humain/node-http.d.ts +2 -0
  611. package/dist/humain/node-http.d.ts.map +1 -1
  612. package/dist/humain/node-http.js +9 -4
  613. package/dist/humain/node-http.js.map +1 -1
  614. package/dist/humain/node-provider.d.ts +2 -0
  615. package/dist/humain/node-provider.d.ts.map +1 -1
  616. package/dist/humain/node-provider.js +39 -8
  617. package/dist/humain/node-provider.js.map +1 -1
  618. package/dist/humain/ponytail/vendor/hooks/ponytail-config.d.ts +1 -1
  619. package/dist/humain/ponytail/vendor/hooks/ponytail-config.d.ts.map +1 -1
  620. package/dist/humain/ponytail/vendor/hooks/ponytail-config.js +4 -4
  621. package/dist/humain/ponytail/vendor/hooks/ponytail-config.js.map +1 -1
  622. package/dist/humain/ponytail/vendor/hooks/ponytail-instructions.d.ts.map +1 -1
  623. package/dist/humain/ponytail/vendor/hooks/ponytail-instructions.js +7 -0
  624. package/dist/humain/ponytail/vendor/hooks/ponytail-instructions.js.map +1 -1
  625. package/dist/humain/ponytail/vendor/pi-extension/index.d.ts.map +1 -1
  626. package/dist/humain/ponytail/vendor/pi-extension/index.js +12 -1
  627. package/dist/humain/ponytail/vendor/pi-extension/index.js.map +1 -1
  628. package/dist/humain/systemone.d.ts +23 -0
  629. package/dist/humain/systemone.d.ts.map +1 -0
  630. package/dist/humain/systemone.js +101 -0
  631. package/dist/humain/systemone.js.map +1 -0
  632. package/dist/humain/trace-capture/flow-producer.d.ts.map +1 -1
  633. package/dist/humain/trace-capture/flow-producer.js +3 -3
  634. package/dist/humain/trace-capture/flow-producer.js.map +1 -1
  635. package/dist/index.d.ts +4 -2
  636. package/dist/index.d.ts.map +1 -1
  637. package/dist/index.js.map +1 -1
  638. package/dist/main.d.ts +1 -0
  639. package/dist/main.d.ts.map +1 -1
  640. package/dist/main.js +292 -183
  641. package/dist/main.js.map +1 -1
  642. package/dist/modes/interactive/bug-report.d.ts.map +1 -1
  643. package/dist/modes/interactive/bug-report.js +82 -36
  644. package/dist/modes/interactive/bug-report.js.map +1 -1
  645. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  646. package/dist/modes/interactive/components/assistant-message.js +8 -5
  647. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  648. package/dist/modes/interactive/components/diff.d.ts.map +1 -1
  649. package/dist/modes/interactive/components/diff.js +11 -5
  650. package/dist/modes/interactive/components/diff.js.map +1 -1
  651. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  652. package/dist/modes/interactive/components/extension-selector.js +9 -1
  653. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  654. package/dist/modes/interactive/components/first-time-setup.d.ts +10 -5
  655. package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
  656. package/dist/modes/interactive/components/first-time-setup.js +55 -29
  657. package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
  658. package/dist/modes/interactive/components/model-selector.d.ts +16 -2
  659. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  660. package/dist/modes/interactive/components/model-selector.js +164 -19
  661. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  662. package/dist/modes/interactive/components/oauth-selector.d.ts +3 -0
  663. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  664. package/dist/modes/interactive/components/oauth-selector.js +19 -2
  665. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  666. package/dist/modes/interactive/components/status-indicator.d.ts +17 -0
  667. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  668. package/dist/modes/interactive/components/status-indicator.js +78 -1
  669. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  670. package/dist/modes/interactive/components/tree-selector.d.ts +1 -0
  671. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  672. package/dist/modes/interactive/components/tree-selector.js +19 -10
  673. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  674. package/dist/modes/interactive/interactive-mode.d.ts +4 -0
  675. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  676. package/dist/modes/interactive/interactive-mode.js +353 -65
  677. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  678. package/dist/modes/interactive/interactive-mode.lazy.d.ts +3 -0
  679. package/dist/modes/interactive/interactive-mode.lazy.d.ts.map +1 -0
  680. package/dist/modes/interactive/interactive-mode.lazy.js +3 -0
  681. package/dist/modes/interactive/interactive-mode.lazy.js.map +1 -0
  682. package/dist/modes/interactive/model-catalog-refresh.d.ts +2 -0
  683. package/dist/modes/interactive/model-catalog-refresh.d.ts.map +1 -1
  684. package/dist/modes/interactive/model-catalog-refresh.js +12 -0
  685. package/dist/modes/interactive/model-catalog-refresh.js.map +1 -1
  686. package/dist/modes/interactive/theme/theme-controller.d.ts +2 -3
  687. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -1
  688. package/dist/modes/interactive/theme/theme-controller.js +4 -5
  689. package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
  690. package/dist/modes/interactive/theme/theme-schema.js +4 -4
  691. package/dist/modes/interactive/theme/theme-schema.js.map +1 -1
  692. package/dist/modes/interactive/theme/theme.d.ts +2 -0
  693. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  694. package/dist/modes/interactive/theme/theme.js +8 -0
  695. package/dist/modes/interactive/theme/theme.js.map +1 -1
  696. package/dist/modes/json-event.d.ts +2 -1
  697. package/dist/modes/json-event.d.ts.map +1 -1
  698. package/dist/modes/json-event.js.map +1 -1
  699. package/dist/modes/print-mode.d.ts +4 -0
  700. package/dist/modes/print-mode.d.ts.map +1 -1
  701. package/dist/modes/print-mode.js +57 -11
  702. package/dist/modes/print-mode.js.map +1 -1
  703. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  704. package/dist/modes/rpc/rpc-mode.js +68 -16
  705. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  706. package/dist/modes/rpc/rpc-types.d.ts +2 -0
  707. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  708. package/dist/modes/rpc/rpc-types.js.map +1 -1
  709. package/dist/utils/changelog.d.ts +1 -1
  710. package/dist/utils/changelog.d.ts.map +1 -1
  711. package/dist/utils/changelog.js +7 -5
  712. package/dist/utils/changelog.js.map +1 -1
  713. package/dist/utils/image-resize.d.ts.map +1 -1
  714. package/dist/utils/image-resize.js +3 -1
  715. package/dist/utils/image-resize.js.map +1 -1
  716. package/dist/utils/lazy-validator.d.ts +5 -0
  717. package/dist/utils/lazy-validator.d.ts.map +1 -0
  718. package/dist/utils/lazy-validator.js +7 -0
  719. package/dist/utils/lazy-validator.js.map +1 -0
  720. package/dist/utils/shell.d.ts +3 -1
  721. package/dist/utils/shell.d.ts.map +1 -1
  722. package/dist/utils/shell.js +9 -4
  723. package/dist/utils/shell.js.map +1 -1
  724. package/docs/cli.md +23 -5
  725. package/docs/codemode.md +21 -1
  726. package/docs/development.md +18 -0
  727. package/docs/docs.json +4 -0
  728. package/docs/extensions.md +4 -0
  729. package/docs/flow.md +115 -16
  730. package/docs/headless-modes.md +61 -0
  731. package/docs/humain-code-forge-architecture.md +65 -13
  732. package/docs/humain-code-forge-component-scorecard.md +10 -1
  733. package/docs/humain-code-forge-flow-walkthrough.md +54 -55
  734. package/docs/humain-code.md +22 -19
  735. package/docs/index.md +1 -0
  736. package/docs/keybindings.md +1 -1
  737. package/docs/models-configuration.md +6 -1
  738. package/docs/models.md +1 -1
  739. package/docs/prompt-templates.md +1 -1
  740. package/docs/providers.md +67 -15
  741. package/docs/run-preflight.md +47 -0
  742. package/docs/sdk.md +39 -1
  743. package/docs/security.md +1 -1
  744. package/docs/settings.md +12 -5
  745. package/docs/skills.md +2 -0
  746. package/docs/slash-commands.md +5 -3
  747. package/docs/usage.md +29 -0
  748. package/examples/extensions/custom-provider-anthropic/package-lock.json +4 -4
  749. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  750. package/examples/tsconfig.json +13 -0
  751. package/npm-shrinkwrap.json +67 -67
  752. package/package.json +25 -19
  753. package/schemas/models.schema.json +30 -0
  754. package/schemas/settings.schema.json +28 -9
  755. package/src/humain/caveman/UPSTREAM.md +19 -3
  756. package/src/humain/caveman/upstream.json +2 -2
  757. package/src/humain/ponytail/UPSTREAM.md +16 -1
  758. package/src/humain/web-access/UPSTREAM.md +10 -0
  759. package/src/humain/web-access/upstream.json +1 -0
  760. package/dist/bundle/chunks/anthropic-messages-MNISFDZA.js +0 -66
  761. package/dist/bundle/chunks/chunk-2HZ2V3HS.js +0 -1985
  762. package/dist/bundle/chunks/chunk-2PZ46FSM.js +0 -6
  763. package/dist/bundle/chunks/chunk-4SQUP6IR.js +0 -88
  764. package/dist/bundle/chunks/chunk-5JSLXC2A.js +0 -3
  765. package/dist/bundle/chunks/chunk-75CQYZ63.js +0 -1336
  766. package/dist/bundle/chunks/chunk-DCPACGLH.js +0 -12267
  767. package/dist/bundle/chunks/chunk-FLVBQ6GS.js +0 -24
  768. package/dist/bundle/chunks/chunk-H7Y4QY7K.js +0 -11
  769. package/dist/bundle/chunks/chunk-JEAM6N22.js +0 -139
  770. package/dist/bundle/chunks/chunk-PS2FJ7M4.js +0 -23
  771. package/dist/bundle/chunks/chunk-TEOMXMW6.js +0 -23
  772. package/dist/bundle/chunks/chunk-WEFEQEIQ.js +0 -28
  773. package/dist/bundle/chunks/chunk-WW4SILXG.js +0 -249
  774. package/dist/bundle/chunks/compat-MXAZPYDN.js +0 -13
  775. package/dist/bundle/chunks/dist-3V7ZSLER.js +0 -3166
  776. package/dist/bundle/chunks/dist-66CW64M2.js +0 -8
  777. package/dist/bundle/chunks/host-SCZ4IKWR.js +0 -2
  778. package/dist/bundle/chunks/openai-codex-responses-LZWBQYVP.js +0 -101
  779. package/dist/bundle/chunks/openai-completions-7NWH423P.js +0 -82
  780. package/dist/bundle/chunks/openai-responses-5YOLHMCF.js +0 -27
  781. package/dist/bundle/chunks/runtime-UVPDE4CX.js +0 -2
  782. package/dist/bundle/chunks/typesafe-system-one-BHJYAZ6E.js +0 -3
  783. package/dist/bundle/chunks/virtual-modules-YQPK57CW.js +0 -23
  784. package/dist/humain/legacy-workflow-tiers.d.ts +0 -3
  785. package/dist/humain/legacy-workflow-tiers.d.ts.map +0 -1
  786. package/dist/humain/legacy-workflow-tiers.js +0 -46
  787. package/dist/humain/legacy-workflow-tiers.js.map +0 -1
  788. /package/dist/bundle/{flow → orchestrate}/agents/orch-architect.md +0 -0
  789. /package/dist/bundle/{flow → orchestrate}/agents/orch-scout.md +0 -0
  790. /package/dist/bundle/{flow → orchestrate}/agents/orch-security-review.md +0 -0
  791. /package/dist/bundle/{flow → orchestrate}/agents/orch-technical-lead.md +0 -0
  792. /package/dist/bundle/{flow → orchestrate}/agents/orch-technical-review.md +0 -0
@@ -14,12 +14,18 @@
14
14
  * Modes use this class and add their own I/O layer on top.
15
15
  */
16
16
  import { AsyncLocalStorage } from "node:async_hooks";
17
+ import { createHash, randomUUID } from "node:crypto";
17
18
  import { readFileSync } from "node:fs";
18
19
  import { basename, dirname } from "node:path";
19
20
  import { runToolCall, } from "@earendil-works/pi-agent-core";
20
- import { contentText, getAssistantRetryDelayMs, getCurrentSystemMessage, getCurrentTools, retryDelayMs, } from "@earendil-works/pi-ai";
21
+ import { contentText, getAssistantRetryDelayMs, getCurrentSystemMessage, getCurrentSystemPrompt, getCurrentTools, getToolStateChanges, normalizeContext, retryDelayMs, } from "@earendil-works/pi-ai";
21
22
  import { clampThinkingLevel, cleanupSessionResources, getSupportedThinkingLevels, isContextOverflow, isRecoverableLength, isRetryableAssistantError, modelsAreEqual, resetApiProviders, streamSimple, } from "@earendil-works/pi-ai/compat";
23
+ import { adaptiveEvidenceLines, adaptiveStatusText, presentAdaptiveChecklist, selectExecutionEngine, } from "../humain/adaptive-execution.js";
22
24
  import { HUMAIN_OBSERVER_EXTENSION_PATHS } from "../humain/bundled-extension-names.js";
25
+ import { loadAdaptiveExecutionHost } from "../humain/flow-loader.js";
26
+ import { HCODE_PROVIDER } from "../humain/hcode/http.js";
27
+ import { assertHcodeSelection, captureHcodeSelection, HCODE_SELECTION_CHANGED_MESSAGE, HCODE_UNSUPPORTED_THINKING_MESSAGE, hcodeSelectionUnavailable, } from "../humain/hcode/selection.js";
28
+ import { validateHcodeImages } from "../humain/hcode/transport.js";
23
29
  import { getNodeAccountFailure, } from "../humain/node-account-failure.js";
24
30
  import { formatNodeSwitchNotice, isNodeFallbackTarget, NODE_FALLBACK_NONE_MESSAGE, nodeFailureExhaustedUntil, } from "../humain/node-account-fallback.js";
25
31
  import { HUMAIN_NODE_BASE_URL_ENV, HUMAIN_NODE_PROVIDER } from "../humain/node-provider.js";
@@ -29,12 +35,14 @@ import { stripFrontmatter } from "../utils/frontmatter.js";
29
35
  import { processImage } from "../utils/image-process.js";
30
36
  import { sleep } from "../utils/sleep.js";
31
37
  import { normalizeToolResultImages } from "../utils/tool-result-images.js";
38
+ import { withReadOnlyAcceptanceCommand } from "./acceptance-command.js";
39
+ import { AcceptanceLedger } from "./acceptance-ledger.js";
32
40
  import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage } from "./auth-guidance.js";
33
41
  import { AUTO_EFFORT_ENTRY_TYPE, getAutoEffortSessionOverride, selectAutoEffort, } from "./auto-effort.js";
34
42
  import { AUTO_NAMER_DEFAULT_MODEL } from "./auto-session-namer.js";
35
43
  import { executeBashWithOperations } from "./bash-executor.js";
36
44
  import { generateBugReportSummary } from "./bug-report.js";
37
- import { SummarizationAbortedError } from "./compaction/compaction.js";
45
+ import { ManagedSummaryStoppedError, SummarizationAbortedError, } from "./compaction/compaction.js";
38
46
  import { calculateContextTokens, collectEntriesForBranchSummary, compact, estimateContextTokens, estimateProjectedContextTokens, estimateTokens, generateBranchSummary, prepareCompaction, shouldCompact, truncateContentForContext, } from "./compaction/index.js";
39
47
  import { DEFAULT_THINKING_LEVEL, THINKING_LEVEL_OPTIONS } from "./defaults.js";
40
48
  import { exportSessionToHtml } from "./export-html/index.js";
@@ -45,17 +53,21 @@ import { createToolNameMatcher, isMcpToolName } from "./mcp-servers.js";
45
53
  import { convertToLlm } from "./messages.js";
46
54
  import { translateBedrockModelId } from "./model-catalog-filter.js";
47
55
  import { ModelRegistry } from "./model-registry.js";
56
+ import { markModelSelectionChosen } from "./model-selection-intent.js";
48
57
  import { NestedToolCallRunner } from "./nested-tool-calls.js";
49
58
  import { getQuotaExhaustionSignal, getUsageLimitSignal, isOAuthAccountUsable, } from "./oauth-account-pool.js";
50
59
  import { expandPromptTemplate } from "./prompt-templates.js";
60
+ import { ModelPreflightFailure } from "./run-outcome.js";
51
61
  import { exportSessionToJsonl } from "./session-export.js";
52
62
  import { getLatestCompactionEntry, SessionManager, } from "./session-manager.js";
53
63
  import { applyToolModifiers, DEFAULT_TOOL_NAMES, } from "./settings-manager.js";
54
64
  import { BUILTIN_PATH_PREFIX, createSyntheticSourceInfo, isSyntheticPath } from "./source-info.js";
55
65
  import { buildSystemPrompt, buildSystemPromptSections, diffSystemPromptSections, normalizeBuildSystemPromptOptions, } from "./system-prompt.js";
56
- import { createLocalBashOperations } from "./tools/bash.js";
57
- import { createAllToolDefinitions } from "./tools/index.js";
66
+ import { createLocalBashOperations, getBashToolOwner } from "./tools/bash.js";
67
+ import { BashJobManager } from "./tools/bash-jobs.js";
68
+ import { createAllToolDefinitions, createJobsToolDefinition } from "./tools/index.js";
58
69
  import { createToolDefinitionFromAgentTool } from "./tools/tool-definition-wrapper.js";
70
+ import { UsageLedger } from "./usage-ledger.js";
59
71
  import { addUsageToTotals, combineUsage, createUsageTotals, getSessionUsage } from "./usage-totals.js";
60
72
  import { findLatestResponse, getBranchSelection, getVirtualModelState, isVirtualModel, VIRTUAL_MODEL_STATE_ENTRY, } from "./virtual-models.js";
61
73
  /**
@@ -88,6 +100,19 @@ export function parseSkillBlock(text) {
88
100
  * grep or find: they may first download ripgrep or fd, which would stay if the early run is dropped.
89
101
  */
90
102
  const EARLY_TOOL_NAMES = new Set(["read", "ls"]);
103
+ const NATIVE_TOOL_METADATA = {
104
+ read: "read",
105
+ write: "write",
106
+ edit: "edit",
107
+ bash: "bash",
108
+ grep: "grep",
109
+ find: "find",
110
+ ls: "ls",
111
+ subagent: "subagent",
112
+ codemode: "codemode",
113
+ web_search: "web_search",
114
+ fetch_content: "fetch_content",
115
+ };
91
116
  /**
92
117
  * Extensions whose `tool_call` handlers let calls of the tools in EARLY_TOOL_NAMES through unchanged. The built-in MCP
93
118
  * extension's handler waits only for MCP servers that the called tool reaches (MCP tools, codemode, tool_search).
@@ -105,6 +130,12 @@ function withoutDeletedHeaders(headers) {
105
130
  ? Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] !== null))
106
131
  : undefined;
107
132
  }
133
+ /** Validate the CLI-independent SDK time-budget boundary before session side effects. */
134
+ export function validateTimeLimitSeconds(seconds) {
135
+ if (seconds !== undefined && (!Number.isSafeInteger(seconds) || seconds <= 0)) {
136
+ throw new Error("timeLimitSeconds must be a positive integer number of seconds");
137
+ }
138
+ }
108
139
  function estimateMessagesTokens(messages) {
109
140
  let tokens = 0;
110
141
  for (const message of messages) {
@@ -141,11 +172,29 @@ const OAUTH_ACCOUNT_POOL_FAILURE_MESSAGE = "Could not read or update the OAuth a
141
172
  // ============================================================================
142
173
  // AgentSession Class
143
174
  // ============================================================================
175
+ /**
176
+ * Index of the model to cycle to, or undefined when there is nothing to switch to.
177
+ * When the current model is not in the list (currentIndex -1), forward picks the first
178
+ * entry and backward the last, so a one-entry list still selects its only model.
179
+ */
180
+ function getNextCycleIndex(currentIndex, length, direction) {
181
+ if (length === 0)
182
+ return undefined;
183
+ if (currentIndex === -1)
184
+ return direction === "forward" ? 0 : length - 1;
185
+ if (length === 1)
186
+ return undefined;
187
+ return direction === "forward" ? (currentIndex + 1) % length : (currentIndex - 1 + length) % length;
188
+ }
144
189
  export class AgentSession {
145
190
  agent;
146
191
  sessionManager;
147
192
  settingsManager;
148
193
  _scopedModels;
194
+ _preparedImageRoute;
195
+ _queuedUserInputs = new WeakSet();
196
+ _disposed = false;
197
+ _modelSelectionRevision = 0;
149
198
  _autoEffortInteractive = false;
150
199
  _autoEffortController;
151
200
  _thinkingSelectionRevision = 0;
@@ -155,8 +204,10 @@ export class AgentSession {
155
204
  _unsubscribeAgent;
156
205
  _eventListeners = [];
157
206
  _isAgentRunActive = false;
207
+ _promptPreflightCount = 0;
158
208
  _agentRunAbortRequested = false;
159
- /** Spans low-level agent runs, post-run recovery, and continuations until session settlement. */
209
+ _providerRunStopped = false;
210
+ /** Spans preparation, low-level agent runs, post-run recovery, and continuations until session settlement. */
160
211
  _agentRunAbortController;
161
212
  _idleWaitPromise;
162
213
  _resolveIdleWait;
@@ -164,6 +215,8 @@ export class AgentSession {
164
215
  _steeringMessages = [];
165
216
  /** Tracks pending follow-up messages for UI display. Removed when delivered. */
166
217
  _followUpMessages = [];
218
+ /** Queued user messages whose images are normalized when they are delivered. */
219
+ _queuedMessagesWithImages = new WeakSet();
167
220
  /** Messages queued to be included with the next user prompt as context ("asides"). */
168
221
  _pendingNextTurnMessages = [];
169
222
  /** Context-only custom messages queued during a run, flushed once the current turn's tool results are in. */
@@ -195,6 +248,9 @@ export class AgentSession {
195
248
  _auxiliaryStreamFunction;
196
249
  /** Wrapped compatibility stream, retained to preserve its strict summarization-auth behavior. */
197
250
  _compatibilityStreamFunction;
251
+ _foregroundTarget;
252
+ _responseTargets = new WeakMap();
253
+ _managedRunStopped = false;
198
254
  /** Account captured for the current assistant response; set at `message_start`. */
199
255
  _oauthServedAccountKey = undefined;
200
256
  /** Account that served the latest response, kept until usage-limit failover handling consumes it. */
@@ -213,6 +269,9 @@ export class AgentSession {
213
269
  _contextEstimate;
214
270
  // Bash execution state
215
271
  _bashAbortControllers = new Set();
272
+ _bashJobs = new BashJobManager({ getRunContext: () => this._adaptiveHost?.runContext });
273
+ // Retain replaced/reloaded owners too: removing a declaration does not stop its effects.
274
+ _bashJobOwners = new Set([this._bashJobs]);
216
275
  _pendingBashMessages = [];
217
276
  // Extension system
218
277
  _extensionRunner;
@@ -223,6 +282,8 @@ export class AgentSession {
223
282
  // Tool results of the last turn: an account failure that already ran tools is not replayed.
224
283
  _lastAssistantToolResults = [];
225
284
  _lastActivityOutcome = "completed";
285
+ _acceptanceLedger;
286
+ _acceptanceInitialUserPending = false;
226
287
  _isBeforeSettle = false;
227
288
  _abortDuringBeforeSettle = false;
228
289
  _isEmittingAgentSettled = false;
@@ -259,6 +320,12 @@ export class AgentSession {
259
320
  _extensionErrorListener;
260
321
  _extensionErrorUnsubscriber;
261
322
  _modelRuntime;
323
+ _runPreflight;
324
+ _usageLedger = UsageLedger.fromEnvironment();
325
+ _usageLedgerRequestContext = this._usageLedger
326
+ ? new AsyncLocalStorage()
327
+ : undefined;
328
+ _usageLedgerCompactionBefore = null;
262
329
  _cacheWarmer;
263
330
  // Tool registry for extension getTools/setTools
264
331
  _toolRegistry = new Map();
@@ -266,6 +333,7 @@ export class AgentSession {
266
333
  _earlyToolExecutes = new WeakSet();
267
334
  /** The session's own `beforeToolCall`: early tool starts stop while anything else is installed. */
268
335
  _installedBeforeToolCall;
336
+ _installedToolResultObserver;
269
337
  /** Created on the first `ctx.executeTool()` call. */
270
338
  _nestedToolCalls;
271
339
  /** Declared tools whose declarations requests leave out, from `prepareLoadout` hooks. */
@@ -273,17 +341,84 @@ export class AgentSession {
273
341
  _toolDefinitions = new Map();
274
342
  _toolPromptSnippets = new Map();
275
343
  _toolPromptGuidelines = new Map();
344
+ _executionEngineOption;
345
+ _adaptiveOptions;
346
+ _restoredExecutionEngine;
347
+ _adaptiveRecoveryRead = false;
348
+ _runExecutionEngine;
349
+ _adaptiveHost;
350
+ _adaptivePeerTransformContext;
351
+ _adaptivePeerPrepareRequest;
352
+ _adaptiveCompletion;
353
+ _adaptiveSeal;
354
+ _adaptiveLegacyJobs;
355
+ _adaptiveAdmissionScope = new AsyncLocalStorage();
356
+ /** Selection is immutable while a run is owned; saved legacy context is never promoted. */
357
+ get executionEngine() {
358
+ return (this._runExecutionEngine ??
359
+ (this._restoredExecutionEngine === "adaptive-v2" && this._adaptiveRecoveryRead
360
+ ? undefined
361
+ : this._restoredExecutionEngine) ??
362
+ this._executionEngineOption ??
363
+ this.settingsManager.getExecutionEngine());
364
+ }
365
+ /** Evidence-bound local result, shared unchanged by SDK, print, JSON and RPC. */
366
+ get adaptiveCompletion() {
367
+ return this._adaptiveCompletion;
368
+ }
369
+ _includeHarnessDocs;
276
370
  _baseSystemPromptOptions;
277
371
  /** Prompt options after before_agent_start mutations for the active run. */
278
372
  _runSystemPromptOptions;
373
+ _timeLimit;
279
374
  constructor(config) {
375
+ if (config.executionEngine !== undefined)
376
+ selectExecutionEngine(config.executionEngine);
377
+ else
378
+ config.settingsManager.getExecutionEngine();
379
+ if (config.adaptiveExecution !== undefined &&
380
+ (!config.adaptiveExecution ||
381
+ typeof config.adaptiveExecution !== "object" ||
382
+ Array.isArray(config.adaptiveExecution)))
383
+ throw new Error("Invalid adaptive execution options");
384
+ this._executionEngineOption = config.executionEngine;
385
+ this._adaptiveOptions =
386
+ config.adaptiveExecution === undefined ? undefined : structuredClone(config.adaptiveExecution);
387
+ const saved = config.sessionManager.getBranch();
388
+ const selection = saved.findLast((entry) => entry.type === "custom" && entry.customType === "execution-engine");
389
+ if (selection?.type === "custom") {
390
+ if (!selection.data ||
391
+ typeof selection.data !== "object" ||
392
+ !("version" in selection.data) ||
393
+ selection.data.version !== 1 ||
394
+ !("engine" in selection.data))
395
+ throw new Error("Invalid persisted execution engine selection");
396
+ this._restoredExecutionEngine = selectExecutionEngine(selection.data.engine);
397
+ }
398
+ else if (saved.some((entry) => entry.type === "custom" && entry.customType === "adaptive-engine-snapshot"))
399
+ this._restoredExecutionEngine = "adaptive-v2";
400
+ else if (saved.some((entry) => entry.type === "message"))
401
+ this._restoredExecutionEngine = "legacy";
402
+ validateTimeLimitSeconds(config.timeLimitSeconds);
403
+ if (config.timeLimitSeconds !== undefined) {
404
+ this._timeLimit = {
405
+ seconds: config.timeLimitSeconds,
406
+ startedAt: Date.now(),
407
+ announced: false,
408
+ reminders: new Set(),
409
+ };
410
+ }
280
411
  this.agent = config.agent;
412
+ // Capture caller/SDK policy before primary-only projection, compaction and forced-prompt wrappers.
413
+ this._adaptivePeerTransformContext = config.agent.transformContext;
414
+ this._adaptivePeerPrepareRequest = config.agent.prepareRequest;
281
415
  this.sessionManager = config.sessionManager;
282
416
  this.settingsManager = config.settingsManager;
283
417
  this._scopedModels = config.scopedModels ?? [];
284
418
  this._resourceLoader = config.resourceLoader;
285
419
  this._customTools = config.customTools ?? [];
286
420
  this._cwd = config.cwd;
421
+ this._includeHarnessDocs = config.includeHarnessDocs ?? false;
287
422
  this._modelRuntime = config.modelRuntime;
288
423
  this._unregisterRequestOwner = this._modelRuntime.addOwnerObserver(this._requestObserver);
289
424
  this._cacheWarmer = config.cacheWarmer;
@@ -308,7 +443,30 @@ export class AgentSession {
308
443
  this._installAgentToolHooks();
309
444
  this._installAgentNextTurnRefresh();
310
445
  this._installAgentRequestProjection();
446
+ this._installQueuedInputValidation();
311
447
  this._installOAuthRequestAttribution();
448
+ if (this._usageLedgerRequestContext) {
449
+ const streamFunction = this.agent.streamFunction;
450
+ const requestContext = this._usageLedgerRequestContext;
451
+ const ledgerStream = (model, context, options) => {
452
+ const system = getCurrentSystemMessage(context.messages);
453
+ return requestContext.run({
454
+ // Stream input follows prepareRequest, context handlers and forced-prompt projection.
455
+ // Historical provider usage cannot describe those transformed messages or summaries.
456
+ projectedContextTokens: (system ? estimateTokens(system) : 0) +
457
+ estimateMessagesTokens(context.messages.filter((message) => message.role !== "system")),
458
+ systemPrompt: getCurrentSystemPrompt(context.messages),
459
+ extensionPaths: this._resourceLoader.getExtensions().extensions.map((extension) => extension.path),
460
+ sessionRetrySequence: this._retryAttempt,
461
+ }, () => streamFunction(model, context, options));
462
+ };
463
+ const runtime = runtimeStreamFunctions.get(streamFunction);
464
+ if (runtime)
465
+ runtimeStreamFunctions.set(ledgerStream, runtime);
466
+ if (this._compatibilityStreamFunction === streamFunction)
467
+ this._compatibilityStreamFunction = ledgerStream;
468
+ this.agent.streamFunction = ledgerStream;
469
+ }
312
470
  this._installAgentBoundaryHooks();
313
471
  this._installHiddenDeclarationsProjection();
314
472
  this._installAgentForcedPromptProjection();
@@ -347,14 +505,24 @@ export class AgentSession {
347
505
  get modelRuntime() {
348
506
  return this._modelRuntime;
349
507
  }
508
+ /** Set an optional gate awaited after extension model selection and before run execution. */
509
+ setRunPreflight(callback) {
510
+ this._runPreflight = callback;
511
+ }
350
512
  _installOAuthRequestAttribution() {
351
513
  const streamFunction = this.agent.streamFunction;
352
514
  const attributedStream = (model, context, options) => {
515
+ if (this._adaptiveHost)
516
+ options = {
517
+ ...options,
518
+ maxTokens: Math.min(options?.maxTokens ?? this._adaptiveHost.maxOutputTokens, this._adaptiveHost.maxOutputTokens),
519
+ };
353
520
  // Auxiliary requests share this transport, but only the agent loop's request owns the
354
521
  // assistant message_start event. A concurrent summary must not replace that identity.
355
522
  if (this._auxiliaryRequest.getStore() || !options?.signal || options.signal !== this.agent.signal) {
356
523
  return streamFunction(model, context, options);
357
524
  }
525
+ this._captureForegroundTarget(model);
358
526
  const pool = this._modelRuntime.oauthAccounts;
359
527
  // Custom/compatibility streams have already resolved their key before this call. Match that
360
528
  // exact credential, not whichever account happens to be active when the first chunk arrives.
@@ -368,7 +536,12 @@ export class AgentSession {
368
536
  this._oauthRequestAccount = account;
369
537
  const requestOptions = {
370
538
  ...options,
539
+ onPhysicalTarget: (target) => {
540
+ this._captureForegroundTarget(target);
541
+ options.onPhysicalTarget?.(target);
542
+ },
371
543
  onOAuthAccount: (provider, key) => {
544
+ options.onOAuthAccount?.(provider, key);
372
545
  // ModelRuntime resolves OAuth lazily (including refresh). Its credential identity is
373
546
  // authoritative and belongs only to this request, not summaries or background work.
374
547
  if (provider === account.provider)
@@ -388,6 +561,18 @@ export class AgentSession {
388
561
  // Scope the exclusion to their async request instead of a mutable session-wide flag.
389
562
  this._auxiliaryStreamFunction = (model, context, options) => this._auxiliaryRequest.run(true, () => this.agent.streamFunction(model, context, options));
390
563
  }
564
+ _captureForegroundTarget(model) {
565
+ this._foregroundTarget = {
566
+ kind: model.provider === HCODE_PROVIDER && this._modelRuntime.getPhysicalModel(model.provider, model.id) === model
567
+ ? "managed"
568
+ : "ordinary",
569
+ };
570
+ }
571
+ _managedRecoveryStopped(message) {
572
+ const fact = this._responseTargets.get(message);
573
+ return (fact?.target.kind === "managed" &&
574
+ (fact.stopped || (message.stopReason !== "stop" && message.stopReason !== "toolUse")));
575
+ }
391
576
  async _getRequiredRequestAuth(model, signal) {
392
577
  let result;
393
578
  try {
@@ -417,15 +602,18 @@ export class AgentSession {
417
602
  }
418
603
  throw new Error(formatNoApiKeyFoundMessage(model.provider));
419
604
  }
420
- async _getSummarizationRequestAuth(selectedModel, signal) {
605
+ async _getSummarizationRequestAuth(selectedModel, signal, messages = this.messages) {
421
606
  // Route a virtual model first: summaries size their input and output from the model they get.
422
607
  const { model, thinkingLevel } = isVirtualModel(selectedModel)
423
- ? await this._modelRuntime.resolveModel(selectedModel, convertToLlm(this.messages), {
608
+ ? await this._modelRuntime.resolveModel(selectedModel, convertToLlm([...messages]), {
424
609
  reason: "direct",
425
610
  thinkingLevel: this.thinkingLevel,
426
611
  signal,
427
612
  })
428
613
  : { model: selectedModel, thinkingLevel: this.thinkingLevel };
614
+ // The native provider delegates auth at dispatch; eager resolution would clone its canonical model.
615
+ if (model.provider === HCODE_PROVIDER)
616
+ return { model, thinkingLevel };
429
617
  if (this.agent.streamFunction === streamSimple ||
430
618
  this.agent.streamFunction === this._compatibilityStreamFunction) {
431
619
  return { ...(await this._getRequiredRequestAuth(model, signal)), thinkingLevel };
@@ -474,19 +662,25 @@ export class AgentSession {
474
662
  return this._modelRuntime.getPhysicalModel(message.provider, message.model);
475
663
  return model?.provider === message.provider && model.id === message.model ? model : undefined;
476
664
  }
665
+ /** Record the live model and thinking level on the current branch, so a resume restores them. */
666
+ _recordSelection() {
667
+ const branch = this.sessionManager.getBranch();
668
+ this._recordModelSelection(branch);
669
+ this._recordThinkingLevel(branch);
670
+ }
477
671
  /**
478
- * Record the selection on the current branch when the branch implies another one, so a resume
479
- * restores it. Tree navigation can leave the latest `model_change` on another branch; responses
480
- * cannot record a virtual selection because they name physical models. Responses do record a
481
- * physical selection unless the branch holds a virtual one; checking a physical selection against
482
- * responses would record it on every prompt while `prepareRequest` redirects to another model.
672
+ * Record the model on the current branch when the branch implies another one. Tree navigation
673
+ * can leave the latest `model_change` on another branch; responses cannot record a virtual
674
+ * selection because they name physical models. Responses do record a physical selection unless
675
+ * the branch holds a virtual one; checking a physical selection against responses would record
676
+ * it on every prompt while `prepareRequest` redirects to another model.
483
677
  */
484
- _recordSelection() {
678
+ _recordModelSelection(branch) {
485
679
  const model = this.model;
486
680
  if (!model)
487
681
  return;
488
682
  const getModel = (provider, modelId) => this._modelRuntime.getModel(provider, modelId);
489
- const recorded = getBranchSelection(this.sessionManager.getBranch(), getModel);
683
+ const recorded = getBranchSelection(branch, getModel);
490
684
  if (!recorded || (recorded.provider === model.provider && recorded.modelId === model.id))
491
685
  return;
492
686
  const recordedModel = getModel(recorded.provider, recorded.modelId);
@@ -494,6 +688,25 @@ export class AgentSession {
494
688
  return;
495
689
  this.sessionManager.appendModelChange(model.provider, model.id);
496
690
  }
691
+ /**
692
+ * Record the thinking level on the current branch when the branch implies another one (#11451).
693
+ * Tree navigation can leave the latest `thinking_level_change` on another branch. The recorded
694
+ * level is compared after clamping to the current model, so a level clamped on resume (e.g.
695
+ * `xhigh` running as `high`) is not recorded over the requested one.
696
+ */
697
+ _recordThinkingLevel(branch) {
698
+ const recorded = branch.findLast((entry) => entry.type === "thinking_level_change");
699
+ if (!recorded)
700
+ return;
701
+ const recordedLevel = recorded.thinkingLevel;
702
+ const availableLevels = this.getAvailableThinkingLevels();
703
+ const effective = availableLevels.includes(recordedLevel)
704
+ ? recordedLevel
705
+ : this._clampThinkingLevel(recordedLevel, availableLevels);
706
+ if (effective === this.thinkingLevel)
707
+ return;
708
+ this.sessionManager.appendThinkingLevelChange(this.thinkingLevel);
709
+ }
497
710
  /** The model whose limits apply to the conversation. */
498
711
  _limitsModel() {
499
712
  return this.routedModel?.model ?? this.model;
@@ -512,8 +725,12 @@ export class AgentSession {
512
725
  this.agent.afterToolCall = (context) => this._afterToolCall(context);
513
726
  const observer = (observation) => this._observeToolResult(observation);
514
727
  this.agent.onToolResult = observer;
728
+ this._installedToolResultObserver = observer;
515
729
  // Caller replacements observe independently of extension interest.
516
- this.agent.shouldObserveToolResult = (callback) => callback !== observer || this._extensionRunner.hasHandlers("tool_result_observed");
730
+ this.agent.shouldObserveToolResult = (callback) => callback !== observer ||
731
+ this._usageLedger !== undefined ||
732
+ this._acceptanceLedger?.needsToolEvidence === true ||
733
+ this._extensionRunner.hasHandlers("tool_result_observed");
517
734
  this.agent.earlyToolExecution = (_toolCall, tool) => this._earlyToolExecution(tool);
518
735
  }
519
736
  /**
@@ -545,23 +762,36 @@ export class AgentSession {
545
762
  * binding follows async context, so concurrent sessions sharing one runtime never cross.
546
763
  */
547
764
  _observeRequests(purpose, fn) {
548
- return this._modelRuntime.observeRequests(this._requestObserver, purpose, fn);
765
+ return this._withAdaptiveAdmission(() => this._modelRuntime.observeRequests(this._requestObserver, purpose, fn));
766
+ }
767
+ _withAdaptiveAdmission(fn) {
768
+ if (!this._adaptiveHost || this._adaptiveAdmissionScope.getStore())
769
+ return fn();
770
+ return this._adaptiveAdmissionScope.run(true, () => this._adaptiveHost.withActAdmission(fn));
549
771
  }
550
772
  _unregisterRequestOwner;
551
773
  _requestObserver = {
552
774
  onRequest: async (observation, purpose) => {
775
+ this._usageLedger?.request(this.sessionId, observation, purpose, this._usageLedgerRequestContext?.getStore() ?? {
776
+ projectedContextTokens: null,
777
+ systemPrompt: null,
778
+ extensionPaths: this._resourceLoader.getExtensions().extensions.map((extension) => extension.path),
779
+ sessionRetrySequence: this._retryAttempt,
780
+ });
553
781
  const runner = this._extensionRunner;
554
782
  if (!runner.hasHandlers("model_request_observed"))
555
783
  return;
556
784
  await runner.emit({ type: "model_request_observed", purpose, observation });
557
785
  },
558
786
  onResponse: async (response) => {
787
+ this._usageLedger?.response(this.sessionId, response, this._usageLedgerRequestContext?.getStore()?.sessionRetrySequence ?? this._retryAttempt);
559
788
  const runner = this._extensionRunner;
560
789
  if (!runner.hasHandlers("model_response_observed"))
561
790
  return;
562
791
  await runner.emit({ ...response, type: "model_response_observed" });
563
792
  },
564
793
  onUnattributed: async () => {
794
+ this._usageLedger?.unattributed(this.sessionId);
565
795
  const runner = this._extensionRunner;
566
796
  if (!runner.hasHandlers("model_request_unattributed"))
567
797
  return;
@@ -570,13 +800,32 @@ export class AgentSession {
570
800
  };
571
801
  /** Read-only `tool_result_observed` delivery; `parentToolCallId` is set for nested calls. */
572
802
  async _observeToolResult(observation) {
803
+ this._usageLedger?.toolResult(this.sessionId, observation);
804
+ this._acceptanceLedger?.observe(observation);
573
805
  const runner = this._extensionRunner;
574
806
  if (!runner.hasHandlers("tool_result_observed"))
575
807
  return;
576
808
  await runner.emitToolResultObserved({ ...observation, type: "tool_result_observed" });
577
809
  }
578
810
  /** `tool_call` handlers. `parentToolCallId` is set for calls another tool made. */
579
- async _beforeToolCall({ toolCall, args }, parentToolCallId) {
811
+ async _beforeToolCall(context, parentToolCallId) {
812
+ const { toolCall, args } = context;
813
+ if (this._adaptiveHost)
814
+ await this._adaptiveHost.beforeTool(toolCall.name, args, !this._baseToolsOverride && this._toolDefinitions.get(toolCall.name)?.sourceInfo.source === "builtin"
815
+ ? "native"
816
+ : "unqualified");
817
+ const result = await this._authorizeToolCall(context, parentToolCallId);
818
+ if (this._adaptiveHost) {
819
+ this._adaptiveHost.authorizeToolResult(result);
820
+ // Extensions may mutate event.input in place; only the final arguments can grant custody.
821
+ await this._adaptiveHost.beforeTool(toolCall.name, args, !this._baseToolsOverride && this._toolDefinitions.get(toolCall.name)?.sourceInfo.source === "builtin"
822
+ ? "native"
823
+ : "unqualified");
824
+ }
825
+ return result;
826
+ }
827
+ async _authorizeToolCall({ toolCall, args }, parentToolCallId) {
828
+ this._acceptanceLedger?.beginToolCall(toolCall.id, toolCall.name, args);
580
829
  const runner = this._extensionRunner;
581
830
  if (!runner.hasHandlers("tool_call")) {
582
831
  return undefined;
@@ -617,10 +866,13 @@ export class AgentSession {
617
866
  const content = hookResult?.content ?? result.content ?? [];
618
867
  // Runs after the extension hook so images injected or replaced by extensions are normalized too.
619
868
  const resizeOptions = this._limitsModel()?.inputLimits?.images?.resize;
620
- const normalizedContent = await normalizeToolResultImages(content, {
621
- autoResizeImages: this.settingsManager.getImageAutoResize(),
622
- ...(resizeOptions ? { resizeOptions } : {}),
623
- });
869
+ const model = this._limitsModel();
870
+ const normalizedContent = model?.provider === HCODE_PROVIDER || (this.model && isVirtualModel(this.model))
871
+ ? content
872
+ : await normalizeToolResultImages(content, {
873
+ autoResizeImages: this.settingsManager.getImageAutoResize(),
874
+ ...(resizeOptions ? { resizeOptions } : {}),
875
+ });
624
876
  if (!hookResult && normalizedContent === content) {
625
877
  return undefined;
626
878
  }
@@ -657,7 +909,9 @@ export class AgentSession {
657
909
  beforeToolCall: (context) => this._beforeToolCall(context, parentId),
658
910
  afterToolCall: (context) => this._afterToolCall(context, parentId),
659
911
  onToolResult: (observation) => this._observeToolResult(observation),
660
- shouldObserveToolResult: () => this._extensionRunner.hasHandlers("tool_result_observed"),
912
+ shouldObserveToolResult: () => this._usageLedger !== undefined ||
913
+ this._acceptanceLedger?.needsToolEvidence === true ||
914
+ this._extensionRunner.hasHandlers("tool_result_observed"),
661
915
  parentToolCallId: parentId,
662
916
  signal,
663
917
  onUpdate,
@@ -707,6 +961,8 @@ export class AgentSession {
707
961
  return this._contextEstimate;
708
962
  }
709
963
  async _compactBeforeNextAssistantResponse(context) {
964
+ if (this._managedRunStopped)
965
+ throw new Error("HUMAIN Code request stopped. No automatic resend was sent.");
710
966
  const projection = this.sessionManager.buildSessionProjection();
711
967
  // A virtual selection is checked in prepareRequest, against the model the request is routed to.
712
968
  const model = this.model;
@@ -780,12 +1036,48 @@ export class AgentSession {
780
1036
  this._emit({ type: "auto_effort_state_changed", selecting: false, failure });
781
1037
  }
782
1038
  }
1039
+ _appendTimeLimitContext() {
1040
+ const limit = this._timeLimit;
1041
+ if (!limit)
1042
+ return;
1043
+ const elapsed = (Date.now() - limit.startedAt) / 1000;
1044
+ const texts = [];
1045
+ if (!limit.announced) {
1046
+ texts.push(`Run time limit: ${limit.seconds / 60} minutes from session start. Finish the task and give your final answer before the limit, leaving time to verify your work.`);
1047
+ limit.announced = true;
1048
+ }
1049
+ if (elapsed < limit.seconds) {
1050
+ for (const threshold of [0.5, 0.85]) {
1051
+ if (elapsed < limit.seconds * threshold || limit.reminders.has(threshold))
1052
+ continue;
1053
+ const remaining = Math.max(0, Math.ceil(limit.seconds - elapsed));
1054
+ const minutes = Math.floor(remaining / 60);
1055
+ texts.push(`Run time limit: ${minutes} minute${minutes === 1 ? "" : "s"} ${remaining % 60} seconds remaining.${threshold === 0.85 ? " Stop exploring, make sure your deliverable is in place, and give your final answer." : " Leave time to verify and give your final answer."}`);
1056
+ limit.reminders.add(threshold);
1057
+ }
1058
+ }
1059
+ for (const content of texts) {
1060
+ // Append at the request boundary, after tool results, without forcing another turn.
1061
+ this._appendCustomMessage({
1062
+ role: "custom",
1063
+ customType: "time-limit",
1064
+ content,
1065
+ display: false,
1066
+ timestamp: Date.now(),
1067
+ });
1068
+ }
1069
+ }
783
1070
  _installAgentRequestProjection() {
784
1071
  const previousPrepareRequest = this.agent.prepareRequest;
785
1072
  this.agent.prepareRequest = async (request, signal) => {
1073
+ if (this._managedRunStopped)
1074
+ throw new Error("HUMAIN Code request stopped. No automatic resend was sent.");
1075
+ if (!isVirtualModel(this.agent.state.model))
1076
+ this._captureForegroundTarget(this.agent.state.model);
786
1077
  const failed = this._failedResponse;
787
1078
  this._failedResponse = undefined;
788
1079
  const prepare = async () => {
1080
+ this._appendTimeLimitContext();
789
1081
  const projection = this.sessionManager.buildSessionProjection();
790
1082
  const canonicalContext = {
791
1083
  ...request.context,
@@ -812,8 +1104,11 @@ export class AgentSession {
812
1104
  await this._prepareAutoEffort(projection, model, signal);
813
1105
  signal?.throwIfAborted();
814
1106
  const effectiveModel = this.agent.state.model === selectedModel ? model : this.agent.state.model;
1107
+ this._captureForegroundTarget(effectiveModel);
815
1108
  await this._prepareAccountRequest(effectiveModel.provider, signal);
816
1109
  const effectiveThinking = revision === this._thinkingSelectionRevision ? thinkingLevel : this.agent.state.thinkingLevel;
1110
+ await this._validateManagedInput(effectiveModel, context.messages, effectiveThinking);
1111
+ context = await this._normalizeOrdinaryToolImages(context, effectiveModel);
817
1112
  return {
818
1113
  ...previous,
819
1114
  context,
@@ -829,13 +1124,18 @@ export class AgentSession {
829
1124
  const lastResponse = context.messages.findLastIndex((message) => message.role === "assistant");
830
1125
  const userTurn = context.messages.slice(lastResponse + 1).some((message) => message.role === "user");
831
1126
  const state = getVirtualModelState(this.sessionManager.getBranch(), model.provider, model.id);
832
- const route = await this._modelRuntime.resolveModel(model, convertToLlm(context.messages), {
833
- reason: failed ? "retry" : userTurn ? "user" : "continuation",
834
- thinkingLevel,
835
- signal,
836
- failed,
837
- state,
838
- });
1127
+ const prepared = this._preparedImageRoute;
1128
+ this._preparedImageRoute = undefined;
1129
+ const route = prepared?.selection === model && prepared.thinkingLevel === thinkingLevel && prepared.state === state
1130
+ ? prepared.route
1131
+ : await this._modelRuntime.resolveModel(model, convertToLlm(context.messages), {
1132
+ reason: failed ? "retry" : userTurn ? "user" : "continuation",
1133
+ thinkingLevel,
1134
+ signal,
1135
+ failed,
1136
+ state,
1137
+ });
1138
+ this._captureForegroundTarget(route.model);
839
1139
  if (route.state !== undefined && route.state !== state) {
840
1140
  const data = { provider: model.provider, modelId: model.id, state: route.state };
841
1141
  const entry = this.sessionManager.getEntry(this.sessionManager.appendCustomEntry(VIRTUAL_MODEL_STATE_ENTRY, data));
@@ -850,6 +1150,8 @@ export class AgentSession {
850
1150
  ({ previous, context } = await prepare());
851
1151
  }
852
1152
  await this._prepareAccountRequest(route.model.provider, signal);
1153
+ await this._validateManagedInput(route.model, context.messages, route.thinkingLevel);
1154
+ context = await this._normalizeOrdinaryToolImages(context, route.model);
853
1155
  return { ...previous, context, model: route.model, thinkingLevel: route.thinkingLevel };
854
1156
  };
855
1157
  }
@@ -893,6 +1195,10 @@ export class AgentSession {
893
1195
  this._boundaryDispatchedMessages.add(turn.message);
894
1196
  const extensionContinue = await this._dispatchTurnEndBoundary(turn.message, turn.toolResults);
895
1197
  const previousDecision = await previousFinishTurn?.(turn, signal);
1198
+ if (this._managedRunStopped || this._managedRecoveryStopped(turn.message)) {
1199
+ this._managedRunStopped = true;
1200
+ return { action: "end" };
1201
+ }
896
1202
  if (previousDecision?.action === "end")
897
1203
  return previousDecision;
898
1204
  if (extensionContinue || previousDecision?.action === "continue")
@@ -1016,6 +1322,21 @@ export class AgentSession {
1016
1322
  }
1017
1323
  /** Emit an event to all listeners */
1018
1324
  _emit(event) {
1325
+ if (this._usageLedger && (event.type === "compaction_start" || event.type === "compaction_end")) {
1326
+ if (event.type === "compaction_start")
1327
+ this._usageLedgerCompactionBefore = this._contextTokenEstimate().tokens;
1328
+ this._usageLedger.compaction(this.sessionId, {
1329
+ event: event.type,
1330
+ reason: event.reason,
1331
+ beforeContextTokens: event.type === "compaction_end"
1332
+ ? (event.result?.tokensBefore ?? this._usageLedgerCompactionBefore)
1333
+ : this._usageLedgerCompactionBefore,
1334
+ afterContextTokens: event.type === "compaction_end" ? (event.result?.estimatedTokensAfter ?? null) : null,
1335
+ ...(event.type === "compaction_end" ? { aborted: event.aborted, willRetry: event.willRetry } : {}),
1336
+ });
1337
+ if (event.type === "compaction_end")
1338
+ this._usageLedgerCompactionBefore = null;
1339
+ }
1019
1340
  for (const l of this._eventListeners) {
1020
1341
  l(event);
1021
1342
  }
@@ -1051,13 +1372,18 @@ export class AgentSession {
1051
1372
  }
1052
1373
  async _emitAgentSettled() {
1053
1374
  this._withdrawControlContinuations();
1054
- this._cacheWarmer?.onAgentSettled();
1375
+ if (this.executionEngine === "legacy")
1376
+ this._cacheWarmer?.onAgentSettled();
1055
1377
  this._isAgentRunActive = false;
1056
1378
  this._isEmittingAgentSettled = true;
1057
1379
  try {
1058
1380
  const aborted = this._agentRunAbortRequested;
1059
1381
  await this._extensionRunner.emit({ type: "agent_settled", aborted });
1060
- this._emit({ type: "agent_settled", aborted });
1382
+ this._emit({
1383
+ type: "agent_settled",
1384
+ aborted,
1385
+ ...(this._providerRunStopped ? { failureClass: "provider" } : {}),
1386
+ });
1061
1387
  }
1062
1388
  finally {
1063
1389
  this._isEmittingAgentSettled = false;
@@ -1102,23 +1428,30 @@ export class AgentSession {
1102
1428
  // When a user message starts, check if it's from either queue and remove it BEFORE emitting
1103
1429
  // This ensures the UI sees the updated queue state
1104
1430
  if (event.type === "message_start" && event.message.role === "user") {
1431
+ // A failed listener can restore the unstarted suffix, which must still pass validation on redelivery.
1432
+ this._queuedUserInputs.delete(event.message);
1105
1433
  this._overflowRecoveryAttempts = 0;
1106
1434
  const messageText = contentText(event.message.content, "");
1107
- if (messageText) {
1108
- // Check steering queue first
1109
- const steeringIndex = this._steeringMessages.indexOf(messageText);
1110
- if (steeringIndex !== -1) {
1111
- this._steeringMessages.splice(steeringIndex, 1);
1435
+ if (this._acceptanceInitialUserPending)
1436
+ this._acceptanceInitialUserPending = false;
1437
+ else if (messageText &&
1438
+ this._acceptanceLedger &&
1439
+ ![...this._controlContinuations.values()].some((pending) => pending.message === event.message)) {
1440
+ this._acceptanceLedger.addTask(messageText);
1441
+ }
1442
+ // Check steering queue first
1443
+ const steeringIndex = this._steeringMessages.indexOf(messageText);
1444
+ if (steeringIndex !== -1) {
1445
+ this._steeringMessages.splice(steeringIndex, 1);
1446
+ this._emitQueueUpdate();
1447
+ }
1448
+ else {
1449
+ // Check follow-up queue
1450
+ const followUpIndex = this._followUpMessages.indexOf(messageText);
1451
+ if (followUpIndex !== -1) {
1452
+ this._followUpMessages.splice(followUpIndex, 1);
1112
1453
  this._emitQueueUpdate();
1113
1454
  }
1114
- else {
1115
- // Check follow-up queue
1116
- const followUpIndex = this._followUpMessages.indexOf(messageText);
1117
- if (followUpIndex !== -1) {
1118
- this._followUpMessages.splice(followUpIndex, 1);
1119
- this._emitQueueUpdate();
1120
- }
1121
- }
1122
1455
  }
1123
1456
  }
1124
1457
  if (event.type === "message_update") {
@@ -1140,12 +1473,30 @@ export class AgentSession {
1140
1473
  // that never produced one.
1141
1474
  if (event.type === "agent_end")
1142
1475
  this._oauthRequestAccount = undefined;
1476
+ // Dequeue by the original text before resize hints change it; resume dispatch without dequeuing twice.
1477
+ if (event.type === "message_start" &&
1478
+ event.message.role === "user" &&
1479
+ this._queuedMessagesWithImages.delete(event.message)) {
1480
+ return this._normalizeQueuedMessageImages(event.message).then(() => this._dispatchAgentEvent(event));
1481
+ }
1482
+ return this._dispatchAgentEvent(event);
1483
+ };
1484
+ /** Dispatch to extensions before public listeners and persistence, without making streamed deltas asynchronous. */
1485
+ _dispatchAgentEvent(event) {
1486
+ // Capture terminal policy before extensions/renderers can relabel or replace message fields.
1487
+ if (event.type === "message_end" && event.message.role === "assistant" && this._foregroundTarget) {
1488
+ const stopped = (event.message.stopReason !== "stop" && event.message.stopReason !== "toolUse") ||
1489
+ event.message.usage.usageIncomplete === true;
1490
+ this._responseTargets.set(event.message, { target: this._foregroundTarget, stopped });
1491
+ if (this._foregroundTarget.kind === "managed" && stopped)
1492
+ this._managedRunStopped = true;
1493
+ }
1143
1494
  // Emit to extensions first, then notify public listeners.
1144
1495
  const extensionDispatch = this._emitExtensionEvent(event);
1145
1496
  if (extensionDispatch)
1146
1497
  return extensionDispatch.then(() => this._finishAgentEvent(event));
1147
1498
  return this._finishAgentEvent(event);
1148
- };
1499
+ }
1149
1500
  /**
1150
1501
  * The part of `_handleAgentEvent` after the extension handlers: public listeners, persistence, turn bookkeeping.
1151
1502
  * Returns a promise only for an assistant `message_end`, whose OAuth credit rotation is awaited.
@@ -1227,7 +1578,7 @@ export class AgentSession {
1227
1578
  break;
1228
1579
  }
1229
1580
  }
1230
- if (!message)
1581
+ if (!message || this._managedRunStopped || this._managedRecoveryStopped(message))
1231
1582
  return false;
1232
1583
  // OAuth account failover retries immediately and does not consume the retry budget.
1233
1584
  if (this._predictOAuthAccountFailover(message))
@@ -1243,6 +1594,8 @@ export class AgentSession {
1243
1594
  * view. `agent_end.willRetry` must be computed before the async failover runs.
1244
1595
  */
1245
1596
  _predictOAuthAccountFailover(message) {
1597
+ if (this._managedRecoveryStopped(message))
1598
+ return false;
1246
1599
  const node = this._nodeFallbackTrigger(message, this._oauthFailoverServedKey);
1247
1600
  if (node)
1248
1601
  return this._predictNodeAccountFallback(message, node);
@@ -1298,6 +1651,8 @@ export class AgentSession {
1298
1651
  this._lastAssistantToolResults.length === 0);
1299
1652
  }
1300
1653
  async _prepareAccountRequest(providerId, signal) {
1654
+ if (providerId === HCODE_PROVIDER)
1655
+ return;
1301
1656
  // A denied activation can stop the run during message_end, before a tool continuation is prepared.
1302
1657
  this._agentRunAbortController?.signal.throwIfAborted();
1303
1658
  signal?.throwIfAborted();
@@ -1348,6 +1703,8 @@ export class AgentSession {
1348
1703
  * the current run or a resumed session. An unpaired result fails the next request (#11227).
1349
1704
  */
1350
1705
  _omitRecoveryAttempt(message) {
1706
+ if (this._managedRecoveryStopped(message))
1707
+ return;
1351
1708
  const toolCallIds = new Set(message.content.flatMap((block) => (block.type === "toolCall" ? [block.id] : [])));
1352
1709
  // A context edit replaces the projected copy, so match it by source entry as well.
1353
1710
  const entryId = this._findPersistedMessageEntryId(message);
@@ -1543,6 +1900,13 @@ export class AgentSession {
1543
1900
  * Call this when completely done with the session.
1544
1901
  */
1545
1902
  dispose() {
1903
+ this._disposed = true;
1904
+ this._foregroundTarget = undefined;
1905
+ this._responseTargets = new WeakMap();
1906
+ this._preparedImageRoute = undefined;
1907
+ for (const owner of this._bashJobOwners)
1908
+ owner.dispose();
1909
+ this._runPreflight = undefined;
1546
1910
  this._autoEffortController?.abort();
1547
1911
  this._autoEffortPendingInputs.clear();
1548
1912
  void closeSessionFlowControl(this);
@@ -1851,6 +2215,7 @@ export class AgentSession {
1851
2215
  const loadedSkills = this._resourceLoader.getSkills().skills;
1852
2216
  const loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;
1853
2217
  this._baseSystemPromptOptions = normalizeBuildSystemPromptOptions({
2218
+ includeHarnessDocs: this._includeHarnessDocs || (this._extensionRunner.hasUI() && this._extensionMode === "tui"),
1854
2219
  cwd: this._cwd,
1855
2220
  skills: loadedSkills,
1856
2221
  contextFiles: loadedContextFiles,
@@ -1970,30 +2335,343 @@ export class AgentSession {
1970
2335
  * Start a run from a user or custom message. The session counts as busy from here on, so
1971
2336
  * messages sent while before_agent_start handlers run are queued into this run instead of
1972
2337
  * starting another, and an abort requested meanwhile aborts the run as soon as it exists.
2338
+ * @param trigger Omit only to reread a restored terminal result without admitting a task.
1973
2339
  * @param onStarted Called once the run's messages are prepared, before the first request.
1974
2340
  * @param autoEffortText Raw interactive input the automatic effort judge sees for a user trigger.
1975
2341
  */
1976
- async _startRun(trigger, onStarted, autoEffortText) {
2342
+ async _startRun(trigger, onStarted, autoEffortText, adaptiveStartingLevel, fileTexts) {
2343
+ const recovering = this._restoredExecutionEngine === "adaptive-v2" && !this._adaptiveRecoveryRead;
2344
+ if (!trigger && !recovering)
2345
+ throw new Error("No restored adaptive terminal completion to read");
2346
+ const selectedEngine = recovering
2347
+ ? "adaptive-v2"
2348
+ : trigger?.messageType === "custom"
2349
+ ? "legacy"
2350
+ : this._restoredExecutionEngine === "legacy"
2351
+ ? "legacy"
2352
+ : (this._executionEngineOption ?? this.settingsManager.getExecutionEngine());
2353
+ if (selectedEngine === "adaptive-v2" && this._extensionRunner.getFlagValues().get("flow-admission") !== undefined)
2354
+ throw new Error("Adaptive execution cannot reinterpret a frozen Flow admission; use its original legacy runtime.");
2355
+ const persistSelection = selectedEngine === "adaptive-v2" ||
2356
+ this._runExecutionEngine === "adaptive-v2" ||
2357
+ this._restoredExecutionEngine === "adaptive-v2";
2358
+ this._runExecutionEngine = selectExecutionEngine(selectedEngine);
2359
+ if (!recovering && persistSelection) {
2360
+ this.sessionManager.appendCustomEntry("execution-engine", { version: 1, engine: selectedEngine });
2361
+ this.sessionManager.flush();
2362
+ }
2363
+ this._adaptiveCompletion = undefined;
2364
+ const started = performance.now();
1977
2365
  this._isAgentRunActive = true;
1978
2366
  this._agentRunAbortRequested = false;
2367
+ this._providerRunStopped = false;
2368
+ this._acceptanceLedger = undefined;
2369
+ this._acceptanceInitialUserPending = false;
2370
+ this._switchedOAuthAccountKeys.clear();
2371
+ this._oauthRecoveryAttempts = 0;
2372
+ this._oauthPoolWarmupFailed = false;
2373
+ this._managedRunStopped = false;
2374
+ this._foregroundTarget = undefined;
1979
2375
  let messages;
2376
+ const runAbortController = new AbortController();
2377
+ let adaptiveSignal;
2378
+ let detachAdaptiveSignal;
2379
+ this._agentRunAbortController = runAbortController;
1980
2380
  try {
1981
- messages = await this._prepareRun(trigger, autoEffortText);
2381
+ if (selectedEngine === "adaptive-v2") {
2382
+ this._adaptiveCompletion = undefined;
2383
+ this._adaptiveSeal = undefined;
2384
+ const branch = this.sessionManager.getBranch();
2385
+ const selection = branch.findLastIndex((entry) => entry.type === "custom" && entry.customType === "execution-engine");
2386
+ // Selection is persisted before admission. Its suffix alone belongs to the interrupted run.
2387
+ const runEntries = recovering && selection >= 0 ? branch.slice(selection + 1) : [];
2388
+ const previous = runEntries.findLast((entry) => entry.type === "custom" && entry.customType === "adaptive-engine-snapshot");
2389
+ const admission = runEntries.findLast((entry) => entry.type === "custom" && entry.customType === "adaptive-engine-admission");
2390
+ const completionSeal = runEntries.findLast((entry) => entry.type === "custom" && entry.customType === "adaptive-engine-completion");
2391
+ const terminal = previous?.type === "custom" &&
2392
+ previous.data !== null &&
2393
+ typeof previous.data === "object" &&
2394
+ "checkpoint" in previous.data &&
2395
+ previous.data.checkpoint === "terminal";
2396
+ if (!trigger && !terminal)
2397
+ throw new Error("Adaptive completion reread requires a terminal snapshot");
2398
+ if (recovering && (previous?.type !== "custom" || admission?.type !== "custom"))
2399
+ throw new Error("Adaptive recovery is unsupported without the original persisted admission; no work replayed");
2400
+ if (this._bashJobs.list().some((job) => job.status === "running" || job.status === "interrupted"))
2401
+ throw new Error("Cannot admit adaptive execution while session jobs are running or cleanup is unconfirmed");
2402
+ if (!this.model)
2403
+ throw new Error("No adaptive model selected");
2404
+ if (trigger?.messageType === "user" &&
2405
+ trigger.images?.length &&
2406
+ (this.settingsManager.getBlockImages() || !this.model.input.includes("image")))
2407
+ throw new Error("Adaptive image capability refused; nothing was dropped or sent");
2408
+ this._cacheWarmer?.cancel();
2409
+ this._adaptiveHost = await loadAdaptiveExecutionHost({
2410
+ cwd: this._cwd,
2411
+ startedAt: { wall: Date.now(), monotonic: performance.now() },
2412
+ sessionId: this.sessionId,
2413
+ text: !trigger
2414
+ ? ""
2415
+ : trigger.messageType === "user"
2416
+ ? trigger.prompt
2417
+ : contentText(trigger.message.content, ""),
2418
+ facts: [
2419
+ ...this._resourceLoader
2420
+ .getAgentsFiles()
2421
+ .agentsFiles.map((file) => `Project context ${file.path}:\n${file.content}`),
2422
+ ...this.sessionManager
2423
+ .getBranch()
2424
+ .flatMap((entry) => entry.type === "message" && entry.message.role === "user"
2425
+ ? [contentText(entry.message.content, "")].filter((text) => text.trim())
2426
+ : []),
2427
+ ],
2428
+ images: trigger?.messageType === "user" ? (trigger.images ?? []) : [],
2429
+ model: this.model,
2430
+ thinkingLevel: () => this.thinkingLevel,
2431
+ runtime: this._modelRuntime,
2432
+ authorityIdentity: createHash("sha256")
2433
+ .update(JSON.stringify({
2434
+ tools: this.getActiveToolNames().map((name) => ({
2435
+ name,
2436
+ source: this._toolDefinitions.get(name)?.sourceInfo,
2437
+ })),
2438
+ overrides: !!this._baseToolsOverride,
2439
+ extensions: this._resourceLoader
2440
+ .getExtensions()
2441
+ .extensions.map((extension) => extension.path),
2442
+ profile: this._extensionRunner.getFlagValues().get("profile") ?? null,
2443
+ flowAdmission: this._extensionRunner.getFlagValues().get("flow-admission") ?? null,
2444
+ trusted: this.settingsManager.isProjectTrusted(),
2445
+ fallback: this.settingsManager.readOAuthAccountActivationPolicy(this.model.provider),
2446
+ nodeFallback: this.model.provider === HUMAIN_NODE_PROVIDER
2447
+ ? this._modelRuntime.nodeAccountMetadata.read().policy
2448
+ : null,
2449
+ }))
2450
+ .digest("hex"),
2451
+ ...(recovering && admission?.type === "custom" && previous?.type === "custom"
2452
+ ? {
2453
+ recovery: {
2454
+ admission: admission.data,
2455
+ snapshot: previous.data,
2456
+ completion: completionSeal?.type === "custom" ? completionSeal.data : undefined,
2457
+ },
2458
+ }
2459
+ : {}),
2460
+ persistAdmission: (admission) => {
2461
+ this.sessionManager.appendCustomEntry("adaptive-engine-admission", admission);
2462
+ this.sessionManager.flush();
2463
+ },
2464
+ signal: runAbortController.signal,
2465
+ mode: this._extensionMode === "tui" ? "interactive" : "headless",
2466
+ deadline: this._timeLimit ? this._timeLimit.startedAt + this._timeLimit.seconds * 1000 : undefined,
2467
+ jobs: this._bashJobs,
2468
+ peerTools: () => this.agent.state.tools.filter((tool) => !this._baseToolsOverride &&
2469
+ ["read", "ls", "edit", "write"].includes(tool.name) &&
2470
+ this._toolDefinitions.get(tool.name)?.sourceInfo.source === "builtin"),
2471
+ peerRequest: async (context, signal, maxTokens, state, nativeTools) => {
2472
+ const requestContext = { messages: context.messages, tools: state.tools.slice() };
2473
+ const prepared = await this._adaptivePeerPrepareRequest?.({
2474
+ context: requestContext,
2475
+ model: state.model,
2476
+ thinkingLevel: state.thinkingLevel,
2477
+ }, signal);
2478
+ const model = prepared?.model ?? state.model;
2479
+ const thinking = prepared?.thinkingLevel ?? state.thinkingLevel;
2480
+ const peerContext = prepared?.context ?? requestContext;
2481
+ const executableTools = peerContext.tools ?? [];
2482
+ // Peer custody covers native implementations only; never ignore a hook's replacement or addition.
2483
+ if (executableTools.some((tool) => !nativeTools.includes(tool)))
2484
+ throw new Error("Adaptive prepared peer tool additions/replacements are unsupported");
2485
+ // Providers replay declarations, not executable tools; retain the same removal policy on later turns.
2486
+ const changes = getToolStateChanges(getCurrentTools(peerContext.messages), executableTools);
2487
+ const preparedMessages = changes.toolsAdded.length || changes.toolsRemoved.length
2488
+ ? [
2489
+ ...peerContext.messages,
2490
+ { role: "system", content: "", ...changes, timestamp: Date.now() },
2491
+ ]
2492
+ : peerContext.messages;
2493
+ // Request-time transforms must not replace or mutate the retained prepared context.
2494
+ const messages = this._adaptivePeerTransformContext
2495
+ ? await this._adaptivePeerTransformContext(structuredClone(preparedMessages), signal)
2496
+ : preparedMessages;
2497
+ const normalized = await this._normalizeOrdinaryToolImages({ ...peerContext, messages }, model);
2498
+ const response = await (await this._auxiliaryStreamFunction(model, normalizeContext({
2499
+ ...context,
2500
+ messages: await this.agent.convertToLlm(normalized.messages),
2501
+ }), {
2502
+ signal,
2503
+ maxTokens,
2504
+ reasoning: thinking === "off" ? undefined : thinking,
2505
+ thinkingBudgets: this.agent.thinkingBudgets,
2506
+ transport: this.agent.transport,
2507
+ maxRetryDelayMs: this.agent.maxRetryDelayMs,
2508
+ identity: this.agent.identity,
2509
+ onPayload: this.agent.onPayload,
2510
+ onResponse: this.agent.onResponse,
2511
+ onProviderStreamEvent: this.agent.onProviderStreamEvent,
2512
+ })).result();
2513
+ return {
2514
+ response,
2515
+ state: {
2516
+ model,
2517
+ thinkingLevel: thinking,
2518
+ tools: executableTools,
2519
+ messages: preparedMessages,
2520
+ },
2521
+ };
2522
+ },
2523
+ beforePeerTool: (context) => {
2524
+ if (this.agent.beforeToolCall !== this._installedBeforeToolCall ||
2525
+ !this.getActiveToolNames().includes(context.toolCall.name) ||
2526
+ this._toolDefinitions.get(context.toolCall.name)?.sourceInfo.source !== "builtin")
2527
+ throw new Error("Adaptive peer tool authority changed");
2528
+ return this._authorizeToolCall(context);
2529
+ },
2530
+ afterPeerTool: (context, signal) => this.agent.afterToolCall?.(context, signal) ?? Promise.resolve(undefined),
2531
+ persist: async (snapshot) => {
2532
+ if (snapshot.checkpoint === "terminal")
2533
+ this._adaptiveSeal = {
2534
+ runId: snapshot.budget.identity.runId,
2535
+ admissionId: snapshot.budget.identity.admissionId,
2536
+ snapshotIdentity: createHash("sha256").update(JSON.stringify(snapshot)).digest("hex"),
2537
+ };
2538
+ this.sessionManager.appendCustomEntry("adaptive-engine-snapshot", snapshot);
2539
+ this.sessionManager.flush();
2540
+ },
2541
+ publish: (status) => {
2542
+ this._emit({ type: "adaptive_status", status });
2543
+ if (this._extensionMode === "tui")
2544
+ this._extensionUIContext?.setWorkingMessage(adaptiveStatusText(status));
2545
+ },
2546
+ presentChecklist: (summary, checklist, signal) => presentAdaptiveChecklist(summary, checklist, signal, this._extensionUIContext),
2547
+ messages: () => this.messages,
2548
+ recordSubmission: (reservation, phase, lane) => {
2549
+ this.sessionManager.appendCustomEntry("adaptive-request-attestation", {
2550
+ ...reservation,
2551
+ phase,
2552
+ lane,
2553
+ });
2554
+ this.sessionManager.flush();
2555
+ },
2556
+ recordUsage: (provider, model, usage) => {
2557
+ const entry = this.sessionManager.appendUsage("adaptive", provider, model, usage);
2558
+ this._emit({ type: "entry_appended", entry });
2559
+ },
2560
+ abortImplementation: () => {
2561
+ this.agent.abort();
2562
+ this.abortCompaction();
2563
+ this.abortRetry();
2564
+ },
2565
+ wakeJob: (record) => {
2566
+ this.sessionManager.appendCustomEntry("adaptive-job-terminal", record);
2567
+ this._pendingCustomMessages.push({
2568
+ role: "custom",
2569
+ customType: "adaptive-job-terminal",
2570
+ content: `Owned job ${record.result.job_id} ${record.result.status}; inspect captured output with jobs before treating it as evidence.`,
2571
+ display: false,
2572
+ timestamp: Date.now(),
2573
+ });
2574
+ },
2575
+ }, {
2576
+ ...this._adaptiveOptions,
2577
+ ...(adaptiveStartingLevel !== undefined ? { startingLevel: adaptiveStartingLevel } : {}),
2578
+ }, this.settingsManager.getAdaptiveExecutionOptions());
2579
+ if (!recovering || !terminal)
2580
+ onStarted?.();
2581
+ const step = await this._adaptiveHost.next();
2582
+ if (step.kind === "complete") {
2583
+ this._acceptAdaptiveCompletion(step.completion);
2584
+ if (recovering)
2585
+ this._adaptiveRecoveryRead = true;
2586
+ this._adaptiveHost = undefined;
2587
+ this._agentRunAbortController = undefined;
2588
+ // A terminal reread is not the new task. Keep prompt ownership until that task settles.
2589
+ // Interrupted recovery still consumes only its frozen request.
2590
+ if (recovering && terminal && trigger) {
2591
+ runAbortController.signal.throwIfAborted();
2592
+ return this._startRun(trigger, onStarted, autoEffortText, adaptiveStartingLevel, fileTexts);
2593
+ }
2594
+ await this._emitAgentSettled();
2595
+ return;
2596
+ }
2597
+ if (runtimeStreamFunctions.get(this.agent.streamFunction) !== this._modelRuntime)
2598
+ throw new Error("Adaptive primary requires a ModelRuntime-owned stream; custom provider loops are unsupported");
2599
+ adaptiveSignal = step.context.signal;
2600
+ const abortPrimary = () => {
2601
+ this._agentRunAbortRequested = true;
2602
+ this.agent.abort();
2603
+ this.abortCompaction();
2604
+ this.abortRetry();
2605
+ };
2606
+ adaptiveSignal.addEventListener("abort", abortPrimary, { once: true });
2607
+ detachAdaptiveSignal = () => adaptiveSignal?.removeEventListener("abort", abortPrimary);
2608
+ if (adaptiveSignal.aborted)
2609
+ abortPrimary();
2610
+ if (!this._baseToolsOverride) {
2611
+ this._adaptiveLegacyJobs = this._baseToolDefinitions.get("jobs");
2612
+ this._baseToolDefinitions.set("jobs", createJobsToolDefinition(this._cwd, {
2613
+ jobs: this._bashJobs,
2614
+ getRunContext: () => this._adaptiveHost?.runContext,
2615
+ }));
2616
+ this._refreshToolRegistry();
2617
+ }
2618
+ this._appendAdaptiveWork(step.input);
2619
+ if (recovering) {
2620
+ trigger = {
2621
+ messageType: "user",
2622
+ prompt: this._adaptiveHost.prompt.text,
2623
+ images: this._adaptiveHost.prompt.images,
2624
+ };
2625
+ autoEffortText = trigger.prompt;
2626
+ }
2627
+ }
2628
+ if (!trigger)
2629
+ throw new Error("Adaptive terminal reread cannot dispatch work");
2630
+ const runTrigger = trigger;
2631
+ messages = await this._withAdaptiveAdmission(() => this._prepareRun(runTrigger, runAbortController.signal, autoEffortText));
1982
2632
  }
1983
2633
  catch (error) {
2634
+ detachAdaptiveSignal?.();
2635
+ if (selectedEngine === "adaptive-v2")
2636
+ runAbortController.abort();
2637
+ try {
2638
+ await this._finishAdaptiveExecution();
2639
+ }
2640
+ catch {
2641
+ /* Preserve the originating pre-run refusal. */
2642
+ }
2643
+ if (selectedEngine === "adaptive-v2")
2644
+ await this._emitAgentSettled();
2645
+ if (this._agentRunAbortController === runAbortController)
2646
+ this._agentRunAbortController = undefined;
2647
+ this._runSystemPromptOptions = undefined;
1984
2648
  this._isAgentRunActive = false;
1985
2649
  this._flushPendingBashMessages();
1986
2650
  this._flushPendingCustomMessages();
1987
2651
  this._resolveIdleWaitIfIdle();
2652
+ this._modelRuntime.metadata.feature("prompt", Math.round(performance.now() - started), "failure");
1988
2653
  throw error;
1989
2654
  }
2655
+ // Adaptive runs retain their own evidence-bound verification and completion authority.
2656
+ if (selectedEngine === "legacy" && trigger.messageType === "user" && this._runPreflight) {
2657
+ this._acceptanceLedger = new AcceptanceLedger(trigger.prompt, () => {
2658
+ for (const owner of this._bashJobOwners)
2659
+ if (owner.hasActiveEffects)
2660
+ return true;
2661
+ return false;
2662
+ }, fileTexts);
2663
+ this._acceptanceInitialUserPending = true;
2664
+ this._emit({
2665
+ type: "acceptance_started",
2666
+ criteria: this._acceptanceLedger.criteria.map((criterion) => ({ ...criterion, evidence: [] })),
2667
+ });
2668
+ }
1990
2669
  // Messages held while the run was starting go before its starting messages, as they would
1991
2670
  // have while idle. No run exists yet, so they cannot split a tool call from its result.
1992
2671
  this._flushPendingBashMessages();
1993
2672
  this._flushPendingCustomMessages();
1994
- onStarted?.();
1995
- const runAbortController = new AbortController();
1996
- this._agentRunAbortController = runAbortController;
2673
+ if (selectedEngine === "legacy")
2674
+ onStarted?.();
1997
2675
  // Compaction before the prompt may have scheduled a retry; the new prompt replaces it.
1998
2676
  this._failedResponse = undefined;
1999
2677
  this._recordSelection();
@@ -2001,8 +2679,6 @@ export class AgentSession {
2001
2679
  // are dropped, so a tool that never registers does not stay pending.
2002
2680
  this._pendingToolNames.clear();
2003
2681
  this._isAgentRunActive = true;
2004
- this._switchedOAuthAccountKeys.clear();
2005
- this._oauthRecoveryAttempts = 0;
2006
2682
  this._accountRetryRequest = undefined;
2007
2683
  this._oauthCreditCapableKeys.clear();
2008
2684
  this._oauthCreditFallbackUsed = false;
@@ -2026,46 +2702,323 @@ export class AgentSession {
2026
2702
  // agent_start applies an abort requested during preparation or warm-up before any provider request.
2027
2703
  await this._observeRequests("chat", () => this.agent.prompt(messages));
2028
2704
  while (!this._agentRunAbortRequested) {
2029
- if (await this._handlePostAgentRun()) {
2705
+ if (!this._adaptiveHost?.implementationStoppedForReserve &&
2706
+ (await this._withAdaptiveAdmission(() => this._handlePostAgentRun()))) {
2030
2707
  if (this._agentRunAbortRequested)
2031
2708
  break;
2032
2709
  await this._observeRequests("chat", () => this.agent.continue());
2033
2710
  continue;
2034
2711
  }
2035
- if (this._agentRunAbortRequested || !(await this._runBeforeSettleBoundary()))
2036
- break;
2037
2712
  if (this._agentRunAbortRequested)
2038
2713
  break;
2714
+ let continuation = this._adaptiveHost?.implementationStoppedForReserve
2715
+ ? false
2716
+ : await this._withAdaptiveAdmission(() => this._runBeforeSettleBoundary());
2717
+ if (!continuation && this._adaptiveHost) {
2718
+ this._adaptiveHost.completeAct();
2719
+ const step = await this._adaptiveHost.next();
2720
+ if (step.kind === "complete") {
2721
+ this._acceptAdaptiveCompletion(step.completion);
2722
+ if (recovering)
2723
+ this._adaptiveRecoveryRead = true;
2724
+ break;
2725
+ }
2726
+ this._appendAdaptiveWork(step.input);
2727
+ continuation = true;
2728
+ }
2729
+ else if (!continuation && !this._managedRunStopped && this._acceptanceLedger) {
2730
+ await this._verifyAcceptance();
2731
+ continuation =
2732
+ this.agent.hasQueuedMessages() && this._buildBoundaryContext([], "agent_before_settle").canContinue;
2733
+ }
2734
+ if (!continuation || this._agentRunAbortRequested)
2735
+ break;
2039
2736
  await this._observeRequests("chat", () => this.agent.continue());
2040
2737
  }
2041
2738
  }
2042
2739
  finally {
2043
- if (this._agentRunAbortRequested)
2044
- this._finishCancelledRetry();
2045
- this._failedResponse = undefined;
2046
- this._runSystemPromptOptions = undefined;
2047
- this._flushPendingBashMessages();
2048
- this._flushPendingCustomMessages();
2049
- if (this._agentRunAbortController === runAbortController)
2050
- this._agentRunAbortController = undefined;
2051
- await this._emitAgentSettled();
2740
+ try {
2741
+ detachAdaptiveSignal?.();
2742
+ if (this._adaptiveHost && !this._adaptiveCompletion) {
2743
+ if (!adaptiveSignal?.aborted)
2744
+ runAbortController.abort();
2745
+ await this._finishAdaptiveExecution();
2746
+ }
2747
+ this._settleAcceptance();
2748
+ }
2749
+ finally {
2750
+ this._adaptiveHost = undefined;
2751
+ this._restoreAdaptiveJobs();
2752
+ if (this._agentRunAbortRequested)
2753
+ this._finishCancelledRetry();
2754
+ this._failedResponse = undefined;
2755
+ this._preparedImageRoute = undefined;
2756
+ this._runSystemPromptOptions = undefined;
2757
+ this._flushPendingBashMessages();
2758
+ this._flushPendingCustomMessages();
2759
+ if (this._agentRunAbortController === runAbortController)
2760
+ this._agentRunAbortController = undefined;
2761
+ await this._emitAgentSettled();
2762
+ this._modelRuntime.metadata.feature("prompt", Math.round(performance.now() - started), this._agentRunAbortRequested || this._lastActivityOutcome === "aborted"
2763
+ ? "cancelled"
2764
+ : this._managedRunStopped || this._lastActivityOutcome === "error"
2765
+ ? "failure"
2766
+ : "success");
2767
+ }
2052
2768
  }
2053
2769
  }
2770
+ async _verifyAcceptance() {
2771
+ const ledger = this._acceptanceLedger;
2772
+ if (!ledger)
2773
+ return;
2774
+ const assistant = this._findLastAssistantMessage();
2775
+ const open = ledger.openChecks();
2776
+ const interrupted = () => this._agentRunAbortRequested || assistant?.stopReason !== "stop";
2777
+ if (assistant &&
2778
+ !interrupted() &&
2779
+ ledger.criteria.some((criterion) => criterion.status !== "checked" && criterion.check.kind !== "output")) {
2780
+ // One local round, bounded by count and a shared deadline; never ask a model to verify itself.
2781
+ const checks = open.slice(0, 8);
2782
+ this._emit({ type: "acceptance_verification_start", criterionIds: checks.map((criterion) => criterion.id) });
2783
+ const signal = AbortSignal.any([
2784
+ AbortSignal.timeout(30_000),
2785
+ ...(this._agentRunAbortController ? [this._agentRunAbortController.signal] : []),
2786
+ ]);
2787
+ for (const criterion of checks) {
2788
+ if (signal.aborted || interrupted() || this.agent.hasQueuedMessages())
2789
+ break;
2790
+ const check = criterion.check;
2791
+ if (check.kind === "output" || (check.kind === "manual" && check.readback === undefined))
2792
+ continue;
2793
+ const name = check.kind === "command" ? "bash" : "read";
2794
+ const tools = this._getCallableTools();
2795
+ if (!tools.some((tool) => tool.name === name))
2796
+ continue;
2797
+ const toolCall = {
2798
+ type: "toolCall",
2799
+ id: `acceptance-${randomUUID()}`,
2800
+ name,
2801
+ arguments: check.kind === "command"
2802
+ ? { command: check.command, timeout: 30 }
2803
+ : { path: check.kind === "file" ? check.path : check.readback },
2804
+ };
2805
+ const start = {
2806
+ type: "tool_execution_start",
2807
+ toolCallId: toolCall.id,
2808
+ toolName: name,
2809
+ args: toolCall.arguments,
2810
+ };
2811
+ await this._extensionRunner.emit(start);
2812
+ this._emit(start);
2813
+ const execute = () => runToolCall(toolCall, {
2814
+ tools,
2815
+ assistantMessage: assistant,
2816
+ context: { messages: this.agent.state.messages, tools: this.agent.state.tools },
2817
+ beforeToolCall: async (context, signal) => {
2818
+ if (this.agent.beforeToolCall !== this._installedBeforeToolCall)
2819
+ ledger.beginToolCall(context.toolCall.id, context.toolCall.name, context.args);
2820
+ return this.agent.beforeToolCall?.(context, signal);
2821
+ },
2822
+ afterToolCall: async (context, signal) => this.agent.afterToolCall?.(context, signal),
2823
+ onToolResult: async (observation) => {
2824
+ await this._observeToolResult(observation);
2825
+ if (this.agent.onToolResult !== this._installedToolResultObserver)
2826
+ await this.agent.onToolResult?.(observation);
2827
+ },
2828
+ signal,
2829
+ });
2830
+ const result = check.kind === "command" && ledger.criteria.filter((item) => item.check.kind === "command").length > 1
2831
+ ? await withReadOnlyAcceptanceCommand(toolCall.id, check.command, this._cwd, signal, execute)
2832
+ : await execute();
2833
+ const nested = this._nestedToolCalls?.takeRecord(toolCall.id);
2834
+ const usage = nested?.usage
2835
+ ? result.result.usage
2836
+ ? combineUsage(result.result.usage, nested.usage)
2837
+ : nested.usage
2838
+ : result.result.usage;
2839
+ if (usage) {
2840
+ // Tool usage is aggregate evidence, not usage of the assistant's provider/model.
2841
+ const entry = this.sessionManager.appendUsage("acceptance-check", "tool", name, usage);
2842
+ this._emit({ type: "entry_appended", entry });
2843
+ }
2844
+ const end = {
2845
+ type: "tool_execution_end",
2846
+ toolCallId: toolCall.id,
2847
+ toolName: name,
2848
+ result: result.result,
2849
+ isError: result.isError,
2850
+ durationMs: result.durationMs,
2851
+ };
2852
+ await this._extensionRunner.emit(end);
2853
+ this._emit(end);
2854
+ }
2855
+ }
2856
+ }
2857
+ _settleAcceptance() {
2858
+ const ledger = this._acceptanceLedger;
2859
+ if (!ledger)
2860
+ return;
2861
+ const assistant = this._findLastAssistantMessage();
2862
+ const outcome = this._agentRunAbortRequested
2863
+ ? "aborted"
2864
+ : assistant?.stopReason === "stop"
2865
+ ? "completed"
2866
+ : "error";
2867
+ const settlement = ledger.settle(assistant ? contentText(assistant.content, "") : "", outcome);
2868
+ this._acceptanceLedger = undefined;
2869
+ this._appendCustomMessage({
2870
+ role: "custom",
2871
+ customType: "acceptance-settlement",
2872
+ content: settlement.report,
2873
+ display: true,
2874
+ details: settlement,
2875
+ timestamp: Date.now(),
2876
+ });
2877
+ this._emit(settlement);
2878
+ }
2879
+ /** Prepare and probe admission using the session's bounded, consent-aware account recovery policy. */
2880
+ async preflightRun(preflight, signal) {
2881
+ for (;;) {
2882
+ signal.throwIfAborted();
2883
+ const model = this.model;
2884
+ if (model)
2885
+ await this._prepareAccountRequest(model.provider, signal);
2886
+ try {
2887
+ await preflight(this.modelRuntime, model, signal);
2888
+ return;
2889
+ }
2890
+ catch (error) {
2891
+ signal.throwIfAborted();
2892
+ // Only attributed, structured quota failures authorize another probe. Managed requests never resend.
2893
+ if (!(error instanceof ModelPreflightFailure) ||
2894
+ error.providerId === HCODE_PROVIDER ||
2895
+ (error.providerId !== model?.provider && (!model || !isVirtualModel(model))) ||
2896
+ error.accountKey === undefined ||
2897
+ !this.settingsManager.getOAuthAccountsAutoSwitch(error.providerId) ||
2898
+ this._oauthRecoveryLimitReached(error.providerId))
2899
+ throw error;
2900
+ const pool = this._modelRuntime.oauthAccounts;
2901
+ const from = pool
2902
+ .getCachedPoolAccounts(error.providerId)
2903
+ ?.find((account) => account.key === error.accountKey);
2904
+ if (!from || this._switchedOAuthAccountKeys.has(from.key))
2905
+ throw error;
2906
+ this._switchedOAuthAccountKeys.add(from.key);
2907
+ try {
2908
+ const result = await pool.failoverAccounts(error.providerId, {
2909
+ expectedActiveKey: from.key,
2910
+ exhaustedUntil: error.resetsAt,
2911
+ skipKeys: this._switchedOAuthAccountKeys,
2912
+ signal,
2913
+ apiKeyFallback: this.settingsManager.getOAuthAccountApiKeyFallback(error.providerId),
2914
+ allowApiKeyRotation: this._modelRuntime.getProvider(error.providerId)?.auth.apiKey?.isSubscription === true,
2915
+ canActivate: (source, target) => this._canActivateAccount(error.providerId, source, target),
2916
+ });
2917
+ signal.throwIfAborted();
2918
+ const to = result?.switched
2919
+ ? result.to
2920
+ : result?.reason === "active_changed"
2921
+ ? result.active
2922
+ : undefined;
2923
+ if (!to ||
2924
+ this._switchedOAuthAccountKeys.has(to.key) ||
2925
+ !this._canActivateAccount(error.providerId, from, to))
2926
+ throw error;
2927
+ await this._modelRuntime.refresh({ allowNetwork: false, providers: [error.providerId], signal });
2928
+ this._oauthRecoveryAttempts++;
2929
+ this._emit({
2930
+ type: "oauth_account_switched",
2931
+ provider: error.providerId,
2932
+ fromAccountKey: from.key,
2933
+ toAccountKey: to.key,
2934
+ fromLabel: from.label,
2935
+ toLabel: to.label,
2936
+ reason: "usage_limit",
2937
+ });
2938
+ }
2939
+ catch {
2940
+ signal.throwIfAborted();
2941
+ throw error;
2942
+ }
2943
+ }
2944
+ }
2945
+ }
2946
+ async _finishAdaptiveExecution() {
2947
+ const host = this._adaptiveHost;
2948
+ if (!host)
2949
+ return;
2950
+ try {
2951
+ host.completeAct();
2952
+ this._acceptAdaptiveCompletion(await host.finished);
2953
+ }
2954
+ finally {
2955
+ this._adaptiveHost = undefined;
2956
+ this._restoreAdaptiveJobs();
2957
+ }
2958
+ }
2959
+ _restoreAdaptiveJobs() {
2960
+ if (!this._adaptiveLegacyJobs)
2961
+ return;
2962
+ this._baseToolDefinitions.set("jobs", this._adaptiveLegacyJobs);
2963
+ this._adaptiveLegacyJobs = undefined;
2964
+ this._refreshToolRegistry();
2965
+ }
2966
+ _acceptAdaptiveCompletion(completion) {
2967
+ const seal = this._adaptiveSeal;
2968
+ if (seal) {
2969
+ this.sessionManager.appendCustomEntry("adaptive-engine-completion", {
2970
+ version: 1,
2971
+ ...seal,
2972
+ verification: completion.verification,
2973
+ workflowOutcome: completion.workflowOutcome,
2974
+ });
2975
+ this.sessionManager.flush();
2976
+ this._adaptiveSeal = undefined;
2977
+ }
2978
+ this._adaptiveCompletion = completion;
2979
+ this._emit({ type: "adaptive_completion", completion });
2980
+ if (this._extensionMode === "tui") {
2981
+ this._extensionUIContext?.setWorkingMessage(undefined);
2982
+ this._extensionUIContext?.notify(adaptiveEvidenceLines(completion).join("\n"), completion.verification === "verified" ? "info" : "warning");
2983
+ }
2984
+ }
2985
+ _appendAdaptiveWork(input) {
2986
+ this._pendingCustomMessages.push({
2987
+ role: "custom",
2988
+ customType: "adaptive-work",
2989
+ display: false,
2990
+ content: `Admitted adaptive primary work: ${JSON.stringify(input)}\n${input.level >= 1 ? "Make a short plan naming affected contracts and checks before mutation. " : ""}Satisfy each criterion, self-check and report limitations. Host-captured checks and a counterexample are required; your prose or JSON cannot certify behavior. Nested model execution is not authorized. ${input.level === 2 ? 'For genuinely independent work, end a short plan with <adaptive_peers>[{"paths":["relative/owned/path"],"task":"bounded independent task","benefit":"why parallel work helps","tokens":30000}]</adaptive_peers>. At most two scopes; give each enough tokens for bounded input plus output on every request. The host admits disjoint scopes and returns collected summaries to you for integration before checking. Do not delegate unsplittable work. ' : ""}If new facts add or refine scope, append <adaptive_updates>{"requirements":[{"kind":"append","acceptance":"new atomic criterion"}],"facts":["observed fact"]}</adaptive_updates>; refine uses kind=refine plus id. This is a proposal only, never evidence/status/removal authority.`,
2991
+ timestamp: Date.now(),
2992
+ });
2993
+ if (this.agent.state.messages.length)
2994
+ this._flushPendingCustomMessages();
2995
+ }
2054
2996
  /**
2055
2997
  * Prepare a run and return its starting messages: compact first when needed, emit
2056
2998
  * before_agent_start, apply the run's prompt options and tool loadout, and build the starting
2057
2999
  * message followed by pending nextTurn messages (consumed here) and handler messages, with a
2058
- * system patch first when the prompt changed.
3000
+ * system patch first when the prompt changed. An opt-in preflight delays compaction until
3001
+ * after the handlers select the effective model and the gate approves it.
2059
3002
  */
2060
- async _prepareRun(trigger, autoEffortText) {
3003
+ async _prepareRun(trigger, signal, autoEffortText) {
2061
3004
  // Check if we need to compact before sending (catches aborted responses).
2062
3005
  // The starting message is sent below, so do not call agent.continue() here.
3006
+ const preflight = this._runPreflight;
2063
3007
  const lastAssistant = this._findLastAssistantMessage();
2064
- if (lastAssistant) {
3008
+ if (lastAssistant && !preflight) {
2065
3009
  await this._checkCompaction(lastAssistant, false);
2066
3010
  }
2067
3011
  const selectedToolsBefore = this._baseSystemPromptOptions.selectedTools;
2068
3012
  const result = await this._extensionRunner.emitBeforeAgentStart(trigger, this._baseSystemPromptOptions);
3013
+ if (preflight) {
3014
+ // Opt-in gates must approve the extension-selected model before compaction can submit a request.
3015
+ signal.throwIfAborted();
3016
+ await this.preflightRun(preflight, signal);
3017
+ signal.throwIfAborted();
3018
+ if (lastAssistant)
3019
+ await this._checkCompaction(lastAssistant, false);
3020
+ signal.throwIfAborted();
3021
+ }
2069
3022
  // Handlers may edit event.systemPromptOptions.selectedTools or call setActiveTools(),
2070
3023
  // which updates the live loadout instead. An explicit edit wins; otherwise the live
2071
3024
  // loadout is authoritative, so a setActiveTools() call is not undone here.
@@ -2074,17 +3027,16 @@ export class AgentSession {
2074
3027
  if (!handlerEditedTools)
2075
3028
  result.systemPromptOptions.selectedTools = this.getActiveToolNames();
2076
3029
  const messages = [];
3030
+ let userMessage;
2077
3031
  if (trigger.messageType === "custom") {
2078
3032
  messages.push(trigger.message);
2079
3033
  }
2080
3034
  else {
2081
3035
  // Normalize images after before_agent_start so extension-driven model selection
2082
3036
  // determines the resize profile used for the request and history.
2083
- const normalized = await this._normalizePromptImages(trigger.images);
2084
- const text = normalized.hints.length > 0 ? `${trigger.prompt}\n\n${normalized.hints.join("\n")}` : trigger.prompt;
2085
- const userMessage = {
3037
+ userMessage = {
2086
3038
  role: "user",
2087
- content: [{ type: "text", text }, ...normalized.images],
3039
+ content: [{ type: "text", text: trigger.prompt }, ...(trigger.images ?? [])],
2088
3040
  timestamp: Date.now(),
2089
3041
  };
2090
3042
  if (autoEffortText !== undefined)
@@ -2093,7 +3045,6 @@ export class AgentSession {
2093
3045
  }
2094
3046
  // Inject any pending "nextTurn" messages as context alongside the starting message
2095
3047
  messages.push(...this._pendingNextTurnMessages);
2096
- this._pendingNextTurnMessages = [];
2097
3048
  for (const msg of result.messages) {
2098
3049
  messages.push({
2099
3050
  role: "custom",
@@ -2109,6 +3060,40 @@ export class AgentSession {
2109
3060
  this._runSystemPromptOptions = result.systemPromptOptions;
2110
3061
  if (updateMessage)
2111
3062
  messages.unshift(updateMessage);
3063
+ const selection = this.model;
3064
+ let target = selection;
3065
+ let prepared;
3066
+ let preparedState;
3067
+ const preparedThinking = this.thinkingLevel;
3068
+ if (selection && isVirtualModel(selection)) {
3069
+ const context = convertToLlm([...this.messages, ...messages]);
3070
+ if (context.some((message) => typeof message.content !== "string" && message.content.some((block) => block.type === "image"))) {
3071
+ preparedState = getVirtualModelState(this.sessionManager.getBranch(), selection.provider, selection.id);
3072
+ const lastResponse = context.findLastIndex((message) => message.role === "assistant");
3073
+ const userTurn = context.slice(lastResponse + 1).some((message) => message.role === "user");
3074
+ prepared = await this._modelRuntime.resolveModel(selection, context, {
3075
+ reason: userTurn ? "user" : "continuation",
3076
+ thinkingLevel: preparedThinking,
3077
+ state: preparedState,
3078
+ });
3079
+ target = prepared.model;
3080
+ }
3081
+ }
3082
+ if (trigger.messageType === "user" && userMessage) {
3083
+ const normalized = await this._normalizePromptImages(trigger.images, target);
3084
+ const text = normalized.hints.length ? `${trigger.prompt}\n\n${normalized.hints.join("\n")}` : trigger.prompt;
3085
+ userMessage.content = [{ type: "text", text }, ...normalized.images];
3086
+ }
3087
+ if (target?.provider === HCODE_PROVIDER)
3088
+ await this._validateManagedInput(target, [...this.messages, ...messages], prepared?.thinkingLevel ?? this.thinkingLevel);
3089
+ if (prepared && selection)
3090
+ this._preparedImageRoute = {
3091
+ selection,
3092
+ route: prepared,
3093
+ thinkingLevel: preparedThinking,
3094
+ state: preparedState,
3095
+ };
3096
+ this._pendingNextTurnMessages = [];
2112
3097
  return messages;
2113
3098
  }
2114
3099
  async _handlePostAgentRun() {
@@ -2119,6 +3104,8 @@ export class AgentSession {
2119
3104
  this._finishCancelledRetry();
2120
3105
  return false;
2121
3106
  }
3107
+ if (this._managedRunStopped || (message && this._managedRecoveryStopped(message)))
3108
+ return false;
2122
3109
  if (!message)
2123
3110
  return this.agent.hasQueuedMessages();
2124
3111
  if (await this._tryOAuthAccountFailover(message)) {
@@ -2156,6 +3143,8 @@ export class AgentSession {
2156
3143
  return !this._agentRunAbortRequested && this.agent.hasQueuedMessages();
2157
3144
  }
2158
3145
  async _runBeforeSettleBoundary() {
3146
+ if (this._managedRunStopped)
3147
+ return false;
2159
3148
  if (!this._extensionRunner.hasHandlers("agent_before_settle"))
2160
3149
  return this.agent.hasQueuedMessages();
2161
3150
  this._isBeforeSettle = true;
@@ -2192,17 +3181,94 @@ export class AgentSession {
2192
3181
  }
2193
3182
  return { text, images };
2194
3183
  }
2195
- async _normalizePromptImages(images) {
3184
+ async _normalizeOrdinaryToolImages(context, model) {
3185
+ if (model.provider === HCODE_PROVIDER)
3186
+ return context;
3187
+ // History keeps originals for future managed routes; normalize only the resolved ordinary request.
3188
+ let messages;
3189
+ for (let index = 0; index < context.messages.length; index++) {
3190
+ const message = context.messages[index];
3191
+ if (message.role !== "toolResult" || !message.content.some((block) => block.type === "image"))
3192
+ continue;
3193
+ const content = await normalizeToolResultImages(message.content, {
3194
+ autoResizeImages: this.settingsManager.getImageAutoResize(),
3195
+ resizeOptions: model.inputLimits?.images?.resize,
3196
+ });
3197
+ if (content === message.content)
3198
+ continue;
3199
+ messages ??= context.messages.slice();
3200
+ messages[index] = { ...message, content };
3201
+ }
3202
+ return messages ? { ...context, messages } : context;
3203
+ }
3204
+ _installQueuedInputValidation() {
3205
+ const previous = this.agent.beforeMessages;
3206
+ this.agent.beforeMessages = async (messages, context, signal) => {
3207
+ if (this._managedRunStopped)
3208
+ throw new Error("HUMAIN Code request stopped. Queued input was not sent.");
3209
+ try {
3210
+ await previous?.(messages, context, signal);
3211
+ if (!messages.some((message) => this._queuedUserInputs.has(message)))
3212
+ return;
3213
+ this._preparedImageRoute = await this._validateQueuedInput(messages, context.messages, signal);
3214
+ }
3215
+ catch (error) {
3216
+ // Agent retains the undelivered batch; stop session continuation instead of repeatedly draining it.
3217
+ this._agentRunAbortRequested = true;
3218
+ throw error;
3219
+ }
3220
+ };
3221
+ }
3222
+ async _validateQueuedInput(messages, context, signal) {
3223
+ const selection = this.model;
3224
+ if (!selection)
3225
+ return;
3226
+ const combined = [...context, ...messages];
3227
+ const thinkingLevel = this.thinkingLevel;
3228
+ if (!isVirtualModel(selection)) {
3229
+ await this._validateManagedInput(selection, combined, thinkingLevel);
3230
+ return;
3231
+ }
3232
+ const llm = convertToLlm(combined);
3233
+ if (!llm.some((message) => typeof message.content !== "string" && message.content.some((block) => block.type === "image")))
3234
+ return;
3235
+ const state = getVirtualModelState(this.sessionManager.getBranch(), selection.provider, selection.id);
3236
+ const route = await this._modelRuntime.resolveModel(selection, llm, {
3237
+ reason: "user",
3238
+ thinkingLevel,
3239
+ state,
3240
+ signal,
3241
+ });
3242
+ await this._validateManagedInput(route.model, combined, route.thinkingLevel);
3243
+ return { selection, route, thinkingLevel, state };
3244
+ }
3245
+ async _validateManagedInput(model, messages, thinkingLevel) {
3246
+ if (model.provider !== HCODE_PROVIDER)
3247
+ return;
3248
+ const reference = captureHcodeSelection(this._modelRuntime, model);
3249
+ this._assertManagedThinkingLevel(model, thinkingLevel);
3250
+ const context = convertToLlm(messages);
3251
+ if (this.settingsManager.getBlockImages() &&
3252
+ context.some((message) => typeof message.content !== "string" && message.content.some((block) => block.type === "image")))
3253
+ throw new Error("HUMAIN Code image attachments are blocked. Remove them or change /settings before sending. Nothing was dropped or sent.");
3254
+ await validateHcodeImages(model, context);
3255
+ assertHcodeSelection(this._modelRuntime, model, reference);
3256
+ }
3257
+ async _normalizePromptImages(images, model) {
2196
3258
  if (!images)
2197
3259
  return { images: [], hints: [] };
3260
+ if (model?.provider === HCODE_PROVIDER || (model && isVirtualModel(model)))
3261
+ return { images, hints: [] };
2198
3262
  const normalizedImages = [];
2199
3263
  const hints = [];
2200
3264
  for (const image of images) {
2201
3265
  const processed = await processImage(Buffer.from(image.data, "base64"), image.mimeType, {
2202
3266
  autoResizeImages: this.settingsManager.getImageAutoResize(),
2203
- resizeOptions: this._limitsModel()?.inputLimits?.images?.resize,
3267
+ resizeOptions: model?.inputLimits?.images?.resize,
2204
3268
  });
2205
3269
  if (!processed.ok) {
3270
+ if (this.executionEngine === "adaptive-v2")
3271
+ throw new Error(`Adaptive image input refused: ${processed.message}`);
2206
3272
  hints.push(processed.message);
2207
3273
  continue;
2208
3274
  }
@@ -2211,6 +3277,15 @@ export class AgentSession {
2211
3277
  }
2212
3278
  return { images: normalizedImages, hints };
2213
3279
  }
3280
+ /** Revalidate a reopened terminal run's evidence without submitting a new task or replaying work. */
3281
+ async rereadAdaptiveCompletion() {
3282
+ if (!this.isIdle || this._promptPreflightCount > 0)
3283
+ throw new Error("Wait for the current session operation before rereading adaptive completion");
3284
+ await this._startRun(undefined);
3285
+ if (!this._adaptiveCompletion)
3286
+ throw new Error("Adaptive terminal completion unavailable");
3287
+ return this._adaptiveCompletion;
3288
+ }
2214
3289
  /**
2215
3290
  * Send a prompt to the agent.
2216
3291
  * - Handles extension commands (registered via pi.registerCommand) immediately, even during streaming
@@ -2237,14 +3312,35 @@ export class AgentSession {
2237
3312
  return;
2238
3313
  }
2239
3314
  }
2240
- if (this._compactionAbortController !== undefined) {
3315
+ if (this._compactionAbortController !== undefined || this._branchSummaryAbortController !== undefined) {
2241
3316
  throw new Error("Cannot submit a prompt while compaction is in progress. Wait for compaction to finish and retry.");
2242
3317
  }
3318
+ // Reserve the context through async input hooks and auth checks so tree navigation cannot
3319
+ // start meanwhile (#9154). _startRun marks the run active synchronously, so there is no gap.
3320
+ this._promptPreflightCount++;
3321
+ let prepared;
3322
+ try {
3323
+ prepared = await this._preparePrompt(text, options);
3324
+ }
3325
+ finally {
3326
+ this._promptPreflightCount--;
3327
+ }
3328
+ if (prepared) {
3329
+ await this._startRun(prepared.trigger, () => preflightResult?.("started"), prepared.autoEffortText, options?.adaptiveStartingLevel, options?.fileTexts);
3330
+ }
3331
+ }
3332
+ /**
3333
+ * Run input hooks, expand templates, queue while streaming, and validate model and auth.
3334
+ * Returns the run trigger, or undefined when the prompt was handled or queued.
3335
+ */
3336
+ async _preparePrompt(text, options) {
3337
+ const expandPromptTemplates = options?.expandPromptTemplates ?? true;
3338
+ const preflightResult = options?.preflightResult;
2243
3339
  // Emit input event for extension interception (before skill/template expansion)
2244
3340
  const processedInput = await this._runInputHandlers(text, options?.images, options?.source ?? "interactive", this.isStreaming ? options?.streamingBehavior : undefined);
2245
3341
  if (!processedInput) {
2246
3342
  preflightResult?.("handled");
2247
- return;
3343
+ return undefined;
2248
3344
  }
2249
3345
  const { text: currentText, images: currentImages } = processedInput;
2250
3346
  // Expand skill commands (/skill:name args) and prompt templates (/template args)
@@ -2265,12 +3361,16 @@ export class AgentSession {
2265
3361
  await this._queueSteer(expandedText, currentImages, (options?.source ?? "interactive") === "interactive" ? currentText : undefined);
2266
3362
  }
2267
3363
  preflightResult?.("queued");
2268
- return;
3364
+ return undefined;
2269
3365
  }
2270
3366
  // Validate model
2271
- if (!this.model) {
3367
+ if (!this.model || this.model.provider === "unknown") {
2272
3368
  throw new Error(formatNoModelSelectedMessage());
2273
3369
  }
3370
+ const selectedModel = this.model;
3371
+ const reference = selectedModel.provider === HCODE_PROVIDER
3372
+ ? captureHcodeSelection(this._modelRuntime, selectedModel)
3373
+ : undefined;
2274
3374
  const hasConfiguredAuth = this._modelRuntime.hasConfiguredAuth(this.model.provider) ||
2275
3375
  (await this._modelRuntime.checkAuth(this.model.provider)) !== undefined;
2276
3376
  if (!hasConfiguredAuth) {
@@ -2282,7 +3382,12 @@ export class AgentSession {
2282
3382
  }
2283
3383
  throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
2284
3384
  }
2285
- await this._startRun({ messageType: "user", prompt: expandedText, images: currentImages }, () => preflightResult?.("started"), (options?.source ?? "interactive") === "interactive" ? currentText : undefined);
3385
+ if (reference)
3386
+ assertHcodeSelection(this._modelRuntime, selectedModel, reference);
3387
+ return {
3388
+ trigger: { messageType: "user", prompt: expandedText, images: currentImages },
3389
+ autoEffortText: (options?.source ?? "interactive") === "interactive" ? currentText : undefined,
3390
+ };
2286
3391
  }
2287
3392
  /**
2288
3393
  * Try to execute an extension command. Returns true if command was found and executed.
@@ -2412,7 +3517,7 @@ export class AgentSession {
2412
3517
  throw new Error("idempotency_conflict");
2413
3518
  return prior.eventId;
2414
3519
  }
2415
- if (!this.isStreaming || this._agentRunAbortRequested)
3520
+ if (!this.isStreaming || this._agentRunAbortRequested || this._managedRunStopped)
2416
3521
  throw new Error("target_settled");
2417
3522
  if (!this.hasControlContinuationCapacity)
2418
3523
  throw new Error("control_limit");
@@ -2441,32 +3546,57 @@ export class AgentSession {
2441
3546
  * Internal: Queue a steering message (already expanded, no extension command check).
2442
3547
  */
2443
3548
  async _queueSteer(text, images, autoEffortText) {
2444
- this._steeringMessages.push(text);
2445
- this._emitQueueUpdate();
2446
3549
  const content = [{ type: "text", text }];
2447
3550
  if (images) {
2448
3551
  content.push(...images);
2449
3552
  }
2450
3553
  const message = { role: "user", content, timestamp: Date.now() };
3554
+ await this._validateQueuedInput([message], this.messages);
3555
+ this._queuedUserInputs.add(message);
3556
+ this._steeringMessages.push(text);
3557
+ this._emitQueueUpdate();
2451
3558
  if (autoEffortText !== undefined)
2452
3559
  this._autoEffortInputs.set(message, autoEffortText);
3560
+ if (images?.length)
3561
+ this._queuedMessagesWithImages.add(message);
2453
3562
  this.agent.steer(message);
2454
3563
  }
2455
3564
  /**
2456
3565
  * Internal: Queue a follow-up message (already expanded, no extension command check).
2457
3566
  */
2458
3567
  async _queueFollowUp(text, images, autoEffortText) {
2459
- this._followUpMessages.push(text);
2460
- this._emitQueueUpdate();
2461
3568
  const content = [{ type: "text", text }];
2462
3569
  if (images) {
2463
3570
  content.push(...images);
2464
3571
  }
2465
3572
  const message = { role: "user", content, timestamp: Date.now() };
3573
+ await this._validateQueuedInput([message], this.messages);
3574
+ this._queuedUserInputs.add(message);
3575
+ this._followUpMessages.push(text);
3576
+ this._emitQueueUpdate();
2466
3577
  if (autoEffortText !== undefined)
2467
3578
  this._autoEffortInputs.set(message, autoEffortText);
3579
+ if (images?.length)
3580
+ this._queuedMessagesWithImages.add(message);
2468
3581
  this.agent.followUp(message);
2469
3582
  }
3583
+ /** Normalize queued images at delivery without changing the original automatic-effort input. */
3584
+ async _normalizeQueuedMessageImages(message) {
3585
+ if (typeof message.content === "string")
3586
+ return;
3587
+ const [first, ...rest] = message.content;
3588
+ if (first?.type !== "text")
3589
+ return;
3590
+ const images = rest.filter((block) => block.type === "image");
3591
+ const prepared = this._preparedImageRoute;
3592
+ const normalized = await this._normalizePromptImages(images, prepared?.selection === this.model ? prepared?.route.model : this.model);
3593
+ const text = normalized.hints.length > 0 ? `${first.text}\n\n${normalized.hints.join("\n")}` : first.text;
3594
+ message.content = [
3595
+ { type: "text", text },
3596
+ ...rest.filter((block) => block.type !== "image"),
3597
+ ...normalized.images,
3598
+ ];
3599
+ }
2470
3600
  /**
2471
3601
  * Throw an error if the text is an extension command.
2472
3602
  */
@@ -2619,6 +3749,7 @@ export class AgentSession {
2619
3749
  * Abort current operation and wait for agent to become idle.
2620
3750
  */
2621
3751
  async abort() {
3752
+ this._providerRunStopped = false;
2622
3753
  if (this._isAgentRunActive) {
2623
3754
  this._agentRunAbortRequested = true;
2624
3755
  }
@@ -2630,6 +3761,7 @@ export class AgentSession {
2630
3761
  if (this._isBeforeSettle)
2631
3762
  this._abortDuringBeforeSettle = true;
2632
3763
  this.agent.abort();
3764
+ await Promise.all(Array.from(this._bashJobOwners, (owner) => owner.abort()));
2633
3765
  await this.waitForIdle();
2634
3766
  }
2635
3767
  async waitForIdle() {
@@ -2658,22 +3790,55 @@ export class AgentSession {
2658
3790
  * @throws Error if no auth is configured for the model
2659
3791
  */
2660
3792
  async setModel(model, options = {}) {
2661
- if (!(await this._modelRuntime.checkAuth(model.provider))) {
2662
- throw new Error(`No API key for ${model.provider}/${model.id}`);
3793
+ await this._selectModel(model, options, "set");
3794
+ }
3795
+ async _selectModel(model, options, source) {
3796
+ const started = performance.now();
3797
+ let outcome = "failure";
3798
+ try {
3799
+ options.signal?.throwIfAborted();
3800
+ const revision = ++this._modelSelectionRevision;
3801
+ const reference = model.provider === HCODE_PROVIDER ? captureHcodeSelection(this._modelRuntime, model) : undefined;
3802
+ if ((source === "set" || reference) && !(await this._modelRuntime.checkAuth(model.provider))) {
3803
+ if (reference) {
3804
+ assertHcodeSelection(this._modelRuntime, model, reference);
3805
+ throw new Error(hcodeSelectionUnavailable(this._modelRuntime));
3806
+ }
3807
+ throw new Error(`No API key for ${model.provider}/${model.id}`);
3808
+ }
3809
+ options.signal?.throwIfAborted();
3810
+ if (this._disposed || revision !== this._modelSelectionRevision)
3811
+ throw new Error(reference
3812
+ ? HCODE_SELECTION_CHANGED_MESSAGE
3813
+ : "Model selection changed. Use /model to choose again. No selection was saved.");
3814
+ const previousModel = this.model;
3815
+ const thinkingLevel = this._getThinkingLevelForModelSwitch(model, options.thinkingLevel);
3816
+ if (reference) {
3817
+ assertHcodeSelection(this._modelRuntime, model, reference);
3818
+ this._assertManagedThinkingLevel(model, thinkingLevel);
3819
+ }
3820
+ // Apply model
3821
+ this.agent.state.model = model;
3822
+ markModelSelectionChosen(this.sessionManager);
3823
+ this.sessionManager.appendModelChange(model.provider, model.id);
3824
+ if (options.persist) {
3825
+ this.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
3826
+ this._addPersistedDefaultToNonEmptyScope(model);
3827
+ }
3828
+ // Apply thinking level for the new model.
3829
+ // Per-model thinking level overrides take priority over the global default.
3830
+ // Model persistence does not implicitly rewrite the global thinking default.
3831
+ this.setThinkingLevel(thinkingLevel);
3832
+ await this._emitModelSelect(model, previousModel, source);
3833
+ outcome = "success";
2663
3834
  }
2664
- const previousModel = this.model;
2665
- const thinkingLevel = this._getThinkingLevelForModelSwitch(model);
2666
- this.agent.state.model = model;
2667
- this.sessionManager.appendModelChange(model.provider, model.id);
2668
- if (options.persist) {
2669
- this.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
2670
- this._addPersistedDefaultToNonEmptyScope(model);
3835
+ finally {
3836
+ if (options.signal?.aborted)
3837
+ outcome = "cancelled";
3838
+ this._modelRuntime.metadata.feature("model", Math.round(performance.now() - started), outcome);
3839
+ if (outcome !== "success")
3840
+ this._modelRuntime.metadata.failure("model", "invalid", 0, outcome);
2671
3841
  }
2672
- // Apply thinking level for the new model.
2673
- // Per-model thinking level overrides take priority over the global default.
2674
- // Model persistence does not implicitly rewrite the global thinking default.
2675
- this.setThinkingLevel(thinkingLevel);
2676
- await this._emitModelSelect(model, previousModel, "set");
2677
3842
  }
2678
3843
  _addPersistedDefaultToNonEmptyScope(model) {
2679
3844
  if (this._scopedModels.length === 0)
@@ -2704,54 +3869,31 @@ export class AgentSession {
2704
3869
  async _cycleScopedModel(direction, options) {
2705
3870
  const availableIds = new Set(this._modelRuntime.getAvailableSnapshot().map((model) => `${model.provider}\0${model.id}`));
2706
3871
  const scopedModels = this._scopedModels.filter((scoped) => availableIds.has(`${scoped.model.provider}\0${scoped.model.id}`));
2707
- if (scopedModels.length <= 1)
2708
- return undefined;
2709
3872
  const currentModel = this.model;
2710
- let currentIndex = scopedModels.findIndex((sm) => modelsAreEqual(sm.model, currentModel));
2711
- if (currentIndex === -1)
2712
- currentIndex = 0;
2713
- const len = scopedModels.length;
2714
- const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
3873
+ const currentIndex = scopedModels.findIndex((sm) => modelsAreEqual(sm.model, currentModel));
3874
+ const nextIndex = getNextCycleIndex(currentIndex, scopedModels.length, direction);
3875
+ if (nextIndex === undefined)
3876
+ return undefined;
2715
3877
  const next = scopedModels[nextIndex];
2716
- const thinkingLevel = this._getThinkingLevelForModelSwitch(next.model, next.thinkingLevel);
2717
- // Apply model
2718
- this.agent.state.model = next.model;
2719
- this.sessionManager.appendModelChange(next.model.provider, next.model.id);
2720
- if (options.persist) {
2721
- this.settingsManager.setDefaultModelAndProvider(next.model.provider, next.model.id);
2722
- this._addPersistedDefaultToNonEmptyScope(next.model);
2723
- }
2724
3878
  // Apply thinking level for the new model.
2725
3879
  // - Explicit scoped model thinking level overrides defaults
2726
3880
  // - Per-model thinking level overrides take priority over the global default
2727
3881
  // setThinkingLevel clamps to model capabilities.
2728
3882
  // Model persistence does not implicitly rewrite the global thinking default.
2729
- this.setThinkingLevel(thinkingLevel);
2730
- await this._emitModelSelect(next.model, currentModel, "cycle");
3883
+ await this._selectModel(next.model, { ...options, thinkingLevel: options.thinkingLevel ?? next.thinkingLevel }, "cycle");
2731
3884
  return { model: next.model, thinkingLevel: this.thinkingLevel, isScoped: true };
2732
3885
  }
2733
3886
  async _cycleAvailableModel(direction, options) {
2734
3887
  const availableModels = this._modelRuntime.getAvailableSnapshot();
2735
- if (availableModels.length <= 1)
2736
- return undefined;
2737
3888
  const currentModel = this.model;
2738
- let currentIndex = availableModels.findIndex((m) => modelsAreEqual(m, currentModel));
2739
- if (currentIndex === -1)
2740
- currentIndex = 0;
2741
- const len = availableModels.length;
2742
- const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
3889
+ const currentIndex = availableModels.findIndex((m) => modelsAreEqual(m, currentModel));
3890
+ const nextIndex = getNextCycleIndex(currentIndex, availableModels.length, direction);
3891
+ if (nextIndex === undefined)
3892
+ return undefined;
2743
3893
  const nextModel = availableModels[nextIndex];
2744
- const thinkingLevel = this._getThinkingLevelForModelSwitch(nextModel);
2745
- this.agent.state.model = nextModel;
2746
- this.sessionManager.appendModelChange(nextModel.provider, nextModel.id);
2747
- if (options.persist) {
2748
- this.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);
2749
- this._addPersistedDefaultToNonEmptyScope(nextModel);
2750
- }
2751
3894
  // Apply thinking level for the new model.
2752
3895
  // Model persistence does not implicitly rewrite the global thinking default.
2753
- this.setThinkingLevel(thinkingLevel);
2754
- await this._emitModelSelect(nextModel, currentModel, "cycle");
3896
+ await this._selectModel(nextModel, options, "cycle");
2755
3897
  return { model: nextModel, thinkingLevel: this.thinkingLevel, isScoped: false };
2756
3898
  }
2757
3899
  // =========================================================================
@@ -2779,10 +3921,14 @@ export class AgentSession {
2779
3921
  this._emit({ type: "entry_appended", entry });
2780
3922
  }
2781
3923
  setManualThinkingLevel(level, options = {}) {
3924
+ if (this.model)
3925
+ this._assertManagedThinkingLevel(this.model, level);
2782
3926
  this.setAutoEffortSessionEnabled(false);
2783
3927
  this.setThinkingLevel(level, options);
2784
3928
  }
2785
3929
  setThinkingLevel(level, options = {}) {
3930
+ if (this.model)
3931
+ this._assertManagedThinkingLevel(this.model, level);
2786
3932
  this._thinkingSelectionRevision++;
2787
3933
  this._autoEffortController?.abort();
2788
3934
  const availableLevels = this.getAvailableThinkingLevels();
@@ -2846,6 +3992,10 @@ export class AgentSession {
2846
3992
  }
2847
3993
  return this.settingsManager.getDefaultThinkingLevel() ?? this.thinkingLevel ?? DEFAULT_THINKING_LEVEL;
2848
3994
  }
3995
+ _assertManagedThinkingLevel(model, level) {
3996
+ if (model.provider === HCODE_PROVIDER && !getSupportedThinkingLevels(model).includes(level))
3997
+ throw new Error(HCODE_UNSUPPORTED_THINKING_MESSAGE);
3998
+ }
2849
3999
  _clampThinkingLevel(level, _availableLevels) {
2850
4000
  return this.model ? clampThinkingLevel(this.model, level) : "off";
2851
4001
  }
@@ -3069,6 +4219,8 @@ export class AgentSession {
3069
4219
  * @returns Whether the post-run loop should call `agent.continue()` for overflow recovery or queued messages
3070
4220
  */
3071
4221
  async _checkCompaction(assistantMessage, skipAbortedCheck = true) {
4222
+ if (this._managedRecoveryStopped(assistantMessage))
4223
+ return false;
3072
4224
  if (!this.settingsManager.getCompactionEnabled())
3073
4225
  return false;
3074
4226
  // Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false
@@ -3383,6 +4535,12 @@ export class AgentSession {
3383
4535
  fromExtension,
3384
4536
  });
3385
4537
  }
4538
+ if (error instanceof ManagedSummaryStoppedError) {
4539
+ // A failed maintenance request must not start a different paid foreground request.
4540
+ if (this._isAgentRunActive)
4541
+ this._managedRunStopped = true;
4542
+ throw error;
4543
+ }
3386
4544
  return false;
3387
4545
  }
3388
4546
  finally {
@@ -3403,6 +4561,9 @@ export class AgentSession {
3403
4561
  return this.settingsManager.getCompactionEnabled();
3404
4562
  }
3405
4563
  async bindExtensions(bindings) {
4564
+ if (this._timeLimit && bindings.mode === "tui") {
4565
+ throw new Error("A time limit is only supported in headless sessions");
4566
+ }
3406
4567
  if (bindings.uiContext !== undefined) {
3407
4568
  this._extensionUIContext = bindings.uiContext;
3408
4569
  }
@@ -3422,6 +4583,7 @@ export class AgentSession {
3422
4583
  this._extensionErrorListener = bindings.onError;
3423
4584
  }
3424
4585
  this._applyExtensionBindings(this._extensionRunner);
4586
+ this._rebuildSystemPrompt(this.getActiveToolNames());
3425
4587
  await this._extensionRunner.emit(this._sessionStartEvent);
3426
4588
  await rebindSessionFlowControl(this);
3427
4589
  this._extensionRunner.reportUnhandledMcpServers();
@@ -3642,6 +4804,14 @@ export class AgentSession {
3642
4804
  sourceInfo: tool.sourceInfo,
3643
4805
  });
3644
4806
  }
4807
+ for (const { definition } of definitionRegistry.values()) {
4808
+ const original = definition === this._baseToolDefinitions.get(definition.name)
4809
+ ? this._baseToolsOverride?.[definition.name]
4810
+ : undefined;
4811
+ const owner = getBashToolOwner(original ?? definition);
4812
+ if (owner)
4813
+ this._bashJobOwners.add(owner);
4814
+ }
3645
4815
  this._toolDefinitions = definitionRegistry;
3646
4816
  this._toolPromptSnippets = new Map(Array.from(definitionRegistry.values())
3647
4817
  .map(({ definition }) => {
@@ -3656,7 +4826,28 @@ export class AgentSession {
3656
4826
  })
3657
4827
  .filter((entry) => entry !== undefined));
3658
4828
  const runner = this._extensionRunner;
3659
- const wrappedExtensionTools = wrapRegisteredTools(allCustomTools, runner);
4829
+ const observeTool = (tool, origin) => ({
4830
+ ...tool,
4831
+ execute: async (...args) => {
4832
+ const started = performance.now();
4833
+ let outcome = "failure";
4834
+ try {
4835
+ const result = await tool.execute(...args);
4836
+ outcome = result.isError ? "failure" : "success";
4837
+ return result;
4838
+ }
4839
+ finally {
4840
+ if (args[2]?.aborted)
4841
+ outcome = "cancelled";
4842
+ const duration = Math.round(performance.now() - started);
4843
+ this._modelRuntime.metadata.tool(origin, duration, outcome);
4844
+ this._modelRuntime.metadata.feature("tool", duration, outcome);
4845
+ if (outcome !== "success")
4846
+ this._modelRuntime.metadata.failure("tool", "other", 0, outcome);
4847
+ }
4848
+ },
4849
+ });
4850
+ const wrappedExtensionTools = wrapRegisteredTools(allCustomTools, runner).map((tool) => observeTool(tool, { kind: "custom" }));
3660
4851
  const wrappedBuiltInTools = wrapRegisteredTools(Array.from(this._baseToolDefinitions.values())
3661
4852
  .filter((definition) => this._isAllowedTool(definition.name))
3662
4853
  .map((definition) => ({
@@ -3664,7 +4855,9 @@ export class AgentSession {
3664
4855
  sourceInfo: createSyntheticSourceInfo(`${BUILTIN_PATH_PREFIX}${definition.name}`, {
3665
4856
  source: "builtin",
3666
4857
  }),
3667
- })), runner);
4858
+ })), runner).map((tool) => observeTool(tool, this._baseToolsOverride
4859
+ ? { kind: "custom" }
4860
+ : { kind: "native", tool: NATIVE_TOOL_METADATA[tool.name] ?? "other" }));
3668
4861
  const toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));
3669
4862
  for (const tool of wrappedExtensionTools) {
3670
4863
  toolRegistry.set(tool.name, tool);
@@ -3718,6 +4911,11 @@ export class AgentSession {
3718
4911
  const autoResizeImages = this.settingsManager.getImageAutoResize();
3719
4912
  const shellCommandPrefix = this.settingsManager.getShellCommandPrefix();
3720
4913
  const shellPath = this.settingsManager.getShellPath();
4914
+ const timeLimit = this._timeLimit;
4915
+ const bashOperations = createLocalBashOperations({
4916
+ shellPath,
4917
+ onProcessStarted: (child, custody) => this._bashJobs.ownProcess(child, custody),
4918
+ });
3721
4919
  const baseToolDefinitions = this._baseToolsOverride
3722
4920
  ? Object.fromEntries(Object.entries(this._baseToolsOverride).map(([name, tool]) => [
3723
4921
  name,
@@ -3725,7 +4923,26 @@ export class AgentSession {
3725
4923
  ]))
3726
4924
  : createAllToolDefinitions(this._cwd, {
3727
4925
  read: { autoResizeImages },
3728
- bash: { commandPrefix: shellCommandPrefix, shellPath },
4926
+ bash: {
4927
+ operations: {
4928
+ ...bashOperations,
4929
+ exec: (command, cwd, options) => {
4930
+ const qualified = this._adaptiveHost?.qualifyShellExecution(command);
4931
+ return qualified
4932
+ ? bashOperations.exec(qualified.command, cwd, { ...options, env: qualified.env })
4933
+ : bashOperations.exec(command, cwd, options);
4934
+ },
4935
+ },
4936
+ jobs: this._bashJobs,
4937
+ getRunContext: () => this._adaptiveHost?.runContext,
4938
+ outputHeadTail: this.settingsManager.getBashOutputHeadTail(),
4939
+ outputCleanup: this.settingsManager.getBashOutputCleanup(),
4940
+ commandPrefix: shellCommandPrefix,
4941
+ shellPath,
4942
+ getRemainingTimeSeconds: timeLimit
4943
+ ? () => timeLimit.seconds - (Date.now() - timeLimit.startedAt) / 1000
4944
+ : undefined,
4945
+ },
3729
4946
  });
3730
4947
  this._baseToolDefinitions = new Map(Object.entries(baseToolDefinitions).map(([name, tool]) => [name, tool]));
3731
4948
  const extensionsResult = this._resourceLoader.getExtensions();
@@ -3742,7 +4959,7 @@ export class AgentSession {
3742
4959
  this._applyExtensionBindings(this._extensionRunner);
3743
4960
  const defaultActiveToolNames = this._baseToolsOverride
3744
4961
  ? Object.keys(this._baseToolsOverride)
3745
- : ["read", "bash", "edit", "write", "subagent"];
4962
+ : ["read", "bash", "jobs", "edit", "write", "subagent"];
3746
4963
  const baseActiveToolNames = options.activeToolNames ?? defaultActiveToolNames;
3747
4964
  this._refreshToolRegistry({
3748
4965
  activeToolNames: baseActiveToolNames,
@@ -3750,6 +4967,12 @@ export class AgentSession {
3750
4967
  });
3751
4968
  }
3752
4969
  async reload(options) {
4970
+ if (this.isStreaming) {
4971
+ throw new Error("Wait for the current response to finish before reloading.");
4972
+ }
4973
+ if (this.isCompacting) {
4974
+ throw new Error("Wait for compaction to finish before reloading.");
4975
+ }
3753
4976
  const oldRunner = this._extensionRunner;
3754
4977
  const previousFlagValues = oldRunner.getFlagValues();
3755
4978
  await closeSessionFlowControl(this);
@@ -3795,6 +5018,8 @@ export class AgentSession {
3795
5018
  * Context overflow errors are NOT retryable (handled by compaction instead).
3796
5019
  */
3797
5020
  _isRetryableError(message) {
5021
+ if (this._managedRecoveryStopped(message))
5022
+ return false;
3798
5023
  // Context overflow is handled by compaction, not retry.
3799
5024
  if (isContextOverflow(message, (this._modelForMessage(message) ?? this.model)?.contextWindow ?? 0))
3800
5025
  return false;
@@ -3861,6 +5086,8 @@ export class AgentSession {
3861
5086
  * Queued steering and follow-up messages stay queued.
3862
5087
  */
3863
5088
  _stopRunForOAuth() {
5089
+ if (!this._agentRunAbortRequested)
5090
+ this._providerRunStopped = true;
3864
5091
  if (this._isAgentRunActive)
3865
5092
  this._agentRunAbortRequested = true;
3866
5093
  this._oauthRequestAccount = undefined;
@@ -3996,6 +5223,8 @@ export class AgentSession {
3996
5223
  * `oauth_account_switch_failed` when the pool itself failed (the account stays retryable).
3997
5224
  */
3998
5225
  async _tryOAuthAccountFailover(message) {
5226
+ if (this._managedRecoveryStopped(message))
5227
+ return false;
3999
5228
  const model = this._modelForMessage(message);
4000
5229
  const retried = await this._attemptOAuthAccountFailover(message);
4001
5230
  if (retried) {
@@ -4385,6 +5614,8 @@ export class AgentSession {
4385
5614
  * handled below without attributing the response to the mutable active account.
4386
5615
  */
4387
5616
  async _tryOAuthCreditsRotation(message) {
5617
+ if (this._responseTargets.get(message)?.target.kind === "managed")
5618
+ return;
4388
5619
  const runSignal = this._agentRunAbortController?.signal;
4389
5620
  const servedKey = this._oauthServedAccountKey;
4390
5621
  this._oauthServedAccountKey = undefined;
@@ -4531,6 +5762,8 @@ export class AgentSession {
4531
5762
  * @returns true if the caller should continue the agent, false otherwise
4532
5763
  */
4533
5764
  async _prepareRetry(message) {
5765
+ if (this._managedRecoveryStopped(message))
5766
+ return false;
4534
5767
  const settings = this.settingsManager.getRetrySettings();
4535
5768
  if (!settings.enabled) {
4536
5769
  return false;
@@ -4606,7 +5839,8 @@ export class AgentSession {
4606
5839
  const shellPath = this.settingsManager.getShellPath();
4607
5840
  const resolvedCommand = prefix ? `${prefix}\n${command}` : command;
4608
5841
  try {
4609
- const result = await executeBashWithOperations(resolvedCommand, this.sessionManager.getCwd(), options?.operations ?? createLocalBashOperations({ shellPath }), {
5842
+ const result = await executeBashWithOperations(resolvedCommand, this.sessionManager.getCwd(), options?.operations ??
5843
+ createLocalBashOperations({ shellPath, onProcessStarted: (child) => this._bashJobs.ownProcess(child) }), {
4610
5844
  onChunk: (delta) => {
4611
5845
  onChunk?.(delta);
4612
5846
  this._emit({ type: "bash_execution_update", id: options?.id, delta });
@@ -4702,7 +5936,7 @@ export class AgentSession {
4702
5936
  * @returns Result with editorText (if user message) and cancelled status
4703
5937
  */
4704
5938
  async navigateTree(targetId, options = {}) {
4705
- if (this.isStreaming) {
5939
+ if (this.isStreaming || this._promptPreflightCount > 0) {
4706
5940
  throw new Error("Wait for the current response to finish before navigating the session tree.");
4707
5941
  }
4708
5942
  if (this.isCompacting) {
@@ -4738,7 +5972,8 @@ export class AgentSession {
4738
5972
  label,
4739
5973
  };
4740
5974
  // Set up abort controller for summarization
4741
- this._branchSummaryAbortController = new AbortController();
5975
+ const abortController = new AbortController();
5976
+ this._branchSummaryAbortController = abortController;
4742
5977
  try {
4743
5978
  let extensionSummary;
4744
5979
  let fromExtension = false;
@@ -4747,7 +5982,7 @@ export class AgentSession {
4747
5982
  const result = (await this._extensionRunner.emit({
4748
5983
  type: "session_before_tree",
4749
5984
  preparation,
4750
- signal: this._branchSummaryAbortController.signal,
5985
+ signal: abortController.signal,
4751
5986
  }));
4752
5987
  if (result?.cancel) {
4753
5988
  return { cancelled: true };
@@ -4773,7 +6008,7 @@ export class AgentSession {
4773
6008
  let summaryUsage;
4774
6009
  const usageEntryIds = [];
4775
6010
  if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
4776
- const signal = this._branchSummaryAbortController.signal;
6011
+ const signal = abortController.signal;
4777
6012
  const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
4778
6013
  const result = await this._observeRequests("branch-summary", async () => generateBranchSummary(entriesToSummarize, {
4779
6014
  ...(await this._getSummarizationRequestAuth(this.model, signal)),
@@ -4847,7 +6082,8 @@ export class AgentSession {
4847
6082
  // Update finalized context from the canonical session projection.
4848
6083
  this._refreshFinalizedContext();
4849
6084
  this._restoreToolsFromTranscript();
4850
- // Emit session_tree event
6085
+ // The selected context is installed; session_tree handlers may now prompt or navigate again.
6086
+ this._branchSummaryAbortController = undefined;
4851
6087
  await this._extensionRunner.emit({
4852
6088
  type: "session_tree",
4853
6089
  newLeafId: this.sessionManager.getLeafId(),
@@ -4859,7 +6095,10 @@ export class AgentSession {
4859
6095
  return { editorText, cancelled: false, summaryEntry };
4860
6096
  }
4861
6097
  finally {
4862
- this._branchSummaryAbortController = undefined;
6098
+ // A navigation started from session_tree owns the controller now; do not clear it.
6099
+ if (this._branchSummaryAbortController === abortController) {
6100
+ this._branchSummaryAbortController = undefined;
6101
+ }
4863
6102
  this._resolveIdleWaitIfIdle();
4864
6103
  }
4865
6104
  }
@@ -4994,8 +6233,8 @@ export class AgentSession {
4994
6233
  throw new Error("No model selected");
4995
6234
  }
4996
6235
  return this._observeRequests("bug-report", async () => generateBugReportSummary({
4997
- ...(await this._getSummarizationRequestAuth(model, options.signal)),
4998
- messages: this.messages,
6236
+ ...(await this._getSummarizationRequestAuth(model, options.signal, options.conversation.messages)),
6237
+ messages: options.conversation.messages,
4999
6238
  hint: options.hint,
5000
6239
  signal: options.signal,
5001
6240
  streamFn: this._auxiliaryStreamFunction,
@@ -5033,6 +6272,12 @@ export class AgentSession {
5033
6272
  text += content.text;
5034
6273
  }
5035
6274
  }
6275
+ const assistantIndex = this.messages.indexOf(lastAssistant);
6276
+ const report = this.messages
6277
+ .slice(assistantIndex + 1)
6278
+ .findLast((message) => message.role === "custom" && message.customType === "acceptance-settlement");
6279
+ if (report?.role === "custom")
6280
+ text += `\n\n${contentText(report.content, "")}`;
5036
6281
  return text.trim() || undefined;
5037
6282
  }
5038
6283
  // =========================================================================