@oh-my-pi/pi-coding-agent 15.9.67 → 15.10.1

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 (266) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/dist/types/cli/args.d.ts +1 -1
  3. package/dist/types/cli/dry-balance-cli.d.ts +15 -1
  4. package/dist/types/cli/gallery-cli.d.ts +43 -0
  5. package/dist/types/cli/gallery-fixtures/agentic.d.ts +2 -0
  6. package/dist/types/cli/gallery-fixtures/codeintel.d.ts +3 -0
  7. package/dist/types/cli/gallery-fixtures/edit.d.ts +3 -0
  8. package/dist/types/cli/gallery-fixtures/fs.d.ts +2 -0
  9. package/dist/types/cli/gallery-fixtures/index.d.ts +4 -0
  10. package/dist/types/cli/gallery-fixtures/interaction.d.ts +3 -0
  11. package/dist/types/cli/gallery-fixtures/memory.d.ts +2 -0
  12. package/dist/types/cli/gallery-fixtures/misc.d.ts +3 -0
  13. package/dist/types/cli/gallery-fixtures/search.d.ts +3 -0
  14. package/dist/types/cli/gallery-fixtures/shell.d.ts +3 -0
  15. package/dist/types/cli/gallery-fixtures/types.d.ts +44 -0
  16. package/dist/types/cli/gallery-fixtures/web.d.ts +2 -0
  17. package/dist/types/cli/gallery-screenshot.d.ts +35 -0
  18. package/dist/types/commands/gallery.d.ts +47 -0
  19. package/dist/types/commit/analysis/conventional.d.ts +2 -2
  20. package/dist/types/commit/analysis/summary.d.ts +2 -2
  21. package/dist/types/commit/changelog/generate.d.ts +2 -2
  22. package/dist/types/commit/changelog/index.d.ts +2 -2
  23. package/dist/types/commit/map-reduce/index.d.ts +3 -3
  24. package/dist/types/commit/map-reduce/map-phase.d.ts +2 -2
  25. package/dist/types/commit/map-reduce/reduce-phase.d.ts +2 -2
  26. package/dist/types/commit/model-selection.d.ts +10 -4
  27. package/dist/types/config/api-key-resolver.d.ts +34 -0
  28. package/dist/types/config/keybindings.d.ts +6 -1
  29. package/dist/types/config/model-id-affixes.d.ts +2 -0
  30. package/dist/types/config/model-registry.d.ts +25 -2
  31. package/dist/types/config/settings-schema.d.ts +41 -6
  32. package/dist/types/dap/config.d.ts +14 -1
  33. package/dist/types/dap/types.d.ts +10 -0
  34. package/dist/types/extensibility/plugins/marketplace-auto-update.d.ts +8 -0
  35. package/dist/types/lsp/types.d.ts +10 -0
  36. package/dist/types/lsp/utils.d.ts +3 -2
  37. package/dist/types/main.d.ts +3 -2
  38. package/dist/types/memory-backend/index.d.ts +2 -1
  39. package/dist/types/memory-backend/resolve.d.ts +1 -1
  40. package/dist/types/memory-backend/types.d.ts +1 -1
  41. package/dist/types/modes/components/chat-block.d.ts +64 -0
  42. package/dist/types/modes/components/custom-editor.d.ts +5 -1
  43. package/dist/types/modes/components/overlay-box.d.ts +17 -0
  44. package/dist/types/modes/components/plan-review-overlay.d.ts +59 -0
  45. package/dist/types/modes/components/plan-toc.d.ts +41 -0
  46. package/dist/types/modes/components/read-tool-group.d.ts +2 -0
  47. package/dist/types/modes/components/tool-execution.d.ts +18 -0
  48. package/dist/types/modes/components/transcript-container.d.ts +11 -0
  49. package/dist/types/modes/controllers/command-controller.d.ts +1 -0
  50. package/dist/types/modes/controllers/event-controller.d.ts +0 -1
  51. package/dist/types/modes/controllers/extension-ui-controller.d.ts +0 -1
  52. package/dist/types/modes/controllers/input-controller.d.ts +1 -1
  53. package/dist/types/modes/controllers/selector-controller.d.ts +1 -1
  54. package/dist/types/modes/controllers/streaming-reveal.d.ts +22 -0
  55. package/dist/types/modes/controllers/tan-command-controller.d.ts +6 -0
  56. package/dist/types/modes/index.d.ts +5 -4
  57. package/dist/types/modes/interactive-mode.d.ts +16 -6
  58. package/dist/types/modes/setup-version.d.ts +11 -0
  59. package/dist/types/modes/setup-wizard/index.d.ts +2 -1
  60. package/dist/types/modes/setup-wizard/scenes/web-search.d.ts +2 -1
  61. package/dist/types/modes/theme/theme.d.ts +1 -1
  62. package/dist/types/modes/types.d.ts +19 -6
  63. package/dist/types/modes/utils/copy-targets.d.ts +21 -1
  64. package/dist/types/plan-mode/approved-plan.d.ts +27 -8
  65. package/dist/types/plan-mode/plan-protection.d.ts +4 -4
  66. package/dist/types/sdk.d.ts +3 -1
  67. package/dist/types/session/agent-session.d.ts +21 -0
  68. package/dist/types/session/messages.d.ts +12 -0
  69. package/dist/types/session/session-manager.d.ts +3 -1
  70. package/dist/types/slash-commands/types.d.ts +4 -6
  71. package/dist/types/task/executor.d.ts +14 -0
  72. package/dist/types/task/index.d.ts +1 -0
  73. package/dist/types/task/render.d.ts +3 -2
  74. package/dist/types/telemetry-export.d.ts +1 -1
  75. package/dist/types/tools/archive-reader.d.ts +5 -0
  76. package/dist/types/tools/ast-edit.d.ts +3 -0
  77. package/dist/types/tools/ast-grep.d.ts +3 -0
  78. package/dist/types/tools/bash.d.ts +1 -0
  79. package/dist/types/tools/eval-render.d.ts +1 -8
  80. package/dist/types/tools/fetch.d.ts +15 -7
  81. package/dist/types/tools/find.d.ts +8 -4
  82. package/dist/types/tools/grouped-file-output.d.ts +95 -12
  83. package/dist/types/tools/memory-render.d.ts +4 -1
  84. package/dist/types/tools/plan-mode-guard.d.ts +8 -9
  85. package/dist/types/tools/render-utils.d.ts +13 -9
  86. package/dist/types/tools/renderers.d.ts +16 -2
  87. package/dist/types/tools/search.d.ts +5 -1
  88. package/dist/types/tools/sqlite-reader.d.ts +1 -0
  89. package/dist/types/tools/todo.d.ts +3 -2
  90. package/dist/types/tools/write.d.ts +5 -0
  91. package/dist/types/tui/output-block.d.ts +16 -4
  92. package/dist/types/tui/status-line.d.ts +3 -0
  93. package/dist/types/utils/enhanced-paste.d.ts +20 -0
  94. package/dist/types/web/scrapers/github.d.ts +22 -0
  95. package/dist/types/web/search/providers/kimi.d.ts +1 -1
  96. package/dist/types/web/search/providers/perplexity.d.ts +8 -1
  97. package/dist/types/web/search/types.d.ts +1 -1
  98. package/package.json +9 -9
  99. package/scripts/dev-launch +42 -0
  100. package/scripts/dev-launch-preload.ts +19 -0
  101. package/src/auto-thinking/classifier.ts +5 -1
  102. package/src/cli/args.ts +2 -2
  103. package/src/cli/dry-balance-cli.ts +52 -17
  104. package/src/cli/gallery-cli.ts +226 -0
  105. package/src/cli/gallery-fixtures/agentic.ts +292 -0
  106. package/src/cli/gallery-fixtures/codeintel.ts +188 -0
  107. package/src/cli/gallery-fixtures/edit.ts +194 -0
  108. package/src/cli/gallery-fixtures/fs.ts +153 -0
  109. package/src/cli/gallery-fixtures/index.ts +40 -0
  110. package/src/cli/gallery-fixtures/interaction.ts +49 -0
  111. package/src/cli/gallery-fixtures/memory.ts +81 -0
  112. package/src/cli/gallery-fixtures/misc.ts +250 -0
  113. package/src/cli/gallery-fixtures/search.ts +213 -0
  114. package/src/cli/gallery-fixtures/shell.ts +167 -0
  115. package/src/cli/gallery-fixtures/types.ts +41 -0
  116. package/src/cli/gallery-fixtures/web.ts +158 -0
  117. package/src/cli/gallery-screenshot.ts +279 -0
  118. package/src/cli-commands.ts +1 -0
  119. package/src/commands/gallery.ts +52 -0
  120. package/src/commands/launch.ts +1 -1
  121. package/src/commit/analysis/conventional.ts +2 -2
  122. package/src/commit/analysis/summary.ts +2 -2
  123. package/src/commit/changelog/generate.ts +2 -2
  124. package/src/commit/changelog/index.ts +2 -2
  125. package/src/commit/map-reduce/index.ts +3 -3
  126. package/src/commit/map-reduce/map-phase.ts +2 -2
  127. package/src/commit/map-reduce/reduce-phase.ts +2 -2
  128. package/src/commit/model-selection.ts +33 -9
  129. package/src/commit/pipeline.ts +4 -4
  130. package/src/config/api-key-resolver.ts +58 -0
  131. package/src/config/keybindings.ts +15 -6
  132. package/src/config/model-equivalence.ts +35 -12
  133. package/src/config/model-id-affixes.ts +39 -22
  134. package/src/config/model-registry.ts +41 -18
  135. package/src/config/settings-schema.ts +28 -5
  136. package/src/config/settings.ts +31 -2
  137. package/src/dap/client.ts +14 -16
  138. package/src/dap/config.ts +41 -2
  139. package/src/dap/defaults.json +1 -0
  140. package/src/dap/session.ts +1 -0
  141. package/src/dap/types.ts +10 -0
  142. package/src/debug/index.ts +40 -54
  143. package/src/edit/renderer.ts +111 -119
  144. package/src/eval/__tests__/agent-bridge.test.ts +75 -32
  145. package/src/eval/__tests__/llm-bridge.test.ts +90 -31
  146. package/src/eval/agent-bridge.ts +34 -7
  147. package/src/eval/llm-bridge.ts +8 -3
  148. package/src/extensibility/extensions/runner.ts +1 -0
  149. package/src/extensibility/plugins/doctor.ts +0 -1
  150. package/src/extensibility/plugins/marketplace-auto-update.ts +49 -0
  151. package/src/goals/tools/goal-tool.ts +37 -27
  152. package/src/internal-urls/docs-index.generated.ts +10 -10
  153. package/src/lsp/client.ts +104 -55
  154. package/src/lsp/types.ts +10 -0
  155. package/src/lsp/utils.ts +3 -2
  156. package/src/main.ts +53 -56
  157. package/src/memories/index.ts +12 -5
  158. package/src/memory-backend/index.ts +13 -1
  159. package/src/memory-backend/resolve.ts +3 -5
  160. package/src/memory-backend/types.ts +1 -1
  161. package/src/mnemopi/backend.ts +5 -1
  162. package/src/modes/acp/acp-agent.ts +33 -26
  163. package/src/modes/components/assistant-message.ts +2 -9
  164. package/src/modes/components/chat-block.ts +111 -0
  165. package/src/modes/components/copy-selector.ts +1 -44
  166. package/src/modes/components/custom-editor.ts +33 -1
  167. package/src/modes/components/custom-message.ts +1 -3
  168. package/src/modes/components/execution-shared.ts +1 -2
  169. package/src/modes/components/hook-message.ts +1 -3
  170. package/src/modes/components/overlay-box.ts +108 -0
  171. package/src/modes/components/plan-review-overlay.ts +799 -0
  172. package/src/modes/components/plan-toc.ts +138 -0
  173. package/src/modes/components/read-tool-group.ts +20 -4
  174. package/src/modes/components/skill-message.ts +0 -1
  175. package/src/modes/components/status-line.ts +3 -5
  176. package/src/modes/components/tips.txt +1 -0
  177. package/src/modes/components/todo-reminder.ts +0 -2
  178. package/src/modes/components/tool-execution.ts +115 -90
  179. package/src/modes/components/transcript-container.ts +84 -24
  180. package/src/modes/components/user-message.ts +1 -2
  181. package/src/modes/controllers/command-controller-shared.ts +7 -6
  182. package/src/modes/controllers/command-controller.ts +70 -57
  183. package/src/modes/controllers/event-controller.ts +41 -40
  184. package/src/modes/controllers/extension-ui-controller.ts +10 -73
  185. package/src/modes/controllers/input-controller.ts +135 -122
  186. package/src/modes/controllers/mcp-command-controller.ts +69 -60
  187. package/src/modes/controllers/selector-controller.ts +25 -27
  188. package/src/modes/controllers/streaming-reveal.ts +212 -0
  189. package/src/modes/controllers/tan-command-controller.ts +173 -0
  190. package/src/modes/index.ts +5 -4
  191. package/src/modes/interactive-mode.ts +171 -82
  192. package/src/modes/setup-version.ts +11 -0
  193. package/src/modes/setup-wizard/index.ts +3 -2
  194. package/src/modes/setup-wizard/scenes/web-search.ts +3 -2
  195. package/src/modes/setup-wizard/wizard-overlay.ts +1 -1
  196. package/src/modes/theme/theme-schema.json +1 -1
  197. package/src/modes/theme/theme.ts +8 -4
  198. package/src/modes/types.ts +19 -8
  199. package/src/modes/utils/context-usage.ts +10 -6
  200. package/src/modes/utils/copy-targets.ts +133 -27
  201. package/src/modes/utils/hotkeys-markdown.ts +1 -0
  202. package/src/modes/utils/ui-helpers.ts +44 -46
  203. package/src/plan-mode/approved-plan.ts +66 -43
  204. package/src/plan-mode/plan-protection.ts +4 -4
  205. package/src/prompts/system/background-tan-dispatch.md +8 -0
  206. package/src/prompts/system/plan-mode-active.md +67 -58
  207. package/src/prompts/system/plan-mode-approved.md +1 -1
  208. package/src/sdk.ts +32 -60
  209. package/src/session/agent-session.ts +89 -13
  210. package/src/session/messages.ts +26 -0
  211. package/src/session/session-manager.ts +13 -5
  212. package/src/slash-commands/builtin-registry.ts +37 -10
  213. package/src/slash-commands/helpers/usage-report.ts +2 -0
  214. package/src/slash-commands/types.ts +4 -6
  215. package/src/task/executor.ts +25 -4
  216. package/src/task/index.ts +4 -0
  217. package/src/task/render.ts +212 -148
  218. package/src/telemetry-export.ts +25 -7
  219. package/src/tools/archive-reader.ts +64 -0
  220. package/src/tools/ask.ts +119 -164
  221. package/src/tools/ast-edit.ts +98 -71
  222. package/src/tools/ast-grep.ts +37 -43
  223. package/src/tools/bash.ts +50 -6
  224. package/src/tools/debug.ts +20 -8
  225. package/src/tools/eval-backends.ts +6 -17
  226. package/src/tools/eval-render.ts +21 -18
  227. package/src/tools/eval.ts +5 -4
  228. package/src/tools/fetch.ts +391 -91
  229. package/src/tools/find.ts +44 -30
  230. package/src/tools/gh-renderer.ts +81 -42
  231. package/src/tools/grouped-file-output.ts +272 -48
  232. package/src/tools/image-gen.ts +150 -103
  233. package/src/tools/inspect-image-renderer.ts +63 -41
  234. package/src/tools/inspect-image.ts +8 -1
  235. package/src/tools/job.ts +3 -4
  236. package/src/tools/memory-render.ts +4 -1
  237. package/src/tools/plan-mode-guard.ts +21 -39
  238. package/src/tools/read.ts +23 -16
  239. package/src/tools/render-utils.ts +38 -40
  240. package/src/tools/renderers.ts +16 -1
  241. package/src/tools/report-tool-issue.ts +1 -1
  242. package/src/tools/resolve.ts +14 -0
  243. package/src/tools/search-tool-bm25.ts +36 -23
  244. package/src/tools/search.ts +189 -95
  245. package/src/tools/sqlite-reader.ts +9 -12
  246. package/src/tools/todo.ts +138 -59
  247. package/src/tools/write.ts +100 -60
  248. package/src/tui/output-block.ts +60 -13
  249. package/src/tui/status-line.ts +5 -1
  250. package/src/utils/commit-message-generator.ts +9 -1
  251. package/src/utils/enhanced-paste.ts +202 -0
  252. package/src/utils/title-generator.ts +2 -1
  253. package/src/web/scrapers/github.ts +255 -3
  254. package/src/web/scrapers/youtube.ts +3 -2
  255. package/src/web/search/providers/anthropic.ts +25 -19
  256. package/src/web/search/providers/exa.ts +11 -3
  257. package/src/web/search/providers/kimi.ts +28 -17
  258. package/src/web/search/providers/parallel.ts +35 -24
  259. package/src/web/search/providers/perplexity.ts +199 -51
  260. package/src/web/search/providers/synthetic.ts +8 -6
  261. package/src/web/search/providers/tavily.ts +9 -8
  262. package/src/web/search/providers/zai.ts +8 -6
  263. package/src/web/search/render.ts +39 -54
  264. package/src/web/search/types.ts +5 -1
  265. package/dist/types/eval/__tests__/shared-executors.test.d.ts +0 -1
  266. package/src/eval/__tests__/shared-executors.test.ts +0 -609
package/src/lsp/client.ts CHANGED
@@ -174,49 +174,69 @@ const CLIENT_CAPABILITIES = {
174
174
  // LSP Message Protocol
175
175
  // =============================================================================
176
176
 
177
- /**
178
- * Parse a single LSP message from a buffer.
179
- * Returns the parsed message and remaining buffer, or null if incomplete.
180
- */
181
- function parseMessage(
182
- buffer: Buffer,
183
- ): { message: LspJsonRpcResponse | LspJsonRpcNotification; remaining: Buffer } | null {
184
- // Only decode enough to find the header
185
- const headerEndIndex = findHeaderEnd(buffer);
186
- if (headerEndIndex === -1) return null;
187
-
188
- const headerText = new TextDecoder().decode(buffer.slice(0, headerEndIndex));
189
- const contentLengthMatch = headerText.match(/Content-Length: (\d+)/i);
190
- if (!contentLengthMatch) return null;
191
-
192
- const contentLength = Number.parseInt(contentLengthMatch[1], 10);
193
- const messageStart = headerEndIndex + 4; // Skip \r\n\r\n
194
- const messageEnd = messageStart + contentLength;
195
-
196
- if (buffer.length < messageEnd) return null;
197
-
198
- const messageBytes = buffer.subarray(messageStart, messageEnd);
199
- const messageText = new TextDecoder().decode(messageBytes);
200
- const remaining = buffer.subarray(messageEnd);
201
-
202
- return {
203
- message: JSON.parse(messageText),
204
- remaining,
205
- };
206
- }
177
+ // Reused for all full (non-streaming) decodes; each decode() resets state, so a
178
+ // single instance is safe and avoids per-message TextDecoder allocation.
179
+ const MESSAGE_DECODER = new TextDecoder("utf-8");
207
180
 
208
181
  /**
209
- * Find the end of the header section (before \r\n\r\n)
182
+ * Locate the `\r\n\r\n` header terminator across the pending chunk list.
183
+ * Returns the absolute byte index of the first `\r`, or -1 when not present.
184
+ * Equivalent to scanning the contiguous concatenation of the chunks.
210
185
  */
211
- function findHeaderEnd(buffer: Uint8Array): number {
212
- for (let i = 0; i < buffer.length - 3; i++) {
213
- if (buffer[i] === 13 && buffer[i + 1] === 10 && buffer[i + 2] === 13 && buffer[i + 3] === 10) {
214
- return i;
186
+ function findHeaderEndInChunks(chunks: Buffer[]): number {
187
+ let global = 0;
188
+ let b0 = -1;
189
+ let b1 = -1;
190
+ let b2 = -1;
191
+ for (const chunk of chunks) {
192
+ for (let i = 0; i < chunk.length; i++) {
193
+ const b3 = chunk[i];
194
+ if (b0 === 13 && b1 === 10 && b2 === 13 && b3 === 10) {
195
+ return global - 3;
196
+ }
197
+ b0 = b1;
198
+ b1 = b2;
199
+ b2 = b3;
200
+ global++;
215
201
  }
216
202
  }
217
203
  return -1;
218
204
  }
219
205
 
206
+ /** Copy the byte range [from, to) out of the pending chunk list into one Buffer. */
207
+ function copyChunkRange(chunks: Buffer[], from: number, to: number): Buffer {
208
+ const out = Buffer.allocUnsafe(to - from);
209
+ let global = 0;
210
+ let written = 0;
211
+ for (const chunk of chunks) {
212
+ const chunkEnd = global + chunk.length;
213
+ if (chunkEnd > from && global < to) {
214
+ const start = Math.max(from, global) - global;
215
+ const end = Math.min(to, chunkEnd) - global;
216
+ chunk.copy(out, written, start, end);
217
+ written += end - start;
218
+ }
219
+ global = chunkEnd;
220
+ if (global >= to) break;
221
+ }
222
+ return out;
223
+ }
224
+
225
+ /** Drop the first `count` bytes from the pending chunk list in place. */
226
+ function dropChunkFront(chunks: Buffer[], count: number): void {
227
+ let removed = 0;
228
+ while (chunks.length > 0) {
229
+ const head = chunks[0];
230
+ if (removed + head.length <= count) {
231
+ removed += head.length;
232
+ chunks.shift();
233
+ } else {
234
+ chunks[0] = head.subarray(count - removed);
235
+ break;
236
+ }
237
+ }
238
+ }
239
+
220
240
  async function writeMessage(
221
241
  sink: Bun.FileSink,
222
242
  message: LspJsonRpcRequest | LspJsonRpcNotification | LspJsonRpcResponse,
@@ -249,22 +269,43 @@ async function startMessageReader(client: LspClient): Promise<void> {
249
269
 
250
270
  const reader = (client.proc.stdout as ReadableStream<Uint8Array>).getReader();
251
271
 
272
+ // Incoming bytes are buffered as a list of chunks and only joined when a full
273
+ // message is framed. Concatenating the accumulator on every read was O(n^2)
274
+ // for messages that span many reads (e.g. a large initial diagnostics burst).
275
+ const pendingChunks: Buffer[] = [];
276
+ let pendingLen = 0;
277
+ if (client.messageBuffer.length > 0) {
278
+ const seed = Buffer.from(client.messageBuffer);
279
+ pendingChunks.push(seed);
280
+ pendingLen = seed.length;
281
+ }
282
+
252
283
  try {
253
284
  while (true) {
254
285
  const { done, value } = await reader.read();
255
286
  if (done) break;
256
287
 
257
- // Atomically update buffer before processing
258
- const currentBuffer: Buffer = Buffer.concat([client.messageBuffer, value]);
259
- client.messageBuffer = currentBuffer;
288
+ pendingChunks.push(Buffer.from(value));
289
+ pendingLen += value.length;
260
290
 
261
- // Process all complete messages in buffer
262
- // Use local variable to avoid race with concurrent buffer updates
263
- let workingBuffer = currentBuffer;
264
- let parsed = parseMessage(workingBuffer);
265
- while (parsed) {
266
- const { message, remaining } = parsed;
267
- workingBuffer = remaining;
291
+ // Drain every complete message currently buffered.
292
+ while (true) {
293
+ const headerEnd = findHeaderEndInChunks(pendingChunks);
294
+ if (headerEnd === -1) break;
295
+
296
+ const headerText = MESSAGE_DECODER.decode(copyChunkRange(pendingChunks, 0, headerEnd));
297
+ const contentLengthMatch = headerText.match(/Content-Length: (\d+)/i);
298
+ if (!contentLengthMatch) break;
299
+
300
+ const contentLength = Number.parseInt(contentLengthMatch[1], 10);
301
+ const messageStart = headerEnd + 4; // Skip \r\n\r\n
302
+ const messageEnd = messageStart + contentLength;
303
+ if (pendingLen < messageEnd) break;
304
+
305
+ const messageText = MESSAGE_DECODER.decode(copyChunkRange(pendingChunks, messageStart, messageEnd));
306
+ const message: LspJsonRpcResponse | LspJsonRpcNotification = JSON.parse(messageText);
307
+ dropChunkFront(pendingChunks, messageEnd);
308
+ pendingLen -= messageEnd;
268
309
 
269
310
  // Route message
270
311
  if ("id" in message && message.id !== undefined) {
@@ -301,12 +342,7 @@ async function startMessageReader(client: LspClient): Promise<void> {
301
342
  }
302
343
  }
303
344
  }
304
-
305
- parsed = parseMessage(workingBuffer);
306
345
  }
307
-
308
- // Atomically commit processed buffer
309
- client.messageBuffer = workingBuffer;
310
346
  }
311
347
  } catch (err) {
312
348
  // Connection closed or error - reject all pending requests
@@ -315,6 +351,13 @@ async function startMessageReader(client: LspClient): Promise<void> {
315
351
  }
316
352
  client.pendingRequests.clear();
317
353
  } finally {
354
+ // Persist any unparsed remainder so a restarted reader resumes mid-message.
355
+ client.messageBuffer =
356
+ pendingChunks.length === 0
357
+ ? new Uint8Array(0)
358
+ : pendingChunks.length === 1
359
+ ? pendingChunks[0]
360
+ : Buffer.concat(pendingChunks, pendingLen);
318
361
  reader.releaseLock();
319
362
  client.isReading = false;
320
363
  }
@@ -438,6 +481,7 @@ export const WARMUP_TIMEOUT_MS = 5000;
438
481
  const RUST_ANALYZER_WORKSPACE_READY_TIMEOUT_MS = 5_000;
439
482
  const RUST_ANALYZER_WORKSPACE_READY_POLL_MS = 100;
440
483
  const RUST_ANALYZER_WORKSPACE_READY_SETTLE_MS = 2_000;
484
+ const RUST_ANALYZER_STATUS_REQUEST_TIMEOUT_MS = 1_000;
441
485
  const rustAnalyzerReadyClients = new WeakSet<LspClient>();
442
486
 
443
487
  function commandBasename(command: string): string {
@@ -462,29 +506,34 @@ async function waitForRustAnalyzerWorkspace(client: LspClient, signal?: AbortSig
462
506
  if (rustAnalyzerReadyClients.has(client)) {
463
507
  return;
464
508
  }
509
+ const timings = client.config.workspaceReadyTimings;
510
+ const timeoutMs = timings?.timeoutMs ?? RUST_ANALYZER_WORKSPACE_READY_TIMEOUT_MS;
511
+ const pollMs = timings?.pollMs ?? RUST_ANALYZER_WORKSPACE_READY_POLL_MS;
512
+ const settleMs = timings?.settleMs ?? RUST_ANALYZER_WORKSPACE_READY_SETTLE_MS;
513
+ const statusRequestTimeoutMs = timings?.statusRequestTimeoutMs ?? RUST_ANALYZER_STATUS_REQUEST_TIMEOUT_MS;
465
514
  const started = Date.now();
466
- const deadline = started + RUST_ANALYZER_WORKSPACE_READY_TIMEOUT_MS;
515
+ const deadline = started + timeoutMs;
467
516
  while (true) {
468
517
  throwIfAborted(signal);
469
518
  let status: unknown;
470
519
  try {
471
- status = await sendRequest(client, "rust-analyzer/analyzerStatus", {}, signal, 1_000);
520
+ status = await sendRequest(client, "rust-analyzer/analyzerStatus", {}, signal, statusRequestTimeoutMs);
472
521
  } catch (err) {
473
522
  if (!isRustAnalyzerStatusTimeout(err) || Date.now() >= deadline) {
474
523
  return;
475
524
  }
476
- await Bun.sleep(RUST_ANALYZER_WORKSPACE_READY_POLL_MS);
525
+ await Bun.sleep(pollMs);
477
526
  continue;
478
527
  }
479
528
  const ready = typeof status === "string" && !status.startsWith("No workspaces");
480
- if (ready && Date.now() - started >= RUST_ANALYZER_WORKSPACE_READY_SETTLE_MS) {
529
+ if (ready && Date.now() - started >= settleMs) {
481
530
  rustAnalyzerReadyClients.add(client);
482
531
  return;
483
532
  }
484
533
  if (Date.now() >= deadline) {
485
534
  return;
486
535
  }
487
- await Bun.sleep(RUST_ANALYZER_WORKSPACE_READY_POLL_MS);
536
+ await Bun.sleep(pollMs);
488
537
  }
489
538
  }
490
539
 
package/src/lsp/types.ts CHANGED
@@ -356,6 +356,16 @@ export interface ServerConfig {
356
356
  disabled?: boolean;
357
357
  /** Per-server warmup timeout in milliseconds. Overrides the global WARMUP_TIMEOUT_MS for this server during startup. */
358
358
  warmupTimeoutMs?: number;
359
+ /**
360
+ * Per-server overrides for rust-analyzer workspace-ready polling. When omitted, the module
361
+ * defaults are used. Primarily a tuning/test seam to bound the multi-second settle window.
362
+ */
363
+ workspaceReadyTimings?: {
364
+ timeoutMs?: number;
365
+ pollMs?: number;
366
+ settleMs?: number;
367
+ statusRequestTimeoutMs?: number;
368
+ };
359
369
  capabilities?: ServerCapabilities;
360
370
  /** If true, this is a linter/formatter server (e.g., Biome) - used only for diagnostics/actions, not type intelligence */
361
371
  isLinter?: boolean;
package/src/lsp/utils.ts CHANGED
@@ -153,9 +153,10 @@ export function formatDiagnostic(diagnostic: Diagnostic, filePath: string): stri
153
153
  const DIAG_PATH_RE = /^(.+?):(\d+:\d+\s+.*)$/;
154
154
 
155
155
  /**
156
- * Reformat pre-formatted diagnostic messages into grep-style directory/file groups.
156
+ * Reformat pre-formatted diagnostic messages into a multi-level, prefix-folded
157
+ * directory/file grouping (see `formatGroupedFiles`).
157
158
  * Input: ["path:line:col [sev] msg", ...]
158
- * Output: "# dir/\n## file.ts\n line:col [sev] msg"
159
+ * Output: "# pkg/src/\n## file.ts\n line:col [sev] msg"
159
160
  *
160
161
  * Messages that don't match the expected format are appended ungrouped at the end.
161
162
  */
package/src/main.ts CHANGED
@@ -40,19 +40,13 @@ import {
40
40
  resolveActiveProjectRegistryPath,
41
41
  } from "./discovery/helpers";
42
42
  import { injectOmpExtensionCliRoots } from "./discovery/omp-extension-roots";
43
- import { exportFromFile } from "./export/html";
44
43
  import { ExtensionRunner } from "./extensibility/extensions/runner";
45
44
  import type { ExtensionUIContext } from "./extensibility/extensions/types";
46
- import {
47
- getInstalledPluginsRegistryPath,
48
- getMarketplacesCacheDir,
49
- getMarketplacesRegistryPath,
50
- getPluginsCacheDir,
51
- MarketplaceManager,
52
- } from "./extensibility/plugins/marketplace";
45
+ import { scheduleMarketplaceAutoUpdate } from "./extensibility/plugins/marketplace-auto-update";
53
46
  import type { MCPManager } from "./mcp";
54
- import { InteractiveMode, runAcpMode, runPrintMode, runRpcMode } from "./modes";
55
- import { ALL_SCENES, runSetupWizard, selectSetupScenes } from "./modes/setup-wizard";
47
+ import { InteractiveMode } from "./modes/interactive-mode";
48
+ import type { PrintModeOptions } from "./modes/print-mode";
49
+ import { CURRENT_SETUP_VERSION } from "./modes/setup-version";
56
50
  import { initTheme, stopThemeWatcher } from "./modes/theme/theme";
57
51
  import type { SubmittedUserInput } from "./modes/types";
58
52
  import {
@@ -72,6 +66,13 @@ import type { LspStartupServerInfo } from "./tools";
72
66
  import { getChangelogPath, getNewEntries, parseChangelog } from "./utils/changelog";
73
67
  import { EventBus } from "./utils/event-bus";
74
68
 
69
+ type RunAcpMode = (createSession: AcpSessionFactory) => Promise<never>;
70
+ type RunPrintMode = (session: AgentSession, options: PrintModeOptions) => Promise<void>;
71
+ type RunRpcMode = (
72
+ session: AgentSession,
73
+ setToolUIContext?: (uiContext: ExtensionUIContext, hasUI: boolean) => void,
74
+ ) => Promise<never>;
75
+
75
76
  async function checkForNewVersion(currentVersion: string): Promise<string | undefined> {
76
77
  if (!settings.get("startup.checkUpdate")) {
77
78
  return;
@@ -261,17 +262,29 @@ async function runInteractiveMode(
261
262
  eventBus,
262
263
  );
263
264
 
264
- const setupScenes = await selectSetupScenes(settings.get("setupVersion"), ALL_SCENES, mode, {
265
- resuming,
266
- isTTY: process.stdin.isTTY && process.stdout.isTTY,
267
- setupWizardEnabled: settings.get("startup.setupWizard"),
268
- force: forceSetupWizard,
265
+ // Cold-launch gate: the full setup wizard (every scene + the overlay and
266
+ // their TUI/OAuth/search/theme deps) is heavy, yet the common case only needs
267
+ // to know whether the stored setup version is current. Lazy-load the wizard
268
+ // barrel only when setup is stale or forced; otherwise skip it entirely.
269
+ const storedSetupVersion = settings.get("setupVersion");
270
+ const setupWizard =
271
+ forceSetupWizard || storedSetupVersion < CURRENT_SETUP_VERSION ? await import("./modes/setup-wizard") : undefined;
272
+ const setupScenes = setupWizard
273
+ ? await setupWizard.selectSetupScenes(storedSetupVersion, setupWizard.ALL_SCENES, mode, {
274
+ resuming,
275
+ isTTY: process.stdin.isTTY && process.stdout.isTTY,
276
+ setupWizardEnabled: settings.get("startup.setupWizard"),
277
+ force: forceSetupWizard,
278
+ })
279
+ : [];
280
+
281
+ await mode.init({
282
+ suppressWelcomeIntro: resuming || setupScenes.length > 0,
283
+ clearInitialTerminalHistory: true,
269
284
  });
270
285
 
271
- await mode.init({ suppressWelcomeIntro: resuming || setupScenes.length > 0 });
272
-
273
- if (setupScenes.length > 0) {
274
- await runSetupWizard(mode, setupScenes);
286
+ if (setupWizard && setupScenes.length > 0) {
287
+ await setupWizard.runSetupWizard(mode, setupScenes);
275
288
  }
276
289
 
277
290
  versionCheckPromise
@@ -285,12 +298,11 @@ async function runInteractiveMode(
285
298
  })
286
299
  .catch(() => {});
287
300
 
288
- // Cold-launch cleanup: wipe the terminal scrollback before painting the
289
- // resumed/new transcript. The TUI's initial paint deliberately preserves
290
- // native scrollback (prior shell content), but on `omp`/`omp -c` that leaves
291
- // the previous run's welcome + transcript stacked above the fresh one. Every
292
- // in-process session load already clears via `clearTerminalHistory`; the cold
293
- // launch is the lone path that did not.
301
+ // Cold-launch cleanup: the first paint already clears native history, and this
302
+ // replay replaces the welcome/startup frame with the resumed/new transcript.
303
+ // Every in-process session load also uses `clearTerminalHistory`; cold launch
304
+ // follows the same clean-cutover path instead of preserving a previous run's
305
+ // transcript above the fresh one.
294
306
  mode.renderInitialMessages(undefined, { preserveExistingChat: true, clearTerminalHistory: true });
295
307
 
296
308
  for (const notify of notifs) {
@@ -716,7 +728,7 @@ async function buildSessionOptions(
716
728
  interface RunRootCommandDependencies {
717
729
  createAgentSession?: typeof createAgentSession;
718
730
  discoverAuthStorage?: typeof discoverAuthStorage;
719
- runAcpMode?: typeof runAcpMode;
731
+ runAcpMode?: RunAcpMode;
720
732
  settings?: Settings;
721
733
  forceSetupWizard?: boolean;
722
734
  }
@@ -773,6 +785,7 @@ export async function runRootCommand(
773
785
  let result: string;
774
786
  try {
775
787
  const outputPath = parsedArgs.messages.length > 0 ? parsedArgs.messages[0] : undefined;
788
+ const { exportFromFile } = await import("./export/html");
776
789
  result = await exportFromFile(parsedArgs.export, outputPath);
777
790
  } catch (error: unknown) {
778
791
  const message = error instanceof Error ? error.message : "Failed to export session";
@@ -940,33 +953,11 @@ export async function runRootCommand(
940
953
 
941
954
  await pluginPreloadPromise;
942
955
 
943
- // Background marketplace auto-update — never blocks startup.
944
- const autoUpdate = settingsInstance.get("marketplace.autoUpdate");
945
- if (autoUpdate !== "off") {
946
- void (async () => {
947
- try {
948
- const mgr = new MarketplaceManager({
949
- marketplacesRegistryPath: getMarketplacesRegistryPath(),
950
- installedRegistryPath: getInstalledPluginsRegistryPath(),
951
- projectInstalledRegistryPath: (await resolveActiveProjectRegistryPath(getProjectDir())) ?? undefined,
952
- marketplacesCacheDir: getMarketplacesCacheDir(),
953
- pluginsCacheDir: getPluginsCacheDir(),
954
- clearPluginRootsCache: clearPluginRootsAndCaches,
955
- });
956
- await mgr.refreshStaleMarketplaces();
957
- const updates = await mgr.checkForUpdates();
958
- if (updates.length === 0) return;
959
- if (autoUpdate === "auto") {
960
- await mgr.upgradeAllPlugins();
961
- logger.debug(`Auto-upgraded ${updates.length} marketplace plugin(s)`);
962
- } else {
963
- logger.debug(`${updates.length} marketplace plugin update(s) available — /marketplace upgrade`);
964
- }
965
- } catch {
966
- // Silently ignore — network failure, corrupt data, offline.
967
- }
968
- })();
969
- }
956
+ scheduleMarketplaceAutoUpdate({
957
+ autoUpdate: settingsInstance.get("marketplace.autoUpdate"),
958
+ resolveActiveProjectRegistryPath,
959
+ clearPluginRootsCache: clearPluginRootsAndCaches,
960
+ });
970
961
 
971
962
  const { options: sessionOptions } = await logger.time(
972
963
  "buildSessionOptions",
@@ -988,7 +979,7 @@ export async function runRootCommand(
988
979
  // Both are no-ops when OTEL_EXPORTER_OTLP_ENDPOINT is unset. An empty config
989
980
  // is enough to enable telemetry — content capture is governed by the
990
981
  // standard OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT env var.
991
- initTelemetryExport();
982
+ await initTelemetryExport();
992
983
  if (isTelemetryExportEnabled()) {
993
984
  sessionOptions.telemetry = {};
994
985
  }
@@ -1027,7 +1018,9 @@ export async function runRootCommand(
1027
1018
  rawArgs,
1028
1019
  createSession,
1029
1020
  });
1030
- await (deps.runAcpMode ?? runAcpMode)(createAcpSession);
1021
+ // Branch-only protocol runner: keep ACP server code out of normal interactive startup.
1022
+ const runAcpMode = deps.runAcpMode ?? (await import("./modes/acp/acp-mode")).runAcpMode;
1023
+ await runAcpMode(createAcpSession);
1031
1024
  } else {
1032
1025
  // Resolve extension-registered CLI flags before creating the session so a
1033
1026
  // bad `@file` fails fast WITHOUT leaving a junk session/breadcrumb
@@ -1091,6 +1084,8 @@ export async function runRootCommand(
1091
1084
  }
1092
1085
 
1093
1086
  if (mode === "rpc" || mode === "rpc-ui") {
1087
+ // Branch-only protocol runner: keep RPC host code out of normal interactive startup.
1088
+ const runRpcMode: RunRpcMode = (await import("./modes/rpc/rpc-mode")).runRpcMode;
1094
1089
  await runRpcMode(session, mode === "rpc-ui" ? setToolUIContext : undefined);
1095
1090
  } else if (isInteractive) {
1096
1091
  const versionCheckPromise = checkForNewVersion(VERSION).catch(() => undefined);
@@ -1109,7 +1104,7 @@ export async function runRootCommand(
1109
1104
 
1110
1105
  if ($env.PI_TIMING) {
1111
1106
  logger.printTimings();
1112
- if ($env.PI_TIMING === "x") {
1107
+ if (logger.shouldExitAfterTimings()) {
1113
1108
  process.exit(0);
1114
1109
  }
1115
1110
  }
@@ -1132,6 +1127,8 @@ export async function runRootCommand(
1132
1127
  initialImages,
1133
1128
  );
1134
1129
  } else {
1130
+ // Branch-only single-shot runner: keep print-mode code out of normal interactive startup.
1131
+ const runPrintMode: RunPrintMode = (await import("./modes/print-mode")).runPrintMode;
1135
1132
  await runPrintMode(session, {
1136
1133
  mode,
1137
1134
  messages: initialArgs.messages,
@@ -3,8 +3,9 @@ import type * as fsNode from "node:fs";
3
3
  import * as fs from "node:fs/promises";
4
4
  import * as path from "node:path";
5
5
  import type { AgentMessage } from "@oh-my-pi/pi-agent-core";
6
- import { clampThinkingLevelForModel, completeSimple, Effort, type Model } from "@oh-my-pi/pi-ai";
6
+ import { type ApiKey, clampThinkingLevelForModel, completeSimple, Effort, type Model } from "@oh-my-pi/pi-ai";
7
7
  import { getAgentDbPath, getMemoriesDir, logger, parseJsonlLenient, prompt } from "@oh-my-pi/pi-utils";
8
+
8
9
  import type { ModelRegistry } from "../config/model-registry";
9
10
  import { resolveModelRoleValue } from "../config/model-resolver";
10
11
  import type { Settings } from "../config/settings";
@@ -271,7 +272,10 @@ async function runPhase1(options: {
271
272
  const result = await runStage1Job({
272
273
  claim,
273
274
  model: phase1Model,
274
- apiKey: phase1ApiKey,
275
+ apiKey: modelRegistry.resolver(phase1Model.provider, {
276
+ sessionId: session.sessionId,
277
+ baseUrl: phase1Model.baseUrl,
278
+ }),
275
279
  modelMaxTokens: computeModelTokenBudget(phase1Model, config),
276
280
  config,
277
281
  metadata: session.agent?.metadataForProvider(phase1Model.provider),
@@ -428,7 +432,10 @@ async function runPhase2(options: {
428
432
  const consolidated = await runConsolidationModel({
429
433
  memoryRoot,
430
434
  model: phase2Model,
431
- apiKey: phase2ApiKey,
435
+ apiKey: modelRegistry.resolver(phase2Model.provider, {
436
+ sessionId: session.sessionId,
437
+ baseUrl: phase2Model.baseUrl,
438
+ }),
432
439
  metadata: session.agent?.metadataForProvider(phase2Model.provider),
433
440
  });
434
441
  await applyConsolidation(memoryRoot, consolidated);
@@ -574,7 +581,7 @@ function extractPersistableMessages(payload: string): AgentMessage[] {
574
581
  async function runStage1Job(options: {
575
582
  claim: Stage1Claim;
576
583
  model: Model;
577
- apiKey: string;
584
+ apiKey: ApiKey;
578
585
  modelMaxTokens: number;
579
586
  config: MemoryRuntimeConfig;
580
587
  metadata?: Record<string, unknown>;
@@ -718,7 +725,7 @@ async function readRolloutSummaries(memoryRoot: string): Promise<string> {
718
725
  async function runConsolidationModel(options: {
719
726
  memoryRoot: string;
720
727
  model: Model;
721
- apiKey: string;
728
+ apiKey: ApiKey;
722
729
  metadata?: Record<string, unknown>;
723
730
  }): Promise<{
724
731
  memoryMd: string;
@@ -1,4 +1,16 @@
1
- export * from "../mnemopi";
1
+ export type {
2
+ MnemopiBackendConfig,
3
+ MnemopiLlmMode,
4
+ MnemopiProviderOptions,
5
+ MnemopiScoping,
6
+ } from "../mnemopi/config";
7
+ export type {
8
+ MnemopiMemoryEditOperation,
9
+ MnemopiMemoryEditOptions,
10
+ MnemopiMemoryEditResult,
11
+ MnemopiSessionState,
12
+ MnemopiSessionStateOptions,
13
+ } from "../mnemopi/state";
2
14
  export * from "./local-backend";
3
15
  export * from "./off-backend";
4
16
  export * from "./resolve";
@@ -1,6 +1,4 @@
1
1
  import type { Settings } from "../config/settings";
2
- import { hindsightBackend } from "../hindsight";
3
- import { mnemopiBackend } from "../mnemopi";
4
2
  import { localBackend } from "./local-backend";
5
3
  import { offBackend } from "./off-backend";
6
4
  import type { MemoryBackend } from "./types";
@@ -18,10 +16,10 @@ import type { MemoryBackend } from "./types";
18
16
  * `memories.enabled` remains accepted only as a legacy migration input. Once
19
17
  * a config is loaded, `memory.backend` is the sole runtime selector.
20
18
  */
21
- export function resolveMemoryBackend(settings: Settings): MemoryBackend {
19
+ export async function resolveMemoryBackend(settings: Settings): Promise<MemoryBackend> {
22
20
  const id = settings.get("memory.backend");
23
- if (id === "hindsight") return hindsightBackend;
24
- if (id === "mnemopi") return mnemopiBackend;
21
+ if (id === "hindsight") return (await import("../hindsight/backend")).hindsightBackend;
22
+ if (id === "mnemopi") return (await import("../mnemopi/backend")).mnemopiBackend;
25
23
  if (id === "local") return localBackend;
26
24
  return offBackend;
27
25
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Memory backend abstraction.
3
3
  *
4
- * Backends are mutually exclusive — `resolveMemoryBackend(settings)` returns
4
+ * Backends are mutually exclusive — `await resolveMemoryBackend(settings)` resolves
5
5
  * exactly one. Implementations MUST be self-contained: they own the per-session
6
6
  * state they create in `start()` and tear it down on `clear()`.
7
7
  */
@@ -5,6 +5,7 @@ import { Mnemopi } from "@oh-my-pi/pi-mnemopi";
5
5
  import { BankManager } from "@oh-my-pi/pi-mnemopi/core";
6
6
  import { type DiagnosticSummary, inspectDatabase } from "@oh-my-pi/pi-mnemopi/diagnose";
7
7
  import { logger } from "@oh-my-pi/pi-utils";
8
+
8
9
  import type { ModelRegistry } from "../config/model-registry";
9
10
  import { resolveRoleSelection } from "../config/model-resolver";
10
11
  import type { MemoryBackend, MemoryBackendStartOptions } from "../memory-backend/types";
@@ -334,7 +335,10 @@ async function resolveMnemopiProviderOptions(
334
335
  messages: [{ role: "user", content: prompt, timestamp: Date.now() }],
335
336
  },
336
337
  {
337
- apiKey,
338
+ apiKey: modelRegistry.resolver(model.provider, {
339
+ sessionId,
340
+ baseUrl: model.baseUrl,
341
+ }),
338
342
  maxTokens: opts?.maxTokens,
339
343
  temperature: opts?.temperature,
340
344
  },