@humain/terminal 0.0.17 → 0.1.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 (367) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/dist/bun/cli.d.ts +3 -1
  3. package/dist/bun/cli.d.ts.map +1 -1
  4. package/dist/bun/cli.js +3 -8
  5. package/dist/bun/cli.js.map +1 -1
  6. package/dist/bun/runtime-setup.d.ts +2 -0
  7. package/dist/bun/runtime-setup.d.ts.map +1 -0
  8. package/dist/bun/runtime-setup.js +9 -0
  9. package/dist/bun/runtime-setup.js.map +1 -0
  10. package/dist/bun/sandbox-env-setup.d.ts +2 -0
  11. package/dist/bun/sandbox-env-setup.d.ts.map +1 -0
  12. package/dist/bun/sandbox-env-setup.js +4 -0
  13. package/dist/bun/sandbox-env-setup.js.map +1 -0
  14. package/dist/bundle/chunks/anthropic-messages-XULXUBIG.js +6 -0
  15. package/dist/bundle/chunks/{azure-openai-responses-ZN52D6YC.js → azure-openai-responses-JEG2XOYC.js} +1 -1
  16. package/dist/bundle/chunks/bedrock-converse-stream.js +6 -6
  17. package/dist/bundle/chunks/{chunk-ARF4OE6X.js → chunk-2LC3S3VV.js} +8 -8
  18. package/dist/bundle/chunks/chunk-43O5DDAH.js +31 -0
  19. package/dist/bundle/chunks/{chunk-H2O6VOXT.js → chunk-46DC2JD6.js} +2 -2
  20. package/dist/bundle/chunks/chunk-7ZC4UXSL.js +2 -0
  21. package/dist/bundle/chunks/{chunk-WJZ4KLGL.js → chunk-E6KP6V7F.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-PSKDLDLZ.js → chunk-HPPQHK3J.js} +3 -3
  23. package/dist/bundle/chunks/chunk-JUPSJTFQ.js +42 -0
  24. package/dist/bundle/chunks/chunk-PL7O7J4J.js +133 -0
  25. package/dist/bundle/chunks/{chunk-PFVS5ZYL.js → chunk-RM336IEI.js} +378 -369
  26. package/dist/bundle/chunks/chunk-USJZMAIR.js +2 -0
  27. package/dist/bundle/chunks/{extract-2L7ZVN7F.js → extract-TRW5FBY6.js} +2 -2
  28. package/dist/bundle/chunks/github-copilot.js +1 -1
  29. package/dist/bundle/chunks/{google-generative-ai-FF7M7XHT.js → google-generative-ai-OX6VSCA6.js} +1 -1
  30. package/dist/bundle/chunks/{google-vertex-YMUBFRBA.js → google-vertex-GW76GSS2.js} +1 -1
  31. package/dist/bundle/chunks/image-resize-worker.js +1 -1
  32. package/dist/bundle/chunks/{mistral-conversations-O4M7IQML.js → mistral-conversations-WXGXZOFJ.js} +1 -1
  33. package/dist/bundle/chunks/node-AUOGOBCN.js +2 -0
  34. package/dist/bundle/chunks/node-KOIP55YZ.js +16 -0
  35. package/dist/bundle/chunks/openai-codex-responses-NPLWP6ZC.js +10 -0
  36. package/dist/bundle/chunks/{openai-completions-L4AHDQ5D.js → openai-completions-OT2GTJKC.js} +3 -3
  37. package/dist/bundle/chunks/openai-responses-5A6CR7GI.js +2 -0
  38. package/dist/bundle/chunks/{openrouter-images-Y2PCWAQH.js → openrouter-images-YLQ4RJ2F.js} +1 -1
  39. package/dist/bundle/chunks/{pi-messages-57K43J6J.js → pi-messages-OJF77SY3.js} +1 -1
  40. package/dist/bundle/chunks/{undici-D6ABF53Q.js → undici-KA2LJNVT.js} +1 -1
  41. package/dist/bundle/chunks/webapi-RFAXLI2D.js +5 -0
  42. package/dist/bundle/cli.js +1 -1
  43. package/dist/bundle/index.js +1 -1
  44. package/dist/bundle/rpc-entry.js +1 -1
  45. package/dist/cli/config-selector.d.ts.map +1 -1
  46. package/dist/cli/config-selector.js +2 -1
  47. package/dist/cli/config-selector.js.map +1 -1
  48. package/dist/cli/setup.d.ts +2 -0
  49. package/dist/cli/setup.d.ts.map +1 -0
  50. package/dist/cli/setup.js +13 -0
  51. package/dist/cli/setup.js.map +1 -0
  52. package/dist/cli.js +2 -14
  53. package/dist/cli.js.map +1 -1
  54. package/dist/config.d.ts +1 -0
  55. package/dist/config.d.ts.map +1 -1
  56. package/dist/config.js +1 -0
  57. package/dist/config.js.map +1 -1
  58. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  59. package/dist/core/agent-session-runtime.js +15 -7
  60. package/dist/core/agent-session-runtime.js.map +1 -1
  61. package/dist/core/agent-session.d.ts +2 -6
  62. package/dist/core/agent-session.d.ts.map +1 -1
  63. package/dist/core/agent-session.js +14 -6
  64. package/dist/core/agent-session.js.map +1 -1
  65. package/dist/core/compaction/branch-summarization.d.ts +1 -1
  66. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  67. package/dist/core/compaction/branch-summarization.js +2 -1
  68. package/dist/core/compaction/branch-summarization.js.map +1 -1
  69. package/dist/core/extensions/loader.d.ts.map +1 -1
  70. package/dist/core/extensions/loader.js +1 -2
  71. package/dist/core/extensions/loader.js.map +1 -1
  72. package/dist/core/extensions/types.d.ts +8 -2
  73. package/dist/core/extensions/types.d.ts.map +1 -1
  74. package/dist/core/extensions/types.js.map +1 -1
  75. package/dist/core/http-dispatcher.d.ts.map +1 -1
  76. package/dist/core/http-dispatcher.js +2 -0
  77. package/dist/core/http-dispatcher.js.map +1 -1
  78. package/dist/core/keybindings.d.ts +5 -0
  79. package/dist/core/keybindings.d.ts.map +1 -1
  80. package/dist/core/keybindings.js +4 -0
  81. package/dist/core/keybindings.js.map +1 -1
  82. package/dist/core/messages.d.ts +1 -1
  83. package/dist/core/messages.d.ts.map +1 -1
  84. package/dist/core/messages.js.map +1 -1
  85. package/dist/core/model-config.d.ts +15 -0
  86. package/dist/core/model-config.d.ts.map +1 -1
  87. package/dist/core/model-config.js +3 -0
  88. package/dist/core/model-config.js.map +1 -1
  89. package/dist/core/model-runtime.d.ts +1 -0
  90. package/dist/core/model-runtime.d.ts.map +1 -1
  91. package/dist/core/model-runtime.js +5 -2
  92. package/dist/core/model-runtime.js.map +1 -1
  93. package/dist/core/provider-composer.d.ts.map +1 -1
  94. package/dist/core/provider-composer.js +8 -2
  95. package/dist/core/provider-composer.js.map +1 -1
  96. package/dist/core/session-manager.d.ts +3 -2
  97. package/dist/core/session-manager.d.ts.map +1 -1
  98. package/dist/core/session-manager.js +40 -13
  99. package/dist/core/session-manager.js.map +1 -1
  100. package/dist/core/settings-manager.js.map +1 -1
  101. package/dist/core/skills.d.ts +1 -1
  102. package/dist/core/skills.d.ts.map +1 -1
  103. package/dist/core/skills.js +4 -2
  104. package/dist/core/skills.js.map +1 -1
  105. package/dist/core/system-prompt.d.ts.map +1 -1
  106. package/dist/core/system-prompt.js +8 -9
  107. package/dist/core/system-prompt.js.map +1 -1
  108. package/dist/core/tools/bash.d.ts.map +1 -1
  109. package/dist/core/tools/bash.js +3 -120
  110. package/dist/core/tools/bash.js.map +1 -1
  111. package/dist/core/tools/edit.d.ts +1 -12
  112. package/dist/core/tools/edit.d.ts.map +1 -1
  113. package/dist/core/tools/edit.js +5 -163
  114. package/dist/core/tools/edit.js.map +1 -1
  115. package/dist/core/tools/find.d.ts.map +1 -1
  116. package/dist/core/tools/find.js +4 -55
  117. package/dist/core/tools/find.js.map +1 -1
  118. package/dist/core/tools/grep.d.ts.map +1 -1
  119. package/dist/core/tools/grep.js +4 -60
  120. package/dist/core/tools/grep.js.map +1 -1
  121. package/dist/core/tools/ls.d.ts.map +1 -1
  122. package/dist/core/tools/ls.js +4 -49
  123. package/dist/core/tools/ls.js.map +1 -1
  124. package/dist/core/tools/read.d.ts.map +1 -1
  125. package/dist/core/tools/read.js +4 -120
  126. package/dist/core/tools/read.js.map +1 -1
  127. package/dist/core/tools/renderers/bash.d.ts +12 -0
  128. package/dist/core/tools/renderers/bash.d.ts.map +1 -0
  129. package/dist/core/tools/renderers/bash.js +133 -0
  130. package/dist/core/tools/renderers/bash.js.map +1 -0
  131. package/dist/core/tools/renderers/edit.d.ts +23 -0
  132. package/dist/core/tools/renderers/edit.d.ts.map +1 -0
  133. package/dist/core/tools/renderers/edit.js +167 -0
  134. package/dist/core/tools/renderers/edit.js.map +1 -0
  135. package/dist/core/tools/renderers/find.d.ts +10 -0
  136. package/dist/core/tools/renderers/find.d.ts.map +1 -0
  137. package/dist/core/tools/renderers/find.js +64 -0
  138. package/dist/core/tools/renderers/find.js.map +1 -0
  139. package/dist/core/tools/renderers/grep.d.ts +10 -0
  140. package/dist/core/tools/renderers/grep.d.ts.map +1 -0
  141. package/dist/core/tools/renderers/grep.js +69 -0
  142. package/dist/core/tools/renderers/grep.js.map +1 -0
  143. package/dist/core/tools/renderers/index.d.ts +22 -0
  144. package/dist/core/tools/renderers/index.d.ts.map +1 -0
  145. package/dist/core/tools/renderers/index.js +48 -0
  146. package/dist/core/tools/renderers/index.js.map +1 -0
  147. package/dist/core/tools/renderers/ls.d.ts +10 -0
  148. package/dist/core/tools/renderers/ls.d.ts.map +1 -0
  149. package/dist/core/tools/renderers/ls.js +58 -0
  150. package/dist/core/tools/renderers/ls.js.map +1 -0
  151. package/dist/core/tools/renderers/read.d.ts +11 -0
  152. package/dist/core/tools/renderers/read.d.ts.map +1 -0
  153. package/dist/core/tools/renderers/read.js +129 -0
  154. package/dist/core/tools/renderers/read.js.map +1 -0
  155. package/dist/core/tools/renderers/write.d.ts +10 -0
  156. package/dist/core/tools/renderers/write.d.ts.map +1 -0
  157. package/dist/core/tools/renderers/write.js +152 -0
  158. package/dist/core/tools/renderers/write.js.map +1 -0
  159. package/dist/core/tools/subagent-worktree.d.ts +1 -0
  160. package/dist/core/tools/subagent-worktree.d.ts.map +1 -1
  161. package/dist/core/tools/subagent-worktree.js +25 -1
  162. package/dist/core/tools/subagent-worktree.js.map +1 -1
  163. package/dist/core/tools/subagent.d.ts.map +1 -1
  164. package/dist/core/tools/subagent.js +5 -2
  165. package/dist/core/tools/subagent.js.map +1 -1
  166. package/dist/core/tools/write.d.ts.map +1 -1
  167. package/dist/core/tools/write.js +5 -145
  168. package/dist/core/tools/write.js.map +1 -1
  169. package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +51 -12
  170. package/dist/humain/mcp-adapter/vendor/package.json +2 -2
  171. package/dist/humain/web-access/vendor/curator-page.d.ts.map +1 -1
  172. package/dist/humain/web-access/vendor/curator-page.js +3 -1
  173. package/dist/humain/web-access/vendor/curator-page.js.map +1 -1
  174. package/dist/humain/web-access/vendor/curator-server.d.ts +2 -0
  175. package/dist/humain/web-access/vendor/curator-server.d.ts.map +1 -1
  176. package/dist/humain/web-access/vendor/curator-server.js +4 -2
  177. package/dist/humain/web-access/vendor/curator-server.js.map +1 -1
  178. package/dist/humain/web-access/vendor/gemini-search.d.ts +2 -2
  179. package/dist/humain/web-access/vendor/gemini-search.d.ts.map +1 -1
  180. package/dist/humain/web-access/vendor/gemini-search.js +11 -4
  181. package/dist/humain/web-access/vendor/gemini-search.js.map +1 -1
  182. package/dist/humain/web-access/vendor/github-extract.d.ts.map +1 -1
  183. package/dist/humain/web-access/vendor/github-extract.js +238 -1
  184. package/dist/humain/web-access/vendor/github-extract.js.map +1 -1
  185. package/dist/humain/web-access/vendor/index.d.ts.map +1 -1
  186. package/dist/humain/web-access/vendor/index.js +118 -64
  187. package/dist/humain/web-access/vendor/index.js.map +1 -1
  188. package/dist/humain/web-access/vendor/mistral-search.d.ts +4 -0
  189. package/dist/humain/web-access/vendor/mistral-search.d.ts.map +1 -0
  190. package/dist/humain/web-access/vendor/mistral-search.js +274 -0
  191. package/dist/humain/web-access/vendor/mistral-search.js.map +1 -0
  192. package/dist/humain/web-access/vendor/perplexity.d.ts.map +1 -1
  193. package/dist/humain/web-access/vendor/perplexity.js +12 -1
  194. package/dist/humain/web-access/vendor/perplexity.js.map +1 -1
  195. package/dist/humain/web-access/vendor/utils.d.ts.map +1 -1
  196. package/dist/humain/web-access/vendor/utils.js +1 -2
  197. package/dist/humain/web-access/vendor/utils.js.map +1 -1
  198. package/dist/humain/web-access/vendor/xai-search.d.ts.map +1 -1
  199. package/dist/humain/web-access/vendor/xai-search.js +92 -35
  200. package/dist/humain/web-access/vendor/xai-search.js.map +1 -1
  201. package/dist/index.d.ts +1 -1
  202. package/dist/index.d.ts.map +1 -1
  203. package/dist/index.js.map +1 -1
  204. package/dist/main.d.ts.map +1 -1
  205. package/dist/main.js +4 -1
  206. package/dist/main.js.map +1 -1
  207. package/dist/modes/interactive/chat-viewport.d.ts +20 -0
  208. package/dist/modes/interactive/chat-viewport.d.ts.map +1 -0
  209. package/dist/modes/interactive/chat-viewport.js +28 -0
  210. package/dist/modes/interactive/chat-viewport.js.map +1 -0
  211. package/dist/modes/interactive/components/assistant-message.d.ts +1 -0
  212. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  213. package/dist/modes/interactive/components/assistant-message.js +18 -10
  214. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  215. package/dist/modes/interactive/components/custom-editor.d.ts +10 -1
  216. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  217. package/dist/modes/interactive/components/custom-editor.js +37 -1
  218. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  219. package/dist/modes/interactive/components/index.d.ts +1 -1
  220. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  221. package/dist/modes/interactive/components/index.js.map +1 -1
  222. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  223. package/dist/modes/interactive/components/model-selector.js +8 -17
  224. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  225. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  226. package/dist/modes/interactive/components/scoped-models-selector.js +21 -23
  227. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  228. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  229. package/dist/modes/interactive/components/settings-selector.js +14 -10
  230. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  231. package/dist/modes/interactive/components/status-indicator.d.ts +3 -1
  232. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  233. package/dist/modes/interactive/components/status-indicator.js +10 -3
  234. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  235. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  236. package/dist/modes/interactive/components/thinking-selector.js +4 -4
  237. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  238. package/dist/modes/interactive/components/tool-execution.d.ts +21 -4
  239. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  240. package/dist/modes/interactive/components/tool-execution.js +34 -32
  241. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  242. package/dist/modes/interactive/components/trust-selector.js +2 -2
  243. package/dist/modes/interactive/components/trust-selector.js.map +1 -1
  244. package/dist/modes/interactive/interactive-mode.d.ts +8 -15
  245. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  246. package/dist/modes/interactive/interactive-mode.js +96 -81
  247. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  248. package/dist/modes/interactive/session-share.d.ts.map +1 -1
  249. package/dist/modes/interactive/session-share.js +8 -12
  250. package/dist/modes/interactive/session-share.js.map +1 -1
  251. package/dist/modes/interactive/theme/dark.json +2 -1
  252. package/dist/modes/interactive/theme/light.json +2 -1
  253. package/dist/modes/interactive/theme/theme-controller.d.ts +1 -0
  254. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -1
  255. package/dist/modes/interactive/theme/theme-controller.js +5 -0
  256. package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
  257. package/dist/modes/interactive/theme/theme-json.d.ts +84 -0
  258. package/dist/modes/interactive/theme/theme-json.d.ts.map +1 -0
  259. package/dist/modes/interactive/theme/theme-json.js +130 -0
  260. package/dist/modes/interactive/theme/theme-json.js.map +1 -0
  261. package/dist/modes/interactive/theme/theme-schema.json +6 -2
  262. package/dist/modes/interactive/theme/theme.d.ts +14 -5
  263. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  264. package/dist/modes/interactive/theme/theme.js +18 -119
  265. package/dist/modes/interactive/theme/theme.js.map +1 -1
  266. package/dist/modes/interactive/tui-renderer.d.ts +21 -0
  267. package/dist/modes/interactive/tui-renderer.d.ts.map +1 -0
  268. package/dist/modes/interactive/tui-renderer.js +66 -0
  269. package/dist/modes/interactive/tui-renderer.js.map +1 -0
  270. package/dist/utils/exif-orientation.d.ts.map +1 -1
  271. package/dist/utils/exif-orientation.js +2 -3
  272. package/dist/utils/exif-orientation.js.map +1 -1
  273. package/dist/utils/tools-manager.d.ts +1 -0
  274. package/dist/utils/tools-manager.d.ts.map +1 -1
  275. package/dist/utils/tools-manager.js +41 -19
  276. package/dist/utils/tools-manager.js.map +1 -1
  277. package/docs/containerization.md +45 -0
  278. package/docs/development.md +19 -0
  279. package/docs/environment-variables.md +2 -0
  280. package/docs/extensions.md +5 -2
  281. package/docs/keybindings.md +5 -2
  282. package/docs/models.md +4 -1
  283. package/docs/rpc.md +1 -1
  284. package/docs/sdk.md +5 -0
  285. package/docs/settings.md +3 -3
  286. package/docs/skills.md +1 -1
  287. package/docs/terminal-setup.md +15 -0
  288. package/docs/themes.md +8 -6
  289. package/docs/tui.md +19 -0
  290. package/examples/README.md +3 -0
  291. package/examples/extensions/custom-provider-anthropic/package-lock.json +84 -84
  292. package/examples/extensions/custom-provider-anthropic/package.json +17 -17
  293. package/examples/extensions/custom-provider-gitlab-duo/package.json +14 -14
  294. package/examples/extensions/dynamic-resources/dynamic.json +2 -0
  295. package/examples/extensions/gondolin/package-lock.json +8 -8
  296. package/examples/extensions/gondolin/package.json +1 -1
  297. package/examples/extensions/sandbox/package-lock.json +6 -6
  298. package/examples/extensions/sandbox/package.json +2 -2
  299. package/examples/extensions/with-deps/package-lock.json +29 -29
  300. package/examples/extensions/with-deps/package.json +20 -20
  301. package/examples/plugins/pi-example-plugin/README.md +38 -0
  302. package/examples/plugins/pi-example-plugin/package.json +10 -0
  303. package/examples/plugins/pi-example-plugin/src/contract.ts +13 -0
  304. package/examples/plugins/pi-example-plugin/src/session.ts +23 -0
  305. package/examples/plugins/pi-example-plugin/src/tui.ts +31 -0
  306. package/npm-shrinkwrap.json +772 -205
  307. package/package.json +31 -24
  308. package/src/humain/web-access/UPSTREAM.md +12 -1
  309. package/src/humain/web-access/upstream.json +4 -4
  310. package/dist/bundle/chunks/anthropic-messages-M4LCS3KH.js +0 -6
  311. package/dist/bundle/chunks/chunk-3VI4HD7D.js +0 -31
  312. package/dist/bundle/chunks/chunk-BOW22LW6.js +0 -42
  313. package/dist/bundle/chunks/chunk-CBHC6EL7.js +0 -133
  314. package/dist/bundle/chunks/chunk-JUUC5AZY.js +0 -2
  315. package/dist/bundle/chunks/node-ZHY4LHC7.js +0 -15
  316. package/dist/bundle/chunks/openai-codex-responses-HRVCDY54.js +0 -8
  317. package/dist/bundle/chunks/openai-responses-4MWLJHIK.js +0 -2
  318. package/dist/bundle/chunks/webapi-AFS5FDJJ.js +0 -5
  319. package/dist/bundle/client.js +0 -2
  320. package/dist/cli/experimental/auth.d.ts +0 -16
  321. package/dist/cli/experimental/auth.d.ts.map +0 -1
  322. package/dist/cli/experimental/auth.js +0 -13
  323. package/dist/cli/experimental/auth.js.map +0 -1
  324. package/dist/cli/experimental/cli.d.ts +0 -6
  325. package/dist/cli/experimental/cli.d.ts.map +0 -1
  326. package/dist/cli/experimental/cli.js +0 -5
  327. package/dist/cli/experimental/cli.js.map +0 -1
  328. package/dist/cli/experimental/command-options.d.ts +0 -17
  329. package/dist/cli/experimental/command-options.d.ts.map +0 -1
  330. package/dist/cli/experimental/command-options.js +0 -35
  331. package/dist/cli/experimental/command-options.js.map +0 -1
  332. package/dist/cli/experimental/command.d.ts +0 -63
  333. package/dist/cli/experimental/command.d.ts.map +0 -1
  334. package/dist/cli/experimental/command.js +0 -127
  335. package/dist/cli/experimental/command.js.map +0 -1
  336. package/dist/cli/experimental/commands/client.d.ts +0 -13
  337. package/dist/cli/experimental/commands/client.d.ts.map +0 -1
  338. package/dist/cli/experimental/commands/client.js +0 -25
  339. package/dist/cli/experimental/commands/client.js.map +0 -1
  340. package/dist/cli/experimental/commands/pi.d.ts +0 -15
  341. package/dist/cli/experimental/commands/pi.d.ts.map +0 -1
  342. package/dist/cli/experimental/commands/pi.js +0 -28
  343. package/dist/cli/experimental/commands/pi.js.map +0 -1
  344. package/dist/cli/experimental/commands/server.d.ts +0 -13
  345. package/dist/cli/experimental/commands/server.d.ts.map +0 -1
  346. package/dist/cli/experimental/commands/server.js +0 -25
  347. package/dist/cli/experimental/commands/server.js.map +0 -1
  348. package/dist/cli/experimental/transport-address.d.ts +0 -10
  349. package/dist/cli/experimental/transport-address.d.ts.map +0 -1
  350. package/dist/cli/experimental/transport-address.js +0 -38
  351. package/dist/cli/experimental/transport-address.js.map +0 -1
  352. package/dist/client/index.d.ts +0 -3
  353. package/dist/client/index.d.ts.map +0 -1
  354. package/dist/client/index.js +0 -3
  355. package/dist/client/index.js.map +0 -1
  356. package/dist/client/remote-session.d.ts +0 -53
  357. package/dist/client/remote-session.d.ts.map +0 -1
  358. package/dist/client/remote-session.js +0 -340
  359. package/dist/client/remote-session.js.map +0 -1
  360. package/dist/client/transcript.d.ts +0 -12
  361. package/dist/client/transcript.d.ts.map +0 -1
  362. package/dist/client/transcript.js +0 -98
  363. package/dist/client/transcript.js.map +0 -1
  364. package/dist/server/create-harness.d.ts +0 -26
  365. package/dist/server/create-harness.d.ts.map +0 -1
  366. package/dist/server/create-harness.js +0 -106
  367. package/dist/server/create-harness.js.map +0 -1
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{parentPort}from"node:worker_threads";function readOrientationFromTiff(bytes,tiffStart){if(tiffStart+8>bytes.length)return 1;let le=(bytes[tiffStart]<<8|bytes[tiffStart+1])===18761,read16=pos=>le?bytes[pos]|bytes[pos+1]<<8:bytes[pos]<<8|bytes[pos+1],ifdOffset=(pos=>le?bytes[pos]|bytes[pos+1]<<8|bytes[pos+2]<<16|bytes[pos+3]<<24:(bytes[pos]<<24|bytes[pos+1]<<16|bytes[pos+2]<<8|bytes[pos+3])>>>0)(tiffStart+4),ifdStart=tiffStart+ifdOffset;if(ifdStart+2>bytes.length)return 1;let entryCount=read16(ifdStart);for(let i=0;i<entryCount;i++){let entryPos=ifdStart+2+i*12;if(entryPos+12>bytes.length)return 1;if(read16(entryPos)===274){let value=read16(entryPos+8);return value>=1&&value<=8?value:1}}return 1}function findJpegTiffOffset(bytes){let offset=2;for(;offset<bytes.length-1;){if(bytes[offset]!==255)return-1;let marker=bytes[offset+1];if(marker===255){offset++;continue}if(marker===225){if(offset+4>=bytes.length)return-1;let segmentStart=offset+4;return segmentStart+6>bytes.length||!hasExifHeader(bytes,segmentStart)?-1:segmentStart+6}if(offset+4>bytes.length)return-1;let length=bytes[offset+2]<<8|bytes[offset+3];offset+=2+length}return-1}function findWebpTiffOffset(bytes){let offset=12;for(;offset+8<=bytes.length;){let chunkId=String.fromCharCode(bytes[offset],bytes[offset+1],bytes[offset+2],bytes[offset+3]),chunkSize=bytes[offset+4]|bytes[offset+5]<<8|bytes[offset+6]<<16|bytes[offset+7]<<24,dataStart=offset+8;if(chunkId==="EXIF")return dataStart+chunkSize>bytes.length?-1:chunkSize>=6&&hasExifHeader(bytes,dataStart)?dataStart+6:dataStart;offset=dataStart+chunkSize+chunkSize%2}return-1}function hasExifHeader(bytes,offset){return bytes[offset]===69&&bytes[offset+1]===120&&bytes[offset+2]===105&&bytes[offset+3]===102&&bytes[offset+4]===0&&bytes[offset+5]===0}function getExifOrientation(bytes){let tiffOffset=-1;return bytes.length>=2&&bytes[0]===255&&bytes[1]===216?tiffOffset=findJpegTiffOffset(bytes):bytes.length>=12&&bytes[0]===82&&bytes[1]===73&&bytes[2]===70&&bytes[3]===70&&bytes[8]===87&&bytes[9]===69&&bytes[10]===66&&bytes[11]===80&&(tiffOffset=findWebpTiffOffset(bytes)),tiffOffset===-1?1:readOrientationFromTiff(bytes,tiffOffset)}function rotate90(photon,image,dstIndex){let w=image.get_width(),h=image.get_height(),src=image.get_raw_pixels(),dst=new Uint8Array(src.length);for(let y=0;y<h;y++)for(let x=0;x<w;x++){let srcIdx=(y*w+x)*4,dstIdx=dstIndex(x,y,w,h)*4;dst[dstIdx]=src[srcIdx],dst[dstIdx+1]=src[srcIdx+1],dst[dstIdx+2]=src[srcIdx+2],dst[dstIdx+3]=src[srcIdx+3]}return new photon.PhotonImage(dst,h,w)}function applyExifOrientation(photon,image,originalBytes){let orientation=getExifOrientation(originalBytes);if(orientation===1)return image;switch(orientation){case 2:return photon.fliph(image),image;case 3:return photon.fliph(image),photon.flipv(image),image;case 4:return photon.flipv(image),image;case 5:{let rotated=rotate90(photon,image,(x,y,_w,h)=>x*h+(h-1-y));return photon.fliph(rotated),rotated}case 6:return rotate90(photon,image,(x,y,_w,h)=>x*h+(h-1-y));case 7:{let rotated=rotate90(photon,image,(x,y,w,h)=>(w-1-x)*h+y);return photon.fliph(rotated),rotated}case 8:return rotate90(photon,image,(x,y,w,h)=>(w-1-x)*h+y);default:return image}}import{createRequire}from"module";import*as path from"path";import{fileURLToPath}from"url";var require2=createRequire(import.meta.url),fs=require2("fs"),WASM_FILENAME="photon_rs_bg.wasm",photonModule=null,loadPromise=null;function pathOrNull(file){return typeof file=="string"?file:file instanceof URL?fileURLToPath(file):null}function getFallbackWasmPaths(){let execDir=path.dirname(process.execPath);return[path.join(execDir,WASM_FILENAME),path.join(execDir,"photon",WASM_FILENAME),path.join(process.cwd(),WASM_FILENAME)]}function patchPhotonWasmRead(){let originalReadFileSync=fs.readFileSync.bind(fs),fallbackPaths=getFallbackWasmPaths(),mutableFs=fs,patchedReadFileSync=((...args)=>{let[file,options]=args;if(pathOrNull(file)?.endsWith(WASM_FILENAME))try{return originalReadFileSync(...args)}catch(error){let err=error;if(err?.code&&err.code!=="ENOENT")throw error;for(let fallbackPath of fallbackPaths)if(fs.existsSync(fallbackPath))return options===void 0?originalReadFileSync(fallbackPath):originalReadFileSync(fallbackPath,options);throw error}return originalReadFileSync(...args)});try{mutableFs.readFileSync=patchedReadFileSync}catch{Object.defineProperty(fs,"readFileSync",{value:patchedReadFileSync,writable:!0,configurable:!0})}return()=>{try{mutableFs.readFileSync=originalReadFileSync}catch{Object.defineProperty(fs,"readFileSync",{value:originalReadFileSync,writable:!0,configurable:!0})}}}async function loadPhoton(){return photonModule||loadPromise||(loadPromise=(async()=>{let restoreReadFileSync=patchPhotonWasmRead();try{return photonModule=await import("@silvia-odwyer/photon-node"),photonModule}catch{return photonModule=null,photonModule}finally{restoreReadFileSync()}})(),loadPromise)}var DEFAULT_MAX_BYTES=4.5*1024*1024,DEFAULT_OPTIONS={maxWidth:2e3,maxHeight:2e3,maxBytes:DEFAULT_MAX_BYTES,jpegQuality:80};function encodeCandidate(buffer,mimeType){let data=Buffer.from(buffer).toString("base64");return{data,encodedSize:Buffer.byteLength(data,"utf-8"),mimeType}}async function resizeImageInProcess(inputBytes,mimeType,options){let opts={...DEFAULT_OPTIONS,...options},inputBase64Size=Math.ceil(inputBytes.byteLength/3)*4,photon=await loadPhoton();if(!photon)return null;let image;try{let tryEncodings=function(width,height,jpegQualities){let resized=photon.resize(image,width,height,photon.SamplingFilter.Lanczos3);try{let candidates=[encodeCandidate(resized.get_bytes(),"image/png")];for(let quality of jpegQualities)candidates.push(encodeCandidate(resized.get_bytes_jpeg(quality),"image/jpeg"));return candidates}finally{resized.free()}},rawImage=photon.PhotonImage.new_from_byteslice(inputBytes);image=applyExifOrientation(photon,rawImage,inputBytes),image!==rawImage&&rawImage.free();let originalWidth=image.get_width(),originalHeight=image.get_height(),format=mimeType.split("/")[1]??"png";if(originalWidth<=opts.maxWidth&&originalHeight<=opts.maxHeight&&inputBase64Size<opts.maxBytes)return{data:Buffer.from(inputBytes).toString("base64"),mimeType:mimeType||`image/${format}`,originalWidth,originalHeight,width:originalWidth,height:originalHeight,wasResized:!1};let targetWidth=originalWidth,targetHeight=originalHeight;targetWidth>opts.maxWidth&&(targetHeight=Math.round(targetHeight*opts.maxWidth/targetWidth),targetWidth=opts.maxWidth),targetHeight>opts.maxHeight&&(targetWidth=Math.round(targetWidth*opts.maxHeight/targetHeight),targetHeight=opts.maxHeight);let qualitySteps=Array.from(new Set([opts.jpegQuality,85,70,55,40])),currentWidth=targetWidth,currentHeight=targetHeight;for(;;){let candidates=tryEncodings(currentWidth,currentHeight,qualitySteps);for(let candidate of candidates)if(candidate.encodedSize<opts.maxBytes)return{data:candidate.data,mimeType:candidate.mimeType,originalWidth,originalHeight,width:currentWidth,height:currentHeight,wasResized:!0};if(currentWidth===1&&currentHeight===1)break;let nextWidth=currentWidth===1?1:Math.max(1,Math.floor(currentWidth*.75)),nextHeight=currentHeight===1?1:Math.max(1,Math.floor(currentHeight*.75));if(nextWidth===currentWidth&&nextHeight===currentHeight)break;currentWidth=nextWidth,currentHeight=nextHeight}return null}catch{return null}finally{image&&image.free()}}function isResizeImageWorkerRequest(value){if(!value||typeof value!="object")return!1;let record=value;return record.inputBytes instanceof Uint8Array&&typeof record.mimeType=="string"}var port=parentPort;if(!port)throw new Error("image resize worker requires parentPort");port.once("message",message=>{(async()=>{try{if(!isResizeImageWorkerRequest(message))throw new Error("Invalid image resize worker request");let response={result:await resizeImageInProcess(message.inputBytes,message.mimeType,message.options)};port.postMessage(response)}catch(error){let response={error:error instanceof Error?error.message:String(error)};port.postMessage(response)}})()});
2
+ import{parentPort}from"node:worker_threads";function readOrientationFromTiff(bytes,tiffStart){if(tiffStart+8>bytes.length)return 1;let le=(bytes[tiffStart]<<8|bytes[tiffStart+1])===18761,read16=pos=>le?bytes[pos]|bytes[pos+1]<<8:bytes[pos]<<8|bytes[pos+1],ifdOffset=(pos=>le?bytes[pos]|bytes[pos+1]<<8|bytes[pos+2]<<16|bytes[pos+3]<<24:(bytes[pos]<<24|bytes[pos+1]<<16|bytes[pos+2]<<8|bytes[pos+3])>>>0)(tiffStart+4),ifdStart=tiffStart+ifdOffset;if(ifdStart+2>bytes.length)return 1;let entryCount=read16(ifdStart);for(let i=0;i<entryCount;i++){let entryPos=ifdStart+2+i*12;if(entryPos+12>bytes.length)return 1;if(read16(entryPos)===274){let value=read16(entryPos+8);return value>=1&&value<=8?value:1}}return 1}function findJpegTiffOffset(bytes){let offset=2;for(;offset<bytes.length-1;){if(bytes[offset]!==255)return-1;let marker=bytes[offset+1];if(marker===255){offset++;continue}if(marker===225){if(offset+4>=bytes.length)return-1;let segmentStart=offset+4;if(segmentStart+6>bytes.length)return-1;if(hasExifHeader(bytes,segmentStart))return segmentStart+6}if(offset+4>bytes.length)return-1;let length=bytes[offset+2]<<8|bytes[offset+3];offset+=2+length}return-1}function findWebpTiffOffset(bytes){let offset=12;for(;offset+8<=bytes.length;){let chunkId=String.fromCharCode(bytes[offset],bytes[offset+1],bytes[offset+2],bytes[offset+3]),chunkSize=bytes[offset+4]|bytes[offset+5]<<8|bytes[offset+6]<<16|bytes[offset+7]<<24,dataStart=offset+8;if(chunkId==="EXIF")return dataStart+chunkSize>bytes.length?-1:chunkSize>=6&&hasExifHeader(bytes,dataStart)?dataStart+6:dataStart;offset=dataStart+chunkSize+chunkSize%2}return-1}function hasExifHeader(bytes,offset){return bytes[offset]===69&&bytes[offset+1]===120&&bytes[offset+2]===105&&bytes[offset+3]===102&&bytes[offset+4]===0&&bytes[offset+5]===0}function getExifOrientation(bytes){let tiffOffset=-1;return bytes.length>=2&&bytes[0]===255&&bytes[1]===216?tiffOffset=findJpegTiffOffset(bytes):bytes.length>=12&&bytes[0]===82&&bytes[1]===73&&bytes[2]===70&&bytes[3]===70&&bytes[8]===87&&bytes[9]===69&&bytes[10]===66&&bytes[11]===80&&(tiffOffset=findWebpTiffOffset(bytes)),tiffOffset===-1?1:readOrientationFromTiff(bytes,tiffOffset)}function rotate90(photon,image,dstIndex){let w=image.get_width(),h=image.get_height(),src=image.get_raw_pixels(),dst=new Uint8Array(src.length);for(let y=0;y<h;y++)for(let x=0;x<w;x++){let srcIdx=(y*w+x)*4,dstIdx=dstIndex(x,y,w,h)*4;dst[dstIdx]=src[srcIdx],dst[dstIdx+1]=src[srcIdx+1],dst[dstIdx+2]=src[srcIdx+2],dst[dstIdx+3]=src[srcIdx+3]}return new photon.PhotonImage(dst,h,w)}function applyExifOrientation(photon,image,originalBytes){let orientation=getExifOrientation(originalBytes);if(orientation===1)return image;switch(orientation){case 2:return photon.fliph(image),image;case 3:return photon.fliph(image),photon.flipv(image),image;case 4:return photon.flipv(image),image;case 5:{let rotated=rotate90(photon,image,(x,y,_w,h)=>x*h+(h-1-y));return photon.fliph(rotated),rotated}case 6:return rotate90(photon,image,(x,y,_w,h)=>x*h+(h-1-y));case 7:{let rotated=rotate90(photon,image,(x,y,w,h)=>(w-1-x)*h+y);return photon.fliph(rotated),rotated}case 8:return rotate90(photon,image,(x,y,w,h)=>(w-1-x)*h+y);default:return image}}import{createRequire}from"module";import*as path from"path";import{fileURLToPath}from"url";var require2=createRequire(import.meta.url),fs=require2("fs"),WASM_FILENAME="photon_rs_bg.wasm",photonModule=null,loadPromise=null;function pathOrNull(file){return typeof file=="string"?file:file instanceof URL?fileURLToPath(file):null}function getFallbackWasmPaths(){let execDir=path.dirname(process.execPath);return[path.join(execDir,WASM_FILENAME),path.join(execDir,"photon",WASM_FILENAME),path.join(process.cwd(),WASM_FILENAME)]}function patchPhotonWasmRead(){let originalReadFileSync=fs.readFileSync.bind(fs),fallbackPaths=getFallbackWasmPaths(),mutableFs=fs,patchedReadFileSync=((...args)=>{let[file,options]=args;if(pathOrNull(file)?.endsWith(WASM_FILENAME))try{return originalReadFileSync(...args)}catch(error){let err=error;if(err?.code&&err.code!=="ENOENT")throw error;for(let fallbackPath of fallbackPaths)if(fs.existsSync(fallbackPath))return options===void 0?originalReadFileSync(fallbackPath):originalReadFileSync(fallbackPath,options);throw error}return originalReadFileSync(...args)});try{mutableFs.readFileSync=patchedReadFileSync}catch{Object.defineProperty(fs,"readFileSync",{value:patchedReadFileSync,writable:!0,configurable:!0})}return()=>{try{mutableFs.readFileSync=originalReadFileSync}catch{Object.defineProperty(fs,"readFileSync",{value:originalReadFileSync,writable:!0,configurable:!0})}}}async function loadPhoton(){return photonModule||loadPromise||(loadPromise=(async()=>{let restoreReadFileSync=patchPhotonWasmRead();try{return photonModule=await import("@silvia-odwyer/photon-node"),photonModule}catch{return photonModule=null,photonModule}finally{restoreReadFileSync()}})(),loadPromise)}var DEFAULT_MAX_BYTES=4.5*1024*1024,DEFAULT_OPTIONS={maxWidth:2e3,maxHeight:2e3,maxBytes:DEFAULT_MAX_BYTES,jpegQuality:80};function encodeCandidate(buffer,mimeType){let data=Buffer.from(buffer).toString("base64");return{data,encodedSize:Buffer.byteLength(data,"utf-8"),mimeType}}async function resizeImageInProcess(inputBytes,mimeType,options){let opts={...DEFAULT_OPTIONS,...options},inputBase64Size=Math.ceil(inputBytes.byteLength/3)*4,photon=await loadPhoton();if(!photon)return null;let image;try{let tryEncodings=function(width,height,jpegQualities){let resized=photon.resize(image,width,height,photon.SamplingFilter.Lanczos3);try{let candidates=[encodeCandidate(resized.get_bytes(),"image/png")];for(let quality of jpegQualities)candidates.push(encodeCandidate(resized.get_bytes_jpeg(quality),"image/jpeg"));return candidates}finally{resized.free()}},rawImage=photon.PhotonImage.new_from_byteslice(inputBytes);image=applyExifOrientation(photon,rawImage,inputBytes),image!==rawImage&&rawImage.free();let originalWidth=image.get_width(),originalHeight=image.get_height(),format=mimeType.split("/")[1]??"png";if(originalWidth<=opts.maxWidth&&originalHeight<=opts.maxHeight&&inputBase64Size<opts.maxBytes)return{data:Buffer.from(inputBytes).toString("base64"),mimeType:mimeType||`image/${format}`,originalWidth,originalHeight,width:originalWidth,height:originalHeight,wasResized:!1};let targetWidth=originalWidth,targetHeight=originalHeight;targetWidth>opts.maxWidth&&(targetHeight=Math.round(targetHeight*opts.maxWidth/targetWidth),targetWidth=opts.maxWidth),targetHeight>opts.maxHeight&&(targetWidth=Math.round(targetWidth*opts.maxHeight/targetHeight),targetHeight=opts.maxHeight);let qualitySteps=Array.from(new Set([opts.jpegQuality,85,70,55,40])),currentWidth=targetWidth,currentHeight=targetHeight;for(;;){let candidates=tryEncodings(currentWidth,currentHeight,qualitySteps);for(let candidate of candidates)if(candidate.encodedSize<opts.maxBytes)return{data:candidate.data,mimeType:candidate.mimeType,originalWidth,originalHeight,width:currentWidth,height:currentHeight,wasResized:!0};if(currentWidth===1&&currentHeight===1)break;let nextWidth=currentWidth===1?1:Math.max(1,Math.floor(currentWidth*.75)),nextHeight=currentHeight===1?1:Math.max(1,Math.floor(currentHeight*.75));if(nextWidth===currentWidth&&nextHeight===currentHeight)break;currentWidth=nextWidth,currentHeight=nextHeight}return null}catch{return null}finally{image&&image.free()}}function isResizeImageWorkerRequest(value){if(!value||typeof value!="object")return!1;let record=value;return record.inputBytes instanceof Uint8Array&&typeof record.mimeType=="string"}var port=parentPort;if(!port)throw new Error("image resize worker requires parentPort");port.once("message",message=>{(async()=>{try{if(!isResizeImageWorkerRequest(message))throw new Error("Invalid image resize worker request");let response={result:await resizeImageInProcess(message.inputBytes,message.mimeType,message.options)};port.postMessage(response)}catch(error){let response={error:error instanceof Error?error.message:String(error)};port.postMessage(response)}})()});
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{shortHash}from"./chunk-PJACZCIR.js";import{buildBaseOptions,getJsonSchemaToolParameters,getPiUserAgent,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-TXBQIIIO.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-6R7UI4IY.js";import{parseStreamingJson}from"./chunk-D7XAASZM.js";import{calculateCost,clampThinkingLevel}from"./chunk-WJZ4KLGL.js";import{AssistantMessageEventStream}from"./chunk-72KO4OMP.js";import"./chunk-JXWJOIH4.js";var MISTRAL_TOOL_CALL_ID_LENGTH=9,MAX_MISTRAL_ERROR_BODY_CHARS=4e3,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output=createOutput(model);try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let normalizeMistralToolCallId=createMistralToolCallIdNormalizer(),transformedMessages=transformMessages(context.messages,model,id=>normalizeMistralToolCallId(id)),payload=buildChatPayload(model,context,transformedMessages,options),nextPayload=await options?.onPayload?.(payload,model);nextPayload!==void 0&&(payload=nextPayload);let mistralStream=await requestMistralStream(model,payload,apiKey,options);if(stream2.push({type:"start",partial:output}),await consumeChatStream(model,output,stream2,mistralStream),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Mistral stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.partialArgs;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatMistralError(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0,reasoning=clampedReasoning==="off"?void 0:clampedReasoning,shouldUseReasoning=model.reasoning&&reasoning!==void 0;return stream(model,context,{...base,promptMode:shouldUseReasoning&&usesPromptModeReasoning(model)?"reasoning":void 0,reasoningEffort:shouldUseReasoning&&usesReasoningEffort(model)?mapReasoningEffort(model,reasoning):void 0})};function createOutput(model){return{role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()}}function createMistralToolCallIdNormalizer(){let idMap=new Map,reverseMap=new Map;return id=>{let existing=idMap.get(id);if(existing)return existing;let attempt=0;for(;;){let candidate=deriveMistralToolCallId(id,attempt),owner=reverseMap.get(candidate);if(!owner||owner===id)return idMap.set(id,candidate),reverseMap.set(candidate,id),candidate;attempt++}}}function deriveMistralToolCallId(id,attempt){let normalized=id.replace(/[^a-zA-Z0-9]/g,"");if(attempt===0&&normalized.length===MISTRAL_TOOL_CALL_ID_LENGTH)return normalized;let seedBase=normalized||id,seed=attempt===0?seedBase:`${seedBase}:${attempt}`;return shortHash(seed).replace(/[^a-zA-Z0-9]/g,"").slice(0,MISTRAL_TOOL_CALL_ID_LENGTH)}function formatMistralError(error){if(error instanceof Error){let httpError=error,statusCode=typeof httpError.statusCode=="number"?httpError.statusCode:void 0,bodyText=typeof httpError.body=="string"?httpError.body.trim():void 0;return statusCode!==void 0&&bodyText?`Mistral API error (${statusCode}): ${truncateErrorText(bodyText,MAX_MISTRAL_ERROR_BODY_CHARS)}`:statusCode!==void 0?`Mistral API error (${statusCode}): ${error.message}`:error.message}return safeJsonStringify(error)}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}async function requestMistralStream(model,payload,apiKey,options){let baseUrl=new URL(model.baseUrl);baseUrl.pathname=`${baseUrl.pathname.replace(/\/+$/u,"")}/`;let url=new URL("v1/chat/completions",baseUrl),headers=buildMistralHeaders(model,apiKey,options),timeoutSignal=AbortSignal.timeout(options?.timeoutMs??6e4),signal=options?.signal?AbortSignal.any([options.signal,timeoutSignal]):timeoutSignal,response=await(options?.fetch??globalThis.fetch)(url,{method:"POST",headers,body:JSON.stringify(toMistralWirePayload(payload)),signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),!response.ok){let body=await response.text();throw new MistralHttpError(response.status,body,response.statusText)}if(!response.body)throw new Error("Mistral response has no body");return readMistralEvents(response.body,signal)}var MistralHttpError=class extends Error{constructor(statusCode,body,statusText){super(statusText||`Request failed with status ${statusCode}`),this.name="MistralHttpError",this.statusCode=statusCode,this.body=body}};function buildMistralHeaders(model,apiKey,options){let headers=new Headers({"User-Agent":getPiUserAgent(),accept:"text/event-stream",authorization:`Bearer ${apiKey}`,"content-type":"application/json"});applyMistralHeaderOverrides(headers,model.headers),applyMistralHeaderOverrides(headers,options?.headers);let hasExplicitAffinity=hasMistralHeaderOverride(model.headers,"x-affinity")||hasMistralHeaderOverride(options?.headers,"x-affinity");return shouldUsePromptCaching(options)&&!hasExplicitAffinity&&headers.set("x-affinity",options.sessionId),headers}function applyMistralHeaderOverrides(headers,overrides){if(overrides)for(let[name,value]of Object.entries(overrides))value===null?headers.delete(name):headers.set(name,value)}function hasMistralHeaderOverride(overrides,target){return!!overrides&&Object.keys(overrides).some(name=>name.toLowerCase()===target)}function toMistralWirePayload(payload){let wirePayload={...payload};for(let[source,target]of[["topP","top_p"],["maxTokens","max_tokens"],["randomSeed","random_seed"],["responseFormat","response_format"],["toolChoice","tool_choice"],["presencePenalty","presence_penalty"],["frequencyPenalty","frequency_penalty"],["parallelToolCalls","parallel_tool_calls"],["reasoningEffort","reasoning_effort"],["promptMode","prompt_mode"],["promptCacheKey","prompt_cache_key"],["safePrompt","safe_prompt"]])remapMistralProperty(wirePayload,source,target);wirePayload.messages=payload.messages.map(message=>toMistralWireMessage(message));let responseFormat=wirePayload.response_format;if(isMistralRecord(responseFormat)){let wireResponseFormat={...responseFormat};remapMistralProperty(wireResponseFormat,"jsonSchema","json_schema");let jsonSchema=wireResponseFormat.json_schema;if(isMistralRecord(jsonSchema)){let wireJsonSchema={...jsonSchema};remapMistralProperty(wireJsonSchema,"schemaDefinition","schema"),wireResponseFormat.json_schema=wireJsonSchema}wirePayload.response_format=wireResponseFormat}return wirePayload}function toMistralWireMessage(message){let wireMessage={...message};return remapMistralProperty(wireMessage,"toolCalls","tool_calls"),remapMistralProperty(wireMessage,"toolCallId","tool_call_id"),Array.isArray(message.content)&&(wireMessage.content=message.content.map(chunk=>toMistralWireContentChunk(chunk))),wireMessage}function toMistralWireContentChunk(chunk){let wireChunk={...chunk};for(let[source,target]of[["imageUrl","image_url"],["documentUrl","document_url"],["documentName","document_name"],["fileId","file_id"],["referenceIds","reference_ids"],["inputAudio","input_audio"]])remapMistralProperty(wireChunk,source,target);return wireChunk}function remapMistralProperty(record,source,target){source in record&&(record[target]=record[source],delete record[source])}function isMistralRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var MISTRAL_STREAM_DONE=Symbol("mistral-stream-done");async function*readMistralEvents(body,signal){let reader=body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>{reader.cancel().catch(()=>{})};signal.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal.aborted)throw signal.reason;let{done,value}=await reader.read();if(signal.aborted)throw signal.reason;buffer+=done?decoder.decode():decoder.decode(value,{stream:!0});let boundary=findMistralEventBoundary(buffer);for(;boundary;){let event=parseMistralEvent(buffer.slice(0,boundary.index));if(buffer=buffer.slice(boundary.index+boundary.length),event===MISTRAL_STREAM_DONE)return;event&&(yield event),boundary=findMistralEventBoundary(buffer)}if(done)break}if(buffer.trim()){let event=parseMistralEvent(buffer);event!==MISTRAL_STREAM_DONE&&event&&(yield event)}}finally{signal.removeEventListener("abort",onAbort);try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function findMistralEventBoundary(buffer){let match=/\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(buffer);return match?.index===void 0?void 0:{index:match.index,length:match[0].length}}function parseMistralEvent(raw){let data=raw.split(/\r\n|\r|\n/u).filter(line=>line.startsWith("data:")).map(line=>line.slice(5).trimStart()).join(`
2
+ import{shortHash}from"./chunk-PJACZCIR.js";import{buildBaseOptions,getJsonSchemaToolParameters,getPiUserAgent,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-TXBQIIIO.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-6R7UI4IY.js";import{parseStreamingJson}from"./chunk-D7XAASZM.js";import{calculateCost,clampThinkingLevel}from"./chunk-E6KP6V7F.js";import{AssistantMessageEventStream}from"./chunk-72KO4OMP.js";import"./chunk-JXWJOIH4.js";var MISTRAL_TOOL_CALL_ID_LENGTH=9,MAX_MISTRAL_ERROR_BODY_CHARS=4e3,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output=createOutput(model);try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let normalizeMistralToolCallId=createMistralToolCallIdNormalizer(),transformedMessages=transformMessages(context.messages,model,id=>normalizeMistralToolCallId(id)),payload=buildChatPayload(model,context,transformedMessages,options),nextPayload=await options?.onPayload?.(payload,model);nextPayload!==void 0&&(payload=nextPayload);let mistralStream=await requestMistralStream(model,payload,apiKey,options);if(stream2.push({type:"start",partial:output}),await consumeChatStream(model,output,stream2,mistralStream),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Mistral stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.partialArgs;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatMistralError(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0,reasoning=clampedReasoning==="off"?void 0:clampedReasoning,shouldUseReasoning=model.reasoning&&reasoning!==void 0;return stream(model,context,{...base,promptMode:shouldUseReasoning&&usesPromptModeReasoning(model)?"reasoning":void 0,reasoningEffort:shouldUseReasoning&&usesReasoningEffort(model)?mapReasoningEffort(model,reasoning):void 0})};function createOutput(model){return{role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()}}function createMistralToolCallIdNormalizer(){let idMap=new Map,reverseMap=new Map;return id=>{let existing=idMap.get(id);if(existing)return existing;let attempt=0;for(;;){let candidate=deriveMistralToolCallId(id,attempt),owner=reverseMap.get(candidate);if(!owner||owner===id)return idMap.set(id,candidate),reverseMap.set(candidate,id),candidate;attempt++}}}function deriveMistralToolCallId(id,attempt){let normalized=id.replace(/[^a-zA-Z0-9]/g,"");if(attempt===0&&normalized.length===MISTRAL_TOOL_CALL_ID_LENGTH)return normalized;let seedBase=normalized||id,seed=attempt===0?seedBase:`${seedBase}:${attempt}`;return shortHash(seed).replace(/[^a-zA-Z0-9]/g,"").slice(0,MISTRAL_TOOL_CALL_ID_LENGTH)}function formatMistralError(error){if(error instanceof Error){let httpError=error,statusCode=typeof httpError.statusCode=="number"?httpError.statusCode:void 0,bodyText=typeof httpError.body=="string"?httpError.body.trim():void 0;return statusCode!==void 0&&bodyText?`Mistral API error (${statusCode}): ${truncateErrorText(bodyText,MAX_MISTRAL_ERROR_BODY_CHARS)}`:statusCode!==void 0?`Mistral API error (${statusCode}): ${error.message}`:error.message}return safeJsonStringify(error)}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}async function requestMistralStream(model,payload,apiKey,options){let baseUrl=new URL(model.baseUrl);baseUrl.pathname=`${baseUrl.pathname.replace(/\/+$/u,"")}/`;let url=new URL("v1/chat/completions",baseUrl),headers=buildMistralHeaders(model,apiKey,options),timeoutSignal=AbortSignal.timeout(options?.timeoutMs??6e4),signal=options?.signal?AbortSignal.any([options.signal,timeoutSignal]):timeoutSignal,response=await(options?.fetch??globalThis.fetch)(url,{method:"POST",headers,body:JSON.stringify(toMistralWirePayload(payload)),signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),!response.ok){let body=await response.text();throw new MistralHttpError(response.status,body,response.statusText)}if(!response.body)throw new Error("Mistral response has no body");return readMistralEvents(response.body,signal)}var MistralHttpError=class extends Error{constructor(statusCode,body,statusText){super(statusText||`Request failed with status ${statusCode}`),this.name="MistralHttpError",this.statusCode=statusCode,this.body=body}};function buildMistralHeaders(model,apiKey,options){let headers=new Headers({"User-Agent":getPiUserAgent(),accept:"text/event-stream",authorization:`Bearer ${apiKey}`,"content-type":"application/json"});applyMistralHeaderOverrides(headers,model.headers),applyMistralHeaderOverrides(headers,options?.headers);let hasExplicitAffinity=hasMistralHeaderOverride(model.headers,"x-affinity")||hasMistralHeaderOverride(options?.headers,"x-affinity");return shouldUsePromptCaching(options)&&!hasExplicitAffinity&&headers.set("x-affinity",options.sessionId),headers}function applyMistralHeaderOverrides(headers,overrides){if(overrides)for(let[name,value]of Object.entries(overrides))value===null?headers.delete(name):headers.set(name,value)}function hasMistralHeaderOverride(overrides,target){return!!overrides&&Object.keys(overrides).some(name=>name.toLowerCase()===target)}function toMistralWirePayload(payload){let wirePayload={...payload};for(let[source,target]of[["topP","top_p"],["maxTokens","max_tokens"],["randomSeed","random_seed"],["responseFormat","response_format"],["toolChoice","tool_choice"],["presencePenalty","presence_penalty"],["frequencyPenalty","frequency_penalty"],["parallelToolCalls","parallel_tool_calls"],["reasoningEffort","reasoning_effort"],["promptMode","prompt_mode"],["promptCacheKey","prompt_cache_key"],["safePrompt","safe_prompt"]])remapMistralProperty(wirePayload,source,target);wirePayload.messages=payload.messages.map(message=>toMistralWireMessage(message));let responseFormat=wirePayload.response_format;if(isMistralRecord(responseFormat)){let wireResponseFormat={...responseFormat};remapMistralProperty(wireResponseFormat,"jsonSchema","json_schema");let jsonSchema=wireResponseFormat.json_schema;if(isMistralRecord(jsonSchema)){let wireJsonSchema={...jsonSchema};remapMistralProperty(wireJsonSchema,"schemaDefinition","schema"),wireResponseFormat.json_schema=wireJsonSchema}wirePayload.response_format=wireResponseFormat}return wirePayload}function toMistralWireMessage(message){let wireMessage={...message};return remapMistralProperty(wireMessage,"toolCalls","tool_calls"),remapMistralProperty(wireMessage,"toolCallId","tool_call_id"),Array.isArray(message.content)&&(wireMessage.content=message.content.map(chunk=>toMistralWireContentChunk(chunk))),wireMessage}function toMistralWireContentChunk(chunk){let wireChunk={...chunk};for(let[source,target]of[["imageUrl","image_url"],["documentUrl","document_url"],["documentName","document_name"],["fileId","file_id"],["referenceIds","reference_ids"],["inputAudio","input_audio"]])remapMistralProperty(wireChunk,source,target);return wireChunk}function remapMistralProperty(record,source,target){source in record&&(record[target]=record[source],delete record[source])}function isMistralRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var MISTRAL_STREAM_DONE=Symbol("mistral-stream-done");async function*readMistralEvents(body,signal){let reader=body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>{reader.cancel().catch(()=>{})};signal.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal.aborted)throw signal.reason;let{done,value}=await reader.read();if(signal.aborted)throw signal.reason;buffer+=done?decoder.decode():decoder.decode(value,{stream:!0});let boundary=findMistralEventBoundary(buffer);for(;boundary;){let event=parseMistralEvent(buffer.slice(0,boundary.index));if(buffer=buffer.slice(boundary.index+boundary.length),event===MISTRAL_STREAM_DONE)return;event&&(yield event),boundary=findMistralEventBoundary(buffer)}if(done)break}if(buffer.trim()){let event=parseMistralEvent(buffer);event!==MISTRAL_STREAM_DONE&&event&&(yield event)}}finally{signal.removeEventListener("abort",onAbort);try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function findMistralEventBoundary(buffer){let match=/\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(buffer);return match?.index===void 0?void 0:{index:match.index,length:match[0].length}}function parseMistralEvent(raw){let data=raw.split(/\r\n|\r|\n/u).filter(line=>line.startsWith("data:")).map(line=>line.slice(5).trimStart()).join(`
3
3
  `).trim();if(!data)return;if(data==="[DONE]")return MISTRAL_STREAM_DONE;let parsed=JSON.parse(data);if(!isMistralRecord(parsed)||!Array.isArray(parsed.choices))throw new Error("Invalid Mistral streaming event");return{data:parsed}}function buildChatPayload(model,context,messages,options){let payload={model:model.id,stream:!0,messages:toChatMessages(messages,model.input.includes("image"))};return context.tools?.length&&(payload.tools=toFunctionTools(context.tools)),options?.temperature!==void 0&&(payload.temperature=options.temperature),options?.maxTokens!==void 0&&(payload.maxTokens=options.maxTokens),options?.toolChoice&&(payload.toolChoice=mapToolChoice(options.toolChoice)),options?.promptMode&&(payload.promptMode=options.promptMode),options?.reasoningEffort&&(payload.reasoningEffort=options.reasoningEffort),shouldUsePromptCaching(options)&&(payload.promptCacheKey=options.sessionId),context.systemPrompt&&payload.messages.unshift({role:"system",content:sanitizeSurrogates(context.systemPrompt)}),payload}function shouldUsePromptCaching(options){return options?.cacheRetention!=="none"&&!!options?.sessionId}function getMistralCachedPromptTokens(usage,promptTokens){let rawUsage=usage,rawCachedTokens=rawUsage.promptTokensDetails?.cachedTokens??rawUsage.prompt_tokens_details?.cached_tokens??rawUsage.promptTokenDetails?.cachedTokens??rawUsage.prompt_token_details?.cached_tokens??rawUsage.numCachedTokens??rawUsage.num_cached_tokens??0,cachedTokens=typeof rawCachedTokens=="number"&&Number.isFinite(rawCachedTokens)?rawCachedTokens:0;return Math.min(promptTokens,Math.max(0,cachedTokens))}async function consumeChatStream(model,output,stream2,mistralStream){let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1,toolBlocksByKey=new Map,finishCurrentBlock=block=>{if(block){if(block.type==="text"){stream2.push({type:"text_end",contentIndex:blockIndex(),content:block.text,partial:output});return}block.type==="thinking"&&stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:block.thinking,partial:output})}};for await(let event of mistralStream){let chunk=event.data;if(output.responseId||=chunk.id,chunk.usage){let promptTokens=chunk.usage.prompt_tokens||0,cachedPromptTokens=getMistralCachedPromptTokens(chunk.usage,promptTokens);output.usage.input=Math.max(0,promptTokens-cachedPromptTokens),output.usage.output=chunk.usage.completion_tokens||0,output.usage.cacheRead=cachedPromptTokens,output.usage.cacheWrite=0,output.usage.totalTokens=chunk.usage.total_tokens||output.usage.input+output.usage.output+output.usage.cacheRead+output.usage.cacheWrite,calculateCost(model,output.usage)}let choice=chunk.choices[0];if(!choice)continue;if(choice.finish_reason){output.rawStopReason=choice.finish_reason;let stopReasonResult=mapChatStopReason(choice.finish_reason);output.stopReason=stopReasonResult.stopReason,stopReasonResult.errorMessage&&(output.errorMessage=stopReasonResult.errorMessage)}let delta=choice.delta;if(delta.content!==null&&delta.content!==void 0){let contentItems=typeof delta.content=="string"?[delta.content]:delta.content;for(let item of contentItems){if(typeof item=="string"){let textDelta=sanitizeSurrogates(item);currentBlock?.type!=="text"&&(finishCurrentBlock(currentBlock),currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output})),currentBlock.text+=textDelta,stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:textDelta,partial:output});continue}if(item.type==="thinking"){let deltaText=(item.thinking??[]).map(part=>part.text??"").filter(text=>text.length>0).join(""),thinkingDelta=sanitizeSurrogates(deltaText);if(!thinkingDelta)continue;currentBlock?.type!=="thinking"&&(finishCurrentBlock(currentBlock),currentBlock={type:"thinking",thinking:""},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})),currentBlock.thinking+=thinkingDelta,stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:thinkingDelta,partial:output});continue}if(item.type==="text"){let textDelta=sanitizeSurrogates(item.text??"");currentBlock?.type!=="text"&&(finishCurrentBlock(currentBlock),currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output})),currentBlock.text+=textDelta,stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:textDelta,partial:output})}}}let toolCalls=delta.tool_calls||[];for(let toolCall of toolCalls){currentBlock&&(finishCurrentBlock(currentBlock),currentBlock=null);let callId=toolCall.id&&toolCall.id!=="null"?toolCall.id:deriveMistralToolCallId(`toolcall:${toolCall.index??0}`,0),key=toolCall.index??callId,existingIndex=toolBlocksByKey.get(key),block;if(existingIndex!==void 0){let existing=output.content[existingIndex];existing?.type==="toolCall"&&(block=existing)}block||(block={type:"toolCall",id:callId,name:toolCall.function.name,arguments:{},partialArgs:""},output.content.push(block),toolBlocksByKey.set(key,output.content.length-1),stream2.push({type:"toolcall_start",contentIndex:output.content.length-1,partial:output}));let argsDelta=typeof toolCall.function.arguments=="string"?toolCall.function.arguments:JSON.stringify(toolCall.function.arguments||{});block.partialArgs=(block.partialArgs||"")+argsDelta,block.arguments=parseStreamingJson(block.partialArgs),stream2.push({type:"toolcall_delta",contentIndex:toolBlocksByKey.get(key),delta:argsDelta,partial:output})}}finishCurrentBlock(currentBlock);for(let index of toolBlocksByKey.values()){let block=output.content[index];if(block.type!=="toolCall")continue;let toolBlock=block;toolBlock.arguments=parseStreamingJson(toolBlock.partialArgs),delete toolBlock.partialArgs,stream2.push({type:"toolcall_end",contentIndex:index,toolCall:toolBlock,partial:output})}}function toFunctionTools(tools){return tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,!0);return{type:"function",function:{name:tool.name,description:tool.description,parameters:stripSymbolKeys(getJsonSchemaToolParameters(tool,strict)),strict:strict??!1}}})}function stripSymbolKeys(value){if(Array.isArray(value))return value.map(item=>stripSymbolKeys(item));if(value&&typeof value=="object"){let result={};for(let[key,entry]of Object.entries(value))result[key]=stripSymbolKeys(entry);return result}return value}function toChatMessages(messages,supportsImages){let result=[];for(let msg of messages){if(msg.role==="user"){if(typeof msg.content=="string"){result.push({role:"user",content:sanitizeSurrogates(msg.content)});continue}let hadImages=msg.content.some(item=>item.type==="image"),content=msg.content.filter(item=>item.type==="text"||supportsImages).map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:{type:"image_url",imageUrl:`data:${item.mimeType};base64,${item.data}`});if(content.length>0){result.push({role:"user",content});continue}hadImages&&!supportsImages&&result.push({role:"user",content:"(image omitted: model does not support images)"});continue}if(msg.role==="assistant"){let contentParts=[],toolCalls=[];for(let block of msg.content){if(block.type==="text"){block.text.trim().length>0&&contentParts.push({type:"text",text:sanitizeSurrogates(block.text)});continue}if(block.type==="thinking"){block.thinking.trim().length>0&&contentParts.push({type:"thinking",thinking:[{type:"text",text:sanitizeSurrogates(block.thinking)}]});continue}toolCalls.push({id:block.id,type:"function",function:{name:block.name,arguments:JSON.stringify(block.arguments||{})},index:0})}let assistantMessage={role:"assistant",prefix:!1};contentParts.length>0&&(assistantMessage.content=contentParts),toolCalls.length>0&&(assistantMessage.toolCalls=toolCalls),(contentParts.length>0||toolCalls.length>0)&&result.push(assistantMessage);continue}let toolContent=[],textResult=msg.content.filter(part=>part.type==="text").map(part=>part.type==="text"?sanitizeSurrogates(part.text):"").join(`
4
4
  `),hasImages=msg.content.some(part=>part.type==="image"),toolText=buildToolResultText(textResult,hasImages,supportsImages,msg.isError);toolContent.push({type:"text",text:toolText});for(let part of msg.content)supportsImages&&part.type==="image"&&toolContent.push({type:"image_url",imageUrl:`data:${part.mimeType};base64,${part.data}`});result.push({role:"tool",toolCallId:msg.toolCallId,name:msg.toolName,content:toolContent})}return result}function buildToolResultText(text,hasImages,supportsImages,isError){let trimmed=text.trim(),errorPrefix=isError?"[tool error] ":"";return trimmed.length>0?`${errorPrefix}${trimmed}${hasImages&&!supportsImages?`
5
5
  [tool image omitted: model does not support images]`:""}`:hasImages?supportsImages?isError?"[tool error] (see attached image)":"(see attached image)":isError?"[tool error] (image omitted: model does not support images)":"(image omitted: model does not support images)":isError?"[tool error] (no tool output)":"(no tool output)"}function usesReasoningEffort(model){return model.id==="mistral-small-2603"||model.id==="mistral-small-latest"||model.id==="mistral-medium-3.5"}function usesPromptModeReasoning(model){return model.reasoning&&!usesReasoningEffort(model)}function mapReasoningEffort(model,level){return model.thinkingLevelMap?.[level]??"high"}function mapToolChoice(choice){if(choice)return choice==="auto"||choice==="none"||choice==="any"||choice==="required"?choice:{type:"function",function:{name:choice.function.name}}}function mapChatStopReason(reason){if(reason===null)return{stopReason:"stop"};switch(reason){case"stop":return{stopReason:"stop"};case"length":case"model_length":return{stopReason:"length"};case"tool_calls":return{stopReason:"toolUse"};case"error":return{stopReason:"error",errorMessage:"Provider stopped with: error"};default:return{stopReason:"error",errorMessage:`Provider stopped with: ${reason}`}}}export{stream,streamSimple};
@@ -0,0 +1,2 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
+ import{child_process,crypto,fs,os,path,stream,util}from"./chunk-7ZC4UXSL.js";import"./chunk-JXWJOIH4.js";export{child_process,crypto,fs,os,path,stream,util};
@@ -0,0 +1,16 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
+ import{child_process,crypto,fs,path,stream,util}from"./chunk-7ZC4UXSL.js";import{AnthropicError,DEFAULT_MEMORY_SYNC_INTERVAL_MS,MIN_MEMORY_SYNC_INTERVAL_MS,ToolError,__classPrivateFieldGet,__classPrivateFieldSet,checkMemorySyncInterval,decodeUTF8,encodeUTF8,isStatus,loggerFor,promiseWithResolvers}from"./chunk-JUPSJTFQ.js";import"./chunk-JXWJOIH4.js";import*as fs4 from"node:fs/promises";import*as fssync from"node:fs";import*as path2 from"node:path";import*as cp from"node:child_process";import*as crypto2 from"node:crypto";import*as readline from"node:readline";function betaTool(options){if(options.inputSchema.type!=="object")throw new Error(`JSON schema for tool "${options.name}" must be an object, but got ${options.inputSchema.type}`);return{type:"custom",name:options.name,input_schema:options.inputSchema,description:options.description,run:options.run,parse:content=>content,...options.close?{close:options.close}:{}}}var fs2=fs.promises,DIR_CREATE_MODE=448,FILE_CREATE_MODE=384;function isWithin(root,p){let rel=path.relative(root,p);return rel===""||!rel.startsWith(".."+path.sep)&&rel!==".."&&!path.isAbsolute(rel)}async function containingRoot(roots,target){for(let root of roots)if(isWithin(await canonicalize(path.resolve(root)),target))return root}var MAX_SYMLINK_HOPS=40;function errnoCode(err){let code=err?.code;return typeof code=="string"?code:void 0}async function canonicalize(abs){let tail=[],prefix=abs,hops=0;for(;;){let real;try{real=await fs2.realpath(prefix)}catch(realpathErr){let isLink;try{isLink=(await fs2.lstat(prefix)).isSymbolicLink()}catch(lstatErr){let code=errnoCode(lstatErr);if(code!=="ENOENT"&&code!=="ENOTDIR")throw lstatErr;let parent=path.dirname(prefix);if(parent===prefix)throw lstatErr;tail.push(path.basename(prefix)),prefix=parent;continue}if(!isLink)throw realpathErr;if(++hops>MAX_SYMLINK_HOPS)throw Object.assign(new Error("too many levels of symbolic links"),{code:"ELOOP"});prefix=path.resolve(path.dirname(prefix),await fs2.readlink(prefix));continue}return tail.length?path.join(real,...tail.reverse()):real}}async function confineToRoot(root,p,opts){let allowedRoots=opts?.allowedRoots??[],realRoot=await canonicalize(path.resolve(root)),real;try{real=await canonicalize(path.resolve(realRoot,p))}catch(err){throw new ToolError(fsErrorMessage(err,`path ${JSON.stringify(p)}`))}if(isWithin(realRoot,real)||await containingRoot(allowedRoots,real)!==void 0)return real;let permitted=allowedRoots.length?"the session's working directory and its other permitted directories":"the session's working directory";throw new ToolError(`path ${JSON.stringify(p)} is outside ${permitted}`)}async function atomicWriteFile(targetPath,content){let dir=path.dirname(targetPath),tempPath=path.join(dir,`.tmp-${process.pid}-${crypto.randomUUID()}`),existingMode=await fs2.stat(targetPath).then(st=>st.mode&511,()=>{}),handle;try{handle=await fs2.open(tempPath,"wx",FILE_CREATE_MODE),existingMode!==void 0&&await handle.chmod(existingMode),await handle.writeFile(content,"utf-8"),await handle.sync(),await handle.close(),handle=void 0,await fs2.rename(tempPath,targetPath)}catch(err){throw handle&&await handle.close().catch(()=>{}),await fs2.unlink(tempPath).catch(()=>{}),err}}function fsErrorMessage(err,file){let code=errnoCode(err);switch(code){case"ENOENT":return`${file}: no such file or directory`;case"EACCES":case"EPERM":return`${file}: permission denied`;case"ENOTDIR":return`${file}: not a directory`;case"EISDIR":return`${file}: is a directory`;case"ELOOP":return`${file}: too many levels of symbolic links`;case"ENAMETOOLONG":return`${file}: file name too long`;case"ENOSPC":return`${file}: no space left on device`;case"EMFILE":case"ENFILE":return`${file}: too many open files`;default:return`${file}: ${code!==void 0?`i/o error (${code})`:"i/o error"}`}}var fs3=fs.promises,execFileAsync=util.promisify(child_process.execFile);async function setupSkills(ctx){let{client,sessionId}=ctx;if(!client)return async()=>{};let log=loggerFor(client),session=ctx.session;if(!session){if(sessionId===void 0)return async()=>{};log.warn("AgentToolContext.sessionId is deprecated and costs an extra session fetch; fetch the session once and set `session` instead",{component:"agent-tool-context"}),session=await client.beta.sessions.retrieve(sessionId)}let skillsRoot=path.resolve(ctx.workdir,"skills"),created=[];for(let skill of session.agent.skills)try{let version=await client.beta.skills.versions.retrieve(skill.version,{skill_id:skill.skill_id}),dirname2=path.basename(version.name.trim());(dirname2===""||dirname2==="."||dirname2==="..")&&(dirname2=skill.skill_id);let dest=path.resolve(skillsRoot,dirname2);if(dest!==skillsRoot&&!dest.startsWith(skillsRoot+path.sep)){log.warn("skill name escapes the skills dir; skipping",{component:"agent-tool-context",name:version.name});continue}let resp=await client.beta.skills.versions.download(version.id,{skill_id:skill.skill_id});await fs3.rm(dest,{recursive:!0,force:!0}),await fs3.mkdir(dest,{recursive:!0,mode:DIR_CREATE_MODE}),created.push(dest),await extractSkillArchive(resp,dest),log.info("downloaded skill",{component:"agent-tool-context",skill_id:skill.skill_id,version:version.id,dest})}catch(e){log.warn("failed to download skill",{component:"agent-tool-context",skill_id:skill.skill_id,error:String(e)})}return async()=>{for(let dest of created)await fs3.rm(dest,{recursive:!0,force:!0}).catch(e=>{log.warn("failed to clean up skill",{component:"agent-tool-context",dest,error:String(e)})})}}function assertSafeMemberNames(names){for(let raw of names){let entry=raw.trim();if(entry&&(path.isAbsolute(entry)||entry.split(/[\\/]/).includes("..")))throw new AnthropicError(`refusing to extract unsafe archive member: ${entry}`)}}var INCONSISTENT_LISTING="skill archive listing is inconsistent; refusing to extract",PLAIN_TYPE_CHARS={unzip:new Set(["-","d","?"]),tar:new Set(["-","d","C"])};function listingLines(listing){let lines=listing.split(`
3
+ `);return lines[lines.length-1]===""&&lines.pop(),lines}function canExcludeVerbatim(cmd,name){return/^[\x20-\x7E]+$/.test(name)&&!/[\\^#]/.test(name)&&!(cmd==="unzip"&&name.startsWith("-"))}function classifyArchiveListing(cmd,names,typed){let nameLines=listingLines(names),typedLines=listingLines(typed);if(nameLines.length!==typedLines.length)throw new AnthropicError(INCONSISTENT_LISTING);let plain=[],special=[];return nameLines.forEach((name,i)=>{if(PLAIN_TYPE_CHARS[cmd].has(typedLines[i].charAt(0))){plain.push(name);return}if(!canExcludeVerbatim(cmd,name))throw new AnthropicError(`refusing to extract archive: cannot safely exclude member ${JSON.stringify(name)}`);special.push(name)}),{plain,special}}async function assertOnlyPlainEntries(dir){for(let entry of await fs3.readdir(dir,{withFileTypes:!0}))if(entry.isDirectory())await assertOnlyPlainEntries(path.join(dir,entry.name));else if(!entry.isFile())throw new AnthropicError(INCONSISTENT_LISTING)}async function runArchiveTool(cmd,args){try{let{stdout}=await execFileAsync(cmd,args);return stdout}catch(e){throw errnoCode(e)==="ENOENT"?new AnthropicError(`skill extraction requires the \`${cmd}\` command, but it was not found on PATH`):e}}function archiveTopDir(names){let top,nested=!1;for(let raw of names){let parts=raw.trim().split("/").filter(p=>p!==""&&p!==".");if(parts.length===0)continue;let first=parts[0];if(top===void 0)top=first;else if(first!==top)return"";parts.length>1&&(nested=!0)}return top!==void 0&&nested?top:""}async function extractSkillArchive(resp,dest){let tmp=path.join(dest,`.skill-archive-${process.pid}-${Date.now()}`);if(!resp.body)throw new AnthropicError("skill download response had no body");await stream.promises.pipeline(stream.Readable.fromWeb(resp.body),fs.createWriteStream(tmp));let stage=path.join(path.dirname(dest),`.skill-stage-${process.pid}-${Date.now()}`),excludeFile=path.join(path.dirname(dest),`.skill-exclude-${process.pid}-${Date.now()}`);try{let head=await readHead(tmp,4),isZip=head.length>=4&&head[0]===80&&head[1]===75&&head[2]===3&&head[3]===4,archiveCmd=isZip?"unzip":"tar",names=await runArchiveTool(archiveCmd,isZip?["-Z1",tmp]:["-tf",tmp]),typed=await runArchiveTool(archiveCmd,isZip?["-Z","--h","--t",tmp]:["-tvf",tmp]),{plain,special}=classifyArchiveListing(archiveCmd,names,typed);assertSafeMemberNames([...plain,...special]);let top=archiveTopDir(plain);await fs3.mkdir(stage,{recursive:!0,mode:DIR_CREATE_MODE}),plain.length>0&&await runArchiveTool(archiveCmd,await extractArgs(archiveCmd,tmp,stage,special,excludeFile)),await assertOnlyPlainEntries(stage);let srcRoot=top?path.join(stage,top):stage,entries=await fs3.readdir(srcRoot).catch(e=>{throw errnoCode(e)==="ENOENT"?new AnthropicError(INCONSISTENT_LISTING):e});for(let entry of entries)await fs3.rename(path.join(srcRoot,entry),path.join(dest,entry))}finally{await fs3.rm(tmp,{force:!0}),await fs3.rm(excludeFile,{force:!0}),await fs3.rm(stage,{recursive:!0,force:!0})}}async function extractArgs(cmd,archive,stage,special,excludeFile){let patterns=special.map(name=>name.replace(/[*?[\\]/g,"\\$&"));return cmd==="unzip"?["-oq",archive,"-d",stage,...patterns.length>0?["-x",...patterns]:[]]:patterns.length===0?["-xf",archive,"-C",stage]:(await fs3.writeFile(excludeFile,patterns.join(`
4
+ `)+`
5
+ `,{flag:"wx",mode:384}),["-xf",archive,"-C",stage,"-X",excludeFile])}async function readHead(file,n){let handle=await fs3.open(file,"r");try{let buf=Buffer.alloc(n),{bytesRead}=await handle.read(buf,0,n,0);return buf.subarray(0,bytesRead)}finally{await handle.close()}}var fsp=fs.promises,C=fs.constants,OWNER_ONLY_DIR_MODE=448,OWNER_ONLY_FILE_MODE=384,OWNER_ONLY_EXEC_MODE=448,O_NOFOLLOW=C.O_NOFOLLOW??0,O_NONBLOCK=C.O_NONBLOCK??0,FileStoreError=class extends Error{constructor(reason,relPath){super(`path ${JSON.stringify(relPath)} ${reason}`),this.name="FileStoreError",this.reason=reason,this.relPath=relPath}};FileStoreError.ESCAPES_ROOT="escapes the store root";FileStoreError.IS_A_SYMLINK="is a symlink";FileStoreError.NOT_A_FILE="is not a regular file";FileStoreError.NOT_A_DIRECTORY="is not a directory";FileStoreError.NOT_UTF8="is not valid utf-8";FileStoreError.MOVE_DESTINATION_EXISTS="already exists";function isPathLegal(p){return p.startsWith("/")&&!p.split("/").includes("..")}var FileStore=class _FileStore{constructor(root,removedOnDispose,utf8Only=!1){this.hashes=new Map,this.rootPath=root,this.removedOnDispose=removedOnDispose,this.decoder=utf8Only?new TextDecoder("utf-8",{fatal:!0}):void 0}static async open(root,opts){if(!platformSupported())throw new Error("FileStore requires O_NOFOLLOW support on this platform");let removedOnDispose=!1;try{await fsp.lstat(root)}catch(e){if(e.code!=="ENOENT")throw e;removedOnDispose=!0}return new _FileStore(path.resolve(root),removedOnDispose,opts?.utf8??!1)}async createRoot(){await makeDirAndAncestors(this.rootPath)}root(){return{path:this.rootPath,removedOnDispose:this.removedOnDispose}}async dispose(){this.removedOnDispose&&await fsp.rm(this.rootPath,{recursive:!0,force:!0})}async put(relPath,data,opts){let tail=relPath.replace(/\\/g,"/");if(tail.endsWith("/")||tail.endsWith("/.")||tail===""||tail===".")throw new FileStoreError(FileStoreError.NOT_A_FILE,relPath);let dest=this.resolveUnderRoot(relPath),payload=typeof data=="string"?encodeUTF8(data):data;this.requireUtf8(relPath,payload),await makeDirsBelowRoot(this.rootPath,path.dirname(dest)),await replaceViaTemp(dest,payload,opts?.executable??!1)}async get(relPath){let dest=this.resolveUnderRoot(relPath),handle;try{handle=await openRegularFile(relPath,dest)}catch(e){if(e.code==="ENOENT")return null;throw e}let data;try{let buf=await handle.readFile();data=new Uint8Array(buf.buffer,buf.byteOffset,buf.byteLength)}finally{await handle.close()}return this.requireUtf8(relPath,data),data}async ls(under="/"){let base=this.resolveUnderRoot(under);return new Set((await filenamesInDir(this.rootPath,under,base)).map(([rel])=>rel))}async findSymlinks(under="/"){let base=this.resolveUnderRoot(under);return symlinksInDir(this.rootPath,under,base)}async hashtree(under="/"){let base=this.resolveUnderRoot(under),walkStartNs=_internals.nowNs(),out=Object.create(null);for(let[rel,full]of await filenamesInDir(this.rootPath,under,base)){let sha=await this.hashViaCache(rel,full,walkStartNs);sha!==null&&(out[rel]=sha)}return out}async hashFile(relPath){let dest=this.resolveUnderRoot(relPath),st;try{st=await fsp.lstat(dest,{bigint:!0})}catch(e){if(e.code==="ENOENT")return null;throw e}if(st.isSymbolicLink())throw new FileStoreError(FileStoreError.IS_A_SYMLINK,relPath);if(!st.isFile())throw new FileStoreError(FileStoreError.NOT_A_FILE,relPath);let rel=path.relative(this.rootPath,dest).split(path.sep).join("/");return this.hashViaCache(rel,dest,_internals.nowNs())}async move(src,dst){let s=this.resolveUnderRoot(src),d=this.resolveUnderRoot(dst);if(s===this.rootPath||d===this.rootPath)return;if(await fsp.stat(d).then(()=>!0,()=>!1))throw new FileStoreError(FileStoreError.MOVE_DESTINATION_EXISTS,dst);await makeDirsBelowRoot(this.rootPath,path.dirname(d)),await fsp.rename(s,d)}async remove(relPath){let dest=this.resolveUnderRoot(relPath);if(dest===this.rootPath)return;let st;try{st=await fsp.lstat(dest,{bigint:!0})}catch(e){if(e.code==="ENOENT")return;throw e}if(st.isDirectory())await fsp.rm(dest,{recursive:!0,force:!0});else try{await fsp.unlink(dest)}catch(e){if(e.code!=="ENOENT")throw e}}resolveUnderRoot(relPath){let norm=relPath.replace(/\\/g,"/").replace(/^\/+/,""),parts=norm.split("/").filter(p=>p!==""&&p!==".");if(path.posix.isAbsolute(norm)||parts.includes(".."))throw new FileStoreError(FileStoreError.ESCAPES_ROOT,relPath);return parts.length===0?this.rootPath:path.join(this.rootPath,...parts)}requireUtf8(relPath,data){if(this.decoder)try{this.decoder.decode(data)}catch{throw new FileStoreError(FileStoreError.NOT_UTF8,relPath)}}async hashViaCache(rel,full,walkStartNs){let st;try{st=await fsp.lstat(full,{bigint:!0})}catch(e){if(e.code==="ENOENT")return null;throw e}if(!st.isFile())return null;let cached=this.hashes.get(rel),sha;if(cached!==void 0&&unchangedSinceHashed(cached,st))sha=cached.sha;else try{sha=await _internals.hashFile(full)}catch(e){let code=e.code;if(code==="ENOENT"||e instanceof FileStoreError||code==="ELOOP"||code==="EMLINK")return null;throw e}return oldEnoughToCache(st,walkStartNs)&&this.hashes.set(rel,{mtimeNs:st.mtimeNs,ctimeNs:st.ctimeNs,size:st.size,sha}),sha}};FileStore.isPathLegal=isPathLegal;function platformSupported(){return O_NOFOLLOW!==0}async function makeDirAndAncestors(dir){let missing=[],current=dir;for(;;){try{await fsp.stat(current);break}catch(e){let code=e.code;if(code!=="ENOENT"&&code!=="ENOTDIR"&&code!=="ELOOP")throw e}missing.push(current);let parent=path.dirname(current);if(parent===current)break;current=parent}for(let directory of missing.reverse())try{await fsp.mkdir(directory,{mode:OWNER_ONLY_DIR_MODE})}catch(e){if(e.code!=="EEXIST")throw e}}async function makeDirsBelowRoot(root,dir){let below=path.relative(root,dir);if(below==="")return;let current=root;for(let part of below.split(path.sep)){current=path.join(current,part);try{await fsp.mkdir(current,{mode:OWNER_ONLY_DIR_MODE})}catch(e){if(e.code!=="EEXIST")throw e}}}async function replaceViaTemp(dest,data,isExecutable){let mode=isExecutable?OWNER_ONLY_EXEC_MODE:OWNER_ONLY_FILE_MODE,tmp=path.join(path.dirname(dest),`.fs-${crypto.randomBytes(8).toString("hex")}.tmp`),handle;try{handle=await fsp.open(tmp,C.O_WRONLY|C.O_CREAT|C.O_EXCL|O_NOFOLLOW,mode),await handle.writeFile(data),await handle.close(),handle=void 0,await fsp.rename(tmp,dest)}catch(err){throw handle&&await handle.close().catch(()=>{}),await fsp.unlink(tmp).catch(()=>{}),err}}async function openRegularFile(relPath,dest){let handle;try{handle=await fsp.open(dest,C.O_RDONLY|O_NOFOLLOW|O_NONBLOCK)}catch(e){let code=e.code;throw code==="ELOOP"||code==="EMLINK"?new FileStoreError(FileStoreError.IS_A_SYMLINK,relPath):e}try{if(!(await handle.stat()).isFile())throw new FileStoreError(FileStoreError.NOT_A_FILE,relPath)}catch(e){throw await handle.close().catch(()=>{}),e}return handle}async function hashFile(full){let digest=crypto.createHash("sha256"),handle=await openRegularFile(path.basename(full),full),buf=new Uint8Array(1024*1024);try{for(;;){let{bytesRead}=await handle.read(buf,0,buf.length);if(bytesRead===0)break;digest.update(buf.subarray(0,bytesRead))}}finally{await handle.close()}return digest.digest("hex")}async function filenamesInDir(root,under,base){if(!await requireDir(under,base))return[];let out=[];return await walk(base,(full,entry)=>{entry.isFile()&&out.push([path.relative(root,full).split(path.sep).join("/"),full])}),out.sort(),out}async function symlinksInDir(root,under,base){let relOf=full=>path.relative(root,full).split(path.sep).join("/"),st;try{st=await fsp.lstat(base,{bigint:!0})}catch(e){let code=e.code;if(code==="ENOENT"||code==="ENOTDIR")return new Set;throw e}if(st.isSymbolicLink())return new Set([relOf(base)]);if(!st.isDirectory())throw new FileStoreError(FileStoreError.NOT_A_DIRECTORY,under);let out=new Set;return await walk(base,(full,entry)=>{entry.isSymbolicLink()&&out.add(relOf(full))}),out}async function requireDir(under,base){let st;try{st=await fsp.lstat(base,{bigint:!0})}catch(e){let code=e.code;if(code==="ENOENT"||code==="ENOTDIR")return!1;throw e}if(!st.isDirectory())throw new FileStoreError(FileStoreError.NOT_A_DIRECTORY,under);return!0}async function walk(base,visit){let stack=[base];for(;stack.length;){let dir=stack.pop(),entries;try{entries=await fsp.readdir(dir,{withFileTypes:!0})}catch(e){if(e.code==="ENOENT")continue;throw e}for(let entry of entries){let full=path.join(dir,entry.name);visit(full,entry),entry.isDirectory()&&!entry.isSymbolicLink()&&stack.push(full)}}}function unchangedSinceHashed(cached,st){return st.mtimeNs===cached.mtimeNs&&st.ctimeNs===cached.ctimeNs&&st.size===cached.size}function oldEnoughToCache(st,walkStartNs){return(st.mtimeNs>st.ctimeNs?st.mtimeNs:st.ctimeNs)<walkStartNs-_internals.timestampTrustMarginNs}var TIMESTAMP_TRUST_MARGIN_NS=2000000000n,_internals={hashFile,timestampTrustMarginNs:TIMESTAMP_TRUST_MARGIN_NS,nowNs:()=>BigInt(Date.now())*1000000n},LocalFileStore=FileStore,asyncDispose=Symbol.asyncDispose;asyncDispose&&Object.defineProperty(FileStore.prototype,asyncDispose,{value:FileStore.prototype.dispose,configurable:!0,writable:!0});var _SessionMemoryStores_instances,_SessionMemoryStores_client,_SessionMemoryStores_workdir,_SessionMemoryStores_syncIntervalMs,_SessionMemoryStores_syncDeletions,_SessionMemoryStores_log,_SessionMemoryStores_lastSyncAt,_SessionMemoryStores_finished,_SessionMemoryStores_stores,_SessionMemoryStores_storeRoot,_SessionMemoryStores_scanMarker,_SessionMemoryStores_syncStore,_SessionMemoryStores_flushStore,_SessionMemoryStores_recover,_SessionMemoryStores_stampAndPull,_SessionMemoryStores_syncPath,_SessionMemoryStores_removeLocal,_SessionMemoryStores_write,_SessionMemoryStores_pullAll,_SessionMemoryStores_uploadAll,_SessionMemoryStores_listMemories,_SessionMemoryStores_upload,_SessionMemoryStores_corroboratedDelete,_SessionMemoryStores_deleteRemote,MEMORY_FLUSH_TIMEOUT_MS=3e4,MARKER_PATH=".anthropic-memory-store",MARKER_VERSION=1;function markerSha(memoryStoreId){return crypto.createHash("sha256").update(`version ${MARKER_VERSION}
6
+ ${memoryStoreId}`,"utf-8").digest("hex")}var DELETE_CORROBORATION_MS=3e4,LIST_PAGE_SIZE=100,FULL_LIST_PAGE_SIZE=20,FETCH_CONCURRENCY=16,UPLOAD_CONCURRENCY=32,DELETE_CAP_FLOOR=8,DELETE_CAP_CEILING=50,SessionMemoryError=class extends AnthropicError{constructor(message,cause){super(message),this.name="SessionMemoryError",cause!==void 0&&(this.cause=cause)}},DeletePass=class{constructor(mode,cap,waiveWindow){this.mode=mode,this.cap=cap,this.waiveWindow=waiveWindow,this.attempted=0,this.capped=0,this.suppressed=0}takeSlot(){return this.attempted>=this.cap?(this.capped++,!1):(this.attempted++,!0)}},SessionMemoryStores=class{constructor(client,opts){_SessionMemoryStores_instances.add(this),_SessionMemoryStores_client.set(this,void 0),_SessionMemoryStores_workdir.set(this,void 0),_SessionMemoryStores_syncIntervalMs.set(this,void 0),_SessionMemoryStores_syncDeletions.set(this,void 0),_SessionMemoryStores_log.set(this,void 0),_SessionMemoryStores_lastSyncAt.set(this,void 0),_SessionMemoryStores_finished.set(this,!1),_SessionMemoryStores_stores.set(this,[]),__classPrivateFieldSet(this,_SessionMemoryStores_client,client,"f"),__classPrivateFieldSet(this,_SessionMemoryStores_workdir,opts.workdir,"f"),__classPrivateFieldSet(this,_SessionMemoryStores_syncIntervalMs,opts.syncIntervalMs??DEFAULT_MEMORY_SYNC_INTERVAL_MS,"f"),checkMemorySyncInterval(__classPrivateFieldGet(this,_SessionMemoryStores_syncIntervalMs,"f"),"syncIntervalMs"),__classPrivateFieldSet(this,_SessionMemoryStores_syncDeletions,opts.syncDeletions??"enabled","f"),__classPrivateFieldSet(this,_SessionMemoryStores_log,loggerFor(client),"f"),__classPrivateFieldSet(this,_SessionMemoryStores_lastSyncAt,Date.now(),"f")}get roots(){return __classPrivateFieldGet(this,_SessionMemoryStores_stores,"f").map(s=>s.files.root().path)}get readOnlyRoots(){return __classPrivateFieldGet(this,_SessionMemoryStores_stores,"f").filter(s=>s.readOnly).map(s=>s.files.root().path)}async download(session){for(let resource of session.resources){if(resource.type!=="memory_store")continue;let root=__classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_storeRoot).call(this,resource),store;try{if(store={memoryStoreId:resource.memory_store_id,files:await LocalFileStore.open(root,{utf8:!0}),readOnly:resource.access==="read_only",baseline:new Map,refusedShas:new Map,pendingDeletes:new Map},!store.files.root().removedOnDispose)throw new SessionMemoryError(`something already exists at the memory store's path: ${root} (memory_store_id=${resource.memory_store_id}); it must not exist when the session starts`);try{await store.files.createRoot()}catch(e){throw isErrno(e)?new SessionMemoryError(`cannot create the memory store's folder: ${root} (memory_store_id=${resource.memory_store_id}): ${e}; the worker host must make this mount path writable`,e):e}await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_stampAndPull).call(this,store),__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").info("downloaded memories",{count:store.baseline.size,memory_store_id:store.memoryStoreId,dest:store.files.root().path}),__classPrivateFieldGet(this,_SessionMemoryStores_stores,"f").push(store)}catch(e){throw store&&await store.files.dispose().catch(()=>{}),e instanceof SessionMemoryError?e:new SessionMemoryError(`failed to download memory store memory_store_id=${resource.memory_store_id}: ${e}`,e)}}__classPrivateFieldSet(this,_SessionMemoryStores_lastSyncAt,Date.now(),"f")}async finish(){if(__classPrivateFieldGet(this,_SessionMemoryStores_finished,"f"))throw new AnthropicError("finish() was already called: it is the session's last sync and runs once");__classPrivateFieldSet(this,_SessionMemoryStores_finished,!0,"f"),await this.syncAll(!0)}async syncAll(final){await Promise.all(__classPrivateFieldGet(this,_SessionMemoryStores_stores,"f").map(store=>__classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_syncStore).call(this,store,final))),__classPrivateFieldSet(this,_SessionMemoryStores_lastSyncAt,Date.now(),"f")}async syncIfDue(){Date.now()-__classPrivateFieldGet(this,_SessionMemoryStores_lastSyncAt,"f")<__classPrivateFieldGet(this,_SessionMemoryStores_syncIntervalMs,"f")||await this.syncAll(!1)}async flushWrites(signal){await Promise.all(__classPrivateFieldGet(this,_SessionMemoryStores_stores,"f").map(store=>__classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_flushStore).call(this,store,signal)))}async dispose(){for(let store of __classPrivateFieldGet(this,_SessionMemoryStores_stores,"f")){let root=store.files.root();try{let scan=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_scanMarker).call(this,store);if(!scan.markerOk&&Object.keys(scan.files).length>0){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`${scan.distrustReason}; leaving the memory store folder on disk`,{root:root.path,memory_store_id:store.memoryStoreId});continue}await store.files.dispose()}catch(e){if(!(e instanceof FileStoreError)&&!isErrno(e))throw e;__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to remove the memory store folder",{root:store.files.root().path,memory_store_id:store.memoryStoreId,error:String(e)});continue}root.removedOnDispose&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").info("removed memory store dir",{dest:root.path,memory_store_id:store.memoryStoreId})}}};_SessionMemoryStores_client=new WeakMap,_SessionMemoryStores_workdir=new WeakMap,_SessionMemoryStores_syncIntervalMs=new WeakMap,_SessionMemoryStores_syncDeletions=new WeakMap,_SessionMemoryStores_log=new WeakMap,_SessionMemoryStores_lastSyncAt=new WeakMap,_SessionMemoryStores_finished=new WeakMap,_SessionMemoryStores_stores=new WeakMap,_SessionMemoryStores_instances=new WeakSet,_SessionMemoryStores_storeRoot=function(resource){if(resource.mount_path){if(!isPathLegal(resource.mount_path))throw new SessionMemoryError(`memory store mount_path is not a clean absolute path: ${JSON.stringify(resource.mount_path)} (memory_store_id=${resource.memory_store_id})`);return resource.mount_path}return path.join(__classPrivateFieldGet(this,_SessionMemoryStores_workdir,"f"),"memory",resource.name||resource.memory_store_id)},_SessionMemoryStores_scanMarker=async function(store){let local=await store.files.hashtree(),marker=local[MARKER_PATH];return delete local[MARKER_PATH],marker===markerSha(store.memoryStoreId)?{files:local,markerOk:!0,distrustReason:null}:{files:local,markerOk:!1,distrustReason:marker!==void 0?"the marker file does not match this store":"the marker file is gone"}},_SessionMemoryStores_syncStore=async function(store,final){try{let scan=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_scanMarker).call(this,store),local=scan.files;if(!scan.markerOk){if(Object.keys(local).length>0){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`${scan.distrustReason}; leaving the memory store folder as found and not syncing`,{root:store.files.root().path,memory_store_id:store.memoryStoreId});return}await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_recover).call(this,store,"the folder or its marker is gone");return}if(Object.keys(local).length===0&&store.baseline.size>1){await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_recover).call(this,store,"every memory file is gone at once");return}let remote=new Map;for await(let[rel,item]of __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_listMemories).call(this,store.memoryStoreId))remote.set(rel,item);let deletes=new DeletePass(__classPrivateFieldGet(this,_SessionMemoryStores_syncDeletions,"f"),Math.max(DELETE_CAP_FLOOR,Math.min(DELETE_CAP_CEILING,Math.floor(store.baseline.size/4))),final),pulls=[],baseline=new Map,paths=[...new Set([...remote.keys(),...Object.keys(local),...store.baseline.keys()])].sort();for(let rel of paths){let remoteItem=remote.get(rel),localSha=local[rel],baseSha=store.baseline.get(rel),sha;localSha===void 0&&baseSha!==void 0&&remoteItem!==void 0&&remoteItem.content_sha256===baseSha&&!store.readOnly?sha=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_corroboratedDelete).call(this,store,rel,remoteItem,baseSha,deletes):sha=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_syncPath).call(this,store,rel,remoteItem,localSha,pulls),sha!==void 0&&baseline.set(rel,sha)}store.baseline=baseline,await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_pullAll).call(this,store,pulls),deletes.suppressed>0&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").debug("remote deletes are disabled; locally deleted memories stay on the server",{count:deletes.suppressed,memory_store_id:store.memoryStoreId}),deletes.capped>0&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`delete cap reached: ${deletes.mode==="log_only"?"would send":"sent"} ${deletes.attempted} deletes, held ${deletes.capped} for later syncs`,{memory_store_id:store.memoryStoreId})}catch(e){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory sync failed",{memory_store_id:store.memoryStoreId,error:String(e)})}},_SessionMemoryStores_flushStore=async function(store,signal){let dirty=new Map,unsent=new Set,push=async()=>{if(store.readOnly)return;let scan=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_scanMarker).call(this,store);if(!scan.markerOk){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`${scan.distrustReason}; not uploading anything from the memory store folder`,{root:store.files.root().path,memory_store_id:store.memoryStoreId});return}for(let[rel,sha]of Object.entries(scan.files))sha!==store.baseline.get(rel)&&store.refusedShas.get(rel)!==sha&&(dirty.set(rel,sha),unsent.add(rel));if(dirty.size===0||signal?.aborted)return;let remote=new Map;for await(let[rel,item]of __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_listMemories).call(this,store.memoryStoreId)){if(signal?.aborted)return;remote.set(rel,item)}let uploads=[];for(let rel of[...dirty.keys()].sort()){let localSha=dirty.get(rel),baseSha=store.baseline.get(rel),existing=remote.get(rel);if(existing!==void 0&&existing.content_sha256===localSha){store.baseline.set(rel,existing.content_sha256),unsent.delete(rel);continue}if(existing!==void 0&&existing.content_sha256!==baseSha){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory changed both locally and remotely; the flush leaves the remote version",{path:rel,memory_store_id:store.memoryStoreId}),unsent.delete(rel);continue}uploads.push([rel,localSha,existing])}await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_uploadAll).call(this,store,uploads,unsent,signal)};try{await settledOrAborted(push(),signal),signal?.aborted&&unsent.size>0&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`memory flush cut off part-way; ${unsent.size} of ${dirty.size} changed files had not finished uploading`,{memory_store_id:store.memoryStoreId})}catch(e){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory flush failed",{memory_store_id:store.memoryStoreId,error:String(e)})}},_SessionMemoryStores_recover=async function(store,reason){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn(`${reason}; re-downloading the memory store folder instead of syncing`,{root:store.files.root().path,memory_store_id:store.memoryStoreId}),await store.files.createRoot(),await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_stampAndPull).call(this,store)},_SessionMemoryStores_stampAndPull=async function(store){store.baseline=new Map,store.pendingDeletes.clear(),await store.files.put(MARKER_PATH,`version ${MARKER_VERSION}
7
+ ${store.memoryStoreId}`);for await(let[rel,item]of __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_listMemories).call(this,store.memoryStoreId,"full"))await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_write).call(this,store,rel,item.content??"")&&store.baseline.set(rel,item.content_sha256)},_SessionMemoryStores_syncPath=async function(store,rel,remote,localSha,pulls){let baseSha=store.baseline.get(rel);if(localSha!==void 0&&store.pendingDeletes.delete(rel),!remote){if(localSha===void 0){store.pendingDeletes.delete(rel);return}if(baseSha!==void 0){if(localSha===baseSha){let fresh=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_removeLocal).call(this,store,rel,baseSha);if(fresh===void 0)return;if(fresh===baseSha)return baseSha;localSha=fresh}store.readOnly?__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory deleted remotely but edited locally; keeping the file, which a read-only store cannot push",{path:rel,memory_store_id:store.memoryStoreId}):store.refusedShas.get(rel)!==localSha&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").info("memory deleted remotely but edited locally; re-creating it from the file",{path:rel,memory_store_id:store.memoryStoreId})}return store.readOnly||store.refusedShas.get(rel)===localSha?void 0:await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_upload).call(this,store,rel,localSha,void 0)}let remoteSha=remote.content_sha256,remoteChanged=remoteSha!==baseSha,locallyEdited=localSha!==void 0&&localSha!==baseSha&&localSha!==remoteSha,localChanged=!store.readOnly&&locallyEdited;return localSha===void 0&&baseSha!==void 0?(remoteChanged&&(__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory deleted locally but changed remotely; restoring the remote version",{path:rel,memory_store_id:store.memoryStoreId}),store.pendingDeletes.delete(rel),pulls.push([rel,remote])),baseSha):remoteChanged?localSha===remoteSha?remoteSha:(locallyEdited&&__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory changed both locally and remotely; keeping the remote version",{path:rel,memory_store_id:store.memoryStoreId}),pulls.push([rel,remote]),baseSha):localChanged?store.refusedShas.get(rel)===localSha?remoteSha:await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_upload).call(this,store,rel,localSha,remote)??remoteSha:remoteSha},_SessionMemoryStores_removeLocal=async function(store,rel,expectSha){let freshSha;try{freshSha=await store.files.hashFile(rel)}catch(e){if(!(e instanceof FileStoreError)&&!isErrno(e))throw e;return expectSha}if(freshSha!==null){if(freshSha!==expectSha)return freshSha;try{await store.files.remove(rel)}catch(e){if(!(e instanceof FileStoreError)&&!isErrno(e))throw e;return __classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to remove memory deleted remotely",{path:rel,memory_store_id:store.memoryStoreId,error:String(e)}),expectSha}}},_SessionMemoryStores_write=async function(store,rel,content){try{await store.files.put(rel,content)}catch(e){if(!(e instanceof FileStoreError)&&!isErrno(e))throw e;return __classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to write memory",{path:rel,memory_store_id:store.memoryStoreId,error:String(e)}),!1}return!0},_SessionMemoryStores_pullAll=async function(store,pulls){if(pulls.length===0)return;let pullOne=async(rel,listed)=>{let item;try{item=await __classPrivateFieldGet(this,_SessionMemoryStores_client,"f").beta.memoryStores.memories.retrieve(listed.id,{memory_store_id:store.memoryStoreId,view:"full"})}catch(e){if(isStatus(e,404))return;__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to fetch memory content",{path:rel,memory_store_id:store.memoryStoreId,error:String(e)});return}await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_write).call(this,store,rel,item.content??"")&&store.baseline.set(rel,item.content_sha256)},queue=pulls[Symbol.iterator](),worker=async()=>{for(let[rel,listed]of queue)await pullOne(rel,listed)};await Promise.all(Array.from({length:Math.min(FETCH_CONCURRENCY,pulls.length)},worker))},_SessionMemoryStores_uploadAll=async function(store,uploads,unsent,signal){let queue=uploads[Symbol.iterator](),worker=async()=>{for(let[rel,localSha,existing]of queue){if(signal?.aborted)return;let sha=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_upload).call(this,store,rel,localSha,existing);unsent.delete(rel),sha!==void 0&&store.baseline.set(rel,sha)}};await Promise.all(Array.from({length:Math.min(UPLOAD_CONCURRENCY,uploads.length)},worker))},_SessionMemoryStores_listMemories=async function*(memoryStoreId,view="basic"){let limit=view==="basic"?LIST_PAGE_SIZE:FULL_LIST_PAGE_SIZE;for await(let item of __classPrivateFieldGet(this,_SessionMemoryStores_client,"f").beta.memoryStores.memories.list(memoryStoreId,{view,limit})){if(item.type!=="memory")continue;let rel=item.path.replace(/^\/+/,"");if(rel===MARKER_PATH){__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("the server listed the reserved marker path; skipping",{path:item.path,memory_store_id:memoryStoreId});continue}yield[rel,item]}},_SessionMemoryStores_upload=async function _SessionMemoryStores_upload2(store,rel,localSha,existing){try{let data=await store.files.get(rel);if(data===null)return;let content=decodeUTF8(data),item=existing?await __classPrivateFieldGet(this,_SessionMemoryStores_client,"f").beta.memoryStores.memories.update(existing.id,{memory_store_id:store.memoryStoreId,content,precondition:{type:"content_sha256",content_sha256:existing.content_sha256}}):await __classPrivateFieldGet(this,_SessionMemoryStores_client,"f").beta.memoryStores.memories.create(store.memoryStoreId,{path:"/"+rel,content});return store.refusedShas.delete(rel),item.content_sha256}catch(e){if(existing&&isStatus(e,404))return await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_upload2).call(this,store,rel,localSha,void 0);let permanent=e instanceof FileStoreError||isStatus(e,400)||isStatus(e,413);existing&&isStatus(e,409)?__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory changed both locally and remotely; the upload was refused and the local edit loses",{path:rel,memory_store_id:store.memoryStoreId}):permanent&&localSha!==void 0?(store.refusedShas.set(rel,localSha),__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("the server rejected this memory file, so it stays un-synced until its content changes",{path:rel,memory_store_id:store.memoryStoreId,rejection:String(e)})):__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to upload memory",{path:rel,memory_store_id:store.memoryStoreId,error:String(e)});return}},_SessionMemoryStores_corroboratedDelete=async function(store,rel,remote,baseSha,deletes){if(deletes.mode==="disabled")return deletes.suppressed++,baseSha;let firstAbsent=store.pendingDeletes.get(rel);if(firstAbsent===void 0&&(firstAbsent=Date.now(),store.pendingDeletes.set(rel,firstAbsent)),!deletes.waiveWindow&&Date.now()-firstAbsent<DELETE_CORROBORATION_MS)return baseSha;let markerOk,stillAbsent;try{markerOk=await store.files.hashFile(MARKER_PATH)===markerSha(store.memoryStoreId),stillAbsent=await store.files.hashFile(rel)===null}catch(e){if(!(e instanceof FileStoreError)&&!isErrno(e))throw e;markerOk=stillAbsent=!1}if(!markerOk)return baseSha;if(!stillAbsent)return store.pendingDeletes.delete(rel),baseSha;if(!deletes.takeSlot())return baseSha;if(deletes.mode==="log_only")return __classPrivateFieldGet(this,_SessionMemoryStores_log,"f").info("log-only: sync would delete this memory on the server",{path:rel,memory_store_id:store.memoryStoreId}),baseSha;let sha=await __classPrivateFieldGet(this,_SessionMemoryStores_instances,"m",_SessionMemoryStores_deleteRemote).call(this,store,rel,remote,baseSha);return sha===void 0&&store.pendingDeletes.delete(rel),sha},_SessionMemoryStores_deleteRemote=async function(store,rel,remote,baseSha){try{await __classPrivateFieldGet(this,_SessionMemoryStores_client,"f").beta.memoryStores.memories.delete(remote.id,{memory_store_id:store.memoryStoreId,expected_content_sha256:baseSha})}catch(e){return isStatus(e,404)?void 0:(isStatus(e,409)||isStatus(e,412)?__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("memory deleted locally but changed remotely; keeping the remote version",{path:rel,memory_store_id:store.memoryStoreId}):__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").warn("failed to delete memory",{path:rel,memory_store_id:store.memoryStoreId,error:String(e)}),baseSha)}__classPrivateFieldGet(this,_SessionMemoryStores_log,"f").info("propagated local deletion",{path:rel,memory_store_id:store.memoryStoreId})};function isErrno(e){return typeof e=="object"&&e!==null&&typeof e.code=="string"}async function settledOrAborted(p,signal){if(!signal){await p;return}let onAbort,aborted=new Promise(resolve2=>{onAbort=resolve2,signal.aborted&&resolve2()});signal.addEventListener("abort",onAbort,{once:!0});try{await Promise.race([p,aborted])}finally{signal.removeEventListener("abort",onAbort)}}var _BashSession_instances,_BashSession_proc,_BashSession_buf,_BashSession_truncated,_BashSession_closed,_BashSession_waiting,_BashSession_append,_LineRangeCollector_instances,_LineRangeCollector_filePath,_LineRangeCollector_startLine,_LineRangeCollector_endLine,_LineRangeCollector_start,_LineRangeCollector_end,_LineRangeCollector_limit,_LineRangeCollector_line,_LineRangeCollector_collected,_LineRangeCollector_collectedBytes,_LineRangeCollector_collect,_LineRangeCollector_overLimitError,BASH_OUTPUT_LIMIT=100*1024,BASH_DEFAULT_TIMEOUT_MS=12e4,DEFAULT_MAX_FILE_BYTES=256*1024,READ_STREAM_CHUNK_BYTES=64*1024,NEWLINE=Buffer.from(`
8
+ `),GREP_OUTPUT_LIMIT=100*1024,GREP_MAX_LINE_LENGTH=2e3,GLOB_RESULT_LIMIT=200,BashTimeoutError=class extends AnthropicError{constructor(timeoutMs){super(`bash command timed out after ${timeoutMs}ms`),this.name="BashTimeoutError",this.timeoutMs=timeoutMs}},ANSI_RE=/\x1b\[[0-9;?]*[ -/]*[@-~]/g,fsGlob=fs4.glob;function resolveMaxBytes(configured){return configured===void 0?DEFAULT_MAX_FILE_BYTES:configured}function rejectUnrestrictedPaths(value){if(value!==void 0)throw new AnthropicError("The `unrestrictedPaths` option you passed to the agent toolset (AgentToolContext) is no longer supported. The toolset's file tools (read, write, edit, glob, grep) are now always confined to the working directory plus the directories listed in `allowedRoots`. Remove `unrestrictedPaths` from your context; to let the file tools reach any other directory, add it to `allowedRoots`.")}function betaAgentToolset20260401(ctx){return[betaBashTool(ctx),betaReadTool(ctx),betaWriteTool(ctx),betaEditTool(ctx),betaGlobTool(ctx),betaGrepTool(ctx)]}async function resolvePath(ctx,p){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),confineToRoot(ctx.workdir,p,{allowedRoots:ctx.allowedRoots??[]})}function readOnlyRootFor(ctx,target){return containingRoot(ctx.readOnlyRoots??[],target)}function scrubbedShellEnv(){let env={};for(let[key,value]of Object.entries(process.env))key.startsWith("ANTHROPIC_")||(env[key]=value);return env}var BashSession=class{constructor(dir,env=scrubbedShellEnv()){_BashSession_instances.add(this),_BashSession_proc.set(this,void 0),_BashSession_buf.set(this,""),_BashSession_truncated.set(this,!1),_BashSession_closed.set(this,!1),_BashSession_waiting.set(this,null),__classPrivateFieldSet(this,_BashSession_proc,cp.spawn("/bin/bash",["--noprofile","--norc"],{cwd:dir,env:{...env,PS1:"",PS2:"",TERM:"dumb"},stdio:["pipe","pipe","pipe"],detached:!0}),"f"),__classPrivateFieldGet(this,_BashSession_proc,"f").stdout.setEncoding("utf8"),__classPrivateFieldGet(this,_BashSession_proc,"f").stderr.setEncoding("utf8"),__classPrivateFieldGet(this,_BashSession_proc,"f").stdout.on("data",d=>__classPrivateFieldGet(this,_BashSession_instances,"m",_BashSession_append).call(this,d)),__classPrivateFieldGet(this,_BashSession_proc,"f").stderr.on("data",d=>__classPrivateFieldGet(this,_BashSession_instances,"m",_BashSession_append).call(this,d)),__classPrivateFieldGet(this,_BashSession_proc,"f").once("close",()=>{__classPrivateFieldSet(this,_BashSession_closed,!0,"f");let w=__classPrivateFieldGet(this,_BashSession_waiting,"f");__classPrivateFieldSet(this,_BashSession_waiting,null,"f"),w?.resolve()})}get closed(){return __classPrivateFieldGet(this,_BashSession_closed,"f")}async exec(command,opts={}){if(__classPrivateFieldGet(this,_BashSession_closed,"f"))throw new AnthropicError("bash session terminated");let timeoutMs=opts.timeoutMs??BASH_DEFAULT_TIMEOUT_MS,signal=opts.signal;signal?.throwIfAborted(),__classPrivateFieldSet(this,_BashSession_buf,"","f"),__classPrivateFieldSet(this,_BashSession_truncated,!1,"f");let sentinel=`__ANT_CMD_${crypto2.randomUUID()}_DONE__`,sentinelSplit=`${sentinel.slice(0,8)}''${sentinel.slice(8)}`,wrapped=`{ ${command}
9
+ } </dev/null 2>&1; printf '\\n${sentinelSplit}%d\\n' $?
10
+ `;if(__classPrivateFieldGet(this,_BashSession_proc,"f").stdin.write(wrapped),__classPrivateFieldGet(this,_BashSession_buf,"f").indexOf(sentinel)<0){let{promise:sentinelSeen,resolve:resolve2}=promiseWithResolvers();__classPrivateFieldSet(this,_BashSession_waiting,{sentinel,resolve:resolve2},"f");let timer,onAbort;try{await Promise.race([sentinelSeen,new Promise((_,reject)=>{timer=setTimeout(()=>reject(new BashTimeoutError(timeoutMs)),timeoutMs)}),new Promise((_,reject)=>{signal&&(onAbort=()=>reject(signal.reason),signal.addEventListener("abort",onAbort,{once:!0}))})])}finally{timer&&clearTimeout(timer),onAbort&&signal&&signal.removeEventListener("abort",onAbort),__classPrivateFieldSet(this,_BashSession_waiting,null,"f")}}let idx=__classPrivateFieldGet(this,_BashSession_buf,"f").indexOf(sentinel);if(idx<0)throw new AnthropicError("bash session terminated");let m=__classPrivateFieldGet(this,_BashSession_buf,"f").slice(idx+sentinel.length).match(/^(-?\d+)/),exitCode=m?parseInt(m[1],10):-1,out=__classPrivateFieldGet(this,_BashSession_buf,"f").slice(0,idx).replace(ANSI_RE,"").replace(/\n+$/,"");return __classPrivateFieldGet(this,_BashSession_truncated,"f")&&(out=`[output truncated]
11
+ ${out}`),{output:out,exitCode}}close(){if(__classPrivateFieldGet(this,_BashSession_closed,"f"))return;__classPrivateFieldSet(this,_BashSession_closed,!0,"f");let w=__classPrivateFieldGet(this,_BashSession_waiting,"f");__classPrivateFieldSet(this,_BashSession_waiting,null,"f"),w?.resolve(),__classPrivateFieldGet(this,_BashSession_proc,"f").stdout.destroy(),__classPrivateFieldGet(this,_BashSession_proc,"f").stderr.destroy(),__classPrivateFieldGet(this,_BashSession_proc,"f").stdin.destroy();try{process.kill(-__classPrivateFieldGet(this,_BashSession_proc,"f").pid,"SIGKILL")}catch{__classPrivateFieldGet(this,_BashSession_proc,"f").kill("SIGKILL")}__classPrivateFieldGet(this,_BashSession_proc,"f").unref()}};_BashSession_proc=new WeakMap,_BashSession_buf=new WeakMap,_BashSession_truncated=new WeakMap,_BashSession_closed=new WeakMap,_BashSession_waiting=new WeakMap,_BashSession_instances=new WeakSet,_BashSession_append=function(d){if(__classPrivateFieldSet(this,_BashSession_buf,__classPrivateFieldGet(this,_BashSession_buf,"f")+d,"f"),__classPrivateFieldGet(this,_BashSession_buf,"f").length>BASH_OUTPUT_LIMIT&&(__classPrivateFieldSet(this,_BashSession_buf,__classPrivateFieldGet(this,_BashSession_buf,"f").slice(__classPrivateFieldGet(this,_BashSession_buf,"f").length-BASH_OUTPUT_LIMIT),"f"),__classPrivateFieldSet(this,_BashSession_truncated,!0,"f")),__classPrivateFieldGet(this,_BashSession_waiting,"f")&&__classPrivateFieldGet(this,_BashSession_buf,"f").indexOf(__classPrivateFieldGet(this,_BashSession_waiting,"f").sentinel)>=0){let w=__classPrivateFieldGet(this,_BashSession_waiting,"f");__classPrivateFieldSet(this,_BashSession_waiting,null,"f"),w.resolve()}};function betaBashTool(ctx){rejectUnrestrictedPaths(ctx.unrestrictedPaths);let session,tail=Promise.resolve();return betaTool({name:"bash",description:"Run a bash command in a persistent shell. State (cwd, env vars) persists across calls.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to run"},restart:{type:"boolean",description:"Restart the persistent shell before running"},timeout_ms:{type:"integer",description:"Per-call timeout in milliseconds"}}},run:async({command,restart,timeout_ms},context)=>{let prev=tail,gate=promiseWithResolvers();tail=gate.promise;try{await prev}catch{}try{if(restart&&(session?.close(),session=void 0),!command){if(restart)return"bash session restarted";throw new ToolError("bash: command is required")}session??(session=new BashSession(ctx.workdir,ctx.env));try{let{output,exitCode}=await session.exec(command,{timeoutMs:timeout_ms??BASH_DEFAULT_TIMEOUT_MS,signal:context?.signal});if(exitCode!==0)throw new ToolError(output||`exit ${exitCode}`);return output}catch(e){throw e instanceof ToolError?e:(session.close(),session=void 0,new ToolError(`bash: ${e instanceof Error?e.message:String(e)}`))}}finally{gate.resolve()}},close:()=>{session?.close(),session=void 0}})}function betaReadTool(ctx){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),betaTool({name:"read",description:"Read a UTF-8 text file relative to the workdir.",inputSchema:{type:"object",properties:{file_path:{type:"string"},view_range:{type:"array",items:{type:"integer"},description:"[start_line, end_line] 1-indexed inclusive"}},required:["file_path"]},run:async({file_path,view_range})=>{if(!file_path)throw new ToolError("read: file_path is required");let abs=await resolvePath(ctx,file_path);if(view_range?.length&&view_range.length!==2)throw new ToolError("read: view_range must be [start_line, end_line]");let data;try{let st=await fs4.stat(abs);if(!st.isFile())throw new ToolError(`read: ${file_path} is not a regular file`);let limit=resolveMaxBytes(ctx.maxFileBytes);if(limit!==null&&st.size>limit){if(!view_range?.length)throw new ToolError(`read: ${file_path} is ${st.size} bytes, exceeds ${limit}-byte limit. Use the view_range parameter to read specific line ranges, e.g. view_range: [1, 500].`);let[startLine2,endLine2]=view_range;return await readRangeStreaming(abs,file_path,startLine2,endLine2,limit)}data=await fs4.readFile(abs,"utf8")}catch(e){throw e instanceof ToolError?e:new ToolError(`read: ${fsErrorMessage(e,file_path)}`)}if(!view_range?.length)return data;let[startLine,endLine]=view_range,lines=data.split(`
12
+ `),start=Math.max(0,startLine-1),end=endLine>0?endLine:lines.length;return lines.slice(start,end).join(`
13
+ `)}})}async function readRangeStreaming(abs,filePath,startLine,endLine,limit){let lines=new LineRangeCollector(filePath,startLine,endLine,limit);if(lines.rangeIsEmpty())return"";let stream2=fssync.createReadStream(abs,{highWaterMark:READ_STREAM_CHUNK_BYTES});try{for await(let chunk of stream2)if(lines.collectFrom(chunk),lines.rangeIsCollected())break}finally{stream2.destroy()}return lines.text()}var LineRangeCollector=class{constructor(filePath,startLine,endLine,limit){_LineRangeCollector_instances.add(this),_LineRangeCollector_filePath.set(this,void 0),_LineRangeCollector_startLine.set(this,void 0),_LineRangeCollector_endLine.set(this,void 0),_LineRangeCollector_start.set(this,void 0),_LineRangeCollector_end.set(this,void 0),_LineRangeCollector_limit.set(this,void 0),_LineRangeCollector_line.set(this,0),_LineRangeCollector_collected.set(this,[]),_LineRangeCollector_collectedBytes.set(this,0),__classPrivateFieldSet(this,_LineRangeCollector_filePath,filePath,"f"),__classPrivateFieldSet(this,_LineRangeCollector_startLine,startLine,"f"),__classPrivateFieldSet(this,_LineRangeCollector_endLine,endLine,"f"),__classPrivateFieldSet(this,_LineRangeCollector_start,Math.max(0,startLine-1),"f"),__classPrivateFieldSet(this,_LineRangeCollector_end,endLine>0?endLine:1/0,"f"),__classPrivateFieldSet(this,_LineRangeCollector_limit,limit,"f")}rangeIsEmpty(){return __classPrivateFieldGet(this,_LineRangeCollector_end,"f")<=__classPrivateFieldGet(this,_LineRangeCollector_start,"f")}rangeIsCollected(){return __classPrivateFieldGet(this,_LineRangeCollector_line,"f")>=__classPrivateFieldGet(this,_LineRangeCollector_end,"f")}collectFrom(chunk){var _a;let lineStart=0;for(;lineStart<chunk.length&&!this.rangeIsCollected();){let newline=chunk.indexOf(10,lineStart),lineEnd=newline<0?chunk.length:newline;if(__classPrivateFieldGet(this,_LineRangeCollector_line,"f")>=__classPrivateFieldGet(this,_LineRangeCollector_start,"f")&&__classPrivateFieldGet(this,_LineRangeCollector_instances,"m",_LineRangeCollector_collect).call(this,chunk.subarray(lineStart,lineEnd),newline>=0),newline<0)break;__classPrivateFieldSet(this,_LineRangeCollector_line,(_a=__classPrivateFieldGet(this,_LineRangeCollector_line,"f"),_a++,_a),"f"),lineStart=newline+1}}text(){return Buffer.concat(__classPrivateFieldGet(this,_LineRangeCollector_collected,"f"),__classPrivateFieldGet(this,_LineRangeCollector_collectedBytes,"f")).toString("utf8")}};_LineRangeCollector_filePath=new WeakMap,_LineRangeCollector_startLine=new WeakMap,_LineRangeCollector_endLine=new WeakMap,_LineRangeCollector_start=new WeakMap,_LineRangeCollector_end=new WeakMap,_LineRangeCollector_limit=new WeakMap,_LineRangeCollector_line=new WeakMap,_LineRangeCollector_collected=new WeakMap,_LineRangeCollector_collectedBytes=new WeakMap,_LineRangeCollector_instances=new WeakSet,_LineRangeCollector_collect=function(lineBytes,newlineTerminated){if(__classPrivateFieldGet(this,_LineRangeCollector_collected,"f").push(lineBytes),__classPrivateFieldSet(this,_LineRangeCollector_collectedBytes,__classPrivateFieldGet(this,_LineRangeCollector_collectedBytes,"f")+lineBytes.length,"f"),newlineTerminated&&__classPrivateFieldGet(this,_LineRangeCollector_line,"f")+1<__classPrivateFieldGet(this,_LineRangeCollector_end,"f")&&(__classPrivateFieldGet(this,_LineRangeCollector_collected,"f").push(NEWLINE),__classPrivateFieldSet(this,_LineRangeCollector_collectedBytes,__classPrivateFieldGet(this,_LineRangeCollector_collectedBytes,"f")+NEWLINE.length,"f")),__classPrivateFieldGet(this,_LineRangeCollector_collectedBytes,"f")>__classPrivateFieldGet(this,_LineRangeCollector_limit,"f"))throw __classPrivateFieldGet(this,_LineRangeCollector_instances,"m",_LineRangeCollector_overLimitError).call(this)},_LineRangeCollector_overLimitError=function(){return __classPrivateFieldGet(this,_LineRangeCollector_end,"f")-__classPrivateFieldGet(this,_LineRangeCollector_start,"f")===1?new ToolError(`read: line ${__classPrivateFieldGet(this,_LineRangeCollector_start,"f")+1} of ${__classPrivateFieldGet(this,_LineRangeCollector_filePath,"f")} alone exceeds ${__classPrivateFieldGet(this,_LineRangeCollector_limit,"f")}-byte limit. The read tool cannot return part of a line, so view_range cannot narrow this further.`):new ToolError(`read: view_range [${__classPrivateFieldGet(this,_LineRangeCollector_startLine,"f")}, ${__classPrivateFieldGet(this,_LineRangeCollector_endLine,"f")}] of ${__classPrivateFieldGet(this,_LineRangeCollector_filePath,"f")} exceeds ${__classPrivateFieldGet(this,_LineRangeCollector_limit,"f")}-byte limit. Narrow the view_range to read a smaller portion.`)};function betaWriteTool(ctx){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),betaTool({name:"write",description:"Write a UTF-8 text file relative to the workdir, creating parent directories as needed.",inputSchema:{type:"object",properties:{file_path:{type:"string"},content:{type:"string"}},required:["file_path","content"]},run:async({file_path,content})=>{if(!file_path)throw new ToolError("write: file_path is required");let abs=await resolvePath(ctx,file_path),ro=await readOnlyRootFor(ctx,abs);if(ro!==void 0)throw new ToolError(`write: ${file_path} is inside read-only directory ${ro}`);try{await fs4.mkdir(path2.dirname(abs),{recursive:!0,mode:DIR_CREATE_MODE}),await atomicWriteFile(abs,content??"")}catch(e){throw new ToolError(`write: ${fsErrorMessage(e,file_path)}`)}return`wrote ${Buffer.byteLength(content??"")} bytes to ${file_path}`}})}function betaEditTool(ctx){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),betaTool({name:"edit",description:"Replace old_string with new_string in a file. old_string must be unique unless replace_all.",inputSchema:{type:"object",properties:{file_path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["file_path","old_string","new_string"]},run:async({file_path,old_string,new_string,replace_all})=>{if(!file_path)throw new ToolError("edit: file_path is required");if(!old_string)throw new ToolError("edit: old_string is required");let abs=await resolvePath(ctx,file_path),ro=await readOnlyRootFor(ctx,abs);if(ro!==void 0)throw new ToolError(`edit: ${file_path} is inside read-only directory ${ro}`);let data;try{let st=await fs4.stat(abs);if(!st.isFile())throw new ToolError(`edit: ${file_path} is not a regular file`);let limit=resolveMaxBytes(ctx.maxFileBytes);if(limit!==null&&st.size>limit)throw new ToolError(`edit: ${file_path} is ${st.size} bytes, exceeds ${limit}-byte limit. The edit tool loads the whole file and cannot modify a file this large.`);data=await fs4.readFile(abs,"utf8")}catch(e){throw e instanceof ToolError?e:new ToolError(`edit: ${fsErrorMessage(e,file_path)}`)}let count=data.split(old_string).length-1;if(count===0)throw new ToolError(`edit: old_string not found in ${file_path}`);let updated;if(replace_all)updated=data.split(old_string).join(new_string);else{if(count>1)throw new ToolError(`edit: old_string appears ${count} times in ${file_path} (must be unique)`);updated=data.replace(old_string,()=>new_string)}try{await atomicWriteFile(abs,updated)}catch(e){throw new ToolError(`edit: write: ${fsErrorMessage(e,file_path)}`)}return`edited ${file_path} (${replace_all?count:1} replacement(s))`}})}function patternCanAscend(pattern){return pattern.split(/[\\/{},]/).includes("..")}function betaGlobTool(ctx){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),betaTool({name:"glob",description:"Match files under the workdir against a glob pattern. Results are mtime-sorted, newest first.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string",description:"Directory to search in. Defaults to the workdir."}},required:["pattern"]},run:async({pattern,path:searchPath})=>{if(!pattern)throw new ToolError("glob: pattern is required");if(path2.isAbsolute(pattern))throw new ToolError("glob: absolute pattern not permitted; pass a relative pattern (and optionally path)");if(patternCanAscend(pattern))throw new ToolError('glob: ".." is not permitted in the pattern');let root=searchPath?await resolvePath(ctx,searchPath):path2.resolve(ctx.workdir),realRoot=searchPath?root:await canonicalize(root),matches=[],remaining=WALK_MAX_ENTRIES;try{for await(let entry of fsGlob(pattern,{cwd:root,withFileTypes:!0,exclude:d=>d.name===".git"||d.name==="node_modules"})){if(remaining--<=0)break;if(!entry.isFile())continue;let full=path2.join(entry.parentPath,entry.name),real;try{real=await fs4.realpath(full)}catch{continue}if(!isWithin(realRoot,real))continue;let mtime=0;try{mtime=(await fs4.stat(full)).mtimeMs}catch{}matches.push({path:full,mtime})}}catch(e){throw new ToolError(`glob: ${e instanceof Error?e.message:String(e)}`)}return matches.length===0?"no matches":(matches.sort((a,b)=>b.mtime-a.mtime),matches.slice(0,GLOB_RESULT_LIMIT).map(m=>m.path).join(`
14
+ `))}})}function betaGrepTool(ctx){return rejectUnrestrictedPaths(ctx.unrestrictedPaths),betaTool({name:"grep",description:"Search file contents for a regex. Uses ripgrep if available, otherwise a built-in walker.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string"}},required:["pattern"]},run:async({pattern,path:p},context)=>{if(!pattern)throw new ToolError("grep: pattern is required");let searchPath=path2.resolve(ctx.workdir);p&&(searchPath=await resolvePath(ctx,p));let rg=await findRg();return rg?runRipgrep(rg,pattern,searchPath,context?.signal):runWalkGrep(pattern,searchPath,context?.signal)}})}function runRipgrep(rg,pattern,searchPath,signal){return new Promise((resolve2,reject)=>{let proc=cp.spawn(rg,["-n","--no-heading","-e",pattern,"--",searchPath],{...signal?{signal}:{}}),out="",errOut="",truncated=!1;proc.stdout.on("data",d=>{truncated||(out+=d,out.length>GREP_OUTPUT_LIMIT&&(truncated=!0,out=out.slice(0,GREP_OUTPUT_LIMIT),proc.kill("SIGKILL")))}),proc.stderr.on("data",d=>errOut+=d),proc.on("close",code=>{if(signal?.aborted)return reject(new ToolError("grep: aborted"));if(truncated)return resolve2(out+`
15
+ [output truncated at ${GREP_OUTPUT_LIMIT} bytes]`);if(code===0)return resolve2(out);if(code===1)return resolve2("no matches");reject(new ToolError(`grep: rg failed: ${errOut||`exit ${code}`}`))}),proc.on("error",e=>{if(signal?.aborted)return reject(new ToolError("grep: aborted"));reject(new ToolError(`grep: rg failed: ${e.message}`))})})}async function runWalkGrep(pattern,root,signal){let re;try{re=new RegExp(pattern)}catch(e){throw new ToolError(`grep: invalid regex: ${e instanceof Error?e.message:String(e)}`)}let hits=[],budget=GREP_OUTPUT_LIMIT,push=line=>(budget-=line.length+1,budget<0?(hits.push(`[output truncated at ${GREP_OUTPUT_LIMIT} bytes]`),!1):(hits.push(line),!0));if((await fs4.stat(root).catch(()=>null))?.isFile()?await grepFile(root,re,push):await walk2(root,"",rel=>grepFile(path2.join(root,rel),re,push),signal),signal?.aborted)throw new ToolError("grep: aborted");return hits.length===0?"no matches":hits.join(`
16
+ `)}async function grepFile(file,re,push){let stream2=fssync.createReadStream(file,{encoding:"utf8"}),rl=readline.createInterface({input:stream2,crlfDelay:1/0}),i=0;try{for await(let line of rl)if(i++,!(line.length>GREP_MAX_LINE_LENGTH)&&re.test(line)&&!push(`${file}:${i}:${line}`))return!1}catch{}finally{stream2.destroy()}return!0}var WALK_MAX_DEPTH=40,WALK_MAX_ENTRIES=5e4;async function walk2(root,rel,fn,signal){let remaining=WALK_MAX_ENTRIES;async function inner(rel2,depth){if(depth>WALK_MAX_DEPTH)return!0;if(signal?.aborted)return!1;let entries;try{entries=await fs4.readdir(path2.join(root,rel2),{withFileTypes:!0})}catch{return!0}for(let e of entries){if(e.name===".git"||e.name==="node_modules")continue;if(remaining--<=0||signal?.aborted)return!1;let childRel=rel2?path2.join(rel2,e.name):e.name;if(e.isDirectory()){if(!await inner(childRel,depth+1))return!1}else if(e.isFile()&&await fn(childRel)===!1)return!1}return!0}await inner(rel,0)}async function findRg(){let dirs=(process.env.PATH??"").split(path2.delimiter);for(let d of dirs){let candidate=path2.join(d,"rg");try{return await fs4.access(candidate,fssync.constants.X_OK),candidate}catch{}}return null}export{BashSession,BashTimeoutError,DEFAULT_MEMORY_SYNC_INTERVAL_MS,MARKER_PATH,MEMORY_FLUSH_TIMEOUT_MS,MIN_MEMORY_SYNC_INTERVAL_MS,SessionMemoryError,SessionMemoryStores,betaAgentToolset20260401,betaBashTool,betaEditTool,betaGlobTool,betaGrepTool,betaReadTool,betaWriteTool,extractSkillArchive,resolvePath,setupSkills};
@@ -0,0 +1,10 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
+ import{convertResponsesMessages,convertResponsesTools,processResponsesStream}from"./chunk-46DC2JD6.js";import{registerSessionResourceCleanup,uuidv7}from"./chunk-USJZMAIR.js";import{clampOpenAIPromptCacheKey}from"./chunk-PRRNXB7S.js";import{formatProviderError,normalizeProviderError}from"./chunk-TEPMHNKQ.js";import"./chunk-PJACZCIR.js";import{splitDeferredTools}from"./chunk-GMWCTUPB.js";import{buildBaseOptions,createGrammarToolInputProperties,getPiUserAgent}from"./chunk-TXBQIIIO.js";import"./chunk-L2ZPNLYD.js";import{headersToRecord}from"./chunk-6R7UI4IY.js";import{getProviderEnvValue}from"./chunk-7DDKXS2Q.js";import"./chunk-D7XAASZM.js";import{clampThinkingLevel}from"./chunk-E6KP6V7F.js";import{AssistantMessageEventStream,appendAssistantMessageDiagnostic,createAssistantMessageDiagnostic,formatThrownValue}from"./chunk-72KO4OMP.js";import"./chunk-JXWJOIH4.js";function combineAbortSignals(signals){let activeSignals=signals.filter(signal=>signal!==void 0);if(activeSignals.length===0)return{cleanup:()=>{}};if(activeSignals.length===1)return{signal:activeSignals[0],cleanup:()=>{}};let controller=new AbortController,listeners=[],abort=signal=>{controller.signal.aborted||controller.abort(signal.reason)};for(let signal of activeSignals){if(signal.aborted){abort(signal);break}let listener=()=>abort(signal);signal.addEventListener("abort",listener,{once:!0}),listeners.push({signal,listener})}return{signal:controller.signal,cleanup:()=>{for(let{signal,listener}of listeners)signal.removeEventListener("abort",listener)}}}var DEFAULT_PROXY_PORTS={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function getProxyEnv(key,env){let lowercaseKey=key.toLowerCase(),uppercaseKey=key.toUpperCase();return env?.[lowercaseKey]||env?.[uppercaseKey]||getProviderEnvValue(lowercaseKey)||getProviderEnvValue(uppercaseKey)||""}function parseProxyTargetUrl(targetUrl){if(targetUrl instanceof URL)return targetUrl;try{return new URL(targetUrl)}catch{return}}function stripBrackets(host){return host.startsWith("[")&&host.endsWith("]")?host.slice(1,-1):host}function parseNoProxyEntry(entry){let trimmed=entry.trim().toLowerCase();if(!trimmed)return;if(trimmed.startsWith("[")){let closingBracket=trimmed.indexOf("]");if(closingBracket!==-1){let host=trimmed.slice(1,closingBracket),rest=trimmed.slice(closingBracket+1);if(rest.startsWith(":")){let port=Number.parseInt(rest.slice(1),10);return{host,port:Number.isNaN(port)?0:port}}return{host,port:0}}}if(trimmed.includes(":")&&trimmed.split(":").length>2)return{host:trimmed,port:0};let colonIndex=trimmed.lastIndexOf(":");if(colonIndex!==-1&&colonIndex===trimmed.indexOf(":")){let host=trimmed.slice(0,colonIndex),port=Number.parseInt(trimmed.slice(colonIndex+1),10);if(!Number.isNaN(port))return{host,port}}return{host:trimmed,port:0}}function shouldProxyHostname(hostname,port,env){let noProxy=getProxyEnv("no_proxy",env).toLowerCase();if(!noProxy)return!0;if(noProxy==="*")return!1;let normalizedTargetHost=stripBrackets(hostname.toLowerCase());return noProxy.split(/[,\s]/).every(entry=>{let parsed=parseNoProxyEntry(entry);if(!parsed||parsed.port&&parsed.port!==port)return!0;let domain=stripBrackets(parsed.host);return domain.startsWith("*.")?domain=domain.slice(2):(domain.startsWith(".")||domain.startsWith("*"))&&(domain=domain.slice(1)),domain?!(normalizedTargetHost===domain||normalizedTargetHost.endsWith(`.${domain}`)):!0})}function getProxyForUrl(targetUrl,env){let parsedUrl=parseProxyTargetUrl(targetUrl);if(!parsedUrl?.protocol||!parsedUrl.host)return"";let protocol=parsedUrl.protocol.split(":",1)[0],hostname=stripBrackets(parsedUrl.hostname||parsedUrl.host.replace(/:\d*$/,"")),port=Number.parseInt(parsedUrl.port,10)||DEFAULT_PROXY_PORTS[protocol]||0;if(!shouldProxyHostname(hostname,port,env))return"";let proxy=getProxyEnv(`${protocol}_proxy`,env)||getProxyEnv("all_proxy",env);return proxy&&!proxy.includes("://")&&(proxy=`${protocol}://${proxy}`),proxy}var UNSUPPORTED_PROXY_PROTOCOL_MESSAGE="Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";function resolveHttpProxyUrlForTarget(targetUrl,env){let proxy=getProxyForUrl(targetUrl,env);if(!proxy)return;let proxyUrl;try{proxyUrl=new URL(proxy)}catch(error){throw new Error(`Invalid proxy URL ${JSON.stringify(proxy)}: ${error instanceof Error?error.message:String(error)}`)}if(proxyUrl.protocol!=="http:"&&proxyUrl.protocol!=="https:")throw new Error(`${UNSUPPORTED_PROXY_PROTOCOL_MESSAGE} Got ${proxyUrl.protocol}`);return proxyUrl}var DEFAULT_CODEX_BASE_URL="https://chatgpt.com/backend-api",JWT_CLAIM_PATH="https://api.openai.com/auth",DEFAULT_MAX_RETRIES=0,BASE_DELAY_MS=1e3,DEFAULT_MAX_RETRY_DELAY_MS=6e4,DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS=15e3,REQUEST_COMPRESSION_ZSTD_LEVEL=3,CODEX_TOOL_CALL_PROVIDERS=new Set(["openai","openai-codex","opencode"]),WEBSOCKET_MESSAGE_TOO_BIG_CLOSE_CODE=1009,WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE="websocket_connection_limit_reached",PREVIOUS_RESPONSE_NOT_FOUND_CODE="previous_response_not_found",CODEX_RESPONSE_STATUSES=new Set(["completed","incomplete","failed","cancelled","queued","in_progress"]);function assertSuccessfulOutput(output){if(output.stopReason==="pending")throw new Error("Codex stream ended without a stop reason");if(output.stopReason==="error"||output.stopReason==="aborted")throw new Error(output.errorMessage||"An unknown error occurred")}function isTerminalRateLimitError(errorText){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(errorText)}function isRetryableError(status,errorText){return status===429&&isTerminalRateLimitError(errorText)?!1:status===429||status===500||status===502||status===503||status===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(errorText)}function getRetryAfterDelayMs(headers){let retryAfterMs=headers.get("retry-after-ms");if(retryAfterMs!==null){let millis=Number(retryAfterMs);if(Number.isFinite(millis))return Math.max(0,millis)}let retryAfter=headers.get("retry-after");if(!retryAfter)return;let seconds=Number(retryAfter);if(Number.isFinite(seconds))return Math.max(0,seconds*1e3);let date=Date.parse(retryAfter);if(!Number.isNaN(date))return Math.max(0,date-Date.now())}var RetryDelayExceededError=class extends Error{};function validateRetryDelayMs(delayMs,options){let maxRetryDelayMs=options?.maxRetryDelayMs??DEFAULT_MAX_RETRY_DELAY_MS;if(maxRetryDelayMs>0&&delayMs>maxRetryDelayMs)throw new RetryDelayExceededError(`Server requested ${Math.ceil(delayMs/1e3)}s retry delay (max: ${Math.ceil(maxRetryDelayMs/1e3)}s)`);return delayMs}function sleep(ms,signal){return new Promise((resolve,reject)=>{if(signal?.aborted){reject(new Error("Request was aborted"));return}let timeout=setTimeout(resolve,ms);signal?.addEventListener("abort",()=>{clearTimeout(timeout),reject(new Error("Request was aborted"))})})}function normalizeTimeoutMs(value){if(value!==void 0){if(!Number.isFinite(value)||value<0)throw new Error(`Invalid timeoutMs: ${String(value)}`);return Math.floor(value)}}function loadNodeZlib(){return typeof process>"u"||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.("node:zlib")??null}function compressRequestBodyZstd(bodyJson){let zlib=loadNodeZlib();if(!zlib||typeof zlib.zstdCompressSync!="function")return null;try{let compressed=zlib.zstdCompressSync(bodyJson,{params:{[zlib.constants.ZSTD_c_compressionLevel]:REQUEST_COMPRESSION_ZSTD_LEVEL}});return Uint8Array.from(compressed)}catch{return null}}var stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream;return(async()=>{let output={role:"assistant",content:[],api:"openai-codex-responses",provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()};try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let accountId=extractAccountId(apiKey),grammarToolInputProperties=createGrammarToolInputProperties(context.tools,model.compat?.supportsOpenAIGrammarTools??!1),cacheSessionId=options?.cacheRetention==="none"?void 0:options?.sessionId,codexSessionId=clampOpenAIPromptCacheKey(cacheSessionId),body=buildRequestBody(model,context,options,codexSessionId,grammarToolInputProperties),nextBody=await options?.onPayload?.(body,model);nextBody!==void 0&&(body=nextBody);let websocketRequestId=codexSessionId||uuidv7(),sseHeaders=buildSSEHeaders(model.headers,options?.headers,accountId,apiKey,codexSessionId),websocketHeaders=buildWebSocketHeaders(model.headers,options?.headers,accountId,apiKey,websocketRequestId),bodyJson=JSON.stringify(body),httpTimeoutMs=normalizeTimeoutMs(options?.timeoutMs),websocketConnectTimeoutMs=normalizeTimeoutMs(options?.websocketConnectTimeoutMs),transport=options?.transport||"auto",startEmitted=!1,websocketDisabledForSession=transport!=="sse"&&isWebSocketSseFallbackActive(cacheSessionId);if(websocketDisabledForSession&&recordWebSocketSseFallback(cacheSessionId),transport!=="sse"&&!websocketDisabledForSession){let websocketStarted=!1,retriedWebSocketConnectionLimit=!1,retriedMissingWebSocketContinuation=!1;for(;;){websocketStarted=!1;try{if(await processWebSocketStream(resolveCodexWebSocketUrl(model.baseUrl),body,websocketHeaders,output,stream2,model,()=>{websocketStarted=!0,startEmitted||(startEmitted=!0,stream2.push({type:"start",partial:output}))},httpTimeoutMs,websocketConnectTimeoutMs,cacheSessionId,accountId,grammarToolInputProperties,options),options?.signal?.aborted)throw new Error("Request was aborted");assertSuccessfulOutput(output),stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end();return}catch(error){let aborted=options?.signal?.aborted,connectionLimitBeforeStart=!websocketStarted&&isWebSocketConnectionLimitReachedError(error),previousResponseNotFound=isPreviousResponseNotFoundError(error);if(!aborted&&previousResponseNotFound&&!retriedMissingWebSocketContinuation){retriedMissingWebSocketContinuation=!0;continue}if(!aborted&&connectionLimitBeforeStart&&!retriedWebSocketConnectionLimit){retriedWebSocketConnectionLimit=!0;continue}if(aborted||isCodexNonTransportError(error)&&!connectionLimitBeforeStart||(appendAssistantMessageDiagnostic(output,createAssistantMessageDiagnostic("provider_transport_failure",error,{configuredTransport:transport,fallbackTransport:websocketStarted?void 0:"sse",eventsEmitted:websocketStarted,phase:websocketStarted?"after_message_stream_start":"before_message_stream_start",requestBytes:new TextEncoder().encode(bodyJson).byteLength})),recordWebSocketFailure(cacheSessionId,error),websocketStarted))throw error;recordWebSocketSseFallback(cacheSessionId);break}}}let compressedBody=compressRequestBodyZstd(bodyJson);compressedBody&&sseHeaders.set("content-encoding","zstd");let sseBody=compressedBody??bodyJson,response,lastError,maxRetries=options?.maxRetries??DEFAULT_MAX_RETRIES;for(let attempt=0;attempt<=maxRetries;attempt++){if(options?.signal?.aborted)throw new Error("Request was aborted");try{let headerTimeoutSignal=httpTimeoutMs!==void 0&&httpTimeoutMs>0?AbortSignal.timeout(httpTimeoutMs):void 0,combinedSignal=combineAbortSignals([options?.signal,headerTimeoutSignal]);try{response=await(options?.fetch??globalThis.fetch)(resolveCodexUrl(model.baseUrl),{method:"POST",headers:sseHeaders,body:sseBody,signal:combinedSignal.signal})}catch(error){throw headerTimeoutSignal?.aborted&&!options?.signal?.aborted?new Error(`Codex SSE response headers timed out after ${httpTimeoutMs}ms`):error}finally{combinedSignal.cleanup()}if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),response.ok)break;let errorText=await response.text();if(attempt<maxRetries&&isRetryableError(response.status,errorText)){let retryAfterDelayMs=getRetryAfterDelayMs(response.headers),delayMs=retryAfterDelayMs===void 0?BASE_DELAY_MS*2**attempt:validateRetryDelayMs(retryAfterDelayMs,options);await sleep(delayMs,options?.signal);continue}let fakeResponse=new Response(errorText,{status:response.status,statusText:response.statusText}),info=await parseErrorResponse(fakeResponse);throw new Error(info.friendlyMessage||info.message)}catch(error){if(error instanceof Error&&(error.name==="AbortError"||error.message==="Request was aborted"))throw new Error("Request was aborted");if(lastError=error instanceof Error?error:new Error(String(error)),attempt<maxRetries&&!(lastError instanceof RetryDelayExceededError)&&!lastError.message.includes("usage limit")){let delayMs=BASE_DELAY_MS*2**attempt;await sleep(delayMs,options?.signal);continue}throw lastError}}if(!response?.ok)throw lastError??new Error("Failed after retries");if(!response.body)throw new Error("No response body");if(startEmitted||(startEmitted=!0,stream2.push({type:"start",partial:output})),await processStream(response,output,stream2,model,grammarToolInputProperties,options),options?.signal?.aborted)throw new Error("Request was aborted");assertSuccessfulOutput(output),stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.partialJson,delete block.customInput;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatProviderError(normalizeProviderError(error)),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0;return stream(model,context,{...base,reasoningEffort:clampedReasoning==="off"?void 0:clampedReasoning})};function buildRequestBody(model,context,options,cacheSessionId,grammarToolInputProperties=createGrammarToolInputProperties(context.tools,model.compat?.supportsOpenAIGrammarTools??!1)){let supportsStrictMode=model.compat?.supportsStrictMode??!0,supportsOpenAIGrammarTools=model.compat?.supportsOpenAIGrammarTools??!1,deferredToolsMode=model.compat?.supportsAdditionalTools?"additional-tools":model.compat?.supportsToolSearch?"tool-search":void 0,toolPlacement=splitDeferredTools(context,deferredToolsMode!==void 0),messages=convertResponsesMessages(model,context,CODEX_TOOL_CALL_PROVIDERS,{includeSystemPrompt:!1,grammarToolInputProperties,deferredTools:toolPlacement.deferred,deferredToolsMode,toolOptions:{strict:null,supportsStrictMode,supportsOpenAIGrammarTools}}),body={model:model.id,store:!1,stream:!0,instructions:context.systemPrompt||"You are a helpful assistant.",input:messages,text:{verbosity:options?.textVerbosity||"low"},include:["reasoning.encrypted_content"],prompt_cache_key:cacheSessionId,tool_choice:options?.toolChoice??"auto",parallel_tool_calls:!0};if(options?.temperature!==void 0&&(body.temperature=options.temperature),options?.serviceTier!==void 0&&(body.service_tier=options.serviceTier),toolPlacement.immediate.length>0&&(body.tools=convertResponsesTools(toolPlacement.immediate,{strict:null,supportsStrictMode,supportsOpenAIGrammarTools})),options?.reasoningEffort!==void 0){let effort=options.reasoningEffort==="none"?model.thinkingLevelMap?.off??"none":model.thinkingLevelMap?.[options.reasoningEffort]??options.reasoningEffort;effort!==null&&(body.reasoning={effort,summary:options.reasoningSummary??"auto"})}return body}function getServiceTierCostMultiplier(model,serviceTier){switch(serviceTier){case"flex":return .5;case"priority":return model.id==="gpt-5.5"?2.5:2;default:return 1}}function applyServiceTierPricing(usage,serviceTier,model){let multiplier=getServiceTierCostMultiplier(model,serviceTier);multiplier!==1&&(usage.cost.input*=multiplier,usage.cost.output*=multiplier,usage.cost.cacheRead*=multiplier,usage.cost.cacheWrite*=multiplier,usage.cost.total=usage.cost.input+usage.cost.output+usage.cost.cacheRead+usage.cost.cacheWrite)}function resolveCodexServiceTier(responseServiceTier,requestServiceTier){return responseServiceTier==="default"&&(requestServiceTier==="flex"||requestServiceTier==="priority")?requestServiceTier:responseServiceTier??requestServiceTier}function resolveCodexUrl(baseUrl){let normalized=(baseUrl&&baseUrl.trim().length>0?baseUrl:DEFAULT_CODEX_BASE_URL).replace(/\/+$/,"");return normalized.endsWith("/codex/responses")?normalized:normalized.endsWith("/codex")?`${normalized}/responses`:`${normalized}/codex/responses`}function resolveCodexWebSocketUrl(baseUrl){let url=new URL(resolveCodexUrl(baseUrl));return url.protocol==="https:"&&(url.protocol="wss:"),url.protocol==="http:"&&(url.protocol="ws:"),url.toString()}async function processStream(response,output,stream2,model,grammarToolInputProperties,options){await processResponsesStream(mapCodexEvents(parseSSE(response,options?.signal),output),output,stream2,model,{serviceTier:options?.serviceTier,grammarToolInputProperties,resolveServiceTier:resolveCodexServiceTier,applyServiceTierPricing:(usage,serviceTier)=>applyServiceTierPricing(usage,serviceTier,model)})}var CodexApiError=class extends Error{constructor(message,options){super(message),this.name="CodexApiError",this.code=options?.code,this.payload=options?.payload,this.cause=options?.cause}},CodexProtocolError=class extends Error{constructor(message,options){super(message),this.name="CodexProtocolError",this.payload=options?.payload,this.cause=options?.cause}};function isCodexNonTransportError(error){return error instanceof CodexApiError||error instanceof CodexProtocolError}function isWebSocketConnectionLimitReachedError(error){return error instanceof CodexApiError&&error.code===WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE}function isPreviousResponseNotFoundError(error){return error instanceof CodexApiError&&error.code===PREVIOUS_RESPONSE_NOT_FOUND_CODE}function extractCodexEventError(event){let nested=event.error&&typeof event.error=="object"?event.error:void 0;return{code:typeof event.code=="string"?event.code:typeof nested?.code=="string"?nested.code:void 0,message:typeof event.message=="string"?event.message:typeof nested?.message=="string"?nested.message:void 0}}async function*mapCodexEvents(events,output){for await(let event of events){let type=typeof event.type=="string"?event.type:void 0;if(type){if(type==="error"){let{code,message}=extractCodexEventError(event);throw new CodexApiError(`Codex error: ${message||code||JSON.stringify(event)}`,{code,payload:event})}if(type==="response.failed"){let response=event.response,code=response?.error?.code,message=response?.error?.message;throw new CodexApiError(message||"Codex response failed",{code,payload:event})}if(type==="response.done"||type==="response.completed"||type==="response.incomplete"){let response=event.response;typeof response?.end_turn=="boolean"&&(output.endTurn=response.end_turn);let normalizedResponse=response&&{...response,status:normalizeCodexStatus(response.status)};yield{...event,type:"response.completed",response:normalizedResponse};return}yield event}}}function normalizeCodexStatus(status){if(typeof status=="string")return CODEX_RESPONSE_STATUSES.has(status)?status:void 0}async function*parseSSE(response,signal){if(!response.body)return;let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>{reader.cancel().catch(()=>{})};signal?.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal?.aborted)throw new Error("Request was aborted");let{done,value}=await reader.read();if(signal?.aborted)throw new Error("Request was aborted");buffer+=done?decoder.decode():decoder.decode(value,{stream:!0}),done&&buffer.trim()&&(buffer+=`
3
+
4
+ `);let idx=buffer.indexOf(`
5
+
6
+ `);for(;idx!==-1;){let chunk=buffer.slice(0,idx);buffer=buffer.slice(idx+2);let dataLines=chunk.split(`
7
+ `).filter(l=>l.startsWith("data:")).map(l=>l.slice(5).trim());if(dataLines.length>0){let data=dataLines.join(`
8
+ `).trim();if(data&&data!=="[DONE]")try{yield JSON.parse(data)}catch(cause){throw new CodexProtocolError(`Invalid Codex SSE JSON: ${formatThrownValue(cause)}`,{cause,payload:data})}}idx=buffer.indexOf(`
9
+
10
+ `)}if(done)break}}finally{signal?.removeEventListener("abort",onAbort);try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}var OPENAI_BETA_RESPONSES_WEBSOCKETS="responses_websockets=2026-02-06",SESSION_WEBSOCKET_CACHE_TTL_MS=300*1e3,SESSION_WEBSOCKET_MAX_AGE_MS=3300*1e3,websocketSessionCache=new Map,websocketDebugStats=new Map,websocketSseFallbackSessions=new Set;function getOrCreateWebSocketDebugStats(sessionId){let stats=websocketDebugStats.get(sessionId);return stats||(stats={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},websocketDebugStats.set(sessionId,stats)),stats}function getOpenAICodexWebSocketDebugStats(sessionId){let stats=websocketDebugStats.get(sessionId);return stats?{...stats}:void 0}function resetOpenAICodexWebSocketDebugStats(sessionId){if(sessionId){websocketDebugStats.delete(sessionId),websocketSseFallbackSessions.delete(sessionId);return}websocketDebugStats.clear(),websocketSseFallbackSessions.clear()}function closeOpenAICodexWebSocketSessions(sessionId){let closeEntry=entry=>{entry.idleTimer&&clearTimeout(entry.idleTimer),closeWebSocketSilently(entry.socket,1e3,"debug_close")};if(sessionId){for(let entry of websocketSessionCache.get(sessionId)?.values()??[])closeEntry(entry);websocketSessionCache.delete(sessionId);return}for(let accountEntries of websocketSessionCache.values())for(let entry of accountEntries.values())closeEntry(entry);websocketSessionCache.clear()}registerSessionResourceCleanup(closeOpenAICodexWebSocketSessions);function isWebSocketSseFallbackActive(sessionId){return sessionId?websocketSseFallbackSessions.has(sessionId):!1}function recordWebSocketSseFallback(sessionId){if(!sessionId)return;let stats=getOrCreateWebSocketDebugStats(sessionId);stats.sseFallbacks++,stats.websocketFallbackActive=isWebSocketSseFallbackActive(sessionId)}function recordWebSocketFailure(sessionId,error){if(!sessionId)return;websocketSseFallbackSessions.add(sessionId);let stats=getOrCreateWebSocketDebugStats(sessionId);stats.websocketFailures++,stats.lastWebSocketError=formatThrownValue(error),stats.websocketFallbackActive=!0}var _cachedWebsocket=null;async function getWebSocketConstructor(env){if(!env&&_cachedWebsocket)return _cachedWebsocket;if(typeof process<"u"&&process.versions?.bun){let WebSocketWithProxy=class extends WebSocket{constructor(url,options){let _opts={};Array.isArray(options)||typeof options=="string"?_opts={protocols:options}:_opts={...options};let proxyUrl=resolveHttpProxyUrlForTarget(url.toString().replace(/^wss:/,"https:").replace(/^ws:/,"http:"),env);super(url,{..._opts,...proxyUrl?{proxy:proxyUrl.toString()}:{}})}};return env||(_cachedWebsocket=WebSocketWithProxy),WebSocketWithProxy}let ctor=globalThis.WebSocket;return typeof ctor!="function"?null:ctor}var WebSocketCloseError=class extends Error{constructor(message,options){super(message),this.name="WebSocketCloseError",this.code=options?.code,this.reason=options?.reason,this.wasClean=options?.wasClean}};function getWebSocketReadyState(socket){let readyState=socket.readyState;return typeof readyState=="number"?readyState:void 0}function isWebSocketReusable(socket){let readyState=getWebSocketReadyState(socket);return readyState===void 0||readyState===1}function isWebSocketSessionExpired(entry){return Date.now()-entry.createdAt>=SESSION_WEBSOCKET_MAX_AGE_MS}function closeWebSocketSilently(socket,code=1e3,reason="done"){try{socket.close(code,reason)}catch{}}function scheduleSessionWebSocketExpiry(sessionId,accountId,entry){entry.idleTimer&&clearTimeout(entry.idleTimer),entry.idleTimer=setTimeout(()=>{if(entry.busy)return;closeWebSocketSilently(entry.socket,1e3,"idle_timeout");let accountEntries=websocketSessionCache.get(sessionId);accountEntries?.get(accountId)===entry&&accountEntries.delete(accountId),accountEntries?.size===0&&websocketSessionCache.delete(sessionId)},SESSION_WEBSOCKET_CACHE_TTL_MS)}async function connectWebSocket(url,headers,signal,connectTimeoutMs=DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS,env){let WebSocketCtor=await getWebSocketConstructor(env);if(!WebSocketCtor)throw new Error("WebSocket transport is not available in this runtime");let wsHeaders=headersToRecord(headers);return delete wsHeaders["OpenAI-Beta"],new Promise((resolve,reject)=>{let settled=!1,timeout,socket;try{socket=new WebSocketCtor(url,{headers:wsHeaders})}catch(error){reject(error instanceof Error?error:new Error(String(error)));return}let cleanup=()=>{timeout&&(clearTimeout(timeout),timeout=void 0),socket.removeEventListener("open",onOpen),socket.removeEventListener("error",onError),socket.removeEventListener("close",onClose),signal?.removeEventListener("abort",onAbort)},fail=(error,closeReason)=>{settled||(settled=!0,cleanup(),closeReason&&closeWebSocketSilently(socket,1e3,closeReason),reject(error))},onOpen=()=>{settled||(settled=!0,cleanup(),resolve(socket))},onError=event=>{fail(extractWebSocketError(event))},onClose=event=>{fail(extractWebSocketCloseError(event))},onAbort=()=>{fail(new Error("Request was aborted"),"aborted")};socket.addEventListener("open",onOpen),socket.addEventListener("error",onError),socket.addEventListener("close",onClose),signal?.addEventListener("abort",onAbort),connectTimeoutMs>0&&(timeout=setTimeout(()=>{fail(new Error(`WebSocket connect timeout after ${connectTimeoutMs}ms`),"connect_timeout")},connectTimeoutMs)),signal?.aborted&&onAbort()})}async function acquireWebSocket(url,headers,sessionId,accountId,signal,connectTimeoutMs,env){if(!sessionId){let socket2=await connectWebSocket(url,headers,signal,connectTimeoutMs,env);return{socket:socket2,reused:!1,release:()=>closeWebSocketSilently(socket2)}}let accountEntries=websocketSessionCache.get(sessionId),cached=accountEntries?.get(accountId);if(cached){if(cached.idleTimer&&(clearTimeout(cached.idleTimer),cached.idleTimer=void 0),!cached.busy&&isWebSocketSessionExpired(cached))closeWebSocketSilently(cached.socket,1e3,"connection_age_limit"),accountEntries?.delete(accountId),accountEntries?.size===0&&websocketSessionCache.delete(sessionId);else if(!cached.busy&&isWebSocketReusable(cached.socket))return cached.busy=!0,{socket:cached.socket,entry:cached,reused:!0,release:({keep}={})=>{if(!keep||!isWebSocketReusable(cached.socket)){closeWebSocketSilently(cached.socket);let currentEntries=websocketSessionCache.get(sessionId);currentEntries?.get(accountId)===cached&&currentEntries.delete(accountId),currentEntries?.size===0&&websocketSessionCache.delete(sessionId);return}cached.busy=!1,scheduleSessionWebSocketExpiry(sessionId,accountId,cached)}};if(cached.busy){let socket2=await connectWebSocket(url,headers,signal,connectTimeoutMs,env);return{socket:socket2,reused:!1,release:()=>{closeWebSocketSilently(socket2)}}}isWebSocketReusable(cached.socket)||(closeWebSocketSilently(cached.socket),accountEntries?.delete(accountId),accountEntries?.size===0&&websocketSessionCache.delete(sessionId))}let socket=await connectWebSocket(url,headers,signal,connectTimeoutMs,env),entry={socket,busy:!0,createdAt:Date.now()};return accountEntries=websocketSessionCache.get(sessionId),accountEntries||(accountEntries=new Map,websocketSessionCache.set(sessionId,accountEntries)),accountEntries.set(accountId,entry),{socket,entry,reused:!1,release:({keep}={})=>{if(!keep||!isWebSocketReusable(entry.socket)){closeWebSocketSilently(entry.socket),entry.idleTimer&&clearTimeout(entry.idleTimer);let currentEntries=websocketSessionCache.get(sessionId);currentEntries?.get(accountId)===entry&&currentEntries.delete(accountId),currentEntries?.size===0&&websocketSessionCache.delete(sessionId);return}entry.busy=!1,scheduleSessionWebSocketExpiry(sessionId,accountId,entry)}}}function extractWebSocketError(event){if(event&&typeof event=="object"){let message="message"in event?event.message:void 0;if(typeof message=="string"&&message.length>0)return new Error(message);let nestedError="error"in event?event.error:void 0;if(nestedError instanceof Error&&nestedError.message.length>0)return nestedError;if(nestedError&&typeof nestedError=="object"&&"message"in nestedError){let nestedMessage=nestedError.message;if(typeof nestedMessage=="string"&&nestedMessage.length>0)return new Error(nestedMessage)}}return new Error("WebSocket error")}function extractWebSocketCloseError(event){if(event&&typeof event=="object"){let code="code"in event?event.code:void 0,reason="reason"in event?event.reason:void 0,wasClean="wasClean"in event?event.wasClean:void 0,codeText=typeof code=="number"?` ${code}`:"",reasonText=typeof reason=="string"&&reason.length>0?` ${reason}`:"";return!reasonText&&code===WEBSOCKET_MESSAGE_TOO_BIG_CLOSE_CODE&&(reasonText=" message too big"),new WebSocketCloseError(`WebSocket closed${codeText}${reasonText}`.trim(),{code:typeof code=="number"?code:void 0,reason:typeof reason=="string"&&reason.length>0?reason:void 0,wasClean:typeof wasClean=="boolean"?wasClean:void 0})}return new Error("WebSocket closed")}async function decodeWebSocketData(data){if(typeof data=="string")return data;if(data instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(data));if(ArrayBuffer.isView(data)){let view=data;return new TextDecoder().decode(new Uint8Array(view.buffer,view.byteOffset,view.byteLength))}if(data&&typeof data=="object"&&"arrayBuffer"in data){let arrayBuffer=await data.arrayBuffer();return new TextDecoder().decode(new Uint8Array(arrayBuffer))}return null}async function*parseWebSocket(socket,signal,idleTimeoutMs){let queue=[],pending=null,done=!1,failed=null,sawCompletion=!1,wake=()=>{if(!pending)return;let resolve=pending;pending=null,resolve()},onMessage=event=>{(async()=>{let text=null;try{if(!event||typeof event!="object"||!("data"in event)||(text=await decodeWebSocketData(event.data),!text))return;let parsed=JSON.parse(text),type=typeof parsed.type=="string"?parsed.type:"";(type==="response.completed"||type==="response.done"||type==="response.incomplete")&&(sawCompletion=!0,done=!0),queue.push(parsed),wake()}catch(cause){failed=new CodexProtocolError(`Invalid Codex WebSocket JSON: ${formatThrownValue(cause)}`,{cause,payload:text}),done=!0,wake()}})()},onError=event=>{failed=extractWebSocketError(event),done=!0,wake()},onClose=event=>{if(sawCompletion){done=!0,wake();return}failed||(failed=extractWebSocketCloseError(event)),done=!0,wake()},onAbort=()=>{failed=new Error("Request was aborted"),done=!0,wake()};socket.addEventListener("message",onMessage),socket.addEventListener("error",onError),socket.addEventListener("close",onClose),signal?.addEventListener("abort",onAbort);try{for(;;){if(signal?.aborted)throw new Error("Request was aborted");if(queue.length>0){yield queue.shift();continue}if(done)break;let timeout;await new Promise((resolve,reject)=>{pending=resolve,idleTimeoutMs!==void 0&&idleTimeoutMs>0&&(timeout=setTimeout(()=>{let error=new Error(`WebSocket idle timeout after ${idleTimeoutMs}ms`);failed=error,done=!0,pending=null,closeWebSocketSilently(socket,1e3,"idle_timeout"),reject(error)},idleTimeoutMs))}).finally(()=>{timeout&&clearTimeout(timeout)})}if(failed)throw failed;if(!sawCompletion)throw new Error("WebSocket stream closed before response.completed")}finally{socket.removeEventListener("message",onMessage),socket.removeEventListener("error",onError),socket.removeEventListener("close",onClose),signal?.removeEventListener("abort",onAbort)}}function requestBodyWithoutInput(body){let{input:_input,previous_response_id:_previousResponseId,...rest}=body;return rest}function responseInputsEqual(a,b){return JSON.stringify(a??[])===JSON.stringify(b??[])}function requestBodiesMatchExceptInput(a,b){return JSON.stringify(requestBodyWithoutInput(a))===JSON.stringify(requestBodyWithoutInput(b))}function getCachedWebSocketInputDelta(body,continuation){if(!requestBodiesMatchExceptInput(body,continuation.lastRequestBody))return;let currentInput=body.input??[],baseline=[...continuation.lastRequestBody.input??[],...continuation.lastResponseItems];if(currentInput.length<baseline.length)return;let prefix=currentInput.slice(0,baseline.length);if(responseInputsEqual(prefix,baseline))return currentInput.slice(baseline.length)}function buildCachedWebSocketRequestBody(entry,body){let continuation=entry.continuation;if(!continuation)return body;let delta=getCachedWebSocketInputDelta(body,continuation);return!delta||!continuation.lastResponseId?(entry.continuation=void 0,body):{...body,previous_response_id:continuation.lastResponseId,input:delta}}async function*startWebSocketOutputOnFirstEvent(events,onStart){let started=!1;for await(let event of events)started||(started=!0,onStart()),yield event}async function processWebSocketStream(url,body,headers,output,stream2,model,onStart,idleTimeoutMs,websocketConnectTimeoutMs,cacheSessionId,accountId,grammarToolInputProperties,options){let{socket,entry,reused,release}=await acquireWebSocket(url,headers,cacheSessionId,accountId,options?.signal,websocketConnectTimeoutMs,options?.env),keepConnection=!0,useCachedContext=options?.transport==="websocket-cached"||options?.transport==="auto",fullBody=body,requestBody=useCachedContext&&entry?buildCachedWebSocketRequestBody(entry,fullBody):fullBody,stats=cacheSessionId?getOrCreateWebSocketDebugStats(cacheSessionId):void 0;stats&&(stats.requests++,reused?stats.connectionsReused++:stats.connectionsCreated++,useCachedContext&&stats.cachedContextRequests++,requestBody.store===!0&&stats.storeTrueRequests++,stats.lastInputItems=requestBody.input?.length??0,requestBody.previous_response_id?(stats.deltaRequests++,stats.lastDeltaInputItems=requestBody.input?.length??0,stats.lastPreviousResponseId=requestBody.previous_response_id):(stats.fullContextRequests++,stats.lastDeltaInputItems=void 0,stats.lastPreviousResponseId=void 0));try{if(socket.send(JSON.stringify({type:"response.create",...requestBody})),await processResponsesStream(startWebSocketOutputOnFirstEvent(mapCodexEvents(parseWebSocket(socket,options?.signal,idleTimeoutMs),output),onStart),output,stream2,model,{serviceTier:options?.serviceTier,grammarToolInputProperties,resolveServiceTier:resolveCodexServiceTier,applyServiceTierPricing:(usage,serviceTier)=>applyServiceTierPricing(usage,serviceTier,model)}),options?.signal?.aborted)keepConnection=!1;else if(useCachedContext&&entry&&output.responseId){let responseItems=convertResponsesMessages(model,{messages:[output]},CODEX_TOOL_CALL_PROVIDERS,{includeSystemPrompt:!1,grammarToolInputProperties}).filter(item=>item.type!=="function_call_output"&&item.type!=="custom_tool_call_output");entry.continuation={lastRequestBody:fullBody,lastResponseId:output.responseId,lastResponseItems:responseItems}}}catch(error){throw entry&&(entry.continuation=void 0),keepConnection=!1,error}finally{release({keep:keepConnection})}}async function parseErrorResponse(response){let raw=await response.text(),message=raw||response.statusText||"Request failed",friendlyMessage;try{let err=JSON.parse(raw)?.error;if(err){let code=err.code||err.type||"";if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(code)||response.status===429){let plan=err.plan_type?` (${err.plan_type.toLowerCase()} plan)`:"",mins=err.resets_at?Math.max(0,Math.round((err.resets_at*1e3-Date.now())/6e4)):void 0,when=mins!==void 0?` Try again in ~${mins} min.`:"";friendlyMessage=`You have hit your ChatGPT usage limit${plan}.${when}`.trim()}message=err.message||friendlyMessage||message}}catch{}return{message,friendlyMessage}}function extractAccountId(token){try{let parts=token.split(".");if(parts.length!==3)throw new Error("Invalid token");let accountId=JSON.parse(atob(parts[1]))?.[JWT_CLAIM_PATH]?.chatgpt_account_id;if(!accountId)throw new Error("No account ID in token");return accountId}catch{throw new Error("Failed to extract accountId from token")}}function buildBaseCodexHeaders(initHeaders,additionalHeaders,accountId,token){let headers=new Headers(initHeaders);for(let[key,value]of Object.entries(additionalHeaders||{}))value===null?headers.delete(key):headers.set(key,value);return headers.set("Authorization",`Bearer ${token}`),headers.set("chatgpt-account-id",accountId),headers.set("originator","pi"),headers.set("User-Agent",getPiUserAgent()),headers}function buildSSEHeaders(initHeaders,additionalHeaders,accountId,token,sessionId){let headers=buildBaseCodexHeaders(initHeaders,additionalHeaders,accountId,token);return headers.set("OpenAI-Beta","responses=experimental"),headers.set("accept","text/event-stream"),headers.set("content-type","application/json"),sessionId&&(headers.set("session-id",sessionId),headers.set("x-client-request-id",sessionId)),headers}function buildWebSocketHeaders(initHeaders,additionalHeaders,accountId,token,requestId){let headers=buildBaseCodexHeaders(initHeaders,additionalHeaders,accountId,token);return headers.delete("accept"),headers.delete("content-type"),headers.delete("OpenAI-Beta"),headers.delete("openai-beta"),headers.set("OpenAI-Beta",OPENAI_BETA_RESPONSES_WEBSOCKETS),headers.set("x-client-request-id",requestId),headers.set("session-id",requestId),headers}export{closeOpenAICodexWebSocketSessions,getOpenAICodexWebSocketDebugStats,resetOpenAICodexWebSocketDebugStats,stream,streamSimple};