@bastani/atomic 0.9.28-alpha.1 → 0.9.28-alpha.3

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 (332) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/builtin/intercom/package.json +1 -1
  3. package/dist/builtin/mcp/native-client-licenses/NOTICE +2 -0
  4. package/dist/builtin/mcp/package.json +1 -1
  5. package/dist/builtin/subagents/package.json +1 -1
  6. package/dist/builtin/web-access/package.json +1 -1
  7. package/dist/builtin/workflows/CHANGELOG.md +34 -0
  8. package/dist/builtin/workflows/builtin/{chunk-wz8v67bn.js → chunk-aqv8ny38.js} +257 -259
  9. package/dist/builtin/workflows/builtin/{chunk-f61w0hpm.js → chunk-br4ac9a3.js} +1 -1
  10. package/dist/builtin/workflows/builtin/{chunk-tecnpe8j.js → chunk-p3xmajmj.js} +438 -39
  11. package/dist/builtin/workflows/builtin/chunk-p6jagvyf.js +8 -0
  12. package/dist/builtin/workflows/builtin/goal.js +2 -2
  13. package/dist/builtin/workflows/builtin/index.js +4 -4
  14. package/dist/builtin/workflows/builtin/ralph.js +2 -2
  15. package/dist/builtin/workflows/package.json +1 -1
  16. package/dist/builtin/workflows/src/authoring.d.ts +14 -0
  17. package/dist/builtin/workflows/src/extension/index.bundle.mjs +111102 -110218
  18. package/dist/builtin/workflows/src/index.js +42284 -41141
  19. package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +16 -11
  20. package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +16 -1
  21. package/dist/cli/args.d.ts.map +1 -1
  22. package/dist/cli/args.js +8 -1
  23. package/dist/cli/args.js.map +1 -1
  24. package/dist/cli/credential-print.d.ts +1 -1
  25. package/dist/cli/credential-print.d.ts.map +1 -1
  26. package/dist/cli/credential-print.js +2 -56
  27. package/dist/cli/credential-print.js.map +1 -1
  28. package/dist/config.d.ts +2 -1
  29. package/dist/config.d.ts.map +1 -1
  30. package/dist/config.js +4 -2
  31. package/dist/config.js.map +1 -1
  32. package/dist/core/agent-session-accessors.d.ts.map +1 -1
  33. package/dist/core/agent-session-accessors.js +6 -1
  34. package/dist/core/agent-session-accessors.js.map +1 -1
  35. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  36. package/dist/core/agent-session-compaction.js +20 -3
  37. package/dist/core/agent-session-compaction.js.map +1 -1
  38. package/dist/core/agent-session-events.d.ts.map +1 -1
  39. package/dist/core/agent-session-events.js +2 -1
  40. package/dist/core/agent-session-events.js.map +1 -1
  41. package/dist/core/agent-session-extension-bindings.d.ts +6 -0
  42. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  43. package/dist/core/agent-session-extension-bindings.js +90 -9
  44. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  45. package/dist/core/agent-session-methods.d.ts +3 -1
  46. package/dist/core/agent-session-methods.d.ts.map +1 -1
  47. package/dist/core/agent-session-methods.js.map +1 -1
  48. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  49. package/dist/core/agent-session-prompt.js +14 -1
  50. package/dist/core/agent-session-prompt.js.map +1 -1
  51. package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
  52. package/dist/core/agent-session-tool-registry.js +1 -0
  53. package/dist/core/agent-session-tool-registry.js.map +1 -1
  54. package/dist/core/agent-session-types.d.ts +2 -0
  55. package/dist/core/agent-session-types.d.ts.map +1 -1
  56. package/dist/core/agent-session-types.js.map +1 -1
  57. package/dist/core/agent-session.d.ts +1 -0
  58. package/dist/core/agent-session.d.ts.map +1 -1
  59. package/dist/core/agent-session.js +6 -1
  60. package/dist/core/agent-session.js.map +1 -1
  61. package/dist/core/bash-executor.d.ts.map +1 -1
  62. package/dist/core/bash-executor.js +22 -4
  63. package/dist/core/bash-executor.js.map +1 -1
  64. package/dist/core/child-session-options.d.ts.map +1 -1
  65. package/dist/core/child-session-options.js +17 -2
  66. package/dist/core/child-session-options.js.map +1 -1
  67. package/dist/core/compaction/classifier-compaction.d.ts +13 -0
  68. package/dist/core/compaction/classifier-compaction.d.ts.map +1 -0
  69. package/dist/core/compaction/classifier-compaction.js +110 -0
  70. package/dist/core/compaction/classifier-compaction.js.map +1 -0
  71. package/dist/core/compaction/compaction-boundary.d.ts.map +1 -1
  72. package/dist/core/compaction/compaction-boundary.js +2 -6
  73. package/dist/core/compaction/compaction-boundary.js.map +1 -1
  74. package/dist/core/compaction/compaction-runner.d.ts +16 -1
  75. package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
  76. package/dist/core/compaction/compaction-runner.js +97 -12
  77. package/dist/core/compaction/compaction-runner.js.map +1 -1
  78. package/dist/core/compaction/compaction-types.d.ts +18 -1
  79. package/dist/core/compaction/compaction-types.d.ts.map +1 -1
  80. package/dist/core/compaction/compaction-types.js +1 -1
  81. package/dist/core/compaction/compaction-types.js.map +1 -1
  82. package/dist/core/compaction/fallback-planner.d.ts +1 -0
  83. package/dist/core/compaction/fallback-planner.d.ts.map +1 -1
  84. package/dist/core/compaction/fallback-planner.js +2 -0
  85. package/dist/core/compaction/fallback-planner.js.map +1 -1
  86. package/dist/core/compaction/index.d.ts +3 -0
  87. package/dist/core/compaction/index.d.ts.map +1 -1
  88. package/dist/core/compaction/index.js +3 -0
  89. package/dist/core/compaction/index.js.map +1 -1
  90. package/dist/core/compaction/model-resolver.d.ts +16 -0
  91. package/dist/core/compaction/model-resolver.d.ts.map +1 -0
  92. package/dist/core/compaction/model-resolver.js +18 -0
  93. package/dist/core/compaction/model-resolver.js.map +1 -0
  94. package/dist/core/compaction/morph-compaction.d.ts +14 -0
  95. package/dist/core/compaction/morph-compaction.d.ts.map +1 -0
  96. package/dist/core/compaction/morph-compaction.js +99 -0
  97. package/dist/core/compaction/morph-compaction.js.map +1 -0
  98. package/dist/core/compaction/pi-summary-fallback.d.ts +34 -0
  99. package/dist/core/compaction/pi-summary-fallback.d.ts.map +1 -0
  100. package/dist/core/compaction/pi-summary-fallback.js +357 -0
  101. package/dist/core/compaction/pi-summary-fallback.js.map +1 -0
  102. package/dist/core/compaction/planner-outcome.d.ts +10 -6
  103. package/dist/core/compaction/planner-outcome.d.ts.map +1 -1
  104. package/dist/core/compaction/planner-outcome.js +11 -4
  105. package/dist/core/compaction/planner-outcome.js.map +1 -1
  106. package/dist/core/compaction/range-planner-diagnostics.d.ts +3 -1
  107. package/dist/core/compaction/range-planner-diagnostics.d.ts.map +1 -1
  108. package/dist/core/compaction/range-planner-diagnostics.js +11 -0
  109. package/dist/core/compaction/range-planner-diagnostics.js.map +1 -1
  110. package/dist/core/compaction/range-planner.d.ts +3 -3
  111. package/dist/core/compaction/range-planner.d.ts.map +1 -1
  112. package/dist/core/compaction/range-planner.js +59 -28
  113. package/dist/core/compaction/range-planner.js.map +1 -1
  114. package/dist/core/compaction/region-trimming.d.ts.map +1 -1
  115. package/dist/core/compaction/region-trimming.js +7 -0
  116. package/dist/core/compaction/region-trimming.js.map +1 -1
  117. package/dist/core/compaction/structured-compaction-input.d.ts +19 -0
  118. package/dist/core/compaction/structured-compaction-input.d.ts.map +1 -0
  119. package/dist/core/compaction/structured-compaction-input.js +70 -0
  120. package/dist/core/compaction/structured-compaction-input.js.map +1 -0
  121. package/dist/core/compaction/transcript-serialization.d.ts +1 -0
  122. package/dist/core/compaction/transcript-serialization.d.ts.map +1 -1
  123. package/dist/core/compaction/transcript-serialization.js +26 -0
  124. package/dist/core/compaction/transcript-serialization.js.map +1 -1
  125. package/dist/core/extensions/api-types.d.ts +2 -2
  126. package/dist/core/extensions/api-types.d.ts.map +1 -1
  127. package/dist/core/extensions/api-types.js.map +1 -1
  128. package/dist/core/extensions/context-types.d.ts +1 -0
  129. package/dist/core/extensions/context-types.d.ts.map +1 -1
  130. package/dist/core/extensions/context-types.js.map +1 -1
  131. package/dist/core/extensions/loader-api.js.map +1 -1
  132. package/dist/core/extensions/loader-virtual-modules.d.ts +3 -4
  133. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  134. package/dist/core/extensions/loader-virtual-modules.js +14 -9
  135. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  136. package/dist/core/extensions/runner-context.d.ts +10 -4
  137. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  138. package/dist/core/extensions/runner-context.js +47 -3
  139. package/dist/core/extensions/runner-context.js.map +1 -1
  140. package/dist/core/extensions/runner.d.ts +10 -3
  141. package/dist/core/extensions/runner.d.ts.map +1 -1
  142. package/dist/core/extensions/runner.js +31 -7
  143. package/dist/core/extensions/runner.js.map +1 -1
  144. package/dist/core/extensions/tool-events.d.ts +1 -1
  145. package/dist/core/extensions/tool-events.js.map +1 -1
  146. package/dist/core/extensions/ts-source-specifiers.d.ts +18 -0
  147. package/dist/core/extensions/ts-source-specifiers.d.ts.map +1 -0
  148. package/dist/core/extensions/ts-source-specifiers.js +142 -0
  149. package/dist/core/extensions/ts-source-specifiers.js.map +1 -0
  150. package/dist/core/extensions/workflow-events.d.ts +49 -0
  151. package/dist/core/extensions/workflow-events.d.ts.map +1 -1
  152. package/dist/core/extensions/workflow-events.js.map +1 -1
  153. package/dist/core/extensions/workflow-run-control-hub.d.ts +16 -4
  154. package/dist/core/extensions/workflow-run-control-hub.d.ts.map +1 -1
  155. package/dist/core/extensions/workflow-run-control-hub.js +72 -1
  156. package/dist/core/extensions/workflow-run-control-hub.js.map +1 -1
  157. package/dist/core/extensions/workflow-run-control.d.ts +11 -3
  158. package/dist/core/extensions/workflow-run-control.d.ts.map +1 -1
  159. package/dist/core/extensions/workflow-run-control.js.map +1 -1
  160. package/dist/core/messages.d.ts +1 -0
  161. package/dist/core/messages.d.ts.map +1 -1
  162. package/dist/core/messages.js +5 -1
  163. package/dist/core/messages.js.map +1 -1
  164. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  165. package/dist/core/remote-catalog-provider.js +3 -0
  166. package/dist/core/remote-catalog-provider.js.map +1 -1
  167. package/dist/core/sdk-exports.d.ts +2 -2
  168. package/dist/core/sdk-exports.js.map +1 -1
  169. package/dist/core/sdk-types.d.ts +3 -0
  170. package/dist/core/sdk-types.d.ts.map +1 -1
  171. package/dist/core/sdk-types.js.map +1 -1
  172. package/dist/core/sdk.d.ts.map +1 -1
  173. package/dist/core/sdk.js +17 -8
  174. package/dist/core/sdk.js.map +1 -1
  175. package/dist/core/session-manager-history.d.ts.map +1 -1
  176. package/dist/core/session-manager-history.js +4 -2
  177. package/dist/core/session-manager-history.js.map +1 -1
  178. package/dist/core/settings-manager-basic-accessors.d.ts +2 -0
  179. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  180. package/dist/core/settings-manager-basic-accessors.js +29 -0
  181. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  182. package/dist/core/settings-manager-core.js.map +1 -1
  183. package/dist/core/settings-merge.d.ts +3 -0
  184. package/dist/core/settings-merge.d.ts.map +1 -1
  185. package/dist/core/settings-merge.js +18 -4
  186. package/dist/core/settings-merge.js.map +1 -1
  187. package/dist/core/settings-storage.js.map +1 -1
  188. package/dist/core/settings-types.d.ts +1 -0
  189. package/dist/core/settings-types.d.ts.map +1 -1
  190. package/dist/core/settings-types.js.map +1 -1
  191. package/dist/core/transcript.d.ts +58 -0
  192. package/dist/core/transcript.d.ts.map +1 -0
  193. package/dist/core/transcript.js +185 -0
  194. package/dist/core/transcript.js.map +1 -0
  195. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  196. package/dist/extensions/codemode/execute.js +14 -1
  197. package/dist/extensions/codemode/execute.js.map +1 -1
  198. package/dist/extensions/codemode/tool.js +2 -2
  199. package/dist/extensions/codemode/tool.js.map +1 -1
  200. package/dist/extensions/herdr/index.d.ts.map +1 -1
  201. package/dist/extensions/herdr/index.js +15 -10
  202. package/dist/extensions/herdr/index.js.map +1 -1
  203. package/dist/extensions/herdr/pane-owner.d.ts +6 -2
  204. package/dist/extensions/herdr/pane-owner.d.ts.map +1 -1
  205. package/dist/extensions/herdr/pane-owner.js +19 -4
  206. package/dist/extensions/herdr/pane-owner.js.map +1 -1
  207. package/dist/extensions/llama/provider.d.ts.map +1 -1
  208. package/dist/extensions/llama/provider.js +19 -8
  209. package/dist/extensions/llama/provider.js.map +1 -1
  210. package/dist/extensions/mcp/cli.js +18 -24
  211. package/dist/extensions/mcp/cli.js.map +1 -1
  212. package/dist/extensions/mcp/client/auth-provider.d.ts +4 -0
  213. package/dist/extensions/mcp/client/auth-provider.d.ts.map +1 -1
  214. package/dist/extensions/mcp/client/auth-provider.js.map +1 -1
  215. package/dist/extensions/mcp/client/oauth/discovery.d.ts +3 -0
  216. package/dist/extensions/mcp/client/oauth/discovery.d.ts.map +1 -1
  217. package/dist/extensions/mcp/client/oauth/discovery.js +8 -5
  218. package/dist/extensions/mcp/client/oauth/discovery.js.map +1 -1
  219. package/dist/extensions/mcp/client/oauth/flow.d.ts +4 -0
  220. package/dist/extensions/mcp/client/oauth/flow.d.ts.map +1 -1
  221. package/dist/extensions/mcp/client/oauth/flow.js +12 -2
  222. package/dist/extensions/mcp/client/oauth/flow.js.map +1 -1
  223. package/dist/extensions/mcp/client/transports/streamable-http.d.ts +3 -0
  224. package/dist/extensions/mcp/client/transports/streamable-http.d.ts.map +1 -1
  225. package/dist/extensions/mcp/client/transports/streamable-http.js +17 -14
  226. package/dist/extensions/mcp/client/transports/streamable-http.js.map +1 -1
  227. package/dist/extensions/mcp/index.d.ts.map +1 -1
  228. package/dist/extensions/mcp/index.js +150 -72
  229. package/dist/extensions/mcp/index.js.map +1 -1
  230. package/dist/extensions/mcp/oauth.d.ts +5 -3
  231. package/dist/extensions/mcp/oauth.d.ts.map +1 -1
  232. package/dist/extensions/mcp/oauth.js +36 -10
  233. package/dist/extensions/mcp/oauth.js.map +1 -1
  234. package/dist/extensions/mcp/ui.d.ts +3 -3
  235. package/dist/extensions/mcp/ui.d.ts.map +1 -1
  236. package/dist/extensions/mcp/ui.js +10 -2
  237. package/dist/extensions/mcp/ui.js.map +1 -1
  238. package/dist/index.d.ts +3 -1
  239. package/dist/index.d.ts.map +1 -1
  240. package/dist/index.js +2 -0
  241. package/dist/index.js.map +1 -1
  242. package/dist/main-deferred-startup.d.ts +1 -0
  243. package/dist/main-deferred-startup.d.ts.map +1 -1
  244. package/dist/main-deferred-startup.js +9 -21
  245. package/dist/main-deferred-startup.js.map +1 -1
  246. package/dist/main.d.ts.map +1 -1
  247. package/dist/main.js +8 -6
  248. package/dist/main.js.map +1 -1
  249. package/dist/modes/interactive/components/compaction-boundary-message.d.ts +2 -0
  250. package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
  251. package/dist/modes/interactive/components/compaction-boundary-message.js +15 -3
  252. package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
  253. package/dist/modes/interactive/components/settings-selector-items.d.ts.map +1 -1
  254. package/dist/modes/interactive/components/settings-selector-items.js +43 -0
  255. package/dist/modes/interactive/components/settings-selector-items.js.map +1 -1
  256. package/dist/modes/interactive/components/settings-selector-types.d.ts +6 -0
  257. package/dist/modes/interactive/components/settings-selector-types.d.ts.map +1 -1
  258. package/dist/modes/interactive/components/settings-selector-types.js.map +1 -1
  259. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  260. package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
  261. package/dist/modes/interactive/interactive-input-handling.js +1 -47
  262. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  263. package/dist/modes/interactive/interactive-mode-base.d.ts +0 -1
  264. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  265. package/dist/modes/interactive/interactive-mode-base.js +0 -1
  266. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  267. package/dist/modes/interactive/interactive-mode-surface.d.ts +0 -1
  268. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  269. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  270. package/dist/modes/interactive/interactive-prompt-restore.d.ts.map +1 -1
  271. package/dist/modes/interactive/interactive-prompt-restore.js +0 -5
  272. package/dist/modes/interactive/interactive-prompt-restore.js.map +1 -1
  273. package/dist/modes/interactive/interactive-prompt-turn.js +6 -4
  274. package/dist/modes/interactive/interactive-prompt-turn.js.map +1 -1
  275. package/dist/modes/interactive/interactive-render-chat.js +13 -6
  276. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  277. package/dist/modes/interactive/interactive-selectors.js +8 -0
  278. package/dist/modes/interactive/interactive-selectors.js.map +1 -1
  279. package/dist/modes/interactive/interactive-session-runtime.js +2 -0
  280. package/dist/modes/interactive/interactive-session-runtime.js.map +1 -1
  281. package/dist/modes/interactive/interactive-startup.js +1 -1
  282. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  283. package/dist/modes/rpc/rpc-client-process.d.ts +7 -0
  284. package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
  285. package/dist/modes/rpc/rpc-client-process.js +20 -3
  286. package/dist/modes/rpc/rpc-client-process.js.map +1 -1
  287. package/dist/modes/rpc/rpc-command-timeouts.d.ts.map +1 -1
  288. package/dist/modes/rpc/rpc-command-timeouts.js +1 -0
  289. package/dist/modes/rpc/rpc-command-timeouts.js.map +1 -1
  290. package/dist/utils/ansi.d.ts +8 -0
  291. package/dist/utils/ansi.d.ts.map +1 -1
  292. package/dist/utils/ansi.js +29 -10
  293. package/dist/utils/ansi.js.map +1 -1
  294. package/dist/utils/clipboard.d.ts.map +1 -1
  295. package/dist/utils/clipboard.js +13 -3
  296. package/dist/utils/clipboard.js.map +1 -1
  297. package/dist/utils/credential-redaction.d.ts +2 -0
  298. package/dist/utils/credential-redaction.d.ts.map +1 -0
  299. package/dist/utils/credential-redaction.js +20 -0
  300. package/dist/utils/credential-redaction.js.map +1 -0
  301. package/dist/utils/image-resize-core.d.ts +8 -0
  302. package/dist/utils/image-resize-core.d.ts.map +1 -1
  303. package/dist/utils/image-resize-core.js +1 -0
  304. package/dist/utils/image-resize-core.js.map +1 -1
  305. package/dist/utils/image-resize-worker.js +3 -2
  306. package/dist/utils/image-resize-worker.js.map +1 -1
  307. package/dist/utils/image-resize.d.ts +2 -2
  308. package/dist/utils/image-resize.d.ts.map +1 -1
  309. package/dist/utils/image-resize.js +7 -10
  310. package/dist/utils/image-resize.js.map +1 -1
  311. package/docs/codemode.md +21 -1
  312. package/docs/compaction/reference.md +10 -4
  313. package/docs/compaction.md +40 -8
  314. package/docs/docs.json +1 -0
  315. package/docs/extensions/api-reference.md +4 -0
  316. package/docs/extensions/events.md +2 -2
  317. package/docs/llama-cpp.md +9 -2
  318. package/docs/mcp-servers.md +3 -3
  319. package/docs/models.md +10 -0
  320. package/docs/providers.md +39 -5
  321. package/docs/reference/cli.md +2 -2
  322. package/docs/sdk/reference.md +19 -4
  323. package/docs/sdk/web-server.md +325 -0
  324. package/docs/sdk.md +83 -1
  325. package/docs/security.md +1 -1
  326. package/docs/settings.md +2 -2
  327. package/docs/tools.md +1 -1
  328. package/docs/workflows/api-reference.md +71 -3
  329. package/docs/workflows/builtins.md +4 -0
  330. package/docs/workflows/operations.md +13 -5
  331. package/npm-shrinkwrap.json +32 -32
  332. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"rpc-command-timeouts.js","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-command-timeouts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAwB,IAAI,GAAG,CAAS;IACvE,qDAAqD;IACrD,OAAO;IACP,YAAY;IACZ,kBAAkB;IAClB,aAAa;IACb,uBAAuB;IACvB,mCAAmC;IACnC,QAAQ;IACR,gBAAgB;IAChB,OAAO;IACP,WAAW;IACX,MAAM;IACN,WAAW;IACX,SAAS;IACT,MAAM;IACN,OAAO;IACP,gBAAgB;IAChB,aAAa;IACb,gBAAgB;IAChB,eAAe;IACf,iBAAiB;CACjB,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,0BAA0B,GAAG,MAAM,CAAC;AAEjD;;;;GAIG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAEzC,kFAAkF;AAClF,MAAM,CAAC,MAAM,yBAAyB,GAAG,sCAAsC,CAAC","sourcesContent":["/**\n * Commands exempt from the generic request deadline.\n *\n * Two groups, for two reasons:\n *\n * - Work legitimately gated on human or agent interaction: interactive prompts\n * and custom-UI pickers (routed through `prompt`), queued turn-boundary sends\n * (`steer`/`follow_up`), long-running shell and compaction work, and\n * session-tree navigation or mutation that can open pickers.\n * - Cooperative cancellation. Escape's whole contract is that it asks the\n * engine to stop and waits for as long as the engine takes. A host-side\n * deadline would surface as `Timeout waiting for response to abort…` — a red\n * error about the host's own impatience while the engine is still working —\n * and would not stop anything.\n *\n * Failure detection is unaffected: engine exit, transport violations, generation\n * replacement, and explicit stop all reject pending requests through\n * rejectPendingRequests/failTransport independently of any timer.\n */\nexport const LONG_LIVED_COMMANDS: ReadonlySet<string> = new Set<string>([\n\t// Cooperative cancellation, all unbounded by design.\n\t\"abort\",\n\t\"abort_bash\",\n\t\"abort_compaction\",\n\t\"abort_retry\",\n\t\"cancel_login_provider\",\n\t// Interaction- or turn-gated work.\n\t\"prompt\",\n\t\"login_provider\",\n\t\"steer\",\n\t\"follow_up\",\n\t\"bash\",\n\t\"user_bash\",\n\t\"compact\",\n\t\"fork\",\n\t\"clone\",\n\t\"switch_session\",\n\t\"new_session\",\n\t\"import_session\",\n\t\"navigate_tree\",\n\t\"invoke_shortcut\",\n]);\n\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * How long to wait for a dead child's stdout to drain before failing the\n * requests it never answered. `'close'` normally arrives first; this only\n * bounds the case where a descendant inherited stdout and keeps it open.\n */\nexport const EXIT_DRAIN_TIMEOUT_MS = 500;\n\n/** Rejection message for a restart superseded by an explicit stop or disposal. */\nexport const RESTART_CANCELLED_MESSAGE = \"Interactive engine restart cancelled\";\n"]}
1
+ {"version":3,"file":"rpc-command-timeouts.js","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-command-timeouts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAwB,IAAI,GAAG,CAAS;IACvE,qDAAqD;IACrD,OAAO;IACP,YAAY;IACZ,kBAAkB;IAClB,aAAa;IACb,uBAAuB;IACvB,mCAAmC;IACnC,QAAQ;IACR,gBAAgB;IAChB,OAAO;IACP,WAAW;IACX,wBAAwB;IACxB,MAAM;IACN,WAAW;IACX,SAAS;IACT,MAAM;IACN,OAAO;IACP,gBAAgB;IAChB,aAAa;IACb,gBAAgB;IAChB,eAAe;IACf,iBAAiB;CACjB,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,0BAA0B,GAAG,MAAM,CAAC;AAEjD;;;;GAIG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAEzC,kFAAkF;AAClF,MAAM,CAAC,MAAM,yBAAyB,GAAG,sCAAsC,CAAC","sourcesContent":["/**\n * Commands exempt from the generic request deadline.\n *\n * Two groups, for two reasons:\n *\n * - Work legitimately gated on human or agent interaction: interactive prompts\n * and custom-UI pickers (routed through `prompt`), queued turn-boundary sends\n * (`steer`/`follow_up`), long-running shell and compaction work, and\n * session-tree navigation or mutation that can open pickers.\n * - Cooperative cancellation. Escape's whole contract is that it asks the\n * engine to stop and waits for as long as the engine takes. A host-side\n * deadline would surface as `Timeout waiting for response to abort…` — a red\n * error about the host's own impatience while the engine is still working —\n * and would not stop anything.\n *\n * Failure detection is unaffected: engine exit, transport violations, generation\n * replacement, and explicit stop all reject pending requests through\n * rejectPendingRequests/failTransport independently of any timer.\n */\nexport const LONG_LIVED_COMMANDS: ReadonlySet<string> = new Set<string>([\n\t// Cooperative cancellation, all unbounded by design.\n\t\"abort\",\n\t\"abort_bash\",\n\t\"abort_compaction\",\n\t\"abort_retry\",\n\t\"cancel_login_provider\",\n\t// Interaction- or turn-gated work.\n\t\"prompt\",\n\t\"login_provider\",\n\t\"steer\",\n\t\"follow_up\",\n\t\"resume_queued_messages\",\n\t\"bash\",\n\t\"user_bash\",\n\t\"compact\",\n\t\"fork\",\n\t\"clone\",\n\t\"switch_session\",\n\t\"new_session\",\n\t\"import_session\",\n\t\"navigate_tree\",\n\t\"invoke_shortcut\",\n]);\n\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * How long to wait for a dead child's stdout to drain before failing the\n * requests it never answered. `'close'` normally arrives first; this only\n * bounds the case where a descendant inherited stdout and keeps it open.\n */\nexport const EXIT_DRAIN_TIMEOUT_MS = 500;\n\n/** Rejection message for a restart superseded by an explicit stop or disposal. */\nexport const RESTART_CANCELLED_MESSAGE = \"Interactive engine restart cancelled\";\n"]}
@@ -1,2 +1,10 @@
1
+ /**
2
+ * Split streamed text into a part that is safe to pass to stripAnsi now and a trailing
3
+ * unfinished escape sequence that should be prepended to the next chunk.
4
+ */
5
+ export declare function splitIncompleteAnsiSuffix(value: string): {
6
+ complete: string;
7
+ pending: string;
8
+ };
1
9
  export declare function stripAnsi(value: string): string;
2
10
  //# sourceMappingURL=ansi.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ansi.d.ts","sourceRoot":"","sources":["../../src/utils/ansi.ts"],"names":[],"mappings":"AA6CA,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAc/C"}
1
+ {"version":3,"file":"ansi.d.ts","sourceRoot":"","sources":["../../src/utils/ansi.ts"],"names":[],"mappings":"AAkDA;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,MAAM,GAAG;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAW9F;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAc/C"}
@@ -25,17 +25,36 @@
25
25
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
26
  * SOFTWARE.
27
27
  */
28
- function ansiRegex({ onlyFirst = false } = {}) {
29
- // Valid string terminator sequences are BEL, ESC\, and 0x9c
30
- const ST = "(?:\\u0007|\\u001B\\u005C|\\u009C)";
31
- // OSC sequences only: ESC ] ... ST (non-greedy until the first ST)
32
- const osc = `(?:\\u001B\\][\\s\\S]*?${ST})`;
33
- // CSI and related: ESC/C1, optional intermediates, optional params (supports ; and :) then final byte
34
- const csi = "[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";
35
- const pattern = `${osc}|${csi}`;
36
- return new RegExp(pattern, onlyFirst ? undefined : "g");
28
+ // Valid string terminator sequences are BEL, ESC\, and 0x9c
29
+ const ST = "(?:\\u0007|\\u001B\\u005C|\\u009C)";
30
+ // OSC sequences: ESC ] ... ST
31
+ const OSC_START = "\\u001B\\]";
32
+ // CSI and related: ESC/C1, optional intermediates, optional params (supports ; and :), then final byte
33
+ const CSI_START = "[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?";
34
+ const CSI_FINAL = "[\\dA-PR-TZcf-nq-uy=><~]";
35
+ // Complete sequences. OSC is non-greedy until the first ST.
36
+ const regex = new RegExp(`(?:${OSC_START}[\\s\\S]*?${ST})|${CSI_START}${CSI_FINAL}`, "g");
37
+ // Unfinished sequence at the end of the text: OSC without its ST (a trailing ESC may start ESC\),
38
+ // or CSI without its final byte.
39
+ const unfinishedAnsiAtEndRegex = new RegExp(`(?:${OSC_START}(?:[^\\u0007\\u009C\\u001B]|\\u001B(?!\\\\))*|${CSI_START})$`);
40
+ // Longest unfinished sequence held back while streaming. Longer ones are processed as-is.
41
+ const MAX_PENDING_ANSI_LENGTH = 256;
42
+ /**
43
+ * Split streamed text into a part that is safe to pass to stripAnsi now and a trailing
44
+ * unfinished escape sequence that should be prepended to the next chunk.
45
+ */
46
+ export function splitIncompleteAnsiSuffix(value) {
47
+ if (!value.includes("\u001B") && !value.includes("\u009B")) {
48
+ return { complete: value, pending: "" };
49
+ }
50
+ const windowStart = Math.max(0, value.length - MAX_PENDING_ANSI_LENGTH);
51
+ const match = unfinishedAnsiAtEndRegex.exec(value.slice(windowStart));
52
+ if (!match) {
53
+ return { complete: value, pending: "" };
54
+ }
55
+ const splitAt = windowStart + match.index;
56
+ return { complete: value.slice(0, splitAt), pending: value.slice(splitAt) };
37
57
  }
38
- const regex = ansiRegex();
39
58
  export function stripAnsi(value) {
40
59
  if (typeof value !== "string") {
41
60
  throw new TypeError(`Expected a \`string\`, got \`${typeof value}\``);
@@ -1 +1 @@
1
- {"version":3,"file":"ansi.js","sourceRoot":"","sources":["../../src/utils/ansi.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,SAAS,SAAS,CAAC,EAAE,SAAS,GAAG,KAAK,EAAE,GAA4B,EAAE;IACrE,4DAA4D;IAC5D,MAAM,EAAE,GAAG,oCAAoC,CAAC;IAEhD,mEAAmE;IACnE,MAAM,GAAG,GAAG,0BAA0B,EAAE,GAAG,CAAC;IAE5C,sGAAsG;IACtG,MAAM,GAAG,GAAG,oFAAoF,CAAC;IAEjG,MAAM,OAAO,GAAG,GAAG,GAAG,IAAI,GAAG,EAAE,CAAC;IAEhC,OAAO,IAAI,MAAM,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;AACzD,CAAC;AAED,MAAM,KAAK,GAAG,SAAS,EAAE,CAAC;AAE1B,MAAM,UAAU,SAAS,CAAC,KAAa;IACtC,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC/B,MAAM,IAAI,SAAS,CAAC,gCAAgC,OAAO,KAAK,IAAI,CAAC,CAAC;IACvE,CAAC;IAED,sEAAsE;IACtE,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC5D,OAAO,KAAK,CAAC;IACd,CAAC;IAED,2EAA2E;IAC3E,6EAA6E;IAC7E,mDAAmD;IACnD,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AACjC,CAAC","sourcesContent":["/*\n * Portions of this file are derived from:\n * - ansi-regex (https://github.com/chalk/ansi-regex)\n * - strip-ansi (https://github.com/chalk/strip-ansi)\n *\n * MIT License\n *\n * Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nfunction ansiRegex({ onlyFirst = false }: { onlyFirst?: boolean } = {}): RegExp {\n\t// Valid string terminator sequences are BEL, ESC\\, and 0x9c\n\tconst ST = \"(?:\\\\u0007|\\\\u001B\\\\u005C|\\\\u009C)\";\n\n\t// OSC sequences only: ESC ] ... ST (non-greedy until the first ST)\n\tconst osc = `(?:\\\\u001B\\\\][\\\\s\\\\S]*?${ST})`;\n\n\t// CSI and related: ESC/C1, optional intermediates, optional params (supports ; and :) then final byte\n\tconst csi = \"[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:\\\\d{1,4}(?:[;:]\\\\d{0,4})*)?[\\\\dA-PR-TZcf-nq-uy=><~]\";\n\n\tconst pattern = `${osc}|${csi}`;\n\n\treturn new RegExp(pattern, onlyFirst ? undefined : \"g\");\n}\n\nconst regex = ansiRegex();\n\nexport function stripAnsi(value: string): string {\n\tif (typeof value !== \"string\") {\n\t\tthrow new TypeError(`Expected a \\`string\\`, got \\`${typeof value}\\``);\n\t}\n\n\t// Fast path: ANSI codes require ESC (7-bit) or CSI (8-bit) introducer\n\tif (!value.includes(\"\\u001B\") && !value.includes(\"\\u009B\")) {\n\t\treturn value;\n\t}\n\n\t// Even though the regex is global, we don't need to reset the `.lastIndex`\n\t// because unlike `.exec()` and `.test()`, `.replace()` does it automatically\n\t// and doing it manually has a performance penalty.\n\treturn value.replace(regex, \"\");\n}\n"]}
1
+ {"version":3,"file":"ansi.js","sourceRoot":"","sources":["../../src/utils/ansi.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,4DAA4D;AAC5D,MAAM,EAAE,GAAG,oCAAoC,CAAC;AAEhD,8BAA8B;AAC9B,MAAM,SAAS,GAAG,YAAY,CAAC;AAE/B,uGAAuG;AACvG,MAAM,SAAS,GAAG,4DAA4D,CAAC;AAC/E,MAAM,SAAS,GAAG,0BAA0B,CAAC;AAE7C,4DAA4D;AAC5D,MAAM,KAAK,GAAG,IAAI,MAAM,CAAC,MAAM,SAAS,aAAa,EAAE,KAAK,SAAS,GAAG,SAAS,EAAE,EAAE,GAAG,CAAC,CAAC;AAE1F,kGAAkG;AAClG,iCAAiC;AACjC,MAAM,wBAAwB,GAAG,IAAI,MAAM,CAC1C,MAAM,SAAS,iDAAiD,SAAS,IAAI,CAC7E,CAAC;AAEF,0FAA0F;AAC1F,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAEpC;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CAAC,KAAa;IAC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\n * - ansi-regex (https://github.com/chalk/ansi-regex)\n * - strip-ansi (https://github.com/chalk/strip-ansi)\n *\n * MIT License\n *\n * Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n// Valid string terminator sequences are BEL, ESC\\, and 0x9c\nconst ST = \"(?:\\\\u0007|\\\\u001B\\\\u005C|\\\\u009C)\";\n\n// OSC sequences: ESC ] ... ST\nconst OSC_START = \"\\\\u001B\\\\]\";\n\n// CSI and related: ESC/C1, optional intermediates, optional params (supports ; and :), then final byte\nconst CSI_START = \"[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:\\\\d{1,4}(?:[;:]\\\\d{0,4})*)?\";\nconst CSI_FINAL = \"[\\\\dA-PR-TZcf-nq-uy=><~]\";\n\n// Complete sequences. OSC is non-greedy until the first ST.\nconst regex = new RegExp(`(?:${OSC_START}[\\\\s\\\\S]*?${ST})|${CSI_START}${CSI_FINAL}`, \"g\");\n\n// Unfinished sequence at the end of the text: OSC without its ST (a trailing ESC may start ESC\\),\n// or CSI without its final byte.\nconst unfinishedAnsiAtEndRegex = new RegExp(\n\t`(?:${OSC_START}(?:[^\\\\u0007\\\\u009C\\\\u001B]|\\\\u001B(?!\\\\\\\\))*|${CSI_START})$`,\n);\n\n// Longest unfinished sequence held back while streaming. Longer ones are processed as-is.\nconst MAX_PENDING_ANSI_LENGTH = 256;\n\n/**\n * Split streamed text into a part that is safe to pass to stripAnsi now and a trailing\n * unfinished escape sequence that should be prepended to the next chunk.\n */\nexport function splitIncompleteAnsiSuffix(value: string): { complete: string; pending: string } {\n\tif (!value.includes(\"\\u001B\") && !value.includes(\"\\u009B\")) {\n\t\treturn { complete: value, pending: \"\" };\n\t}\n\tconst windowStart = Math.max(0, value.length - MAX_PENDING_ANSI_LENGTH);\n\tconst match = unfinishedAnsiAtEndRegex.exec(value.slice(windowStart));\n\tif (!match) {\n\t\treturn { complete: value, pending: \"\" };\n\t}\n\tconst splitAt = windowStart + match.index;\n\treturn { complete: value.slice(0, splitAt), pending: value.slice(splitAt) };\n}\n\nexport function stripAnsi(value: string): string {\n\tif (typeof value !== \"string\") {\n\t\tthrow new TypeError(`Expected a \\`string\\`, got \\`${typeof value}\\``);\n\t}\n\n\t// Fast path: ANSI codes require ESC (7-bit) or CSI (8-bit) introducer\n\tif (!value.includes(\"\\u001B\") && !value.includes(\"\\u009B\")) {\n\t\treturn value;\n\t}\n\n\t// Even though the regex is global, we don't need to reset the `.lastIndex`\n\t// because unlike `.exec()` and `.test()`, `.replace()` does it automatically\n\t// and doing it manually has a performance penalty.\n\treturn value.replace(regex, \"\");\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"clipboard.d.ts","sourceRoot":"","sources":["../../src/utils/clipboard.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,KAAK,eAAe,EAAa,MAAM,uBAAuB,CAAC;AAqExE,wBAAsB,iBAAiB,CACtC,MAAM,GAAE;IAAE,OAAO,IAAI,OAAO,CAAC,MAAM,CAAC,CAAA;CAAE,GAAG,IAAgB,GACvD,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAOxB;AAeD;;;;GAIG;AACH,wBAAsB,sBAAsB,CAC3C,MAAM,GAAE,IAAI,CAAC,eAAe,EAAE,kBAAkB,CAAC,GAAG,IAAgB,EACpE,eAAe,GAAE,MAAM,CAAC,QAA2B,GACjD,OAAO,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC,CAqB1B;AAED,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAyIjE"}
1
+ {"version":3,"file":"clipboard.d.ts","sourceRoot":"","sources":["../../src/utils/clipboard.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,KAAK,eAAe,EAAa,MAAM,uBAAuB,CAAC;AA6ExE,wBAAsB,iBAAiB,CACtC,MAAM,GAAE;IAAE,OAAO,IAAI,OAAO,CAAC,MAAM,CAAC,CAAA;CAAE,GAAG,IAAgB,GACvD,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAWxB;AAeD;;;;GAIG;AACH,wBAAsB,sBAAsB,CAC3C,MAAM,GAAE,IAAI,CAAC,eAAe,EAAE,kBAAkB,CAAC,GAAG,IAAgB,EACpE,eAAe,GAAE,MAAM,CAAC,QAA2B,GACjD,OAAO,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC,CAqB1B;AAED,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAyIjE"}
@@ -66,7 +66,17 @@ function copyViaWindowsClipboard(text) {
66
66
  }
67
67
  }
68
68
  }
69
+ function readTermuxClipboardText() {
70
+ return new Promise((resolve) => {
71
+ execFile("termux-clipboard-get", [], { timeout: 5000, env: createChildProcessEnvironment() }, (error, stdout) => resolve(error ? undefined : stdout));
72
+ });
73
+ }
69
74
  export async function readClipboardText(source = clipboard) {
75
+ if (process.env.TERMUX_VERSION) {
76
+ const text = await readTermuxClipboardText();
77
+ if (text !== undefined)
78
+ return text || null;
79
+ }
70
80
  try {
71
81
  if (!source)
72
82
  return null;
@@ -245,10 +255,10 @@ export async function copyToClipboard(text) {
245
255
  return;
246
256
  if (oversized)
247
257
  throw new Error("Clipboard unavailable: text exceeds the OSC 52 size limit");
258
+ if (env.TERMUX_VERSION) {
259
+ throw new Error("Clipboard unavailable: install the Termux:API app and `termux-api` package");
260
+ }
248
261
  if (p === "linux") {
249
- if (env.TERMUX_VERSION) {
250
- throw new Error("Clipboard unavailable: install the Termux:API app and `termux-api` package");
251
- }
252
262
  if (env.WAYLAND_DISPLAY) {
253
263
  throw new Error("Clipboard unavailable: install `wl-clipboard` (`wl-copy`) or check Wayland access");
254
264
  }
@@ -1 +1 @@
1
- {"version":3,"file":"clipboard.js","sourceRoot":"","sources":["../../src/utils/clipboard.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACxE,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,IAAI,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,IAAI,CAAC;AACtC,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,6BAA6B,EAAE,MAAM,oBAAoB,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxD,OAAO,EAAwB,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACxE,OAAO,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AASjC,SAAS,kBAAkB,CAAC,OAAmC;IAC9D,IAAI,CAAC;QACJ,QAAQ,CAAC,4BAA4B,EAAE,OAAO,CAAC,CAAC;IACjD,CAAC;IAAC,MAAM,CAAC;QACR,QAAQ,CAAC,0BAA0B,EAAE,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AAI,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 { execFile, execFileSync, execSync, spawn } from \"child_process\";\nimport { randomUUID } from \"crypto\";\nimport { unlinkSync, writeFileSync } from \"fs\";\nimport { platform, tmpdir } from \"os\";\nimport { join } from \"path\";\nimport { createChildProcessEnvironment } from \"./child-process.ts\";\nimport { isWaylandSession } from \"./clipboard-image.ts\";\nimport { type ClipboardModule, clipboard } from \"./clipboard-native.ts\";\nimport { isWSL } from \"./wsl.ts\";\n\ntype NativeClipboardExecOptions = {\n\tinput: string;\n\ttimeout: number;\n\tstdio: [\"pipe\", \"ignore\", \"ignore\"];\n\tenv: NodeJS.ProcessEnv;\n};\n\nfunction copyToX11Clipboard(options: NativeClipboardExecOptions): void {\n\ttry {\n\t\texecSync(\"xclip -selection clipboard\", options);\n\t} catch {\n\t\texecSync(\"xsel --clipboard --input\", options);\n\t}\n}\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 */\nfunction copyViaWindowsClipboard(text: string): boolean {\n\tconst tmpFile = join(tmpdir(), `pi-wsl-clip-${randomUUID()}.txt`);\n\tconst env = createChildProcessEnvironment();\n\ttry {\n\t\twriteFileSync(tmpFile, text, { encoding: \"utf8\", mode: 0o600 });\n\t\tconst winPath = execFileSync(\"wslpath\", [\"-w\", tmpFile], {\n\t\t\ttimeout: 1000,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t\tenv,\n\t\t})\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\texecFileSync(\"powershell.exe\", [\"-NoProfile\", \"-Command\", script], {\n\t\t\ttimeout: 5000,\n\t\t\tstdio: [\"ignore\", \"ignore\", \"ignore\"],\n\t\t\tenv,\n\t\t});\n\t\treturn true;\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\nexport async function readClipboardText(\n\tsource: { getText(): Promise<string> } | null = clipboard,\n): Promise<string | null> {\n\ttry {\n\t\tif (!source) return null;\n\t\treturn await source.getText();\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Pasteboard type that Finder and other macOS apps publish for copied files. */\nconst FILE_URL_PASTEBOARD_TYPE = \"public.file-url\";\n\n/** Prints the POSIX paths of the file URLs on the general pasteboard as a JSON array. */\nconst READ_FILE_URLS_SCRIPT = `ObjC.import(\"AppKit\");\nconst urls = $.NSPasteboard.generalPasteboard.readObjectsForClassesOptions(\n\t$.NSArray.arrayWithObject($.NSURL),\n\t$.NSDictionary.dictionaryWithObjectForKey($.NSNumber.numberWithBool(true), $.NSPasteboardURLReadingFileURLsOnlyKey)\n);\nconst paths = [];\nfor (let i = 0; i < urls.count; i++) paths.push(ObjC.unwrap(urls.objectAtIndex(i).path));\nJSON.stringify(paths);`;\n\n/**\n * Read file paths, such as Finder file copies, from the macOS clipboard. The native clipboard\n * module reports whether file URLs are present; AppKit is read through JavaScript for Automation\n * only then, because the module cannot read file URLs itself.\n */\nexport async function readClipboardFilePaths(\n\tsource: Pick<ClipboardModule, \"availableFormats\"> | null = clipboard,\n\tcurrentPlatform: NodeJS.Platform = process.platform,\n): Promise<string[] | null> {\n\tif (currentPlatform !== \"darwin\" || !source?.availableFormats?.().includes(FILE_URL_PASTEBOARD_TYPE)) return null;\n\tconst stdout = await new Promise<string>((resolve, reject) => {\n\t\texecFile(\n\t\t\t\"osascript\",\n\t\t\t[\"-l\", \"JavaScript\", \"-e\", READ_FILE_URLS_SCRIPT],\n\t\t\t{ timeout: 5000, env: createChildProcessEnvironment() },\n\t\t\t(error, output, stderr) => {\n\t\t\t\tif (error) {\n\t\t\t\t\t// The default error message repeats the whole script; report what osascript printed instead.\n\t\t\t\t\tconst detail = stderr.trim();\n\t\t\t\t\treject(new Error(`osascript could not read the copied files${detail ? `: ${detail}` : \"\"}`));\n\t\t\t\t} else resolve(output);\n\t\t\t},\n\t\t);\n\t});\n\tconst paths = JSON.parse(stdout) as string[] | null;\n\tif (!Array.isArray(paths) || paths.some((path) => typeof path !== \"string\")) {\n\t\tthrow new Error(\"Unexpected clipboard file path output\");\n\t}\n\treturn paths.length > 0 ? paths : null;\n}\n\nexport async function copyToClipboard(text: string): Promise<void> {\n\tlet copied = false;\n\n\tconst p = platform();\n\tconst env = process.env;\n\t// Prefer direct clipboard writes. Emitting OSC 52 first can make terminals\n\t// write the same native clipboard concurrently with the addon, and very large\n\t// OSC 52 payloads can desynchronize terminal rendering.\n\t//\n\t// On Linux, skip the native addon. The underlying `clipboard-rs` crate is\n\t// X11-only and does not retain selection ownership after `set_text`\n\t// resolves, so on Wayland-only compositors (Hyprland, Niri, ...) and even\n\t// some X11 sessions the call resolves successfully without populating the\n\t// clipboard. The platform tools below (wl-copy, xclip, xsel) properly\n\t// daemonize and keep ownership.\n\ttry {\n\t\tif (clipboard && p !== \"linux\") {\n\t\t\tawait clipboard.setText(text);\n\t\t\tcopied = true;\n\t\t}\n\t} catch {\n\t\t// Fall through to platform-specific clipboard tools.\n\t}\n\n\tconst remote = isRemoteSession(env);\n\tif (copied && !remote) {\n\t\treturn;\n\t}\n\n\tconst options: NativeClipboardExecOptions = {\n\t\tinput: text,\n\t\ttimeout: 5000,\n\t\tstdio: [\"pipe\", \"ignore\", \"ignore\"],\n\t\tenv: createChildProcessEnvironment(),\n\t};\n\n\tif (!copied) {\n\t\ttry {\n\t\t\tif (p === \"darwin\") {\n\t\t\t\texecSync(\"pbcopy\", options);\n\t\t\t\tcopied = true;\n\t\t\t} else if (p === \"win32\") {\n\t\t\t\texecSync(\"clip\", options);\n\t\t\t\tcopied = true;\n\t\t\t} else {\n\t\t\t\t// Linux. Try Termux, Wayland, or X11 clipboard tools.\n\t\t\t\tif (env.TERMUX_VERSION) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\texecSync(\"termux-clipboard-set\", options);\n\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Fall back to Wayland or X11 tools.\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!copied) {\n\t\t\t\t\tconst hasWaylandDisplay = Boolean(env.WAYLAND_DISPLAY);\n\t\t\t\t\tconst hasX11Display = Boolean(env.DISPLAY);\n\t\t\t\t\tconst isWayland = isWaylandSession();\n\t\t\t\t\tif (isWayland && hasWaylandDisplay) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t// Verify wl-copy exists (spawn errors are async and won't be caught)\n\t\t\t\t\t\t\texecSync(\"which wl-copy\", { stdio: \"ignore\", env: createChildProcessEnvironment() });\n\t\t\t\t\t\t\t// wl-copy with execSync hangs due to fork behavior; use spawn instead.\n\t\t\t\t\t\t\t// Await its terminal event so failures can fall through to X11 or OSC 52.\n\t\t\t\t\t\t\tconst exitCode = await new Promise<number>((resolve) => {\n\t\t\t\t\t\t\t\tconst proc = spawn(\"wl-copy\", [], {\n\t\t\t\t\t\t\t\t\tstdio: [\"pipe\", \"ignore\", \"ignore\"],\n\t\t\t\t\t\t\t\t\tenv: createChildProcessEnvironment(),\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tlet settled = false;\n\t\t\t\t\t\t\t\tconst finish = (code: number) => {\n\t\t\t\t\t\t\t\t\tif (settled) return;\n\t\t\t\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\t\t\t\tresolve(code);\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tproc.once(\"error\", () => finish(1));\n\t\t\t\t\t\t\t\tproc.once(\"close\", (code) => finish(code ?? 1));\n\t\t\t\t\t\t\t\tproc.stdin.on(\"error\", () => {});\n\t\t\t\t\t\t\t\tproc.stdin.end(text);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (exitCode === 0) copied = true;\n\t\t\t\t\t\t\telse if (hasX11Display) {\n\t\t\t\t\t\t\t\tcopyToX11Clipboard(options);\n\t\t\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tif (hasX11Display) {\n\t\t\t\t\t\t\t\tcopyToX11Clipboard(options);\n\t\t\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (hasX11Display) {\n\t\t\t\t\t\tcopyToX11Clipboard(options);\n\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Fall through to OSC 52 fallback.\n\t\t}\n\t}\n\n\tlet osc52Emitted = false;\n\t// A remote session skips the Windows clipboard: the copied text belongs on the connected\n\t// client, which the OSC 52 fallback below reaches, not on the remote host.\n\tif (!copied && !remote && 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 || copyViaWindowsClipboard(text);\n\t}\n\t// OSC 52 cannot be verified, so a desktop session with a display reports the failure\n\t// instead. Without a display the terminal is the only clipboard route (containers,\n\t// WSL without WSLg). A remote session emits it even after a successful local write:\n\t// that write reached the remote host's display clipboard, while the user is at the\n\t// client, which only the terminal can reach. The Windows interop fallback above is\n\t// different because it is a last resort that a remote session gains nothing from.\n\tconst headless = p === \"linux\" && !env.DISPLAY && !env.WAYLAND_DISPLAY && !env.TERMUX_VERSION;\n\tlet oversized = false;\n\tif (!osc52Emitted && (remote || (!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/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S,GAAG,IAAI,CAAC;IACvB,CAAC;IACD,IAAI,MAAM;QAAE,OAAO;IACnB,IAAI,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,2DAA2D,CAAC,CAAC;IAC5F,IAAI,GAAG,CAAC,cAAc,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;IAC/F,CAAC;IACD,IAAI,CAAC,KAAK,OAAO,EAAE,CAAC;QACnB,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 { execFile, execFileSync, execSync, spawn } from \"child_process\";\nimport { randomUUID } from \"crypto\";\nimport { unlinkSync, writeFileSync } from \"fs\";\nimport { platform, tmpdir } from \"os\";\nimport { join } from \"path\";\nimport { createChildProcessEnvironment } from \"./child-process.ts\";\nimport { isWaylandSession } from \"./clipboard-image.ts\";\nimport { type ClipboardModule, clipboard } from \"./clipboard-native.ts\";\nimport { isWSL } from \"./wsl.ts\";\n\ntype NativeClipboardExecOptions = {\n\tinput: string;\n\ttimeout: number;\n\tstdio: [\"pipe\", \"ignore\", \"ignore\"];\n\tenv: NodeJS.ProcessEnv;\n};\n\nfunction copyToX11Clipboard(options: NativeClipboardExecOptions): void {\n\ttry {\n\t\texecSync(\"xclip -selection clipboard\", options);\n\t} catch {\n\t\texecSync(\"xsel --clipboard --input\", options);\n\t}\n}\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 */\nfunction copyViaWindowsClipboard(text: string): boolean {\n\tconst tmpFile = join(tmpdir(), `pi-wsl-clip-${randomUUID()}.txt`);\n\tconst env = createChildProcessEnvironment();\n\ttry {\n\t\twriteFileSync(tmpFile, text, { encoding: \"utf8\", mode: 0o600 });\n\t\tconst winPath = execFileSync(\"wslpath\", [\"-w\", tmpFile], {\n\t\t\ttimeout: 1000,\n\t\t\tstdio: [\"ignore\", \"pipe\", \"ignore\"],\n\t\t\tenv,\n\t\t})\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\texecFileSync(\"powershell.exe\", [\"-NoProfile\", \"-Command\", script], {\n\t\t\ttimeout: 5000,\n\t\t\tstdio: [\"ignore\", \"ignore\", \"ignore\"],\n\t\t\tenv,\n\t\t});\n\t\treturn true;\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\nfunction readTermuxClipboardText(): Promise<string | undefined> {\n\treturn new Promise((resolve) => {\n\t\texecFile(\"termux-clipboard-get\", [], { timeout: 5000, env: createChildProcessEnvironment() }, (error, stdout) =>\n\t\t\tresolve(error ? undefined : stdout),\n\t\t);\n\t});\n}\n\nexport async function readClipboardText(\n\tsource: { getText(): Promise<string> } | null = clipboard,\n): Promise<string | null> {\n\tif (process.env.TERMUX_VERSION) {\n\t\tconst text = await readTermuxClipboardText();\n\t\tif (text !== undefined) return text || null;\n\t}\n\ttry {\n\t\tif (!source) return null;\n\t\treturn await source.getText();\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** Pasteboard type that Finder and other macOS apps publish for copied files. */\nconst FILE_URL_PASTEBOARD_TYPE = \"public.file-url\";\n\n/** Prints the POSIX paths of the file URLs on the general pasteboard as a JSON array. */\nconst READ_FILE_URLS_SCRIPT = `ObjC.import(\"AppKit\");\nconst urls = $.NSPasteboard.generalPasteboard.readObjectsForClassesOptions(\n\t$.NSArray.arrayWithObject($.NSURL),\n\t$.NSDictionary.dictionaryWithObjectForKey($.NSNumber.numberWithBool(true), $.NSPasteboardURLReadingFileURLsOnlyKey)\n);\nconst paths = [];\nfor (let i = 0; i < urls.count; i++) paths.push(ObjC.unwrap(urls.objectAtIndex(i).path));\nJSON.stringify(paths);`;\n\n/**\n * Read file paths, such as Finder file copies, from the macOS clipboard. The native clipboard\n * module reports whether file URLs are present; AppKit is read through JavaScript for Automation\n * only then, because the module cannot read file URLs itself.\n */\nexport async function readClipboardFilePaths(\n\tsource: Pick<ClipboardModule, \"availableFormats\"> | null = clipboard,\n\tcurrentPlatform: NodeJS.Platform = process.platform,\n): Promise<string[] | null> {\n\tif (currentPlatform !== \"darwin\" || !source?.availableFormats?.().includes(FILE_URL_PASTEBOARD_TYPE)) return null;\n\tconst stdout = await new Promise<string>((resolve, reject) => {\n\t\texecFile(\n\t\t\t\"osascript\",\n\t\t\t[\"-l\", \"JavaScript\", \"-e\", READ_FILE_URLS_SCRIPT],\n\t\t\t{ timeout: 5000, env: createChildProcessEnvironment() },\n\t\t\t(error, output, stderr) => {\n\t\t\t\tif (error) {\n\t\t\t\t\t// The default error message repeats the whole script; report what osascript printed instead.\n\t\t\t\t\tconst detail = stderr.trim();\n\t\t\t\t\treject(new Error(`osascript could not read the copied files${detail ? `: ${detail}` : \"\"}`));\n\t\t\t\t} else resolve(output);\n\t\t\t},\n\t\t);\n\t});\n\tconst paths = JSON.parse(stdout) as string[] | null;\n\tif (!Array.isArray(paths) || paths.some((path) => typeof path !== \"string\")) {\n\t\tthrow new Error(\"Unexpected clipboard file path output\");\n\t}\n\treturn paths.length > 0 ? paths : null;\n}\n\nexport async function copyToClipboard(text: string): Promise<void> {\n\tlet copied = false;\n\n\tconst p = platform();\n\tconst env = process.env;\n\t// Prefer direct clipboard writes. Emitting OSC 52 first can make terminals\n\t// write the same native clipboard concurrently with the addon, and very large\n\t// OSC 52 payloads can desynchronize terminal rendering.\n\t//\n\t// On Linux, skip the native addon. The underlying `clipboard-rs` crate is\n\t// X11-only and does not retain selection ownership after `set_text`\n\t// resolves, so on Wayland-only compositors (Hyprland, Niri, ...) and even\n\t// some X11 sessions the call resolves successfully without populating the\n\t// clipboard. The platform tools below (wl-copy, xclip, xsel) properly\n\t// daemonize and keep ownership.\n\ttry {\n\t\tif (clipboard && p !== \"linux\") {\n\t\t\tawait clipboard.setText(text);\n\t\t\tcopied = true;\n\t\t}\n\t} catch {\n\t\t// Fall through to platform-specific clipboard tools.\n\t}\n\n\tconst remote = isRemoteSession(env);\n\tif (copied && !remote) {\n\t\treturn;\n\t}\n\n\tconst options: NativeClipboardExecOptions = {\n\t\tinput: text,\n\t\ttimeout: 5000,\n\t\tstdio: [\"pipe\", \"ignore\", \"ignore\"],\n\t\tenv: createChildProcessEnvironment(),\n\t};\n\n\tif (!copied) {\n\t\ttry {\n\t\t\tif (p === \"darwin\") {\n\t\t\t\texecSync(\"pbcopy\", options);\n\t\t\t\tcopied = true;\n\t\t\t} else if (p === \"win32\") {\n\t\t\t\texecSync(\"clip\", options);\n\t\t\t\tcopied = true;\n\t\t\t} else {\n\t\t\t\t// Linux. Try Termux, Wayland, or X11 clipboard tools.\n\t\t\t\tif (env.TERMUX_VERSION) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\texecSync(\"termux-clipboard-set\", options);\n\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Fall back to Wayland or X11 tools.\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!copied) {\n\t\t\t\t\tconst hasWaylandDisplay = Boolean(env.WAYLAND_DISPLAY);\n\t\t\t\t\tconst hasX11Display = Boolean(env.DISPLAY);\n\t\t\t\t\tconst isWayland = isWaylandSession();\n\t\t\t\t\tif (isWayland && hasWaylandDisplay) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t// Verify wl-copy exists (spawn errors are async and won't be caught)\n\t\t\t\t\t\t\texecSync(\"which wl-copy\", { stdio: \"ignore\", env: createChildProcessEnvironment() });\n\t\t\t\t\t\t\t// wl-copy with execSync hangs due to fork behavior; use spawn instead.\n\t\t\t\t\t\t\t// Await its terminal event so failures can fall through to X11 or OSC 52.\n\t\t\t\t\t\t\tconst exitCode = await new Promise<number>((resolve) => {\n\t\t\t\t\t\t\t\tconst proc = spawn(\"wl-copy\", [], {\n\t\t\t\t\t\t\t\t\tstdio: [\"pipe\", \"ignore\", \"ignore\"],\n\t\t\t\t\t\t\t\t\tenv: createChildProcessEnvironment(),\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tlet settled = false;\n\t\t\t\t\t\t\t\tconst finish = (code: number) => {\n\t\t\t\t\t\t\t\t\tif (settled) return;\n\t\t\t\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\t\t\t\tresolve(code);\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tproc.once(\"error\", () => finish(1));\n\t\t\t\t\t\t\t\tproc.once(\"close\", (code) => finish(code ?? 1));\n\t\t\t\t\t\t\t\tproc.stdin.on(\"error\", () => {});\n\t\t\t\t\t\t\t\tproc.stdin.end(text);\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (exitCode === 0) copied = true;\n\t\t\t\t\t\t\telse if (hasX11Display) {\n\t\t\t\t\t\t\t\tcopyToX11Clipboard(options);\n\t\t\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\tif (hasX11Display) {\n\t\t\t\t\t\t\t\tcopyToX11Clipboard(options);\n\t\t\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (hasX11Display) {\n\t\t\t\t\t\tcopyToX11Clipboard(options);\n\t\t\t\t\t\tcopied = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// Fall through to OSC 52 fallback.\n\t\t}\n\t}\n\n\tlet osc52Emitted = false;\n\t// A remote session skips the Windows clipboard: the copied text belongs on the connected\n\t// client, which the OSC 52 fallback below reaches, not on the remote host.\n\tif (!copied && !remote && 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 || copyViaWindowsClipboard(text);\n\t}\n\t// OSC 52 cannot be verified, so a desktop session with a display reports the failure\n\t// instead. Without a display the terminal is the only clipboard route (containers,\n\t// WSL without WSLg). A remote session emits it even after a successful local write:\n\t// that write reached the remote host's display clipboard, while the user is at the\n\t// client, which only the terminal can reach. The Windows interop fallback above is\n\t// different because it is a last resort that a remote session gains nothing from.\n\tconst headless = p === \"linux\" && !env.DISPLAY && !env.WAYLAND_DISPLAY && !env.TERMUX_VERSION;\n\tlet oversized = false;\n\tif (!osc52Emitted && (remote || (!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"]}
@@ -0,0 +1,2 @@
1
+ export declare function redactCredentialShapes(text: string): string;
2
+ //# sourceMappingURL=credential-redaction.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credential-redaction.d.ts","sourceRoot":"","sources":["../../src/utils/credential-redaction.ts"],"names":[],"mappings":"AAgBA,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAU3D"}
@@ -0,0 +1,20 @@
1
+ const CREDENTIAL_SHAPES = [
2
+ /\bBearer\s+[\w.~+/-]+=*/giu,
3
+ /\beyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]+/gu,
4
+ /\b(?:sk|pk|rk|api|key|tok|token|secret)[-_][\w-]{12,}/giu,
5
+ ];
6
+ const CREDENTIAL_FIELD_NAME = "(?:x-)?(?:api[-_]?key|apikey|auth(?:orization)?|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|secret[-_]?key|private[-_]?key|session[-_]?key|password|passwd|token|secret|key)";
7
+ const CREDENTIAL_AUTH_SCHEME = "(?:Bearer|Basic|Digest|Token|ApiKey|OAuth)";
8
+ const CREDENTIAL_CONTEXTS = [
9
+ new RegExp(String.raw `\b${CREDENTIAL_FIELD_NAME}\s*:\s*(?:${CREDENTIAL_AUTH_SCHEME}\s+)?[^\s,;}"']+`, "giu"),
10
+ new RegExp(String.raw `(["']?)${CREDENTIAL_FIELD_NAME}\1\s*:\s*(["'])(?:(?!\2).)*\2`, "giu"),
11
+ new RegExp(String.raw `\b${CREDENTIAL_FIELD_NAME}\s*=\s*[^\s&,;}"']+`, "giu"),
12
+ ];
13
+ export function redactCredentialShapes(text) {
14
+ const byContext = CREDENTIAL_CONTEXTS.reduce((masked, context) => masked.replace(context, (match) => {
15
+ const separator = /[:=]/u.exec(match);
16
+ return separator ? `${match.slice(0, separator.index + 1)} [redacted]` : "[redacted]";
17
+ }), text);
18
+ return CREDENTIAL_SHAPES.reduce((masked, shape) => masked.replace(shape, "[redacted]"), byContext);
19
+ }
20
+ //# sourceMappingURL=credential-redaction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credential-redaction.js","sourceRoot":"","sources":["../../src/utils/credential-redaction.ts"],"names":[],"mappings":"AAAA,MAAM,iBAAiB,GAAsB;IAC5C,4BAA4B;IAC5B,qCAAqC;IACrC,0DAA0D;CAC1D,CAAC;AAEF,MAAM,qBAAqB,GAC1B,oMAAoM,CAAC;AACtM,MAAM,sBAAsB,GAAG,4CAA4C,CAAC;AAE5E,MAAM,mBAAmB,GAAsB;IAC9C,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,CAAA,KAAK,qBAAqB,aAAa,sBAAsB,kBAAkB,EAAE,KAAK,CAAC;IAC5G,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,CAAA,UAAU,qBAAqB,+BAA+B,EAAE,KAAK,CAAC;IAC3F,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,CAAA,KAAK,qBAAqB,qBAAqB,EAAE,KAAK,CAAC;CAC5E,CAAC;AAEF,MAAM,UAAU,sBAAsB,CAAC,IAAY;IAClD,MAAM,SAAS,GAAG,mBAAmB,CAAC,MAAM,CAC3C,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,CACnB,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE;QACjC,MAAM,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACtC,OAAO,SAAS,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,KAAK,GAAG,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,YAAY,CAAC;IACvF,CAAC,CAAC,EACH,IAAI,CACJ,CAAC;IACF,OAAO,iBAAiB,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,YAAY,CAAC,EAAE,SAAS,CAAC,CAAC;AACpG,CAAC","sourcesContent":["const CREDENTIAL_SHAPES: readonly RegExp[] = [\n\t/\\bBearer\\s+[\\w.~+/-]+=*/giu,\n\t/\\beyJ[\\w-]{8,}\\.[\\w-]{8,}\\.[\\w-]+/gu,\n\t/\\b(?:sk|pk|rk|api|key|tok|token|secret)[-_][\\w-]{12,}/giu,\n];\n\nconst CREDENTIAL_FIELD_NAME =\n\t\"(?:x-)?(?:api[-_]?key|apikey|auth(?:orization)?|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|secret[-_]?key|private[-_]?key|session[-_]?key|password|passwd|token|secret|key)\";\nconst CREDENTIAL_AUTH_SCHEME = \"(?:Bearer|Basic|Digest|Token|ApiKey|OAuth)\";\n\nconst CREDENTIAL_CONTEXTS: readonly RegExp[] = [\n\tnew RegExp(String.raw`\\b${CREDENTIAL_FIELD_NAME}\\s*:\\s*(?:${CREDENTIAL_AUTH_SCHEME}\\s+)?[^\\s,;}\"']+`, \"giu\"),\n\tnew RegExp(String.raw`([\"']?)${CREDENTIAL_FIELD_NAME}\\1\\s*:\\s*([\"'])(?:(?!\\2).)*\\2`, \"giu\"),\n\tnew RegExp(String.raw`\\b${CREDENTIAL_FIELD_NAME}\\s*=\\s*[^\\s&,;}\"']+`, \"giu\"),\n];\n\nexport function redactCredentialShapes(text: string): string {\n\tconst byContext = CREDENTIAL_CONTEXTS.reduce(\n\t\t(masked, context) =>\n\t\t\tmasked.replace(context, (match) => {\n\t\t\t\tconst separator = /[:=]/u.exec(match);\n\t\t\t\treturn separator ? `${match.slice(0, separator.index + 1)} [redacted]` : \"[redacted]\";\n\t\t\t}),\n\t\ttext,\n\t);\n\treturn CREDENTIAL_SHAPES.reduce((masked, shape) => masked.replace(shape, \"[redacted]\"), byContext);\n}\n"]}
@@ -13,6 +13,14 @@ export interface ResizedImage {
13
13
  height: number;
14
14
  wasResized: boolean;
15
15
  }
16
+ export declare const IMAGE_RESIZE_WORKER_RESPONSE_TYPE = "pi:image-resize-response";
17
+ export type ResizeImageWorkerResponse = {
18
+ type: typeof IMAGE_RESIZE_WORKER_RESPONSE_TYPE;
19
+ result: ResizedImage | null;
20
+ } | {
21
+ type: typeof IMAGE_RESIZE_WORKER_RESPONSE_TYPE;
22
+ error: string;
23
+ };
16
24
  /**
17
25
  * Resize an image to fit within the specified max dimensions and encoded file size.
18
26
  * 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,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,6 @@
1
1
  import { applyExifOrientation } from "./exif-orientation.js";
2
2
  import { loadPhoton } from "./photon.js";
3
+ export const IMAGE_RESIZE_WORKER_RESPONSE_TYPE = "pi:image-resize-response";
3
4
  // 4.5MB of base64 payload. Provides headroom below Anthropic's 5MB limit.
4
5
  const DEFAULT_MAX_BYTES = 4.5 * 1024 * 1024;
5
6
  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,u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AAC;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,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,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,CA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,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\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,EAAE,MAAM,wBAAwB,CAAC;AAa1G,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,MAAM,EAAE,CAAC;YACvD,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;QAC5B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,MAAM,QAAQ,GAA8B;gBAC3C,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 { type ImageResizeOptions, 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.js\";\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,5 +1,5 @@
1
- import { type ImageResizeOptions, type ResizedImage } from "./image-resize-core.ts";
2
- export type { ImageResizeOptions, ResizedImage } from "./image-resize-core.ts";
1
+ import { type ImageResizeOptions, type ResizedImage } from "./image-resize-core.js";
2
+ export type { ImageResizeOptions, ResizedImage } from "./image-resize-core.js";
3
3
  /**
4
4
  * Resize an image to fit within the specified max dimensions and encoded file size.
5
5
  * Runs Photon in a worker thread so WASM decoding, resizing, and encoding do not
@@ -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;AAiE/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,13 @@ 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
+ if (!isResizeImageWorkerResponse(message))
35
34
  return;
36
- }
37
- if (message.error) {
35
+ if ("error" in message)
38
36
  fail(new Error(message.error));
39
- return;
40
- }
41
- settle(message.result ?? null);
37
+ else
38
+ settle(message.result);
42
39
  });
43
40
  worker.once("error", fail);
44
41
  worker.once("exit", (code) => {
@@ -1 +1 @@
1
- {"version":3,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OAAO,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":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EACN,iCAAiC,EAIjC,oBAAoB,GACpB,MAAM,wBAAwB,CAAC;AAIhC,SAAS,mBAAmB,CAAC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C,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.js\";\n\nexport type { ImageResizeOptions, ResizedImage } from \"./image-resize-core.js\";\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\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"]}
package/docs/codemode.md CHANGED
@@ -64,7 +64,7 @@ The store is for small state such as IDs, cursors, or summaries. One value may h
64
64
 
65
65
  ## Models
66
66
 
67
- `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. Classifier models include [TypeSafe Jev](/providers#typesafe-jev) and [local llama.cpp models](/llama-cpp); image models include OpenRouter's, such as `google/gemini-2.5-flash-image` and `black-forest-labs/flux.2-pro`, which use the same `OPENROUTER_API_KEY` or `/login` credential as its chat models. Neither kind appears in `/model`.
67
+ `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. Classifier models include [TypeSafe Jev](/providers#typesafe-jev), [OpenAI GPT-6 Luna](/models#use-classifier-models), and [local llama.cpp models](/llama-cpp); image models include OpenRouter's, such as `google/gemini-2.5-flash-image` and `black-forest-labs/flux.2-pro`, which use the same `OPENROUTER_API_KEY` or `/login` credential as its chat models. Neither kind appears in `/model`.
68
68
 
69
69
  ```ts
70
70
  type ModelType = "chat" | "image" | "classifier";
@@ -105,6 +105,7 @@ Model IDs differ between providers. Use `models.getAvailableOfType(type)` to fin
105
105
  interface ClassifierContext {
106
106
  /** The data to classify. */
107
107
  state: Record<string, unknown>;
108
+ images?: { type: "image"; data: string; mimeType: string }[];
108
109
  /** Questions by ID. One call answers all of them. */
109
110
  questions: Record<string, ClassifierQuestion>;
110
111
  }
@@ -168,6 +169,25 @@ return results.map((result, i) =>
168
169
  );
169
170
  ```
170
171
 
172
+ Classifiers whose `input` includes `"image"` can judge images alongside the state. `tools.read()` returns image blocks that `images` accepts. Text-only classifiers and APIs that cannot send images return an error result for nonempty `images`.
173
+
174
+ ```js
175
+ const luna = await models.getModelOfType("classifier", "openai", "gpt-6-luna");
176
+ const photo = await tools.read({ path: "screenshot.png" });
177
+ const result = await models.classify(luna, {
178
+ state: { task: "Settings page redesign" },
179
+ images: [photo],
180
+ questions: {
181
+ broken: {
182
+ type: "bool",
183
+ instructions: "Does the screenshot show a broken layout?",
184
+ criteria: { true: "Overlapping, cut-off, or misaligned elements", false: "Clean layout" },
185
+ },
186
+ },
187
+ });
188
+ return result.stopReason === "stop" ? result.answers : result.errorMessage;
189
+ ```
190
+
171
191
  ### Generate images
172
192
 
173
193
  ```ts
@@ -20,6 +20,8 @@ The effective parameters appear in extension events and successful results:
20
20
 
21
21
  Atomic carries the recent tail with the compaction boundary rather than replaying it as separate assistant and tool-result messages. Tail text, tool calls, and tool results remain lossless; images remain image blocks. If `query` is absent, Atomic uses the last visible user message.
22
22
 
23
+ The policy-refusal summary fallback instead keeps a token-based recent tail, replayed as separate messages. Its checkpoint is lossy rather than a verbatim transcript.
24
+
23
25
  Compaction resets Claude's signed reasoning chain: `thinking` and `redacted_thinking` blocks do not survive the boundary. See [Preserved thinking and model switches](/models/reference#preserved-thinking-and-model-switches) for behavior between boundaries.
24
26
 
25
27
  The query is never truncated. An oversized planner request reports overflow rather than silently dropping part of it. Use `keepContext` tags, not a longer query, to guarantee protection.
@@ -75,8 +77,10 @@ A successful run appends the existing pi-style `type:"compaction"` entry shape:
75
77
  "tokensBefore": 51234,
76
78
  "details": {
77
79
  "strategy": "verbatim-lines",
78
- "promptVersion": 3,
80
+ "promptVersion": 4,
79
81
  "rung": "planned",
82
+ "backend": "planner",
83
+ "model": "openai-codex/gpt-6.1-sol",
80
84
  "parameters": {"compression_ratio": 0.5, "preserve_recent": 2, "query": "fix the failing test"},
81
85
  "stats": {"linesBefore": 812, "linesDeleted": 417, "linesKept": 395, "rangeCount": 63, "tokensBefore": 51234, "tokensAfter": 24980, "percentReduction": 51.2}
82
86
  }
@@ -85,12 +89,12 @@ A successful run appends the existing pi-style `type:"compaction"` entry shape:
85
89
 
86
90
  The entry's `tokensBefore` is the provider-aware whole-context count used for budgeting and the Compacted from display. `details.stats.tokensBefore`, `tokensAfter`, and `percentReduction` are heuristic estimates of the compactable region plus the kept tail. Those stats can differ from the entry count, and `percentReduction` is negative when the reconstructed estimate is larger. The display count is not stored again under `details.tokensBefore`.
87
91
 
88
- `details.rung` is one of `"planned"` (a model ranked the lines — the session model **or** a borrowed fallback, including silent partial recovery), `"extension"` (a `session_before_compact` override), or `"fresh"` (the compactable conversation was discarded and a new context window started). `details.plannerModel` is present **only** when a borrowed fallback model ranked the lines:
92
+ `details.rung` is `"planned"` for successful model compaction, `"extension"` for a `session_before_compact` override, or `"fresh"` when older context was discarded. `details.backend` and `details.model` identify the successful compactor. A policy-refusal fallback records `backend: "summary"`, the same model that refused, and file lists in `details.summary`. Its card says `summary (pi fallback)`. `details.plannerModel` identifies a borrowed chat planner:
89
93
 
90
94
  ```json
91
95
  "details": {
92
96
  "strategy": "verbatim-lines",
93
- "promptVersion": 3,
97
+ "promptVersion": 4,
94
98
  "rung": "planned",
95
99
  "plannerModel": {"provider": "openai", "id": "gpt-5.1", "thinkingLevel": "high"}
96
100
  }
@@ -255,7 +259,9 @@ Configure compaction in `~/.atomic/agent/settings.json` or `<project-dir>/.atomi
255
259
  | `enabled` | `true` | Enable automatic Verbatim Compaction. |
256
260
  | `reserveTokens` | `16384` | Tokens to reserve for the next LLM response; threshold auto-compaction starts when completed-response usage or a prospective post-tool context exceeds the model's effective input budget minus this reserve. It is an **input-side** reserve only and never caps planner output. |
257
261
 
258
- Compaction has no configuration key of its own for fallback borrowing: it reuses `settings.fallbackModels`, the same ordered `provider/model[:thinkingLevel]` list that main-chat model fallback walks. With no `fallbackModels` configured, compaction behaves as before: one planner model, then either an honest failure (recoverable) or a fresh context window (load-bearing).
262
+ The top-level `compactionModel` setting defaults to `"auto"`, using the session model. An exact registered chat-model, classifier, or compactor ID selects a separate compactor. Project settings may not select `morph/*`. See [Compaction model](/compaction#compaction-model).
263
+
264
+ Fallback borrowing reuses `settings.fallbackModels`, the same ordered `provider/model[:thinkingLevel]` list used for chat fallback. It skips entries equal to the selected compaction model. A policy refusal from any chat compaction model, including `auto`, explicit chat-model IDs, and borrowed fallback entries, first tries pi's summary compaction on the same model. Classifier and Morph refusals skip summary fallback and advance directly to the next configured model. Other failures and failed summaries also advance to the next configured model. Only load-bearing recovery may clear older context after all attempts fail.
259
265
 
260
266
  Disable auto-compaction with `"enabled": false`. You can still compact manually with `/compact`.
261
267