@oh-my-pi/pi-coding-agent 15.10.10 → 15.10.11

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 (345) hide show
  1. package/CHANGELOG.md +95 -4
  2. package/dist/cli.js +23087 -0
  3. package/dist/tokenizers.linux-x64-gnu-xcjh3jwk.node +0 -0
  4. package/dist/types/async/job-manager.d.ts +18 -0
  5. package/dist/types/cli/args.d.ts +1 -1
  6. package/dist/types/cli/dry-balance-cli.d.ts +1 -1
  7. package/dist/types/cli/gallery-cli.d.ts +1 -1
  8. package/dist/types/cli/gallery-fixtures/types.d.ts +1 -1
  9. package/dist/types/cli/usage-cli.d.ts +72 -0
  10. package/dist/types/commands/launch.d.ts +1 -1
  11. package/dist/types/commands/read.d.ts +1 -1
  12. package/dist/types/commands/usage.d.ts +25 -0
  13. package/dist/types/config/append-only-context-mode.d.ts +2 -1
  14. package/dist/types/config/model-discovery.d.ts +55 -0
  15. package/dist/types/config/model-registry.d.ts +7 -219
  16. package/dist/types/config/model-resolver.d.ts +16 -10
  17. package/dist/types/config/model-roles.d.ts +28 -0
  18. package/dist/types/config/models-config-schema.d.ts +523 -42
  19. package/dist/types/config/models-config.d.ts +385 -0
  20. package/dist/types/config/settings-schema.d.ts +12 -7
  21. package/dist/types/config/settings.d.ts +1 -1
  22. package/dist/types/debug/log-viewer.d.ts +1 -1
  23. package/dist/types/debug/raw-sse.d.ts +1 -1
  24. package/dist/types/eval/backend.d.ts +0 -2
  25. package/dist/types/eval/idle-timeout.d.ts +0 -4
  26. package/dist/types/eval/js/shared/rewrite-imports.d.ts +6 -6
  27. package/dist/types/export/html/template.generated.d.ts +1 -1
  28. package/dist/types/extensibility/extensions/types.d.ts +3 -3
  29. package/dist/types/hindsight/mental-models.d.ts +17 -8
  30. package/dist/types/internal-urls/artifact-protocol.d.ts +2 -2
  31. package/dist/types/internal-urls/types.d.ts +1 -1
  32. package/dist/types/lsp/edits.d.ts +9 -0
  33. package/dist/types/lsp/index.d.ts +2 -2
  34. package/dist/types/lsp/types.d.ts +2 -0
  35. package/dist/types/lsp/utils.d.ts +3 -0
  36. package/dist/types/mcp/json-rpc.d.ts +5 -0
  37. package/dist/types/mnemopi/state.d.ts +11 -1
  38. package/dist/types/modes/components/agent-dashboard.d.ts +1 -1
  39. package/dist/types/modes/components/assistant-message.d.ts +3 -1
  40. package/dist/types/modes/components/bash-execution.d.ts +1 -1
  41. package/dist/types/modes/components/copy-selector.d.ts +1 -1
  42. package/dist/types/modes/components/dynamic-border.d.ts +1 -1
  43. package/dist/types/modes/components/extensions/extension-dashboard.d.ts +1 -1
  44. package/dist/types/modes/components/extensions/extension-list.d.ts +1 -1
  45. package/dist/types/modes/components/extensions/inspector-panel.d.ts +1 -1
  46. package/dist/types/modes/components/footer.d.ts +1 -1
  47. package/dist/types/modes/components/hook-editor.d.ts +5 -0
  48. package/dist/types/modes/components/hook-input.d.ts +4 -0
  49. package/dist/types/modes/components/hook-selector.d.ts +1 -1
  50. package/dist/types/modes/components/model-selector.d.ts +1 -1
  51. package/dist/types/modes/components/plan-review-overlay.d.ts +1 -1
  52. package/dist/types/modes/components/session-observer-overlay.d.ts +1 -1
  53. package/dist/types/modes/components/session-selector.d.ts +1 -1
  54. package/dist/types/modes/components/status-line/component.d.ts +1 -1
  55. package/dist/types/modes/components/tiny-title-download-progress.d.ts +1 -1
  56. package/dist/types/modes/components/transcript-container.d.ts +25 -6
  57. package/dist/types/modes/components/tree-selector.d.ts +1 -1
  58. package/dist/types/modes/components/user-message-selector.d.ts +1 -1
  59. package/dist/types/modes/components/user-message.d.ts +2 -1
  60. package/dist/types/modes/components/visual-truncate.d.ts +1 -1
  61. package/dist/types/modes/components/welcome.d.ts +19 -3
  62. package/dist/types/modes/controllers/mcp-command-controller.d.ts +1 -1
  63. package/dist/types/modes/controllers/streaming-reveal.d.ts +1 -1
  64. package/dist/types/modes/interactive-mode.d.ts +1 -1
  65. package/dist/types/modes/setup-wizard/scenes/sign-in.d.ts +1 -1
  66. package/dist/types/modes/setup-wizard/scenes/types.d.ts +1 -1
  67. package/dist/types/modes/setup-wizard/scenes/web-search.d.ts +1 -1
  68. package/dist/types/modes/setup-wizard/wizard-overlay.d.ts +1 -1
  69. package/dist/types/modes/types.d.ts +2 -1
  70. package/dist/types/session/agent-session.d.ts +1 -1
  71. package/dist/types/session/auth-broker-config.d.ts +4 -0
  72. package/dist/types/session/session-manager.d.ts +1 -1
  73. package/dist/types/slash-commands/helpers/stats-dashboard.d.ts +13 -0
  74. package/dist/types/ssh/connection-manager.d.ts +8 -0
  75. package/dist/types/task/parallel.d.ts +2 -2
  76. package/dist/types/task/worktree.d.ts +2 -0
  77. package/dist/types/tools/ask.d.ts +4 -0
  78. package/dist/types/tools/conflict-detect.d.ts +16 -0
  79. package/dist/types/tools/github-cache.d.ts +7 -0
  80. package/dist/types/tools/sqlite-reader.d.ts +3 -0
  81. package/dist/types/tui/output-block.d.ts +3 -3
  82. package/dist/types/utils/changelog.d.ts +8 -0
  83. package/dist/types/web/scrapers/readthedocs.d.ts +3 -0
  84. package/dist/types/web/scrapers/types.d.ts +12 -0
  85. package/dist/types/web/search/providers/codex.d.ts +1 -1
  86. package/dist/types/web/search/providers/gemini.d.ts +1 -1
  87. package/examples/extensions/tools.ts +5 -4
  88. package/package.json +14 -11
  89. package/scripts/build-binary.ts +18 -23
  90. package/scripts/bundle-dist.ts +81 -0
  91. package/scripts/{dev-launch → omp} +1 -1
  92. package/scripts/{dev-launch-preload.ts → omp.ts} +1 -1
  93. package/src/async/job-manager.ts +57 -3
  94. package/src/autoresearch/dashboard.ts +1 -1
  95. package/src/autoresearch/prompt-setup.md +6 -6
  96. package/src/autoresearch/prompt.md +6 -6
  97. package/src/capability/fs.ts +10 -0
  98. package/src/cli/args.ts +1 -1
  99. package/src/cli/auth-gateway-cli.ts +1 -3
  100. package/src/cli/dry-balance-cli.ts +1 -1
  101. package/src/cli/gallery-cli.ts +1 -1
  102. package/src/cli/gallery-fixtures/fs.ts +1 -1
  103. package/src/cli/gallery-fixtures/types.ts +5 -1
  104. package/src/cli/list-models.ts +2 -1
  105. package/src/cli/usage-cli.ts +603 -0
  106. package/src/cli-commands.ts +1 -0
  107. package/src/cli.ts +69 -5
  108. package/src/commands/complete.ts +1 -1
  109. package/src/commands/launch.ts +1 -1
  110. package/src/commands/read.ts +6 -3
  111. package/src/commands/usage.ts +35 -0
  112. package/src/commit/agentic/agent.ts +1 -1
  113. package/src/commit/model-selection.ts +1 -1
  114. package/src/config/append-only-context-mode.ts +6 -12
  115. package/src/config/model-discovery.ts +554 -0
  116. package/src/config/model-registry.ts +231 -1019
  117. package/src/config/model-resolver.ts +113 -156
  118. package/src/config/model-roles.ts +74 -0
  119. package/src/config/models-config-schema.ts +57 -8
  120. package/src/config/models-config.ts +129 -0
  121. package/src/config/settings-schema.ts +18 -4
  122. package/src/config/settings.ts +37 -1
  123. package/src/dap/client.ts +124 -37
  124. package/src/dap/session.ts +259 -158
  125. package/src/debug/log-viewer.ts +1 -1
  126. package/src/debug/raw-sse.ts +1 -1
  127. package/src/edit/diff.ts +47 -3
  128. package/src/edit/hashline/block-resolver.ts +20 -1
  129. package/src/edit/hashline/diff.ts +36 -1
  130. package/src/edit/hashline/execute.ts +8 -2
  131. package/src/edit/index.ts +16 -1
  132. package/src/edit/modes/patch.ts +52 -0
  133. package/src/edit/modes/replace.ts +56 -22
  134. package/src/edit/notebook.ts +22 -2
  135. package/src/edit/renderer.ts +36 -10
  136. package/src/eval/__tests__/completion-bridge.test.ts +1 -1
  137. package/src/eval/backend.ts +0 -2
  138. package/src/eval/completion-bridge.ts +2 -1
  139. package/src/eval/idle-timeout.ts +2 -9
  140. package/src/eval/js/context-manager.ts +6 -8
  141. package/src/eval/js/executor.ts +6 -2
  142. package/src/eval/js/index.ts +0 -2
  143. package/src/eval/js/shared/helpers.ts +5 -6
  144. package/src/eval/js/shared/local-module-loader.ts +1 -1
  145. package/src/eval/js/shared/prelude.txt +62 -1
  146. package/src/eval/js/shared/rewrite-imports.ts +40 -22
  147. package/src/eval/js/shared/runtime.ts +1 -1
  148. package/src/eval/py/index.ts +0 -2
  149. package/src/eval/py/kernel.ts +19 -0
  150. package/src/eval/py/runner.py +107 -3
  151. package/src/exec/bash-executor.ts +3 -1
  152. package/src/export/html/template.generated.ts +1 -1
  153. package/src/export/html/template.js +3 -1
  154. package/src/extensibility/extensions/types.ts +3 -2
  155. package/src/extensibility/plugins/legacy-pi-compat.ts +20 -3
  156. package/src/hindsight/mental-models.ts +59 -12
  157. package/src/hindsight/state.ts +6 -1
  158. package/src/internal-urls/artifact-protocol.ts +11 -2
  159. package/src/internal-urls/docs-index.generated.ts +8 -8
  160. package/src/internal-urls/issue-pr-protocol.ts +12 -5
  161. package/src/internal-urls/router.ts +1 -1
  162. package/src/internal-urls/types.ts +1 -1
  163. package/src/lib/xai-http.ts +1 -1
  164. package/src/lsp/client.ts +118 -38
  165. package/src/lsp/clients/biome-client.ts +101 -39
  166. package/src/lsp/edits.ts +143 -95
  167. package/src/lsp/index.ts +31 -22
  168. package/src/lsp/render.ts +1 -1
  169. package/src/lsp/types.ts +2 -0
  170. package/src/lsp/utils.ts +28 -10
  171. package/src/main.ts +165 -17
  172. package/src/mcp/json-rpc.ts +35 -5
  173. package/src/mcp/transports/stdio.ts +7 -1
  174. package/src/memories/index.ts +2 -1
  175. package/src/mnemopi/backend.ts +25 -3
  176. package/src/mnemopi/state.ts +38 -2
  177. package/src/modes/components/agent-dashboard.ts +10 -7
  178. package/src/modes/components/assistant-message.ts +19 -13
  179. package/src/modes/components/bash-execution.ts +1 -1
  180. package/src/modes/components/copy-selector.ts +1 -1
  181. package/src/modes/components/diff.ts +13 -2
  182. package/src/modes/components/dynamic-border.ts +12 -3
  183. package/src/modes/components/extensions/extension-dashboard.ts +8 -5
  184. package/src/modes/components/extensions/extension-list.ts +1 -1
  185. package/src/modes/components/extensions/inspector-panel.ts +1 -1
  186. package/src/modes/components/footer.ts +1 -1
  187. package/src/modes/components/history-search.ts +1 -1
  188. package/src/modes/components/hook-editor.ts +8 -0
  189. package/src/modes/components/hook-input.ts +8 -0
  190. package/src/modes/components/hook-selector.ts +2 -2
  191. package/src/modes/components/model-selector.ts +4 -2
  192. package/src/modes/components/plan-review-overlay.ts +1 -1
  193. package/src/modes/components/session-observer-overlay.ts +2 -2
  194. package/src/modes/components/session-selector.ts +1 -1
  195. package/src/modes/components/settings-selector.ts +5 -1
  196. package/src/modes/components/status-line/component.ts +1 -1
  197. package/src/modes/components/tiny-title-download-progress.ts +1 -1
  198. package/src/modes/components/transcript-container.ts +258 -53
  199. package/src/modes/components/tree-selector.ts +3 -3
  200. package/src/modes/components/user-message-selector.ts +1 -1
  201. package/src/modes/components/user-message.ts +17 -5
  202. package/src/modes/components/visual-truncate.ts +1 -1
  203. package/src/modes/components/welcome.ts +108 -26
  204. package/src/modes/controllers/command-controller.ts +10 -3
  205. package/src/modes/controllers/event-controller.ts +73 -4
  206. package/src/modes/controllers/input-controller.ts +1 -1
  207. package/src/modes/controllers/mcp-command-controller.ts +1 -1
  208. package/src/modes/controllers/selector-controller.ts +1 -1
  209. package/src/modes/controllers/streaming-reveal.ts +85 -18
  210. package/src/modes/interactive-mode.ts +3 -9
  211. package/src/modes/setup-wizard/scenes/glyph.ts +1 -1
  212. package/src/modes/setup-wizard/scenes/providers.ts +1 -1
  213. package/src/modes/setup-wizard/scenes/sign-in.ts +1 -1
  214. package/src/modes/setup-wizard/scenes/theme.ts +1 -1
  215. package/src/modes/setup-wizard/scenes/types.ts +1 -1
  216. package/src/modes/setup-wizard/scenes/web-search.ts +1 -1
  217. package/src/modes/setup-wizard/wizard-overlay.ts +1 -1
  218. package/src/modes/types.ts +2 -1
  219. package/src/prompts/agents/explore.md +2 -2
  220. package/src/prompts/agents/librarian.md +1 -2
  221. package/src/prompts/agents/oracle.md +1 -1
  222. package/src/prompts/agents/plan.md +5 -5
  223. package/src/prompts/agents/task.md +5 -5
  224. package/src/prompts/ci-green-request.md +5 -7
  225. package/src/prompts/goals/goal-budget-limit.md +2 -2
  226. package/src/prompts/goals/goal-continuation.md +4 -4
  227. package/src/prompts/goals/goal-mode-active.md +1 -1
  228. package/src/prompts/memories/read-path.md +1 -1
  229. package/src/prompts/memories/stage_one_system.md +2 -2
  230. package/src/prompts/review-custom-request.md +1 -1
  231. package/src/prompts/system/agent-creation-architect.md +2 -2
  232. package/src/prompts/system/auto-continue.md +1 -1
  233. package/src/prompts/system/background-tan-dispatch.md +1 -1
  234. package/src/prompts/system/btw-user.md +2 -2
  235. package/src/prompts/system/commit-message-system.md +13 -1
  236. package/src/prompts/system/custom-system-prompt.md +1 -1
  237. package/src/prompts/system/eager-todo.md +2 -2
  238. package/src/prompts/system/irc-incoming.md +1 -1
  239. package/src/prompts/system/manual-continue.md +1 -1
  240. package/src/prompts/system/omfg-user.md +3 -4
  241. package/src/prompts/system/orchestrate-notice.md +9 -9
  242. package/src/prompts/system/plan-mode-active.md +4 -4
  243. package/src/prompts/system/plan-mode-subagent.md +4 -5
  244. package/src/prompts/system/plan-mode-tool-decision-reminder.md +1 -1
  245. package/src/prompts/system/project-prompt.md +2 -2
  246. package/src/prompts/system/subagent-system-prompt.md +4 -4
  247. package/src/prompts/system/system-prompt.md +13 -24
  248. package/src/prompts/system/title-system.md +2 -2
  249. package/src/prompts/system/ttsr-tool-reminder.md +1 -1
  250. package/src/prompts/system/workflow-notice.md +1 -1
  251. package/src/prompts/tools/ast-edit.md +1 -1
  252. package/src/prompts/tools/ast-grep.md +2 -2
  253. package/src/prompts/tools/bash.md +5 -7
  254. package/src/prompts/tools/browser.md +7 -7
  255. package/src/prompts/tools/debug.md +1 -1
  256. package/src/prompts/tools/eval.md +3 -3
  257. package/src/prompts/tools/find.md +0 -1
  258. package/src/prompts/tools/github.md +8 -7
  259. package/src/prompts/tools/goal.md +1 -1
  260. package/src/prompts/tools/image-gen.md +1 -1
  261. package/src/prompts/tools/inspect-image-system.md +1 -1
  262. package/src/prompts/tools/irc.md +15 -15
  263. package/src/prompts/tools/lsp.md +2 -2
  264. package/src/prompts/tools/patch.md +2 -2
  265. package/src/prompts/tools/read.md +3 -4
  266. package/src/prompts/tools/recall.md +1 -1
  267. package/src/prompts/tools/reflect.md +1 -1
  268. package/src/prompts/tools/render-mermaid.md +2 -2
  269. package/src/prompts/tools/replace.md +4 -10
  270. package/src/prompts/tools/rewind.md +2 -2
  271. package/src/prompts/tools/search-tool-bm25.md +1 -9
  272. package/src/prompts/tools/search.md +0 -1
  273. package/src/prompts/tools/ssh.md +0 -4
  274. package/src/prompts/tools/task.md +2 -3
  275. package/src/prompts/tools/todo.md +1 -1
  276. package/src/sdk.ts +23 -10
  277. package/src/session/agent-session.ts +44 -10
  278. package/src/session/auth-broker-config.ts +30 -1
  279. package/src/session/session-manager.ts +2 -2
  280. package/src/session/streaming-output.ts +23 -2
  281. package/src/slash-commands/builtin-registry.ts +20 -0
  282. package/src/slash-commands/helpers/stats-dashboard.ts +85 -0
  283. package/src/ssh/connection-manager.ts +27 -0
  284. package/src/task/commands.ts +2 -1
  285. package/src/task/executor.ts +61 -53
  286. package/src/task/index.ts +137 -60
  287. package/src/task/parallel.ts +3 -3
  288. package/src/task/render.ts +2 -2
  289. package/src/task/worktree.ts +64 -56
  290. package/src/thinking.ts +2 -1
  291. package/src/tiny/title-client.ts +26 -11
  292. package/src/tools/archive-reader.ts +30 -2
  293. package/src/tools/ask.ts +104 -21
  294. package/src/tools/ast-edit.ts +25 -5
  295. package/src/tools/auto-generated-guard.ts +20 -3
  296. package/src/tools/bash-interactive.ts +27 -7
  297. package/src/tools/bash.ts +54 -13
  298. package/src/tools/browser/launch.ts +11 -2
  299. package/src/tools/browser/readable.ts +19 -2
  300. package/src/tools/browser/registry.ts +4 -1
  301. package/src/tools/browser/render.ts +2 -2
  302. package/src/tools/browser/tab-supervisor.ts +55 -16
  303. package/src/tools/conflict-detect.ts +50 -4
  304. package/src/tools/debug.ts +1 -1
  305. package/src/tools/eval-render.ts +5 -5
  306. package/src/tools/eval.ts +0 -2
  307. package/src/tools/fetch.ts +33 -10
  308. package/src/tools/gh-cache-invalidation.ts +63 -8
  309. package/src/tools/gh-renderer.ts +1 -1
  310. package/src/tools/gh.ts +172 -29
  311. package/src/tools/github-cache.ts +70 -6
  312. package/src/tools/image-gen.ts +3 -9
  313. package/src/tools/irc.ts +5 -1
  314. package/src/tools/job.ts +1 -1
  315. package/src/tools/read.ts +202 -61
  316. package/src/tools/render-utils.ts +3 -3
  317. package/src/tools/resolve.ts +1 -1
  318. package/src/tools/search.ts +92 -29
  319. package/src/tools/sqlite-reader.ts +17 -5
  320. package/src/tools/ssh.ts +8 -8
  321. package/src/tools/todo.ts +38 -8
  322. package/src/tools/write.ts +118 -18
  323. package/src/tui/output-block.ts +4 -4
  324. package/src/utils/changelog.ts +27 -1
  325. package/src/utils/file-mentions.ts +2 -1
  326. package/src/web/scrapers/arxiv.ts +1 -1
  327. package/src/web/scrapers/go-pkg.ts +1 -1
  328. package/src/web/scrapers/iacr.ts +1 -1
  329. package/src/web/scrapers/readthedocs.ts +1 -1
  330. package/src/web/scrapers/twitter.ts +2 -1
  331. package/src/web/scrapers/types.ts +87 -8
  332. package/src/web/scrapers/wikipedia.ts +1 -1
  333. package/src/web/scrapers/youtube.ts +6 -1
  334. package/src/web/search/index.ts +1 -1
  335. package/src/web/search/providers/codex.ts +2 -1
  336. package/src/web/search/providers/gemini.ts +2 -3
  337. package/src/web/search/render.ts +8 -6
  338. package/dist/types/config/model-equivalence.d.ts +0 -24
  339. package/dist/types/config/model-id-affixes.d.ts +0 -12
  340. package/dist/types/config/model-provider-priority.d.ts +0 -1
  341. package/dist/types/exec/idle-timeout-watchdog.d.ts +0 -18
  342. package/src/config/model-equivalence.ts +0 -875
  343. package/src/config/model-id-affixes.ts +0 -81
  344. package/src/config/model-provider-priority.ts +0 -56
  345. package/src/exec/idle-timeout-watchdog.ts +0 -126
@@ -57,6 +57,39 @@ async function readSectionText(absolutePath: string, sectionPath: string): Promi
57
57
  }
58
58
  }
59
59
 
60
+ /**
61
+ * Streaming previews recompute on every streamed chunk; re-reading the target
62
+ * file from disk each tick dominates the cost on large files. Cache the raw
63
+ * section text keyed by mtime+size so any on-disk change invalidates
64
+ * naturally. Used by the streaming path only — the args-complete pass always
65
+ * reads fresh.
66
+ */
67
+ const streamingTextCache = new Map<string, { mtimeMs: number; size: number; rawContent: string }>();
68
+ const STREAMING_TEXT_CACHE_MAX = 8;
69
+
70
+ async function readSectionTextCached(absolutePath: string, sectionPath: string): Promise<string> {
71
+ let stamp: { mtimeMs: number; size: number } | undefined;
72
+ try {
73
+ const stat = await Bun.file(absolutePath).stat();
74
+ stamp = { mtimeMs: stat.mtimeMs, size: stat.size };
75
+ } catch {
76
+ stamp = undefined;
77
+ }
78
+ if (stamp) {
79
+ const cached = streamingTextCache.get(absolutePath);
80
+ if (cached && cached.mtimeMs === stamp.mtimeMs && cached.size === stamp.size) return cached.rawContent;
81
+ }
82
+ const rawContent = await readSectionText(absolutePath, sectionPath);
83
+ if (stamp) {
84
+ if (streamingTextCache.size >= STREAMING_TEXT_CACHE_MAX && !streamingTextCache.has(absolutePath)) {
85
+ const oldest = streamingTextCache.keys().next().value;
86
+ if (oldest !== undefined) streamingTextCache.delete(oldest);
87
+ }
88
+ streamingTextCache.set(absolutePath, { mtimeMs: stamp.mtimeMs, size: stamp.size, rawContent });
89
+ }
90
+ return rawContent;
91
+ }
92
+
60
93
  function hasAnchorScopedEdit(edits: readonly Edit[]): boolean {
61
94
  return edits.some(edit => {
62
95
  if (edit.kind === "delete") return true;
@@ -220,7 +253,9 @@ export async function computeHashlineSectionDiff(
220
253
  ): Promise<{ diff: string; firstChangedLine: number | undefined } | { error: string }> {
221
254
  try {
222
255
  const absolutePath = resolveToCwd(section.path, cwd);
223
- const rawContent = await readSectionText(absolutePath, section.path);
256
+ const rawContent = options.streaming
257
+ ? await readSectionTextCached(absolutePath, section.path)
258
+ : await readSectionText(absolutePath, section.path);
224
259
  const { text: content } = stripBom(rawContent);
225
260
  const normalized = normalizeToLF(content);
226
261
  // Streaming favors a stable, monotonic preview over an exact unified
@@ -78,11 +78,17 @@ interface RenderedSection {
78
78
  }
79
79
 
80
80
  function formatBlockResolution(resolution: BlockResolution): string {
81
- const op = resolution.isDelete ? "delete block" : "replace block";
81
+ const op =
82
+ resolution.op === "delete"
83
+ ? "delete block"
84
+ : resolution.op === "insert_after"
85
+ ? "insert after block"
86
+ : "replace block";
82
87
  const lines = resolution.end - resolution.start + 1;
83
88
  const span =
84
89
  resolution.start === resolution.end ? `line ${resolution.start}` : `lines ${resolution.start}-${resolution.end}`;
85
- return `${op} ${resolution.anchorLine} resolved ${span} (${lines} line${lines === 1 ? "" : "s"})`;
90
+ const suffix = resolution.op === "insert_after" ? `; body lands after line ${resolution.end}` : "";
91
+ return `${op} ${resolution.anchorLine} → resolved ${span} (${lines} line${lines === 1 ? "" : "s"})${suffix}`;
86
92
  }
87
93
 
88
94
  function renderSection(result: PatchSectionResult, diagnostics: FileDiagnosticsResult | undefined): RenderedSection {
package/src/edit/index.ts CHANGED
@@ -238,8 +238,23 @@ async function executeSinglePathEntries(
238
238
  if (text) contentTexts.push(text);
239
239
  } catch (err) {
240
240
  const errorText = err instanceof Error ? err.message : String(err);
241
- contentTexts.push(`Error editing ${path}: ${errorText}`);
241
+ contentTexts.push(`Error editing ${path} (entry ${i + 1} of ${runs.length}): ${errorText}`);
242
+ if (i > 0) {
243
+ contentTexts.push(i === 1 ? `Entry 1 was already applied.` : `Entries 1-${i} were already applied.`);
244
+ }
245
+ if (i + 1 < runs.length) {
246
+ contentTexts.push(
247
+ (i + 2 === runs.length
248
+ ? `Entry ${runs.length} was NOT applied`
249
+ : `Entries ${i + 2}-${runs.length} were NOT applied`) +
250
+ `; re-read the file and re-issue only the failed and unapplied entries.`,
251
+ );
252
+ }
242
253
  errorCount++;
254
+ // Stop at the first failure: later entries were authored against
255
+ // line numbers/content that assumed this entry succeeded, and
256
+ // applying them after a failure compounds the damage.
257
+ break;
243
258
  }
244
259
 
245
260
  if (!isLast && onUpdate) {
@@ -40,6 +40,7 @@ import {
40
40
  countLeadingWhitespace,
41
41
  detectLineEnding,
42
42
  getLeadingWhitespace,
43
+ normalizeForFuzzy,
43
44
  normalizeToLF,
44
45
  restoreLineEndings,
45
46
  stripBom,
@@ -1007,6 +1008,41 @@ async function readExistingPatchFile(fileSystem: FileSystem, absolutePath: strin
1007
1008
  }
1008
1009
  }
1009
1010
 
1011
+ /**
1012
+ * A prefix/substring strategy matched pattern lines that cover only part of
1013
+ * the corresponding file lines; replacing whole lines would silently drop the
1014
+ * uncovered text the model never saw. Allow the replacement only when every
1015
+ * discarded piece (normalized) survives somewhere in the hunk's new lines.
1016
+ */
1017
+ function assertPartialMatchPreservesDiscardedText(
1018
+ path: string,
1019
+ pattern: string[],
1020
+ matchedLines: string[],
1021
+ newLines: string[],
1022
+ matchStartIndex: number,
1023
+ ): void {
1024
+ let newLinesNorm: string | undefined;
1025
+ for (let j = 0; j < pattern.length; j++) {
1026
+ const lineNorm = normalizeForFuzzy(matchedLines[j]);
1027
+ const patternNorm = normalizeForFuzzy(pattern[j]);
1028
+ if (lineNorm === patternNorm) continue;
1029
+ const at = lineNorm.indexOf(patternNorm);
1030
+ if (at === -1) continue;
1031
+ const discardedParts = [lineNorm.slice(0, at).trim(), lineNorm.slice(at + patternNorm.length).trim()];
1032
+ for (const part of discardedParts) {
1033
+ if (part.length === 0) continue;
1034
+ newLinesNorm ??= newLines.map(normalizeForFuzzy).join("\n");
1035
+ if (!newLinesNorm.includes(part)) {
1036
+ throw new ApplyPatchError(
1037
+ `Refusing partial-line match in ${path} at line ${matchStartIndex + j + 1}: ` +
1038
+ `the file line also contains ${JSON.stringify(part)}, which the replacement would silently drop. ` +
1039
+ `Provide the complete line in the hunk.`,
1040
+ );
1041
+ }
1042
+ }
1043
+ }
1044
+ }
1045
+
1010
1046
  /**
1011
1047
  * Compute replacements needed to transform originalLines using the diff hunks.
1012
1048
  */
@@ -1253,6 +1289,18 @@ function computeReplacements(
1253
1289
  if (searchResult.strategy === "fuzzy-dominant") {
1254
1290
  const similarity = Math.round(searchResult.confidence * 100);
1255
1291
  warnings.push(`Dominant fuzzy match selected in ${path} near line ${found + 1} (${similarity}% similar).`);
1292
+ } else if (
1293
+ searchResult.strategy === "comment-prefix" ||
1294
+ searchResult.strategy === "prefix" ||
1295
+ searchResult.strategy === "substring" ||
1296
+ searchResult.strategy === "fuzzy" ||
1297
+ searchResult.strategy === "character"
1298
+ ) {
1299
+ const similarity = Math.round(searchResult.confidence * 100);
1300
+ warnings.push(
1301
+ `Inexact match in ${path} near line ${found + 1}: matched via ${searchResult.strategy} strategy ` +
1302
+ `(${similarity}% similar). Re-read the file if the result is not what you intended.`,
1303
+ );
1256
1304
  }
1257
1305
 
1258
1306
  // Reject if match is ambiguous (prefix/substring matching found multiple matches)
@@ -1305,6 +1353,10 @@ function computeReplacements(
1305
1353
  continue;
1306
1354
  }
1307
1355
 
1356
+ if (searchResult.strategy === "prefix" || searchResult.strategy === "substring") {
1357
+ assertPartialMatchPreservesDiscardedText(path, pattern, actualMatchedLines, newSlice, found);
1358
+ }
1359
+
1308
1360
  const adjustedNewLines = adjustLinesIndentation(pattern, actualMatchedLines, newSlice);
1309
1361
  replacements.push({ startIndex: found, oldLen: pattern.length, newLines: adjustedNewLines });
1310
1362
  lineIndex = found + pattern.length;
@@ -525,29 +525,45 @@ function matchesAt(lines: string[], pattern: string[], i: number, compare: (a: s
525
525
  return true;
526
526
  }
527
527
 
528
- /** Compute average similarity score for pattern at position */
529
- function fuzzyScoreAt(lines: string[], pattern: string[], i: number): number {
528
+ /**
529
+ * Compute average similarity score for pre-normalized pattern lines at
530
+ * position `i` of pre-normalized file lines.
531
+ *
532
+ * `minScore` is a bail threshold: when even perfect similarity on the
533
+ * remaining lines cannot lift the average to `minScore`, returns the partial
534
+ * average early (always ≤ the true score). The length-difference lower bound
535
+ * on Levenshtein distance is used to skip the DP entirely for line pairs the
536
+ * bail test already rules out.
537
+ */
538
+ function fuzzyScoreAt(linesNorm: string[], patternNorm: string[], i: number, minScore = 0): number {
539
+ const count = patternNorm.length;
530
540
  let totalScore = 0;
531
- for (let j = 0; j < pattern.length; j++) {
532
- const lineNorm = normalizeForFuzzy(lines[i + j]);
533
- const patternNorm = normalizeForFuzzy(pattern[j]);
534
- totalScore += similarity(lineNorm, patternNorm);
541
+ for (let j = 0; j < count; j++) {
542
+ const lineNorm = linesNorm[i + j];
543
+ const patNorm = patternNorm[j];
544
+ if (lineNorm === patNorm) {
545
+ totalScore += 1;
546
+ continue;
547
+ }
548
+ const remaining = count - j - 1;
549
+ const maxLen = Math.max(lineNorm.length, patNorm.length);
550
+ // similarity ≤ 1 − |lenA−lenB|/maxLen: test the bound before the DP.
551
+ const upperBound = 1 - Math.abs(lineNorm.length - patNorm.length) / maxLen;
552
+ if ((totalScore + upperBound + remaining) / count < minScore) return totalScore / count;
553
+ if (upperBound > 0) totalScore += similarity(lineNorm, patNorm);
554
+ if ((totalScore + remaining) / count < minScore) return totalScore / count;
535
555
  }
536
- return totalScore / pattern.length;
556
+ return totalScore / count;
537
557
  }
538
558
 
539
- /** Check if line starts with pattern (normalized) */
540
- function lineStartsWithPattern(line: string, pattern: string): boolean {
541
- const lineNorm = normalizeForFuzzy(line);
542
- const patternNorm = normalizeForFuzzy(pattern);
559
+ /** Check if pre-normalized line starts with pre-normalized pattern */
560
+ function normStartsWith(lineNorm: string, patternNorm: string): boolean {
543
561
  if (patternNorm.length === 0) return lineNorm.length === 0;
544
562
  return lineNorm.startsWith(patternNorm);
545
563
  }
546
564
 
547
- /** Check if line contains pattern as significant substring */
548
- function lineIncludesPattern(line: string, pattern: string): boolean {
549
- const lineNorm = normalizeForFuzzy(line);
550
- const patternNorm = normalizeForFuzzy(pattern);
565
+ /** Check if pre-normalized line contains pre-normalized pattern as significant substring */
566
+ function normIncludes(lineNorm: string, patternNorm: string): boolean {
551
567
  if (patternNorm.length === 0) return lineNorm.length === 0;
552
568
  if (patternNorm.length < PARTIAL_MATCH_MIN_LENGTH) return false;
553
569
  if (!lineNorm.includes(patternNorm)) return false;
@@ -613,6 +629,13 @@ export function seekSequence(
613
629
  const searchStart = eof && lines.length >= pattern.length ? lines.length - pattern.length : start;
614
630
  const maxStart = lines.length - pattern.length;
615
631
 
632
+ // Fuzzy and partial passes compare normalizeForFuzzy forms; normalize the
633
+ // file and pattern once per call instead of once per candidate position.
634
+ let linesNormCache: string[] | undefined;
635
+ let patternNormCache: string[] | undefined;
636
+ const getLinesNorm = () => (linesNormCache ??= lines.map(normalizeForFuzzy));
637
+ const getPatternNorm = () => (patternNormCache ??= pattern.map(normalizeForFuzzy));
638
+
616
639
  const runExactPasses = (from: number, to: number): SequenceSearchResult | undefined => {
617
640
  const comparisonPasses: Array<{
618
641
  compare: (a: string, b: string) => boolean;
@@ -646,17 +669,19 @@ export function seekSequence(
646
669
  return undefined;
647
670
  }
648
671
 
672
+ const linesNorm = getLinesNorm();
673
+ const patternNorm = getPatternNorm();
649
674
  const partialPasses: Array<{
650
- compare: (line: string, patternLine: string) => boolean;
675
+ compare: (lineNorm: string, patternLineNorm: string) => boolean;
651
676
  confidence: number;
652
677
  strategy: SequenceMatchStrategy;
653
678
  }> = [
654
- { compare: lineStartsWithPattern, confidence: 0.965, strategy: "prefix" },
655
- { compare: lineIncludesPattern, confidence: 0.94, strategy: "substring" },
679
+ { compare: normStartsWith, confidence: 0.965, strategy: "prefix" },
680
+ { compare: normIncludes, confidence: 0.94, strategy: "substring" },
656
681
  ];
657
682
 
658
683
  for (const pass of partialPasses) {
659
- const matches = collectIndexedMatches(from, to, i => matchesAt(lines, pattern, i, pass.compare));
684
+ const matches = collectIndexedMatches(from, to, i => matchesAt(linesNorm, patternNorm, i, pass.compare));
660
685
  const result = toAmbiguousMatchResult(matches, pass.confidence, pass.strategy);
661
686
  if (result) {
662
687
  return result;
@@ -692,9 +717,14 @@ export function seekSequence(
692
717
  matchIndices: [],
693
718
  };
694
719
 
720
+ const fuzzyLinesNorm = getLinesNorm();
721
+ const fuzzyPatternNorm = getPatternNorm();
722
+ // Positions scoring below this can neither become a fuzzy match nor affect
723
+ // the dominant-fuzzy gap test; let fuzzyScoreAt bail early on them.
724
+ const fuzzyBail = SEQUENCE_FUZZY_THRESHOLD - DOMINANT_FUZZY_DELTA;
695
725
  const scoreFuzzyRange = (from: number, to: number): void => {
696
726
  for (let i = from; i <= to; i++) {
697
- const score = fuzzyScoreAt(lines, pattern, i);
727
+ const score = fuzzyScoreAt(fuzzyLinesNorm, fuzzyPatternNorm, i, fuzzyBail);
698
728
  if (score >= SEQUENCE_FUZZY_THRESHOLD) {
699
729
  if (fuzzyMatches.firstMatch === undefined) {
700
730
  fuzzyMatches.firstMatch = i;
@@ -787,12 +817,16 @@ export function findClosestSequenceMatch(
787
817
  const eof = options?.eof ?? false;
788
818
  const maxStart = lines.length - pattern.length;
789
819
  const searchStart = eof && lines.length >= pattern.length ? maxStart : start;
820
+ const linesNorm = lines.map(normalizeForFuzzy);
821
+ const patternNorm = pattern.map(normalizeForFuzzy);
790
822
 
791
823
  let bestIndex: number | undefined;
792
824
  let bestScore = 0;
793
825
 
826
+ // Passing the running best as the bail threshold is exact: a bailed
827
+ // position returns a value strictly below it, so it can never win.
794
828
  for (let i = searchStart; i <= maxStart; i++) {
795
- const score = fuzzyScoreAt(lines, pattern, i);
829
+ const score = fuzzyScoreAt(linesNorm, patternNorm, i, bestScore);
796
830
  if (score > bestScore) {
797
831
  bestScore = score;
798
832
  bestIndex = i;
@@ -801,7 +835,7 @@ export function findClosestSequenceMatch(
801
835
 
802
836
  if (eof && searchStart > start) {
803
837
  for (let i = start; i < searchStart; i++) {
804
- const score = fuzzyScoreAt(lines, pattern, i);
838
+ const score = fuzzyScoreAt(linesNorm, patternNorm, i, bestScore);
805
839
  if (score > bestScore) {
806
840
  bestScore = score;
807
841
  bestIndex = i;
@@ -21,6 +21,26 @@ export interface NotebookDocument {
21
21
  }
22
22
 
23
23
  const CELL_MARKER_RE = /^# %% \[(code|markdown|raw)\](?: cell:(\d+))?$/;
24
+ /**
25
+ * Cell source lines that would themselves parse as (possibly already-escaped)
26
+ * cell markers gain one extra `%` on render and lose it on parse, so a
27
+ * notebook that *contains* the literal text `# %% [markdown] cell:3` survives
28
+ * the editable-text round trip instead of being split into extra cells.
29
+ */
30
+ const ESCAPABLE_MARKER_RE = /^# %%+ \[(?:code|markdown|raw)\](?: cell:\d+)?$/;
31
+ const ESCAPED_MARKER_RE = /^# %%%+ \[(?:code|markdown|raw)\](?: cell:\d+)?$/;
32
+
33
+ function escapeMarkerLikeSourceLines(source: string): string {
34
+ if (!source.includes("# %%")) return source;
35
+ return source
36
+ .split("\n")
37
+ .map(line => (ESCAPABLE_MARKER_RE.test(line) ? line.replace("# %", "# %%") : line))
38
+ .join("\n");
39
+ }
40
+
41
+ function unescapeMarkerLikeLine(line: string): string {
42
+ return ESCAPED_MARKER_RE.test(line) ? line.replace("# %%", "# %") : line;
43
+ }
24
44
 
25
45
  export function isNotebookPath(filePath: string): boolean {
26
46
  return path.extname(filePath).toLowerCase() === ".ipynb";
@@ -100,7 +120,7 @@ export async function readNotebookDocument(absolutePath: string, displayPath: st
100
120
  export function notebookToEditableText(notebook: NotebookDocument): string {
101
121
  return notebook.cells
102
122
  .map((cell, index) => {
103
- const source = sourceToText(cell.source);
123
+ const source = escapeMarkerLikeSourceLines(sourceToText(cell.source));
104
124
  return source.length > 0
105
125
  ? `# %% [${cell.cell_type}] cell:${index}\n${source}`
106
126
  : `# %% [${cell.cell_type}] cell:${index}`;
@@ -156,7 +176,7 @@ function parseNotebookEditableText(text: string, displayPath: string): ParsedVir
156
176
  `Invalid notebook editable representation for ${displayPath}: expected first line to be "# %% [code] cell:0", "# %% [markdown] cell:0", or "# %% [raw] cell:0".`,
157
177
  );
158
178
  }
159
- current.lines.push(line);
179
+ current.lines.push(unescapeMarkerLikeLine(line));
160
180
  }
161
181
  flush();
162
182
  return cells;
@@ -261,7 +261,6 @@ function renderEditHeader(
261
261
  options: {
262
262
  icon: "pending" | "success" | "error";
263
263
  iconOverride?: string;
264
- spinnerFrame?: number;
265
264
  op?: Operation;
266
265
  rawPath: string;
267
266
  rename?: string;
@@ -284,7 +283,6 @@ function renderEditHeader(
284
283
  {
285
284
  icon: options.icon,
286
285
  iconOverride: options.iconOverride,
287
- spinnerFrame: options.spinnerFrame,
288
286
  title,
289
287
  description,
290
288
  },
@@ -322,6 +320,7 @@ function formatStreamingDiff(
322
320
  uiTheme: Theme,
323
321
  expanded: boolean,
324
322
  label = "streaming",
323
+ spinnerFrame?: number,
325
324
  ): string {
326
325
  if (!diff) return "";
327
326
  // Collapsed uses a "Cursor" tail window: pin the last
@@ -342,11 +341,26 @@ function formatStreamingDiff(
342
341
  text += `${uiTheme.fg("dim", `… (${remainder.join(", ")} above)`)}\n`;
343
342
  }
344
343
  text += renderDiffColored(visible.join("\n"), { filePath: rawPath });
345
- if (!expanded || label !== "preview") text += uiTheme.fg("dim", `\n(${label})`);
344
+ // The animated glyph rides this trailing line inside the transcript's
345
+ // volatile-tail holdback — never the block header: an animating head row
346
+ // pins the native-scrollback commit boundary at the top of the block, so a
347
+ // tall expanded preview could never scroll-append mid-stream.
348
+ const spinner = spinnerFrame !== undefined ? `${formatStatusIcon("running", uiTheme, spinnerFrame)} ` : "";
349
+ // Expanded approval previews hide the "(preview)" label (#1992) but keep
350
+ // the animated glyph when one is active so the volatile tail stays live.
351
+ const hideLabel = expanded && label === "preview";
352
+ if (spinner || !hideLabel) {
353
+ text += `\n${hideLabel ? spinner.trimEnd() : `${spinner}${uiTheme.fg("dim", `(${label})`)}`}`;
354
+ }
346
355
  return text;
347
356
  }
348
357
 
349
- function formatMultiFileStreamingDiff(previews: PerFileDiffPreview[], uiTheme: Theme, expanded: boolean): string {
358
+ function formatMultiFileStreamingDiff(
359
+ previews: PerFileDiffPreview[],
360
+ uiTheme: Theme,
361
+ expanded: boolean,
362
+ spinnerFrame?: number,
363
+ ): string {
350
364
  const parts: string[] = [];
351
365
  for (const preview of previews) {
352
366
  if (!preview.diff && !preview.error) continue;
@@ -356,7 +370,13 @@ function formatMultiFileStreamingDiff(previews: PerFileDiffPreview[], uiTheme: T
356
370
  continue;
357
371
  }
358
372
  if (preview.diff) {
359
- parts.push(`${header}${formatStreamingDiff(preview.diff, preview.path, uiTheme, expanded, "preview")}`);
373
+ // Only the last file's preview carries the animated streaming glyph;
374
+ // earlier files have settled and must stay byte-stable so their rows
375
+ // can commit to native scrollback mid-stream.
376
+ const isLast = preview === previews[previews.length - 1];
377
+ parts.push(
378
+ `${header}${formatStreamingDiff(preview.diff, preview.path, uiTheme, expanded, "preview", isLast ? spinnerFrame : undefined)}`,
379
+ );
360
380
  }
361
381
  }
362
382
  return parts.join("");
@@ -368,16 +388,17 @@ function getCallPreview(
368
388
  uiTheme: Theme,
369
389
  renderContext: EditRenderContext | undefined,
370
390
  expanded: boolean,
391
+ spinnerFrame?: number,
371
392
  ): string {
372
393
  const multi = renderContext?.perFileDiffPreview;
373
394
  if (multi && multi.length > 1 && multi.some(p => p.diff || p.error)) {
374
- return formatMultiFileStreamingDiff(multi, uiTheme, expanded);
395
+ return formatMultiFileStreamingDiff(multi, uiTheme, expanded, spinnerFrame);
375
396
  }
376
397
  if (args.previewDiff) {
377
- return formatStreamingDiff(args.previewDiff, rawPath, uiTheme, expanded, "preview");
398
+ return formatStreamingDiff(args.previewDiff, rawPath, uiTheme, expanded, "preview", spinnerFrame);
378
399
  }
379
400
  if (args.diff && args.op) {
380
- return formatStreamingDiff(args.diff, rawPath, uiTheme, expanded);
401
+ return formatStreamingDiff(args.diff, rawPath, uiTheme, expanded, "streaming", spinnerFrame);
381
402
  }
382
403
  if (args.diff) {
383
404
  return renderPlainTextPreview(args.diff, uiTheme, rawPath);
@@ -554,15 +575,20 @@ export const editToolRenderer = {
554
575
  fileCount = countEditFiles(editArgs.edits);
555
576
  }
556
577
  return framedBlock(uiTheme, width => {
578
+ // Static pending icon, never the animated glyph: the header is the
579
+ // head row of the framed block, and native-scrollback commits are
580
+ // prefix-only — an animating head row would pin the commit boundary
581
+ // at the top and keep a tall expanded preview from scroll-appending
582
+ // mid-stream. The liveness cue rides the trailing "(preview)" /
583
+ // "(streaming)" line instead.
557
584
  const header = renderEditHeader(width, uiTheme, {
558
585
  icon: "pending",
559
- spinnerFrame: options?.spinnerFrame,
560
586
  op,
561
587
  rawPath,
562
588
  rename,
563
589
  extraSuffix: fileCount > 1 ? uiTheme.fg("dim", ` (+${fileCount - 1} more)`) : undefined,
564
590
  });
565
- let body = getCallPreview(editArgs, rawPath, uiTheme, renderContext, options.expanded);
591
+ let body = getCallPreview(editArgs, rawPath, uiTheme, renderContext, options.expanded, options?.spinnerFrame);
566
592
  if (applyPatchSummary?.error) {
567
593
  body += `\n${uiTheme.fg("error", truncateToWidth(replaceTabs(applyPatchSummary.error, rawPath), Math.max(1, width - 2)))}`;
568
594
  }
@@ -38,7 +38,7 @@ const SLOW = makeModel("p", "slow");
38
38
  const REASONING_SLOW = makeModel("p", "slow", {
39
39
  api: "anthropic-messages",
40
40
  reasoning: true,
41
- thinking: { minLevel: Effort.Low, maxLevel: Effort.High, mode: "anthropic-adaptive" },
41
+ thinking: { efforts: [Effort.Low, Effort.Medium, Effort.High], mode: "anthropic-adaptive" },
42
42
  });
43
43
 
44
44
  interface SessionOptions {
@@ -20,8 +20,6 @@ export interface ExecutorBackendExecOptions {
20
20
  */
21
21
  idleTimeoutMs: number;
22
22
  reset: boolean;
23
- artifactPath: string | undefined;
24
- artifactId: string | undefined;
25
23
  onChunk: (chunk: string) => void;
26
24
  /**
27
25
  * Live status events (read/write/agent/…) delivered as they are emitted,
@@ -12,7 +12,8 @@
12
12
  * in, text (or, with `schema`, a structured object) out.
13
13
  */
14
14
  import { instrumentedCompleteSimple, resolveTelemetry } from "@oh-my-pi/pi-agent-core";
15
- import { type Api, Effort, getSupportedEfforts, type Model, type Tool } from "@oh-my-pi/pi-ai";
15
+ import { type Api, Effort, type Model, type Tool } from "@oh-my-pi/pi-ai";
16
+ import { getSupportedEfforts } from "@oh-my-pi/pi-catalog/model-thinking";
16
17
  import * as z from "zod/v4";
17
18
  import { extractTextContent, extractToolCall, parseJsonPayload } from "../commit/utils";
18
19
 
@@ -6,8 +6,6 @@
6
6
  * `agent()`/`parallel()`/`completion()` work is ignored completely, then {@link resume}
7
7
  * starts a fresh timeout window once the runtime gets control back.
8
8
  *
9
- * The active timer self-reschedules instead of being torn down on every
10
- * activity event, so frequent activity costs one timestamp write per event.
11
9
  * Pause is reference-counted because `parallel()` can have multiple bridge calls
12
10
  * in flight at once.
13
11
  */
@@ -36,11 +34,6 @@ export class IdleTimeout {
36
34
  return this.#idleMs;
37
35
  }
38
36
 
39
- /** Record runtime activity, pushing the active deadline forward by `idleMs`. */
40
- bump(): void {
41
- if (this.#settled || this.#pauseDepth > 0) return;
42
- this.#deadlineMs = Date.now() + this.#idleMs;
43
- }
44
37
  /** Suspend timeout accounting while control is delegated to host-side work. */
45
38
  pause(): void {
46
39
  if (this.#settled) return;
@@ -86,8 +79,8 @@ export class IdleTimeout {
86
79
  if (this.#settled || this.#pauseDepth > 0) return;
87
80
  const remainingMs = this.#deadlineMs - Date.now();
88
81
  if (remainingMs > 0) {
89
- // A bump moved the deadline forward after this timer was armed; wait
90
- // out the remaining window instead of firing early.
82
+ // The deadline moved forward (resume re-arming) after this timer was
83
+ // armed; wait out the remaining window instead of firing early.
91
84
  this.#arm(remainingMs);
92
85
  return;
93
86
  }
@@ -1,13 +1,10 @@
1
- import { isCompiledBinary, logger, Snowflake } from "@oh-my-pi/pi-utils";
1
+ import { logger, Snowflake, workerHostEntry } from "@oh-my-pi/pi-utils";
2
2
  import type { ToolSession } from "../../tools";
3
3
  import { ToolAbortError, ToolError } from "../../tools/tool-errors";
4
4
  import { callSessionTool, type JsStatusEvent } from "./tool-bridge";
5
5
  import { WorkerCore } from "./worker-core";
6
- // Worker entry. See `tab-supervisor.ts` for the rationale behind the
7
- // literal-string + `new URL(import.meta.url)` hybrid: the literal is what
8
- // Bun's `--compile` bundler discovers, the `new URL` form is what makes dev
9
- // runs portable across cwds. The worker is registered as an additional
10
- // `--compile` entrypoint in `scripts/build-binary.ts`.
6
+ // Coding-agent binary/bundle workers route through the CLI entrypoint with a
7
+ // hidden argv mode, so compiled/npm builds only need one JavaScript entry.
11
8
  import type {
12
9
  JsDisplayOutput,
13
10
  RunErrorPayload,
@@ -384,8 +381,9 @@ async function raceWithTimeout<T>(promise: Promise<T>, timeoutMs: number, reason
384
381
 
385
382
  async function spawnJsWorker(): Promise<WorkerHandle> {
386
383
  try {
387
- const worker = isCompiledBinary()
388
- ? new Worker("./packages/coding-agent/src/eval/js/worker-entry.ts", { type: "module" })
384
+ const hostEntry = workerHostEntry();
385
+ const worker = hostEntry
386
+ ? new Worker(hostEntry, { type: "module", argv: ["__omp_js_eval_worker"] })
389
387
  : new Worker(new URL("./worker-entry.ts", import.meta.url).href, { type: "module" });
390
388
  return wrapBunWorker(worker);
391
389
  } catch (err) {
@@ -63,9 +63,13 @@ function isTimeoutReason(reason: unknown): boolean {
63
63
  }
64
64
 
65
65
  function formatJsTimeoutAnnotation(timeoutMs: number | undefined): string {
66
- if (timeoutMs === undefined) return "Command timed out";
66
+ // Timeout cancellation force-kills the worker (the only way to interrupt
67
+ // synchronous user code), which discards the persistent VM state. Say so,
68
+ // or the model will keep referencing variables that no longer exist.
69
+ const reset = "The JS worker was force-killed and its VM state was reset; variables from earlier cells are gone.";
70
+ if (timeoutMs === undefined) return `Command timed out. ${reset}`;
67
71
  const secs = Math.max(1, Math.round(timeoutMs / 1000));
68
- return `Command timed out after ${secs} seconds`;
72
+ return `Command timed out after ${secs} seconds. ${reset}`;
69
73
  }
70
74
 
71
75
  export async function executeJs(code: string, options: JsExecutorOptions): Promise<JsResult> {
@@ -30,8 +30,6 @@ export default {
30
30
  sessionId: namespaceSessionId(opts.sessionId),
31
31
  sessionFile: opts.sessionFile,
32
32
  reset: opts.reset,
33
- artifactPath: opts.artifactPath,
34
- artifactId: opts.artifactId,
35
33
  onChunk: opts.onChunk,
36
34
  onStatus: opts.onStatus,
37
35
  session: opts.session,
@@ -83,12 +83,11 @@ export function createHelpers(ctx: HelperContext): HelperBundle {
83
83
  },
84
84
  append: async (rawPath, content) => {
85
85
  const target = resolveHelperPath(ctx, rawPath, "write");
86
- await Bun.write(
87
- target,
88
- `${await Bun.file(target)
89
- .text()
90
- .catch(() => "")}${content}`,
91
- );
86
+ // O(1) append; read-all+rewrite both raced concurrent writers and went
87
+ // quadratic when called in a loop. Bun.write creates parent dirs, so
88
+ // keep that behavior for the append path too.
89
+ await fs.promises.mkdir(path.dirname(target), { recursive: true });
90
+ await fs.promises.appendFile(target, content, "utf-8");
92
91
  ctx.emitStatus({
93
92
  op: "append",
94
93
  path: target,
@@ -102,7 +102,7 @@ export class LocalModuleLoader {
102
102
  });
103
103
  const moduleDir = path.dirname(modulePath);
104
104
  const localDeps = new Set<string>();
105
- for (const specifier of collectModuleSourceSpecifiers(stripped)) {
105
+ for (const specifier of await collectModuleSourceSpecifiers(stripped)) {
106
106
  const resolved = resolveImportSpecifier(moduleDir, specifier);
107
107
  if (isLocalPathSpecifier(specifier) && isManagedLocalModulePath(resolved)) {
108
108
  localDeps.add(resolved);