@astralyn/pi 1.0.5 → 1.2.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 (436) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/dist/bundle/chunks/anthropic-messages-NVP5OPIM.js +6 -0
  3. package/dist/bundle/chunks/anthropic.js +1 -1
  4. package/dist/bundle/chunks/{azure-openai-responses-LDW4FGAQ.js → azure-openai-responses-IBTOZ5MH.js} +1 -1
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +2 -2
  6. package/dist/bundle/chunks/chunk-4XZYHGVN.js +11 -0
  7. package/dist/bundle/chunks/{chunk-GIG5IHES.js → chunk-5KJH3GGH.js} +1 -1
  8. package/dist/bundle/chunks/chunk-6VYRLG5F.js +2 -0
  9. package/dist/bundle/chunks/{chunk-UCXU7KLO.js → chunk-7HJ6CHUB.js} +1 -1
  10. package/dist/bundle/chunks/chunk-7UBIBLPN.js +2 -0
  11. package/dist/bundle/chunks/{chunk-IE3Z7ESB.js → chunk-A5HU4TE6.js} +418 -362
  12. package/dist/bundle/chunks/{chunk-HDHRZ7GT.js → chunk-B2UOWO4A.js} +1 -1
  13. package/dist/bundle/chunks/chunk-J75WV3FL.js +2 -0
  14. package/dist/bundle/chunks/{chunk-A6ALEEY5.js → chunk-LHSPN2IO.js} +1 -1
  15. package/dist/bundle/chunks/chunk-Q74S7ILH.js +2 -0
  16. package/dist/bundle/chunks/chunk-QDDSFJ35.js +2 -0
  17. package/dist/bundle/chunks/{chunk-IFELM7MW.js → chunk-UQECUCUH.js} +1 -1
  18. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-HGOVFZDC.js +2 -0
  19. package/dist/bundle/chunks/codemode-worker.js +18 -10
  20. package/dist/bundle/chunks/github-copilot.js +1 -1
  21. package/dist/bundle/chunks/{google-generative-ai-S5A5IBU4.js → google-generative-ai-M44TSMAN.js} +1 -1
  22. package/dist/bundle/chunks/{google-vertex-UBRQFDB4.js → google-vertex-3C4OWLFX.js} +1 -1
  23. package/dist/bundle/chunks/image-resize-worker.js +1 -1
  24. package/dist/bundle/chunks/{llama-cpp-classify-R7DQLTQN.js → llama-cpp-classify-H3IZDR5O.js} +2 -2
  25. package/dist/bundle/chunks/mistral-conversations-I5PL4VCZ.js +5 -0
  26. package/dist/bundle/chunks/openai-chatgpt.js +1 -1
  27. package/dist/bundle/chunks/openai-codex-responses-O5EUDL54.js +10 -0
  28. package/dist/bundle/chunks/openai-codex.js +1 -1
  29. package/dist/bundle/chunks/{openai-completions-H4VMO7AU.js → openai-completions-X3SSG5BQ.js} +1 -1
  30. package/dist/bundle/chunks/openai-decisions-TVCDIPZX.js +5 -0
  31. package/dist/bundle/chunks/{openai-responses-G4PGNM2H.js → openai-responses-NYPNKVDV.js} +1 -1
  32. package/dist/bundle/chunks/{openrouter-images-YP3YVB54.js → openrouter-images-TDLJV5N4.js} +1 -1
  33. package/dist/bundle/chunks/{pi-messages-HZZ7GEEW.js → pi-messages-ZXNERWJG.js} +1 -1
  34. package/dist/bundle/chunks/typesafe-system-one-LWPJYTJP.js +2 -0
  35. package/dist/bundle/chunks/{virtual-modules-46MSJGKO.js → virtual-modules-OZTPKGU7.js} +1 -1
  36. package/dist/bundle/cli.js +1 -1
  37. package/dist/bundle/index.js +1 -1
  38. package/dist/bundle/rpc-entry.js +1 -1
  39. package/dist/cli/args.d.ts +1 -1
  40. package/dist/cli/args.d.ts.map +1 -1
  41. package/dist/cli/args.js +13 -1
  42. package/dist/cli/args.js.map +1 -1
  43. package/dist/core/agent-session.d.ts +26 -7
  44. package/dist/core/agent-session.d.ts.map +1 -1
  45. package/dist/core/agent-session.js +190 -183
  46. package/dist/core/agent-session.js.map +1 -1
  47. package/dist/core/auth-storage.d.ts.map +1 -1
  48. package/dist/core/auth-storage.js +20 -13
  49. package/dist/core/auth-storage.js.map +1 -1
  50. package/dist/core/bash-executor.d.ts.map +1 -1
  51. package/dist/core/bash-executor.js +40 -45
  52. package/dist/core/bash-executor.js.map +1 -1
  53. package/dist/core/bug-report.d.ts +9 -1
  54. package/dist/core/bug-report.d.ts.map +1 -1
  55. package/dist/core/compaction/utils.d.ts +6 -0
  56. package/dist/core/compaction/utils.d.ts.map +1 -1
  57. package/dist/core/compaction/utils.js +7 -8
  58. package/dist/core/compaction/utils.js.map +1 -1
  59. package/dist/core/context-snapshot.d.ts +4 -1
  60. package/dist/core/context-snapshot.d.ts.map +1 -1
  61. package/dist/core/context-snapshot.js +45 -0
  62. package/dist/core/context-snapshot.js.map +1 -1
  63. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  64. package/dist/core/export-html/tool-renderer.js +2 -0
  65. package/dist/core/export-html/tool-renderer.js.map +1 -1
  66. package/dist/core/extensions/index.d.ts +1 -1
  67. package/dist/core/extensions/index.d.ts.map +1 -1
  68. package/dist/core/extensions/index.js.map +1 -1
  69. package/dist/core/extensions/runner.d.ts +4 -2
  70. package/dist/core/extensions/runner.d.ts.map +1 -1
  71. package/dist/core/extensions/runner.js +2 -3
  72. package/dist/core/extensions/runner.js.map +1 -1
  73. package/dist/core/extensions/types.d.ts +42 -7
  74. package/dist/core/extensions/types.d.ts.map +1 -1
  75. package/dist/core/extensions/types.js.map +1 -1
  76. package/dist/core/key-id-schema.d.ts +6 -0
  77. package/dist/core/key-id-schema.d.ts.map +1 -0
  78. package/dist/core/key-id-schema.js +16 -0
  79. package/dist/core/key-id-schema.js.map +1 -0
  80. package/dist/core/keybinding-registry.d.ts +4 -3
  81. package/dist/core/keybinding-registry.d.ts.map +1 -1
  82. package/dist/core/keybinding-registry.js +4 -3
  83. package/dist/core/keybinding-registry.js.map +1 -1
  84. package/dist/core/keybindings-schema.d.ts +4 -0
  85. package/dist/core/keybindings-schema.d.ts.map +1 -0
  86. package/dist/core/keybindings-schema.js +16 -0
  87. package/dist/core/keybindings-schema.js.map +1 -0
  88. package/dist/core/keybindings.d.ts +258 -81
  89. package/dist/core/keybindings.d.ts.map +1 -1
  90. package/dist/core/keybindings.js +27 -24
  91. package/dist/core/keybindings.js.map +1 -1
  92. package/dist/core/model-config.d.ts +713 -180
  93. package/dist/core/model-config.d.ts.map +1 -1
  94. package/dist/core/model-config.js +18 -179
  95. package/dist/core/model-config.js.map +1 -1
  96. package/dist/core/model-runtime.d.ts.map +1 -1
  97. package/dist/core/model-runtime.js +13 -7
  98. package/dist/core/model-runtime.js.map +1 -1
  99. package/dist/core/nested-tool-calls.d.ts +1 -0
  100. package/dist/core/nested-tool-calls.d.ts.map +1 -1
  101. package/dist/core/nested-tool-calls.js +1 -0
  102. package/dist/core/nested-tool-calls.js.map +1 -1
  103. package/dist/core/package-manager.d.ts.map +1 -1
  104. package/dist/core/package-manager.js +3 -3
  105. package/dist/core/package-manager.js.map +1 -1
  106. package/dist/core/project-trust.d.ts.map +1 -1
  107. package/dist/core/project-trust.js +2 -1
  108. package/dist/core/project-trust.js.map +1 -1
  109. package/dist/core/remote-catalog-provider.d.ts +12 -1
  110. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  111. package/dist/core/remote-catalog-provider.js +82 -24
  112. package/dist/core/remote-catalog-provider.js.map +1 -1
  113. package/dist/core/resource-loader.d.ts.map +1 -1
  114. package/dist/core/resource-loader.js +7 -2
  115. package/dist/core/resource-loader.js.map +1 -1
  116. package/dist/core/sdk.d.ts +4 -0
  117. package/dist/core/sdk.d.ts.map +1 -1
  118. package/dist/core/sdk.js +17 -5
  119. package/dist/core/sdk.js.map +1 -1
  120. package/dist/core/settings-defaults.d.ts +65 -0
  121. package/dist/core/settings-defaults.d.ts.map +1 -0
  122. package/dist/core/settings-defaults.js +66 -0
  123. package/dist/core/settings-defaults.js.map +1 -0
  124. package/dist/core/settings-manager.d.ts +15 -147
  125. package/dist/core/settings-manager.d.ts.map +1 -1
  126. package/dist/core/settings-manager.js +85 -57
  127. package/dist/core/settings-manager.js.map +1 -1
  128. package/dist/core/settings-schema.d.ts +231 -0
  129. package/dist/core/settings-schema.d.ts.map +1 -0
  130. package/dist/core/settings-schema.js +294 -0
  131. package/dist/core/settings-schema.js.map +1 -0
  132. package/dist/core/tasks/session.d.ts +9 -0
  133. package/dist/core/tasks/session.d.ts.map +1 -1
  134. package/dist/core/tasks/session.js +21 -0
  135. package/dist/core/tasks/session.js.map +1 -1
  136. package/dist/core/tools/render-utils.d.ts +18 -0
  137. package/dist/core/tools/render-utils.d.ts.map +1 -1
  138. package/dist/core/tools/render-utils.js +46 -0
  139. package/dist/core/tools/render-utils.js.map +1 -1
  140. package/dist/core/tools/renderers/bash.d.ts.map +1 -1
  141. package/dist/core/tools/renderers/bash.js +21 -45
  142. package/dist/core/tools/renderers/bash.js.map +1 -1
  143. package/dist/core/tools/renderers/edit.js +1 -1
  144. package/dist/core/tools/renderers/edit.js.map +1 -1
  145. package/dist/extensions/btw/keybindings.d.ts +2 -2
  146. package/dist/extensions/btw/keybindings.d.ts.map +1 -1
  147. package/dist/extensions/btw/keybindings.js.map +1 -1
  148. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  149. package/dist/extensions/codemode/execute.js +115 -40
  150. package/dist/extensions/codemode/execute.js.map +1 -1
  151. package/dist/extensions/codemode/index.d.ts.map +1 -1
  152. package/dist/extensions/codemode/index.js +3 -7
  153. package/dist/extensions/codemode/index.js.map +1 -1
  154. package/dist/extensions/codemode/renderer.d.ts +2 -2
  155. package/dist/extensions/codemode/renderer.d.ts.map +1 -1
  156. package/dist/extensions/codemode/renderer.js +9 -3
  157. package/dist/extensions/codemode/renderer.js.map +1 -1
  158. package/dist/extensions/codemode/tool.d.ts +6 -12
  159. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  160. package/dist/extensions/codemode/tool.js +46 -34
  161. package/dist/extensions/codemode/tool.js.map +1 -1
  162. package/dist/extensions/index.js +2 -2
  163. package/dist/extensions/index.js.map +1 -1
  164. package/dist/extensions/list-keybindings.d.ts +2 -2
  165. package/dist/extensions/list-keybindings.d.ts.map +1 -1
  166. package/dist/extensions/list-keybindings.js.map +1 -1
  167. package/dist/extensions/llama/provider.d.ts.map +1 -1
  168. package/dist/extensions/llama/provider.js +34 -11
  169. package/dist/extensions/llama/provider.js.map +1 -1
  170. package/dist/extensions/mcp/cli.js +22 -31
  171. package/dist/extensions/mcp/cli.js.map +1 -1
  172. package/dist/extensions/mcp/index.d.ts.map +1 -1
  173. package/dist/extensions/mcp/index.js +187 -95
  174. package/dist/extensions/mcp/index.js.map +1 -1
  175. package/dist/extensions/mcp/oauth.d.ts +5 -3
  176. package/dist/extensions/mcp/oauth.d.ts.map +1 -1
  177. package/dist/extensions/mcp/oauth.js +36 -10
  178. package/dist/extensions/mcp/oauth.js.map +1 -1
  179. package/dist/extensions/mcp/resources.d.ts +0 -6
  180. package/dist/extensions/mcp/resources.d.ts.map +1 -1
  181. package/dist/extensions/mcp/resources.js +1 -1
  182. package/dist/extensions/mcp/resources.js.map +1 -1
  183. package/dist/extensions/mcp/runtime.d.ts +3 -6
  184. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  185. package/dist/extensions/mcp/runtime.js +4 -39
  186. package/dist/extensions/mcp/runtime.js.map +1 -1
  187. package/dist/extensions/mcp/tools.d.ts +2 -3
  188. package/dist/extensions/mcp/tools.d.ts.map +1 -1
  189. package/dist/extensions/mcp/tools.js +62 -6
  190. package/dist/extensions/mcp/tools.js.map +1 -1
  191. package/dist/extensions/mcp/ui.d.ts +3 -3
  192. package/dist/extensions/mcp/ui.d.ts.map +1 -1
  193. package/dist/extensions/mcp/ui.js +10 -2
  194. package/dist/extensions/mcp/ui.js.map +1 -1
  195. package/dist/extensions/provider/keybindings.d.ts +2 -2
  196. package/dist/extensions/provider/keybindings.d.ts.map +1 -1
  197. package/dist/extensions/provider/keybindings.js.map +1 -1
  198. package/dist/extensions/search/code-search.d.ts +27 -0
  199. package/dist/extensions/search/code-search.d.ts.map +1 -0
  200. package/dist/extensions/search/code-search.js +120 -0
  201. package/dist/extensions/search/code-search.js.map +1 -0
  202. package/dist/extensions/search/command.d.ts +5 -0
  203. package/dist/extensions/search/command.d.ts.map +1 -0
  204. package/dist/extensions/search/command.js +69 -0
  205. package/dist/extensions/search/command.js.map +1 -0
  206. package/dist/extensions/search/credential.d.ts +25 -0
  207. package/dist/extensions/search/credential.d.ts.map +1 -0
  208. package/dist/extensions/search/credential.js +117 -0
  209. package/dist/extensions/search/credential.js.map +1 -0
  210. package/dist/extensions/search/devin.d.ts +34 -0
  211. package/dist/extensions/search/devin.d.ts.map +1 -0
  212. package/dist/extensions/search/devin.js +210 -0
  213. package/dist/extensions/search/devin.js.map +1 -0
  214. package/dist/extensions/search/index.d.ts +5 -0
  215. package/dist/extensions/search/index.d.ts.map +1 -0
  216. package/dist/extensions/search/index.js +113 -0
  217. package/dist/extensions/search/index.js.map +1 -0
  218. package/dist/extensions/search/panel.d.ts +53 -0
  219. package/dist/extensions/search/panel.d.ts.map +1 -0
  220. package/dist/extensions/search/panel.js +157 -0
  221. package/dist/extensions/search/panel.js.map +1 -0
  222. package/dist/extensions/search/prompt.d.ts +14 -0
  223. package/dist/extensions/search/prompt.d.ts.map +1 -0
  224. package/dist/extensions/search/prompt.js +221 -0
  225. package/dist/extensions/search/prompt.js.map +1 -0
  226. package/dist/extensions/search/render.d.ts +28 -0
  227. package/dist/extensions/search/render.d.ts.map +1 -0
  228. package/dist/extensions/search/render.js +86 -0
  229. package/dist/extensions/search/render.js.map +1 -0
  230. package/dist/extensions/search/workspace.d.ts +39 -0
  231. package/dist/extensions/search/workspace.d.ts.map +1 -0
  232. package/dist/extensions/search/workspace.js +363 -0
  233. package/dist/extensions/search/workspace.js.map +1 -0
  234. package/dist/extensions/tool-search/index.d.ts.map +1 -1
  235. package/dist/extensions/tool-search/index.js +1 -6
  236. package/dist/extensions/tool-search/index.js.map +1 -1
  237. package/dist/extensions/tool-search/tool.d.ts +0 -2
  238. package/dist/extensions/tool-search/tool.d.ts.map +1 -1
  239. package/dist/extensions/tool-search/tool.js +2 -4
  240. package/dist/extensions/tool-search/tool.js.map +1 -1
  241. package/dist/index.d.ts +1 -1
  242. package/dist/index.d.ts.map +1 -1
  243. package/dist/index.js.map +1 -1
  244. package/dist/main.js +3 -3
  245. package/dist/main.js.map +1 -1
  246. package/dist/modes/interactive/components/bash-execution.d.ts +5 -1
  247. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  248. package/dist/modes/interactive/components/bash-execution.js +14 -14
  249. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  250. package/dist/modes/interactive/components/branch-summary-message.d.ts +2 -1
  251. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  252. package/dist/modes/interactive/components/branch-summary-message.js +5 -2
  253. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  254. package/dist/modes/interactive/components/compaction-summary-message.d.ts +2 -1
  255. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  256. package/dist/modes/interactive/components/compaction-summary-message.js +5 -2
  257. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  258. package/dist/modes/interactive/components/custom-entry.d.ts +3 -1
  259. package/dist/modes/interactive/components/custom-entry.d.ts.map +1 -1
  260. package/dist/modes/interactive/components/custom-entry.js +7 -2
  261. package/dist/modes/interactive/components/custom-entry.js.map +1 -1
  262. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  263. package/dist/modes/interactive/components/custom-message.js +1 -0
  264. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  265. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  266. package/dist/modes/interactive/components/settings-selector.js +4 -3
  267. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  268. package/dist/modes/interactive/components/skill-invocation-message.d.ts +2 -1
  269. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  270. package/dist/modes/interactive/components/skill-invocation-message.js +5 -2
  271. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  272. package/dist/modes/interactive/components/status-indicator.d.ts +1 -1
  273. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  274. package/dist/modes/interactive/components/status-indicator.js +2 -2
  275. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  276. package/dist/modes/interactive/interactive-mode.d.ts +2 -0
  277. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  278. package/dist/modes/interactive/interactive-mode.js +63 -64
  279. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  280. package/dist/modes/interactive/program-status-reporter.d.ts +34 -0
  281. package/dist/modes/interactive/program-status-reporter.d.ts.map +1 -0
  282. package/dist/modes/interactive/program-status-reporter.js +107 -0
  283. package/dist/modes/interactive/program-status-reporter.js.map +1 -0
  284. package/dist/modes/interactive/tasks/host-hooks.d.ts +14 -0
  285. package/dist/modes/interactive/tasks/host-hooks.d.ts.map +1 -0
  286. package/dist/modes/interactive/tasks/host-hooks.js +31 -0
  287. package/dist/modes/interactive/tasks/host-hooks.js.map +1 -0
  288. package/dist/modes/interactive/theme/dark.json +1 -1
  289. package/dist/modes/interactive/theme/light.json +1 -1
  290. package/dist/modes/interactive/theme/theme-schema.d.ts +28 -0
  291. package/dist/modes/interactive/theme/theme-schema.d.ts.map +1 -0
  292. package/dist/modes/interactive/theme/theme-schema.js +105 -0
  293. package/dist/modes/interactive/theme/theme-schema.js.map +1 -0
  294. package/dist/modes/interactive/theme/theme-tokens.d.ts +257 -0
  295. package/dist/modes/interactive/theme/theme-tokens.d.ts.map +1 -0
  296. package/dist/modes/interactive/theme/theme-tokens.js +94 -0
  297. package/dist/modes/interactive/theme/theme-tokens.js.map +1 -0
  298. package/dist/modes/interactive/theme/theme.d.ts +13 -16
  299. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  300. package/dist/modes/interactive/theme/theme.js +23 -31
  301. package/dist/modes/interactive/theme/theme.js.map +1 -1
  302. package/dist/modes/interactive/tool-view/tool-execution.d.ts +5 -0
  303. package/dist/modes/interactive/tool-view/tool-execution.d.ts.map +1 -1
  304. package/dist/modes/interactive/tool-view/tool-execution.js +7 -0
  305. package/dist/modes/interactive/tool-view/tool-execution.js.map +1 -1
  306. package/dist/modes/print-mode.d.ts.map +1 -1
  307. package/dist/modes/print-mode.js +4 -0
  308. package/dist/modes/print-mode.js.map +1 -1
  309. package/dist/package-manager-cli.d.ts.map +1 -1
  310. package/dist/package-manager-cli.js +24 -0
  311. package/dist/package-manager-cli.js.map +1 -1
  312. package/dist/utils/ansi.d.ts +8 -0
  313. package/dist/utils/ansi.d.ts.map +1 -1
  314. package/dist/utils/ansi.js +30 -11
  315. package/dist/utils/ansi.js.map +1 -1
  316. package/dist/utils/clipboard.d.ts.map +1 -1
  317. package/dist/utils/clipboard.js +18 -12
  318. package/dist/utils/clipboard.js.map +1 -1
  319. package/dist/utils/image-resize-core.d.ts +12 -0
  320. package/dist/utils/image-resize-core.d.ts.map +1 -1
  321. package/dist/utils/image-resize-core.js +5 -0
  322. package/dist/utils/image-resize-core.js.map +1 -1
  323. package/dist/utils/image-resize-worker.js +3 -2
  324. package/dist/utils/image-resize-worker.js.map +1 -1
  325. package/dist/utils/image-resize.d.ts.map +1 -1
  326. package/dist/utils/image-resize.js +9 -10
  327. package/dist/utils/image-resize.js.map +1 -1
  328. package/docs/bundled/README.md +1 -1
  329. package/docs/bundled/extensions/provider.md +1 -1
  330. package/docs/bundled/extensions/question.md +1 -1
  331. package/docs/bundled/extensions/search.md +51 -0
  332. package/docs/bundled/extensions/statusline.md +15 -41
  333. package/docs/codemode.md +24 -4
  334. package/docs/compaction.md +2 -2
  335. package/docs/docs.json +0 -4
  336. package/docs/environment-variables.md +3 -1
  337. package/docs/extensions.md +15 -5
  338. package/docs/json.md +2 -2
  339. package/docs/keybindings.md +1 -0
  340. package/docs/llama-cpp.md +8 -1
  341. package/docs/mcp.md +1 -1
  342. package/docs/models.md +5 -1
  343. package/docs/providers.md +33 -0
  344. package/docs/rpc.md +6 -3
  345. package/docs/session-format.md +1 -0
  346. package/docs/settings.md +5 -5
  347. package/docs/terminal-setup.md +14 -0
  348. package/docs/themes.md +4 -2
  349. package/docs/tui.md +1 -1
  350. package/docs/usage.md +7 -3
  351. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  352. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  353. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  354. package/examples/extensions/dynamic-resources/dynamic.json +1 -1
  355. package/examples/extensions/gondolin/package-lock.json +2 -2
  356. package/examples/extensions/gondolin/package.json +1 -1
  357. package/examples/extensions/overlay-test.ts +2 -2
  358. package/examples/extensions/plan-mode/index.ts +6 -2
  359. package/examples/extensions/sandbox/package-lock.json +2 -2
  360. package/examples/extensions/sandbox/package.json +1 -1
  361. package/examples/extensions/with-deps/package-lock.json +2 -2
  362. package/examples/extensions/with-deps/package.json +1 -1
  363. package/npm-shrinkwrap.json +54 -102
  364. package/package.json +10 -20
  365. package/schemas/keybindings.schema.json +453 -0
  366. package/schemas/models.schema.json +1157 -0
  367. package/schemas/settings.schema.json +782 -0
  368. package/schemas/theme.schema.json +365 -0
  369. package/dist/bundle/chunks/anthropic-messages-YIOJIMVL.js +0 -6
  370. package/dist/bundle/chunks/chunk-57XI7YJH.js +0 -2
  371. package/dist/bundle/chunks/chunk-JI4WGISU.js +0 -2
  372. package/dist/bundle/chunks/chunk-TCQ4HHQD.js +0 -2
  373. package/dist/bundle/chunks/chunk-TXJO4AJ7.js +0 -11
  374. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-OWU5SM6J.js +0 -2
  375. package/dist/bundle/chunks/mistral-conversations-A2N5FSOV.js +0 -5
  376. package/dist/bundle/chunks/openai-codex-responses-Q6JHCWLE.js +0 -10
  377. package/dist/bundle/chunks/typesafe-system-one-KYKKNU3E.js +0 -2
  378. package/dist/extensions/web-search/auth.d.ts +0 -12
  379. package/dist/extensions/web-search/auth.d.ts.map +0 -1
  380. package/dist/extensions/web-search/auth.js +0 -90
  381. package/dist/extensions/web-search/auth.js.map +0 -1
  382. package/dist/extensions/web-search/constants.d.ts +0 -13
  383. package/dist/extensions/web-search/constants.d.ts.map +0 -1
  384. package/dist/extensions/web-search/constants.js +0 -26
  385. package/dist/extensions/web-search/constants.js.map +0 -1
  386. package/dist/extensions/web-search/execute.d.ts +0 -9
  387. package/dist/extensions/web-search/execute.d.ts.map +0 -1
  388. package/dist/extensions/web-search/execute.js +0 -96
  389. package/dist/extensions/web-search/execute.js.map +0 -1
  390. package/dist/extensions/web-search/format.d.ts +0 -21
  391. package/dist/extensions/web-search/format.d.ts.map +0 -1
  392. package/dist/extensions/web-search/format.js +0 -117
  393. package/dist/extensions/web-search/format.js.map +0 -1
  394. package/dist/extensions/web-search/index.d.ts +0 -6
  395. package/dist/extensions/web-search/index.d.ts.map +0 -1
  396. package/dist/extensions/web-search/index.js +0 -50
  397. package/dist/extensions/web-search/index.js.map +0 -1
  398. package/dist/extensions/web-search/providers/deepseek.d.ts +0 -13
  399. package/dist/extensions/web-search/providers/deepseek.d.ts.map +0 -1
  400. package/dist/extensions/web-search/providers/deepseek.js +0 -110
  401. package/dist/extensions/web-search/providers/deepseek.js.map +0 -1
  402. package/dist/extensions/web-search/providers/http.d.ts +0 -4
  403. package/dist/extensions/web-search/providers/http.d.ts.map +0 -1
  404. package/dist/extensions/web-search/providers/http.js +0 -42
  405. package/dist/extensions/web-search/providers/http.js.map +0 -1
  406. package/dist/extensions/web-search/providers/minimax.d.ts +0 -12
  407. package/dist/extensions/web-search/providers/minimax.d.ts.map +0 -1
  408. package/dist/extensions/web-search/providers/minimax.js +0 -61
  409. package/dist/extensions/web-search/providers/minimax.js.map +0 -1
  410. package/dist/extensions/web-search/render.d.ts +0 -15
  411. package/dist/extensions/web-search/render.d.ts.map +0 -1
  412. package/dist/extensions/web-search/render.js +0 -142
  413. package/dist/extensions/web-search/render.js.map +0 -1
  414. package/dist/extensions/web-search/results.d.ts +0 -35
  415. package/dist/extensions/web-search/results.d.ts.map +0 -1
  416. package/dist/extensions/web-search/results.js +0 -167
  417. package/dist/extensions/web-search/results.js.map +0 -1
  418. package/dist/extensions/web-search/schema.d.ts +0 -10
  419. package/dist/extensions/web-search/schema.d.ts.map +0 -1
  420. package/dist/extensions/web-search/schema.js +0 -36
  421. package/dist/extensions/web-search/schema.js.map +0 -1
  422. package/dist/extensions/web-search/types.d.ts +0 -51
  423. package/dist/extensions/web-search/types.d.ts.map +0 -1
  424. package/dist/extensions/web-search/types.js +0 -5
  425. package/dist/extensions/web-search/types.js.map +0 -1
  426. package/dist/modes/interactive/theme/theme-json.d.ts +0 -85
  427. package/dist/modes/interactive/theme/theme-json.d.ts.map +0 -1
  428. package/dist/modes/interactive/theme/theme-json.js +0 -132
  429. package/dist/modes/interactive/theme/theme-json.js.map +0 -1
  430. package/dist/modes/interactive/theme/theme-schema.json +0 -361
  431. package/docs/bundled/extensions/web-search.md +0 -46
  432. package/examples/plugins/pi-example-plugin/README.md +0 -38
  433. package/examples/plugins/pi-example-plugin/package.json +0 -10
  434. package/examples/plugins/pi-example-plugin/src/contract.ts +0 -13
  435. package/examples/plugins/pi-example-plugin/src/session.ts +0 -24
  436. package/examples/plugins/pi-example-plugin/src/tui.ts +0 -31
@@ -6,8 +6,13 @@ import { getNativeClipboard } from "@earendil-works/pi-tui";
6
6
  import { runClipboardCommand } from "./clipboard-command.js";
7
7
  import { isWSL } from "./wsl.js";
8
8
  const MAX_OSC52_ENCODED_LENGTH = 100_000;
9
+ /**
10
+ * Remote sessions also emit OSC 52 so the client terminal receives the copy. PI_CLIPBOARD_OSC52=1
11
+ * covers remote clients that leave no SSH markers, such as multiplexer attaches (#10114, #10835)
12
+ * or IDE daemons (#10826).
13
+ */
9
14
  function isRemoteSession(env) {
10
- return Boolean(env.SSH_CONNECTION || env.SSH_CLIENT || env.MOSH_CONNECTION);
15
+ return Boolean(env.SSH_CONNECTION || env.SSH_CLIENT || env.MOSH_CONNECTION || env.PI_CLIPBOARD_OSC52 === "1");
11
16
  }
12
17
  function emitOsc52(text) {
13
18
  const encoded = Buffer.from(text).toString("base64");
@@ -51,20 +56,21 @@ async function copyViaWindowsClipboard(text) {
51
56
  }
52
57
  /** Read plain text from the system clipboard. */
53
58
  export async function readClipboardText() {
59
+ const commands = [];
60
+ // Termux reports platform "android", not "linux" (#10391).
61
+ if (process.env.TERMUX_VERSION)
62
+ commands.push(["termux-clipboard-get", []]);
54
63
  if (platform() === "linux") {
55
- const commands = [];
56
- if (process.env.TERMUX_VERSION)
57
- commands.push(["termux-clipboard-get", []]);
58
64
  if (process.env.WAYLAND_DISPLAY)
59
65
  commands.push(["wl-paste", ["--no-newline", "--type", "text"]]);
60
66
  if (process.env.DISPLAY) {
61
67
  commands.push(["xclip", ["-selection", "clipboard", "-out"]], ["xsel", ["--clipboard", "--output"]]);
62
68
  }
63
- for (const [command, args] of commands) {
64
- const bytes = await runClipboardCommand(command, args, { timeoutMs: 5000 });
65
- if (bytes !== undefined)
66
- return bytes.toString("utf8") || null;
67
- }
69
+ }
70
+ for (const [command, args] of commands) {
71
+ const bytes = await runClipboardCommand(command, args, { timeoutMs: 5000 });
72
+ if (bytes !== undefined)
73
+ return bytes.toString("utf8") || null;
68
74
  }
69
75
  try {
70
76
  return (await getNativeClipboard()?.getText()) || null;
@@ -140,10 +146,10 @@ export async function copyToClipboard(text) {
140
146
  return;
141
147
  if (oversized)
142
148
  throw new Error("Clipboard unavailable: text exceeds the OSC 52 size limit");
149
+ if (env.TERMUX_VERSION) {
150
+ throw new Error("Clipboard unavailable: install the Termux:API app and `termux-api` package");
151
+ }
143
152
  if (p === "linux") {
144
- if (env.TERMUX_VERSION) {
145
- throw new Error("Clipboard unavailable: install the Termux:API app and `termux-api` package");
146
- }
147
153
  if (env.WAYLAND_DISPLAY) {
148
154
  throw new Error("Clipboard unavailable: install `wl-clipboard` (`wl-copy`) or check Wayland access");
149
155
  }
@@ -1 +1 @@
1
- {"version":3,"file":"clipboard.js","sourceRoot":"","sources":["../../src/utils/clipboard.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE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AAS,CAAC,IAAI,CAAC,CAAC;QACnD,MAAM,GAAG,YAAY,IAAI,CAAC,MAAM,uBAAuB,CAAC,IAAI,CAAC,CAAC,CAAC;IAChE,CAAC;IACD,qFAAqF;IACrF,2FAA2F;IAC3F,uFAAuF;IACvF,MAAM,QAAQ,GAAG,CAAC,KAAK,OAAO,IAAI,CAAC,GAAG,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,eAAe,IAAI,CAAC,GAAG,CAAC,cAAc,CAAC;IAC9F,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,IAAI,CAAC,YAAY,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,MAAM,IAAI,QAAQ,CAAC,CAAC,EAAE,CAAC;QACtE,IAAI,SAAS,CAAC,IAAI,CAAC;YAAE,MAAM,GAAG,IAAI,CAAC;;YAC9B,SAAS,GAAG,IAAI,CAAC;IACvB,CAAC;IACD,IAAI,MAAM;QAAE,OAAO;IACnB,IAAI,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,2DAA2D,CAAC,CAAC;IAC5F,IAAI,CAAC,KAAK,OAAO,EAAE,CAAC;QACnB,IAAI,GAAG,CAAC,cAAc,EAAE,CAAC;YACxB,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;QAC/F,CAAC;QACD,IAAI,GAAG,CAAC,eAAe,EAAE,CAAC;YACzB,MAAM,IAAI,KAAK,CAAC,mFAAmF,CAAC,CAAC;QACtG,CAAC;QACD,IAAI,GAAG,CAAC,OAAO,EAAE,CAAC;YACjB,MAAM,IAAI,KAAK,CAAC,uEAAuE,CAAC,CAAC;QAC1F,CAAC;IACF,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;AAC1C,CAAC","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { unlinkSync, writeFileSync } from \"node:fs\";\nimport { platform, tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { getNativeClipboard } from \"@earendil-works/pi-tui\";\nimport { runClipboardCommand } from \"./clipboard-command.ts\";\nimport { isWSL } from \"./wsl.ts\";\n\nconst MAX_OSC52_ENCODED_LENGTH = 100_000;\n\nfunction isRemoteSession(env: NodeJS.ProcessEnv): boolean {\n\treturn Boolean(env.SSH_CONNECTION || env.SSH_CLIENT || env.MOSH_CONNECTION);\n}\n\nfunction emitOsc52(text: string): boolean {\n\tconst encoded = Buffer.from(text).toString(\"base64\");\n\tif (encoded.length > MAX_OSC52_ENCODED_LENGTH) {\n\t\treturn false;\n\t}\n\tprocess.stdout.write(`\\x1b]52;c;${encoded}\\x07`);\n\treturn true;\n}\n\n/**\n * WSL without WSLg has no Linux display, so the Windows clipboard is written through\n * interop. PowerShell reads the text from a file because `clip.exe` and PowerShell stdin\n * decode piped bytes with the console code page, which mangles non-ASCII UTF-8.\n */\nasync function copyViaWindowsClipboard(text: string): Promise<boolean> {\n\tconst tmpFile = join(tmpdir(), `pi-wsl-clip-${randomUUID()}.txt`);\n\ttry {\n\t\twriteFileSync(tmpFile, text, { encoding: \"utf8\", mode: 0o600 });\n\t\tconst winPath = (await runClipboardCommand(\"wslpath\", [\"-w\", tmpFile], { timeoutMs: 1000 }))\n\t\t\t?.toString(\"utf8\")\n\t\t\t.trim();\n\t\tif (!winPath) return false;\n\t\tconst script = `Set-Clipboard -Value ([System.IO.File]::ReadAllText('${winPath.replaceAll(\"'\", \"''\")}', [System.Text.Encoding]::UTF8))`;\n\t\tconst result = await runClipboardCommand(\"powershell.exe\", [\"-NoProfile\", \"-Command\", script], {\n\t\t\ttimeoutMs: 5000,\n\t\t});\n\t\treturn result !== undefined;\n\t} catch {\n\t\treturn false;\n\t} finally {\n\t\ttry {\n\t\t\tunlinkSync(tmpFile);\n\t\t} catch {\n\t\t\t// The file may not have been created.\n\t\t}\n\t}\n}\n\n/** Read plain text from the system clipboard. */\nexport async function readClipboardText(): Promise<string | null> {\n\tif (platform() === \"linux\") {\n\t\tconst commands: [string, string[]][] = [];\n\t\tif (process.env.TERMUX_VERSION) commands.push([\"termux-clipboard-get\", []]);\n\t\tif (process.env.WAYLAND_DISPLAY) commands.push([\"wl-paste\", [\"--no-newline\", \"--type\", \"text\"]]);\n\t\tif (process.env.DISPLAY) {\n\t\t\tcommands.push([\"xclip\", [\"-selection\", \"clipboard\", \"-out\"]], [\"xsel\", [\"--clipboard\", \"--output\"]]);\n\t\t}\n\t\tfor (const [command, args] of commands) {\n\t\t\tconst bytes = await runClipboardCommand(command, args, { timeoutMs: 5000 });\n\t\t\tif (bytes !== undefined) return bytes.toString(\"utf8\") || null;\n\t\t}\n\t}\n\ttry {\n\t\treturn (await getNativeClipboard()?.getText()) || null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Read file paths, such as Finder file copies, from the native clipboard. */\nexport async function readClipboardFilePaths(): Promise<string[] | null> {\n\tconst paths = await getNativeClipboard()?.getFilePaths?.();\n\treturn paths?.length ? paths : null;\n}\n\nexport async function copyToClipboard(text: string): Promise<void> {\n\tconst p = platform();\n\tconst env = process.env;\n\tlet copied = false;\n\t// Direct writes precede OSC 52 so the terminal cannot race the native writer.\n\t// Linux tools retain clipboard selection ownership after this call returns.\n\tif (p !== \"linux\") {\n\t\ttry {\n\t\t\tconst clipboard = getNativeClipboard();\n\t\t\tif (clipboard?.setText) {\n\t\t\t\tawait clipboard.setText(text);\n\t\t\t\tcopied = true;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Try platform commands next.\n\t\t}\n\t}\n\tif (!copied) {\n\t\tconst commands: [string, string[]][] = [];\n\t\tif (p === \"darwin\") commands.push([\"pbcopy\", []]);\n\t\telse if (p === \"win32\") commands.push([\"clip\", []]);\n\t\telse {\n\t\t\tif (env.TERMUX_VERSION) commands.push([\"termux-clipboard-set\", []]);\n\t\t\tif (env.WAYLAND_DISPLAY) commands.push([\"wl-copy\", []]);\n\t\t\tif (env.DISPLAY) {\n\t\t\t\tcommands.push([\"xclip\", [\"-selection\", \"clipboard\"]], [\"xsel\", [\"--clipboard\", \"--input\"]]);\n\t\t\t}\n\t\t}\n\t\tfor (const [command, args] of commands) {\n\t\t\tif ((await runClipboardCommand(command, args, { input: text, timeoutMs: 5000 })) !== undefined) {\n\t\t\t\tcopied = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tlet osc52Emitted = false;\n\tif (!copied && p === \"linux\" && isWSL(env)) {\n\t\t// Windows Terminal supports OSC 52; prefer it over the slower PowerShell round trip.\n\t\tif (env.WT_SESSION) osc52Emitted = emitOsc52(text);\n\t\tcopied = osc52Emitted || (await copyViaWindowsClipboard(text));\n\t}\n\t// OSC 52 cannot be verified, so a desktop session with a display reports the failure\n\t// instead (#9618). Without a display the terminal is the only clipboard route (containers,\n\t// WSL without WSLg), and remote sessions always emit it to reach the client clipboard.\n\tconst headless = p === \"linux\" && !env.DISPLAY && !env.WAYLAND_DISPLAY && !env.TERMUX_VERSION;\n\tlet oversized = false;\n\tif (!osc52Emitted && (isRemoteSession(env) || (!copied && headless))) {\n\t\tif (emitOsc52(text)) copied = true;\n\t\telse oversized = true;\n\t}\n\tif (copied) return;\n\tif (oversized) throw new Error(\"Clipboard unavailable: text exceeds the OSC 52 size limit\");\n\tif (p === \"linux\") {\n\t\tif (env.TERMUX_VERSION) {\n\t\t\tthrow new Error(\"Clipboard unavailable: install the Termux:API app and `termux-api` package\");\n\t\t}\n\t\tif (env.WAYLAND_DISPLAY) {\n\t\t\tthrow new Error(\"Clipboard unavailable: install `wl-clipboard` (`wl-copy`) or check Wayland access\");\n\t\t}\n\t\tif (env.DISPLAY) {\n\t\t\tthrow new Error(\"Clipboard unavailable: install `xclip` or `xsel`, or check X11 access\");\n\t\t}\n\t}\n\tthrow new Error(\"Clipboard unavailable\");\n}\n"]}
1
+ {"version":3,"file":"clipboard.js","sourceRoot":"","sources":["../../src/utils/clipboard.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,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{ platform, tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { getNativeClipboard } from \"@earendil-works/pi-tui\";\nimport { runClipboardCommand } from \"./clipboard-command.ts\";\nimport { isWSL } from \"./wsl.ts\";\n\nconst MAX_OSC52_ENCODED_LENGTH = 100_000;\n\n/**\n * Remote sessions also emit OSC 52 so the client terminal receives the copy. PI_CLIPBOARD_OSC52=1\n * covers remote clients that leave no SSH markers, such as multiplexer attaches (#10114, #10835)\n * or IDE daemons (#10826).\n */\nfunction isRemoteSession(env: NodeJS.ProcessEnv): boolean {\n\treturn Boolean(env.SSH_CONNECTION || env.SSH_CLIENT || env.MOSH_CONNECTION || env.PI_CLIPBOARD_OSC52 === \"1\");\n}\n\nfunction emitOsc52(text: string): boolean {\n\tconst encoded = Buffer.from(text).toString(\"base64\");\n\tif (encoded.length > MAX_OSC52_ENCODED_LENGTH) {\n\t\treturn false;\n\t}\n\tprocess.stdout.write(`\\x1b]52;c;${encoded}\\x07`);\n\treturn true;\n}\n\n/**\n * WSL without WSLg has no Linux display, so the Windows clipboard is written through\n * interop. PowerShell reads the text from a file because `clip.exe` and PowerShell stdin\n * decode piped bytes with the console code page, which mangles non-ASCII UTF-8.\n */\nasync function copyViaWindowsClipboard(text: string): Promise<boolean> {\n\tconst tmpFile = join(tmpdir(), `pi-wsl-clip-${randomUUID()}.txt`);\n\ttry {\n\t\twriteFileSync(tmpFile, text, { encoding: \"utf8\", mode: 0o600 });\n\t\tconst winPath = (await runClipboardCommand(\"wslpath\", [\"-w\", tmpFile], { timeoutMs: 1000 }))\n\t\t\t?.toString(\"utf8\")\n\t\t\t.trim();\n\t\tif (!winPath) return false;\n\t\tconst script = `Set-Clipboard -Value ([System.IO.File]::ReadAllText('${winPath.replaceAll(\"'\", \"''\")}', [System.Text.Encoding]::UTF8))`;\n\t\tconst result = await runClipboardCommand(\"powershell.exe\", [\"-NoProfile\", \"-Command\", script], {\n\t\t\ttimeoutMs: 5000,\n\t\t});\n\t\treturn result !== undefined;\n\t} catch {\n\t\treturn false;\n\t} finally {\n\t\ttry {\n\t\t\tunlinkSync(tmpFile);\n\t\t} catch {\n\t\t\t// The file may not have been created.\n\t\t}\n\t}\n}\n\n/** Read plain text from the system clipboard. */\nexport async function readClipboardText(): Promise<string | null> {\n\tconst commands: [string, string[]][] = [];\n\t// Termux reports platform \"android\", not \"linux\" (#10391).\n\tif (process.env.TERMUX_VERSION) commands.push([\"termux-clipboard-get\", []]);\n\tif (platform() === \"linux\") {\n\t\tif (process.env.WAYLAND_DISPLAY) commands.push([\"wl-paste\", [\"--no-newline\", \"--type\", \"text\"]]);\n\t\tif (process.env.DISPLAY) {\n\t\t\tcommands.push([\"xclip\", [\"-selection\", \"clipboard\", \"-out\"]], [\"xsel\", [\"--clipboard\", \"--output\"]]);\n\t\t}\n\t}\n\tfor (const [command, args] of commands) {\n\t\tconst bytes = await runClipboardCommand(command, args, { timeoutMs: 5000 });\n\t\tif (bytes !== undefined) return bytes.toString(\"utf8\") || null;\n\t}\n\ttry {\n\t\treturn (await getNativeClipboard()?.getText()) || null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Read file paths, such as Finder file copies, from the native clipboard. */\nexport async function readClipboardFilePaths(): Promise<string[] | null> {\n\tconst paths = await getNativeClipboard()?.getFilePaths?.();\n\treturn paths?.length ? paths : null;\n}\n\nexport async function copyToClipboard(text: string): Promise<void> {\n\tconst p = platform();\n\tconst env = process.env;\n\tlet copied = false;\n\t// Direct writes precede OSC 52 so the terminal cannot race the native writer.\n\t// Linux tools retain clipboard selection ownership after this call returns.\n\tif (p !== \"linux\") {\n\t\ttry {\n\t\t\tconst clipboard = getNativeClipboard();\n\t\t\tif (clipboard?.setText) {\n\t\t\t\tawait clipboard.setText(text);\n\t\t\t\tcopied = true;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Try platform commands next.\n\t\t}\n\t}\n\tif (!copied) {\n\t\tconst commands: [string, string[]][] = [];\n\t\tif (p === \"darwin\") commands.push([\"pbcopy\", []]);\n\t\telse if (p === \"win32\") commands.push([\"clip\", []]);\n\t\telse {\n\t\t\tif (env.TERMUX_VERSION) commands.push([\"termux-clipboard-set\", []]);\n\t\t\tif (env.WAYLAND_DISPLAY) commands.push([\"wl-copy\", []]);\n\t\t\tif (env.DISPLAY) {\n\t\t\t\tcommands.push([\"xclip\", [\"-selection\", \"clipboard\"]], [\"xsel\", [\"--clipboard\", \"--input\"]]);\n\t\t\t}\n\t\t}\n\t\tfor (const [command, args] of commands) {\n\t\t\tif ((await runClipboardCommand(command, args, { input: text, timeoutMs: 5000 })) !== undefined) {\n\t\t\t\tcopied = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tlet osc52Emitted = false;\n\tif (!copied && p === \"linux\" && isWSL(env)) {\n\t\t// Windows Terminal supports OSC 52; prefer it over the slower PowerShell round trip.\n\t\tif (env.WT_SESSION) osc52Emitted = emitOsc52(text);\n\t\tcopied = osc52Emitted || (await copyViaWindowsClipboard(text));\n\t}\n\t// OSC 52 cannot be verified, so a desktop session with a display reports the failure\n\t// instead (#9618). Without a display the terminal is the only clipboard route (containers,\n\t// WSL without WSLg), and remote sessions always emit it to reach the client clipboard.\n\tconst headless = p === \"linux\" && !env.DISPLAY && !env.WAYLAND_DISPLAY && !env.TERMUX_VERSION;\n\tlet oversized = false;\n\tif (!osc52Emitted && (isRemoteSession(env) || (!copied && headless))) {\n\t\tif (emitOsc52(text)) copied = true;\n\t\telse oversized = true;\n\t}\n\tif (copied) return;\n\tif (oversized) throw new Error(\"Clipboard unavailable: text exceeds the OSC 52 size limit\");\n\tif (env.TERMUX_VERSION) {\n\t\tthrow new Error(\"Clipboard unavailable: install the Termux:API app and `termux-api` package\");\n\t}\n\tif (p === \"linux\") {\n\t\tif (env.WAYLAND_DISPLAY) {\n\t\t\tthrow new Error(\"Clipboard unavailable: install `wl-clipboard` (`wl-copy`) or check Wayland access\");\n\t\t}\n\t\tif (env.DISPLAY) {\n\t\t\tthrow new Error(\"Clipboard unavailable: install `xclip` or `xsel`, or check X11 access\");\n\t\t}\n\t}\n\tthrow new Error(\"Clipboard unavailable\");\n}\n"]}
@@ -13,6 +13,18 @@ export interface ResizedImage {
13
13
  height: number;
14
14
  wasResized: boolean;
15
15
  }
16
+ /**
17
+ * Tag on image resize worker replies. Node can post its own messages on the worker channel
18
+ * (for example `{ "watch:require": [...] }` under `node --watch`), so replies must be identifiable.
19
+ */
20
+ export declare const IMAGE_RESIZE_WORKER_RESPONSE_TYPE = "pi:image-resize-response";
21
+ export type ResizeImageWorkerResponse = {
22
+ type: typeof IMAGE_RESIZE_WORKER_RESPONSE_TYPE;
23
+ result: ResizedImage | null;
24
+ } | {
25
+ type: typeof IMAGE_RESIZE_WORKER_RESPONSE_TYPE;
26
+ error: string;
27
+ };
16
28
  /**
17
29
  * Resize an image to fit within the specified max dimensions and encoded file size.
18
30
  * Returns null if the image cannot be resized below maxBytes.
@@ -1 +1 @@
1
- {"version":3,"file":"image-resize-core.d.ts","sourceRoot":"","sources":["../../src/utils/image-resize-core.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,kBAAkB;IAClC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,YAAY;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,MAAM,CAAC;IACtB,cAAc,EAAE,MAAM,CAAC;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,OAAO,CAAC;CACpB;AA2BD;;;;;;;;;;;;GAYG;AACH,wBAAsB,oBAAoB,CACzC,UAAU,EAAE,UAAU,EACtB,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,kBAAkB,GAC1B,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAqG9B"}
1
+ {"version":3,"file":"image-resize-core.d.ts","sourceRoot":"","sources":["../../src/utils/image-resize-core.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,kBAAkB;IAClC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,YAAY;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,MAAM,CAAC;IACtB,cAAc,EAAE,MAAM,CAAC;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,OAAO,CAAC;CACpB;AAED;;;GAGG;AACH,eAAO,MAAM,iCAAiC,6BAA6B,CAAC;AAE5E,MAAM,MAAM,yBAAyB,GAClC;IAAE,IAAI,EAAE,OAAO,iCAAiC,CAAC;IAAC,MAAM,EAAE,YAAY,GAAG,IAAI,CAAA;CAAE,GAC/E;IAAE,IAAI,EAAE,OAAO,iCAAiC,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AA2BrE;;;;;;;;;;;;GAYG;AACH,wBAAsB,oBAAoB,CACzC,UAAU,EAAE,UAAU,EACtB,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,kBAAkB,GAC1B,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAqG9B"}
@@ -1,5 +1,10 @@
1
1
  import { applyExifOrientation } from "./exif-orientation.js";
2
2
  import { loadPhoton } from "./photon.js";
3
+ /**
4
+ * Tag on image resize worker replies. Node can post its own messages on the worker channel
5
+ * (for example `{ "watch:require": [...] }` under `node --watch`), so replies must be identifiable.
6
+ */
7
+ export const IMAGE_RESIZE_WORKER_RESPONSE_TYPE = "pi:image-resize-response";
3
8
  // 4.5MB of base64 payload. Provides headroom below Anthropic's 5MB limit.
4
9
  const DEFAULT_MAX_BYTES = 4.5 * 1024 * 1024;
5
10
  const DEFAULT_OPTIONS = {
@@ -1 +1 @@
1
- {"version":3,"file":"image-resize-core.js","sourceRoot":"","sources":["../../src/utils/image-resize-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAmBzC,0EAA0E;AAC1E,MAAM,iBAAiB,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,CAAC;AAE5C,MAAM,eAAe,GAAiC;IACrD,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,IAAI;IACf,QAAQ,EAAE,iBAAiB;IAC3B,WAAW,EAAE,EAAE;CACf,CAAC;AAQF,SAAS,eAAe,CAAC,MAAkB,EAAE,QAAgB;IAC5D,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IACpD,OAAO;QACN,IAAI;QACJ,WAAW,EAAE,MAAM,CAAC,UAAU,CAAC,IAAI,EAAE,OAAO,CAAC;QAC7C,QAAQ;KACR,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACzC,UAAsB,EACtB,QAAgB,EAChB,OAA4B;IAE5B,MAAM,IAAI,GAAG,EAAE,GAAG,eAAe,EAAE,GAAG,OAAO,EAAE,CAAC;IAChD,MAAM,eAAe,GAAG,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,UAAU,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IAEjE,MAAM,MAAM,GAAG,MAAM,UAAU,EAAE,CAAC;IAClC,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,OAAO,IAAI,CAAC;IACb,CAAC;IAED,IAAI,KAA2E,CAAC;IAChF,IAAI,CAAC;QACJ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I;wBACpB,QAAQ,EAAE,SAAS,CAAC,QAAQ;wBAC5B,aAAa;wBACb,cAAc;wBACd,KAAK,EAAE,YAAY;wBACnB,MAAM,EAAE,aAAa;wBACrB,UAAU,EAAE,IAAI;qBAChB,CAAC;gBACH,CAAC;YACF,CAAC;YAED,IAAI,YAAY,KAAK,CAAC,IAAI,aAAa,KAAK,CAAC,EAAE,CAAC;gBAC/C,MAAM;YACP,CAAC;YAED,MAAM,SAAS,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,YAAY,GAAG,IAAI,CAAC,CAAC,CAAC;YACxF,MAAM,UAAU,GAAG,aAAa,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,aAAa,GAAG,IAAI,CAAC,CAAC,CAAC;YAC3F,IAAI,SAAS,KAAK,YAAY,IAAI,UAAU,KAAK,aAAa,EAAE,CAAC;gBAChE,MAAM;YACP,CAAC;YAED,YAAY,GAAG,SAAS,CAAC;YACzB,aAAa,GAAG,UAAU,CAAC;QAC5B,CAAC;QAED,OAAO,IAAI,CAAC;IACb,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,IAAI,CAAC;IACb,CAAC;YAAS,CAAC;QACV,IAAI,KAAK,EAAE,CAAC;YACX,KAAK,CAAC,IAAI,EAAE,CAAC;QACd,CAAC;IACF,CAAC;AACF,CAAC","sourcesContent":["import { applyExifOrientation } from \"./exif-orientation.ts\";\nimport { loadPhoton } from \"./photon.ts\";\n\nexport interface ImageResizeOptions {\n\tmaxWidth?: number; // Default: 2000\n\tmaxHeight?: number; // Default: 2000\n\tmaxBytes?: number; // Default: 4.5MB of base64 payload (below Anthropic's 5MB limit)\n\tjpegQuality?: number; // Default: 80\n}\n\nexport interface ResizedImage {\n\tdata: string; // base64\n\tmimeType: string;\n\toriginalWidth: number;\n\toriginalHeight: number;\n\twidth: number;\n\theight: number;\n\twasResized: boolean;\n}\n\n// 4.5MB of base64 payload. Provides headroom below Anthropic's 5MB limit.\nconst DEFAULT_MAX_BYTES = 4.5 * 1024 * 1024;\n\nconst DEFAULT_OPTIONS: Required<ImageResizeOptions> = {\n\tmaxWidth: 2000,\n\tmaxHeight: 2000,\n\tmaxBytes: DEFAULT_MAX_BYTES,\n\tjpegQuality: 80,\n};\n\ninterface EncodedCandidate {\n\tdata: string;\n\tencodedSize: number;\n\tmimeType: string;\n}\n\nfunction encodeCandidate(buffer: Uint8Array, mimeType: string): EncodedCandidate {\n\tconst data = Buffer.from(buffer).toString(\"base64\");\n\treturn {\n\t\tdata,\n\t\tencodedSize: Buffer.byteLength(data, \"utf-8\"),\n\t\tmimeType,\n\t};\n}\n\n/**\n * Resize an image to fit within the specified max dimensions and encoded file size.\n * Returns null if the image cannot be resized below maxBytes.\n *\n * Uses Photon (Rust/WASM) for image processing. If Photon is not available,\n * returns null.\n *\n * Strategy for staying under maxBytes:\n * 1. First resize to maxWidth/maxHeight\n * 2. Try both PNG and JPEG formats, pick the smaller one\n * 3. If still too large, try JPEG with decreasing quality\n * 4. If still too large, progressively reduce dimensions until 1x1\n */\nexport async function resizeImageInProcess(\n\tinputBytes: Uint8Array,\n\tmimeType: string,\n\toptions?: ImageResizeOptions,\n): Promise<ResizedImage | null> {\n\tconst opts = { ...DEFAULT_OPTIONS, ...options };\n\tconst inputBase64Size = Math.ceil(inputBytes.byteLength / 3) * 4;\n\n\tconst photon = await loadPhoton();\n\tif (!photon) {\n\t\treturn null;\n\t}\n\n\tlet image: ReturnType<typeof photon.PhotonImage.new_from_byteslice> | undefined;\n\ttry {\n\t\tconst rawImage = photon.PhotonImage.new_from_byteslice(inputBytes);\n\t\timage = applyExifOrientation(photon, rawImage, inputBytes);\n\t\tif (image !== rawImage) rawImage.free();\n\n\t\tconst originalWidth = image.get_width();\n\t\tconst originalHeight = image.get_height();\n\t\tconst format = mimeType.split(\"/\")[1] ?? \"png\";\n\n\t\t// Check if already within all limits (dimensions AND encoded size)\n\t\tif (originalWidth <= opts.maxWidth && originalHeight <= opts.maxHeight && inputBase64Size < opts.maxBytes) {\n\t\t\treturn {\n\t\t\t\tdata: Buffer.from(inputBytes).toString(\"base64\"),\n\t\t\t\tmimeType: mimeType || `image/${format}`,\n\t\t\t\toriginalWidth,\n\t\t\t\toriginalHeight,\n\t\t\t\twidth: originalWidth,\n\t\t\t\theight: originalHeight,\n\t\t\t\twasResized: false,\n\t\t\t};\n\t\t}\n\n\t\t// Calculate initial dimensions respecting max limits\n\t\tlet targetWidth = originalWidth;\n\t\tlet targetHeight = originalHeight;\n\n\t\tif (targetWidth > opts.maxWidth) {\n\t\t\ttargetHeight = Math.round((targetHeight * opts.maxWidth) / targetWidth);\n\t\t\ttargetWidth = opts.maxWidth;\n\t\t}\n\t\tif (targetHeight > opts.maxHeight) {\n\t\t\ttargetWidth = Math.round((targetWidth * opts.maxHeight) / targetHeight);\n\t\t\ttargetHeight = opts.maxHeight;\n\t\t}\n\n\t\tfunction tryEncodings(width: number, height: number, jpegQualities: number[]): EncodedCandidate[] {\n\t\t\tconst resized = photon!.resize(image!, width, height, photon!.SamplingFilter.Lanczos3);\n\n\t\t\ttry {\n\t\t\t\tconst candidates: EncodedCandidate[] = [encodeCandidate(resized.get_bytes(), \"image/png\")];\n\t\t\t\tfor (const quality of jpegQualities) {\n\t\t\t\t\tcandidates.push(encodeCandidate(resized.get_bytes_jpeg(quality), \"image/jpeg\"));\n\t\t\t\t}\n\t\t\t\treturn candidates;\n\t\t\t} finally {\n\t\t\t\tresized.free();\n\t\t\t}\n\t\t}\n\n\t\tconst qualitySteps = Array.from(new Set([opts.jpegQuality, 85, 70, 55, 40]));\n\t\tlet currentWidth = targetWidth;\n\t\tlet currentHeight = targetHeight;\n\n\t\twhile (true) {\n\t\t\tconst candidates = tryEncodings(currentWidth, currentHeight, qualitySteps);\n\t\t\tfor (const candidate of candidates) {\n\t\t\t\tif (candidate.encodedSize < opts.maxBytes) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdata: candidate.data,\n\t\t\t\t\t\tmimeType: candidate.mimeType,\n\t\t\t\t\t\toriginalWidth,\n\t\t\t\t\t\toriginalHeight,\n\t\t\t\t\t\twidth: currentWidth,\n\t\t\t\t\t\theight: currentHeight,\n\t\t\t\t\t\twasResized: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (currentWidth === 1 && currentHeight === 1) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst nextWidth = currentWidth === 1 ? 1 : Math.max(1, Math.floor(currentWidth * 0.75));\n\t\t\tconst nextHeight = currentHeight === 1 ? 1 : Math.max(1, Math.floor(currentHeight * 0.75));\n\t\t\tif (nextWidth === currentWidth && nextHeight === currentHeight) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcurrentWidth = nextWidth;\n\t\t\tcurrentHeight = nextHeight;\n\t\t}\n\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t} finally {\n\t\tif (image) {\n\t\t\timage.free();\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"image-resize-core.js","sourceRoot":"","sources":["../../src/utils/image-resize-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAmBzC;;;GAGG;AACH,MAAM,CAAC,MAAM,iCAAiC,GAAG,0BAA0B,CAAC;AAM5E,0EAA0E;AAC1E,MAAM,iBAAiB,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,CAAC;AAE5C,MAAM,eAAe,GAAiC;IACrD,QAAQ,EAAE,IAAI;IACd,SAAS,EAAE,IAAI;IACf,QAAQ,EAAE,iBAAiB;IAC3B,WAAW,EAAE,EAAE;CACf,CAAC;AAQF,SAAS,e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IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,aAAa,GAAG,IAAI,CAAC,CAAC,CAAC;YAC3F,IAAI,SAAS,KAAK,YAAY,IAAI,UAAU,KAAK,aAAa,EAAE,CAAC;gBAChE,MAAM;YACP,CAAC;YAED,YAAY,GAAG,SAAS,CAAC;YACzB,aAAa,GAAG,UAAU,CAAC;QAC5B,CAAC;QAED,OAAO,IAAI,CAAC;IACb,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,IAAI,CAAC;IACb,CAAC;YAAS,CAAC;QACV,IAAI,KAAK,EAAE,CAAC;YACX,KAAK,CAAC,IAAI,EAAE,CAAC;QACd,CAAC;IACF,CAAC;AACF,CAAC","sourcesContent":["import { applyExifOrientation } from \"./exif-orientation.ts\";\nimport { loadPhoton } from \"./photon.ts\";\n\nexport interface ImageResizeOptions {\n\tmaxWidth?: number; // Default: 2000\n\tmaxHeight?: number; // Default: 2000\n\tmaxBytes?: number; // Default: 4.5MB of base64 payload (below Anthropic's 5MB limit)\n\tjpegQuality?: number; // Default: 80\n}\n\nexport interface ResizedImage {\n\tdata: string; // base64\n\tmimeType: string;\n\toriginalWidth: number;\n\toriginalHeight: number;\n\twidth: number;\n\theight: number;\n\twasResized: boolean;\n}\n\n/**\n * Tag on image resize worker replies. Node can post its own messages on the worker channel\n * (for example `{ \"watch:require\": [...] }` under `node --watch`), so replies must be identifiable.\n */\nexport const IMAGE_RESIZE_WORKER_RESPONSE_TYPE = \"pi:image-resize-response\";\n\nexport type ResizeImageWorkerResponse =\n\t| { type: typeof IMAGE_RESIZE_WORKER_RESPONSE_TYPE; result: ResizedImage | null }\n\t| { type: typeof IMAGE_RESIZE_WORKER_RESPONSE_TYPE; error: string };\n\n// 4.5MB of base64 payload. Provides headroom below Anthropic's 5MB limit.\nconst DEFAULT_MAX_BYTES = 4.5 * 1024 * 1024;\n\nconst DEFAULT_OPTIONS: Required<ImageResizeOptions> = {\n\tmaxWidth: 2000,\n\tmaxHeight: 2000,\n\tmaxBytes: DEFAULT_MAX_BYTES,\n\tjpegQuality: 80,\n};\n\ninterface EncodedCandidate {\n\tdata: string;\n\tencodedSize: number;\n\tmimeType: string;\n}\n\nfunction encodeCandidate(buffer: Uint8Array, mimeType: string): EncodedCandidate {\n\tconst data = Buffer.from(buffer).toString(\"base64\");\n\treturn {\n\t\tdata,\n\t\tencodedSize: Buffer.byteLength(data, \"utf-8\"),\n\t\tmimeType,\n\t};\n}\n\n/**\n * Resize an image to fit within the specified max dimensions and encoded file size.\n * Returns null if the image cannot be resized below maxBytes.\n *\n * Uses Photon (Rust/WASM) for image processing. If Photon is not available,\n * returns null.\n *\n * Strategy for staying under maxBytes:\n * 1. First resize to maxWidth/maxHeight\n * 2. Try both PNG and JPEG formats, pick the smaller one\n * 3. If still too large, try JPEG with decreasing quality\n * 4. If still too large, progressively reduce dimensions until 1x1\n */\nexport async function resizeImageInProcess(\n\tinputBytes: Uint8Array,\n\tmimeType: string,\n\toptions?: ImageResizeOptions,\n): Promise<ResizedImage | null> {\n\tconst opts = { ...DEFAULT_OPTIONS, ...options };\n\tconst inputBase64Size = Math.ceil(inputBytes.byteLength / 3) * 4;\n\n\tconst photon = await loadPhoton();\n\tif (!photon) {\n\t\treturn null;\n\t}\n\n\tlet image: ReturnType<typeof photon.PhotonImage.new_from_byteslice> | undefined;\n\ttry {\n\t\tconst rawImage = photon.PhotonImage.new_from_byteslice(inputBytes);\n\t\timage = applyExifOrientation(photon, rawImage, inputBytes);\n\t\tif (image !== rawImage) rawImage.free();\n\n\t\tconst originalWidth = image.get_width();\n\t\tconst originalHeight = image.get_height();\n\t\tconst format = mimeType.split(\"/\")[1] ?? \"png\";\n\n\t\t// Check if already within all limits (dimensions AND encoded size)\n\t\tif (originalWidth <= opts.maxWidth && originalHeight <= opts.maxHeight && inputBase64Size < opts.maxBytes) {\n\t\t\treturn {\n\t\t\t\tdata: Buffer.from(inputBytes).toString(\"base64\"),\n\t\t\t\tmimeType: mimeType || `image/${format}`,\n\t\t\t\toriginalWidth,\n\t\t\t\toriginalHeight,\n\t\t\t\twidth: originalWidth,\n\t\t\t\theight: originalHeight,\n\t\t\t\twasResized: false,\n\t\t\t};\n\t\t}\n\n\t\t// Calculate initial dimensions respecting max limits\n\t\tlet targetWidth = originalWidth;\n\t\tlet targetHeight = originalHeight;\n\n\t\tif (targetWidth > opts.maxWidth) {\n\t\t\ttargetHeight = Math.round((targetHeight * opts.maxWidth) / targetWidth);\n\t\t\ttargetWidth = opts.maxWidth;\n\t\t}\n\t\tif (targetHeight > opts.maxHeight) {\n\t\t\ttargetWidth = Math.round((targetWidth * opts.maxHeight) / targetHeight);\n\t\t\ttargetHeight = opts.maxHeight;\n\t\t}\n\n\t\tfunction tryEncodings(width: number, height: number, jpegQualities: number[]): EncodedCandidate[] {\n\t\t\tconst resized = photon!.resize(image!, width, height, photon!.SamplingFilter.Lanczos3);\n\n\t\t\ttry {\n\t\t\t\tconst candidates: EncodedCandidate[] = [encodeCandidate(resized.get_bytes(), \"image/png\")];\n\t\t\t\tfor (const quality of jpegQualities) {\n\t\t\t\t\tcandidates.push(encodeCandidate(resized.get_bytes_jpeg(quality), \"image/jpeg\"));\n\t\t\t\t}\n\t\t\t\treturn candidates;\n\t\t\t} finally {\n\t\t\t\tresized.free();\n\t\t\t}\n\t\t}\n\n\t\tconst qualitySteps = Array.from(new Set([opts.jpegQuality, 85, 70, 55, 40]));\n\t\tlet currentWidth = targetWidth;\n\t\tlet currentHeight = targetHeight;\n\n\t\twhile (true) {\n\t\t\tconst candidates = tryEncodings(currentWidth, currentHeight, qualitySteps);\n\t\t\tfor (const candidate of candidates) {\n\t\t\t\tif (candidate.encodedSize < opts.maxBytes) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdata: candidate.data,\n\t\t\t\t\t\tmimeType: candidate.mimeType,\n\t\t\t\t\t\toriginalWidth,\n\t\t\t\t\t\toriginalHeight,\n\t\t\t\t\t\twidth: currentWidth,\n\t\t\t\t\t\theight: currentHeight,\n\t\t\t\t\t\twasResized: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (currentWidth === 1 && currentHeight === 1) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst nextWidth = currentWidth === 1 ? 1 : Math.max(1, Math.floor(currentWidth * 0.75));\n\t\t\tconst nextHeight = currentHeight === 1 ? 1 : Math.max(1, Math.floor(currentHeight * 0.75));\n\t\t\tif (nextWidth === currentWidth && nextHeight === currentHeight) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcurrentWidth = nextWidth;\n\t\t\tcurrentHeight = nextHeight;\n\t\t}\n\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t} finally {\n\t\tif (image) {\n\t\t\timage.free();\n\t\t}\n\t}\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { parentPort } from "node:worker_threads";
2
- import { resizeImageInProcess } from "./image-resize-core.js";
2
+ import { IMAGE_RESIZE_WORKER_RESPONSE_TYPE, resizeImageInProcess, } from "./image-resize-core.js";
3
3
  function isResizeImageWorkerRequest(value) {
4
4
  if (!value || typeof value !== "object")
5
5
  return false;
@@ -17,11 +17,12 @@ port.once("message", (message) => {
17
17
  throw new Error("Invalid image resize worker request");
18
18
  }
19
19
  const result = await resizeImageInProcess(message.inputBytes, message.mimeType, message.options);
20
- const response = { result };
20
+ const response = { type: IMAGE_RESIZE_WORKER_RESPONSE_TYPE, result };
21
21
  port.postMessage(response);
22
22
  }
23
23
  catch (error) {
24
24
  const response = {
25
+ type: IMAGE_RESIZE_WORKER_RESPONSE_TYPE,
25
26
  error: error instanceof Error ? error.message : String(error),
26
27
  };
27
28
  port.postMessage(response);
@@ -1 +1 @@
1
- {"version":3,"file":"image-resize-worker.js","sourceRoot":"","sources":["../../src/utils/image-resize-worker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAA8C,oBAAoB,EA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ageResizeOptions, type ResizedImage, resizeImageInProcess } from \"./image-resize-core.ts\";\n\ninterface ResizeImageWorkerRequest {\n\tinputBytes: Uint8Array;\n\tmimeType: string;\n\toptions?: ImageResizeOptions;\n}\n\ninterface ResizeImageWorkerResponse {\n\tresult?: ResizedImage | null;\n\terror?: string;\n}\n\nfunction isResizeImageWorkerRequest(value: unknown): value is ResizeImageWorkerRequest {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst record = value as Record<string, unknown>;\n\treturn record.inputBytes instanceof Uint8Array && typeof record.mimeType === \"string\";\n}\n\nconst port = parentPort;\nif (!port) {\n\tthrow new Error(\"image resize worker requires parentPort\");\n}\n\nport.once(\"message\", (message: unknown) => {\n\tvoid (async () => {\n\t\ttry {\n\t\t\tif (!isResizeImageWorkerRequest(message)) {\n\t\t\t\tthrow new Error(\"Invalid image resize worker request\");\n\t\t\t}\n\t\t\tconst result = await resizeImageInProcess(message.inputBytes, message.mimeType, message.options);\n\t\t\tconst response: ResizeImageWorkerResponse = { result };\n\t\t\tport.postMessage(response);\n\t\t} catch (error) {\n\t\t\tconst response: ResizeImageWorkerResponse = {\n\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t};\n\t\t\tport.postMessage(response);\n\t\t}\n\t})();\n});\n"]}
1
+ {"version":3,"file":"image-resize-worker.js","sourceRoot":"","sources":["../../src/utils/image-resize-worker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EACN,iCAAiC,EAGjC,oBAAoB,GACpB,MAAM,wBAAwB,CAAC;AAQhC,SAAS,0BAA0B,CAAC,KAAc;IACjD,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACtD,MAAM,MAAM,GAAG,KAAgC,CAAC;IAChD,OAAO,MAAM,CAAC,UAAU,YAAY,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ,CAAC;AACvF,CAAC;AAED,MAAM,IAAI,GAAG,UAAU,CAAC;AACxB,IAAI,CAAC,IAAI,EAAE,CAAC;IACX,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;AAC5D,CAAC;AAED,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC,OAAgB,EAAE,EAAE;IACzC,KAAK,CAAC,KAAK,IAAI,EAAE;QAChB,IAAI,CAAC;YACJ,IAAI,CAAC,0BAA0B,CAAC,OAAO,CAAC,EAAE,CAAC;gBAC1C,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;YACxD,CAAC;YACD,MAAM,MAAM,GAAG,MAAM,oBAAoB,CAAC,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;YACjG,MAAM,QAAQ,GAA8B,EAAE,IAAI,EAAE,iCAAiC,EAAE,MAAM,EAAE,CAAC;YAChG,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;QAC5B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,MAAM,QAAQ,GAA8B;gBAC3C,IAAI,EAAE,iCAAiC;gBACvC,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;aAC7D,CAAC;YACF,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;QAC5B,CAAC;IACF,CAAC,CAAC,EAAE,CAAC;AACN,CAAC,CAAC,CAAC","sourcesContent":["import { parentPort } from \"node:worker_threads\";\nimport {\n\tIMAGE_RESIZE_WORKER_RESPONSE_TYPE,\n\ttype ImageResizeOptions,\n\ttype ResizeImageWorkerResponse,\n\tresizeImageInProcess,\n} from \"./image-resize-core.ts\";\n\ninterface ResizeImageWorkerRequest {\n\tinputBytes: Uint8Array;\n\tmimeType: string;\n\toptions?: ImageResizeOptions;\n}\n\nfunction isResizeImageWorkerRequest(value: unknown): value is ResizeImageWorkerRequest {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst record = value as Record<string, unknown>;\n\treturn record.inputBytes instanceof Uint8Array && typeof record.mimeType === \"string\";\n}\n\nconst port = parentPort;\nif (!port) {\n\tthrow new Error(\"image resize worker requires parentPort\");\n}\n\nport.once(\"message\", (message: unknown) => {\n\tvoid (async () => {\n\t\ttry {\n\t\t\tif (!isResizeImageWorkerRequest(message)) {\n\t\t\t\tthrow new Error(\"Invalid image resize worker request\");\n\t\t\t}\n\t\t\tconst result = await resizeImageInProcess(message.inputBytes, message.mimeType, message.options);\n\t\t\tconst response: ResizeImageWorkerResponse = { type: IMAGE_RESIZE_WORKER_RESPONSE_TYPE, result };\n\t\t\tport.postMessage(response);\n\t\t} catch (error) {\n\t\t\tconst response: ResizeImageWorkerResponse = {\n\t\t\t\ttype: IMAGE_RESIZE_WORKER_RESPONSE_TYPE,\n\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t};\n\t\t\tport.postMessage(response);\n\t\t}\n\t})();\n});\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"image-resize.d.ts","sourceRoot":"","sources":["../../src/utils/image-resize.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,kBAAkB,EAAE,KAAK,YAAY,EAAwB,MAAM,wBAAwB,CAAC;AAE1G,YAAY,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AA0E/E;;;;;;GAMG;AACH,wBAAsB,WAAW,CAChC,UAAU,EAAE,UAAU,EACtB,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,kBAAkB,GAC1B,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAqB9B;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,CAO5E"}
1
+ {"version":3,"file":"image-resize.d.ts","sourceRoot":"","sources":["../../src/utils/image-resize.ts"],"names":[],"mappings":"AACA,OAAO,EAEN,KAAK,kBAAkB,EACvB,KAAK,YAAY,EAGjB,MAAM,wBAAwB,CAAC;AAEhC,YAAY,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAmE/E;;;;;;GAMG;AACH,wBAAsB,WAAW,CAChC,UAAU,EAAE,UAAU,EACtB,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,kBAAkB,GAC1B,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAqB9B;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,CAO5E"}
@@ -1,12 +1,12 @@
1
1
  import { Worker } from "node:worker_threads";
2
- import { resizeImageInProcess } from "./image-resize-core.js";
2
+ import { IMAGE_RESIZE_WORKER_RESPONSE_TYPE, resizeImageInProcess, } from "./image-resize-core.js";
3
3
  function toTransferableBytes(input) {
4
4
  // Transfer detaches the buffer, so transfer a worker-owned copy and leave the
5
5
  // caller's bytes intact.
6
6
  return new Uint8Array(input);
7
7
  }
8
8
  function isResizeImageWorkerResponse(value) {
9
- return value !== null && typeof value === "object";
9
+ return (value !== null && typeof value === "object" && "type" in value && value.type === IMAGE_RESIZE_WORKER_RESPONSE_TYPE);
10
10
  }
11
11
  function createResizeWorker(workerSpecifier) {
12
12
  return new Worker(workerSpecifier);
@@ -29,16 +29,15 @@ async function resizeImageInWorker(workerSpecifier, inputBytes, mimeType, option
29
29
  settled = true;
30
30
  reject(error);
31
31
  };
32
- worker.once("message", (message) => {
33
- if (!isResizeImageWorkerResponse(message)) {
34
- fail(new Error("Invalid image resize worker response"));
32
+ worker.on("message", (message) => {
33
+ // Ignore messages Node posts on the worker channel itself, such as
34
+ // `{ "watch:require": [...] }` under `node --watch` (nodejs/node#65044).
35
+ if (!isResizeImageWorkerResponse(message))
35
36
  return;
36
- }
37
- if (message.error) {
37
+ if ("error" in message)
38
38
  fail(new Error(message.error));
39
- return;
40
- }
41
- settle(message.result ?? null);
39
+ else
40
+ settle(message.result);
42
41
  });
43
42
  worker.once("error", fail);
44
43
  worker.once("exit", (code) => {
@@ -1 +1 @@
1
- {"version":3,"file":"image-resize.js","sourceRoot":"","sources":["../../src/utils/image-resize.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAA8C,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAS1G,SAAS,mBAAmB,CAAC,KAAiB;IAC7C,8EAA8E;IAC9E,yBAAyB;IACzB,OAAO,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;AAC9B,CAAC;AAED,SAAS,2BAA2B,CAAC,KAAc;IAClD,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC;AACpD,CAAC;AAED,SAAS,kBAAkB,CAAC,eAA6B;IACxD,OAAO,IAAI,MAAM,CAAC,eAAe,CAAC,CAAC;AACpC,CAAC;AAED,KAAK,UAAU,mBAAmB,CACjC,eAA6B,EAC7B,UAAsB,EACtB,QAAgB,EAChB,OAA4B;IAE5B,MAAM,MAAM,GAAG,kBAAkB,CAAC,eAAe,CAAC,CAAC;IACnD,IAAI,CAAC;QACJ,MAAM,mBAAmB,GAAG,mBAAmB,CAAC,UAAU,CAAC,CAAC;QAC5D,OAAO,MAAM,IAAI,OAAO,CAAsB,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACjE,IAAI,OAAO,GAAG,KAAK,CAAC;YACpB,MAAM,MAAM,GAAG,CAAC,MAA2B,EAAQ,EAAE;gBACpD,IAAI,OAAO;oBAAE,OAAO;gBACpB,OAAO,GAAG,IAAI,CAAC;gBACf,OAAO,CAAC,MAAM,CAAC,CAAC;YACjB,CAAC,CAAC;YACF,MAAM,IAAI,GAAG,CAAC,KAAY,EAAQ,EAAE;gBACnC,IAAI,OAAO;oBAAE,OAAO;gBACpB,OAAO,GAAG,IAAI,CA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,CAAC,KAAK,CAAC,CAAC;IAC5D,MAAM,SAAS,GAAG,IAAI,GAAG,CACxB,mBAAmB,CAAC,CAAC,CAAC,0BAA0B,CAAC,CAAC,CAAC,0BAA0B,EAC7E,MAAM,CAAC,IAAI,CAAC,GAAG,CACf,CAAC;IAEF,8EAA8E;IAC9E,4EAA4E;IAC5E,8EAA8E;IAC9E,IAAI,OAAO,OAAO,CAAC,QAAQ,CAAC,GAAG,KAAK,QAAQ,EAAE,CAAC;QAC9C,IAAI,CAAC;YACJ,OAAO,MAAM,mBAAmB,CAAC,oCAAoC,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;QACvG,CAAC;QAAC,MAAM,CAAC,CAAA,CAAC;IACX,CAAC;IAED,IAAI,CAAC;QACJ,OAAO,MAAM,mBAAmB,CAAC,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC5E,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,oBAAoB,CAAC,UAAU,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC5D,CAAC;AACF,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAAoB;IACvD,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;QACxB,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,MAAM,KAAK,GAAG,MAAM,CAAC,aAAa,GAAG,MAAM,CAAC,KAAK,CAAC;IAClD,OAAO,oBAAoB,MAAM,CAAC,aAAa,IAAI,MAAM,CAAC,cAAc,kBAAkB,MAAM,CAAC,KAAK,IAAI,MAAM,CAAC,MAAM,6BAA6B,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,6BAA6B,CAAC;AACnM,CAAC","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport { type ImageResizeOptions, type ResizedImage, resizeImageInProcess } from \"./image-resize-core.ts\";\n\nexport type { ImageResizeOptions, ResizedImage } from \"./image-resize-core.ts\";\n\ninterface ResizeImageWorkerResponse {\n\tresult?: ResizedImage | null;\n\terror?: string;\n}\n\nfunction toTransferableBytes(input: Uint8Array): Uint8Array<ArrayBuffer> {\n\t// Transfer detaches the buffer, so transfer a worker-owned copy and leave the\n\t// caller's bytes intact.\n\treturn new Uint8Array(input);\n}\n\nfunction isResizeImageWorkerResponse(value: unknown): value is ResizeImageWorkerResponse {\n\treturn value !== null && typeof value === \"object\";\n}\n\nfunction createResizeWorker(workerSpecifier: string | URL): Worker {\n\treturn new Worker(workerSpecifier);\n}\n\nasync function resizeImageInWorker(\n\tworkerSpecifier: string | URL,\n\tinputBytes: Uint8Array,\n\tmimeType: string,\n\toptions?: ImageResizeOptions,\n): Promise<ResizedImage | null> {\n\tconst worker = createResizeWorker(workerSpecifier);\n\ttry {\n\t\tconst inputBytesForWorker = toTransferableBytes(inputBytes);\n\t\treturn await new Promise<ResizedImage | null>((resolve, reject) => {\n\t\t\tlet settled = false;\n\t\t\tconst settle = (result: ResizedImage | null): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tresolve(result);\n\t\t\t};\n\t\t\tconst fail = (error: Error): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\treject(error);\n\t\t\t};\n\n\t\t\tworker.once(\"message\", (message: unknown) => {\n\t\t\t\tif (!isResizeImageWorkerResponse(message)) {\n\t\t\t\t\tfail(new Error(\"Invalid image resize worker response\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (message.error) {\n\t\t\t\t\tfail(new Error(message.error));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettle(message.result ?? null);\n\t\t\t});\n\t\t\tworker.once(\"error\", fail);\n\t\t\tworker.once(\"exit\", (code) => {\n\t\t\t\tif (!settled) {\n\t\t\t\t\tfail(new Error(`Image resize worker exited with code ${code}`));\n\t\t\t\t}\n\t\t\t});\n\t\t\tworker.postMessage(\n\t\t\t\t{\n\t\t\t\t\tinputBytes: inputBytesForWorker,\n\t\t\t\t\tmimeType,\n\t\t\t\t\toptions,\n\t\t\t\t},\n\t\t\t\t[inputBytesForWorker.buffer],\n\t\t\t);\n\t\t});\n\t} finally {\n\t\tvoid worker.terminate().catch(() => undefined);\n\t}\n}\n\n/**\n * Resize an image to fit within the specified max dimensions and encoded file size.\n * Runs Photon in a worker thread so WASM decoding, resizing, and encoding do not\n * block the TUI event loop. If the worker cannot be loaded (for example in some\n * Bun compiled executable layouts), fall back to in-process resizing so image\n * reads still work.\n */\nexport async function resizeImage(\n\tinputBytes: Uint8Array,\n\tmimeType: string,\n\toptions?: ImageResizeOptions,\n): Promise<ResizedImage | null> {\n\tconst isTypeScriptRuntime = import.meta.url.endsWith(\".ts\");\n\tconst workerUrl = new URL(\n\t\tisTypeScriptRuntime ? \"./image-resize-worker.ts\" : \"./image-resize-worker.js\",\n\t\timport.meta.url,\n\t);\n\n\t// Bun compiled executables resolve worker entrypoints by string path, not via\n\t// new URL(..., import.meta.url). Try the string path first under Bun so the\n\t// release binary uses the embedded worker instead of falling back in-process.\n\tif (typeof process.versions.bun === \"string\") {\n\t\ttry {\n\t\t\treturn await resizeImageInWorker(\"./src/utils/image-resize-worker.ts\", inputBytes, mimeType, options);\n\t\t} catch {}\n\t}\n\n\ttry {\n\t\treturn await resizeImageInWorker(workerUrl, inputBytes, mimeType, options);\n\t} catch {\n\t\treturn resizeImageInProcess(inputBytes, mimeType, options);\n\t}\n}\n\n/**\n * Format a dimension note for resized images.\n * This helps the model understand the coordinate mapping.\n */\nexport function formatDimensionNote(result: ResizedImage): string | undefined {\n\tif (!result.wasResized) {\n\t\treturn undefined;\n\t}\n\n\tconst scale = result.originalWidth / result.width;\n\treturn `[Image: original ${result.originalWidth}x${result.originalHeight}, displayed at ${result.width}x${result.height}. Multiply coordinates by ${scale.toFixed(2)} to map to original image.]`;\n}\n"]}
1
+ {"version":3,"file":"image-resize.js","sourceRoot":"","sources":["../../src/utils/image-resize.ts"],"names":[],"mappings":"A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E,8EAA8E;IAC9E,IAAI,OAAO,OAAO,CAAC,QAAQ,CAAC,GAAG,KAAK,QAAQ,EAAE,CAAC;QAC9C,IAAI,CAAC;YACJ,OAAO,MAAM,mBAAmB,CAAC,oCAAoC,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;QACvG,CAAC;QAAC,MAAM,CAAC,CAAA,CAAC;IACX,CAAC;IAED,IAAI,CAAC;QACJ,OAAO,MAAM,mBAAmB,CAAC,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC5E,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,oBAAoB,CAAC,UAAU,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC5D,CAAC;AACF,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAAoB;IACvD,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;QACxB,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,MAAM,KAAK,GAAG,MAAM,CAAC,aAAa,GAAG,MAAM,CAAC,KAAK,CAAC;IAClD,OAAO,oBAAoB,MAAM,CAAC,aAAa,IAAI,MAAM,CAAC,cAAc,kBAAkB,MAAM,CAAC,KAAK,IAAI,MAAM,CAAC,MAAM,6BAA6B,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,6BAA6B,CAAC;AACnM,CAAC","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport {\n\tIMAGE_RESIZE_WORKER_RESPONSE_TYPE,\n\ttype ImageResizeOptions,\n\ttype ResizedImage,\n\ttype ResizeImageWorkerResponse,\n\tresizeImageInProcess,\n} from \"./image-resize-core.ts\";\n\nexport type { ImageResizeOptions, ResizedImage } from \"./image-resize-core.ts\";\n\nfunction toTransferableBytes(input: Uint8Array): Uint8Array<ArrayBuffer> {\n\t// Transfer detaches the buffer, so transfer a worker-owned copy and leave the\n\t// caller's bytes intact.\n\treturn new Uint8Array(input);\n}\n\nfunction isResizeImageWorkerResponse(value: unknown): value is ResizeImageWorkerResponse {\n\treturn (\n\t\tvalue !== null && typeof value === \"object\" && \"type\" in value && value.type === IMAGE_RESIZE_WORKER_RESPONSE_TYPE\n\t);\n}\n\nfunction createResizeWorker(workerSpecifier: string | URL): Worker {\n\treturn new Worker(workerSpecifier);\n}\n\nasync function resizeImageInWorker(\n\tworkerSpecifier: string | URL,\n\tinputBytes: Uint8Array,\n\tmimeType: string,\n\toptions?: ImageResizeOptions,\n): Promise<ResizedImage | null> {\n\tconst worker = createResizeWorker(workerSpecifier);\n\ttry {\n\t\tconst inputBytesForWorker = toTransferableBytes(inputBytes);\n\t\treturn await new Promise<ResizedImage | null>((resolve, reject) => {\n\t\t\tlet settled = false;\n\t\t\tconst settle = (result: ResizedImage | null): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tresolve(result);\n\t\t\t};\n\t\t\tconst fail = (error: Error): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\treject(error);\n\t\t\t};\n\n\t\t\tworker.on(\"message\", (message: unknown) => {\n\t\t\t\t// Ignore messages Node posts on the worker channel itself, such as\n\t\t\t\t// `{ \"watch:require\": [...] }` under `node --watch` (nodejs/node#65044).\n\t\t\t\tif (!isResizeImageWorkerResponse(message)) return;\n\t\t\t\tif (\"error\" in message) fail(new Error(message.error));\n\t\t\t\telse settle(message.result);\n\t\t\t});\n\t\t\tworker.once(\"error\", fail);\n\t\t\tworker.once(\"exit\", (code) => {\n\t\t\t\tif (!settled) {\n\t\t\t\t\tfail(new Error(`Image resize worker exited with code ${code}`));\n\t\t\t\t}\n\t\t\t});\n\t\t\tworker.postMessage(\n\t\t\t\t{\n\t\t\t\t\tinputBytes: inputBytesForWorker,\n\t\t\t\t\tmimeType,\n\t\t\t\t\toptions,\n\t\t\t\t},\n\t\t\t\t[inputBytesForWorker.buffer],\n\t\t\t);\n\t\t});\n\t} finally {\n\t\tvoid worker.terminate().catch(() => undefined);\n\t}\n}\n\n/**\n * Resize an image to fit within the specified max dimensions and encoded file size.\n * Runs Photon in a worker thread so WASM decoding, resizing, and encoding do not\n * block the TUI event loop. If the worker cannot be loaded (for example in some\n * Bun compiled executable layouts), fall back to in-process resizing so image\n * reads still work.\n */\nexport async function resizeImage(\n\tinputBytes: Uint8Array,\n\tmimeType: string,\n\toptions?: ImageResizeOptions,\n): Promise<ResizedImage | null> {\n\tconst isTypeScriptRuntime = import.meta.url.endsWith(\".ts\");\n\tconst workerUrl = new URL(\n\t\tisTypeScriptRuntime ? \"./image-resize-worker.ts\" : \"./image-resize-worker.js\",\n\t\timport.meta.url,\n\t);\n\n\t// Bun compiled executables resolve worker entrypoints by string path, not via\n\t// new URL(..., import.meta.url). Try the string path first under Bun so the\n\t// release binary uses the embedded worker instead of falling back in-process.\n\tif (typeof process.versions.bun === \"string\") {\n\t\ttry {\n\t\t\treturn await resizeImageInWorker(\"./src/utils/image-resize-worker.ts\", inputBytes, mimeType, options);\n\t\t} catch {}\n\t}\n\n\ttry {\n\t\treturn await resizeImageInWorker(workerUrl, inputBytes, mimeType, options);\n\t} catch {\n\t\treturn resizeImageInProcess(inputBytes, mimeType, options);\n\t}\n}\n\n/**\n * Format a dimension note for resized images.\n * This helps the model understand the coordinate mapping.\n */\nexport function formatDimensionNote(result: ResizedImage): string | undefined {\n\tif (!result.wasResized) {\n\t\treturn undefined;\n\t}\n\n\tconst scale = result.originalWidth / result.width;\n\treturn `[Image: original ${result.originalWidth}x${result.originalHeight}, displayed at ${result.width}x${result.height}. Multiply coordinates by ${scale.toFixed(2)} to map to original image.]`;\n}\n"]}
@@ -24,7 +24,7 @@ The following extensions are additions maintained by `@astralyn/pi`:
24
24
  | [Question](extensions/question.md) | `question` | Ask structured questions through native interactive UI |
25
25
  | [Provider](extensions/provider.md) | `/provider` | Edit models.json providers: connection, API type, and models |
26
26
  | [Statusline](extensions/statusline.md) | Footer status | Show concise extension-managed activity state |
27
- | [Web Search](extensions/web-search.md) | `web_search` | Search the live web through MiniMax and DeepSeek with fused results |
27
+ | [Search](extensions/search.md) | `code_search`, `web_search` | Devin-driven semantic code search and web search with one shared key |
28
28
 
29
29
  All bundled extensions use the public Extension API. Enable or disable them in `pi config` or through `builtin:<name>` entries in [settings](../settings.md#codemode-and-tool-selection). `--no-extensions` disables them; `-e builtin:<name>` loads one explicitly.
30
30
 
@@ -1,4 +1,4 @@
1
- # provider — visual models.json editor
1
+ # Provider
2
2
 
3
3
  Minimalist visual editor for the `providers` record of `models.json` (`~/.pi/agent/models.json`; respects `PI_CODING_AGENT_DIR`). The extension never registers runtime providers and stores no parallel configuration; Pi's native [models.json](../../models.md) mechanism remains the source of truth. See [Providers](../../providers.md) for credential setup and runtime resolution.
4
4
 
@@ -1,4 +1,4 @@
1
- # question — structured user questions
1
+ # Question
2
2
 
3
3
  Adds a `question` tool for asking one to four multiple-choice questions when the agent needs a user decision. A Pi-native take on AskUserQuestion: a lightweight custom dialog with concise transcript summaries and a bounded model-facing result.
4
4
 
@@ -0,0 +1,51 @@
1
+ # Search
2
+
3
+ Devin Search adds two tools that share one Devin sign-in:
4
+
5
+ | Tool | What it does |
6
+ |---|---|
7
+ | `code_search` | Finds where behavior lives in the local repository from a plain-language description |
8
+ | `web_search` | Searches the live web and returns page excerpts |
9
+
10
+ In the transcript, each call is one line: the query, then live progress while it runs and the number of files or results once it finishes. Expand it (`Ctrl+O` or a click) to see the files with their line ranges, or the result titles with their sites; titles open the page. A failed call always shows its error.
11
+
12
+ ## Signing in
13
+
14
+ Run `/search` to open the Devin Search panel. It shows whether you are signed in and offers:
15
+
16
+ - **Sign in with browser** opens `app.devin.ai` (the panel also shows the link, and the copy key copies it). Approve access, then paste the code Devin shows into the panel. Pasting a session token there works too.
17
+ - **Paste a token** saves an existing Devin session token.
18
+ - **Sign out** removes the saved token after a confirmation.
19
+
20
+ The panel checks every new token with Devin before saving it, so a rejected token never replaces a working one. The token is saved, exactly as Devin issued it, to `~/.pi/agent/search-auth.json`.
21
+
22
+ For headless and CI runs, set `SEARCH_KEY` to a Devin session token. A saved token takes precedence over it.
23
+
24
+ Without a credential, a session starts with both tools turned off. Signing in turns them on; turning one off with `/tools` is respected.
25
+
26
+ ## code_search
27
+
28
+ `code_search` sends your query and a directory tree of the working directory (up to three levels) to Devin's SWE-grep model. The model plans up to three rounds of up to eight read-only commands, `rg`, `readfile`, and `tree`, which run on your machine, and then answers with files and line ranges. The result is a reading list to verify, not evidence.
29
+
30
+ What leaves your machine: the query, the directory tree, and the output of the commands the model runs, including the file contents it reads.
31
+
32
+ Enforced locally, not by Devin:
33
+
34
+ - **Confinement.** Every path the model names must resolve inside the searched directory, both as written and after following symlinks.
35
+ - **Ignored files stay local.** The tree, `rg`, and `readfile` see only the files ripgrep would search: anything excluded by `.gitignore`, `.ignore`, or `.rgignore` (even outside a git repository) is neither listed, searched, nor read, even when the model names it. So, at any depth and with or without an ignore file, are `.git` and dependency and cache directories such as `node_modules`, `.venv`, and `__pycache__`. To hide more, such as a committed `vendor/` directory, add it to `.ignore`.
36
+ - **Read-only.** The three commands are the only operations; there is no shell and no write.
37
+ - **Bounded output.** Each command result is capped at 40 lines of 200 characters, and each request times out after 30 seconds.
38
+
39
+ | Parameter | Type | Default | Description |
40
+ |---|---|---|---|
41
+ | `query` | string | required | The behavior, flow, error, or concept to locate, in concise English. Keep identifiers and error text verbatim |
42
+ | `path` | string | working directory | Subdirectory to search; must be inside the working directory |
43
+
44
+ ## web_search
45
+
46
+ `web_search` returns up to 10 results, each with a title, URL, and the parts of the page that match the query (shortened to 1,500 characters).
47
+
48
+ | Parameter | Type | Default | Description |
49
+ |---|---|---|---|
50
+ | `query` | string | required | Search query. Be specific: product names, versions, exact error text |
51
+ | `max_results` | int 1–10 | 5 | Results to return |
@@ -1,9 +1,6 @@
1
- # statusline — fixed two-line footer
1
+ # Statusline
2
2
 
3
- Replaces Pi's built-in footer with a fixed, color-coded two-line status display
4
- using a balanced left/right layout. It registers no tool or command and has no
5
- configuration file. The footer auto-enables on `session_start` in TUI mode and
6
- clears itself on `session_shutdown`.
3
+ Replaces Pi's built-in footer with a fixed, color-coded two-line status display using a balanced left/right layout. It registers no tool or command and has no configuration file. The footer auto-enables on `session_start` in TUI mode and clears itself on `session_shutdown`.
7
4
 
8
5
  ## What it shows
9
6
 
@@ -17,10 +14,8 @@ CTX 2.1%/1.0M ↑13k ↓13k R440k CH99.4% $0.074
17
14
  **Left**
18
15
 
19
16
  - **Model:** human-readable model name, falling back to the model id.
20
- - **Provider:** the model source in parentheses, such as `(deepseek)` or
21
- `(opencode-go)`.
22
- - **Effort:** the current runtime thinking level when the model supports reasoning and
23
- the level is not `off`.
17
+ - **Provider:** the model source in parentheses, such as `(deepseek)` or `(opencode-go)`.
18
+ - **Effort:** the current runtime thinking level when the model supports reasoning and the level is not `off`.
24
19
 
25
20
  **Right**
26
21
 
@@ -31,8 +26,7 @@ CTX 2.1%/1.0M ↑13k ↓13k R440k CH99.4% $0.074
31
26
 
32
27
  **Left**
33
28
 
34
- - **Context:** used percentage plus context-window size. The percentage uses
35
- fixed semantic tiers: accent normally, warning above 40%, error above 80%.
29
+ - **Context:** used percentage plus context-window size. The percentage uses fixed semantic tiers: accent normally, warning above 40%, error above 80%.
36
30
 
37
31
  **Right**
38
32
 
@@ -41,20 +35,12 @@ CTX 2.1%/1.0M ↑13k ↓13k R440k CH99.4% $0.074
41
35
  - `R` cumulative cache-read tokens.
42
36
  - `W` cumulative cache-write tokens, omitted when zero.
43
37
  - Cumulative totals include assistant requests, usage-bearing tool results, compaction summaries, branch summaries, and independently settled Background usage records on the active branch.
44
- - `CH` cache-hit percentage for the latest assistant request, calculated as
45
- `cacheRead / (input + cacheRead + cacheWrite)` and shown only when that
46
- request used cache.
47
- - `$` cumulative cost; `(sub)` is appended when the current model uses an OAuth
48
- subscription.
38
+ - `CH` cache-hit percentage for the latest assistant request, calculated as `cacheRead / (input + cacheRead + cacheWrite)` and shown only when that request used cache.
39
+ - `$` cumulative cost; `(sub)` is appended when the current model uses an OAuth subscription.
49
40
 
50
41
  **Middle (optional)**
51
42
 
52
- - Extension status text from `ctx.ui.setStatus()` is sorted by key and pinned
53
- to the center of the line — anchored to the absolute line center so it does
54
- not drift as the usage cluster grows, falling back to balancing the free
55
- space when the side zones collide with the center anchor. When space runs
56
- out it is dropped so CTX and usage stay readable. Plain text is muted;
57
- strings that already carry ANSI color are left unchanged.
43
+ - Extension status text from `ctx.ui.setStatus()` is sorted by key and pinned to the center of the line — anchored to the absolute line center so it does not drift as the usage cluster grows, falling back to balancing the free space when the side zones collide with the center anchor. When space runs out it is dropped so CTX and usage stay readable. Plain text is muted; strings that already carry ANSI color are left unchanged.
58
44
 
59
45
  Background billing uses the first valid `task-usage` record per execution ID; managed foreground results omit duplicate `usage`. Opening `/tasks`, detaching, or repeating `tasks read`/`wait` does not add billing. Accrued worker retry, cancellation, failure, and provider-supplied compaction usage is included when settled; missing usage is not fabricated. Quarantined late settlements are excluded from active totals. This does not change the footer's active-branch scope (session-wide statistics can include other branches), parent CTX estimate, or latest-parent-request `CH`. See the [persisted record format](../../session-format.md#background-records).
60
46
 
@@ -74,14 +60,11 @@ When the terminal is too narrow for the full layout:
74
60
  4. Model/effort with the short path and git branch, then the short path alone.
75
61
  5. Model/effort alone.
76
62
 
77
- The short path is `~/basename` (or bare basename). Shortening the path or dropping
78
- the provider can make room for the branch again. If none of these pairs fits,
79
- the model/effort and short path are truncated.
63
+ The short path is `~/basename` (or bare basename). Shortening the path or dropping the provider can make room for the branch again. If none of these pairs fits, the model/effort and short path are truncated.
80
64
 
81
65
  **Line 2** (first drop → last):
82
66
 
83
- 1. Keep the fullest usage cluster that fits beside CTX, trying full usage,
84
- then without `W`, then without `W` and `R`.
67
+ 1. Keep the fullest usage cluster that fits beside CTX, trying full usage, then without `W`, then without `W` and `R`.
85
68
  2. Include centered extension status only if the selected pair leaves enough room.
86
69
  3. If no usage variant fits, omit status and truncate CTX with the full usage cluster.
87
70
 
@@ -94,17 +77,13 @@ Status therefore yields to usage; it never causes an extra usage field to be dro
94
77
  - Context uses `accent`, `warning`, or `error` according to the fixed thresholds.
95
78
  - Working directory uses `success`; Git branch uses `accent`.
96
79
  - Usage statistics use `dim`; extension status text uses `muted`.
97
- - Each line left-aligns its primary cluster and right-aligns the secondary
98
- cluster, filling the gap with spaces so wide terminals stay balanced.
80
+ - Each line left-aligns its primary cluster and right-aligns the secondary cluster, filling the gap with spaces so wide terminals stay balanced.
99
81
 
100
- Pi does not expose auto-compaction state to extension footer factories, so the
101
- native `(auto)` marker is intentionally not reproduced.
82
+ Pi does not expose auto-compaction state to extension footer factories, so the native `(auto)` marker is intentionally not reproduced.
102
83
 
103
84
  ## Migration
104
85
 
105
- The previous `/statusline` command and `~/.pi/agent/pi-config/statusline.json`
106
- configuration are no longer used. An existing config file is left untouched and
107
- may be removed manually.
86
+ The previous `/statusline` command and `~/.pi/agent/pi-config/statusline.json` configuration are no longer used. An existing config file is left untouched and may be removed manually.
108
87
 
109
88
  ## Limits
110
89
 
@@ -113,11 +92,6 @@ may be removed manually.
113
92
 
114
93
  ## Implementation notes
115
94
 
116
- Footer paint runs on every TUI render. Each footer instance keeps one cache for
117
- active-branch usage totals and the latest assistant cache-hit percentage, keyed
118
- by session manager, session id, and leaf id. It clears on footer `invalidate()`.
119
- Session entries are append-only: finalized messages and usage records advance
120
- the leaf, so accounting does not need to inspect streaming message mutations.
95
+ Footer paint runs on every TUI render. Each footer instance keeps one cache for active-branch usage totals and the latest assistant cache-hit percentage, keyed by session manager, session id, and leaf id. It clears on footer `invalidate()`. Session entries are append-only: finalized messages and usage records advance the leaf, so accounting does not need to inspect streaming message mutations.
121
96
 
122
- Thinking level and context usage come from the live Extension API. Rendering
123
- receives plain display data and owns no session state or subscriptions.
97
+ Thinking level and context usage come from the live Extension API. Rendering receives plain display data and owns no session state or subscriptions.
package/docs/codemode.md CHANGED
@@ -6,7 +6,7 @@ The `codemode` tool lets the model write a JavaScript script that calls pi's oth
6
6
 
7
7
  The tool input is raw JavaScript source, not JSON and not a markdown code fence. It runs as the body of an async function in a QuickJS sandbox, so top-level `await` and `return` work. The sandbox has no Node APIs, file system, network, or timers; scripts reach the outside world only through tools and `models`.
8
8
 
9
- A script may start with an options line:
9
+ A script may start with an options line. It must be the first line; an options line anywhere else fails the call before the script runs:
10
10
 
11
11
  ```js
12
12
  // @options: {"max_output_tokens": 2000, "timeout_ms": 60000}
@@ -15,7 +15,7 @@ A script may start with an options line:
15
15
  - `max_output_tokens` (default 10000) limits the output. Longer output keeps its start and end, and the full text is written to a temp file whose path is included in the result. A script fails when its output passes 16777216 characters of text and base64 image data or 100000 `text()`, `image()`, and `console` calls; write large data to a file with a tool instead.
16
16
  - `timeout_ms` is a hard deadline for the whole script. It is unset by default. Image generation can take minutes, so do not set a short deadline for scripts that generate images.
17
17
 
18
- The result starts with `Script completed` or `Script failed`, the wall time, and the output. A failed script keeps its partial output, followed by `Script error:` and the error. Tool calls are real: calls made before a failure are not undone. Calls still running when the script ends are cancelled, and unawaited promises are discarded.
18
+ The result starts with `Script completed` or `Script failed`, the wall time, and the output. Text and image items appear in order, each on its own line. When the output has more than one text item (from `text()` or `return`), each starts with a `==> text N/M <==` line. `console` calls follow in one `<console_output>` block with one line per call. A failed script keeps its partial output, followed by `Script error:` and the error. Tool calls are real: calls made before a failure are not undone. Calls still running when the script ends are cancelled, and unawaited promises are discarded.
19
19
 
20
20
  ## Globals
21
21
 
@@ -24,7 +24,7 @@ The result starts with `Script completed` or `Script failed`, the wall time, and
24
24
  | `tools.<name>(args)` | Call a tool. See [Call tools](#call-tools). |
25
25
  | `text(value)` | Add a text item to the output. Strings are added as is, other values as JSON. |
26
26
  | `image(value)` | Add an image to the output: a base64 `data:` URL, an `{ image_url }` object, or an image block `{ type: "image", data, mimeType }` such as those returned by MCP tools and `models.generateImages()`. Remote URLs are not supported. PNG, JPEG, GIF, and WebP are accepted. Each image is also saved to a temp file, and the result names the path before the image. |
27
- | `console.log(...)` | Like `text()`; `info`, `warn`, `error`, and `debug` do the same. |
27
+ | `console.log(...)` | Add a line to the `<console_output>` block after the other output. Arguments are joined with spaces; `info`, `warn`, `error`, and `debug` do the same. |
28
28
  | `return value` | A top-level `return` adds the value like `text()`. |
29
29
  | `exit()` | End the script successfully. |
30
30
  | `store(key, value)` / `load(key)` | Keep small JSON values across `codemode` calls. See [Store values](#store-values). |
@@ -59,7 +59,7 @@ The store is for small state such as IDs, cursors, or summaries. One value may h
59
59
 
60
60
  ## Models
61
61
 
62
- `models` reaches the model catalog and runs non-LLM models with the session's credentials: classifiers, which answer typed questions about JSON state, and image models, which generate images. Chat models are listed but cannot be run from scripts. Which classifier and image models exist is described in [Use classifier models](models.md#use-classifier-models) and [Use image models](models.md#use-image-models).
62
+ `models` reaches the model catalog and runs non-LLM models with the session's credentials: classifiers, which answer typed questions about JSON state and, for some models, images, and image models, which generate images. Chat models are listed but cannot be run from scripts. Which classifier and image models exist is described in [Use classifier models](models.md#use-classifier-models) and [Use image models](models.md#use-image-models).
63
63
 
64
64
  ```ts
65
65
  type ModelType = "chat" | "image" | "classifier";
@@ -100,6 +100,8 @@ Model IDs differ between providers, for example `typesafe/jev-latest` and `openr
100
100
  interface ClassifierContext {
101
101
  /** The data to classify. */
102
102
  state: Record<string, unknown>;
103
+ /** Images judged together with `state`. Only models whose `input` includes "image" accept them. */
104
+ images?: { type: "image"; data: string; mimeType: string }[];
103
105
  /** Questions by ID. One call answers all of them. */
104
106
  questions: Record<string, ClassifierQuestion>;
105
107
  }
@@ -163,6 +165,24 @@ return results.map((result, i) =>
163
165
  );
164
166
  ```
165
167
 
168
+ Classifiers whose `input` includes `"image"` also judge images. `tools.read()` returns an image file as an image block that `images` accepts. Other classifiers return an error result when `images` is not empty.
169
+
170
+ ```js
171
+ const luna = await models.getModelOfType("classifier", "openai", "gpt-6-luna");
172
+ const photo = await tools.read({ path: "screenshot.png" });
173
+ const result = await models.classify(luna, {
174
+ state: { task: "Settings page redesign" },
175
+ images: [photo],
176
+ questions: {
177
+ broken: {
178
+ type: "bool",
179
+ instructions: "Does the screenshot show a broken layout?",
180
+ criteria: { true: "Overlapping, cut-off, or misaligned elements", false: "Clean layout" },
181
+ },
182
+ },
183
+ });
184
+ ```
185
+
166
186
  ### Generate images
167
187
 
168
188
  ```ts
@@ -288,7 +288,6 @@ Before summarization, the exported `serializeConversation()` function serializes
288
288
 
289
289
  ```
290
290
  [User]: What they said
291
- [Assistant thinking]: Internal reasoning
292
291
  [Assistant]: Response text
293
292
  [Assistant tool calls]: read(path="foo.ts"); edit(path="bar.ts", ...)
294
293
  [Tool result]: Output from tool
@@ -296,6 +295,8 @@ Before summarization, the exported `serializeConversation()` function serializes
296
295
 
297
296
  This prevents the model from treating it as a conversation to continue.
298
297
 
298
+ Thinking blocks are omitted. Providers return summaries of the real reasoning, and replayed thinking is often not part of the model's live context, so including it could make the summarization request larger than the context it summarizes.
299
+
299
300
  Tool results are truncated to 2000 characters during serialization. Content beyond that limit is replaced with a marker indicating how many characters were truncated. This keeps summarization requests within reasonable token budgets, since tool results (especially from `read` and `bash`) are typically the largest contributors to context size.
300
301
 
301
302
  ## Custom Summarization via Extensions
@@ -354,7 +355,6 @@ pi.on("session_before_compact", async (event, ctx) => {
354
355
  );
355
356
  // Returns:
356
357
  // [User]: message text
357
- // [Assistant thinking]: thinking content
358
358
  // [Assistant]: response text
359
359
  // [Assistant tool calls]: read(path="..."); bash(command="...")
360
360
  // [Tool result]: output text