@humain/humain-code 0.6.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (792) hide show
  1. package/CHANGELOG.md +119 -0
  2. package/README.md +23 -6
  3. package/dist/agent-monitor/entry.lazy.d.ts +3 -0
  4. package/dist/agent-monitor/entry.lazy.d.ts.map +1 -0
  5. package/dist/agent-monitor/entry.lazy.js +3 -0
  6. package/dist/agent-monitor/entry.lazy.js.map +1 -0
  7. package/dist/bundle/agent-monitor.js +1 -1
  8. package/dist/bundle/chunks/adaptive-peer-worker-X2ZNZE3S.js +8 -0
  9. package/dist/bundle/chunks/adaptive-session-host-7KDSQV5I.js +162 -0
  10. package/dist/bundle/chunks/anthropic-messages-TQK3FUV3.js +68 -0
  11. package/dist/bundle/chunks/anthropic.js +13 -10
  12. package/dist/bundle/chunks/{azure-openai-responses-IV74M5OR.js → azure-openai-responses-JY7OSLH2.js} +6 -6
  13. package/dist/bundle/chunks/bedrock-converse-stream.js +79 -74
  14. package/dist/bundle/chunks/chunk-2FYYW6FY.js +2 -0
  15. package/dist/bundle/chunks/{chunk-A2VPLMF2.js → chunk-2G7YVAVF.js} +1 -1
  16. package/dist/bundle/chunks/chunk-32QLLD2P.js +1114 -0
  17. package/dist/bundle/chunks/{chunk-3LP543EX.js → chunk-3EDMWQ35.js} +17 -16
  18. package/dist/bundle/chunks/chunk-3HVHETMU.js +18 -0
  19. package/dist/bundle/chunks/{chunk-XMZGB3H4.js → chunk-4HTVBBJD.js} +11 -6
  20. package/dist/bundle/chunks/chunk-4JRER4XK.js +175 -0
  21. package/dist/bundle/chunks/{chunk-FHLLDO7U.js → chunk-4PRNKB6V.js} +5 -5
  22. package/dist/bundle/chunks/chunk-4QAXV5T6.js +49 -0
  23. package/dist/bundle/chunks/{chunk-JCTQQ3DX.js → chunk-4V5VL2BO.js} +1 -1
  24. package/dist/bundle/chunks/chunk-5B25YXF7.js +24 -0
  25. package/dist/bundle/chunks/chunk-5L4PBYC7.js +11 -0
  26. package/dist/bundle/chunks/chunk-66FZJO75.js +5146 -0
  27. package/dist/bundle/chunks/chunk-6P6GJPYB.js +4 -0
  28. package/dist/bundle/chunks/chunk-6PNQYO6A.js +10 -0
  29. package/dist/bundle/chunks/chunk-7NKUVTBL.js +76 -0
  30. package/dist/bundle/chunks/chunk-AEWYICBL.js +89 -0
  31. package/dist/bundle/chunks/chunk-AQ4EXORZ.js +14 -0
  32. package/dist/bundle/chunks/chunk-AZXVJN6E.js +19 -0
  33. package/dist/bundle/chunks/chunk-CRN54O4D.js +24 -0
  34. package/dist/bundle/chunks/chunk-CTU2ECLD.js +7 -0
  35. package/dist/bundle/chunks/{chunk-BQ3TMEWD.js → chunk-EIC7CQX3.js} +4 -3
  36. package/dist/bundle/chunks/chunk-F6ZAYLU2.js +59 -0
  37. package/dist/bundle/chunks/chunk-G4QPSFBF.js +493 -0
  38. package/dist/bundle/chunks/chunk-GME4AWDG.js +23 -0
  39. package/dist/bundle/chunks/{chunk-SFMDIVZ4.js → chunk-GRJUKEE3.js} +43 -30
  40. package/dist/bundle/chunks/chunk-GTILMMUF.js +12 -0
  41. package/dist/bundle/chunks/chunk-GUHNFZ2Q.js +51 -0
  42. package/dist/bundle/chunks/chunk-GY663MNP.js +11 -0
  43. package/dist/bundle/chunks/chunk-HTA325LJ.js +56 -0
  44. package/dist/bundle/chunks/{chunk-5L4JG6PO.js → chunk-I3NDOUHE.js} +8 -7
  45. package/dist/bundle/chunks/chunk-I5E7RQ5V.js +21 -0
  46. package/dist/bundle/chunks/chunk-IWZQ25I3.js +5 -0
  47. package/dist/bundle/chunks/chunk-IYGHKVUG.js +2 -0
  48. package/dist/bundle/chunks/chunk-J57HOSWD.js +21 -0
  49. package/dist/bundle/chunks/chunk-JF7FYXAI.js +288 -0
  50. package/dist/bundle/chunks/chunk-JSZBTGI6.js +10 -0
  51. package/dist/bundle/chunks/chunk-JYWUOKOI.js +1061 -0
  52. package/dist/bundle/chunks/{chunk-DLCBSLHW.js → chunk-KRCX3ZBA.js} +1 -1
  53. package/dist/bundle/chunks/chunk-KTSJYIYC.js +30 -0
  54. package/dist/bundle/chunks/{chunk-K7SDY3VJ.js → chunk-LB4CIS4F.js} +40 -165
  55. package/dist/bundle/chunks/{chunk-NN53K2QQ.js → chunk-LYZ37DJP.js} +2 -14
  56. package/dist/bundle/chunks/chunk-MD7K7RPN.js +20 -0
  57. package/dist/bundle/chunks/chunk-MX4Q4W6H.js +214 -0
  58. package/dist/bundle/chunks/{chunk-6PD3T2EF.js → chunk-N2SNMUD3.js} +1 -1
  59. package/dist/bundle/chunks/chunk-NXA6NEHE.js +54 -0
  60. package/dist/bundle/chunks/chunk-OB332KMV.js +300 -0
  61. package/dist/bundle/chunks/chunk-P6AXBESH.js +1883 -0
  62. package/dist/bundle/chunks/chunk-PPBDDQHP.js +11 -0
  63. package/dist/bundle/chunks/chunk-PWUDFU5V.js +51 -0
  64. package/dist/bundle/chunks/chunk-Q5RKNQ2T.js +73 -0
  65. package/dist/bundle/chunks/chunk-QT6ZHDMP.js +12 -0
  66. package/dist/bundle/chunks/chunk-R5OOX7RW.js +16 -0
  67. package/dist/bundle/chunks/chunk-R6YQR7TZ.js +25 -0
  68. package/dist/bundle/chunks/{chunk-4ZBGTJJM.js → chunk-RNBZBCH2.js} +1 -1
  69. package/dist/bundle/chunks/chunk-RQU722SY.js +1 -0
  70. package/dist/bundle/chunks/{chunk-RGUZULEE.js → chunk-RS6PZK35.js} +71 -72
  71. package/dist/bundle/chunks/{jiti-loader-6P33XTLC.js → chunk-RW7GT7L3.js} +1 -1
  72. package/dist/bundle/chunks/{chunk-PCTLFSQG.js → chunk-SCINMV4X.js} +1 -1
  73. package/dist/bundle/chunks/{chunk-NCC2FAJN.js → chunk-SSRCVJZK.js} +28 -28
  74. package/dist/bundle/chunks/chunk-T5A6T24H.js +93 -0
  75. package/dist/bundle/chunks/chunk-T7BXP46S.js +3367 -0
  76. package/dist/bundle/chunks/chunk-TGDPZCSW.js +9 -0
  77. package/dist/bundle/chunks/{chunk-4J6BGNX2.js → chunk-TWAHPPXN.js} +434 -429
  78. package/dist/bundle/chunks/chunk-UEW6TUSP.js +36 -0
  79. package/dist/bundle/chunks/chunk-UZNIPOGS.js +323 -0
  80. package/dist/bundle/chunks/{chunk-KM4GQ2BU.js → chunk-VFLVWPLZ.js} +5 -6
  81. package/dist/bundle/chunks/chunk-WAPZN4KP.js +74 -0
  82. package/dist/bundle/chunks/chunk-WCFHG6NO.js +16 -0
  83. package/dist/bundle/chunks/chunk-WQ7EJQIT.js +839 -0
  84. package/dist/bundle/chunks/chunk-WQOOJP7U.js +4 -0
  85. package/dist/bundle/chunks/chunk-XHDVDJM7.js +17 -0
  86. package/dist/bundle/chunks/chunk-YPZPCHNV.js +3 -0
  87. package/dist/bundle/chunks/chunk-Z5YLKK3S.js +41 -0
  88. package/dist/bundle/chunks/chunk-ZJUU6WOV.js +2052 -0
  89. package/dist/bundle/chunks/{cli-N7KOVPLB.js → cli-H4LJNE2V.js} +2 -2
  90. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-KRMHG2L3.js → cloudflare-workers-ai-system-one-T5R2RVFQ.js} +1 -1
  91. package/dist/bundle/chunks/codemode-worker.js +2 -0
  92. package/dist/bundle/chunks/compat-ZK2DIW3P.js +15 -0
  93. package/dist/bundle/chunks/dist-EY7YKQHB.js +11 -0
  94. package/dist/bundle/chunks/dist-FMWWM4H7.js +268 -0
  95. package/dist/bundle/chunks/dist-NHQTBDHT.js +1107 -0
  96. package/dist/bundle/chunks/{easter-egg-3d-O2GG2XIG.js → easter-egg-3d-BUEOC3NO.js} +1 -1
  97. package/dist/bundle/chunks/entry-A2CSLKHC.js +323 -0
  98. package/dist/bundle/chunks/entry-AL54ZGYO.js +2 -0
  99. package/dist/bundle/chunks/{execute-LMBACTKA.js → execute-MY5JSEPV.js} +18 -15
  100. package/dist/bundle/chunks/{extract-CXXLVFC5.js → extract-PTGACPGP.js} +3 -3
  101. package/dist/bundle/chunks/flow-implementer-APJFY4YI.js +21 -0
  102. package/dist/bundle/chunks/github-copilot.js +66 -62
  103. package/dist/bundle/chunks/{google-generative-ai-SBL77OXO.js → google-generative-ai-UL7YEQ6J.js} +2 -3
  104. package/dist/bundle/chunks/{google-vertex-NZBNNXMK.js → google-vertex-OTMSPUYH.js} +3 -3
  105. package/dist/bundle/chunks/host-75YAHLDR.js +3 -0
  106. package/dist/bundle/chunks/index.bundle-THL4EUSU.js +390 -0
  107. package/dist/bundle/chunks/inprocess-5NP5VJHZ.js +32 -0
  108. package/dist/bundle/chunks/interactive-mode-IW4PIVAQ.js +5 -0
  109. package/dist/bundle/chunks/jiti-bun-loader-VSLLRCSD.js +3459 -0
  110. package/dist/bundle/chunks/jiti-loader-TMJL6S2D.js +2 -0
  111. package/dist/bundle/chunks/{llama-cpp-classify-PP63BYDF.js → llama-cpp-classify-GJAXULWL.js} +1 -1
  112. package/dist/bundle/chunks/{mistral-conversations-DX4YKJSO.js → mistral-conversations-E72Y6OC3.js} +2 -2
  113. package/dist/bundle/chunks/{node-UGQUSQE6.js → node-ZFIIS5IM.js} +32 -32
  114. package/dist/bundle/chunks/openai-codex-responses-S7CMCAOY.js +101 -0
  115. package/dist/bundle/chunks/openai-completions-2Z57N7PC.js +87 -0
  116. package/dist/bundle/chunks/{openai-decisions-ALJROWBE.js → openai-decisions-JIOJDB4C.js} +1 -1
  117. package/dist/bundle/chunks/openai-responses-5VBZSTHL.js +27 -0
  118. package/dist/bundle/chunks/{openrouter-images-FCJT7C7I.js → openrouter-images-S6O7DBEJ.js} +1 -1
  119. package/dist/bundle/chunks/{pi-messages-NHTQQOPW.js → pi-messages-SMLN5J2W.js} +10 -7
  120. package/dist/bundle/chunks/runtime-OYTWXIUM.js +2 -0
  121. package/dist/bundle/chunks/session-picker-DM6S37IF.js +4 -0
  122. package/dist/bundle/chunks/startup-ui-4GGLWNSU.js +3 -0
  123. package/dist/bundle/chunks/trace-command-YLDYCL55.js +254 -0
  124. package/dist/bundle/chunks/typesafe-system-one-7BEL3H5N.js +3 -0
  125. package/dist/bundle/chunks/virtual-modules-TI3W24YL.js +28 -0
  126. package/dist/bundle/cli-runtime.js +5 -3
  127. package/dist/bundle/flow/agents/orch-implementation-fast.md +4 -4
  128. package/dist/bundle/flow/agents/orch-implementation-strong.md +5 -5
  129. package/dist/bundle/flow/package.json +35 -3
  130. package/dist/bundle/index.js +20 -17
  131. package/dist/bundle/orchestrate/README.md +37 -0
  132. package/dist/bundle/{flow → orchestrate}/agents/orch-qa-agent.md +1 -1
  133. package/dist/bundle/{flow → orchestrate}/agents/orch-worker.md +1 -1
  134. package/dist/bundle/{flow → orchestrate}/agents/orchestrator-lead.md +1 -1
  135. package/dist/bundle/orchestrate/package.json +29 -0
  136. package/dist/bundle/rpc-entry.js +5 -3
  137. package/dist/cli/args.d.ts +6 -0
  138. package/dist/cli/args.d.ts.map +1 -1
  139. package/dist/cli/args.js +69 -2
  140. package/dist/cli/args.js.map +1 -1
  141. package/dist/cli/auth-check.d.ts +3 -2
  142. package/dist/cli/auth-check.d.ts.map +1 -1
  143. package/dist/cli/auth-check.js +4 -3
  144. package/dist/cli/auth-check.js.map +1 -1
  145. package/dist/cli/config-selector.d.ts.map +1 -1
  146. package/dist/cli/config-selector.js +3 -1
  147. package/dist/cli/config-selector.js.map +1 -1
  148. package/dist/cli/file-processor.d.ts +2 -0
  149. package/dist/cli/file-processor.d.ts.map +1 -1
  150. package/dist/cli/file-processor.js +6 -6
  151. package/dist/cli/file-processor.js.map +1 -1
  152. package/dist/cli/metadata-disclosure.d.ts +4 -0
  153. package/dist/cli/metadata-disclosure.d.ts.map +1 -0
  154. package/dist/cli/metadata-disclosure.js +23 -0
  155. package/dist/cli/metadata-disclosure.js.map +1 -0
  156. package/dist/cli/project-trust.d.ts.map +1 -1
  157. package/dist/cli/project-trust.js +4 -1
  158. package/dist/cli/project-trust.js.map +1 -1
  159. package/dist/cli/session-picker.lazy.d.ts +3 -0
  160. package/dist/cli/session-picker.lazy.d.ts.map +1 -0
  161. package/dist/cli/session-picker.lazy.js +3 -0
  162. package/dist/cli/session-picker.lazy.js.map +1 -0
  163. package/dist/cli/startup-ui.d.ts +4 -4
  164. package/dist/cli/startup-ui.d.ts.map +1 -1
  165. package/dist/cli/startup-ui.js +38 -14
  166. package/dist/cli/startup-ui.js.map +1 -1
  167. package/dist/cli/startup-ui.lazy.d.ts +3 -0
  168. package/dist/cli/startup-ui.lazy.d.ts.map +1 -0
  169. package/dist/cli/startup-ui.lazy.js +3 -0
  170. package/dist/cli/startup-ui.lazy.js.map +1 -0
  171. package/dist/cli/trace-command.lazy.d.ts +3 -0
  172. package/dist/cli/trace-command.lazy.d.ts.map +1 -0
  173. package/dist/cli/trace-command.lazy.js +3 -0
  174. package/dist/cli/trace-command.lazy.js.map +1 -0
  175. package/dist/cli.js.map +1 -1
  176. package/dist/coordination/broker/entry.lazy.d.ts +3 -0
  177. package/dist/coordination/broker/entry.lazy.d.ts.map +1 -0
  178. package/dist/coordination/broker/entry.lazy.js +3 -0
  179. package/dist/coordination/broker/entry.lazy.js.map +1 -0
  180. package/dist/core/acceptance-command.d.ts +15 -0
  181. package/dist/core/acceptance-command.d.ts.map +1 -0
  182. package/dist/core/acceptance-command.js +150 -0
  183. package/dist/core/acceptance-command.js.map +1 -0
  184. package/dist/core/acceptance-ledger.d.ts +52 -0
  185. package/dist/core/acceptance-ledger.d.ts.map +1 -0
  186. package/dist/core/acceptance-ledger.js +341 -0
  187. package/dist/core/acceptance-ledger.js.map +1 -0
  188. package/dist/core/admission-types.d.ts +69 -0
  189. package/dist/core/admission-types.js +2 -0
  190. package/dist/core/admission-types.js.map +1 -0
  191. package/dist/core/agent-session-runtime.d.ts +7 -0
  192. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  193. package/dist/core/agent-session-runtime.js +43 -9
  194. package/dist/core/agent-session-runtime.js.map +1 -1
  195. package/dist/core/agent-session-services.d.ts +8 -0
  196. package/dist/core/agent-session-services.d.ts.map +1 -1
  197. package/dist/core/agent-session-services.js +13 -1
  198. package/dist/core/agent-session-services.js.map +1 -1
  199. package/dist/core/agent-session.d.ts +127 -10
  200. package/dist/core/agent-session.d.ts.map +1 -1
  201. package/dist/core/agent-session.js +1390 -145
  202. package/dist/core/agent-session.js.map +1 -1
  203. package/dist/core/anthropic-subscription-usage.d.ts +1 -1
  204. package/dist/core/anthropic-subscription-usage.d.ts.map +1 -1
  205. package/dist/core/anthropic-subscription-usage.js +31 -3
  206. package/dist/core/anthropic-subscription-usage.js.map +1 -1
  207. package/dist/core/auth-storage.d.ts +2 -1
  208. package/dist/core/auth-storage.d.ts.map +1 -1
  209. package/dist/core/auth-storage.js +13 -10
  210. package/dist/core/auth-storage.js.map +1 -1
  211. package/dist/core/auto-session-namer.d.ts.map +1 -1
  212. package/dist/core/auto-session-namer.js +3 -1
  213. package/dist/core/auto-session-namer.js.map +1 -1
  214. package/dist/core/bash-executor.d.ts.map +1 -1
  215. package/dist/core/bash-executor.js +3 -1
  216. package/dist/core/bash-executor.js.map +1 -1
  217. package/dist/core/bug-report-redaction.d.ts +4 -0
  218. package/dist/core/bug-report-redaction.d.ts.map +1 -0
  219. package/dist/core/bug-report-redaction.js +209 -0
  220. package/dist/core/bug-report-redaction.js.map +1 -0
  221. package/dist/core/bug-report.d.ts +26 -6
  222. package/dist/core/bug-report.d.ts.map +1 -1
  223. package/dist/core/bug-report.js +82 -9
  224. package/dist/core/bug-report.js.map +1 -1
  225. package/dist/core/cache-warmer.d.ts.map +1 -1
  226. package/dist/core/cache-warmer.js +5 -0
  227. package/dist/core/cache-warmer.js.map +1 -1
  228. package/dist/core/compaction/compaction.d.ts +6 -0
  229. package/dist/core/compaction/compaction.d.ts.map +1 -1
  230. package/dist/core/compaction/compaction.js +103 -71
  231. package/dist/core/compaction/compaction.js.map +1 -1
  232. package/dist/core/compaction/utils.d.ts.map +1 -1
  233. package/dist/core/compaction/utils.js +2 -1
  234. package/dist/core/compaction/utils.js.map +1 -1
  235. package/dist/core/extensions/jiti-bun-babel.d.ts +4 -0
  236. package/dist/core/extensions/jiti-bun-babel.d.ts.map +1 -0
  237. package/dist/core/extensions/jiti-bun-babel.js +4 -0
  238. package/dist/core/extensions/jiti-bun-babel.js.map +1 -0
  239. package/dist/core/extensions/jiti-bun-loader.d.ts +4 -0
  240. package/dist/core/extensions/jiti-bun-loader.d.ts.map +1 -0
  241. package/dist/core/extensions/jiti-bun-loader.js +13 -0
  242. package/dist/core/extensions/jiti-bun-loader.js.map +1 -0
  243. package/dist/core/extensions/jiti-bun-loader.lazy.d.ts +3 -0
  244. package/dist/core/extensions/jiti-bun-loader.lazy.d.ts.map +1 -0
  245. package/dist/core/extensions/jiti-bun-loader.lazy.js +3 -0
  246. package/dist/core/extensions/jiti-bun-loader.lazy.js.map +1 -0
  247. package/dist/core/extensions/loader.d.ts.map +1 -1
  248. package/dist/core/extensions/loader.js +9 -3
  249. package/dist/core/extensions/loader.js.map +1 -1
  250. package/dist/core/extensions/runner.d.ts.map +1 -1
  251. package/dist/core/extensions/runner.js +4 -0
  252. package/dist/core/extensions/runner.js.map +1 -1
  253. package/dist/core/extensions/types.d.ts +3 -0
  254. package/dist/core/extensions/types.d.ts.map +1 -1
  255. package/dist/core/extensions/types.js.map +1 -1
  256. package/dist/core/flow-implementer.d.ts +25 -0
  257. package/dist/core/flow-implementer.d.ts.map +1 -0
  258. package/dist/core/flow-implementer.js +301 -0
  259. package/dist/core/flow-implementer.js.map +1 -0
  260. package/dist/core/internal-process.d.ts +23 -0
  261. package/dist/core/internal-process.d.ts.map +1 -0
  262. package/dist/core/internal-process.js +88 -0
  263. package/dist/core/internal-process.js.map +1 -0
  264. package/dist/core/keybindings.d.ts +2 -2
  265. package/dist/core/keybindings.js +1 -1
  266. package/dist/core/keybindings.js.map +1 -1
  267. package/dist/core/model-config.d.ts +52 -0
  268. package/dist/core/model-config.d.ts.map +1 -1
  269. package/dist/core/model-config.js +4 -4
  270. package/dist/core/model-config.js.map +1 -1
  271. package/dist/core/model-registry.d.ts +4 -0
  272. package/dist/core/model-registry.d.ts.map +1 -1
  273. package/dist/core/model-registry.js +8 -0
  274. package/dist/core/model-registry.js.map +1 -1
  275. package/dist/core/model-request-admission.d.ts +51 -0
  276. package/dist/core/model-request-admission.d.ts.map +1 -0
  277. package/dist/core/model-request-admission.js +103 -0
  278. package/dist/core/model-request-admission.js.map +1 -0
  279. package/dist/core/model-resolver.d.ts +4 -0
  280. package/dist/core/model-resolver.d.ts.map +1 -1
  281. package/dist/core/model-resolver.js +109 -2
  282. package/dist/core/model-resolver.js.map +1 -1
  283. package/dist/core/model-runtime.d.ts +56 -1
  284. package/dist/core/model-runtime.d.ts.map +1 -1
  285. package/dist/core/model-runtime.js +482 -40
  286. package/dist/core/model-runtime.js.map +1 -1
  287. package/dist/core/model-selection-intent.d.ts +14 -0
  288. package/dist/core/model-selection-intent.d.ts.map +1 -0
  289. package/dist/core/model-selection-intent.js +15 -0
  290. package/dist/core/model-selection-intent.js.map +1 -0
  291. package/dist/core/oauth-account-pool.d.ts +4 -1
  292. package/dist/core/oauth-account-pool.d.ts.map +1 -1
  293. package/dist/core/oauth-account-pool.js +251 -228
  294. package/dist/core/oauth-account-pool.js.map +1 -1
  295. package/dist/core/os-secret-store.d.ts +25 -0
  296. package/dist/core/os-secret-store.d.ts.map +1 -0
  297. package/dist/core/os-secret-store.js +290 -0
  298. package/dist/core/os-secret-store.js.map +1 -0
  299. package/dist/core/output-guard.d.ts.map +1 -1
  300. package/dist/core/output-guard.js +62 -2
  301. package/dist/core/output-guard.js.map +1 -1
  302. package/dist/core/pi-ai-schemas.d.ts +4 -0
  303. package/dist/core/pi-ai-schemas.d.ts.map +1 -1
  304. package/dist/core/private-windows-path.d.ts +4 -0
  305. package/dist/core/private-windows-path.d.ts.map +1 -0
  306. package/dist/core/private-windows-path.js +44 -0
  307. package/dist/core/private-windows-path.js.map +1 -0
  308. package/dist/core/prompt-templates.d.ts.map +1 -1
  309. package/dist/core/prompt-templates.js +18 -2
  310. package/dist/core/prompt-templates.js.map +1 -1
  311. package/dist/core/provider-composer.d.ts.map +1 -1
  312. package/dist/core/provider-composer.js +1 -1
  313. package/dist/core/provider-composer.js.map +1 -1
  314. package/dist/core/resource-loader.d.ts.map +1 -1
  315. package/dist/core/resource-loader.js +6 -2
  316. package/dist/core/resource-loader.js.map +1 -1
  317. package/dist/core/run-outcome.d.ts +40 -0
  318. package/dist/core/run-outcome.d.ts.map +1 -0
  319. package/dist/core/run-outcome.js +91 -0
  320. package/dist/core/run-outcome.js.map +1 -0
  321. package/dist/core/run-preflight.d.ts +5 -0
  322. package/dist/core/run-preflight.d.ts.map +1 -0
  323. package/dist/core/run-preflight.js +96 -0
  324. package/dist/core/run-preflight.js.map +1 -0
  325. package/dist/core/runtime-credentials.d.ts +18 -2
  326. package/dist/core/runtime-credentials.d.ts.map +1 -1
  327. package/dist/core/runtime-credentials.js +65 -9
  328. package/dist/core/runtime-credentials.js.map +1 -1
  329. package/dist/core/sdk.d.ts +19 -3
  330. package/dist/core/sdk.d.ts.map +1 -1
  331. package/dist/core/sdk.js +115 -20
  332. package/dist/core/sdk.js.map +1 -1
  333. package/dist/core/settings-defaults.d.ts +2 -1
  334. package/dist/core/settings-defaults.d.ts.map +1 -1
  335. package/dist/core/settings-defaults.js +2 -1
  336. package/dist/core/settings-defaults.js.map +1 -1
  337. package/dist/core/settings-manager.d.ts +15 -4
  338. package/dist/core/settings-manager.d.ts.map +1 -1
  339. package/dist/core/settings-manager.js +114 -22
  340. package/dist/core/settings-manager.js.map +1 -1
  341. package/dist/core/settings-schema.d.ts +7 -2
  342. package/dist/core/settings-schema.d.ts.map +1 -1
  343. package/dist/core/settings-schema.js +12 -5
  344. package/dist/core/settings-schema.js.map +1 -1
  345. package/dist/core/skills.d.ts.map +1 -1
  346. package/dist/core/skills.js +11 -0
  347. package/dist/core/skills.js.map +1 -1
  348. package/dist/core/system-prompt.d.ts +3 -0
  349. package/dist/core/system-prompt.d.ts.map +1 -1
  350. package/dist/core/system-prompt.js +10 -2
  351. package/dist/core/system-prompt.js.map +1 -1
  352. package/dist/core/tools/bash-jobs.d.ts +109 -0
  353. package/dist/core/tools/bash-jobs.d.ts.map +1 -0
  354. package/dist/core/tools/bash-jobs.js +563 -0
  355. package/dist/core/tools/bash-jobs.js.map +1 -0
  356. package/dist/core/tools/bash.d.ts +68 -6
  357. package/dist/core/tools/bash.d.ts.map +1 -1
  358. package/dist/core/tools/bash.js +350 -37
  359. package/dist/core/tools/bash.js.map +1 -1
  360. package/dist/core/tools/edit-diff.d.ts +11 -1
  361. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  362. package/dist/core/tools/edit-diff.js +89 -20
  363. package/dist/core/tools/edit-diff.js.map +1 -1
  364. package/dist/core/tools/edit.d.ts.map +1 -1
  365. package/dist/core/tools/edit.js +15 -7
  366. package/dist/core/tools/edit.js.map +1 -1
  367. package/dist/core/tools/file-mutation-custody.d.ts +29 -0
  368. package/dist/core/tools/file-mutation-custody.d.ts.map +1 -0
  369. package/dist/core/tools/file-mutation-custody.js +173 -0
  370. package/dist/core/tools/file-mutation-custody.js.map +1 -0
  371. package/dist/core/tools/find.d.ts +6 -0
  372. package/dist/core/tools/find.d.ts.map +1 -1
  373. package/dist/core/tools/find.js +84 -38
  374. package/dist/core/tools/find.js.map +1 -1
  375. package/dist/core/tools/grep.d.ts +8 -2
  376. package/dist/core/tools/grep.d.ts.map +1 -1
  377. package/dist/core/tools/grep.js +121 -77
  378. package/dist/core/tools/grep.js.map +1 -1
  379. package/dist/core/tools/index.d.ts +3 -1
  380. package/dist/core/tools/index.d.ts.map +1 -1
  381. package/dist/core/tools/index.js +12 -0
  382. package/dist/core/tools/index.js.map +1 -1
  383. package/dist/core/tools/jobs.d.ts +24 -0
  384. package/dist/core/tools/jobs.d.ts.map +1 -0
  385. package/dist/core/tools/jobs.js +86 -0
  386. package/dist/core/tools/jobs.js.map +1 -0
  387. package/dist/core/tools/ls.d.ts.map +1 -1
  388. package/dist/core/tools/ls.js +2 -1
  389. package/dist/core/tools/ls.js.map +1 -1
  390. package/dist/core/tools/output-accumulator.d.ts +12 -1
  391. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  392. package/dist/core/tools/output-accumulator.js +88 -8
  393. package/dist/core/tools/output-accumulator.js.map +1 -1
  394. package/dist/core/tools/output-cleanup.d.ts +40 -0
  395. package/dist/core/tools/output-cleanup.d.ts.map +1 -0
  396. package/dist/core/tools/output-cleanup.js +273 -0
  397. package/dist/core/tools/output-cleanup.js.map +1 -0
  398. package/dist/core/tools/powershell.d.ts.map +1 -1
  399. package/dist/core/tools/powershell.js +15 -2
  400. package/dist/core/tools/powershell.js.map +1 -1
  401. package/dist/core/tools/read.d.ts +21 -0
  402. package/dist/core/tools/read.d.ts.map +1 -1
  403. package/dist/core/tools/read.js +162 -29
  404. package/dist/core/tools/read.js.map +1 -1
  405. package/dist/core/tools/renderers/bash.d.ts.map +1 -1
  406. package/dist/core/tools/renderers/bash.js +3 -1
  407. package/dist/core/tools/renderers/bash.js.map +1 -1
  408. package/dist/core/tools/renderers/index.d.ts.map +1 -1
  409. package/dist/core/tools/renderers/index.js +1 -0
  410. package/dist/core/tools/renderers/index.js.map +1 -1
  411. package/dist/core/tools/subagent.d.ts +5 -1
  412. package/dist/core/tools/subagent.d.ts.map +1 -1
  413. package/dist/core/tools/subagent.js +76 -19
  414. package/dist/core/tools/subagent.js.map +1 -1
  415. package/dist/core/tools/truncate.d.ts +4 -0
  416. package/dist/core/tools/truncate.d.ts.map +1 -1
  417. package/dist/core/tools/truncate.js +24 -1
  418. package/dist/core/tools/truncate.js.map +1 -1
  419. package/dist/core/tools/write.d.ts.map +1 -1
  420. package/dist/core/tools/write.js +6 -1
  421. package/dist/core/tools/write.js.map +1 -1
  422. package/dist/core/trace/config.js +3 -3
  423. package/dist/core/trace/config.js.map +1 -1
  424. package/dist/core/trace/redaction.d.ts.map +1 -1
  425. package/dist/core/trace/redaction.js +12 -9
  426. package/dist/core/trace/redaction.js.map +1 -1
  427. package/dist/core/trace-client/credential-store.d.ts +1 -1
  428. package/dist/core/trace-client/credential-store.d.ts.map +1 -1
  429. package/dist/core/trace-client/credential-store.js +20 -3
  430. package/dist/core/trace-client/credential-store.js.map +1 -1
  431. package/dist/core/usage-ledger.d.ts +35 -0
  432. package/dist/core/usage-ledger.d.ts.map +1 -0
  433. package/dist/core/usage-ledger.js +140 -0
  434. package/dist/core/usage-ledger.js.map +1 -0
  435. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  436. package/dist/extensions/codemode/execute.js +24 -15
  437. package/dist/extensions/codemode/execute.js.map +1 -1
  438. package/dist/extensions/codemode/index.d.ts +4 -2
  439. package/dist/extensions/codemode/index.d.ts.map +1 -1
  440. package/dist/extensions/codemode/index.js +8 -4
  441. package/dist/extensions/codemode/index.js.map +1 -1
  442. package/dist/extensions/codemode/tool.d.ts +4 -2
  443. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  444. package/dist/extensions/codemode/tool.js +34 -12
  445. package/dist/extensions/codemode/tool.js.map +1 -1
  446. package/dist/extensions/llama/client.d.ts +2 -0
  447. package/dist/extensions/llama/client.d.ts.map +1 -1
  448. package/dist/extensions/llama/client.js +23 -2
  449. package/dist/extensions/llama/client.js.map +1 -1
  450. package/dist/extensions/llama/ui.d.ts.map +1 -1
  451. package/dist/extensions/llama/ui.js +15 -3
  452. package/dist/extensions/llama/ui.js.map +1 -1
  453. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  454. package/dist/extensions/mcp/runtime.js +3 -2
  455. package/dist/extensions/mcp/runtime.js.map +1 -1
  456. package/dist/extensions/tool-search/tool.d.ts.map +1 -1
  457. package/dist/extensions/tool-search/tool.js +18 -6
  458. package/dist/extensions/tool-search/tool.js.map +1 -1
  459. package/dist/extensions/usage/hcode-overview.d.ts +23 -0
  460. package/dist/extensions/usage/hcode-overview.d.ts.map +1 -0
  461. package/dist/extensions/usage/hcode-overview.js +109 -0
  462. package/dist/extensions/usage/hcode-overview.js.map +1 -0
  463. package/dist/extensions/usage/index.d.ts +5 -0
  464. package/dist/extensions/usage/index.d.ts.map +1 -1
  465. package/dist/extensions/usage/index.js +194 -12
  466. package/dist/extensions/usage/index.js.map +1 -1
  467. package/dist/extensions/usage/overview.d.ts +5 -0
  468. package/dist/extensions/usage/overview.d.ts.map +1 -1
  469. package/dist/extensions/usage/overview.js +21 -1
  470. package/dist/extensions/usage/overview.js.map +1 -1
  471. package/dist/extensions/usage/popup.d.ts +14 -3
  472. package/dist/extensions/usage/popup.d.ts.map +1 -1
  473. package/dist/extensions/usage/popup.js +199 -25
  474. package/dist/extensions/usage/popup.js.map +1 -1
  475. package/dist/humain/adaptive-execution.d.ts +51 -0
  476. package/dist/humain/adaptive-execution.d.ts.map +1 -0
  477. package/dist/humain/adaptive-execution.js +100 -0
  478. package/dist/humain/adaptive-execution.js.map +1 -0
  479. package/dist/humain/adaptive-peer-process.d.ts +44 -0
  480. package/dist/humain/adaptive-peer-process.d.ts.map +1 -0
  481. package/dist/humain/adaptive-peer-process.js +159 -0
  482. package/dist/humain/adaptive-peer-process.js.map +1 -0
  483. package/dist/humain/adaptive-peer-worker.d.ts +3 -0
  484. package/dist/humain/adaptive-peer-worker.d.ts.map +1 -0
  485. package/dist/humain/adaptive-peer-worker.js +122 -0
  486. package/dist/humain/adaptive-peer-worker.js.map +1 -0
  487. package/dist/humain/adaptive-runtime-types.d.ts +621 -0
  488. package/dist/humain/adaptive-runtime-types.d.ts.map +1 -0
  489. package/dist/humain/adaptive-runtime-types.js +3 -0
  490. package/dist/humain/adaptive-runtime-types.js.map +1 -0
  491. package/dist/humain/adaptive-session-host.d.ts +113 -0
  492. package/dist/humain/adaptive-session-host.d.ts.map +1 -0
  493. package/dist/humain/adaptive-session-host.js +1838 -0
  494. package/dist/humain/adaptive-session-host.js.map +1 -0
  495. package/dist/humain/adhd/index.d.ts +2 -2
  496. package/dist/humain/adhd/index.d.ts.map +1 -1
  497. package/dist/humain/adhd/index.js +22 -13
  498. package/dist/humain/adhd/index.js.map +1 -1
  499. package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +162 -49
  500. package/dist/humain/caveman/index.d.ts +1 -1
  501. package/dist/humain/caveman/index.d.ts.map +1 -1
  502. package/dist/humain/caveman/index.js +21 -12
  503. package/dist/humain/caveman/index.js.map +1 -1
  504. package/dist/humain/classify-tool.d.ts +4 -0
  505. package/dist/humain/classify-tool.d.ts.map +1 -0
  506. package/dist/humain/classify-tool.js +50 -0
  507. package/dist/humain/classify-tool.js.map +1 -0
  508. package/dist/humain/flow-command.d.ts +1 -1
  509. package/dist/humain/flow-command.d.ts.map +1 -1
  510. package/dist/humain/flow-command.js +21 -3
  511. package/dist/humain/flow-command.js.map +1 -1
  512. package/dist/humain/flow-loader.d.ts +15 -10
  513. package/dist/humain/flow-loader.d.ts.map +1 -1
  514. package/dist/humain/flow-loader.js +72 -18
  515. package/dist/humain/flow-loader.js.map +1 -1
  516. package/dist/humain/fuse-provider.d.ts +5 -0
  517. package/dist/humain/fuse-provider.d.ts.map +1 -0
  518. package/dist/humain/fuse-provider.js +302 -0
  519. package/dist/humain/fuse-provider.js.map +1 -0
  520. package/dist/humain/gateway/provider.d.ts.map +1 -1
  521. package/dist/humain/gateway/provider.js +2 -0
  522. package/dist/humain/gateway/provider.js.map +1 -1
  523. package/dist/humain/gateway/secret-store.d.ts +3 -7
  524. package/dist/humain/gateway/secret-store.d.ts.map +1 -1
  525. package/dist/humain/gateway/secret-store.js +21 -249
  526. package/dist/humain/gateway/secret-store.js.map +1 -1
  527. package/dist/humain/hcode/account-store.d.ts +92 -0
  528. package/dist/humain/hcode/account-store.d.ts.map +1 -0
  529. package/dist/humain/hcode/account-store.js +720 -0
  530. package/dist/humain/hcode/account-store.js.map +1 -0
  531. package/dist/humain/hcode/account.d.ts +42 -0
  532. package/dist/humain/hcode/account.d.ts.map +1 -0
  533. package/dist/humain/hcode/account.js +552 -0
  534. package/dist/humain/hcode/account.js.map +1 -0
  535. package/dist/humain/hcode/catalog.d.ts +6 -0
  536. package/dist/humain/hcode/catalog.d.ts.map +1 -0
  537. package/dist/humain/hcode/catalog.js +47 -0
  538. package/dist/humain/hcode/catalog.js.map +1 -0
  539. package/dist/humain/hcode/contracts.d.ts +389 -0
  540. package/dist/humain/hcode/contracts.d.ts.map +1 -0
  541. package/dist/humain/hcode/contracts.js +1243 -0
  542. package/dist/humain/hcode/contracts.js.map +1 -0
  543. package/dist/humain/hcode/environment.d.ts +9 -0
  544. package/dist/humain/hcode/environment.d.ts.map +1 -0
  545. package/dist/humain/hcode/environment.js +24 -0
  546. package/dist/humain/hcode/environment.js.map +1 -0
  547. package/dist/humain/hcode/facade.d.ts +54 -0
  548. package/dist/humain/hcode/facade.d.ts.map +1 -0
  549. package/dist/humain/hcode/facade.js +326 -0
  550. package/dist/humain/hcode/facade.js.map +1 -0
  551. package/dist/humain/hcode/http.d.ts +10 -0
  552. package/dist/humain/hcode/http.d.ts.map +1 -0
  553. package/dist/humain/hcode/http.js +119 -0
  554. package/dist/humain/hcode/http.js.map +1 -0
  555. package/dist/humain/hcode/notices.d.ts +15 -0
  556. package/dist/humain/hcode/notices.d.ts.map +1 -0
  557. package/dist/humain/hcode/notices.js +69 -0
  558. package/dist/humain/hcode/notices.js.map +1 -0
  559. package/dist/humain/hcode/ports.d.ts +34 -0
  560. package/dist/humain/hcode/ports.d.ts.map +1 -0
  561. package/dist/humain/hcode/ports.js +2 -0
  562. package/dist/humain/hcode/ports.js.map +1 -0
  563. package/dist/humain/hcode/provider.d.ts +15 -0
  564. package/dist/humain/hcode/provider.d.ts.map +1 -0
  565. package/dist/humain/hcode/provider.js +200 -0
  566. package/dist/humain/hcode/provider.js.map +1 -0
  567. package/dist/humain/hcode/selection.d.ts +16 -0
  568. package/dist/humain/hcode/selection.d.ts.map +1 -0
  569. package/dist/humain/hcode/selection.js +37 -0
  570. package/dist/humain/hcode/selection.js.map +1 -0
  571. package/dist/humain/hcode/transport.d.ts +22 -0
  572. package/dist/humain/hcode/transport.d.ts.map +1 -0
  573. package/dist/humain/hcode/transport.js +368 -0
  574. package/dist/humain/hcode/transport.js.map +1 -0
  575. package/dist/humain/hcode/usage.d.ts +5 -0
  576. package/dist/humain/hcode/usage.d.ts.map +1 -0
  577. package/dist/humain/hcode/usage.js +66 -0
  578. package/dist/humain/hcode/usage.js.map +1 -0
  579. package/dist/humain/hcode/wire.d.ts +16 -0
  580. package/dist/humain/hcode/wire.d.ts.map +1 -0
  581. package/dist/humain/hcode/wire.js +104 -0
  582. package/dist/humain/hcode/wire.js.map +1 -0
  583. package/dist/humain/index.d.ts +1 -3
  584. package/dist/humain/index.d.ts.map +1 -1
  585. package/dist/humain/index.js +8 -60
  586. package/dist/humain/index.js.map +1 -1
  587. package/dist/humain/login-menu.d.ts.map +1 -1
  588. package/dist/humain/login-menu.js +8 -1
  589. package/dist/humain/login-menu.js.map +1 -1
  590. package/dist/humain/metadata/contracts.d.ts +82 -0
  591. package/dist/humain/metadata/contracts.d.ts.map +1 -0
  592. package/dist/humain/metadata/contracts.js +214 -0
  593. package/dist/humain/metadata/contracts.js.map +1 -0
  594. package/dist/humain/metadata/identity.d.ts +10 -0
  595. package/dist/humain/metadata/identity.d.ts.map +1 -0
  596. package/dist/humain/metadata/identity.js +209 -0
  597. package/dist/humain/metadata/identity.js.map +1 -0
  598. package/dist/humain/metadata/index.d.ts +41 -0
  599. package/dist/humain/metadata/index.d.ts.map +1 -0
  600. package/dist/humain/metadata/index.js +100 -0
  601. package/dist/humain/metadata/index.js.map +1 -0
  602. package/dist/humain/metadata/sender.d.ts +20 -0
  603. package/dist/humain/metadata/sender.d.ts.map +1 -0
  604. package/dist/humain/metadata/sender.js +302 -0
  605. package/dist/humain/metadata/sender.js.map +1 -0
  606. package/dist/humain/metadata/version.d.ts +8 -0
  607. package/dist/humain/metadata/version.d.ts.map +1 -0
  608. package/dist/humain/metadata/version.js +38 -0
  609. package/dist/humain/metadata/version.js.map +1 -0
  610. package/dist/humain/node-http.d.ts +2 -0
  611. package/dist/humain/node-http.d.ts.map +1 -1
  612. package/dist/humain/node-http.js +9 -4
  613. package/dist/humain/node-http.js.map +1 -1
  614. package/dist/humain/node-provider.d.ts +2 -0
  615. package/dist/humain/node-provider.d.ts.map +1 -1
  616. package/dist/humain/node-provider.js +39 -8
  617. package/dist/humain/node-provider.js.map +1 -1
  618. package/dist/humain/ponytail/vendor/hooks/ponytail-config.d.ts +1 -1
  619. package/dist/humain/ponytail/vendor/hooks/ponytail-config.d.ts.map +1 -1
  620. package/dist/humain/ponytail/vendor/hooks/ponytail-config.js +4 -4
  621. package/dist/humain/ponytail/vendor/hooks/ponytail-config.js.map +1 -1
  622. package/dist/humain/ponytail/vendor/hooks/ponytail-instructions.d.ts.map +1 -1
  623. package/dist/humain/ponytail/vendor/hooks/ponytail-instructions.js +7 -0
  624. package/dist/humain/ponytail/vendor/hooks/ponytail-instructions.js.map +1 -1
  625. package/dist/humain/ponytail/vendor/pi-extension/index.d.ts.map +1 -1
  626. package/dist/humain/ponytail/vendor/pi-extension/index.js +12 -1
  627. package/dist/humain/ponytail/vendor/pi-extension/index.js.map +1 -1
  628. package/dist/humain/systemone.d.ts +23 -0
  629. package/dist/humain/systemone.d.ts.map +1 -0
  630. package/dist/humain/systemone.js +101 -0
  631. package/dist/humain/systemone.js.map +1 -0
  632. package/dist/humain/trace-capture/flow-producer.d.ts.map +1 -1
  633. package/dist/humain/trace-capture/flow-producer.js +3 -3
  634. package/dist/humain/trace-capture/flow-producer.js.map +1 -1
  635. package/dist/index.d.ts +4 -2
  636. package/dist/index.d.ts.map +1 -1
  637. package/dist/index.js.map +1 -1
  638. package/dist/main.d.ts +1 -0
  639. package/dist/main.d.ts.map +1 -1
  640. package/dist/main.js +292 -183
  641. package/dist/main.js.map +1 -1
  642. package/dist/modes/interactive/bug-report.d.ts.map +1 -1
  643. package/dist/modes/interactive/bug-report.js +82 -36
  644. package/dist/modes/interactive/bug-report.js.map +1 -1
  645. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  646. package/dist/modes/interactive/components/assistant-message.js +8 -5
  647. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  648. package/dist/modes/interactive/components/diff.d.ts.map +1 -1
  649. package/dist/modes/interactive/components/diff.js +11 -5
  650. package/dist/modes/interactive/components/diff.js.map +1 -1
  651. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  652. package/dist/modes/interactive/components/extension-selector.js +9 -1
  653. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  654. package/dist/modes/interactive/components/first-time-setup.d.ts +10 -5
  655. package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
  656. package/dist/modes/interactive/components/first-time-setup.js +55 -29
  657. package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
  658. package/dist/modes/interactive/components/model-selector.d.ts +16 -2
  659. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  660. package/dist/modes/interactive/components/model-selector.js +164 -19
  661. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  662. package/dist/modes/interactive/components/oauth-selector.d.ts +3 -0
  663. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  664. package/dist/modes/interactive/components/oauth-selector.js +19 -2
  665. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  666. package/dist/modes/interactive/components/status-indicator.d.ts +17 -0
  667. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  668. package/dist/modes/interactive/components/status-indicator.js +78 -1
  669. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  670. package/dist/modes/interactive/components/tree-selector.d.ts +1 -0
  671. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  672. package/dist/modes/interactive/components/tree-selector.js +19 -10
  673. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  674. package/dist/modes/interactive/interactive-mode.d.ts +4 -0
  675. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  676. package/dist/modes/interactive/interactive-mode.js +353 -65
  677. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  678. package/dist/modes/interactive/interactive-mode.lazy.d.ts +3 -0
  679. package/dist/modes/interactive/interactive-mode.lazy.d.ts.map +1 -0
  680. package/dist/modes/interactive/interactive-mode.lazy.js +3 -0
  681. package/dist/modes/interactive/interactive-mode.lazy.js.map +1 -0
  682. package/dist/modes/interactive/model-catalog-refresh.d.ts +2 -0
  683. package/dist/modes/interactive/model-catalog-refresh.d.ts.map +1 -1
  684. package/dist/modes/interactive/model-catalog-refresh.js +12 -0
  685. package/dist/modes/interactive/model-catalog-refresh.js.map +1 -1
  686. package/dist/modes/interactive/theme/theme-controller.d.ts +2 -3
  687. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -1
  688. package/dist/modes/interactive/theme/theme-controller.js +4 -5
  689. package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
  690. package/dist/modes/interactive/theme/theme-schema.js +4 -4
  691. package/dist/modes/interactive/theme/theme-schema.js.map +1 -1
  692. package/dist/modes/interactive/theme/theme.d.ts +2 -0
  693. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  694. package/dist/modes/interactive/theme/theme.js +8 -0
  695. package/dist/modes/interactive/theme/theme.js.map +1 -1
  696. package/dist/modes/json-event.d.ts +2 -1
  697. package/dist/modes/json-event.d.ts.map +1 -1
  698. package/dist/modes/json-event.js.map +1 -1
  699. package/dist/modes/print-mode.d.ts +4 -0
  700. package/dist/modes/print-mode.d.ts.map +1 -1
  701. package/dist/modes/print-mode.js +57 -11
  702. package/dist/modes/print-mode.js.map +1 -1
  703. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  704. package/dist/modes/rpc/rpc-mode.js +68 -16
  705. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  706. package/dist/modes/rpc/rpc-types.d.ts +2 -0
  707. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  708. package/dist/modes/rpc/rpc-types.js.map +1 -1
  709. package/dist/utils/changelog.d.ts +1 -1
  710. package/dist/utils/changelog.d.ts.map +1 -1
  711. package/dist/utils/changelog.js +7 -5
  712. package/dist/utils/changelog.js.map +1 -1
  713. package/dist/utils/image-resize.d.ts.map +1 -1
  714. package/dist/utils/image-resize.js +3 -1
  715. package/dist/utils/image-resize.js.map +1 -1
  716. package/dist/utils/lazy-validator.d.ts +5 -0
  717. package/dist/utils/lazy-validator.d.ts.map +1 -0
  718. package/dist/utils/lazy-validator.js +7 -0
  719. package/dist/utils/lazy-validator.js.map +1 -0
  720. package/dist/utils/shell.d.ts +3 -1
  721. package/dist/utils/shell.d.ts.map +1 -1
  722. package/dist/utils/shell.js +9 -4
  723. package/dist/utils/shell.js.map +1 -1
  724. package/docs/cli.md +23 -5
  725. package/docs/codemode.md +21 -1
  726. package/docs/development.md +18 -0
  727. package/docs/docs.json +4 -0
  728. package/docs/extensions.md +4 -0
  729. package/docs/flow.md +115 -16
  730. package/docs/headless-modes.md +61 -0
  731. package/docs/humain-code-forge-architecture.md +65 -13
  732. package/docs/humain-code-forge-component-scorecard.md +10 -1
  733. package/docs/humain-code-forge-flow-walkthrough.md +54 -55
  734. package/docs/humain-code.md +22 -19
  735. package/docs/index.md +1 -0
  736. package/docs/keybindings.md +1 -1
  737. package/docs/models-configuration.md +6 -1
  738. package/docs/models.md +1 -1
  739. package/docs/prompt-templates.md +1 -1
  740. package/docs/providers.md +67 -15
  741. package/docs/run-preflight.md +47 -0
  742. package/docs/sdk.md +39 -1
  743. package/docs/security.md +1 -1
  744. package/docs/settings.md +12 -5
  745. package/docs/skills.md +2 -0
  746. package/docs/slash-commands.md +5 -3
  747. package/docs/usage.md +29 -0
  748. package/examples/extensions/custom-provider-anthropic/package-lock.json +4 -4
  749. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  750. package/examples/tsconfig.json +13 -0
  751. package/npm-shrinkwrap.json +67 -67
  752. package/package.json +25 -19
  753. package/schemas/models.schema.json +30 -0
  754. package/schemas/settings.schema.json +28 -9
  755. package/src/humain/caveman/UPSTREAM.md +19 -3
  756. package/src/humain/caveman/upstream.json +2 -2
  757. package/src/humain/ponytail/UPSTREAM.md +16 -1
  758. package/src/humain/web-access/UPSTREAM.md +10 -0
  759. package/src/humain/web-access/upstream.json +1 -0
  760. package/dist/bundle/chunks/anthropic-messages-MNISFDZA.js +0 -66
  761. package/dist/bundle/chunks/chunk-2HZ2V3HS.js +0 -1985
  762. package/dist/bundle/chunks/chunk-2PZ46FSM.js +0 -6
  763. package/dist/bundle/chunks/chunk-4SQUP6IR.js +0 -88
  764. package/dist/bundle/chunks/chunk-5JSLXC2A.js +0 -3
  765. package/dist/bundle/chunks/chunk-75CQYZ63.js +0 -1336
  766. package/dist/bundle/chunks/chunk-DCPACGLH.js +0 -12267
  767. package/dist/bundle/chunks/chunk-FLVBQ6GS.js +0 -24
  768. package/dist/bundle/chunks/chunk-H7Y4QY7K.js +0 -11
  769. package/dist/bundle/chunks/chunk-JEAM6N22.js +0 -139
  770. package/dist/bundle/chunks/chunk-PS2FJ7M4.js +0 -23
  771. package/dist/bundle/chunks/chunk-TEOMXMW6.js +0 -23
  772. package/dist/bundle/chunks/chunk-WEFEQEIQ.js +0 -28
  773. package/dist/bundle/chunks/chunk-WW4SILXG.js +0 -249
  774. package/dist/bundle/chunks/compat-MXAZPYDN.js +0 -13
  775. package/dist/bundle/chunks/dist-3V7ZSLER.js +0 -3166
  776. package/dist/bundle/chunks/dist-66CW64M2.js +0 -8
  777. package/dist/bundle/chunks/host-SCZ4IKWR.js +0 -2
  778. package/dist/bundle/chunks/openai-codex-responses-LZWBQYVP.js +0 -101
  779. package/dist/bundle/chunks/openai-completions-7NWH423P.js +0 -82
  780. package/dist/bundle/chunks/openai-responses-5YOLHMCF.js +0 -27
  781. package/dist/bundle/chunks/runtime-UVPDE4CX.js +0 -2
  782. package/dist/bundle/chunks/typesafe-system-one-BHJYAZ6E.js +0 -3
  783. package/dist/bundle/chunks/virtual-modules-YQPK57CW.js +0 -23
  784. package/dist/humain/legacy-workflow-tiers.d.ts +0 -3
  785. package/dist/humain/legacy-workflow-tiers.d.ts.map +0 -1
  786. package/dist/humain/legacy-workflow-tiers.js +0 -46
  787. package/dist/humain/legacy-workflow-tiers.js.map +0 -1
  788. /package/dist/bundle/{flow → orchestrate}/agents/orch-architect.md +0 -0
  789. /package/dist/bundle/{flow → orchestrate}/agents/orch-scout.md +0 -0
  790. /package/dist/bundle/{flow → orchestrate}/agents/orch-security-review.md +0 -0
  791. /package/dist/bundle/{flow → orchestrate}/agents/orch-technical-lead.md +0 -0
  792. /package/dist/bundle/{flow → orchestrate}/agents/orch-technical-review.md +0 -0
@@ -1,17 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{__commonJS,__toESM}from"./chunk-JXWJOIH4.js";var require_options=__commonJS({"node_modules/partial-json/dist/options.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.Allow=exports.ALL=exports.COLLECTION=exports.ATOM=exports.SPECIAL=exports.INF=exports._INFINITY=exports.INFINITY=exports.NAN=exports.BOOL=exports.NULL=exports.OBJ=exports.ARR=exports.NUM=exports.STR=void 0;exports.STR=1;exports.NUM=2;exports.ARR=4;exports.OBJ=8;exports.NULL=16;exports.BOOL=32;exports.NAN=64;exports.INFINITY=128;exports._INFINITY=
3
- 256;exports.INF=exports.INFINITY|exports._INFINITY;exports.SPECIAL=exports.NULL|exports.BOOL|exports.INF|exports.NAN;exports.ATOM=exports.STR|exports.NUM|exports.SPECIAL;exports.COLLECTION=exports.ARR|exports.OBJ;exports.ALL=exports.ATOM|exports.COLLECTION;exports.Allow={STR:exports.STR,NUM:exports.NUM,ARR:exports.ARR,OBJ:exports.OBJ,NULL:exports.NULL,BOOL:exports.BOOL,NAN:exports.NAN,INFINITY:exports.INFINITY,_INFINITY:exports._INFINITY,INF:exports.INF,SPECIAL:exports.SPECIAL,ATOM:exports.ATOM,
4
- COLLECTION:exports.COLLECTION,ALL:exports.ALL};exports.default=exports.Allow}});var require_dist=__commonJS({"node_modules/partial-json/dist/index.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__exportStar=exports&&exports.__exportStar||
5
- function(m,exports2){for(var p in m)p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p)&&__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:!0});exports.Allow=exports.MalformedJSON=exports.PartialJSON=exports.parseJSON=exports.parse=void 0;var options_1=require_options();Object.defineProperty(exports,"Allow",{enumerable:!0,get:function(){return options_1.Allow}});__exportStar(require_options(),exports);var PartialJSON=class extends Error{};exports.PartialJSON=
6
- PartialJSON;var MalformedJSON=class extends Error{};exports.MalformedJSON=MalformedJSON;function parseJSON(jsonString,allowPartial=options_1.Allow.ALL){if(typeof jsonString!="string")throw new TypeError(`expecting str, got ${typeof jsonString}`);if(!jsonString.trim())throw new Error(`${jsonString} is empty`);return _parseJSON(jsonString.trim(),allowPartial)}exports.parseJSON=parseJSON;var _parseJSON=(jsonString,allow)=>{let length=jsonString.length,index=0,markPartialJSON=msg=>{throw new PartialJSON(
7
- `${msg} at position ${index}`)},throwMalformedError=msg=>{throw new MalformedJSON(`${msg} at position ${index}`)},parseAny=()=>(skipBlank(),index>=length&&markPartialJSON("Unexpected end of input"),jsonString[index]==='"'?parseStr():jsonString[index]==="{"?parseObj():jsonString[index]==="["?parseArr():jsonString.substring(index,index+4)==="null"||options_1.Allow.NULL&allow&&length-index<4&&"null".startsWith(jsonString.substring(index))?(index+=4,null):jsonString.substring(index,index+4)==="true"||
8
- options_1.Allow.BOOL&allow&&length-index<4&&"true".startsWith(jsonString.substring(index))?(index+=4,!0):jsonString.substring(index,index+5)==="false"||options_1.Allow.BOOL&allow&&length-index<5&&"false".startsWith(jsonString.substring(index))?(index+=5,!1):jsonString.substring(index,index+8)==="Infinity"||options_1.Allow.INFINITY&allow&&length-index<8&&"Infinity".startsWith(jsonString.substring(index))?(index+=8,1/0):jsonString.substring(index,index+9)==="-Infinity"||options_1.Allow._INFINITY&allow&&
9
- 1<length-index&&length-index<9&&"-Infinity".startsWith(jsonString.substring(index))?(index+=9,-1/0):jsonString.substring(index,index+3)==="NaN"||options_1.Allow.NAN&allow&&length-index<3&&"NaN".startsWith(jsonString.substring(index))?(index+=3,NaN):parseNum()),parseStr=()=>{let start=index,escape=!1;for(index++;index<length&&(jsonString[index]!=='"'||escape&&jsonString[index-1]==="\\");)escape=jsonString[index]==="\\"?!escape:!1,index++;if(jsonString.charAt(index)=='"')try{return JSON.parse(jsonString.
10
- substring(start,++index-Number(escape)))}catch(e){throwMalformedError(String(e))}else if(options_1.Allow.STR&allow)try{return JSON.parse(jsonString.substring(start,index-Number(escape))+'"')}catch{return JSON.parse(jsonString.substring(start,jsonString.lastIndexOf("\\"))+'"')}markPartialJSON("Unterminated string literal")},parseObj=()=>{index++,skipBlank();let obj={};try{for(;jsonString[index]!=="}";){if(skipBlank(),index>=length&&options_1.Allow.OBJ&allow)return obj;let key=parseStr();skipBlank(),
11
- index++;try{let value=parseAny();obj[key]=value}catch(e){if(options_1.Allow.OBJ&allow)return obj;throw e}skipBlank(),jsonString[index]===","&&index++}}catch{if(options_1.Allow.OBJ&allow)return obj;markPartialJSON("Expected '}' at end of object")}return index++,obj},parseArr=()=>{index++;let arr=[];try{for(;jsonString[index]!=="]";)arr.push(parseAny()),skipBlank(),jsonString[index]===","&&index++}catch{if(options_1.Allow.ARR&allow)return arr;markPartialJSON("Expected ']' at end of array")}return index++,
12
- arr},parseNum=()=>{if(index===0){jsonString==="-"&&throwMalformedError("Not sure what '-' is");try{return JSON.parse(jsonString)}catch(e){if(options_1.Allow.NUM&allow)try{return JSON.parse(jsonString.substring(0,jsonString.lastIndexOf("e")))}catch{}throwMalformedError(String(e))}}let start=index;for(jsonString[index]==="-"&&index++;jsonString[index]&&",]}".indexOf(jsonString[index])===-1;)index++;index==length&&!(options_1.Allow.NUM&allow)&&markPartialJSON("Unterminated number literal");try{return JSON.
13
- parse(jsonString.substring(start,index))}catch{jsonString.substring(start,index)==="-"&&markPartialJSON("Not sure what '-' is");try{return JSON.parse(jsonString.substring(start,jsonString.lastIndexOf("e")))}catch(e2){throwMalformedError(String(e2))}}},skipBlank=()=>{for(;index<length&&`
14
- \r `.includes(jsonString[index]);)index++};return parseAny()},parse=parseJSON;exports.parse=parse}});var import_partial_json=__toESM(require_dist(),1),VALID_JSON_ESCAPES=new Set(['"',"\\","/","b","f","n","r","t"]);function escapeControlCharacter(char){switch(char){case"\b":return"\\b";case"\f":return"\\f";case`
2
+ import{require_dist}from"./chunk-AQ4EXORZ.js";import{__toESM}from"./chunk-JXWJOIH4.js";var import_partial_json=__toESM(require_dist(),1),VALID_JSON_ESCAPES=new Set(['"',"\\","/","b","f","n","r","t"]);function escapeControlCharacter(char){switch(char){case"\b":return"\\b";case"\f":return"\\f";case`
15
3
  `:return"\\n";case"\r":return"\\r";case" ":return"\\t";default:return`\\u${char.codePointAt(0)?.toString(16).padStart(4,"0")??"0000"}`}}function repairJson(json){let repaired="",runStart=0,inString=!1;for(let index=0;index<json.length;index++){let code=json.charCodeAt(index);if(!inString){code===34&&(inString=!0);continue}if(code===34){inString=!1;continue}if(code===92){let nextChar=json[index+1],validUnicodeEscape=nextChar==="u"&&isHexDigit(json.charCodeAt(index+2))&&isHexDigit(json.charCodeAt(
16
4
  index+3))&&isHexDigit(json.charCodeAt(index+4))&&isHexDigit(json.charCodeAt(index+5));if(nextChar!==void 0&&(VALID_JSON_ESCAPES.has(nextChar)||validUnicodeEscape)){index+=1;continue}repaired+=`${json.slice(runStart,index)}\\\\`,runStart=index+1;continue}code<=31&&(repaired+=json.slice(runStart,index)+escapeControlCharacter(json[index]),runStart=index+1)}return runStart===0?json:repaired+json.slice(runStart)}function parseJsonWithRepair(json){try{return JSON.parse(json)}catch(error){let repairedJson=repairJson(
17
5
  json);if(repairedJson!==json)return JSON.parse(repairedJson);throw error}}function parseToolCallArguments(json){if(!json?.trim())return{arguments:{}};try{let parsed=parseJsonWithRepair(json);if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new Error("Tool arguments must be a JSON object");return{arguments:parsed}}catch(error){return{arguments:{},argumentsError:`${error instanceof Error?error.message:String(error)}
@@ -49,4 +37,4 @@ let delta=text.slice(this.#text.length);return{delta,arguments:delta===""?this.#
49
37
  SIMPLE_ESCAPES={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
50
38
  `,r:"\r",t:" "};function isDelimiter(char){return char===" "||char===" "||char===`
51
39
  `||char==="\r"||char===","||char===":"||char==="{"||char==="}"||char==="["||char==="]"||char==='"'}function isHexDigit2(char){return char>="0"&&char<="9"||char>="a"&&char<="f"||char>="A"&&char<="F"}function scalarValue(token){for(let[literal,value]of LITERALS)if(token===literal)return value;return NUMBER2.test(token)?Number(token):void 0}function pendingScalarValue(token){for(let[literal,value]of LITERALS)if(literal.startsWith(token))return value;if(NUMBER2.test(token))return Number(token);let mantissa=NUMBER_WITHOUT_EXPONENT_DIGITS.
52
- exec(token);return mantissa===null?void 0:Number(mantissa[1])}function setSlot(container,slot,value){slot.kind==="element"?container[slot.index]=value:slot.kind==="member"&&setMember(container,slot.key,value)}function setMember(members,key,value){key==="__proto__"?Object.defineProperty(members,key,{value,writable:!0,enumerable:!0,configurable:!0}):members[key]=value}export{require_dist,repairJson,parseJsonWithRepair,parseToolCallArguments,parseStreamingJson,parseStreamingJsonWhileStreaming,StreamingJsonParser,ToolCallArgumentsStream};
40
+ exec(token);return mantissa===null?void 0:Number(mantissa[1])}function setSlot(container,slot,value){slot.kind==="element"?container[slot.index]=value:slot.kind==="member"&&setMember(container,slot.key,value)}function setMember(members,key,value){key==="__proto__"?Object.defineProperty(members,key,{value,writable:!0,enumerable:!0,configurable:!0}):members[key]=value}export{repairJson,parseJsonWithRepair,parseToolCallArguments,parseStreamingJson,parseStreamingJsonWhileStreaming,StreamingJsonParser,ToolCallArgumentsStream};
@@ -0,0 +1,20 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
+ import{resolveSchemaRef}from"./chunk-WAPZN4KP.js";import{typebox_exports}from"./chunk-VEGJT52D.js";var TOOL_SEARCH_TOOL_NAME="tool_search",DEFAULT_TOOL_SEARCH_LIMIT=8,wordSegmenter=new Intl.Segmenter(void 0,{granularity:"word"}),STOP_WORDS=new Set(["a","an","and","are","as","at","be","by","for","from","in","is","it","of","on","or","that","the","this","to","with"]);function stem(term){return term.length>4&&term.endsWith("ies")?`${term.slice(0,-3)}y`:term.length>4&&/(ches|shes|sses|xes|zes)$/.test(term)?term.slice(0,-2):term.length>3&&term.endsWith("s")&&!term.endsWith("ss")?term.slice(0,-1):term}
3
+ function tokenize(text){let normalized=text.normalize("NFC").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().replace(/[^\p{L}\p{M}\p{N}]+/gu," ");return(/^[a-z0-9 ]*$/.test(normalized)?normalized.split(" "):Array.from(wordSegmenter.segment(normalized),segment=>segment.isWordLike?segment.segment:"")).filter(word=>word.length>0&&!STOP_WORDS.has(word)).map(word=>/^[a-z0-9]+$/.test(word)?stem(word):word)}function isObject(value){return typeof value=="obje\
4
+ ct"&&value!==null&&!Array.isArray(value)}function schemaText(schema,root,parts,seen){if(isObject(schema)){if(typeof schema.$ref=="string"){let target=resolveSchemaRef(schema.$ref,root);isObject(target)&&!seen.has(target)&&(seen.add(target),schemaText(target,root,parts,seen))}if(typeof schema.description=="string"&&parts.push(schema.description),isObject(schema.properties))for(let[name,property]of Object.entries(schema.properties))parts.push(name),schemaText(property,root,parts,seen);schemaText(schema.
5
+ items,root,parts,seen);for(let key of["anyOf","oneOf","allOf"]){let variants=schema[key];if(Array.isArray(variants))for(let variant of variants)schemaText(variant,root,parts,seen)}}}function createToolSearchDocument(tool,namespace){let parts=[tool.description];schemaText(tool.parameters,tool.parameters,parts,new Set([tool.parameters]));let namespaceText=namespace?[namespace.name,namespace.description??"",namespace.instructions??""].join(" "):"";return{name:tool.name,text:parts.filter(part=>part.
6
+ trim()).join(" "),namespaceText}}function normalizeName(name){return name.trim().toLowerCase().replace(/[^a-z0-9_$]/g,"_")}function isExactNameQuery(query,name){let normalized=normalizeName(name);return normalized===query||normalized.endsWith(`__${query}`)}function indexDocument(document){let textCounts=new Map;for(let term of tokenize(document.text))textCounts.set(term,(textCounts.get(term)??0)+1);let segments=document.name.split("__");return{name:document.name,nameTerms:new Set(tokenize(document.
7
+ name)),localNameTerms:[...new Set(tokenize(segments[segments.length-1]))],textCounts,textLength:[...textCounts.values()].reduce((sum,count)=>sum+count,0),namespaceTerms:new Set(tokenize(document.namespaceText??""))}}var NAME_WEIGHT=3,NAMESPACE_WEIGHT=.5,Bm25Ranker=class{k1;b;constructor(options={}){this.k1=options.k1??1.2,this.b=options.b??.75}rank(query,documents,limit){let queryTerms=new Set(tokenize(query));if(queryTerms.size===0||documents.length===0||limit<=0)return[];let indexed=documents.
8
+ map(indexDocument),averageLength=indexed.reduce((sum,document)=>sum+document.textLength,0)/indexed.length||1,idf=new Map([...queryTerms].map(term=>{let frequency=indexed.filter(document=>document.nameTerms.has(term)||document.textCounts.has(term)||document.namespaceTerms.has(term)).length;return[term,Math.log(1+(indexed.length-frequency+.5)/(frequency+.5))]})),fullNameBonus=[...idf.values()].reduce((sum,value)=>sum+value,0),exactQuery=normalizeName(query),matches=[];for(let document of indexed){
9
+ let norm=this.k1*(1-this.b+this.b*document.textLength/averageLength),score=0,covered=0;for(let term of queryTerms){let count=document.textCounts.get(term)??0,weight=(document.nameTerms.has(term)?NAME_WEIGHT:0)+(document.namespaceTerms.has(term)?NAMESPACE_WEIGHT:0)+count*(this.k1+1)/(count+norm);weight>0&&covered++,score+=(idf.get(term)??0)*weight}if(score===0)continue;let local=document.localNameTerms;local.length>0&&local.every(term=>queryTerms.has(term))&&(score+=fullNameBonus),matches.push({name:document.
10
+ name,score,covered,exact:isExactNameQuery(exactQuery,document.name)})}return matches.sort((a,b)=>Number(b.exact)-Number(a.exact)||b.covered-a.covered||b.score-a.score).slice(0,limit).map(({name,score})=>({name,score}))}},toolSearchSchema=typebox_exports.Object({query:typebox_exports.String({description:"Search query for deferred tools."}),limit:typebox_exports.Optional(typebox_exports.Number({description:`Maximum number of tools to return. Defaults to ${DEFAULT_TOOL_SEARCH_LIMIT}.`}))});function isSearchable(exposure){
11
+ return exposure==="codemode"||exposure==="deferred"}function searchAndLoad(tools,query,limit){let active=tools.getActiveTools(),candidates=tools.getAllTools().filter(tool=>isSearchable(tool.exposure)&&!active.includes(tool.name)),documents=candidates.map(tool=>createToolSearchDocument(tool,tool.namespace)),matches=new Bm25Ranker().rank(query,documents,limit);return matches.length>0&&tools.setActiveTools([...active,...matches.map(match=>match.name)]),matches.map(match=>({name:match.name,description:candidates.
12
+ find(tool=>tool.name===match.name)?.description??""}))}var TOOL_SEARCH_DESCRIPTION=`# Tool discovery
13
+
14
+ Searches over deferred tool metadata with BM25 and exposes matching tools for the next model call.
15
+
16
+ Some of the tools, such as tools of MCP servers, may not have been provided to you upfront, and you should use this tool (\`${TOOL_SEARCH_TOOL_NAME}\`) to search for the required tools. For MCP tool discovery, always use \`${TOOL_SEARCH_TOOL_NAME}\`.`;function createToolSearchToolDefinition(options={}){return{name:TOOL_SEARCH_TOOL_NAME,label:TOOL_SEARCH_TOOL_NAME,description:TOOL_SEARCH_DESCRIPTION,promptSnippet:"Search for tools that are not loaded yet and load the matches",parameters:toolSearchSchema,
17
+ exposure:"model-only",reachesTools:()=>"all",async execute(_toolCallId,{query,limit}){if(query.trim()==="")throw new Error("query must not be empty");let max=limit??DEFAULT_TOOL_SEARCH_LIMIT;if(!Number.isInteger(max)||max<=0)throw new Error("limit must be a positive integer");let tools=options.tools?searchAndLoad(options.tools,query,max):[];return{content:[{type:"text",text:tools.length===0?"No matching tools found.":`Loaded ${tools.length} tool${tools.length===1?"":"s"}. They are available from\
18
+ your next call:
19
+ ${tools.map(tool=>`- ${tool.name}: ${tool.description.trim().split(/\r?\n/)[0]}`).join(`
20
+ `)}`}],details:{loaded:tools.map(tool=>tool.name)}}}}}export{TOOL_SEARCH_TOOL_NAME,DEFAULT_TOOL_SEARCH_LIMIT,createToolSearchDocument,Bm25Ranker,createToolSearchToolDefinition};
@@ -0,0 +1,214 @@
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};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{retryProviderRequest}from"./chunk-BQ3TMEWD.js";import{createRequestObserver,headersToRecord,providerHeadersToRecord}from"./chunk-5JSLXC2A.js";import{calculateCost}from"./chunk-4SQUP6IR.js";import{getIdentityHeaders}from"./chunk-XMZGB3H4.js";function httpError(label,response,body){let error=new Error(`${label} returned ${response.status}`);return error.status=response.status,error.headers=response.headers,error.body=body,error}function timeoutError(timeoutMs){let error=new Error(`Request timed out after ${timeoutMs}ms`);return error.name="TimeoutError",error.status=void 0,error.headers=void 0,error.body="",error}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function requiredNumber(label,value,field){
2
+ import{retryProviderRequest}from"./chunk-EIC7CQX3.js";import{calculateCost}from"./chunk-AEWYICBL.js";import{createRequestObserver,getIdentityHeaders,headersToRecord,providerHeadersToRecord}from"./chunk-4HTVBBJD.js";function httpError(label,response,body){let error=new Error(`${label} returned ${response.status}`);return error.status=response.status,error.headers=response.headers,error.body=body,error}function timeoutError(timeoutMs){let error=new Error(`Request timed out after ${timeoutMs}ms`);return error.name="TimeoutError",error.status=void 0,error.headers=void 0,error.body="",error}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function requiredNumber(label,value,field){
3
3
  if(typeof value!="number"||!Number.isFinite(value))throw new Error(`${label} returned an invalid ${field}`);return value}function requestHeaders(model,apiKey,optionsHeaders,identity){return providerHeadersToRecord(getIdentityHeaders(model,identity),{authorization:`Bearer ${apiKey}`,"content-type":"application/json"},model.headers,optionsHeaders)??{}}async function postClassifierRequest(label,url,model,body,options,noRetryStatuses){if(!options?.apiKey)throw new Error(`No API key for provider: ${model.
4
4
  provider}`);let apiKey=options.apiKey,payload=body,transformed=await options.onPayload?.(payload,model);transformed!==void 0&&(payload=transformed);let requestFetch=options.fetch??globalThis.fetch,observe=createRequestObserver(options,{api:model.api,provider:model.provider,model:model.id,operation:"classifier"}),{response,json}=await retryProviderRequest(async()=>{let timeoutSignal=options.timeoutMs!==void 0?AbortSignal.timeout(options.timeoutMs):void 0,signal=options.signal&&timeoutSignal?AbortSignal.
5
5
  any([options.signal,timeoutSignal]):options.signal??timeoutSignal;try{let requestBody=JSON.stringify(payload);await observe(requestBody);let next=await requestFetch(url,{method:"POST",headers:requestHeaders(model,apiKey,options.headers,options.identity),body:requestBody,signal});if(!next.ok)throw httpError(label,next,await next.text());return{response:next,json:await next.json()}}catch(error){throw timeoutSignal?.aborted&&!options.signal?.aborted?timeoutError(options.timeoutMs):error}},{maxRetries:options.
@@ -0,0 +1,54 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
+ import{HCODE_PROVIDER,fetchWithRetry,getCodexAvailability,getPiUserAgent,isWSL,parseHcodeInferenceError,parseSubscriptionCreditAmount}from"./chunk-T7BXP46S.js";import{raceWithAbortSignal}from"./chunk-PWUDFU5V.js";import{addUsageToTotals,createUsageTotals,getSessionUsage}from"./chunk-GTILMMUF.js";import{stripAnsi}from"./chunk-5B25YXF7.js";import{areExperimentalFeaturesEnabled}from"./chunk-J57HOSWD.js";import{require_semver}from"./chunk-G4QPSFBF.js";import{getThemeInstance,
3
+ keyHint,theme}from"./chunk-JF7FYXAI.js";import{Container,Text,getNativeClipboard,hyperlink,truncateToWidth,visibleWidth,wrapTextWithAnsi}from"./chunk-JYWUOKOI.js";import{killTrackedDetachedChildrenAsync}from"./chunk-CRN54O4D.js";import{APP_COMMAND,ENV_OFFLINE,ENV_SKIP_VERSION_CHECK,getVersionCheckUrl}from"./chunk-VFLVWPLZ.js";import{__toESM}from"./chunk-JXWJOIH4.js";import{randomUUID}from"node:crypto";import{unlinkSync,writeFileSync}from"node:fs";import{platform,tmpdir}from"node:os";import{join}from"node:path";import{spawn}from"node:child_process";function runClipboardCommand(command,args,options){return new Promise(resolve2=>{let child=spawn(command,args,{stdio:["pipe",options?.input===void 0?"pipe":"ignore","ignore"],cwd:"/",detached:process.platform!=="win32",windowsHide:!0}),chunks=[],length=0,settled=!1,finish=result=>{settled||(settled=!0,clearTimeout(timer),resolve2(result))},abort=()=>{child.kill("SIGKILL"),child.stdout?.destroy(),child.stdin?.destroy(),finish(void 0)},timer=setTimeout(abort,options?.
4
+ timeoutMs??3e3);child.on("error",()=>finish(void 0)),child.on("close",code=>{settled||finish(code===0?Buffer.concat(chunks,length):void 0)}),child.stdout?.on("data",chunk=>{settled||(length+=chunk.length,length>(options?.maxBufferBytes??50*1024*1024)?abort():chunks.push(chunk))}),child.stdin?.on("error",()=>{}),child.stdin?.end(options?.input)})}var MAX_OSC52_ENCODED_LENGTH=1e5;function isRemoteSession(env){return!!(env.SSH_CONNECTION||env.SSH_CLIENT||env.MOSH_CONNECTION||env.HUMAIN_TERMINAL_CLIPBOARD_OSC52==="1")}function emitOsc52(text){let encoded=Buffer.from(text).toString("base64");return encoded.length>MAX_OSC52_ENCODED_LENGTH?!1:(process.stdout.write(`\x1B]52;c;${encoded}\x07`),!0)}async function copyViaWindowsClipboard(text){let tmpFile=join(tmpdir(),`pi-wsl-clip-${randomUUID()}.txt`);try{writeFileSync(tmpFile,text,{encoding:"ut\
5
+ f8",mode:384});let winPath=(await runClipboardCommand("wslpath",["-w",tmpFile],{timeoutMs:1e3}))?.toString("utf8").trim();if(!winPath)return!1;let script=`Set-Clipboard -Value ([System.IO.File]::ReadAllText('${winPath.replaceAll("'","''")}', [System.Text.Encoding]::UTF8))`;return await runClipboardCommand("powershell.exe",["-NoProfile","-Command",script],{timeoutMs:5e3})!==void 0}catch{return!1}finally{try{unlinkSync(tmpFile)}catch{}}}async function readClipboardText(){let commands=[];process.env.
6
+ TERMUX_VERSION&&commands.push(["termux-clipboard-get",[]]),platform()==="linux"&&(process.env.WAYLAND_DISPLAY&&commands.push(["wl-paste",["--no-newline","--type","text"]]),process.env.DISPLAY&&commands.push(["xclip",["-selection","clipboard","-out"]],["xsel",["--clipboard","--output"]]));for(let[command,args]of commands){let bytes=await runClipboardCommand(command,args,{timeoutMs:5e3});if(bytes!==void 0)return bytes.toString("utf8")||null}try{return await getNativeClipboard()?.getText()||null}catch{
7
+ return null}}async function readClipboardFilePaths(){let paths=await getNativeClipboard()?.getFilePaths?.();return paths?.length?paths:null}async function copyToClipboard(text){let p=platform(),env=process.env,copied=!1;if(p!=="linux")try{let clipboard=getNativeClipboard();clipboard?.setText&&(await clipboard.setText(text),copied=!0)}catch{}if(!copied){let commands=[];p==="darwin"?commands.push(["pbcopy",[]]):p==="win32"?commands.push(["clip",[]]):(env.TERMUX_VERSION&&commands.push(["termux-clip\
8
+ board-set",[]]),env.WAYLAND_DISPLAY&&commands.push(["wl-copy",[]]),env.DISPLAY&&commands.push(["xclip",["-selection","clipboard"]],["xsel",["--clipboard","--input"]]));for(let[command,args]of commands)if(await runClipboardCommand(command,args,{input:text,timeoutMs:5e3})!==void 0){copied=!0;break}}let osc52Emitted=!1;!copied&&p==="linux"&&isWSL(env)&&(env.WT_SESSION&&(osc52Emitted=emitOsc52(text)),copied=osc52Emitted||await copyViaWindowsClipboard(text));let headless=p==="linux"&&!env.DISPLAY&&!env.
9
+ WAYLAND_DISPLAY&&!env.TERMUX_VERSION,oversized=!1;if(!osc52Emitted&&(isRemoteSession(env)||!copied&&headless)&&(emitOsc52(text)?copied=!0:oversized=!0),!copied){if(oversized)throw new Error("Clipboard unavailable: text exceeds the OSC 52 size limit");if(env.TERMUX_VERSION)throw new Error("Clipboard unavailable: install the Termux:API app and `termux-api` package");if(p==="linux"){if(env.WAYLAND_DISPLAY)throw new Error("Clipboard unavailable: install `wl-clipboard` (`wl-copy`) or check Wayland ac\
10
+ cess");if(env.DISPLAY)throw new Error("Clipboard unavailable: install `xclip` or `xsel`, or check X11 access")}throw new Error("Clipboard unavailable")}}var current,listeners=new Set;function notify(){for(let listener of listeners)try{listener()}catch{}}function trackUserWait(reason,promise){let wait={reason};return current=wait,notify(),promise.finally(()=>{current===wait&&(current=void 0,notify())})}function currentUserWait(){return current?.reason}function onUserWaitChange(listener){return listeners.add(listener),()=>{listeners.delete(listener)}}var import_semver=__toESM(require_semver(),1);var DEFAULT_VERSION_CHECK_TIMEOUT_MS=1e4;function formatVersionCheckError(error){let rootMessage=error instanceof Error&&error.message?error.message:String(error),cause=error instanceof Error?error.cause:void 0,causes=cause instanceof AggregateError?cause.errors:cause===void 0?[]:[cause],codes=causes.map(value=>typeof value=="object"&&value!==null&&"code"in value&&typeof value.code=="string"?value.code:void 0).filter(code=>code!==void 0);if(codes.length>0)return`${rootMessage} (${[...new Set(codes)].
11
+ join(", ")})`;let causeMessage=causes.find(value=>value instanceof Error&&!!value.message)?.message;return causeMessage?`${rootMessage} (cause: ${causeMessage})`:rootMessage}function comparePackageVersions(leftVersion,rightVersion){let left=(0,import_semver.valid)(leftVersion.trim()),right=(0,import_semver.valid)(rightVersion.trim());if(!(!left||!right))return(0,import_semver.compare)(left,right)}function isNewerPackageVersion(candidateVersion,currentVersion){let comparison=comparePackageVersions(
12
+ candidateVersion,currentVersion);return comparison!==void 0?comparison>0:candidateVersion.trim()!==currentVersion.trim()}async function getLatestPiRelease(currentVersion,options={}){if(process.env[ENV_OFFLINE])return;let response=await fetchWithRetry(getVersionCheckUrl(),{headers:{"User-Agent":getPiUserAgent(currentVersion),accept:"application/json"}},{maxRetries:options.retry?2:0,timeoutMs:options.timeoutMs??DEFAULT_VERSION_CHECK_TIMEOUT_MS});if(!response.ok)return;let data=await response.json();
13
+ if(typeof data.version!="string"||!data.version.trim())return;let packageField=data.packageName??data.name,packageName=typeof packageField=="string"&&packageField.trim()?packageField.trim():void 0,note=typeof data.note=="string"&&data.note.trim()?data.note.trim():void 0;return{version:data.version.trim(),packageName,...note?{note}:{}}}async function checkForNewPiVersion(currentVersion){if(!process.env[ENV_SKIP_VERSION_CHECK])try{let latestRelease=await getLatestPiRelease(currentVersion);return latestRelease&&isNewerPackageVersion(latestRelease.version,currentVersion)?latestRelease:void 0}catch{return}}var SIGNAL_SHUTDOWN_GRACE_MS=1500;async function waitForSignalShutdown(shutdown){let timer;try{await Promise.race([shutdown,new Promise(resolve2=>{timer=setTimeout(resolve2,SIGNAL_SHUTDOWN_GRACE_MS)})])}finally{clearTimeout(timer)}}async function exitAfterSignalShutdown(shutdown,exitCode){try{await waitForSignalShutdown(shutdown)}finally{await killTrackedDetachedChildrenAsync(),process.exit(exitCode)}}import{basename,isAbsolute,relative,resolve,sep}from"node:path";function sanitizeStatusText(text){return text.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()}function formatTokens(count){return count<1e3?count.toString():count<1e4?`${(count/1e3).toFixed(1)}k`:count<1e6?`${Math.round(count/1e3)}k`:count<1e7?`${(count/1e6).toFixed(1)}M`:`${Math.round(count/1e6)}M`}function formatCwdForFooter(cwd,home){if(!home)return cwd;let resolvedCwd=resolve(cwd),resolvedHome=resolve(home),relativeToHome=relative(resolvedHome,resolvedCwd);return relativeToHome===""||relativeToHome!==
14
+ ".."&&!relativeToHome.startsWith(`..${sep}`)&&!isAbsolute(relativeToHome)?relativeToHome===""?"~":`~${sep}${relativeToHome}`:cwd}var FOOTER_VALUE_INPUTS=["width","theme","identity","effort","modelName","accountLabel","routedModelId","provider","age","contextPercent","contextWindow","usingSubscription","usageIncomplete","cost","input","output","cacheRead","cacheWrite","latestCacheHitRate","experimental"];var NO_EXTENSION_STATUSES=[];function sameFooterInputs(a,b){for(let key of FOOTER_VALUE_INPUTS)if(!Object.is(a[key],b[key]))return!1;let statuses=a.extensionStatuses;if(statuses.length!==b.extensionStatuses.length)return!1;for(let i=0;i<statuses.length;i++)if(statuses[i]!==b.extensionStatuses[i])return!1;return!0}var FooterComponent=class{lastEventAt;activitySessionId;activityTimer;session;footerData;sessionStats;rendered;constructor(session,footerData,requestRender){this.session=session,this.footerData=
15
+ footerData,this.activitySessionId=session.sessionManager.getSessionId(),this.refreshActivityFromSession(),requestRender&&this.startActivityTimer(requestRender)}setSession(session){let changed=this.session!==session||this.activitySessionId!==session.sessionManager.getSessionId();this.session=session,changed&&this.refreshActivityFromSession()}markActivity(){this.lastEventAt=performance.now()}refreshActivityFromSession(){this.activitySessionId=this.session.sessionManager.getSessionId(),this.lastEventAt=
16
+ void 0;let now=Date.now(),latest=0;for(let entry of this.session.sessionManager.getBranch()){if(entry.type!=="message"||entry.message.role!=="user"&&entry.message.role!=="assistant"&&entry.message.role!=="toolResult")continue;let timestamp=Date.parse(entry.timestamp);Number.isFinite(timestamp)&&timestamp>latest&&timestamp<=now&&(latest=timestamp)}latest>0&&(this.lastEventAt=performance.now()-(now-latest))}startActivityTimer(onTick){this.activityTimer||(this.activityTimer=setInterval(()=>{this.lastEventAt!==
17
+ void 0&&onTick()},1e3),this.activityTimer.unref())}invalidate(){}dispose(){this.activityTimer&&clearInterval(this.activityTimer),this.activityTimer=void 0}getSessionStats(){let sessionManager=this.session.sessionManager,entryCount=sessionManager.getEntryCount(),sessionId=sessionManager.getSessionId(),leafId=sessionManager.getLeafId(),limitsModel=this.session.routedModel?.model??this.session.model,cached=this.sessionStats;if(cached&&cached.session===this.session&&cached.sessionId===sessionId&&cached.
18
+ leafId===leafId&&cached.entryCount===entryCount&&cached.limitsModel===limitsModel)return cached;let usageTotals=createUsageTotals(),latestCacheHitRate,entries=sessionManager.getEntries();for(let{usage}of getSessionUsage(entries))addUsageToTotals(usageTotals,usage);for(let entry of entries)if(entry.type==="message"&&entry.message.role==="assistant"){let latestPromptTokens=entry.message.usage.input+entry.message.usage.cacheRead+entry.message.usage.cacheWrite;latestCacheHitRate=latestPromptTokens>0?
19
+ entry.message.usage.cacheRead/latestPromptTokens*100:void 0}let contextUsage=this.session.getContextUsage();return this.sessionStats={session:this.session,sessionId,leafId,entryCount,limitsModel,usageTotals,latestCacheHitRate,contextUsage},this.sessionStats}renderInputs(width){let state=this.session.state,{usageTotals,latestCacheHitRate,contextUsage}=this.getSessionStats(),routed=this.session.routedModel,pwd=basename(this.session.sessionManager.getCwd())||sep,branch=this.footerData.getGitBranch(),
20
+ sessionName=this.session.sessionManager.getSessionName(),effectiveModel=routed?.model??state.model,thinkingLevel=routed?.thinkingLevel??state.thinkingLevel??"off",elapsed=this.lastEventAt===void 0?void 0:Math.max(0,Math.floor((performance.now()-this.lastEventAt)/1e3)),accountLabel=state.model?this.footerData.getOAuthAccountLabel(state.model.provider):void 0,statuses=this.footerData.getExtensionStatuses();return{width,theme:getThemeInstance(),identity:[pwd,branch,sessionName].filter(Boolean).map(
21
+ text=>stripAnsi(sanitizeStatusText(text))).join(" \xB7 "),effort:this.session.autoEffortSelecting?"Choosing effort\u2026":effectiveModel?.reasoning&&thinkingLevel!=="off"?thinkingLevel[0].toUpperCase()+thinkingLevel.slice(1):"Thinking off",modelName:stripAnsi(sanitizeStatusText(state.model?.id??"no-model")),accountLabel:accountLabel?stripAnsi(sanitizeStatusText(accountLabel)):void 0,routedModelId:routed?stripAnsi(sanitizeStatusText(routed.model.id)):void 0,provider:this.footerData.getAvailableProviderCount()>
22
+ 1&&state.model?stripAnsi(sanitizeStatusText(state.model.provider)):void 0,age:elapsed===void 0?"\u2014":elapsed===0?"now":elapsed<60?`${elapsed}s ago`:elapsed<3600?`${Math.floor(elapsed/60)}m ago`:elapsed<86400?`${Math.floor(elapsed/3600)}h ago`:`${Math.floor(elapsed/86400)}d ago`,contextPercent:contextUsage?.percent??void 0,contextWindow:contextUsage?.contextWindow??routed?.model.contextWindow??state.model?.contextWindow??0,usingSubscription:state.model?this.session.modelRuntime.isUsingSubscription(
23
+ state.model.provider):!1,usageIncomplete:!!usageTotals.usageIncomplete,cost:usageTotals.cost,input:usageTotals.input,output:usageTotals.output,cacheRead:usageTotals.cacheRead,cacheWrite:usageTotals.cacheWrite,latestCacheHitRate,experimental:areExperimentalFeaturesEnabled(),extensionStatuses:statuses.size===0?NO_EXTENSION_STATUSES:Array.from(statuses.entries()).filter(([key])=>key!=="adhd"&&key!=="caveman"&&key!=="ponytail").sort(([a],[b])=>a.localeCompare(b)).map(([,text])=>sanitizeStatusText(text))}}render(width){
24
+ if(width<1)return[];let inputs=this.renderInputs(width),known=this.rendered;if(known&&sameFooterInputs(known.inputs,inputs))return known.lines.slice();let lines=this.renderLines(inputs);return this.rendered={inputs,lines:lines.slice()},lines}renderLines(inputs){let{width,contextPercent}=inputs,context=`Context ${contextPercent===void 0?"?":`${contextPercent.toFixed(1)}%`}/${formatTokens(inputs.contextWindow)}`,lines=[truncateToWidth(theme.fg("dim",inputs.identity),width,theme.fg("dim","..."))],{
25
+ effort,modelName}=inputs,model=modelName,modelFields=[theme.fg("accent",effort)],activity=theme.fg("dim",`Last event ${inputs.age}`);if(inputs.accountLabel){let withAccount=`${modelName} [${inputs.accountLabel}]`;visibleWidth(effort)+3+visibleWidth(withAccount)+2+visibleWidth(activity)<=width&&(model=withAccount)}if(modelFields.push(theme.fg("text",model)),inputs.routedModelId!==void 0&&modelFields.push(theme.fg("muted",`\u2192 ${inputs.routedModelId}`)),inputs.provider!==void 0){let provider=theme.
26
+ fg("dim",`(${inputs.provider})`);visibleWidth([...modelFields,provider].join(" \xB7 "))+2+visibleWidth(activity)<=width&&modelFields.push(provider)}lines.push(...this.renderBand(modelFields,activity,width));let contextColor=(contextPercent??0)>90?"error":(contextPercent??0)>70?"warning":"text",{usingSubscription}=inputs,statsParts=[theme.fg(contextColor,context)];inputs.usageIncomplete?statsParts.push(theme.fg("muted",`${inputs.cost>0?`\u2265$${inputs.cost.toFixed(3)}`:"Cost unknown"}${usingSubscription?
27
+ " (sub)":""} (usage incomplete)`)):(inputs.cost||usingSubscription)&&statsParts.push(theme.fg("muted",`$${inputs.cost.toFixed(3)}${usingSubscription?" (sub)":""}`)),statsParts.push(theme.fg("dim",`In ${formatTokens(inputs.input)}`),theme.fg("dim",`Out ${formatTokens(inputs.output)}`)),inputs.experimental&&statsParts.push(theme.bold(theme.fg("warning","xp"))),lines.push(...this.renderBand(statsParts,void 0,width));let cacheParts=[theme.fg("dim",`Cache read ${formatTokens(inputs.cacheRead)}`)];return inputs.
28
+ cacheWrite&&cacheParts.push(theme.fg("dim",`Cache write ${formatTokens(inputs.cacheWrite)}`)),cacheParts.push(theme.fg("dim",`Hit ${inputs.latestCacheHitRate===void 0?"\u2014":`${inputs.latestCacheHitRate.toFixed(1)}%`}`)),lines.push(...this.renderBand(cacheParts,theme.fg("dim","/settings"),width)),inputs.extensionStatuses.length&&lines.push(truncateToWidth(inputs.extensionStatuses.join(" "),width,theme.fg("dim","..."))),lines}renderBand(fields,right,width){let lines=[],line="";for(let field of fields)
29
+ if(line&&visibleWidth(`${line} \xB7 ${field}`)>width&&(lines.push(line),line=""),visibleWidth(field)>width){let wrapped=wrapTextWithAnsi(field,width);lines.push(...wrapped.slice(0,-1)),line=wrapped.at(-1)??""}else line=line?`${line} \xB7 ${field}`:field;if(right)if(line&&visibleWidth(line)+2+visibleWidth(right)<=width)line+=" ".repeat(width-visibleWidth(line)-visibleWidth(right))+right;else{line&&lines.push(line);let wrapped=wrapTextWithAnsi(right,width);lines.push(...wrapped.slice(0,-1)),line=wrapped.
30
+ at(-1)??""}return line&&lines.push(line),lines.map(rendered=>truncateToWidth(rendered,width,""))}};var ModelCatalogRefreshCoordinator=class{activeByRuntime=new WeakMap;refresh(modelRuntime,signal){signal.throwIfAborted();let active=this.activeByRuntime.get(modelRuntime);if(!active){let controller=new AbortController,created,operation=modelRuntime.refresh({signal:controller.signal}),promise=raceWithAbortSignal(operation,controller.signal).finally(()=>{this.activeByRuntime.get(modelRuntime)===created&&this.activeByRuntime.delete(modelRuntime)});created={controller,promise,waiters:0},active=created,
31
+ this.activeByRuntime.set(modelRuntime,active)}return active.waiters++,raceWithAbortSignal(active.promise,signal).finally(()=>{active.waiters--,active.waiters===0&&this.activeByRuntime.get(modelRuntime)===active&&active.controller.abort()})}},modelCatalogRefreshCoordinator=new ModelCatalogRefreshCoordinator;function refreshModelCatalogs(modelRuntime,signal){return modelCatalogRefreshCoordinator.refresh(modelRuntime,signal)}function refreshStartupModelCatalogs(modelRuntime,signal){return signal.throwIfAborted(),
32
+ raceWithAbortSignal(modelRuntime.refresh({providers:modelRuntime.getProviders().filter(provider=>provider.id!==HCODE_PROVIDER).map(provider=>provider.id),signal}),signal)}function formatSubscriptionCredits(credits){if(credits?.unlimited===!0)return"unlimited";if(credits?.hasCredits===!1)return"none";let balance=parseSubscriptionCreditAmount(credits?.balance);if(balance===void 0||credits?.unit===void 0)return"unavailable";if(Number(balance)===0)return"none";let[integer,fraction]=balance.split("."),amount=`${Number(integer).toLocaleString("en-US")}${fraction===void 0?"":`.${fraction}`}`;return credits.unit==="USD"?`$${amount}`:`${amount} credits`}function formatSubscriptionAccountSummary(result){
33
+ let weekly=formatOAuthAccountUsage({kind:"unavailable",...result?.status==="unavailable"?{reason:result.reason}:{}});if(result?.status!=="ok")return`${weekly}, saved resets: unavailable, paid credits: unavailable`;if("fetchedAt"in result){let window=result.windows.find(window2=>window2.id==="seven_day");window&&(weekly=`weekly: ${Math.round(100-window.usedPercent)}% left`,window.resetsAt!==void 0&&(weekly+=`, resets ${formatOAuthAccountResetTime(window.resetsAt)}`))}else result.usage&&(weekly=formatOAuthAccountUsage(
34
+ {kind:"available",...result.usage}));let count=result.resets?.availableCount,resets=count===void 0?"unavailable":count===0?"none":String(count),enabled=result.credits?.enabled;return`${weekly}, saved resets: ${resets}, paid credits: ${formatSubscriptionCredits(result.credits)}${enabled===void 0?"":`, extra usage: ${enabled?"enabled":"disabled"}`}`}function formatOAuthAccountResetTime(epochMs){let date=new Date(epochMs),time=`${String(date.getHours()).padStart(2,"0")}:${String(date.getMinutes()).
35
+ padStart(2,"0")}`;return date.toDateString()===new Date().toDateString()?time:`${time} on ${date.toLocaleDateString()}`}function formatOAuthAccountUsage(usage){switch(usage.kind){case"none":return"";case"loading":return"weekly usage: loading\u2026";case"subscription":return formatSubscriptionAccountSummary(usage.result);case"unavailable":return usage.reason==="expired_credential"?"weekly usage: unavailable (sign-in expired)":"weekly usage: unavailable";case"available":{let remaining=`weekly: ${Math.
36
+ round(usage.remainingPercent)}% left, provider: ${getCodexAvailability(usage)}`;return usage.resetsAt!==void 0?`${remaining}, resets ${formatOAuthAccountResetTime(usage.resetsAt)}`:remaining}}}function formatOAuthAccountOption(label,usage){let usageText=formatOAuthAccountUsage(usage);return usageText?`${label} (${usageText})`:label}var AuthCommandError=class extends Error{},AUTH_COMMAND_USAGE={check:`${APP_COMMAND} auth check --provider <provider> [--json] [--credentials] [--no-refresh]`,api_key:`${APP_COMMAND} auth print-api-key --provider <provider> [--model <model>]`,bearer_token:`${APP_COMMAND} auth print-bearer-token --provider <provider> [--model <model>] [--min-expiry <duration>]`};function getAuthCommandName(kind){return kind==="check"?"auth check":kind==="api_key"?"auth print-api-key":"auth print-bearer-token"}function getAuthCommandUsage(kind){
37
+ return AUTH_COMMAND_USAGE[kind]}function isAuthCommandHelp(args){return args[0]==="auth"&&(args[1]===void 0||args[1]==="help"||args.includes("--help")||args.includes("-h"))}function printAuthCommandHelp(){console.log(`Usage:
38
+ ${APP_COMMAND} auth print-api-key [--provider <provider>] [--model <model>]
39
+ ${APP_COMMAND} auth print-bearer-token [--provider <provider>] [--model <model>] [--min-expiry <duration>]
40
+ ${APP_COMMAND} auth check [--provider <provider>] [--model <model>] [--json] [--credentials] [--no-refresh]
41
+
42
+ Auth commands require at least one of --provider or --model. Checks refresh expired OAuth credentials by default; --no-refresh prevents this. --credentials emits the credential, or includes it in JSON output.`)}function parseAuthCommand(args){if(args[0]!=="auth")return;let kind=args[1]==="check"?"check":args[1]==="print-api-key"?"api_key":args[1]==="print-bearer-token"?"bearer_token":void 0;if(!kind)throw new AuthCommandError(`Unknown auth command "${args[1]??""}". Use "${APP_COMMAND} auth print\
43
+ -api-key", "${APP_COMMAND} auth print-bearer-token", or "${APP_COMMAND} auth check".`);let commandArgs=[],json=!1,credentials=!1,noRefresh=!1,minExpiryMs;for(let index=2;index<args.length;index++){let arg=args[index];if(arg==="--min-expiry"){if(kind!=="bearer_token")throw new AuthCommandError("--min-expiry is only supported by print-bearer-token");let value=args[++index],match=value?/^(\d+)(ms|s|m|h)$/iu.exec(value):void 0;if(!match)throw new AuthCommandError("--min-expiry must use a duration su\
44
+ ch as 30m or 1h");let amount=Number(match[1]),unit=match[2];minExpiryMs=amount*(unit==="ms"?1:unit==="s"?1e3:unit==="m"?6e4:36e5);continue}if(arg==="--json"||arg==="--credentials"||arg==="--no-refresh"){if(kind!=="check")throw new AuthCommandError(`${arg} is only supported by auth check`);arg==="--json"?json=!0:arg==="--credentials"?credentials=!0:noRefresh=!0;continue}commandArgs.push(arg)}return minExpiryMs===void 0?{kind,args:commandArgs,json,credentials,noRefresh}:{kind,args:commandArgs,json,
45
+ credentials,noRefresh,minExpiryMs}}function validateAuthCommandArgs(args,kind){let provider=args.provider?.trim()||void 0,model=args.model?.trim()||void 0;if(args.unknownFlags.size>0){let option=args.unknownFlags.keys().next().value;throw new AuthCommandError(`Unknown option --${option} for "${getAuthCommandName(kind)}".`)}if(args.apiKey!==void 0||args.messages.length>0||args.fileArgs.length>0)throw new AuthCommandError("Auth commands only accept --provider and --model");if(kind==="check"){if(!provider&&
46
+ !model)throw new AuthCommandError("Auth checks require --provider <provider> or --model <model>");return{provider,model}}if(!provider&&!model)throw new AuthCommandError("Credential printing requires --provider <provider> or --model <model>");return{provider,model}}function getAuthCredential(auth){if(auth?.auth.apiKey)return auth.auth.apiKey;let authorization=Object.entries(auth?.auth.headers??{}).find(([name])=>name.toLowerCase()==="authorization")?.[1];return typeof authorization=="string"?/^Bearer\s+(.+)$/iu.
47
+ exec(authorization)?.[1]:void 0}var AuthUrlComponent=class extends Container{url;tui;hint;constructor(tui,url){super(),this.tui=tui,this.url=url,this.addChild(new Text(theme.fg("accent",hyperlink(url,url)),1,0)),this.hint=new Text("",1,0),this.addChild(this.hint),this.setHint(keyHint("app.message.copy","to copy"))}setHint(suffix){let clickHint=process.platform==="darwin"?"Cmd+click to open":"Ctrl+click to open";this.hint.setText(`${theme.fg("dim",hyperlink(clickHint,this.url))} ${theme.fg("dim","\u2022")} ${suffix}`),this.tui.
48
+ requestRender()}async copy(){try{await copyToClipboard(this.url),this.setHint(theme.fg("success","Copied URL to clipboard"))}catch(error){this.setHint(theme.fg("error",error instanceof Error?error.message:String(error)))}}};var HCODE_PENDING_EXPLANATION="Pending usage is awaiting provider confirmation. It remains reserved until confirmed or reviewed by an admin. It is not a final charge and is not free usage.",HCODE_AMBIGUOUS_NOTICE="HUMAIN Code couldn't confirm this request's outcome. It may still be charged. No automatic retry was sent. Check /usage before trying again.";function formatHcodeReset(resetAt){return`Resets ${new Date(resetAt).toISOString().slice(0,16).replace("T"," ")} UTC`}function formatHcodeNotice(failure,receivedAt){
49
+ let error=failure.error;if(error.code==="hcode_busy")return{message:error.message,lines:[`Retry after ${new Date(receivedAt+error.details.retryAfterMs).toISOString().slice(0,19).replace("T"," ")} UTC.`,"No request was dispatched. No automatic retry was sent."],retryAfterMs:error.details.retryAfterMs};if(error.code==="quota_exceeded"){let usage=error.details.usage,money=value=>value.kind==="known"?`${value.value} ${usage.currency} ${usage.unit}${value.value===1?"":"s"}`:value.kind;return{message:error.
50
+ message,lines:[`Used${usage.costComplete?"":" (known subtotal)"} ${money(usage.actual)}`,`Pending ${money(usage.reserved)}`,`Remaining ${money(usage.remaining)}`,formatHcodeReset(usage.period.resetAt),"No request was dispatched. No automatic retry was sent."]}}let recovery=error.code==="unauthorized"?"Sign in again with /login.":error.code==="legal_acknowledgment_required"?"Accept terms in the web app, then try again.":error.code==="model_unavailable"?"Choose an available model with /model.":void 0;
51
+ return{message:error.message,lines:recovery?[recovery,"No automatic retry was sent."]:[HCODE_AMBIGUOUS_NOTICE]}}function formatHcodeMessageNotice(message){if(message.provider===HCODE_PROVIDER){if(message.stopReason==="error"){let diagnostic=message.diagnostics?.findLast(entry=>entry.type==="provider_http_error"),refusal=diagnostic?.details?.hcode;if(refusal&&typeof refusal=="object"&&"error"in refusal)try{let notice=formatHcodeNotice(parseHcodeInferenceError({error:refusal.error}),diagnostic.timestamp);
52
+ return[notice.message,...notice.lines].join(`
53
+ `)}catch{}}return HCODE_AMBIGUOUS_NOTICE}}export{AuthCommandError,getAuthCommandName,getAuthCommandUsage,isAuthCommandHelp,printAuthCommandHelp,parseAuthCommand,validateAuthCommandArgs,getAuthCredential,runClipboardCommand,readClipboardText,readClipboardFilePaths,copyToClipboard,AuthUrlComponent,trackUserWait,currentUserWait,onUserWaitChange,formatVersionCheckError,isNewerPackageVersion,getLatestPiRelease,checkForNewPiVersion,waitForSignalShutdown,exitAfterSignalShutdown,HCODE_PENDING_EXPLANATION,formatHcodeReset,formatHcodeMessageNotice,
54
+ formatTokens,formatCwdForFooter,FooterComponent,refreshModelCatalogs,refreshStartupModelCatalogs,formatSubscriptionCredits,formatOAuthAccountResetTime,formatOAuthAccountOption};