@humain/humain-code 0.7.0 → 0.8.1

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 (735) hide show
  1. package/CHANGELOG.md +160 -0
  2. package/README.md +2 -2
  3. package/dist/bundle/agent-monitor.js +1 -1
  4. package/dist/bundle/chunks/anthropic-messages-XFCDMGD6.js +77 -0
  5. package/dist/bundle/chunks/anthropic.js +25 -24
  6. package/dist/bundle/chunks/azure-openai-responses-F4KQM3NK.js +15 -0
  7. package/dist/bundle/chunks/bedrock-converse-stream.js +460 -431
  8. package/dist/bundle/chunks/bowser-DXKSTXFQ.js +89 -0
  9. package/dist/bundle/chunks/{chunk-2G7YVAVF.js → chunk-2JNJJ6SZ.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-HTA325LJ.js → chunk-2NVGOSBN.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-5B25YXF7.js → chunk-3CGMVKHA.js} +13 -3
  12. package/dist/bundle/chunks/{chunk-SCINMV4X.js → chunk-46C6D7UC.js} +22 -21
  13. package/dist/bundle/chunks/chunk-4MKATHT2.js +24 -0
  14. package/dist/bundle/chunks/{chunk-TGDPZCSW.js → chunk-4TDNOR36.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-C6VERWRZ.js → chunk-4XF5JX7X.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-4HTVBBJD.js → chunk-65FLSKDA.js} +2 -2
  17. package/dist/bundle/chunks/chunk-6HTHDVJC.js +4 -0
  18. package/dist/bundle/chunks/{chunk-4PRNKB6V.js → chunk-6P6MMQUH.js} +7 -7
  19. package/dist/bundle/chunks/{chunk-66FZJO75.js → chunk-6TTMNQXI.js} +472 -3924
  20. package/dist/bundle/chunks/{chunk-32QLLD2P.js → chunk-6YVORXTX.js} +410 -352
  21. package/dist/bundle/chunks/chunk-7H2WNBX7.js +11 -0
  22. package/dist/bundle/chunks/{chunk-2FYYW6FY.js → chunk-7OZNMWAJ.js} +1 -1
  23. package/dist/bundle/chunks/{chunk-R6YQR7TZ.js → chunk-7WE77IE3.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-Z5YLKK3S.js → chunk-7WETECIB.js} +1 -1
  25. package/dist/bundle/chunks/chunk-7X6DNT45.js +78 -0
  26. package/dist/bundle/chunks/{chunk-KRCX3ZBA.js → chunk-APNPBT7Y.js} +1 -1
  27. package/dist/bundle/chunks/{chunk-R5OOX7RW.js → chunk-B47PNNLL.js} +9 -2
  28. package/dist/bundle/chunks/{chunk-PPBDDQHP.js → chunk-CQ2CE3RB.js} +7 -6
  29. package/dist/bundle/chunks/{chunk-MD7K7RPN.js → chunk-D3KYOSQY.js} +1 -1
  30. package/dist/bundle/chunks/{chunk-I3NDOUHE.js → chunk-DCXHRP6C.js} +1 -1
  31. package/dist/bundle/chunks/{chunk-OB332KMV.js → chunk-DD5UT56Y.js} +46 -32
  32. package/dist/bundle/chunks/{chunk-I5E7RQ5V.js → chunk-DJG2WUNM.js} +5 -5
  33. package/dist/bundle/chunks/{chunk-4QAXV5T6.js → chunk-E7OBH44W.js} +9 -9
  34. package/dist/bundle/chunks/{chunk-Q7VXYXY3.js → chunk-ENBDASDN.js} +2 -2
  35. package/dist/bundle/chunks/{chunk-RS6PZK35.js → chunk-F2H47FRF.js} +249 -216
  36. package/dist/bundle/chunks/{chunk-2H3LUS62.js → chunk-FJIISX5W.js} +241 -229
  37. package/dist/bundle/chunks/chunk-FQ4KS5S4.js +23 -0
  38. package/dist/bundle/chunks/{chunk-SSRCVJZK.js → chunk-GPLWWO5Q.js} +5 -5
  39. package/dist/bundle/chunks/{chunk-WQOOJP7U.js → chunk-GV5OVRKK.js} +1 -1
  40. package/dist/bundle/chunks/{chunk-KTSJYIYC.js → chunk-HHWVVNGG.js} +1 -1
  41. package/dist/bundle/chunks/{chunk-4JRER4XK.js → chunk-HQMUDHC3.js} +19 -19
  42. package/dist/bundle/chunks/{chunk-G4QPSFBF.js → chunk-IMUFBWEK.js} +216 -223
  43. package/dist/bundle/chunks/{chunk-RU7ADKA7.js → chunk-J4GII2EE.js} +112 -96
  44. package/dist/bundle/chunks/{chunk-QT6ZHDMP.js → chunk-JBSWWCT5.js} +1 -1
  45. package/dist/bundle/chunks/{chunk-PWUDFU5V.js → chunk-JWOPWHVH.js} +4 -4
  46. package/dist/bundle/chunks/{chunk-AEWYICBL.js → chunk-KI7CHPWC.js} +2 -2
  47. package/dist/bundle/chunks/{chunk-4V5VL2BO.js → chunk-KLSRGGOH.js} +131 -154
  48. package/dist/bundle/chunks/{chunk-JF7FYXAI.js → chunk-KONLZKPL.js} +7 -6
  49. package/dist/bundle/chunks/{chunk-N2SNMUD3.js → chunk-KRBELWQH.js} +1 -1
  50. package/dist/bundle/chunks/{chunk-UZNIPOGS.js → chunk-L4J7SMJB.js} +1 -1
  51. package/dist/bundle/chunks/{chunk-EIC7CQX3.js → chunk-LSRXA7OS.js} +1 -1
  52. package/dist/bundle/chunks/{chunk-GRJUKEE3.js → chunk-MIAXMK5F.js} +4 -4
  53. package/dist/bundle/chunks/chunk-MPRAQ6ZI.js +41 -0
  54. package/dist/bundle/chunks/{chunk-GUHNFZ2Q.js → chunk-NICPFMOP.js} +20 -19
  55. package/dist/bundle/chunks/{chunk-WAPZN4KP.js → chunk-P2Y2H7SD.js} +2 -2
  56. package/dist/bundle/chunks/{chunk-T7BXP46S.js → chunk-P42E6YY6.js} +1892 -1680
  57. package/dist/bundle/chunks/{chunk-3EDMWQ35.js → chunk-PFBAIRCY.js} +17 -15
  58. package/dist/bundle/chunks/{chunk-XHDVDJM7.js → chunk-PVNXN2TC.js} +7 -7
  59. package/dist/bundle/chunks/{chunk-TWAHPPXN.js → chunk-PWFM6AQQ.js} +1307 -1194
  60. package/dist/bundle/chunks/{chunk-RNBZBCH2.js → chunk-QJB5YI3I.js} +1 -1
  61. package/dist/bundle/chunks/{chunk-P6AXBESH.js → chunk-QRRVZYTG.js} +1119 -1098
  62. package/dist/bundle/chunks/{chunk-WQ7EJQIT.js → chunk-ROFZVEFN.js} +247 -250
  63. package/dist/bundle/chunks/chunk-SKCJ25SX.js +24 -0
  64. package/dist/bundle/chunks/{chunk-AZXVJN6E.js → chunk-SXOIQWNX.js} +1 -1
  65. package/dist/bundle/chunks/{chunk-6E6RHNOU.js → chunk-UXM4WFLH.js} +12 -11
  66. package/dist/bundle/chunks/{chunk-LB4CIS4F.js → chunk-VCMXBP5S.js} +17 -17
  67. package/dist/bundle/chunks/{chunk-JYWUOKOI.js → chunk-WBSGWISD.js} +367 -353
  68. package/dist/bundle/chunks/chunk-XZ7FTBXS.js +2102 -0
  69. package/dist/bundle/chunks/chunk-YSWDFV2L.js +11 -0
  70. package/dist/bundle/chunks/chunk-ZG74NES2.js +2 -0
  71. package/dist/bundle/chunks/chunk-ZTG5OKI7.js +3 -0
  72. package/dist/bundle/chunks/{cli-H4LJNE2V.js → cli-6DJO467D.js} +2 -2
  73. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-T5R2RVFQ.js → cloudflare-workers-ai-system-one-JEZVYITT.js} +1 -1
  74. package/dist/bundle/chunks/codemode-worker.js +68 -68
  75. package/dist/bundle/chunks/compat-SRCNS6OQ.js +15 -0
  76. package/dist/bundle/chunks/curator-server-QB4GITGS.js +3600 -0
  77. package/dist/bundle/chunks/dist-35STTNYA.js +37 -0
  78. package/dist/bundle/chunks/{dist-FMWWM4H7.js → dist-4OMLHRJE.js} +2 -2
  79. package/dist/bundle/chunks/dist-CBODG4CA.js +11 -0
  80. package/dist/bundle/chunks/{dist-NHQTBDHT.js → dist-TRAK7EXI.js} +91 -257
  81. package/dist/bundle/chunks/dist-cjs-EROMDUKS.js +193 -0
  82. package/dist/bundle/chunks/{easter-egg-3d-BUEOC3NO.js → easter-egg-3d-VVUF3C3X.js} +1 -1
  83. package/dist/bundle/chunks/entry-2GZ3PTWQ.js +2 -0
  84. package/dist/bundle/chunks/{entry-A2CSLKHC.js → entry-SRYLSS5P.js} +3 -3
  85. package/dist/bundle/chunks/{event-streams-7YGFEPBZ.js → event-streams-F67JLS6B.js} +1 -1
  86. package/dist/bundle/chunks/{execute-MY5JSEPV.js → execute-I3WGGPWL.js} +2 -2
  87. package/dist/bundle/chunks/{extract-PTGACPGP.js → extract-L373D6O7.js} +68 -65
  88. package/dist/bundle/chunks/{flow-implementer-APJFY4YI.js → flow-implementer-4KO3Q4B5.js} +8 -9
  89. package/dist/bundle/chunks/github-copilot.js +53 -46
  90. package/dist/bundle/chunks/google-generative-ai-WIASMWS3.js +22 -0
  91. package/dist/bundle/chunks/google-vertex-WSPHRZIZ.js +25 -0
  92. package/dist/bundle/chunks/host-WOLZCWQQ.js +3 -0
  93. package/dist/bundle/chunks/image-resize-worker.js +3 -3
  94. package/dist/bundle/chunks/{index.bundle-THL4EUSU.js → index.bundle-HONF3PUD.js} +177 -176
  95. package/dist/bundle/chunks/{inprocess-5NP5VJHZ.js → inprocess-TOBRVK4C.js} +6 -6
  96. package/dist/bundle/chunks/interactive-mode-BJJKPBXD.js +5 -0
  97. package/dist/bundle/chunks/{llama-cpp-classify-GJAXULWL.js → llama-cpp-classify-KYZT532X.js} +1 -1
  98. package/dist/bundle/chunks/mistral-conversations-7JYDDRUT.js +43 -0
  99. package/dist/bundle/chunks/{node-UNHECG4X.js → node-MHHE76P4.js} +475 -440
  100. package/dist/bundle/chunks/{node-ZFIIS5IM.js → node-N7TPBUJB.js} +53 -30
  101. package/dist/bundle/chunks/{openai-codex-responses-S7CMCAOY.js → openai-codex-responses-7PAML4NF.js} +30 -29
  102. package/dist/bundle/chunks/openai-codex.js +9 -8
  103. package/dist/bundle/chunks/{openai-completions-2Z57N7PC.js → openai-completions-UJDAIGTK.js} +22 -22
  104. package/dist/bundle/chunks/{openai-decisions-JIOJDB4C.js → openai-decisions-JMSDGR7K.js} +1 -1
  105. package/dist/bundle/chunks/{openai-responses-5VBZSTHL.js → openai-responses-2WNCE6AY.js} +4 -5
  106. package/dist/bundle/chunks/{openrouter-images-S6O7DBEJ.js → openrouter-images-V3UCCO6X.js} +1 -1
  107. package/dist/bundle/chunks/openrouter.js +9 -8
  108. package/dist/bundle/chunks/pdfjs-FE3L72A6.js +3662 -0
  109. package/dist/bundle/chunks/{pdfjs-decoders-OFXX4HDZ.js → pdfjs-decoders-VCMCTQJ2.js} +1 -1
  110. package/dist/bundle/chunks/pdfjs-jbig2_nowasm_fallback-I4K6AIV4.js +295 -0
  111. package/dist/bundle/chunks/pdfjs-openjpeg-PYQCV6CM.js +590 -0
  112. package/dist/bundle/chunks/pdfjs-openjpeg_nowasm_fallback-G363SGDI.js +775 -0
  113. package/dist/bundle/chunks/{pi-messages-SMLN5J2W.js → pi-messages-TQ7LJUNQ.js} +11 -11
  114. package/dist/bundle/chunks/radius.js +8 -7
  115. package/dist/bundle/chunks/{runtime-OYTWXIUM.js → runtime-H7LYNKCZ.js} +1 -1
  116. package/dist/bundle/chunks/session-picker-4JQEGLDD.js +4 -0
  117. package/dist/bundle/chunks/startup-ui-AKTA4NDP.js +3 -0
  118. package/dist/bundle/chunks/{trace-command-YLDYCL55.js → trace-command-7ORDQ3JS.js} +4 -4
  119. package/dist/bundle/chunks/{typesafe-system-one-7BEL3H5N.js → typesafe-system-one-YP7GGN4C.js} +1 -1
  120. package/dist/bundle/chunks/{undici-C6S56CGI.js → undici-WVNE45GY.js} +1 -1
  121. package/dist/bundle/chunks/virtual-modules-3CT5BMBA.js +28 -0
  122. package/dist/bundle/cli-runtime.js +5 -5
  123. package/dist/bundle/flow/package.json +5 -5
  124. package/dist/bundle/index.js +13 -13
  125. package/dist/bundle/orchestrate/package.json +22 -6
  126. package/dist/bundle/rpc-entry.js +4 -5
  127. package/dist/cli/args.d.ts.map +1 -1
  128. package/dist/cli/args.js +4 -3
  129. package/dist/cli/args.js.map +1 -1
  130. package/dist/cli/config-selector.d.ts.map +1 -1
  131. package/dist/cli/config-selector.js +9 -6
  132. package/dist/cli/config-selector.js.map +1 -1
  133. package/dist/cli/list-models.d.ts.map +1 -1
  134. package/dist/cli/list-models.js +16 -1
  135. package/dist/cli/list-models.js.map +1 -1
  136. package/dist/cli/session-picker.d.ts.map +1 -1
  137. package/dist/cli/session-picker.js +9 -6
  138. package/dist/cli/session-picker.js.map +1 -1
  139. package/dist/cli/setup.d.ts +1 -1
  140. package/dist/cli/setup.d.ts.map +1 -1
  141. package/dist/cli/setup.js +3 -2
  142. package/dist/cli/setup.js.map +1 -1
  143. package/dist/cli/startup-ui.d.ts.map +1 -1
  144. package/dist/cli/startup-ui.js +8 -4
  145. package/dist/cli/startup-ui.js.map +1 -1
  146. package/dist/cli.js.map +1 -1
  147. package/dist/core/agent-session-runtime.d.ts +14 -0
  148. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  149. package/dist/core/agent-session-runtime.js +30 -2
  150. package/dist/core/agent-session-runtime.js.map +1 -1
  151. package/dist/core/agent-session-services.d.ts +0 -2
  152. package/dist/core/agent-session-services.d.ts.map +1 -1
  153. package/dist/core/agent-session-services.js +0 -2
  154. package/dist/core/agent-session-services.js.map +1 -1
  155. package/dist/core/agent-session.d.ts +31 -39
  156. package/dist/core/agent-session.d.ts.map +1 -1
  157. package/dist/core/agent-session.js +231 -535
  158. package/dist/core/agent-session.js.map +1 -1
  159. package/dist/core/anthropic-subscription-usage.d.ts +4 -2
  160. package/dist/core/anthropic-subscription-usage.d.ts.map +1 -1
  161. package/dist/core/anthropic-subscription-usage.js +32 -16
  162. package/dist/core/anthropic-subscription-usage.js.map +1 -1
  163. package/dist/core/auto-session-namer.js +1 -1
  164. package/dist/core/auto-session-namer.js.map +1 -1
  165. package/dist/core/cache-warmer.d.ts.map +1 -1
  166. package/dist/core/cache-warmer.js +2 -0
  167. package/dist/core/cache-warmer.js.map +1 -1
  168. package/dist/core/exec.d.ts +1 -0
  169. package/dist/core/exec.d.ts.map +1 -1
  170. package/dist/core/exec.js +4 -1
  171. package/dist/core/exec.js.map +1 -1
  172. package/dist/core/export-html/ansi-to-html.d.ts +6 -1
  173. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
  174. package/dist/core/export-html/ansi-to-html.js +57 -20
  175. package/dist/core/export-html/ansi-to-html.js.map +1 -1
  176. package/dist/core/export-html/template.js +1 -1
  177. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  178. package/dist/core/export-html/tool-renderer.js +2 -3
  179. package/dist/core/export-html/tool-renderer.js.map +1 -1
  180. package/dist/core/extensions/loader.d.ts.map +1 -1
  181. package/dist/core/extensions/loader.js +18 -1
  182. package/dist/core/extensions/loader.js.map +1 -1
  183. package/dist/core/extensions/runner.d.ts.map +1 -1
  184. package/dist/core/extensions/runner.js +5 -0
  185. package/dist/core/extensions/runner.js.map +1 -1
  186. package/dist/core/extensions/types.d.ts +5 -0
  187. package/dist/core/extensions/types.d.ts.map +1 -1
  188. package/dist/core/extensions/types.js.map +1 -1
  189. package/dist/core/flow-implementer.d.ts.map +1 -1
  190. package/dist/core/flow-implementer.js +3 -9
  191. package/dist/core/flow-implementer.js.map +1 -1
  192. package/dist/core/keybindings.d.ts +64 -0
  193. package/dist/core/keybindings.d.ts.map +1 -1
  194. package/dist/core/keybindings.js +8 -0
  195. package/dist/core/keybindings.js.map +1 -1
  196. package/dist/core/model-config.d.ts +13 -0
  197. package/dist/core/model-config.d.ts.map +1 -1
  198. package/dist/core/model-registry.d.ts +3 -0
  199. package/dist/core/model-registry.d.ts.map +1 -1
  200. package/dist/core/model-registry.js +44 -9
  201. package/dist/core/model-registry.js.map +1 -1
  202. package/dist/core/model-resolver.d.ts +0 -1
  203. package/dist/core/model-resolver.d.ts.map +1 -1
  204. package/dist/core/model-resolver.js +14 -17
  205. package/dist/core/model-resolver.js.map +1 -1
  206. package/dist/core/model-runtime.d.ts +28 -8
  207. package/dist/core/model-runtime.d.ts.map +1 -1
  208. package/dist/core/model-runtime.js +64 -14
  209. package/dist/core/model-runtime.js.map +1 -1
  210. package/dist/core/oauth-account-pool.d.ts +9 -0
  211. package/dist/core/oauth-account-pool.d.ts.map +1 -1
  212. package/dist/core/oauth-account-pool.js +138 -23
  213. package/dist/core/oauth-account-pool.js.map +1 -1
  214. package/dist/core/package-manager.d.ts +16 -0
  215. package/dist/core/package-manager.d.ts.map +1 -1
  216. package/dist/core/package-manager.js +46 -3
  217. package/dist/core/package-manager.js.map +1 -1
  218. package/dist/core/pi-ai-schemas.d.ts +1 -0
  219. package/dist/core/pi-ai-schemas.d.ts.map +1 -1
  220. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  221. package/dist/core/remote-catalog-provider.js +7 -0
  222. package/dist/core/remote-catalog-provider.js.map +1 -1
  223. package/dist/core/resource-loader.d.ts +5 -1
  224. package/dist/core/resource-loader.d.ts.map +1 -1
  225. package/dist/core/resource-loader.js +2 -0
  226. package/dist/core/resource-loader.js.map +1 -1
  227. package/dist/core/run-outcome.d.ts +6 -3
  228. package/dist/core/run-outcome.d.ts.map +1 -1
  229. package/dist/core/run-outcome.js +36 -9
  230. package/dist/core/run-outcome.js.map +1 -1
  231. package/dist/core/run-preflight.d.ts +1 -1
  232. package/dist/core/run-preflight.d.ts.map +1 -1
  233. package/dist/core/run-preflight.js +19 -11
  234. package/dist/core/run-preflight.js.map +1 -1
  235. package/dist/core/sdk.d.ts +0 -6
  236. package/dist/core/sdk.d.ts.map +1 -1
  237. package/dist/core/sdk.js +9 -18
  238. package/dist/core/sdk.js.map +1 -1
  239. package/dist/core/settings-manager.d.ts +0 -5
  240. package/dist/core/settings-manager.d.ts.map +1 -1
  241. package/dist/core/settings-manager.js +0 -9
  242. package/dist/core/settings-manager.js.map +1 -1
  243. package/dist/core/settings-schema.d.ts +0 -4
  244. package/dist/core/settings-schema.d.ts.map +1 -1
  245. package/dist/core/settings-schema.js +0 -1
  246. package/dist/core/settings-schema.js.map +1 -1
  247. package/dist/core/slash-commands.d.ts.map +1 -1
  248. package/dist/core/slash-commands.js +1 -0
  249. package/dist/core/slash-commands.js.map +1 -1
  250. package/dist/core/tools/bash-jobs.d.ts.map +1 -1
  251. package/dist/core/tools/bash-jobs.js +2 -9
  252. package/dist/core/tools/bash-jobs.js.map +1 -1
  253. package/dist/core/tools/find.d.ts.map +1 -1
  254. package/dist/core/tools/find.js +28 -16
  255. package/dist/core/tools/find.js.map +1 -1
  256. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  257. package/dist/core/tools/output-accumulator.js +4 -1
  258. package/dist/core/tools/output-accumulator.js.map +1 -1
  259. package/dist/core/tools/read.d.ts +8 -4
  260. package/dist/core/tools/read.d.ts.map +1 -1
  261. package/dist/core/tools/read.js +10 -15
  262. package/dist/core/tools/read.js.map +1 -1
  263. package/dist/core/tools/renderers/read.d.ts.map +1 -1
  264. package/dist/core/tools/renderers/read.js +6 -2
  265. package/dist/core/tools/renderers/read.js.map +1 -1
  266. package/dist/core/tools/subagent-worktree.d.ts.map +1 -1
  267. package/dist/core/tools/subagent-worktree.js +2 -10
  268. package/dist/core/tools/subagent-worktree.js.map +1 -1
  269. package/dist/core/trace-client/credential-store.d.ts.map +1 -1
  270. package/dist/core/trace-client/credential-store.js +9 -5
  271. package/dist/core/trace-client/credential-store.js.map +1 -1
  272. package/dist/extensions/codemode/execute.js +2 -2
  273. package/dist/extensions/codemode/execute.js.map +1 -1
  274. package/dist/extensions/llama/provider.d.ts +1 -1
  275. package/dist/extensions/llama/provider.d.ts.map +1 -1
  276. package/dist/extensions/llama/provider.js +6 -4
  277. package/dist/extensions/llama/provider.js.map +1 -1
  278. package/dist/extensions/usage/account-reconnect.d.ts +5 -0
  279. package/dist/extensions/usage/account-reconnect.d.ts.map +1 -0
  280. package/dist/extensions/usage/account-reconnect.js +12 -0
  281. package/dist/extensions/usage/account-reconnect.js.map +1 -0
  282. package/dist/extensions/usage/confirmation.d.ts.map +1 -1
  283. package/dist/extensions/usage/confirmation.js +1 -1
  284. package/dist/extensions/usage/confirmation.js.map +1 -1
  285. package/dist/extensions/usage/hcode-overview.d.ts +6 -19
  286. package/dist/extensions/usage/hcode-overview.d.ts.map +1 -1
  287. package/dist/extensions/usage/hcode-overview.js +86 -100
  288. package/dist/extensions/usage/hcode-overview.js.map +1 -1
  289. package/dist/extensions/usage/index.d.ts.map +1 -1
  290. package/dist/extensions/usage/index.js +75 -99
  291. package/dist/extensions/usage/index.js.map +1 -1
  292. package/dist/extensions/usage/overview.d.ts +22 -17
  293. package/dist/extensions/usage/overview.d.ts.map +1 -1
  294. package/dist/extensions/usage/overview.js +98 -13
  295. package/dist/extensions/usage/overview.js.map +1 -1
  296. package/dist/extensions/usage/panes.d.ts +5 -0
  297. package/dist/extensions/usage/panes.d.ts.map +1 -0
  298. package/dist/extensions/usage/panes.js +10 -0
  299. package/dist/extensions/usage/panes.js.map +1 -0
  300. package/dist/extensions/usage/popup.d.ts +9 -14
  301. package/dist/extensions/usage/popup.d.ts.map +1 -1
  302. package/dist/extensions/usage/popup.js +87 -183
  303. package/dist/extensions/usage/popup.js.map +1 -1
  304. package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +4 -1
  305. package/dist/humain/flow-command.js +1 -1
  306. package/dist/humain/flow-command.js.map +1 -1
  307. package/dist/humain/flow-loader.d.ts +9 -4
  308. package/dist/humain/flow-loader.d.ts.map +1 -1
  309. package/dist/humain/flow-loader.js +30 -21
  310. package/dist/humain/flow-loader.js.map +1 -1
  311. package/dist/humain/gateway/client.d.ts +3 -1
  312. package/dist/humain/gateway/client.d.ts.map +1 -1
  313. package/dist/humain/gateway/client.js +10 -5
  314. package/dist/humain/gateway/client.js.map +1 -1
  315. package/dist/humain/gateway/login.d.ts.map +1 -1
  316. package/dist/humain/gateway/login.js +160 -53
  317. package/dist/humain/gateway/login.js.map +1 -1
  318. package/dist/humain/hcode/account-store.d.ts +29 -5
  319. package/dist/humain/hcode/account-store.d.ts.map +1 -1
  320. package/dist/humain/hcode/account-store.js +224 -124
  321. package/dist/humain/hcode/account-store.js.map +1 -1
  322. package/dist/humain/hcode/account.d.ts +6 -0
  323. package/dist/humain/hcode/account.d.ts.map +1 -1
  324. package/dist/humain/hcode/account.js +348 -129
  325. package/dist/humain/hcode/account.js.map +1 -1
  326. package/dist/humain/hcode/catalog-watch.d.ts +21 -0
  327. package/dist/humain/hcode/catalog-watch.d.ts.map +1 -0
  328. package/dist/humain/hcode/catalog-watch.js +46 -0
  329. package/dist/humain/hcode/catalog-watch.js.map +1 -0
  330. package/dist/humain/hcode/contracts.d.ts +31 -1
  331. package/dist/humain/hcode/contracts.d.ts.map +1 -1
  332. package/dist/humain/hcode/contracts.js +205 -136
  333. package/dist/humain/hcode/contracts.js.map +1 -1
  334. package/dist/humain/hcode/environment.d.ts +3 -1
  335. package/dist/humain/hcode/environment.d.ts.map +1 -1
  336. package/dist/humain/hcode/environment.js +14 -2
  337. package/dist/humain/hcode/environment.js.map +1 -1
  338. package/dist/humain/hcode/facade.d.ts +26 -6
  339. package/dist/humain/hcode/facade.d.ts.map +1 -1
  340. package/dist/humain/hcode/facade.js +148 -38
  341. package/dist/humain/hcode/facade.js.map +1 -1
  342. package/dist/humain/hcode/http.d.ts +3 -1
  343. package/dist/humain/hcode/http.d.ts.map +1 -1
  344. package/dist/humain/hcode/http.js +44 -23
  345. package/dist/humain/hcode/http.js.map +1 -1
  346. package/dist/humain/hcode/images.d.ts +67 -0
  347. package/dist/humain/hcode/images.d.ts.map +1 -0
  348. package/dist/humain/hcode/images.js +465 -0
  349. package/dist/humain/hcode/images.js.map +1 -0
  350. package/dist/humain/hcode/login-copy.d.ts +28 -0
  351. package/dist/humain/hcode/login-copy.d.ts.map +1 -0
  352. package/dist/humain/hcode/login-copy.js +74 -0
  353. package/dist/humain/hcode/login-copy.js.map +1 -0
  354. package/dist/humain/hcode/login-failure.d.ts +26 -0
  355. package/dist/humain/hcode/login-failure.d.ts.map +1 -0
  356. package/dist/humain/hcode/login-failure.js +50 -0
  357. package/dist/humain/hcode/login-failure.js.map +1 -0
  358. package/dist/humain/hcode/notices.d.ts +45 -1
  359. package/dist/humain/hcode/notices.d.ts.map +1 -1
  360. package/dist/humain/hcode/notices.js +124 -7
  361. package/dist/humain/hcode/notices.js.map +1 -1
  362. package/dist/humain/hcode/provider.d.ts +9 -3
  363. package/dist/humain/hcode/provider.d.ts.map +1 -1
  364. package/dist/humain/hcode/provider.js +204 -20
  365. package/dist/humain/hcode/provider.js.map +1 -1
  366. package/dist/humain/hcode/run-credential.d.ts +21 -0
  367. package/dist/humain/hcode/run-credential.d.ts.map +1 -0
  368. package/dist/humain/hcode/run-credential.js +140 -0
  369. package/dist/humain/hcode/run-credential.js.map +1 -0
  370. package/dist/humain/hcode/sandbox.d.ts +6 -0
  371. package/dist/humain/hcode/sandbox.d.ts.map +1 -0
  372. package/dist/humain/hcode/sandbox.js +139 -0
  373. package/dist/humain/hcode/sandbox.js.map +1 -0
  374. package/dist/humain/hcode/selection.d.ts +9 -2
  375. package/dist/humain/hcode/selection.d.ts.map +1 -1
  376. package/dist/humain/hcode/selection.js +37 -6
  377. package/dist/humain/hcode/selection.js.map +1 -1
  378. package/dist/humain/hcode/transport.d.ts +14 -10
  379. package/dist/humain/hcode/transport.d.ts.map +1 -1
  380. package/dist/humain/hcode/transport.js +119 -149
  381. package/dist/humain/hcode/transport.js.map +1 -1
  382. package/dist/humain/hcode/wire.d.ts +3 -0
  383. package/dist/humain/hcode/wire.d.ts.map +1 -1
  384. package/dist/humain/hcode/wire.js +11 -0
  385. package/dist/humain/hcode/wire.js.map +1 -1
  386. package/dist/humain/metadata/contracts.d.ts +1 -0
  387. package/dist/humain/metadata/contracts.d.ts.map +1 -1
  388. package/dist/humain/metadata/contracts.js +2 -1
  389. package/dist/humain/metadata/contracts.js.map +1 -1
  390. package/dist/humain/remote/broker.d.ts +84 -0
  391. package/dist/humain/remote/broker.d.ts.map +1 -0
  392. package/dist/humain/remote/broker.js +427 -0
  393. package/dist/humain/remote/broker.js.map +1 -0
  394. package/dist/humain/remote/deny-store.d.ts +12 -0
  395. package/dist/humain/remote/deny-store.d.ts.map +1 -0
  396. package/dist/humain/remote/deny-store.js +164 -0
  397. package/dist/humain/remote/deny-store.js.map +1 -0
  398. package/dist/humain/remote/enablement.d.ts +5 -0
  399. package/dist/humain/remote/enablement.d.ts.map +1 -0
  400. package/dist/humain/remote/enablement.js +8 -0
  401. package/dist/humain/remote/enablement.js.map +1 -0
  402. package/dist/humain/remote/environment.d.ts +11 -0
  403. package/dist/humain/remote/environment.d.ts.map +1 -0
  404. package/dist/humain/remote/environment.js +19 -0
  405. package/dist/humain/remote/environment.js.map +1 -0
  406. package/dist/humain/remote/host-watch.d.ts +21 -0
  407. package/dist/humain/remote/host-watch.d.ts.map +1 -0
  408. package/dist/humain/remote/host-watch.js +186 -0
  409. package/dist/humain/remote/host-watch.js.map +1 -0
  410. package/dist/humain/remote/ipc-posix.d.ts +5 -0
  411. package/dist/humain/remote/ipc-posix.d.ts.map +1 -0
  412. package/dist/humain/remote/ipc-posix.js +29 -0
  413. package/dist/humain/remote/ipc-posix.js.map +1 -0
  414. package/dist/humain/remote/ipc-windows.d.ts +3 -0
  415. package/dist/humain/remote/ipc-windows.d.ts.map +1 -0
  416. package/dist/humain/remote/ipc-windows.js +5 -0
  417. package/dist/humain/remote/ipc-windows.js.map +1 -0
  418. package/dist/humain/remote/ipc.d.ts +10 -0
  419. package/dist/humain/remote/ipc.d.ts.map +1 -0
  420. package/dist/humain/remote/ipc.js +19 -0
  421. package/dist/humain/remote/ipc.js.map +1 -0
  422. package/dist/humain/remote/protocol.d.ts +43 -0
  423. package/dist/humain/remote/protocol.d.ts.map +1 -0
  424. package/dist/humain/remote/protocol.js +76 -0
  425. package/dist/humain/remote/protocol.js.map +1 -0
  426. package/dist/humain/remote/relay-socket.d.ts +30 -0
  427. package/dist/humain/remote/relay-socket.d.ts.map +1 -0
  428. package/dist/humain/remote/relay-socket.js +137 -0
  429. package/dist/humain/remote/relay-socket.js.map +1 -0
  430. package/dist/humain/remote/secure-channel.d.ts +10 -0
  431. package/dist/humain/remote/secure-channel.d.ts.map +1 -0
  432. package/dist/humain/remote/secure-channel.js +5 -0
  433. package/dist/humain/remote/secure-channel.js.map +1 -0
  434. package/dist/humain/remote/terminal.d.ts +48 -0
  435. package/dist/humain/remote/terminal.d.ts.map +1 -0
  436. package/dist/humain/remote/terminal.js +119 -0
  437. package/dist/humain/remote/terminal.js.map +1 -0
  438. package/dist/humain/remote/tickets.d.ts +35 -0
  439. package/dist/humain/remote/tickets.d.ts.map +1 -0
  440. package/dist/humain/remote/tickets.js +132 -0
  441. package/dist/humain/remote/tickets.js.map +1 -0
  442. package/dist/humain/web-access/vendor/anysearch.d.ts.map +1 -1
  443. package/dist/humain/web-access/vendor/anysearch.js +7 -3
  444. package/dist/humain/web-access/vendor/anysearch.js.map +1 -1
  445. package/dist/humain/web-access/vendor/autom.d.ts +4 -0
  446. package/dist/humain/web-access/vendor/autom.d.ts.map +1 -0
  447. package/dist/humain/web-access/vendor/autom.js +191 -0
  448. package/dist/humain/web-access/vendor/autom.js.map +1 -0
  449. package/dist/humain/web-access/vendor/cloro.d.ts +4 -0
  450. package/dist/humain/web-access/vendor/cloro.d.ts.map +1 -0
  451. package/dist/humain/web-access/vendor/cloro.js +236 -0
  452. package/dist/humain/web-access/vendor/cloro.js.map +1 -0
  453. package/dist/humain/web-access/vendor/curator-page.d.ts.map +1 -1
  454. package/dist/humain/web-access/vendor/curator-page.js +7 -1
  455. package/dist/humain/web-access/vendor/curator-page.js.map +1 -1
  456. package/dist/humain/web-access/vendor/curator-server.d.ts.map +1 -1
  457. package/dist/humain/web-access/vendor/curator-server.js +6 -0
  458. package/dist/humain/web-access/vendor/curator-server.js.map +1 -1
  459. package/dist/humain/web-access/vendor/domain-filter-normalization.d.ts +8 -0
  460. package/dist/humain/web-access/vendor/domain-filter-normalization.d.ts.map +1 -1
  461. package/dist/humain/web-access/vendor/domain-filter-normalization.js +37 -0
  462. package/dist/humain/web-access/vendor/domain-filter-normalization.js.map +1 -1
  463. package/dist/humain/web-access/vendor/duckduckgo-rate-limit.d.ts +28 -8
  464. package/dist/humain/web-access/vendor/duckduckgo-rate-limit.d.ts.map +1 -1
  465. package/dist/humain/web-access/vendor/duckduckgo-rate-limit.js +135 -34
  466. package/dist/humain/web-access/vendor/duckduckgo-rate-limit.js.map +1 -1
  467. package/dist/humain/web-access/vendor/duckduckgo.d.ts +1 -1
  468. package/dist/humain/web-access/vendor/duckduckgo.d.ts.map +1 -1
  469. package/dist/humain/web-access/vendor/duckduckgo.js +10 -3
  470. package/dist/humain/web-access/vendor/duckduckgo.js.map +1 -1
  471. package/dist/humain/web-access/vendor/extract.d.ts.map +1 -1
  472. package/dist/humain/web-access/vendor/extract.js +61 -5
  473. package/dist/humain/web-access/vendor/extract.js.map +1 -1
  474. package/dist/humain/web-access/vendor/gemini-search.d.ts +3 -3
  475. package/dist/humain/web-access/vendor/gemini-search.d.ts.map +1 -1
  476. package/dist/humain/web-access/vendor/gemini-search.js +35 -5
  477. package/dist/humain/web-access/vendor/gemini-search.js.map +1 -1
  478. package/dist/humain/web-access/vendor/index.d.ts.map +1 -1
  479. package/dist/humain/web-access/vendor/index.js +8 -1
  480. package/dist/humain/web-access/vendor/index.js.map +1 -1
  481. package/dist/humain/web-access/vendor/page-query.d.ts +5 -0
  482. package/dist/humain/web-access/vendor/page-query.d.ts.map +1 -1
  483. package/dist/humain/web-access/vendor/page-query.js +12 -2
  484. package/dist/humain/web-access/vendor/page-query.js.map +1 -1
  485. package/dist/humain/web-access/vendor/specstream.d.ts +6 -0
  486. package/dist/humain/web-access/vendor/specstream.d.ts.map +1 -0
  487. package/dist/humain/web-access/vendor/specstream.js +253 -0
  488. package/dist/humain/web-access/vendor/specstream.js.map +1 -0
  489. package/dist/humain/web-access/vendor/tool-activation.d.ts.map +1 -1
  490. package/dist/humain/web-access/vendor/tool-activation.js +21 -5
  491. package/dist/humain/web-access/vendor/tool-activation.js.map +1 -1
  492. package/dist/humain/web-access/vendor/upgrade-notice.d.ts +1 -1
  493. package/dist/humain/web-access/vendor/upgrade-notice.js +1 -1
  494. package/dist/humain/web-access/vendor/upgrade-notice.js.map +1 -1
  495. package/dist/humain/web-access/vendor/utils.d.ts +1 -0
  496. package/dist/humain/web-access/vendor/utils.d.ts.map +1 -1
  497. package/dist/humain/web-access/vendor/utils.js +3 -0
  498. package/dist/humain/web-access/vendor/utils.js.map +1 -1
  499. package/dist/humain/web-access/vendor/video-extract.js +2 -2
  500. package/dist/humain/web-access/vendor/video-extract.js.map +1 -1
  501. package/dist/humain/web-access/vendor/web-tool-core.d.ts +13 -0
  502. package/dist/humain/web-access/vendor/web-tool-core.d.ts.map +1 -1
  503. package/dist/humain/web-access/vendor/web-tool-core.js +16 -5
  504. package/dist/humain/web-access/vendor/web-tool-core.js.map +1 -1
  505. package/dist/humain/web-access/vendor/youtube-extract.js +2 -2
  506. package/dist/humain/web-access/vendor/youtube-extract.js.map +1 -1
  507. package/dist/index.d.ts +0 -2
  508. package/dist/index.d.ts.map +1 -1
  509. package/dist/index.js.map +1 -1
  510. package/dist/main.d.ts +1 -1
  511. package/dist/main.d.ts.map +1 -1
  512. package/dist/main.js +109 -29
  513. package/dist/main.js.map +1 -1
  514. package/dist/modes/diagnostics-stderr.d.ts +4 -0
  515. package/dist/modes/diagnostics-stderr.d.ts.map +1 -0
  516. package/dist/modes/diagnostics-stderr.js +11 -0
  517. package/dist/modes/diagnostics-stderr.js.map +1 -0
  518. package/dist/modes/interactive/components/account-picker.d.ts +31 -0
  519. package/dist/modes/interactive/components/account-picker.d.ts.map +1 -0
  520. package/dist/modes/interactive/components/account-picker.js +150 -0
  521. package/dist/modes/interactive/components/account-picker.js.map +1 -0
  522. package/dist/modes/interactive/components/assistant-message.d.ts +1 -1
  523. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  524. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  525. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  526. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  527. package/dist/modes/interactive/components/config-selector.js +5 -2
  528. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  529. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  530. package/dist/modes/interactive/components/extension-selector.js +14 -5
  531. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  532. package/dist/modes/interactive/components/first-time-setup.d.ts +1 -1
  533. package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
  534. package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
  535. package/dist/modes/interactive/components/keybinding-hints.d.ts +2 -0
  536. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
  537. package/dist/modes/interactive/components/keybinding-hints.js +6 -0
  538. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
  539. package/dist/modes/interactive/components/model-selector.d.ts +10 -0
  540. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  541. package/dist/modes/interactive/components/model-selector.js +101 -23
  542. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  543. package/dist/modes/interactive/components/oauth-selector.d.ts +5 -0
  544. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  545. package/dist/modes/interactive/components/oauth-selector.js +17 -6
  546. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  547. package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -1
  548. package/dist/modes/interactive/components/radius-login-selector.js +2 -1
  549. package/dist/modes/interactive/components/radius-login-selector.js.map +1 -1
  550. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  551. package/dist/modes/interactive/components/scoped-models-selector.js +13 -6
  552. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  553. package/dist/modes/interactive/components/session-selector.d.ts +8 -1
  554. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  555. package/dist/modes/interactive/components/session-selector.js +41 -9
  556. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  557. package/dist/modes/interactive/components/settings-submenu.d.ts +1 -1
  558. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
  559. package/dist/modes/interactive/components/settings-submenu.js +5 -1
  560. package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
  561. package/dist/modes/interactive/components/status-indicator.d.ts +0 -17
  562. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  563. package/dist/modes/interactive/components/status-indicator.js +1 -78
  564. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  565. package/dist/modes/interactive/components/themed-text.d.ts +1 -1
  566. package/dist/modes/interactive/components/themed-text.d.ts.map +1 -1
  567. package/dist/modes/interactive/components/themed-text.js.map +1 -1
  568. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  569. package/dist/modes/interactive/components/thinking-selector.js +5 -1
  570. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  571. package/dist/modes/interactive/components/tool-execution.d.ts +1 -1
  572. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  573. package/dist/modes/interactive/components/tool-execution.js +3 -1
  574. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  575. package/dist/modes/interactive/components/trust-selector.d.ts.map +1 -1
  576. package/dist/modes/interactive/components/trust-selector.js +14 -5
  577. package/dist/modes/interactive/components/trust-selector.js.map +1 -1
  578. package/dist/modes/interactive/components/user-message.d.ts +1 -1
  579. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  580. package/dist/modes/interactive/components/user-message.js.map +1 -1
  581. package/dist/modes/interactive/components/visual-truncate.d.ts +2 -2
  582. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  583. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  584. package/dist/modes/interactive/interactive-mode.d.ts +35 -4
  585. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  586. package/dist/modes/interactive/interactive-mode.js +821 -250
  587. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  588. package/dist/modes/interactive/model-catalog-refresh.d.ts +4 -0
  589. package/dist/modes/interactive/model-catalog-refresh.d.ts.map +1 -1
  590. package/dist/modes/interactive/model-catalog-refresh.js +40 -1
  591. package/dist/modes/interactive/model-catalog-refresh.js.map +1 -1
  592. package/dist/modes/interactive/oauth-account-format.d.ts +15 -2
  593. package/dist/modes/interactive/oauth-account-format.d.ts.map +1 -1
  594. package/dist/modes/interactive/oauth-account-format.js +39 -21
  595. package/dist/modes/interactive/oauth-account-format.js.map +1 -1
  596. package/dist/modes/interactive/session-share.js +2 -0
  597. package/dist/modes/interactive/session-share.js.map +1 -1
  598. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  599. package/dist/modes/interactive/theme/theme.js +1 -0
  600. package/dist/modes/interactive/theme/theme.js.map +1 -1
  601. package/dist/modes/print-mode.d.ts.map +1 -1
  602. package/dist/modes/print-mode.js +30 -32
  603. package/dist/modes/print-mode.js.map +1 -1
  604. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  605. package/dist/modes/rpc/rpc-mode.js +26 -39
  606. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  607. package/dist/modes/rpc/rpc-types.d.ts +1 -0
  608. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  609. package/dist/modes/rpc/rpc-types.js.map +1 -1
  610. package/dist/package-manager-cli.d.ts.map +1 -1
  611. package/dist/package-manager-cli.js +14 -1
  612. package/dist/package-manager-cli.js.map +1 -1
  613. package/dist/utils/abort.d.ts +5 -0
  614. package/dist/utils/abort.d.ts.map +1 -1
  615. package/dist/utils/abort.js +9 -0
  616. package/dist/utils/abort.js.map +1 -1
  617. package/dist/utils/changelog.d.ts.map +1 -1
  618. package/dist/utils/changelog.js +3 -2
  619. package/dist/utils/changelog.js.map +1 -1
  620. package/dist/utils/flush-stdout.d.ts +8 -0
  621. package/dist/utils/flush-stdout.d.ts.map +1 -0
  622. package/dist/utils/flush-stdout.js +23 -0
  623. package/dist/utils/flush-stdout.js.map +1 -0
  624. package/dist/utils/image-process.d.ts +2 -0
  625. package/dist/utils/image-process.d.ts.map +1 -1
  626. package/dist/utils/image-process.js +3 -3
  627. package/dist/utils/image-process.js.map +1 -1
  628. package/dist/utils/image-resize-core.js +2 -2
  629. package/dist/utils/image-resize-core.js.map +1 -1
  630. package/dist/utils/shell.d.ts +2 -0
  631. package/dist/utils/shell.d.ts.map +1 -1
  632. package/dist/utils/shell.js +19 -0
  633. package/dist/utils/shell.js.map +1 -1
  634. package/docs/cli.md +1 -1
  635. package/docs/development.md +0 -13
  636. package/docs/extensions.md +6 -4
  637. package/docs/flow.md +4 -62
  638. package/docs/forge-run-bootstrap.md +46 -0
  639. package/docs/humain-code-forge-architecture.md +1 -47
  640. package/docs/humain-code-forge-flow-walkthrough.md +1 -1
  641. package/docs/humain-code.md +2 -2
  642. package/docs/index.md +2 -1
  643. package/docs/keybindings.md +12 -0
  644. package/docs/llama-cpp.md +5 -5
  645. package/docs/models-configuration.md +4 -2
  646. package/docs/nvidia-rtx-llama-cpp.md +5 -5
  647. package/docs/providers.md +14 -9
  648. package/docs/quickstart.md +16 -2
  649. package/docs/rpc-commands.md +1 -1
  650. package/docs/run-preflight.md +1 -1
  651. package/docs/slash-commands.md +5 -3
  652. package/docs/tui.md +2 -0
  653. package/examples/README.md +0 -3
  654. package/examples/extensions/custom-provider-anthropic/package-lock.json +4 -4
  655. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  656. package/examples/extensions/gondolin/index.ts +4 -7
  657. package/examples/tsconfig.json +96 -76
  658. package/npm-shrinkwrap.json +285 -764
  659. package/package.json +24 -37
  660. package/schemas/keybindings.schema.json +32 -0
  661. package/schemas/models.schema.json +5 -1
  662. package/schemas/settings.schema.json +0 -13
  663. package/src/humain/web-access/UPSTREAM.md +52 -1
  664. package/src/humain/web-access/upstream.json +5 -5
  665. package/src/humain/web-access/vendor/CHANGELOG.md +29 -0
  666. package/dist/bundle/chunks/adaptive-peer-worker-X2ZNZE3S.js +0 -8
  667. package/dist/bundle/chunks/adaptive-session-host-7KDSQV5I.js +0 -162
  668. package/dist/bundle/chunks/anthropic-messages-TQK3FUV3.js +0 -68
  669. package/dist/bundle/chunks/azure-openai-responses-JY7OSLH2.js +0 -15
  670. package/dist/bundle/chunks/chunk-5L4PBYC7.js +0 -11
  671. package/dist/bundle/chunks/chunk-6PNQYO6A.js +0 -10
  672. package/dist/bundle/chunks/chunk-CRN54O4D.js +0 -24
  673. package/dist/bundle/chunks/chunk-CTU2ECLD.js +0 -7
  674. package/dist/bundle/chunks/chunk-DBL35X7L.js +0 -3
  675. package/dist/bundle/chunks/chunk-GME4AWDG.js +0 -23
  676. package/dist/bundle/chunks/chunk-GTILMMUF.js +0 -12
  677. package/dist/bundle/chunks/chunk-J57HOSWD.js +0 -21
  678. package/dist/bundle/chunks/chunk-KQM7ZGL6.js +0 -11
  679. package/dist/bundle/chunks/chunk-MX4Q4W6H.js +0 -214
  680. package/dist/bundle/chunks/chunk-NXA6NEHE.js +0 -54
  681. package/dist/bundle/chunks/chunk-PJACZCIR.js +0 -2
  682. package/dist/bundle/chunks/chunk-T5A6T24H.js +0 -93
  683. package/dist/bundle/chunks/chunk-WCFHG6NO.js +0 -16
  684. package/dist/bundle/chunks/chunk-ZJUU6WOV.js +0 -2052
  685. package/dist/bundle/chunks/compat-ZK2DIW3P.js +0 -15
  686. package/dist/bundle/chunks/dist-EY7YKQHB.js +0 -11
  687. package/dist/bundle/chunks/dist-J5IUPLMH.js +0 -37
  688. package/dist/bundle/chunks/dist-cjs-2SKN226B.js +0 -184
  689. package/dist/bundle/chunks/entry-AL54ZGYO.js +0 -2
  690. package/dist/bundle/chunks/es5-GYTRHFKS.js +0 -77
  691. package/dist/bundle/chunks/google-generative-ai-UL7YEQ6J.js +0 -21
  692. package/dist/bundle/chunks/google-vertex-OTMSPUYH.js +0 -26
  693. package/dist/bundle/chunks/host-75YAHLDR.js +0 -3
  694. package/dist/bundle/chunks/interactive-mode-IW4PIVAQ.js +0 -5
  695. package/dist/bundle/chunks/mistral-conversations-E72Y6OC3.js +0 -43
  696. package/dist/bundle/chunks/pdfjs-AKD6EBKN.js +0 -3614
  697. package/dist/bundle/chunks/pdfjs-jbig2_nowasm_fallback-FH3KJM4H.js +0 -326
  698. package/dist/bundle/chunks/pdfjs-openjpeg-SKR7C34X.js +0 -671
  699. package/dist/bundle/chunks/pdfjs-openjpeg_nowasm_fallback-VUBL7UEE.js +0 -974
  700. package/dist/bundle/chunks/session-picker-DM6S37IF.js +0 -4
  701. package/dist/bundle/chunks/startup-ui-4GGLWNSU.js +0 -3
  702. package/dist/bundle/chunks/virtual-modules-TI3W24YL.js +0 -28
  703. package/dist/core/internal-process.d.ts +0 -23
  704. package/dist/core/internal-process.d.ts.map +0 -1
  705. package/dist/core/internal-process.js +0 -88
  706. package/dist/core/internal-process.js.map +0 -1
  707. package/dist/humain/adaptive-execution.d.ts +0 -51
  708. package/dist/humain/adaptive-execution.d.ts.map +0 -1
  709. package/dist/humain/adaptive-execution.js +0 -100
  710. package/dist/humain/adaptive-execution.js.map +0 -1
  711. package/dist/humain/adaptive-peer-process.d.ts +0 -44
  712. package/dist/humain/adaptive-peer-process.d.ts.map +0 -1
  713. package/dist/humain/adaptive-peer-process.js +0 -159
  714. package/dist/humain/adaptive-peer-process.js.map +0 -1
  715. package/dist/humain/adaptive-peer-worker.d.ts +0 -3
  716. package/dist/humain/adaptive-peer-worker.d.ts.map +0 -1
  717. package/dist/humain/adaptive-peer-worker.js +0 -122
  718. package/dist/humain/adaptive-peer-worker.js.map +0 -1
  719. package/dist/humain/adaptive-runtime-types.d.ts +0 -621
  720. package/dist/humain/adaptive-runtime-types.d.ts.map +0 -1
  721. package/dist/humain/adaptive-runtime-types.js +0 -3
  722. package/dist/humain/adaptive-runtime-types.js.map +0 -1
  723. package/dist/humain/adaptive-session-host.d.ts +0 -113
  724. package/dist/humain/adaptive-session-host.d.ts.map +0 -1
  725. package/dist/humain/adaptive-session-host.js +0 -1838
  726. package/dist/humain/adaptive-session-host.js.map +0 -1
  727. package/dist/utils/deprecation.d.ts +0 -4
  728. package/dist/utils/deprecation.d.ts.map +0 -1
  729. package/dist/utils/deprecation.js +0 -13
  730. package/dist/utils/deprecation.js.map +0 -1
  731. package/examples/plugins/pi-example-plugin/README.md +0 -38
  732. package/examples/plugins/pi-example-plugin/package.json +0 -10
  733. package/examples/plugins/pi-example-plugin/src/contract.ts +0 -13
  734. package/examples/plugins/pi-example-plugin/src/session.ts +0 -24
  735. package/examples/plugins/pi-example-plugin/src/tui.ts +0 -31
@@ -1,23 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{appendAssistantMessageDiagnostic,findSubmissionAdmissionError,ownedSlice}from"./chunk-4HTVBBJD.js";var MAX_PROVIDER_ERROR_BODY_CHARS=4e3,MAX_PROVIDER_ERROR_INPUT_CHARS=64*1024,OVERSIZED_ERROR_TEXT="Provider error text exceeded 65536 characters",UNPARSEABLE_ERROR_TEXT="Unparseable structured provider error";function normalizeProviderError(error){let refusal=findSubmissionAdmissionError(error);if(refusal)return{message:refusal.message,messageCarriesBody:!0,admissionRefused:!0};if(!(error instanceof Error))return{message:truncateErrorText(safeJsonStringify(error),MAX_PROVIDER_ERROR_BODY_CHARS),messageCarriesBody:!1};
3
- let sdkError=error,status=extractStatus(sdkError),body=extractBody(sdkError),message=body==="[REDACTED]"?body:truncateErrorText(error.message,MAX_PROVIDER_ERROR_BODY_CHARS),transport=transportEvidence(error);transport.transportCode&&TRANSPORT_CODES.has(transport.transportCode)&&!message.includes(transport.transportCode)&&(message=truncateErrorText(`${message} (${transport.transportCode})`,MAX_PROVIDER_ERROR_BODY_CHARS));let messageCarriesBody=body===void 0||message!=="[REDACTED]"&&message.includes(
4
- body);return{status,body,message,messageCarriesBody,...transport}}function transportEvidence(error){let candidate=error,transportCode,transportName;for(let depth=0;depth<8&&candidate&&typeof candidate=="object";depth++){let nested=candidate,status=extractStatus(nested);if(status!==void 0&&status>=400||nested.name==="AbortError"||nested.constructor?.name==="APIUserAbortError")return{};typeof nested.code=="string"&&TRANSPORT_CODES.has(nested.code)&&(transportCode??=nested.code);for(let name of[nested.
5
- name,nested.constructor?.name])["TimeoutError","APIConnectionTimeoutError","APIConnectionError"].includes(name)&&(transportName??=name);candidate=nested.cause}return transportCode??=transportName,transportCode?{transportCode}:{}}function appendProviderTransportDiagnostic(message,error){if(error.admissionRefused){appendAssistantMessageDiagnostic(message,{type:"provider_http_error",timestamp:Date.now(),details:{retryable:!1}});return}message.stopReason!=="error"||!error.transportCode||appendAssistantMessageDiagnostic(
6
- message,{type:"provider_transport_error",timestamp:Date.now(),details:{reason:"provider_unreachable",code:error.transportCode}})}function extractStatus(error){return[error.statusCode,error.status,error.$metadata?.httpStatusCode,error.$response?.statusCode].find(value=>typeof value=="number"&&Number.isInteger(value)&&value>=100&&value<=599)}function extractBody(error){let bodyText=pickBodyText(error);if(bodyText===void 0)return;let trimmed=sanitizeErrorText(bodyText).trim();if(trimmed.length!==0)
7
- return truncateErrorText(trimmed,MAX_PROVIDER_ERROR_BODY_CHARS)}function pickBodyText(error){if(typeof error.body=="string")return error.body;if(isPlainNonEmptyObject(error.error))return safeJsonStringify(error.error);let responseBody=error.$response?.body;if(typeof responseBody=="string")return responseBody;if(responseBody instanceof Uint8Array)return responseBody.byteLength>MAX_PROVIDER_ERROR_INPUT_CHARS?OVERSIZED_ERROR_TEXT:new TextDecoder().decode(responseBody);if(!isReadableStreamLike(responseBody)&&
8
- isPlainNonEmptyObject(responseBody))return safeJsonStringify(responseBody)}function isReadableStreamLike(value){return typeof value=="object"&&value!==null&&"pipe"in value&&typeof value.pipe=="function"}function isPlainNonEmptyObject(value){if(typeof value!="object"||value===null)return!1;let proto=Object.getPrototypeOf(value);return proto!==Object.prototype&&proto!==null?!1:Object.keys(value).length>0}function formatProviderError(norm,prefix){if(norm.messageCarriesBody||norm.status===void 0||norm.
9
- body===void 0){let message=prefix!==void 0&&norm.status!==void 0?`${prefix} (${norm.status}): ${norm.message}`:norm.message;return truncateErrorText(message,MAX_PROVIDER_ERROR_BODY_CHARS)}return truncateErrorText(prefix!==void 0?`${prefix} (${norm.status}): ${norm.body}`:`${norm.status}: ${norm.body}`,MAX_PROVIDER_ERROR_BODY_CHARS)}function truncateErrorText(text,maxChars){let clean=sanitizeErrorText(text),cap=Number.isFinite(maxChars)?Math.max(0,Math.floor(maxChars)):MAX_PROVIDER_ERROR_BODY_CHARS;
10
- if(clean.length<=cap)return clean;let start=clean.search(/[{[]/);if(start>=0)try{let parsed=JSON.parse(clean.slice(start));clean=clean.slice(0,start)+summarizeErrorValue(parsed)}catch{}let suffix="... [truncated]";return cap<suffix.length?suffix.slice(0,cap):`${ownedSlice(clean,0,cap-suffix.length).replace(/\[[^\]]*$/,"")}${suffix}`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value,(key,nested)=>{if(nested!==null&&typeof nested=="object"&&hasSensitiveLabel(nested,!0))return Array.
11
- isArray(nested)?["[REDACTED]"]:"[REDACTED]";let label=normalizeErrorLabel(key);if(hasAmbiguousErrorControls(key)||SENSITIVE_KEY.test(label)||/headers?/i.test(label)||Array.isArray(nested)&&nested.some(item=>typeof item=="string"&&SENSITIVE_KEY.test(normalizeErrorLabel(item)))||nested!==null&&typeof nested=="object"&&Object.entries(nested).some(([name,item])=>typeof item=="string"&&SENSITIVE_HEADER_NAME.test(normalizeErrorLabel(item))||/^(?:name|key|header|header[-_]?name|header[-_]?key|field[-_]?name|label|identifier)$/i.
12
- test(normalizeErrorLabel(name))&&hasSensitiveLabel(item)))return"[REDACTED]";if(Array.isArray(nested)&&hasSensitiveLabel(nested))return["[REDACTED]"];if(nested!==null&&typeof nested=="object"&&!Array.isArray(nested)){let entries=Object.entries(nested);if(entries.some(([name])=>sanitizePlainText(name)!==stripErrorControls(name)))return Object.fromEntries(entries.map(([name,value2])=>sanitizePlainText(name)!==stripErrorControls(name)?[sanitizePlainText(name),"[REDACTED]"]:[name,value2]))}return typeof nested==
13
- "string"?sanitizeErrorText(nested):nested});return serialized!==void 0&&serialized.length>MAX_PROVIDER_ERROR_INPUT_CHARS?truncateErrorText(summarizeErrorValue(JSON.parse(serialized)),MAX_PROVIDER_ERROR_BODY_CHARS):serialized===void 0?sanitizePlainText(String(value)):serialized}catch{return"[Unserializable provider error]"}}function summarizeErrorValue(value){if(typeof value=="string")try{return summarizeErrorValue(JSON.parse(value))}catch{return sanitizePlainText(value)}if(value===null||typeof value!=
14
- "object")return String(value);let entries=Object.entries(value),reasons=["message","error","reason","detail"];entries.sort(([left],[right])=>(reasons.includes(left)?reasons.indexOf(left):reasons.length)-(reasons.includes(right)?reasons.indexOf(right):reasons.length));let parts=[],length=0;for(let[,nested]of entries){let part=truncateErrorText(summarizeErrorValue(nested),MAX_PROVIDER_ERROR_BODY_CHARS);if(parts.push(part),length+=part.length+2,length>=MAX_PROVIDER_ERROR_BODY_CHARS)break}return truncateErrorText(
15
- parts.join("; "),MAX_PROVIDER_ERROR_BODY_CHARS)}var TRANSPORT_CODES=new Set(["ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","EPIPE","EPROTO","CERT_HAS_EXPIRED","DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE","ERR_TLS_CERT_ALTNAME_INVALID","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_SOCKET"]),SENSITIVE_KEY=/(?:authorization|cookie|(?:api[-_\s]*key)|token|password|passwd|secret|credential|signature|private[-_\s]*key)/i,
16
- SENSITIVE_HEADER_NAME=/^(?:[a-z0-9]+[-_])*(?:authorization|cookie|(?:api|private|secret)[-_\s]*key|(?:access|refresh|session|security)[-_\s]*token|token|password|passwd|secret|credentials?|signature)$/i;function sanitizeErrorText(text){if(text.length>MAX_PROVIDER_ERROR_INPUT_CHARS)return OVERSIZED_ERROR_TEXT;try{let parsed=JSON.parse(text);if(parsed!==null&&typeof parsed=="object")return safeJsonStringify(parsed);if(typeof parsed=="string")return sanitizeErrorText(parsed)}catch{let start=text.search(
17
- /[{[]/);if(start>0)try{let parsed=JSON.parse(text.slice(start));return sanitizePlainText(text.slice(0,start))+safeJsonStringify(parsed)}catch{}}return sanitizePlainText(text)}function hasSensitiveLabel(value,ambiguityOnly=!1){let pending=[value],seen=new Set,scanned=0;for(;pending.length>0;){if(++scanned>1024)return!0;let item=pending.pop();if(typeof item=="string"){if(item.length>MAX_PROVIDER_ERROR_INPUT_CHARS||hasAmbiguousErrorControls(item)||!ambiguityOnly&&SENSITIVE_HEADER_NAME.test(normalizeErrorLabel(
18
- item)))return!0;try{let decoded=JSON.parse(ambiguityOnly?item:stripErrorControls(item," "));(typeof decoded=="string"||decoded!==null&&typeof decoded=="object")&&pending.push(decoded)}catch{let sanitized=sanitizePlainText(item);if(ambiguityOnly?sanitized===UNPARSEABLE_ERROR_TEXT:sanitized!==stripErrorControls(item))return!0}}if(item!==null&&typeof item=="object"){if(seen.has(item))return!0;seen.add(item);let entries=Object.entries(item);if(entries.length*2+pending.length>1024)return!0;for(let[name,
19
- nested]of entries){if(ambiguityOnly&&hasAmbiguousErrorKey(name))return!0;ambiguityOnly||pending.push(name),pending.push(nested)}}}return!1}function hasAmbiguousErrorKey(name){return name.length>MAX_PROVIDER_ERROR_INPUT_CHARS||name!==normalizeErrorLabel(name)||sanitizePlainText(name)===UNPARSEABLE_ERROR_TEXT}function normalizeErrorLabel(text){return stripErrorControls(text).replace(/[\s\p{Default_Ignorable_Code_Point}]/gu,"").trim().replace(/:+$/,"").trim()}var ERROR_TERMINAL_SEQUENCES=/(?:\x1b\]|\x9d)[\s\S]*?(?:\x07|\x1b\\|\x9c|$)|\x1b[PX^_][\s\S]*?(?:\x1b\\|$)|(?:\x1b\[|\x9b)[0-?]*[ -/]*[@-~]|\x1b[@-_]/g,
20
- ERROR_CONTROLS=/[\x00-\x08\x0b-\x1f\x7f-\x9f\p{Cf}\p{Default_Ignorable_Code_Point}]/gu;function hasAmbiguousErrorControls(text){return text.replace(ERROR_TERMINAL_SEQUENCES,sequence=>(sequence.startsWith("\x1B[")||sequence.startsWith("\x9B"))&&sequence.endsWith("m")?"":sequence).search(ERROR_CONTROLS)>=0}function stripErrorControls(text,replacement=""){return text.replace(ERROR_TERMINAL_SEQUENCES,replacement).replace(ERROR_CONTROLS,replacement)}function sanitizePlainText(text){if(text.length>MAX_PROVIDER_ERROR_INPUT_CHARS)
21
- return OVERSIZED_ERROR_TEXT;let boundaries=stripErrorControls(text," "),clean=stripErrorControls(text);if((/[@?#<>]/.test(clean)||clean.split(/\s+/).some(part=>{let start=part.search(/(?:https?|wss?|ftp):|[/\\]/i);return start>=0&&/["']/.test(part.slice(start))}))&&/(?:https?|wss?|ftp):|[/\\]/i.test(clean.replace(/\s/g,"")))return"[REDACTED]";if(/\\["/bfnrtu]/i.test(boundaries))return UNPARSEABLE_ERROR_TEXT;let structure=clean.replaceAll("[REDACTED]","").replaceAll("[truncated]","").replace(/\b[a-z_$][\w$]*(?:\[\d+\])+/gi,
22
- "");if(/[{}[\]]/.test(structure))return UNPARSEABLE_ERROR_TEXT;if(hasAmbiguousErrorControls(text)||SENSITIVE_KEY.test(normalizeErrorLabel(clean))||/\b(?:B\s*e\s*a\s*r\s*e\s*r|B\s*a\s*s\s*i\s*c)\s/i.test(boundaries)||/\b(?:B\s*e\s*a\s*r\s*e\s*r|B\s*a\s*s\s*i\s*c)\s/i.test(clean))return"[REDACTED]";let tokenText=clean.replace(/[\t\n\u2028\u2029]/g,"");return tokenText.replace(/[\w-]+(?:\.[\w-]+)*/g,token=>{let segments=token.split(".");return/\b(?:sk-|glpat-|gh[pousr]_|github_pat_|xox[baprs]-)[\w-]+|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\bAIza[\w-]{35}/.
23
- test(token)||segments.length>=3&&/\beyJ[\w-]+$/.test(segments[0])?"[REDACTED]":token})===tokenText?clean:"[REDACTED]"}export{MAX_PROVIDER_ERROR_BODY_CHARS,normalizeProviderError,appendProviderTransportDiagnostic,formatProviderError,truncateErrorText};
@@ -1,12 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- function createUsageTotals(){return{input:0,output:0,cacheRead:0,cacheWrite:0,cost:0}}function addUsageToTotals(totals,usage){usage.usageIncomplete&&(totals.usageIncomplete=!0),totals.input+=usage.input,totals.output+=usage.output,totals.cacheRead+=usage.cacheRead,totals.cacheWrite+=usage.cacheWrite,totals.cost+=usage.cost.total}function combineUsage(first,second){return{...first.usageIncomplete||second.usageIncomplete?{usageIncomplete:!0}:{},input:first.input+second.input,output:first.output+second.
3
- output,cacheRead:first.cacheRead+second.cacheRead,cacheWrite:first.cacheWrite+second.cacheWrite,...first.cacheWrite1h!==void 0||second.cacheWrite1h!==void 0?{cacheWrite1h:(first.cacheWrite1h??0)+(second.cacheWrite1h??0)}:{},...first.reasoning!==void 0||second.reasoning!==void 0?{reasoning:(first.reasoning??0)+(second.reasoning??0)}:{},totalTokens:first.totalTokens+second.totalTokens,cost:{input:first.cost.input+second.cost.input,output:first.cost.output+second.cost.output,cacheRead:first.cost.cacheRead+
4
- second.cost.cacheRead,cacheWrite:first.cost.cacheWrite+second.cost.cacheWrite,total:first.cost.total+second.cost.total,totalFromProvider:first.cost.totalFromProvider===!0&&second.cost.totalFromProvider===!0}}}function normalizeUsage(usage){let result={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},...usage?.usageIncomplete?{usageIncomplete:!0}:{}};for(let key of["input","output","cacheRead","cacheWrite"]){let count=usage?.[key];typeof count==
5
- "number"&&Number.isSafeInteger(count)&&count>=0?result[key]=count:result.usageIncomplete=!0;let cost2=usage?.cost?.[key];typeof cost2=="number"&&Number.isFinite(cost2)&&cost2>=0?result.cost[key]=cost2:result.usageIncomplete=!0}let totalTokens=usage?.totalTokens;(typeof totalTokens!="number"||!Number.isSafeInteger(totalTokens)||totalTokens<0)&&(result.usageIncomplete=!0),result.totalTokens=result.input+result.output+result.cacheRead+result.cacheWrite;let cost=usage?.cost?.total;return typeof cost==
6
- "number"&&Number.isFinite(cost)&&cost>=0?result.cost.total=cost:result.usageIncomplete=!0,result}function getSummaryUsage(usage,ids,kind,owners){if(ids===void 0||Array.isArray(ids)&&ids.length===0)return usage;let remaining=normalizeUsage(usage),ownerIds=Array.isArray(ids)?[...new Set(ids)]:[],covered=ownerIds.length>0,observed=createUsageTotals();for(let id of ownerIds){let owner=typeof id=="string"&&id.length>0?owners.find(entry=>entry.id===id):void 0;if(!owner||owner.kind!==kind){covered=!1;continue}
7
- let value=normalizeUsage(owner.usage);(typeof owner.provider!="string"||owner.provider.length===0||typeof owner.model!="string"||owner.model.length===0||value.usageIncomplete)&&(covered=!1),addUsageToTotals(observed,value)}if(covered&&!usage)return;covered&&!usage?.usageIncomplete&&delete remaining.usageIncomplete;let residual=remaining.cost.total-observed.cost,drift=Number.EPSILON*Math.max(remaining.cost.total,observed.cost)*(ownerIds.length+1);remaining.cost.total=residual>drift?residual:0;for(let key of[
8
- "input","output","cacheRead","cacheWrite"])remaining[key]=Math.max(0,remaining[key]-observed[key]);return remaining.totalTokens=remaining.input+remaining.output+remaining.cacheRead+remaining.cacheWrite,(!covered||remaining.cost.total>0||remaining.totalTokens>0)&&(remaining.usageIncomplete=!0),remaining.usageIncomplete||remaining.cost.total>0||remaining.totalTokens>0?remaining:void 0}function getSessionUsage(entries){let owners=entries.filter(entry=>entry.type==="usage"),seen=new Set,summaries=new Map,
9
- result=[];for(let entry of entries){let usage;if(entry.type==="usage"){if(seen.has(entry.id))continue;seen.add(entry.id),usage=normalizeUsage(entry.usage)}else if(entry.type==="message"&&(entry.message.role==="assistant"||entry.message.role==="toolResult"))usage=entry.message.usage;else if((entry.type==="compaction"||entry.type==="branch_summary")&&(usage=getSummaryUsage(entry.usage,entry.usageEntryIds,entry.type==="compaction"?"compaction":"branchSummary",owners),Array.isArray(entry.usageEntryIds)&&
10
- entry.usageEntryIds.length>0)){let key=JSON.stringify([entry.type,[...new Set(entry.usageEntryIds)].sort()]),previous=summaries.get(key);usage&&(!previous||usage.cost.total>=previous.usage.cost.total)&&summaries.set(key,{entry,usage});continue}usage&&result.push({entry,usage})}return[...result,...summaries.values()]}function getUsageCostBreakdown(entries){let totalsByKey=new Map;for(let{entry,usage}of getSessionUsage(entries)){let key;if(entry.type==="message"&&entry.message.role==="assistant"?key=
11
- `${entry.message.provider}/${entry.message.responseModel??entry.message.model}`:entry.type==="usage"?key=`${entry.provider}/${entry.model}`:key="Tools/summaries",!key||!usage)continue;let totals=totalsByKey.get(key);totals||(totals=createUsageTotals(),totalsByKey.set(key,totals)),addUsageToTotals(totals,usage)}return Array.from(totalsByKey,([key,totals])=>({key,...totals.usageIncomplete?{usageIncomplete:!0}:{},cost:totals.cost,tokens:totals.input+totals.output+totals.cacheRead+totals.cacheWrite})).
12
- filter(entry=>entry.usageIncomplete||entry.cost>0||entry.tokens>0).sort((a,b)=>b.cost-a.cost)}export{createUsageTotals,addUsageToTotals,combineUsage,getSummaryUsage,getSessionUsage,getUsageCostBreakdown};
@@ -1,21 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{theme}from"./chunk-JF7FYXAI.js";import{Key,KeybindingsManager,TUI_KEYBINDINGS}from"./chunk-JYWUOKOI.js";import{Compile}from"./chunk-LB4CIS4F.js";import{typebox_exports}from"./chunk-VEGJT52D.js";import{getAgentDir,stripBom}from"./chunk-VFLVWPLZ.js";function areExperimentalFeaturesEnabled(){return process.env.PI_EXPERIMENTAL==="1"}import{existsSync,readFileSync}from"fs";import{join}from"path";var modifiers=["ctrl","shift","alt","super"],baseKeyPattern=`(?:[a-z0-9]|${Object.values(Key).flatMap(value=>typeof value=="string"?[value.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&")]:[]).join("|")})`,duplicateModifierPattern=modifiers.map(modifier=>`${modifier}\\+.*${modifier}\\+`).join("|"),KeyIdSchema=typebox_exports.Unsafe(typebox_exports.String({pattern:`^(?!.*(?:${duplicateModifierPattern}))(?:(?:${modifiers.join("|")})\\+){0,4}${baseKeyPattern}$`,description:"Key identifier with optional ctrl, \
3
- shift, alt, or super modifiers."}));function keybindingValueSchema(options){return typebox_exports.Union([KeyIdSchema,typebox_exports.Array(KeyIdSchema)],options)}var KeybindingValueSchema=keybindingValueSchema();function useWindowsKeybindings(platform=process.platform,env=process.env){return platform==="win32"||platform==="linux"&&!!(env.WSL_DISTRO_NAME||env.WSL_INTEROP)}var windowsKeybindings=useWindowsKeybindings(),APP_KEYBINDINGS={"app.interrupt":{defaultKeys:"escape",description:"Cancel or abort"},"app.clear":{defaultKeys:"ctrl+c",description:"Clear editor"},"app.exit":{defaultKeys:"ctrl+d",description:"Exit when editor is empty"},"app.suspend":{defaultKeys:process.platform==="win32"?[]:"ctrl+z",description:"\
4
- Suspend to background"},"app.thinking.cycle":{defaultKeys:"shift+tab",description:"Cycle thinking level"},"app.thinking.save":{defaultKeys:"ctrl+s",description:"Save thinking level"},"app.model.cycleForward":{defaultKeys:"ctrl+p",description:"Cycle to next model"},"app.model.cycleBackward":{defaultKeys:windowsKeybindings?"alt+p":"shift+ctrl+p",description:"Cycle to previous model"},"app.model.select":{defaultKeys:"ctrl+l",description:"Open model selector"},"app.tools.expand":{defaultKeys:"ctrl+o",
5
- description:"Toggle tool output"},"app.usage.nextTab":{defaultKeys:["tab","right"],description:"Next usage account"},"app.usage.previousTab":{defaultKeys:["shift+tab","left"],description:"Previous usage account"},"app.usage.showAccounts":{defaultKeys:"a",description:"Show subscription accounts"},"app.usage.showSession":{defaultKeys:"s",description:"Show session usage"},"app.usage.reset":{defaultKeys:"r",description:"Check or use a saved reset"},"app.usage.billing":{defaultKeys:"b",description:"O\
6
- pen provider billing settings"},"app.thinking.toggle":{defaultKeys:"ctrl+t",description:"Toggle thinking blocks"},"app.session.toggleNamedFilter":{defaultKeys:"ctrl+n",description:"Toggle named session filter"},"app.editor.external":{defaultKeys:"ctrl+g",description:"Open external editor"},"app.message.copy":{defaultKeys:"ctrl+x",description:"Copy selection or last assistant message"},"app.block.copy":{defaultKeys:"ctrl+alt+c",description:"Choose an assistant fenced block to copy"},"app.message.\
7
- followUp":{defaultKeys:windowsKeybindings?"ctrl+q":"alt+enter",description:"Queue follow-up message"},"app.message.followUpWhileBusy":{defaultKeys:"tab",description:"Queue follow-up while busy (autocomplete takes precedence)"},"app.message.dequeue":{defaultKeys:windowsKeybindings?"alt+q":"alt+up",description:"Restore queued messages"},"app.clipboard.pasteImage":{defaultKeys:windowsKeybindings?["alt+v","ctrl+v"]:"ctrl+v",description:"Paste files on macOS, images, or text from clipboard"},"app.ses\
8
- sion.new":{defaultKeys:[],description:"Start a new session"},"app.session.tree":{defaultKeys:[],description:"Open session tree"},"app.session.fork":{defaultKeys:[],description:"Fork current session"},"app.session.resume":{defaultKeys:[],description:"Resume a session"},"app.tree.foldOrUp":{defaultKeys:process.platform==="darwin"?["alt+left","ctrl+left"]:["ctrl+left","alt+left"],description:"Fold tree branch or move up"},"app.tree.unfoldOrDown":{defaultKeys:process.platform==="darwin"?["alt+right",
9
- "ctrl+right"]:["ctrl+right","alt+right"],description:"Unfold tree branch or move down"},"app.tree.editLabel":{defaultKeys:"shift+l",description:"Edit tree label"},"app.tree.toggleLabelTimestamp":{defaultKeys:"shift+t",description:"Toggle tree label timestamps"},"app.session.togglePath":{defaultKeys:"ctrl+p",description:"Toggle session path display"},"app.session.toggleSort":{defaultKeys:"ctrl+s",description:"Toggle session sort mode"},"app.session.rename":{defaultKeys:"ctrl+r",description:"Renam\
10
- e session"},"app.session.delete":{defaultKeys:"ctrl+d",description:"Delete session"},"app.session.deleteNoninvasive":{defaultKeys:"ctrl+backspace",description:"Delete session when query is empty"},"app.models.save":{defaultKeys:"ctrl+s",description:"Save model selection"},"app.models.enableAll":{defaultKeys:"ctrl+a",description:"Enable all models"},"app.models.clearAll":{defaultKeys:"ctrl+x",description:"Clear all models"},"app.models.toggleProvider":{defaultKeys:"ctrl+p",description:"Toggle all\
11
- models for provider"},"app.models.reorderUp":{defaultKeys:"alt+up",description:"Move model up in order"},"app.models.reorderDown":{defaultKeys:"alt+down",description:"Move model down in order"},"app.tree.filter.default":{defaultKeys:"ctrl+d",description:"Tree filter: default view"},"app.tree.filter.noTools":{defaultKeys:"ctrl+t",description:"Tree filter: hide tool results"},"app.tree.filter.userOnly":{defaultKeys:"ctrl+u",description:"Tree filter: user messages only"},"app.tree.filter.labeledOn\
12
- ly":{defaultKeys:"ctrl+l",description:"Tree filter: labeled entries only"},"app.tree.filter.all":{defaultKeys:"ctrl+a",description:"Tree filter: show all entries"},"app.tree.filter.cycleForward":{defaultKeys:"ctrl+o",description:"Tree filter: cycle forward"},"app.tree.filter.cycleBackward":{defaultKeys:"shift+ctrl+o",description:"Tree filter: cycle backward"}},KEYBINDINGS={...TUI_KEYBINDINGS,"tui.editor.undo":{...TUI_KEYBINDINGS["tui.editor.undo"],defaultKeys:process.platform==="win32"?"ctrl+z":
13
- windowsKeybindings?"alt+z":"ctrl+-"},"tui.altScreen.previousPrompt":{...TUI_KEYBINDINGS["tui.altScreen.previousPrompt"],defaultKeys:windowsKeybindings?"ctrl+up":["ctrl+shift+up","ctrl+up"]},"tui.altScreen.nextPrompt":{...TUI_KEYBINDINGS["tui.altScreen.nextPrompt"],defaultKeys:windowsKeybindings?"ctrl+down":["ctrl+shift+down","ctrl+down"]},"tui.altScreen.search":{...TUI_KEYBINDINGS["tui.altScreen.search"],defaultKeys:windowsKeybindings?"ctrl+f":"ctrl+shift+f"},...APP_KEYBINDINGS},KEYBINDING_NAME_MIGRATIONS={
14
- cursorUp:"tui.editor.cursorUp",cursorDown:"tui.editor.cursorDown",cursorLeft:"tui.editor.cursorLeft",cursorRight:"tui.editor.cursorRight",cursorWordLeft:"tui.editor.cursorWordLeft",cursorWordRight:"tui.editor.cursorWordRight",cursorLineStart:"tui.editor.cursorLineStart",cursorLineEnd:"tui.editor.cursorLineEnd",jumpForward:"tui.editor.jumpForward",jumpBackward:"tui.editor.jumpBackward",pageUp:"tui.editor.pageUp",pageDown:"tui.editor.pageDown",deleteCharBackward:"tui.editor.deleteCharBackward",deleteCharForward:"\
15
- tui.editor.deleteCharForward",deleteWordBackward:"tui.editor.deleteWordBackward",deleteWordForward:"tui.editor.deleteWordForward",deleteToLineStart:"tui.editor.deleteToLineStart",deleteToLineEnd:"tui.editor.deleteToLineEnd",yank:"tui.editor.yank",yankPop:"tui.editor.yankPop",undo:"tui.editor.undo",newLine:"tui.input.newLine",submit:"tui.input.submit",tab:"tui.input.tab",copy:"tui.input.copy",selectUp:"tui.select.up",selectDown:"tui.select.down",selectPageUp:"tui.select.pageUp",selectPageDown:"tu\
16
- i.select.pageDown",selectConfirm:"tui.select.confirm",selectCancel:"tui.select.cancel",interrupt:"app.interrupt",clear:"app.clear",exit:"app.exit",suspend:"app.suspend",cycleThinkingLevel:"app.thinking.cycle",cycleModelForward:"app.model.cycleForward",cycleModelBackward:"app.model.cycleBackward",selectModel:"app.model.select",expandTools:"app.tools.expand",toggleThinking:"app.thinking.toggle",toggleSessionNamedFilter:"app.session.toggleNamedFilter",externalEditor:"app.editor.external",followUp:"\
17
- app.message.followUp",dequeue:"app.message.dequeue",pasteImage:"app.clipboard.pasteImage",newSession:"app.session.new",tree:"app.session.tree",fork:"app.session.fork",resume:"app.session.resume",treeFoldOrUp:"app.tree.foldOrUp",treeUnfoldOrDown:"app.tree.unfoldOrDown",treeEditLabel:"app.tree.editLabel",treeToggleLabelTimestamp:"app.tree.toggleLabelTimestamp",toggleSessionPath:"app.session.togglePath",toggleSessionSort:"app.session.toggleSort",renameSession:"app.session.rename",deleteSession:"app\
18
- .session.delete",deleteSessionNoninvasive:"app.session.deleteNoninvasive"};function isLegacyKeybindingName(key){return key in KEYBINDING_NAME_MIGRATIONS}var keybindingValueValidator;function toKeybindingsConfig(value){let config={};for(let[key,binding]of Object.entries(value))key!=="$schema"&&(keybindingValueValidator??=Compile(KeybindingValueSchema),keybindingValueValidator.Check(binding)&&(config[key]=binding));return config}function migrateKeybindingsConfig(rawConfig){let config={},migrated=!1;
19
- for(let[key,value]of Object.entries(rawConfig)){let nextKey=isLegacyKeybindingName(key)?KEYBINDING_NAME_MIGRATIONS[key]:key;if(nextKey!==key&&(migrated=!0),key!==nextKey&&Object.hasOwn(rawConfig,nextKey)){migrated=!0;continue}config[nextKey]=value}return{config:orderKeybindingsConfig(config),migrated}}function orderKeybindingsConfig(config){let ordered={};for(let keybinding of Object.keys(KEYBINDINGS))Object.hasOwn(config,keybinding)&&(ordered[keybinding]=config[keybinding]);let extras=Object.keys(
20
- config).filter(key=>!Object.hasOwn(ordered,key)).sort();for(let key of extras)ordered[key]=config[key];return ordered}function loadRawConfig(path){if(existsSync(path))try{let parsed=JSON.parse(stripBom(readFileSync(path,"utf-8")));return typeof parsed!="object"||parsed===null?void 0:parsed}catch{return}}var KeybindingsManager2=class _KeybindingsManager extends KeybindingsManager{configPath;constructor(userBindings={},configPath){super(KEYBINDINGS,userBindings),this.configPath=configPath}static create(agentDir=getAgentDir()){
21
- let configPath=join(agentDir,"keybindings.json"),userBindings=_KeybindingsManager.loadFromFile(configPath);return new _KeybindingsManager(userBindings,configPath)}reload(){this.configPath&&this.setUserBindings(_KeybindingsManager.loadFromFile(this.configPath))}getEffectiveConfig(){return this.getResolvedBindings()}static loadFromFile(path){let rawConfig=loadRawConfig(path);return rawConfig?toKeybindingsConfig(migrateKeybindingsConfig(rawConfig).config):{}}};var DynamicBorder=class{color;constructor(color=str=>theme.fg("border",str)){this.color=color}invalidate(){}render(width){return[this.color("\u2500".repeat(Math.max(1,width)))]}};export{areExperimentalFeaturesEnabled,migrateKeybindingsConfig,KeybindingsManager2 as KeybindingsManager,DynamicBorder};
@@ -1,11 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{getProviderEnvValue}from"./chunk-FACBDLFU.js";var __rewriteRelativeImportExtension=function(path,preserveJsx){return typeof path=="string"&&/^\.\.?\//.test(path)?path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(m,tsx,d,ext,cm){return tsx?preserveJsx?".jsx":".js":d&&(!ext||!cm)?m:d+ext+"."+cm.toLowerCase()+"js"}):path},_existsSync=null,_homedir=null,_join=null,dynamicImport=specifier=>import(__rewriteRelativeImportExtension(specifier)),NODE_FS_SPECIFIER="node:fs",NODE_OS_SPECIFIER="node:os",NODE_PATH_SPECIFIER="node:p\
3
- ath";typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(dynamicImport(NODE_FS_SPECIFIER).then(m=>{_existsSync=m.existsSync}),dynamicImport(NODE_OS_SPECIFIER).then(m=>{_homedir=m.homedir}),dynamicImport(NODE_PATH_SPECIFIER).then(m=>{_join=m.join}));var ANTHROPIC_AUTH_TOKEN_ENV="ANTHROPIC_AUTH_TOKEN",ANTHROPIC_OAUTH_TOKEN_ENV="ANTHROPIC_OAUTH_TOKEN",ANTHROPIC_API_KEY_ENV="ANTHROPIC_API_KEY",ANTHROPIC_FEDERATION_RULE_ID_ENV="ANTHROPIC_FEDERATION_RULE_ID",ANTHROPIC_ORGANIZATION_ID_ENV="\
4
- ANTHROPIC_ORGANIZATION_ID",ANTHROPIC_SERVICE_ACCOUNT_ID_ENV="ANTHROPIC_SERVICE_ACCOUNT_ID",ANTHROPIC_IDENTITY_TOKEN_FILE_ENV="ANTHROPIC_IDENTITY_TOKEN_FILE",ANTHROPIC_WORKSPACE_ID_ENV="ANTHROPIC_WORKSPACE_ID",cachedVertexAdcCredentialsExists=null;function hasVertexAdcCredentials(env){let explicitCredentialsPath=env?.GOOGLE_APPLICATION_CREDENTIALS;if(explicitCredentialsPath)return _existsSync?_existsSync(explicitCredentialsPath):!1;if(cachedVertexAdcCredentialsExists===null){if(!_existsSync||!_homedir||
5
- !_join)return typeof process<"u"&&(process.versions?.node||process.versions?.bun)||(cachedVertexAdcCredentialsExists=!1),!1;let gacPath=getProviderEnvValue("GOOGLE_APPLICATION_CREDENTIALS",env);gacPath?cachedVertexAdcCredentialsExists=_existsSync(gacPath):cachedVertexAdcCredentialsExists=_existsSync(_join(_homedir(),".config","gcloud","application_default_credentials.json"))}return cachedVertexAdcCredentialsExists}function getApiKeyEnvVars(provider){if(provider==="github-copilot")return["COPILOT\
6
- _GITHUB_TOKEN"];if(provider==="anthropic")return[ANTHROPIC_AUTH_TOKEN_ENV,ANTHROPIC_OAUTH_TOKEN_ENV,ANTHROPIC_API_KEY_ENV];let envVar={"ant-ling":"ANT_LING_API_KEY","qwen-token-plan":"QWEN_TOKEN_PLAN_API_KEY","qwen-token-plan-cn":"QWEN_TOKEN_PLAN_CN_API_KEY","qwen-token-plan-individual":"QWEN_TOKEN_PLAN_API_KEY",openai:"OPENAI_API_KEY",azure:"AZURE_OPENAI_API_KEY",nvidia:"NVIDIA_API_KEY",deepseek:"DEEPSEEK_API_KEY",google:"GEMINI_API_KEY","google-vertex":"GOOGLE_CLOUD_API_KEY",groq:"GROQ_API_KEY",
7
- cerebras:"CEREBRAS_API_KEY",xai:"XAI_API_KEY",typesafe:"TYPESAFE_API_KEY",radius:"RADIUS_API_KEY",openrouter:"OPENROUTER_API_KEY","vercel-ai-gateway":"AI_GATEWAY_API_KEY",zai:"ZAI_API_KEY","zai-coding-cn":"ZAI_CODING_CN_API_KEY",mistral:"MISTRAL_API_KEY",minimax:"MINIMAX_API_KEY","minimax-cn":"MINIMAX_CN_API_KEY",moonshotai:"MOONSHOT_API_KEY","moonshotai-cn":"MOONSHOT_API_KEY",huggingface:"HF_TOKEN",fireworks:"FIREWORKS_API_KEY",together:"TOGETHER_API_KEY",baseten:"BASETEN_API_KEY",opencode:"OPE\
8
- NCODE_API_KEY","opencode-go":"OPENCODE_API_KEY","kimi-coding":"KIMI_API_KEY",meta:"META_API_KEY","humain-node":"HUMAIN_NODE_API_KEY","cloudflare-workers-ai":"CLOUDFLARE_API_KEY","cloudflare-ai-gateway":"CLOUDFLARE_API_KEY",xiaomi:"XIAOMI_API_KEY","xiaomi-token-plan-cn":"XIAOMI_TOKEN_PLAN_CN_API_KEY","xiaomi-token-plan-ams":"XIAOMI_TOKEN_PLAN_AMS_API_KEY","xiaomi-token-plan-sgp":"XIAOMI_TOKEN_PLAN_SGP_API_KEY"}[provider];return envVar?[envVar]:void 0}function findEnvKeys(provider,env){let envVars=getApiKeyEnvVars(
9
- provider);if(!envVars)return;let found=envVars.filter(envVar=>!!getProviderEnvValue(envVar,env));return found.length>0?found:void 0}function getEnvApiKey(provider,env){let envKeys=findEnvKeys(provider,env);if(envKeys?.[0]){let apiKeyEnv=provider==="anthropic"?envKeys.find(key=>key!==ANTHROPIC_AUTH_TOKEN_ENV):envKeys[0];if(apiKeyEnv)return getProviderEnvValue(apiKeyEnv,env)}if(provider==="google-vertex"){let hasCredentials=hasVertexAdcCredentials(env),hasProject=!!(getProviderEnvValue("GOOGLE_CLO\
10
- UD_PROJECT",env)||getProviderEnvValue("GCLOUD_PROJECT",env)),hasLocation=!!getProviderEnvValue("GOOGLE_CLOUD_LOCATION",env);if(hasCredentials&&hasProject&&hasLocation)return"<authenticated>"}if(provider==="amazon-bedrock"&&(getProviderEnvValue("AWS_PROFILE",env)||getProviderEnvValue("AWS_ACCESS_KEY_ID",env)&&getProviderEnvValue("AWS_SECRET_ACCESS_KEY",env)||getProviderEnvValue("AWS_BEARER_TOKEN_BEDROCK",env)||getProviderEnvValue("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",env)||getProviderEnvValue(
11
- "AWS_CONTAINER_CREDENTIALS_FULL_URI",env)||getProviderEnvValue("AWS_WEB_IDENTITY_TOKEN_FILE",env)))return"<authenticated>"}export{ANTHROPIC_AUTH_TOKEN_ENV,ANTHROPIC_OAUTH_TOKEN_ENV,ANTHROPIC_API_KEY_ENV,ANTHROPIC_FEDERATION_RULE_ID_ENV,ANTHROPIC_ORGANIZATION_ID_ENV,ANTHROPIC_SERVICE_ACCOUNT_ID_ENV,ANTHROPIC_IDENTITY_TOKEN_FILE_ENV,ANTHROPIC_WORKSPACE_ID_ENV,findEnvKeys,getEnvApiKey};
@@ -1,214 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{VisualLinePreview,createOutputFileStream,getTextOutput,invalidArgText,startToolTimer,str,toolTimerText,wrapToolDefinition}from"./chunk-5B25YXF7.js";import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,formatSize,truncateTail}from"./chunk-3HVHETMU.js";import{getLanguageFromPath,keyHint,theme}from"./chunk-JF7FYXAI.js";import{Container,Spacer,Text,visibleWidth}from"./chunk-JYWUOKOI.js";import{TRACE_ENV}from"./chunk-WCFHG6NO.js";import{getShellConfig,getShellEnv,hasTrackedProcessEffects,
3
- killProcessTreeAsync,killTrackedDetachedChildren,trackDetachedChildPid,untrackDetachedChildPid}from"./chunk-CRN54O4D.js";import{attestProviderRequest,normalizeAdmissionUsage}from"./chunk-GRJUKEE3.js";import{calculateCost,isModelType,lazyStream}from"./chunk-AEWYICBL.js";import{SubmissionAdmissionError}from"./chunk-4HTVBBJD.js";import{Check}from"./chunk-LB4CIS4F.js";import{typebox_exports}from"./chunk-VEGJT52D.js";import{isBunRuntime,resolvePath,waitForChildProcess}from"./chunk-VFLVWPLZ.js";function assertAdmittedModelInput(model,context){let requiredImageCount=0;for(let message of context.messages)if((message.role==="user"||message.role==="toolResult")&&Array.isArray(message.content))for(let block of message.content)block.type==="image"&&requiredImageCount++;if(requiredImageCount>0&&!model.input.includes("image"))throw new SubmissionAdmissionError("image-capability");return requiredImageCount}function admissionIntent(model,options){let effort=options?.reasoning??options?.reasoningEffort??
4
- options?.effort;return{requested:{provider:model.provider,model:model.id,protocol:model.api,...typeof effort=="string"?{effort}:{}},maxOutputTokens:options?.maxTokens}}function boundModelOutputTokens(requested,catalogMaximum){if(!Number.isSafeInteger(requested)||requested<=0||!Number.isSafeInteger(catalogMaximum)||catalogMaximum<0)throw new SubmissionAdmissionError("output-bound");return catalogMaximum===0?requested:Math.min(requested,catalogMaximum)}function submissionAdmission(admission,model,intent,purpose){
5
- return async observation=>{let chat=model,attestation=attestProviderRequest(observation,{...intent,requested:admission.requested??intent.requested,effective:{provider:model.provider,model:model.id,protocol:model.api},contextWindow:chat.contextWindow,generationLimit:chat.maxTokens,tools:chat.tools,images:model.input.includes("image")});if(attestation.effective.model===null||attestation.effective.protocol!==model.api)throw new SubmissionAdmissionError("unsupported-route");if(intent.requiredImageCount&&
6
- (attestation.images.value!==!0||attestation.imageInputCount.value===null||attestation.imageInputCount.value<intent.requiredImageCount))throw new SubmissionAdmissionError("image-capability");let maxOutputTokens=attestation.maxOutputTokens.value;if(maxOutputTokens===null||maxOutputTokens>boundModelOutputTokens(intent.maxOutputTokens??chat.maxTokens,chat.maxTokens))throw new SubmissionAdmissionError("output-bound");let estimate=admission.estimate(observation,attestation);if(!Number.isSafeInteger(estimate.
7
- inputTokens)||estimate.inputTokens<0||!Number.isSafeInteger(estimate.inputTokens+maxOutputTokens)||estimate.spend!==null&&(!Number.isFinite(estimate.spend)||estimate.spend<0))throw new SubmissionAdmissionError("invalid-estimate");await admission.reserve({requestId:observation.requestId,submissionId:observation.submissionId,submissionNumber:observation.submissionNumber,inputTokens:estimate.inputTokens,maxOutputTokens,reservedSpend:estimate.spend,purpose,attestation})}}function reconcileAdmittedUsage(admission,submission,usage,model){
8
- let normalized=normalizeAdmissionUsage(usage,submission.api),total=normalized&&usage?usage.cost.totalFromProvider===!0?usage.cost.total:calculateCost(model,{...usage,...normalized,cost:{...usage.cost}}).total:null,spend=typeof total=="number"&&Number.isFinite(total)&&total>=0?total:null;admission.reconcile({requestId:submission.requestId,submissionId:submission.submissionId,usageRecordId:submission.requestId,usage:normalized,spend,spendProvenance:spend===null?"unknown":usage?.cost.totalFromProvider===
9
- !0?"response":"catalog"})}var VIRTUAL_MODEL_API="pi-virtual",VIRTUAL_MODEL_STATE_ENTRY="pi.virtual-model-state",THINKING_LEVELS=["off","minimal","low","medium","high","xhigh","max"];function isVirtualModel(model){return model.api===VIRTUAL_MODEL_API}function findLatestResponse(messages){for(let i=messages.length-1;i>=0;i--){let message=messages[i];if(message.role==="assistant"&&message.stopReason!=="error"&&message.stopReason!=="aborted")return message}}function getBranchSelection(branch,getModel){for(let i=branch.length-
10
- 1;i>=0;i--){let entry=branch[i];if(entry.type==="model_change")return{provider:entry.provider,modelId:entry.modelId};if(entry.type==="message"&&entry.message.role==="assistant"&&!isVirtualModel(entry.message)){let response={provider:entry.message.provider,modelId:entry.message.model},change=findLastModelChange(branch,i),model=change&&getModel(change.provider,change.modelId);return change&&model&&isVirtualModel(model)?change:response}}}function findLastModelChange(branch,before){for(let i=before-
11
- 1;i>=0;i--){let entry=branch[i];if(entry.type==="model_change")return{provider:entry.provider,modelId:entry.modelId}}}function getVirtualModelState(branch,provider,modelId){for(let i=branch.length-1;i>=0;i--){let entry=branch[i];if(entry.type!=="custom"||entry.customType!==VIRTUAL_MODEL_STATE_ENTRY)continue;let data=entry.data;if(data?.provider===provider&&data.modelId===modelId)return data.state}}function createVirtualModel(definition){let levels=definition.thinkingLevels??["off"],thinkingLevelMap={};
12
- for(let level of THINKING_LEVELS)thinkingLevelMap[level]=levels.includes(level)?level:null;return{id:definition.id,name:definition.name,api:VIRTUAL_MODEL_API,provider:definition.provider,baseUrl:"",reasoning:levels.some(level=>level!=="off"),thinkingLevelMap,input:definition.input??["text","image"],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:definition.contextWindow??0,maxTokens:definition.maxTokens??0}}function unroutedStream(model){return lazyStream(model,async()=>{throw new Error(
13
- `Virtual model ${model.provider}/${model.id} must be routed before streaming`)})}function withVirtualModels(providerId,provider,virtualModels){if(!provider)return{id:providerId,name:providerId,auth:{apiKey:{name:"Virtual model",resolve:async()=>({auth:{},source:"virtual"})}},getModels:()=>virtualModels,stream:unroutedStream,streamSimple:unroutedStream};let ids=new Set(virtualModels.map(model=>model.id)),physical=models=>models.filter(model=>!isVirtualModel(model)&&!(isModelType(model,"chat")&&ids.
14
- has(model.id))),virtual=models=>models.filter(model=>isVirtualModel(model)),{filterModels,filterAllModels}=provider;return{...provider,getModels:()=>[...physical(provider.getModels()),...virtualModels],getAllModels:()=>[...physical(provider.getAllModels?.()??provider.getModels()),...virtualModels],filterModels:(models,credential)=>{let real=physical(models);return[...filterModels?.(real,credential)??real,...virtual(models)]},filterAllModels:filterAllModels&&((models,credential)=>[...filterAllModels(
15
- physical(models),credential),...virtual(models)]),stream:(model,context,options)=>isVirtualModel(model)?unroutedStream(model):provider.stream(model,context,options),streamSimple:(model,context,options)=>isVirtualModel(model)?unroutedStream(model):provider.streamSimple(model,context,options)}}import{accessSync,constants}from"node:fs";import{access}from"node:fs/promises";var NARROW_NO_BREAK_SPACE="\u202F";function tryMacOSScreenshotPath(filePath){return filePath.replace(/ (AM|PM)\./gi,`${NARROW_NO_BREAK_SPACE}$1.`)}function tryNFDVariant(filePath){return filePath.normalize("NFD")}function tryCurlyQuoteVariant(filePath){return filePath.replace(/'/g,"\u2019")}function fileExists(filePath){try{return accessSync(filePath,constants.F_OK),!0}catch{return!1}}async function pathExists(filePath){try{return await access(filePath,constants.F_OK),!0}catch{return!1}}function resolveToCwd(filePath,cwd){return resolvePath(filePath,cwd,{normalizeUnicodeSpaces:!0,stripAtPrefix:!0})}function resolveReadPath(filePath,cwd){let resolved=resolveToCwd(filePath,cwd);if(fileExists(resolved))return resolved;let amPmVariant=tryMacOSScreenshotPath(resolved);if(amPmVariant!==resolved&&fileExists(amPmVariant))return amPmVariant;let nfdVariant=tryNFDVariant(resolved);if(nfdVariant!==resolved&&fileExists(nfdVariant))return nfdVariant;let curlyVariant=tryCurlyQuoteVariant(resolved);
16
- if(curlyVariant!==resolved&&fileExists(curlyVariant))return curlyVariant;let nfdCurlyVariant=tryCurlyQuoteVariant(nfdVariant);return nfdCurlyVariant!==resolved&&fileExists(nfdCurlyVariant)?nfdCurlyVariant:resolved}async function resolveReadPathAsync(filePath,cwd){let resolved=resolveToCwd(filePath,cwd);if(await pathExists(resolved))return resolved;let amPmVariant=tryMacOSScreenshotPath(resolved);if(amPmVariant!==resolved&&await pathExists(amPmVariant))return amPmVariant;let nfdVariant=tryNFDVariant(
17
- resolved);if(nfdVariant!==resolved&&await pathExists(nfdVariant))return nfdVariant;let curlyVariant=tryCurlyQuoteVariant(resolved);if(curlyVariant!==resolved&&await pathExists(curlyVariant))return curlyVariant;let nfdCurlyVariant=tryCurlyQuoteVariant(nfdVariant);return nfdCurlyVariant!==resolved&&await pathExists(nfdCurlyVariant)?nfdCurlyVariant:resolved}import{constants as constants2}from"node:fs";import{access as fsAccess}from"node:fs/promises";import{constants as osConstants}from"node:os";import{spawn as spawn2}from"child_process";import{AsyncLocalStorage}from"node:async_hooks";import{spawn}from"node:child_process";var scopes=new AsyncLocalStorage;async function withReadOnlyAcceptanceCommand(id,command,cwd,signal,run){let filter=socketFilter();return!filter||!await sandboxAvailable(filter,signal)?run():scopes.run({id,command,cwd,executions:0,completed:!1},run)}function acceptanceCommandIsReadOnly(id){let scope=scopes.getStore();return scope?.id===id&&scope.executions===1&&scope.completed}function readOnlyAcceptanceSpawn(command,cwd,shell,env){let scope=scopes.getStore();if(!(!scope||scope.command!==command||
18
- scope.cwd!==cwd||hasLoaderOverrides(env)))return scope.executions++,{shell:"/usr/bin/bwrap",args:[...sandboxArgs(),"--",shell.shell,...shell.args],commandTransport:shell.commandTransport,filter:socketFilter(),completed:()=>{scope.completed=!0},retry:run=>(scope.executions++,scopes.exit(run))}}function sandboxArgs(){return["--unshare-all","--unshare-user","--disable-userns","--cap-drop","ALL","--ro-bind","/","/","--proc","/proc","--dev","/dev","--die-with-parent","--new-session","--seccomp","3"]}
19
- function socketFilter(){if(process.platform!=="linux"||!["x64","arm64"].includes(process.arch))return;let arch=process.arch==="x64"?3221225534:3221225655,denied=process.arch==="x64"?[41,42,44,46,85,248,249,250,303,307]:[198,203,206,211,217,218,219,265,269],opens=process.arch==="x64"?[[2,1],[257,2]]:[[56,2]],instructions=[[32,0,0,4],[21,1,0,arch],[6,0,0,2147483648],[32,0,0,0],[53,0,1,1073741824],[6,0,0,2147483648],[21,0,4,process.arch==="x64"?16:29],[32,0,0,24],[21,1,0,21537],[6,0,0,327681],[6,0,
20
- 0,2147418112],...opens.flatMap(([syscall,flagsArgument])=>[[21,0,4,syscall],[32,0,0,16+flagsArgument*8],[69,0,1,1603],[6,0,0,327681],[32,0,0,0]]),...[...denied,425,426,427,437].flatMap(syscall=>[[21,0,1,syscall],[6,0,0,327681]]),[6,0,0,2147418112]],buffer=Buffer.alloc(instructions.length*8);for(let[index,instruction]of instructions.entries())buffer.writeUInt16LE(instruction[0],index*8),buffer[index*8+2]=instruction[1],buffer[index*8+3]=instruction[2],buffer.writeUInt32LE(instruction[3],index*8+4);
21
- return buffer}function hasLoaderOverrides(env){return Object.keys(env).some(name=>/^(?:LD_|GLIBC_TUNABLES$)/.test(name)&&env[name]!==void 0)}async function sandboxAvailable(filter,signal){if(signal.aborted||hasLoaderOverrides(process.env))return!1;let child=spawn("/usr/bin/bwrap",[...sandboxArgs(),"--","/bin/true"],{stdio:["ignore","ignore","ignore","pipe"],detached:!0,signal:AbortSignal.any([signal,AbortSignal.timeout(2e3)]),killSignal:"SIGKILL"});child.pid&&trackDetachedChildPid(child.pid,child);
22
- let input=child.stdio[3];input&&"end"in input&&(input.on("error",()=>{}),input.end(filter));let available=!1;try{available=await waitForChildProcess(child)===0}catch{}finally{child.pid&&(available=await killProcessTreeAsync(child.pid,0,child)&&available,untrackDetachedChildPid(child.pid,child))}return available}import{once}from"node:events";import{open}from"node:fs/promises";import{finished}from"node:stream/promises";var bashJobOutputSchema=typebox_exports.Object({job_id:typebox_exports.String(),command:typebox_exports.String(),status:typebox_exports.Union([typebox_exports.Literal("running"),typebox_exports.Literal("completed"),typebox_exports.Literal("failed"),typebox_exports.Literal("killed")]),output:typebox_exports.String(),truncated:typebox_exports.Boolean(),output_dropped:typebox_exports.Boolean(),full_output_path:typebox_exports.String(),exit_code:typebox_exports.Optional(typebox_exports.Number()),error:typebox_exports.
23
- Optional(typebox_exports.String())}),adaptiveBashJobOutputSchema=typebox_exports.Object({...bashJobOutputSchema.properties,status:typebox_exports.Union([...bashJobOutputSchema.properties.status.anyOf,typebox_exports.Literal("interrupted")])}),jobInputResultSchema=typebox_exports.Object({status:typebox_exports.Union([typebox_exports.Literal("written"),typebox_exports.Literal("closed"),typebox_exports.Literal("unsupported"),typebox_exports.Literal("backpressure")]),bytes:typebox_exports.Integer({minimum:0,
24
- maximum:64*1024,description:"Bytes confirmed written to the transport, not consumed by the process. Closed input may have partial delivery."})}),MAX_JOB_INPUT_BYTES=64*1024,provenanceSchema=typebox_exports.Object({runId:typebox_exports.String({minLength:1}),ownerId:typebox_exports.String({minLength:1}),sessionId:typebox_exports.String({minLength:1}),generation:typebox_exports.Integer({minimum:0,maximum:Number.MAX_SAFE_INTEGER}),command:typebox_exports.String(),cwd:typebox_exports.String(),environmentIdentity:typebox_exports.
25
- String({pattern:"^[a-f0-9]{64}$"}),lineage:typebox_exports.Array(typebox_exports.String({minLength:1})),deadline:typebox_exports.Number(),reserveCutoff:typebox_exports.Number(),process:typebox_exports.Optional(typebox_exports.Object({pid:typebox_exports.Integer({minimum:2,maximum:Number.MAX_SAFE_INTEGER}),parentPid:typebox_exports.Integer({minimum:1,maximum:Number.MAX_SAFE_INTEGER})},{additionalProperties:!1}))},{additionalProperties:!1}),snapshotSchema=typebox_exports.Object({result:typebox_exports.
26
- Object(adaptiveBashJobOutputSchema.properties,{additionalProperties:!1}),provenance:provenanceSchema},{additionalProperties:!1}),MAX_ACTIVE_JOBS=4,MAX_RETAINED_JOBS=32,MAX_OUTPUT_BYTES=10*1024*1024,exitCleanupRegistered=!1,BashJobManager=class{jobs=new Map;processes=new Map;nextId=1;closed=!1;recoveryUnknown=!1;custodyUncertain=!1;options;constructor(options={}){this.options=options}get nextJobId(){return this.nextId}recoverNextId(value){if(typeof value!="number"||!Number.isSafeInteger(value)||value<
27
- 1)throw new Error("Invalid recovered job identity high-water mark");if(this.closed||this.jobs.size)throw new Error("Job identity recovery requires an empty open manager");this.nextId=Math.max(this.nextId,value)}get hasActiveEffects(){let active=this.custodyUncertain||this.recoveryUnknown;for(let[pid,child]of this.processes)hasTrackedProcessEffects(pid,child)?active=!0:this.processes.delete(pid);for(let job of this.jobs.values())job.effectsActive&&(active=!0);return active}ownProcess(child,custody="\
28
- uncertain"){this.registerExitCleanup();let pid=child.pid;pid&&(custody==="uncertain"&&(this.custodyUncertain=!0),this.processes.set(pid,child),child.once("close",()=>{hasTrackedProcessEffects(pid,child)||this.processes.delete(pid)}))}start(operations,context,timeout,runContext=this.options.getRunContext?.()){if(this.closed)throw new Error("Background job manager is closed");if(this.nextId>=Number.MAX_SAFE_INTEGER)throw new Error("Background job identity namespace exhausted");if(this.recoveryUnknown)
29
- throw new Error("Restored process custody unknown; new work requires owner reconciliation");if(timeout!==void 0&&(!Number.isFinite(timeout)||timeout<=0||timeout*1e3>2147483647))throw new Error("Invalid timeout");if(runContext&&admitBashRun(runContext),[...this.jobs.values()].filter(job2=>job2.effectsActive).length>=MAX_ACTIVE_JOBS)throw new Error(`Background job limit reached (${MAX_ACTIVE_JOBS} active jobs)`);if(this.jobs.size>=MAX_RETAINED_JOBS){for(let[id,job2]of this.jobs)if(!job2.effectsActive){
30
- this.jobs.delete(id);break}}let provenance=runContext?{runId:runContext.runId,ownerId:runContext.ownerId,sessionId:runContext.sessionId,generation:runContext.generation,command:context.command,cwd:context.cwd,environmentIdentity:runContext.environmentIdentity,lineage:[...runContext.lineage],deadline:runContext.deadline,reserveCutoff:runContext.reserveCutoff}:void 0;this.assertCustody({runContext,provenance});let{path,stream}=createOutputFileStream("pi-bash-job",".log");this.registerExitCleanup();
31
- let closed=finished(stream,{cleanup:!0});closed.catch(()=>{});let inputReady=()=>{},inputRegistration=new Promise(resolve2=>{inputReady=resolve2}),job={effectsActive:!0,result:{job_id:String(this.nextId++),command:context.command,status:"running",output:"",truncated:!1,output_dropped:!1,full_output_path:path},controller:new AbortController,done:Promise.resolve(),ready:once(stream,"open"),bytes:0,cursor:0,decoder:new TextDecoder,reading:Promise.resolve(),runContext,provenance,inputReady:inputRegistration,
32
- writingInput:!1,executionFinished:!1};(!runContext||!operations.supportsStdin)&&inputReady();let deadlineTimer,deadlineExpired=!1;return runContext&&(deadlineTimer=setTimeout(()=>{deadlineExpired=!0,job.controller.abort()},Math.min(2147483647,Math.max(0,runContext.deadline-runContext.now())))),this.jobs.set(job.result.job_id,job),job.done=(async()=>{let exitCode=null,cleanupUnknown=!1;try{await job.ready;let remaining=runContext?admitBashRun(runContext):void 0;if(exitCode=(await operations.exec(
33
- context.command,context.cwd,{signal:job.controller.signal,timeout:remaining===void 0?timeout:Math.min(timeout??2147483647e-3,remaining),env:context.env,...runContext?{deadline:runContext.deadline,now:runContext.now,beforeSpawn:()=>{this.assertCustody(job),admitBashRun(runContext)},onProcessStarted:child=>{provenance&&child.pid&&(provenance.process={pid:child.pid,parentPid:process.pid})}}:{},...runContext&&operations.supportsStdin?{onStdin:input=>{job.input=input,inputReady()}}:{},terminateChildrenOnExit:!0,
34
- onData:async data=>{let captured=data.subarray(0,Math.max(0,MAX_OUTPUT_BYTES-job.bytes));captured.length<data.length&&(job.result.output_dropped=!0),captured.length&&(await new Promise((resolve2,reject)=>{stream.write(captured,error=>error?reject(error):resolve2())}),job.bytes+=captured.length)}})).exitCode,exitCode===null)throw new Error("Command terminated without an exit code");job.result.exit_code=exitCode}catch(error){cleanupUnknown=error instanceof BashProcessCleanupError,runContext&&cleanupUnknown&&
35
- (this.recoveryUnknown=!0),job.result.error=error instanceof Error?error.message:String(error)}finally{deadlineTimer&&clearTimeout(deadlineTimer),job.executionFinished=!0,inputReady(),job.input=void 0,deadlineExpired&&(job.result.error=`Run deadline exceeded${cleanupUnknown?`; ${job.result.error}`:""}`),stream.end();try{await closed}catch(error){job.result.error=error instanceof Error?error.message:String(error)}if(job.effectsActive=cleanupUnknown,job.result.status=runContext&&cleanupUnknown?"int\
36
- errupted":job.controller.signal.aborted?"killed":exitCode===0&&!job.result.error?"completed":"failed",provenance&&runContext?.onTerminal)try{runContext.onTerminal({result:{...job.result},provenance:{...provenance,lineage:[...provenance.lineage]}})}catch(error){job.result.error=`Terminal notification failed: ${error instanceof Error?error.message:String(error)}`}}})(),{...job.result}}list(){return[...this.jobs.values()].map(job=>(this.assertObservable(job),{...job.result}))}async read(id){let job=this.
37
- get(id);this.assertObservable(job);let reading=job.reading.then(async()=>{await job.ready.catch(()=>{}),this.assertObservable(job);let end=job.bytes,start=Math.max(job.cursor,end-51200),skipped=start>job.cursor,output="";if(end>start){let file=await open(job.result.full_output_path,"r");try{let buffer=Buffer.alloc(end-start),{bytesRead}=await file.read(buffer,0,buffer.length,start);this.assertObservable(job);let offset=0;if(skipped)for(job.decoder=new TextDecoder;offset<bytesRead&&(buffer[offset]&
38
- 192)===128;)offset++;output=job.decoder.decode(buffer.subarray(offset,bytesRead),{stream:job.result.status==="running"}),job.cursor=start+bytesRead}finally{await file.close()}}else job.result.status!=="running"&&(output=job.decoder.decode());let truncated=truncateTail(output);return{...job.result,output:truncated.content,truncated:skipped||truncated.truncated}});return job.reading=reading.catch(()=>{}),reading}async wait(id,seconds,signal){let job=this.get(id);this.assertCustody(job);let timer,aborted=!1,
39
- cancel=()=>{},canceled=new Promise(resolve2=>{cancel=()=>{aborted=!0,resolve2()}});signal?.addEventListener("abort",cancel,{once:!0}),signal?.aborted&&cancel();try{if(await Promise.race([job.done,canceled,new Promise(resolve2=>{timer=setTimeout(resolve2,seconds*1e3)})]),aborted)throw await this.abort(),new Error("Job wait aborted");return await this.read(id)}finally{timer&&clearTimeout(timer),signal?.removeEventListener("abort",cancel)}}async kill(id){let job=this.get(id);return this.assertCustody(
40
- job),job.result.status==="running"&&job.controller.abort(),await job.done,this.read(id)}async stdin(id,input,eof=!1,signal){let job=this.get(id);if(this.assertCustody(job),typeof input!="string"||typeof eof!="boolean")throw new Error("Invalid stdin input/eof");if(!job.runContext&&!job.provenance)return{status:"unsupported",bytes:0};if(job.result.status!=="running")return{status:"closed",bytes:0};if(Buffer.byteLength(input)>MAX_JOB_INPUT_BYTES||job.writingInput)return{status:"backpressure",bytes:0};
41
- job.writingInput=!0;let cancel=()=>{},cancellation=new Promise(resolve2=>{cancel=resolve2}).then(async()=>{throw this.assertCustody(job),job.controller.abort(),await job.done,new Error("Job stdin aborted")});signal?.addEventListener("abort",cancel,{once:!0}),signal?.aborted&&cancel();try{let writing=(async()=>{if(await job.inputReady,this.assertCustody(job),job.result.status!=="running"||job.controller.signal.aborted||job.executionFinished)return{status:"closed",bytes:0};let current=this.options.
42
- getRunContext?this.options.getRunContext():job.runContext;return current&&admitBashRun(current),job.input?await job.input.write(input,eof):{status:"unsupported",bytes:0}})(),result=await Promise.race([writing,cancellation]);return signal?.aborted&&await cancellation,result}finally{signal?.removeEventListener("abort",cancel),job.writingInput=!1}}snapshot(){let records=[];for(let job of this.jobs.values())this.assertObservable(job),job.provenance&&records.push({result:{...job.result},provenance:{...job.
43
- provenance,lineage:[...job.provenance.lineage]}});return records}restore(records){if(this.closed||this.jobs.size)throw new Error("Job restore requires an empty open manager");let current=this.options.getRunContext?.();if(!current)throw new Error("Job restore requires run custody");if(current.assertCurrent(),!Check(typebox_exports.Array(snapshotSchema,{maxItems:MAX_RETAINED_JOBS}),records))throw new Error("Invalid job restore records");let ids=new Set;for(let record of records){let id=Number(record.
44
- result.job_id);if(!Number.isSafeInteger(id)||id<1||id>=Number.MAX_SAFE_INTEGER||String(id)!==record.result.job_id||ids.has(record.result.job_id)||!Number.isFinite(record.provenance.deadline)||!Number.isFinite(record.provenance.reserveCutoff)||record.provenance.reserveCutoff>record.provenance.deadline)throw new Error("Invalid job restore identity");ids.add(record.result.job_id),this.assertCustody({provenance:record.provenance})}this.recoveryUnknown=records.length>0;for(let record of records)this.
45
- jobs.set(record.result.job_id,{effectsActive:!0,result:{...record.result,output:"",status:"interrupted",error:"Original process custody unavailable; outcome unknown; do not replay"},provenance:{...record.provenance,lineage:[...record.provenance.lineage]},controller:new AbortController,done:Promise.resolve(),ready:Promise.resolve(),bytes:0,cursor:0,decoder:new TextDecoder,reading:Promise.resolve(),inputReady:Promise.resolve(),writingInput:!1,executionFinished:!0}),this.nextId=Math.max(this.nextId,
46
- Number(record.result.job_id)+1)}async abort(){let jobs=[...this.jobs.values()].filter(job=>job.result.status==="running");for(let job of jobs)job.controller.abort();await Promise.all([...jobs.map(job=>job.done),...Array.from(this.processes,([pid,child])=>killProcessTreeAsync(pid,void 0,child))]),this.hasActiveEffects}dispose(){this.closed=!0,this.abort()}registerExitCleanup(){if(!exitCleanupRegistered){process.once("exit",()=>killTrackedDetachedChildren());for(let signal of["SIGINT","SIGTERM","S\
47
- IGHUP"])process.once(signal,()=>{killTrackedDetachedChildren(),process.listenerCount(signal)===0&&process.kill(process.pid,signal)});exitCleanupRegistered=!0}}get(id){let job=this.jobs.get(id);if(!job)throw new Error(`Unknown background job: ${id}`);return job}assertObservable(job){job.result.status==="running"&&this.assertCustody(job)}assertCustody(job){let provenance=job.provenance;if(!provenance)return;let current=this.options.getRunContext?this.options.getRunContext():job.runContext;if(!current||
48
- current.runId!==provenance.runId||current.ownerId!==provenance.ownerId||current.sessionId!==provenance.sessionId||current.generation!==provenance.generation)throw new Error("Background job custody mismatch");current.assertCurrent()}};import{open as open2}from"node:fs/promises";import{finished as finished2}from"node:stream/promises";var OutputCleanup=class{state="text";osc=!1;pendingHighSurrogate="";pendingGrapheme="";segmenter;eraseMode=0;validErase=!0;head;cursorPrevious;column=0;openLine=!1;previousLine;previousBlank=!1;repetitions=0;terminated=!1;finished=!1;append(text){if(this.finished)throw new Error("Cannot append to a finished output cleaner");if(text.length===0)return"";text=this.pendingHighSurrogate+text,this.pendingHighSurrogate="";let last=text.charCodeAt(text.length-1);last>=55296&&last<=56319&&(this.pendingHighSurrogate=
49
- text.slice(-1),text=text.slice(0,-1));let output=[],controls=/[\x00-\x08\x0a-\x1f\x7f-\x9f]/g,stringControls=/[\x07\x18\x1a\x1b\x9c]/g,index=0;for(;index<text.length;){if(this.state==="text"){controls.lastIndex=index;let end=controls.exec(text)?.index??text.length;if(end>index&&this.write(text,index,end),index=end,index===text.length)break}else if(this.state==="string"){stringControls.lastIndex=index;let match=stringControls.exec(text);if(!match)break;index=match.index}this.control(text.charCodeAt(
50
- index++),output)}return output.join("")}finish(){if(this.finished)return"";this.finished=!0;let output=[];return this.pendingHighSurrogate&&(this.state==="text"?this.write(this.pendingHighSurrogate,0,1):this.control(this.pendingHighSurrogate.charCodeAt(0),output),this.pendingHighSurrogate=""),this.flushGrapheme(),this.openLine&&this.completeLine(!1,output),this.flushRun(output),this.state="text",output.join("")}control(code,output){if(code===24||code===26){this.state="text";return}if(this.state===
51
- "string-escape"){if(code===92){this.state="text";return}this.state="string"}if(this.state==="string"){code===27?this.state="string-escape":(code===156||this.osc&&code===7)&&(this.state="text");return}if(code===27){this.state="escape";return}if(code===155||this.state==="escape"&&code===91){this.state="csi",this.eraseMode=0,this.validErase=!0;return}if(code===144||code===152||code===157||code===158||code===159||this.state==="escape"&&[80,88,93,94,95].includes(code)){this.osc=code===157||code===93,
52
- this.state="string";return}if(code===10){this.completeLine(!0,output);return}if(code===13){this.flushGrapheme(),this.cursorPrevious=void 0,this.column=0;return}code<32||code>=127&&code<=159||(this.state==="escape"||this.state==="intermediate"?this.state=code>=32&&code<=47?"intermediate":"text":this.state==="csi"&&(code>=64&&code<=126?(code===75&&this.validErase&&this.eraseMode<=2&&this.eraseLine(),this.state="text"):code>=48&&code<=57?this.eraseMode=Math.min(3,this.eraseMode*10+code-48):this.validErase=
53
- !1))}write(text,start,end){let visible=this.pendingGrapheme+Buffer.from(text.slice(start,end),"utf16le").toString("utf16le");this.pendingGrapheme="";let asciiRuns=/[\x20-\x7e]{3,}/g,index=0;for(let match of visible.matchAll(asciiRuns)){this.segment(visible.slice(index,match.index+1)),this.flushGrapheme();let end2=match.index+match[0].length-1;this.writeRun(visible.slice(match.index+1,end2),end2-match.index-1,!0),index=end2}this.segment(visible.slice(index))}segment(text){this.segmenter??=new Intl.
54
- Segmenter(void 0,{granularity:"grapheme"});for(let{segment}of this.segmenter.segment(text))this.flushGrapheme(),this.pendingGrapheme=segment}flushGrapheme(){if(!this.pendingGrapheme)return;let text=this.pendingGrapheme;this.pendingGrapheme="";let width=text===" "?8-this.column%8:visibleWidth(text);this.writeRun(text,width,/^[\x20-\x7e]+$/.test(text))}writeRun(text,width,ascii){let next=this.skip(this.cursorPrevious?this.cursorPrevious.next:this.head,width),run={text,start:0,end:text.length,width,
55
- ascii,next};this.cursorPrevious?this.cursorPrevious.next=run:this.head=run,this.cursorPrevious=run,this.column+=width,this.openLine=!0}skip(next,remaining){for(;next&&remaining>=next.width;)remaining-=next.width,next=next.next;return next&&remaining>0&&(next.width-=remaining,next.ascii?next.start+=remaining:(next.text=" ".repeat(next.width),next.start=0,next.end=next.width,next.ascii=!0)),next}eraseLine(){if(this.flushGrapheme(),this.eraseMode===0){this.cursorPrevious?this.cursorPrevious.next=void 0:
56
- this.head=void 0;return}let next=this.cursorPrevious?this.cursorPrevious.next:this.head;this.eraseMode===2?next=void 0:next&&(next={text:" ",start:0,end:1,width:1,ascii:!0,next:this.skip(next,1)}),this.head=this.column>0?{text:" ".repeat(this.column),start:0,end:this.column,width:this.column,ascii:!0,next}:next,this.cursorPrevious=this.column>0?this.head:void 0}completeLine(terminated,output){this.flushGrapheme();let parts=[];for(let run=this.head;run;run=run.next)parts.push(run.text.slice(run.start,
57
- run.end));let line=parts.join(""),blank=/^[\t ]*$/.test(line);this.previousLine!==void 0&&(line===this.previousLine||blank&&this.previousBlank)?this.repetitions++:(this.flushRun(output),this.previousLine=line,this.previousBlank=blank),this.terminated=terminated,this.head=void 0,this.cursorPrevious=void 0,this.column=0,this.openLine=!1}flushRun(output){this.previousLine!==void 0&&(output.push(this.previousLine),this.repetitions>0&&output.push(`
58
- [previous line repeated ${this.repetitions} more times]`),this.terminated&&output.push(`
59
- `),this.previousLine=void 0,this.repetitions=0)}};function byteLength(text){return Buffer.byteLength(text,"utf-8")}var OutputAccumulator=class{maxLines;maxBytes;maxRollingBytes;tempFilePrefix;decoder=new TextDecoder;cleanup;headAndTail;headText="";headComplete=!1;rawChunks=[];tailText="";tailBytes=0;tailStartsAtLineBoundary=!0;totalRawBytes=0;totalDecodedBytes=0;completedLines=0;totalLines=0;currentLineBytes=0;hasOpenLine=!1;finished=!1;tempFilePath;tempFileStream;tempFileDone;pendingDrain;constructor(options={}){this.cleanup=options.cleanup?new OutputCleanup:
60
- void 0,this.headAndTail=options.headAndTail??!1,this.maxLines=options.maxLines??2e3,this.maxBytes=options.maxBytes??51200,this.maxRollingBytes=Math.max(this.maxBytes*2,1),this.tempFilePrefix=options.tempFilePrefix??"pi-output"}append(data){if(this.finished)throw new Error("Cannot append to a finished output accumulator");this.totalRawBytes+=data.length;let decoded=this.decoder.decode(data,{stream:!0});if(this.appendDecodedText(this.cleanup?this.cleanup.append(decoded):decoded),this.cleanup||this.
61
- tempFileStream||this.shouldUseTempFile()){this.ensureTempFile();let stream=this.tempFileStream;if(stream.errored)throw stream.errored;if(stream.write(data),stream.writableNeedDrain)return this.waitForDrain()}else data.length>0&&this.rawChunks.push(data)}finish(){if(this.finished)return;this.finished=!0;let decoded=this.decoder.decode();this.appendDecodedText(this.cleanup?this.cleanup.append(decoded)+this.cleanup.finish():decoded),this.shouldUseTempFile()&&this.ensureTempFile()}snapshot(options={}){
62
- this.cleanup&&this.ensureTempFile();let snapshot=this.contentSnapshot(options);if(!this.cleanup)return snapshot;let content=`${snapshot.content}
63
-
64
- [Output cleanup applied (terminal controls, CR overwrites, repeated/blank lines). Raw output: ${snapshot.fullOutputPath}. Use read with offset/limit, or grep the saved file.]`;return{...snapshot,content,truncation:{...snapshot.truncation,content}}}contentSnapshot(options){if(this.headAndTail)return this.headAndTailSnapshot();let tailTruncation=truncateTail(this.getSnapshotText(),{maxLines:this.maxLines,maxBytes:this.maxBytes}),truncated=this.totalLines>this.maxLines||this.totalDecodedBytes>this.
65
- maxBytes,truncatedBy=truncated?tailTruncation.truncatedBy??(this.totalDecodedBytes>this.maxBytes?"bytes":"lines"):null,truncation={...tailTruncation,truncated,truncatedBy,totalLines:this.totalLines,totalBytes:this.totalDecodedBytes,maxLines:this.maxLines,maxBytes:this.maxBytes};return options.persistIfTruncated&&truncation.truncated&&this.ensureTempFile(),{content:truncation.content,truncation,fullOutputPath:this.tempFilePath}}async closeTempFile(){this.tempFileStream&&(this.tempFileStream.end(),
66
- await this.tempFileDone)}async readFullOutput(maxBytes){if(!this.tempFilePath)return{content:new TextDecoder().decode(Buffer.concat(this.rawChunks)),truncated:!1};let file=await open2(this.tempFilePath,"r");try{let size=(await file.stat()).size;if(size<=maxBytes)return{content:new TextDecoder().decode(await file.readFile()),truncated:!1};let headBytes=Math.floor(maxBytes/2),tailBytes=maxBytes-headBytes,head=Buffer.alloc(headBytes),tail=Buffer.alloc(tailBytes);await file.read(head,0,headBytes,0),
67
- await file.read(tail,0,tailBytes,size-tailBytes);let headText=new TextDecoder().decode(head,{stream:!0}),tailStart=0;for(;tailStart<tail.length&&(tail[tailStart]&192)===128;)tailStart++;let tailText=new TextDecoder().decode(tail.subarray(tailStart)),omitted=size-headBytes-tailBytes;return{content:`${headText}
68
-
69
- [... ${omitted} bytes omitted ...]
70
-
71
- ${tailText}`,truncated:!0}}finally{await file.close()}}headAndTailSnapshot(){let truncated=this.totalLines>this.maxLines||this.totalDecodedBytes>this.maxBytes,content=this.tailText,outputBytes=this.totalDecodedBytes,outputLines=this.totalLines;if(truncated){this.ensureTempFile();let head=this.headText.split(`
72
- `).slice(0,Math.floor(this.maxLines/2)).join(`
73
- `),tail=truncateTail(this.tailText,{maxBytes:this.maxBytes-Math.floor(this.maxBytes/2),maxLines:this.maxLines-Math.floor(this.maxLines/2)});outputBytes=byteLength(head)+tail.outputBytes,outputLines=(head?head.split(`
74
- `).length-Number(head.endsWith(`
75
- `)):0)+tail.outputLines;let omitted=this.totalDecodedBytes-outputBytes;content=`${head}
76
-
77
- [... ${omitted} bytes omitted; showing head and tail (8 KiB / 2,000-line limit). Full output: ${this.tempFilePath}. Use read with offset/limit, or grep the saved file. Do not infer success from truncated output.]
78
-
79
- ${tail.content}`}return{content,fullOutputPath:this.tempFilePath,truncation:{content,truncated,truncatedBy:truncated?this.totalDecodedBytes>this.maxBytes?"bytes":"lines":null,totalBytes:this.totalDecodedBytes,totalLines:this.totalLines,outputBytes,outputLines,maxBytes:this.maxBytes,maxLines:this.maxLines,lastLinePartial:!1,firstLineExceedsLimit:!1}}}getLastLineBytes(){return this.currentLineBytes}appendDecodedText(text){if(text.length===0)return;let bytes=byteLength(text);if(this.headAndTail&&!this.
80
- headComplete){let limit=Math.floor(this.maxBytes/2),head=Buffer.from(this.headText+text.slice(0,limit));this.headText=new TextDecoder("utf-8",{ignoreBOM:!0}).decode(head.subarray(0,limit),{stream:!0}),this.headComplete=head.length>=limit}this.totalDecodedBytes+=bytes;let tailLength=this.tailText.length;if(this.tailBytes+bytes>this.maxRollingBytes*2&&bytes===text.length&&this.tailBytes===tailLength){let start=tailLength+bytes-this.maxRollingBytes,before=start-1<tailLength?this.tailText.charCodeAt(
81
- start-1):text.charCodeAt(start-1-tailLength);this.tailStartsAtLineBoundary=before===10,this.tailText=Buffer.from(start>=tailLength?text.slice(start-tailLength):this.tailText.slice(start)+text,"utf-8").toString("utf-8"),this.tailBytes=this.maxRollingBytes}else this.tailText+=text,this.tailBytes+=bytes,this.tailBytes>this.maxRollingBytes*2&&this.trimTail();let newlines=0,lastNewline=-1;for(let i=text.indexOf(`
82
- `);i!==-1;i=text.indexOf(`
83
- `,i+1))newlines++,lastNewline=i;if(newlines===0)this.currentLineBytes+=bytes,this.hasOpenLine=!0;else{this.completedLines+=newlines;let tail=text.slice(lastNewline+1);this.currentLineBytes=byteLength(tail),this.hasOpenLine=tail.length>0}this.totalLines=this.completedLines+(this.hasOpenLine?1:0)}trimTail(){let buffer=Buffer.from(this.tailText,"utf-8");if(buffer.length<=this.maxRollingBytes){this.tailBytes=buffer.length;return}let start=buffer.length-this.maxRollingBytes;for(;start<buffer.length&&
84
- (buffer[start]&192)===128;)start++;this.tailStartsAtLineBoundary=start===0?this.tailStartsAtLineBoundary:buffer[start-1]===10,this.tailText=buffer.subarray(start).toString("utf-8"),this.tailBytes=byteLength(this.tailText)}getSnapshotText(){if(this.tailStartsAtLineBoundary)return this.tailText;let firstNewline=this.tailText.indexOf(`
85
- `);return firstNewline===-1?this.tailText:this.tailText.slice(firstNewline+1)}shouldUseTempFile(){return this.totalRawBytes>this.maxBytes||this.totalDecodedBytes>this.maxBytes||this.totalLines>this.maxLines}ensureTempFile(){if(this.tempFilePath)return;let{path,stream}=createOutputFileStream(this.tempFilePrefix,".log");this.tempFilePath=path,this.tempFileStream=stream,this.tempFileDone=finished2(stream,{cleanup:!0}),this.tempFileDone.catch(()=>{});for(let chunk of this.rawChunks)this.tempFileStream.
86
- write(chunk);this.rawChunks=[]}waitForDrain(){if(this.pendingDrain)return this.pendingDrain;let stream=this.tempFileStream;return this.pendingDrain=new Promise((resolve2,reject)=>{let cleanup=()=>{stream.off("drain",onDrain),stream.off("error",onError),stream.off("close",onClose),stream.off("finish",onDrain),this.pendingDrain=void 0},onDrain=()=>{cleanup(),resolve2()},onError=error=>{cleanup(),reject(error)},onClose=()=>onError(stream.errored??new Error("Output file closed before draining"));stream.
87
- once("drain",onDrain),stream.once("error",onError),stream.once("close",onClose),stream.once("finish",onDrain)}),this.pendingDrain.catch(()=>{}),this.pendingDrain}};var plainRenderFunctions=new WeakSet,pathRenderFunctions=new WeakSet;function renderFunctions(renderers){return[renderers.renderCall,renderers.renderResult].filter(render=>render!==void 0)}function declarePlainRenderers(renderers){for(let render of renderFunctions(renderers))plainRenderFunctions.add(render)}function declarePathHighlightingRenderers(renderers){for(let render of renderFunctions(renderers))pathRenderFunctions.add(render)}function renderersMayHighlight(renderers,args,languages){if(renderers===
88
- void 0)return!1;let highlightsPath=!1;for(let render of renderFunctions(renderers))if(!plainRenderFunctions.has(render)){if(!pathRenderFunctions.has(render))return!0;highlightsPath=!0}if(!highlightsPath)return!1;let record=typeof args=="object"&&args!==null?args:{},path=typeof record.file_path=="string"?record.file_path:record.path,language=typeof path=="string"?getLanguageFromPath(path):void 0;return language!==void 0&&languages.has(language.toLowerCase())}var BASH_PREVIEW_LINES=5,BASH_UPDATE_THROTTLE_MS=100;function formatShellCall(args,prompt){let command=str(args?.command),timeout=args?.timeout,timeoutSuffix=timeout?theme.fg("muted",` (timeout ${timeout}s)`):"",commandDisplay=command===null?invalidArgText(theme):command||theme.fg("toolOutput","...");return theme.fg("toolTitle",theme.bold(`${prompt} ${commandDisplay}`))+timeoutSuffix}function rebuildBashResultRenderComponent(component,result,options,showImages,timerText){component.clear();let output=getTextOutput(
89
- result,showImages).trim(),truncation=result.details?.truncation,fullOutputPath=result.details?.fullOutputPath;if(!options.isPartial&&truncation?.truncated&&fullOutputPath&&output.endsWith("]")){let footerStart=output.lastIndexOf(`
90
-
91
- [`);footerStart!==-1&&output.startsWith(`
92
-
93
- [Showing `,footerStart)&&output.slice(footerStart).includes(fullOutputPath)&&(output=output.slice(0,footerStart).trimEnd())}if(output){let styleLine=line=>theme.fg("toolOutput",line);if(options.expanded){let styledOutput=output.split(`
94
- `).map(styleLine).join(`
95
- `);component.addChild(new Text(`
96
- ${styledOutput}`,0,0))}else component.addChild(new Spacer(1)),component.addChild(new VisualLinePreview({lines:output.split(`
97
- `),styleLine,maxVisualLines:BASH_PREVIEW_LINES,keep:"end",formatHint:hidden=>theme.fg("muted",`... (${hidden} earlier lines,`)+` ${keyHint("app.tools.expand","to expand")}${theme.fg("muted",")")}`}))}if(truncation?.truncated||fullOutputPath){let warnings=[];fullOutputPath&&warnings.push(`Full output: ${fullOutputPath}`),truncation?.truncated&&(truncation.truncatedBy==="lines"?warnings.push(`Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`):warnings.push(`Truncated:\
98
- ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes??51200)} limit)`)),component.addChild(new Text(`
99
- ${theme.fg("warning",`[${warnings.join(". ")}]`)}`,0,0))}timerText&&component.addChild(new Text(`
100
- ${theme.fg("muted",timerText)}`,0,0))}function createShellRenderers(prompt){let renderers={renderCall(args,_theme,context){startToolTimer(context);let text=context.lastComponent??new Text("",0,0);return text.setText(formatShellCall(args,prompt)),text},renderResult(result,options,_theme,context){let timerText=toolTimerText(context,options.isPartial),component=context.lastComponent??new Container;return rebuildBashResultRenderComponent(component,result,options,context.showImages,timerText),component.
101
- invalidate(),component}};return declarePlainRenderers(renderers),renderers}var SUBAGENT_DEPTH_ENV="HUMAIN_TERMINAL_SUBAGENT_DEPTH",SUBAGENT_MAX_DEPTH_ENV="HUMAIN_TERMINAL_SUBAGENT_MAX_DEPTH",SUBAGENT_MAX_CONCURRENCY_ENV="HUMAIN_TERMINAL_SUBAGENT_MAX_CONCURRENCY",SUBAGENT_MAX_WORKTREES_ENV="HUMAIN_TERMINAL_SUBAGENT_MAX_WORKTREES",SUBAGENT_MAX_TASKS_ENV="HUMAIN_TERMINAL_SUBAGENT_MAX_TASKS",TASK_ID_ENV="HUMAIN_TERMINAL_TASK_ID",PARENT_TASK_ID_ENV="HUMAIN_TERMINAL_PARENT_TASK_ID",TASK_BASE_REVISION_ENV="HUMAIN_TERMINAL_TASK_BASE_REVISION",DEFAULT_MAX_DEPTH=1,DEFAULT_MAX_CONCURRENCY=4,
102
- DEFAULT_MAX_TASKS=8,CEILING_DEPTH=3,CEILING_CONCURRENCY=8,CEILING_TASKS=16;function clampedInt(raw,fallback,min,max){let n=Number(raw);return raw===void 0||raw.trim()===""||!Number.isFinite(n)?fallback:Math.min(max,Math.max(min,Math.floor(n)))}function currentSubagentDepth(env=process.env){let raw=Number(env[SUBAGENT_DEPTH_ENV]??"0");return Number.isFinite(raw)&&raw>0?Math.floor(raw):0}function maxSubagentDepth(env=process.env){return clampedInt(env[SUBAGENT_MAX_DEPTH_ENV],DEFAULT_MAX_DEPTH,1,CEILING_DEPTH)}
103
- function maxSubagentConcurrency(env=process.env){return clampedInt(env[SUBAGENT_MAX_CONCURRENCY_ENV],DEFAULT_MAX_CONCURRENCY,1,CEILING_CONCURRENCY)}function maxSubagentWorktrees(env=process.env){return clampedInt(env[SUBAGENT_MAX_WORKTREES_ENV],maxSubagentConcurrency(env),1,CEILING_CONCURRENCY)}function maxParallelTasks(env=process.env){return clampedInt(env[SUBAGENT_MAX_TASKS_ENV],DEFAULT_MAX_TASKS,1,CEILING_TASKS)}function currentTaskId(env=process.env){let raw=env[TASK_ID_ENV]?.trim();return raw||
104
- void 0}function scrubTraceEnv(env){let scrubbed={...env};for(let name of Object.values(TRACE_ENV))delete scrubbed[name];return scrubbed}var DEFAULT_BASH_TIMEOUT_SECONDS=120,MAX_TIMEOUT_MS=2147483647,STRUCTURED_OUTPUT_MAX_BYTES=1024*1024,MAX_TIMEOUT_SECONDS=MAX_TIMEOUT_MS/1e3;function resolveTimeoutMs(timeout){if(timeout===void 0)return;if(!Number.isFinite(timeout)||timeout<=0)throw new Error("Invalid timeout: must be a finite number of seconds");let timeoutMs=timeout*1e3;if(timeoutMs>MAX_TIMEOUT_MS)throw new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);return timeoutMs}var shellSchema=typebox_exports.Object(
105
- {command:typebox_exports.String({description:"Shell command to execute"}),timeout:typebox_exports.Optional(typebox_exports.Number({description:"Timeout in seconds (optional, no default timeout)"}))}),bashSchema=typebox_exports.Object({...shellSchema.properties,background:typebox_exports.Optional(typebox_exports.Boolean({description:"Start session-owned background work and return a job ID"})),timeout:typebox_exports.Optional(typebox_exports.Number({description:`Timeout in seconds (optional, defau\
106
- lts to ${DEFAULT_BASH_TIMEOUT_SECONDS} seconds)`}))}),bashToolSystemPromptContribution={snippet:"Execute bash commands (ls, grep, find, etc.)",guidelines:["You can inspect HUMAIN_TERMINAL_* environment variables for current model and session details."]},bashOutputSchema=typebox_exports.Object({output:typebox_exports.String({description:"Combined stdout and stderr, possibly truncated"}),truncated:typebox_exports.Boolean(),full_output_path:typebox_exports.Optional(typebox_exports.String({description:"\
107
- Full output, when truncated"})),exit_code:typebox_exports.Number(),wall_time_seconds:typebox_exports.Number()}),BashProcessCleanupError=class extends Error{};function admitBashRun(context){context.assertCurrent();let now=context.now();if(![now,context.deadline,context.reserveCutoff].every(Number.isFinite)||context.reserveCutoff>context.deadline||!Number.isSafeInteger(context.generation)||context.generation<0||![context.runId,context.ownerId,context.sessionId].every(id=>typeof id=="string"&&id.length>
108
- 0)||!/^[a-f0-9]{64}$/.test(context.environmentIdentity)||!Array.isArray(context.lineage)||!context.lineage.every(id=>typeof id=="string"&&id.length>0)||!["implementation","verification"].includes(context.phase))throw new Error("Invalid bash run context");if(now>=context.deadline)throw new Error("Run deadline exceeded");if(context.phase==="implementation"&&now>=context.reserveCutoff)throw new Error("Run verification reserve reached");return(context.deadline-now)/1e3}var BashCleanupError=class extends BashProcessCleanupError{constructor(){
109
- super("Owned process cleanup unconfirmed"),this.name="BashCleanupError"}},ShellTimeoutError=class extends Error{shellExit;constructor(timeout,shellExit){super(`timeout:${timeout}`),this.shellExit=shellExit}},literalShellWord=String.raw`(?:[a-zA-Z0-9_./:=,%@+\-]+|'[^']*'|"[^"$\x60\\]*")`,literalPrintfFormat=String.raw`(?!['"]?-)(?:(?:[a-zA-Z0-9_./:=,@+\-]|%[s%])+|'(?:[^'%]|%[s%])*'|"(?:[^"%$\x60\\]|%[s%])*")`,launchFreeBuiltin=new RegExp(String.raw`^[ \t]*(?:builtin[ \t]+)?(?:printf[ \t]+${literalPrintfFormat}|echo|true|false|:)(?:[ \t]+${literalShellWord})*(?:[ \t]*>>?[ \t]*${literalShellWord})?[ \t]*$`);
110
- function createLocalShellOperations(shellName,resolveShellConfig,onProcessStarted){let operations={supportsStdin:!0,exec:async(command,cwd,{onData,signal,timeout,env,terminateChildrenOnExit,deadline,now,beforeSpawn,onStdin,onProcessStarted:recordProcessStarted})=>{let timeoutMs=resolveTimeoutMs(timeout);if(terminateChildrenOnExit&&process.platform==="win32")throw new Error("Local background bash jobs are unavailable on Windows");if(signal?.aborted)throw new Error("aborted");let originalShell=resolveShellConfig(),
111
- environment=scrubTraceEnv(env??getShellEnv()),readOnly=readOnlyAcceptanceSpawn(command,cwd,originalShell,environment),shellConfig=readOnly??originalShell;try{await fsAccess(cwd,constants2.F_OK)}catch{throw new Error(`Working directory does not exist: ${cwd}
112
- Cannot execute ${shellName} commands.`)}if(signal?.aborted)throw new Error("aborted");if(deadline!==void 0){let remaining=deadline-(now??(()=>performance.now()))();if(remaining<=0)throw new Error("Run deadline exceeded");timeoutMs=Math.min(timeoutMs??MAX_TIMEOUT_MS,remaining,MAX_TIMEOUT_MS)}beforeSpawn?.();let commandFromStdin=shellConfig.commandTransport==="stdin",child=spawn2(shellConfig.shell,commandFromStdin?shellConfig.args:[...shellConfig.args,command],{cwd,detached:process.platform!=="win\
113
- 32",env:environment,stdio:[commandFromStdin||onStdin?"pipe":"ignore","pipe","pipe",...readOnly?["pipe"]:[]],windowsHide:!0}),filterInput=readOnly?child.stdio[3]:void 0;readOnly&&filterInput&&"end"in filterInput&&(filterInput.on("error",()=>{}),filterInput.end(readOnly.filter)),child.pid&&trackDetachedChildPid(child.pid,child);let launchFree=originalShell.shell==="/bin/bash"&&originalShell.args.length===1&&originalShell.args[0]==="-c"&&!Object.keys(environment).some(name=>/^(?:BASH_ENV$|ENV$|SSH_CLIENT$|SSH2_CLIENT$|SHELLOPTS$|BASHOPTS$|PS4$|BASH_FUNC_|LD_|DYLD_|GLIBC_TUNABLES$)/.
114
- test(name))&&launchFreeBuiltin.test(command);onProcessStarted?.(child,readOnly||launchFree?"bounded":"uncertain"),recordProcessStarted?.(child),child.stdin?.on("error",()=>{}),commandFromStdin&&child.stdin?.end(command);let writingInput=!1,closeInput;onStdin?.(commandFromStdin?void 0:{async write(input,eof=!1){if(typeof input!="string"||typeof eof!="boolean")throw new Error("Invalid stdin input/eof");let bytes=Buffer.byteLength(input);if(bytes>MAX_JOB_INPUT_BYTES||writingInput)return{status:"bac\
115
- kpressure",bytes:0};let stdin=child.stdin;if(!stdin||stdin.destroyed||stdin.writableEnded||child.exitCode!==null||child.signalCode!==null)return{status:"closed",bytes:0};writingInput=!0;try{return await new Promise(resolve2=>{let settled=!1,written=!1,drained=!0,ended=!eof,finish=result=>{settled||(settled=!0,stdin.off("error",closed),stdin.off("close",closed),stdin.off("drain",drain),resolve2(result))},complete=()=>{written&&drained&&ended&&finish({status:"written",bytes})},closed=()=>finish({status:"\
116
- closed",bytes:0});closeInput=closed;let drain=()=>{drained=!0,complete()};stdin.once("error",closed),stdin.once("close",closed),drained=stdin.write(input,error=>{if(!settled){if(error){closed();return}written=!0,eof&&stdin.end(()=>{ended=!0,complete()}),complete()}}),drained||stdin.once("drain",drain)})}finally{closeInput=void 0,writingInput=!1}}});let startedAt=performance.now(),shellExitedAfterMs;child.once("exit",()=>{shellExitedAfterMs=performance.now()-startedAt});let timedOut=!1,exitedBeforeDeadlineAfterMs,
117
- timeoutHandle,drainTimer,termination,finished3=!1,quiescent=!0,outcome,outputFailure,pendingOutput,drainController=new AbortController,drainAborted=new Promise(resolve2=>{drainController.signal.addEventListener("abort",()=>resolve2(),{once:!0})}),terminateChildren=()=>termination??=child.pid?killProcessTreeAsync(child.pid,void 0,child):Promise.resolve(!0),onAbort=()=>{terminateChildren().then(()=>{!finished3&&!drainTimer&&(drainTimer=setTimeout(()=>drainController.abort(),500))})},failOutput=error=>{
118
- outputFailure={error},child.stdout?.off("data",handleData),child.stderr?.off("data",handleData),onAbort(),child.stdout?.resume(),child.stderr?.resume()},handleData=data=>{try{let pending=onData(data);pending instanceof Promise&&(child.stdout?.pause(),child.stderr?.pause(),pendingOutput=pending.then(()=>{child.stdout?.resume(),child.stderr?.resume()},failOutput))}catch(error){failOutput(error)}};terminateChildrenOnExit&&child.once("exit",terminateChildren);try{timeoutMs!==void 0&&(timeoutHandle=setTimeout(
119
- ()=>{timedOut=!0,exitedBeforeDeadlineAfterMs=shellExitedAfterMs,onAbort()},timeoutMs)),child.stdout?.on("data",handleData),child.stderr?.on("data",handleData),signal&&(signal.aborted?onAbort():signal.addEventListener("abort",onAbort,{once:!0}));let exitCode=await waitForChildProcess(child,drainController.signal);if(await Promise.race([pendingOutput,drainAborted]),outputFailure)throw outputFailure.error;if(signal?.aborted)throw new Error("aborted");let signalCode=child.signalCode,resolvedExitCode=exitCode??
120
- (signalCode?128+(osConstants.signals[signalCode]??0):1);if(timedOut)throw new ShellTimeoutError(timeout,exitedBeforeDeadlineAfterMs!==void 0?{exitCode:resolvedExitCode,afterSeconds:Math.round(exitedBeforeDeadlineAfterMs/100)/10}:void 0);readOnly&&resolvedExitCode!==0?(await onData(Buffer.from(`
121
- [Read-only verification failed; retrying with normal execution, without common-state proof]
122
- `)),outcome={kind:"completed",...await readOnly.retry(()=>operations.exec(command,cwd,{onData,signal,timeout,env,terminateChildrenOnExit,deadline,now,beforeSpawn,onStdin,onProcessStarted:recordProcessStarted}))}):(resolvedExitCode===0&&readOnly?.completed(),outcome={kind:"completed",exitCode:resolvedExitCode})}catch(error){outcome={kind:"error",error}}finally{finished3=!0,closeInput?.(),child.stdin?.destroy(),(terminateChildrenOnExit||deadline!==void 0)&&(child.off("exit",terminateChildren),quiescent=
123
- await terminateChildren()),drainTimer&&clearTimeout(drainTimer),timeoutHandle&&clearTimeout(timeoutHandle),signal&&signal.removeEventListener("abort",onAbort),child.stdout?.off("data",handleData),child.stderr?.off("data",handleData)}if(deadline!==void 0&&!quiescent)throw new BashCleanupError;if(!quiescent)throw new BashProcessCleanupError("Background process cleanup could not confirm quiescence");if(outcome.kind==="error")throw outcome.error;return{exitCode:outcome.exitCode}}};return operations}
124
- function createLocalBashOperations(options){return createLocalShellOperations("bash",()=>getShellConfig(options?.shellPath),options?.onProcessStarted)}function resolveSpawnContext(command,cwd,spawnHook,exposeSessionEnvironment,ctx,environment){let env=scrubTraceEnv(getShellEnv(environment));for(let name of["HUMAIN_TERMINAL_SESSION_ID","HUMAIN_TERMINAL_SESSION_FILE","HUMAIN_TERMINAL_PROVIDER","HUMAIN_TERMINAL_MODEL","HUMAIN_TERMINAL_REASONING_LEVEL","PI_SESSION_ID","PI_SESSION_FILE","PI_PROVIDER",
125
- "PI_MODEL","PI_REASONING_LEVEL"])delete env[name];if(exposeSessionEnvironment&&ctx){let model=ctx.model,sessionId=ctx.sessionManager.getSessionId();env.HUMAIN_TERMINAL_SESSION_ID=sessionId,env.PI_SESSION_ID=sessionId;let sessionFile=ctx.sessionManager.getSessionFile();sessionFile&&(env.HUMAIN_TERMINAL_SESSION_FILE=sessionFile,env.PI_SESSION_FILE=sessionFile),model&&(env.HUMAIN_TERMINAL_PROVIDER=model.provider,env.HUMAIN_TERMINAL_MODEL=model.id,env.PI_PROVIDER=model.provider,env.PI_MODEL=model.id),
126
- ctx.thinkingLevel&&(env.HUMAIN_TERMINAL_REASONING_LEVEL=ctx.thinkingLevel,env.PI_REASONING_LEVEL=ctx.thinkingLevel)}let baseContext={command,cwd,env};return spawnHook?spawnHook(baseContext):baseContext}var bashToolOwners=new WeakMap;function getBashToolOwner(definition){return bashToolOwners.get(definition.execute)}function createShellToolDefinition(cwd,config,options){let owner=options?.jobs??new BashJobManager,ops=options?.operations??createLocalBashOperations({shellPath:options?.shellPath,onProcessStarted:(child,custody)=>{
127
- owner.ownProcess(child,custody),options?.onProcessStarted?.(child)}}),commandPrefix=options?.commandPrefix,exposeSessionEnvironment=options?.exposeSessionEnvironment??!0,spawnHook=options?.spawnHook,defaultTimeout=config.name==="bash"?DEFAULT_BASH_TIMEOUT_SECONDS:void 0,outputCleanupEnv=(options?.environment??process.env).HUMAIN_TERMINAL_BASH_OUTPUT_CLEANUP,outputCleanup=config.name==="bash"&&(outputCleanupEnv==="1"?!0:outputCleanupEnv==="0"?!1:options?.outputCleanup===!0),outputCapEnv=(options?.
128
- environment??process.env).HUMAIN_TERMINAL_BASH_OUTPUT_HEAD_TAIL,outputHeadTail=config.name==="bash"&&(outputCapEnv==="1"?!0:outputCapEnv==="0"?!1:options?.outputHeadTail===!0),definition={name:config.name,label:config.label,description:`Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr. ${outputHeadTail?"Output keeps up to 4 KiB each from the head and tail, at most 8 KiB and 2,000 lines combined.":`Output is truncated to last ${2e3} lines or ${51200/
129
- 1024}KB (whichever is hit first).`} If truncated, full output is saved to a temp file. ${defaultTimeout===void 0?"Optionally provide a timeout in seconds.":`Commands time out after ${defaultTimeout} seconds by default; provide timeout in seconds for longer commands. Use background:true for servers, watchers, builds and solvers taking minutes, then jobs to inspect or wait. Background work has no default timeout; local background jobs require Linux or macOS.`}`,promptSnippet:config.promptSnippet,promptGuidelines:exposeSessionEnvironment&&
130
- config.promptGuidelines?[...config.promptGuidelines]:void 0,parameters:defaultTimeout===void 0?shellSchema:bashSchema,outputSchema:defaultTimeout===void 0?bashOutputSchema:typebox_exports.Union([bashOutputSchema,bashJobOutputSchema]),constrainedSampling:{type:"json_schema",strict:"prefer"},async execute(_toolCallId,{command,timeout,background},signal,onUpdate,ctx){let resolvedCommand=commandPrefix?`${commandPrefix}
131
- ${command}`:command,spawnContext=resolveSpawnContext(resolvedCommand,ctx?.cwd||cwd,spawnHook,exposeSessionEnvironment,ctx,options?.environment),runContext=options?.getRunContext?.();if(runContext&&admitBashRun(runContext),background){if(config.name!=="bash"||!options?.jobs)throw new Error("Background bash requires a session job manager");if(resolveTimeoutMs(timeout),signal?.aborted)throw new Error("Command aborted");let job=options.jobs.start(ops,spawnContext,timeout,runContext);return{content:[
132
- {type:"text",text:`Background job ${job.job_id} started. Use jobs to read, wait, or kill it. Output: ${job.full_output_path}`}],details:void 0,structuredContent:job}}let output=new OutputAccumulator({tempFilePrefix:config.tempFilePrefix,cleanup:outputCleanup,...outputHeadTail?{maxBytes:8*1024,headAndTail:!0}:{}}),acceptingOutput=!0,updateTimer,updateDirty=!1,lastUpdateAt=0,emitOutputUpdate=()=>{if(!onUpdate||!updateDirty)return;updateDirty=!1,lastUpdateAt=Date.now();let snapshot=output.snapshot(
133
- {persistIfTruncated:!0});onUpdate({content:[{type:"text",text:snapshot.content||""}],details:{truncation:snapshot.truncation.truncated?snapshot.truncation:void 0,fullOutputPath:snapshot.fullOutputPath}})},clearUpdateTimer=()=>{updateTimer&&(clearTimeout(updateTimer),updateTimer=void 0)},scheduleOutputUpdate=()=>{if(!onUpdate)return;updateDirty=!0;let delay=BASH_UPDATE_THROTTLE_MS-(Date.now()-lastUpdateAt);if(delay<=0){clearUpdateTimer(),emitOutputUpdate();return}updateTimer??=setTimeout(()=>{updateTimer=
134
- void 0,emitOutputUpdate()},delay)};onUpdate&&onUpdate({content:[],details:void 0});let handleData=data=>{if(!acceptingOutput)return;let pending=output.append(data);return scheduleOutputUpdate(),pending},finishOutput=async()=>{acceptingOutput=!1,output.finish(),clearUpdateTimer(),emitOutputUpdate();let snapshot=output.snapshot({persistIfTruncated:!0});return await output.closeTempFile(),snapshot},formatOutput=(snapshot,emptyText="(no output)")=>{let truncation=snapshot.truncation,text=snapshot.content||
135
- emptyText,details=outputCleanup?{fullOutputPath:snapshot.fullOutputPath}:void 0;if(truncation.truncated){if(details={truncation,fullOutputPath:snapshot.fullOutputPath},outputHeadTail)return{text,details};let startLine=truncation.totalLines-truncation.outputLines+1,endLine=truncation.totalLines;if(truncation.lastLinePartial){let lastLineSize=formatSize(output.getLastLineBytes());text+=`
136
-
137
- [Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`}else truncation.truncatedBy==="lines"?text+=`
138
-
139
- [Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`:text+=`
140
-
141
- [Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(51200)} limit). Full output: ${snapshot.fullOutputPath}]`}return{text,details}},appendStatus=(text,status)=>`${text?`${text}
142
-
143
- `:""}${status}`,startedAt=performance.now(),timeLimitCapped=!1;try{let exitCode;try{let effectiveTimeout=timeout===void 0?defaultTimeout:timeout;if(!runContext&&config.name==="bash"&&options?.getRemainingTimeSeconds){resolveTimeoutMs(effectiveTimeout);let cap=Math.max(5,options.getRemainingTimeSeconds()-20);timeLimitCapped=effectiveTimeout!==void 0&&cap<effectiveTimeout,timeLimitCapped&&(effectiveTimeout=cap)}runContext&&(resolveTimeoutMs(effectiveTimeout),effectiveTimeout=Math.min(effectiveTimeout??
144
- MAX_TIMEOUT_SECONDS,admitBashRun(runContext),MAX_TIMEOUT_SECONDS)),exitCode=(await ops.exec(spawnContext.command,spawnContext.cwd,{onData:handleData,signal,timeout:effectiveTimeout,env:spawnContext.env,...runContext?{deadline:runContext.deadline,now:runContext.now,terminateChildrenOnExit:!0,beforeSpawn:()=>{admitBashRun(runContext)}}:{}})).exitCode}catch(err){let snapshot2=await finishOutput(),{text}=formatOutput(snapshot2,"");if(err instanceof Error&&err.message==="aborted")throw new Error(appendStatus(
145
- text,"Command aborted"));if(err instanceof Error&&err.message.startsWith("timeout:")){let status=`Command timed out after ${err.message.split(":")[1]} seconds${timeLimitCapped?"; stopped to respect the run's time limit (20-second reserve).":timeout===void 0&&defaultTimeout!==void 0?"; pass a larger timeout for commands that need longer, and start long-running processes (servers, watchers) in the background with output redirected to a file.":""}`;throw err instanceof ShellTimeoutError&&err.shellExit&&
146
- (status+=`. The shell exited with code ${err.shellExit.exitCode} after ${err.shellExit.afterSeconds} seconds, but background processes it started kept writing output until the timeout.`),new Error(appendStatus(text,status))}throw err}let snapshot=await finishOutput(),{text:outputText,details}=formatOutput(snapshot);if(exitCode===null)throw new Error(appendStatus(outputText,"Command terminated without an exit code"));let wallTimeSeconds=Math.round((performance.now()-startedAt)/100)/10,fullOutput=await output.
147
- readFullOutput(STRUCTURED_OUTPUT_MAX_BYTES),structuredContent={output:fullOutput.content,truncated:fullOutput.truncated,...fullOutput.truncated&&snapshot.fullOutputPath?{full_output_path:snapshot.fullOutputPath}:{},exit_code:exitCode,wall_time_seconds:wallTimeSeconds};return exitCode!==0?{content:[{type:"text",text:appendStatus(outputText,`Command exited with code ${exitCode}`)}],details,structuredContent,isError:!0}:{content:[{type:"text",text:outputText}],details,structuredContent}}finally{clearUpdateTimer()}},
148
- ...createShellRenderers(config.prompt)};return bashToolOwners.set(definition.execute,owner),definition}var bashToolConfig={name:"bash",label:"bash",shellName:"bash",prompt:"$",promptSnippet:bashToolSystemPromptContribution.snippet,promptGuidelines:bashToolSystemPromptContribution.guidelines,tempFilePrefix:"pi-bash"};function createBashToolDefinition(cwd,options){return createShellToolDefinition(cwd,bashToolConfig,options)}function createBashTool(cwd,options){let definition=createBashToolDefinition(
149
- cwd,options),tool=wrapToolDefinition(definition),owner=getBashToolOwner(definition);return owner&&bashToolOwners.set(tool.execute,owner),Object.assign(tool,{promptSnippet:definition.promptSnippet,promptGuidelines:definition.promptGuidelines}),tool}import{AsyncLocalStorage as AsyncLocalStorage2}from"node:async_hooks";import{spawnSync}from"node:child_process";import{closeSync,constants as constants3,fstatSync,openSync,realpathSync}from"node:fs";import{isAbsolute,relative,resolve}from"node:path";var FileMutationCustodyError=class extends Error{},scopes2=new AsyncLocalStorage2;function captureFileMutationRoot(root){assertSupportedRuntime();let physical=realpathSync(root),fd=openSync(physical,constants3.O_RDONLY|constants3.O_DIRECTORY|constants3.O_NOFOLLOW);try{let{dev,ino}=fstatSync(fd);return{logical:resolve(root),physical,dev,ino,fd}}catch(error){throw closeSync(fd),error}}function closeFileMutationRoot(root){let fd=root.fd;fd!==void 0&&(root.fd=void 0,closeSync(fd))}async function withFileMutationCustody(custody,run){
150
- let root=custody.root,active=!0,invoke=(path,action,content)=>{try{if(!active)throw new FileMutationCustodyError("File mutation custody lifetime ended");if(custody.assertCurrent(path),assertSupportedRuntime(),root.fd===void 0)throw new FileMutationCustodyError("Root custody closed");let pathInRoot=relative(root.logical,resolve(path)),parts=pathInRoot.split("/");if(isAbsolute(pathInRoot)||parts.some(part=>!part||part==="."||part===".."||part.normalize("NFC").toLowerCase()===".git"))throw new FileMutationCustodyError(
151
- "Physical file mutation path refused");let remaining=custody.deadline-Date.now();if(remaining<=0)throw new FileMutationCustodyError("File mutation custody deadline reached");let result=spawnSync(process.execPath,["--input-type=commonjs","-e",mutationProgram],{cwd:root.physical,stdio:["pipe","pipe","pipe",root.fd],env:{},input:JSON.stringify({root:root.physical,dev:root.dev,ino:root.ino,parts,action,content}),timeout:Math.min(5e3,remaining),maxBuffer:1/0});if(result.error)throw new FileMutationCustodyError(
152
- `Physical file mutation refused: ${result.error.message}`);if(result.status!==0){let failure;try{failure=JSON.parse(result.stderr.toString())}catch{throw new FileMutationCustodyError("Physical file mutation helper terminated without a result")}throw failure.code&&["ENOENT","EACCES","EPERM","ENOSPC","EDQUOT","EROFS"].includes(failure.code)?new Error(failure.message):new FileMutationCustodyError(`Physical file mutation refused: ${failure.message}`)}return result.stdout}catch(error){throw error instanceof
153
- FileMutationCustodyError&&custody.onRefusal?.(error),error}};try{return await scopes2.run({mkdir:async()=>{},access:async path=>{invoke(path,"access")},readFile:async path=>invoke(path,"read"),writeFile:async(path,content)=>{invoke(path,"write",content)}},run)}finally{active=!1}}function currentFileMutationCustody(){return scopes2.getStore()}function assertSupportedRuntime(){if(!["darwin","linux"].includes(process.platform)||isBunRuntime)throw new FileMutationCustodyError("Physical file mutation\
154
- custody requires POSIX Node.js; this runtime is unsupported")}var mutationProgram=`
155
- const fs = require("node:fs");
156
- const path = require("node:path");
157
- try {
158
- // The inherited descriptor pins the admitted inode, including while spawn resolves its cwd.
159
- const root = fs.fstatSync(3);
160
- const cwd = fs.statSync(".");
161
- if (!root.isDirectory() || cwd.dev !== root.dev || cwd.ino !== root.ino)
162
- throw new Error("Root custody changed");
163
- const request = JSON.parse(fs.readFileSync(0, "utf8"));
164
- let physicalRoot;
165
- try { physicalRoot = fs.realpathSync.native("."); }
166
- catch { throw new Error("Root custody changed"); }
167
- if (root.dev !== request.dev || root.ino !== request.ino || physicalRoot !== request.root)
168
- throw new Error("Root custody changed");
169
- let physical = request.root;
170
- const leaf = request.parts.pop();
171
- for (const part of request.parts) {
172
- const names = fs.readdirSync(".");
173
- if (!names.includes(part) && names.some(name => name.normalize("NFC").toLowerCase() === part.normalize("NFC").toLowerCase()))
174
- throw new Error("Directory spelling alias refused");
175
- let before = fs.lstatSync(part, {throwIfNoEntry:false});
176
- if (!before && request.action === "write") {
177
- fs.mkdirSync(part);
178
- before = fs.lstatSync(part);
179
- }
180
- if (!before || !before.isDirectory() || before.isSymbolicLink()) throw new Error("Parent custody refused");
181
- process.chdir(part);
182
- physical = path.join(physical, part);
183
- const opened = fs.statSync(".");
184
- if (opened.dev !== before.dev || opened.ino !== before.ino || fs.realpathSync.native(".") !== physical)
185
- throw new Error("Parent custody changed");
186
- }
187
- const names = fs.readdirSync(".");
188
- if (!names.includes(leaf) && names.some(name => name.normalize("NFC").toLowerCase() === leaf.normalize("NFC").toLowerCase()))
189
- throw new Error("File spelling alias refused");
190
- const flags = fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK;
191
- let fd;
192
- try {
193
- const mode = request.action === "read" ? fs.constants.O_RDONLY : request.action === "write" ? fs.constants.O_WRONLY : fs.constants.O_RDWR;
194
- fd = fs.openSync(leaf, flags | mode);
195
- } catch (error) {
196
- if (error.code !== "ENOENT" || request.action !== "write") throw error;
197
- fd = fs.openSync(leaf, flags | fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o666);
198
- }
199
- try {
200
- const opened = fs.fstatSync(fd);
201
- if (!opened.isFile() || opened.nlink !== 1) throw new Error("File custody refused");
202
- if (request.action === "read") process.stdout.write(fs.readFileSync(fd));
203
- else if (request.action === "write") {
204
- fs.ftruncateSync(fd, 0);
205
- fs.writeFileSync(fd, request.content, "utf8");
206
- }
207
- } finally { fs.closeSync(fd); }
208
- } catch (error) {
209
- process.stderr.write(JSON.stringify({message: error.message, code: error.code}));
210
- process.exitCode = 1;
211
- }
212
- `;export{assertAdmittedModelInput,admissionIntent,boundModelOutputTokens,submissionAdmission,reconcileAdmittedUsage,VIRTUAL_MODEL_STATE_ENTRY,isVirtualModel,findLatestResponse,getBranchSelection,getVirtualModelState,createVirtualModel,withVirtualModels,pathExists,resolveToCwd,resolveReadPath,resolveReadPathAsync,withReadOnlyAcceptanceCommand,acceptanceCommandIsReadOnly,OutputAccumulator,declarePlainRenderers,declarePathHighlightingRenderers,renderersMayHighlight,createShellRenderers,SUBAGENT_DEPTH_ENV,
213
- TASK_ID_ENV,PARENT_TASK_ID_ENV,TASK_BASE_REVISION_ENV,currentSubagentDepth,maxSubagentDepth,maxSubagentConcurrency,maxSubagentWorktrees,maxParallelTasks,currentTaskId,scrubTraceEnv,createLocalShellOperations,createLocalBashOperations,getBashToolOwner,createShellToolDefinition,createBashToolDefinition,createBashTool,bashJobOutputSchema,adaptiveBashJobOutputSchema,jobInputResultSchema,MAX_JOB_INPUT_BYTES,BashJobManager,FileMutationCustodyError,captureFileMutationRoot,closeFileMutationRoot,withFileMutationCustody,
214
- currentFileMutationCustody};