pi-namespace-patch 0.85.1 → 0.86.1-namespace.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 (330) hide show
  1. package/CHANGELOG.md +110 -0
  2. package/README.md +26 -705
  3. package/dist/bundle/chunks/anthropic-messages-MYU5ZMRF.js +6 -0
  4. package/dist/bundle/chunks/azure-openai-responses-HUSQ3GP2.js +2 -0
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +47 -38
  6. package/dist/bundle/chunks/chunk-4YJERF5N.js +2 -0
  7. package/dist/bundle/chunks/chunk-A3JYRWB6.js +2 -0
  8. package/dist/bundle/chunks/chunk-CVPNLAPW.js +1562 -0
  9. package/dist/bundle/chunks/chunk-DTD7JQ7Y.js +42 -0
  10. package/dist/bundle/chunks/chunk-FUXEF6JQ.js +44 -0
  11. package/dist/bundle/chunks/{chunk-IDDQWTHI.js → chunk-RCZIEVGO.js} +10 -1
  12. package/dist/bundle/chunks/chunk-S7SZN6Z3.js +2 -0
  13. package/dist/bundle/chunks/chunk-WIUZI2CJ.js +11 -0
  14. package/dist/bundle/chunks/github-copilot.js +1 -1
  15. package/dist/bundle/chunks/google-generative-ai-IMS5EK2Y.js +2 -0
  16. package/dist/bundle/chunks/google-vertex-O4YJEQUW.js +2 -0
  17. package/dist/bundle/chunks/jiti-loader-C3NU2SDH.js +21 -0
  18. package/dist/bundle/chunks/jiti-static-loader-E6ANQD5T.js +2 -0
  19. package/dist/bundle/chunks/meta.js +2 -0
  20. package/dist/bundle/chunks/mistral-conversations-NOSQHBEY.js +5 -0
  21. package/dist/bundle/chunks/{node-KG362ECQ.js → node-O3RIBJRH.js} +1 -1
  22. package/dist/bundle/chunks/openai-codex-responses-QDSOTBBO.js +10 -0
  23. package/dist/bundle/chunks/openai-completions-CYGM3XXP.js +7 -0
  24. package/dist/bundle/chunks/openai-responses-HWEUZ6WZ.js +2 -0
  25. package/dist/bundle/chunks/{pi-messages-PML4SPVJ.js → pi-messages-GFKBWJHZ.js} +1 -1
  26. package/dist/bundle/chunks/virtual-modules-R7YYFUSE.js +2 -0
  27. package/dist/bundle/cli-runtime.js +3 -0
  28. package/dist/bundle/cli.js +4 -2
  29. package/dist/bundle/index.js +1 -1
  30. package/dist/bundle/rpc-entry.js +1 -1
  31. package/dist/cli/args.d.ts.map +1 -1
  32. package/dist/cli/args.js +1 -0
  33. package/dist/cli/args.js.map +1 -1
  34. package/dist/cli/session-picker.d.ts +1 -1
  35. package/dist/cli/session-picker.d.ts.map +1 -1
  36. package/dist/cli/session-picker.js.map +1 -1
  37. package/dist/config.d.ts.map +1 -1
  38. package/dist/config.js +1 -1
  39. package/dist/config.js.map +1 -1
  40. package/dist/core/agent-session.d.ts +56 -6
  41. package/dist/core/agent-session.d.ts.map +1 -1
  42. package/dist/core/agent-session.js +294 -157
  43. package/dist/core/agent-session.js.map +1 -1
  44. package/dist/core/bug-report-upload.d.ts +12 -0
  45. package/dist/core/bug-report-upload.d.ts.map +1 -0
  46. package/dist/core/bug-report-upload.js +22 -0
  47. package/dist/core/bug-report-upload.js.map +1 -0
  48. package/dist/core/bug-report.d.ts +176 -0
  49. package/dist/core/bug-report.d.ts.map +1 -0
  50. package/dist/core/bug-report.js +292 -0
  51. package/dist/core/bug-report.js.map +1 -0
  52. package/dist/core/cache-stats.d.ts.map +1 -1
  53. package/dist/core/cache-stats.js +12 -1
  54. package/dist/core/cache-stats.js.map +1 -1
  55. package/dist/core/cache-warmer.d.ts +102 -0
  56. package/dist/core/cache-warmer.d.ts.map +1 -0
  57. package/dist/core/cache-warmer.js +342 -0
  58. package/dist/core/cache-warmer.js.map +1 -0
  59. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  60. package/dist/core/compaction/branch-summarization.js +2 -2
  61. package/dist/core/compaction/branch-summarization.js.map +1 -1
  62. package/dist/core/compaction/compaction.d.ts +2 -2
  63. package/dist/core/compaction/compaction.d.ts.map +1 -1
  64. package/dist/core/compaction/compaction.js +11 -12
  65. package/dist/core/compaction/compaction.js.map +1 -1
  66. package/dist/core/crash-log.d.ts +22 -0
  67. package/dist/core/crash-log.d.ts.map +1 -0
  68. package/dist/core/crash-log.js +71 -0
  69. package/dist/core/crash-log.js.map +1 -0
  70. package/dist/core/experimental.d.ts +0 -4
  71. package/dist/core/experimental.d.ts.map +1 -1
  72. package/dist/core/experimental.js +0 -4
  73. package/dist/core/experimental.js.map +1 -1
  74. package/dist/core/extensions/index.d.ts +1 -1
  75. package/dist/core/extensions/index.d.ts.map +1 -1
  76. package/dist/core/extensions/index.js.map +1 -1
  77. package/dist/core/extensions/jiti-loader.d.ts +2 -0
  78. package/dist/core/extensions/jiti-loader.d.ts.map +1 -0
  79. package/dist/core/extensions/jiti-loader.js +4 -0
  80. package/dist/core/extensions/jiti-loader.js.map +1 -0
  81. package/dist/core/extensions/jiti-static-loader.d.ts +2 -0
  82. package/dist/core/extensions/jiti-static-loader.d.ts.map +1 -0
  83. package/dist/core/extensions/jiti-static-loader.js +4 -0
  84. package/dist/core/extensions/jiti-static-loader.js.map +1 -0
  85. package/dist/core/extensions/loader.d.ts.map +1 -1
  86. package/dist/core/extensions/loader.js +38 -51
  87. package/dist/core/extensions/loader.js.map +1 -1
  88. package/dist/core/extensions/runner.d.ts +10 -7
  89. package/dist/core/extensions/runner.d.ts.map +1 -1
  90. package/dist/core/extensions/runner.js +85 -67
  91. package/dist/core/extensions/runner.js.map +1 -1
  92. package/dist/core/extensions/types.d.ts +60 -50
  93. package/dist/core/extensions/types.d.ts.map +1 -1
  94. package/dist/core/extensions/types.js.map +1 -1
  95. package/dist/core/extensions/virtual-modules.d.ts +3 -0
  96. package/dist/core/extensions/virtual-modules.d.ts.map +1 -0
  97. package/dist/core/extensions/virtual-modules.js +38 -0
  98. package/dist/core/extensions/virtual-modules.js.map +1 -0
  99. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  100. package/dist/core/extensions/wrapper.js +1 -20
  101. package/dist/core/extensions/wrapper.js.map +1 -1
  102. package/dist/core/index.d.ts +2 -1
  103. package/dist/core/index.d.ts.map +1 -1
  104. package/dist/core/index.js.map +1 -1
  105. package/dist/core/keybindings.d.ts +1 -1
  106. package/dist/core/keybindings.d.ts.map +1 -1
  107. package/dist/core/keybindings.js +1 -1
  108. package/dist/core/keybindings.js.map +1 -1
  109. package/dist/core/messages.d.ts.map +1 -1
  110. package/dist/core/messages.js +1 -0
  111. package/dist/core/messages.js.map +1 -1
  112. package/dist/core/model-config.d.ts +101 -20
  113. package/dist/core/model-config.d.ts.map +1 -1
  114. package/dist/core/model-config.js +25 -18
  115. package/dist/core/model-config.js.map +1 -1
  116. package/dist/core/model-registry.d.ts +5 -1
  117. package/dist/core/model-registry.d.ts.map +1 -1
  118. package/dist/core/model-registry.js +8 -0
  119. package/dist/core/model-registry.js.map +1 -1
  120. package/dist/core/model-resolver.d.ts.map +1 -1
  121. package/dist/core/model-resolver.js +2 -1
  122. package/dist/core/model-resolver.js.map +1 -1
  123. package/dist/core/model-runtime.d.ts.map +1 -1
  124. package/dist/core/model-runtime.js +5 -3
  125. package/dist/core/model-runtime.js.map +1 -1
  126. package/dist/core/provider-composer.d.ts +3 -2
  127. package/dist/core/provider-composer.d.ts.map +1 -1
  128. package/dist/core/provider-composer.js +2 -0
  129. package/dist/core/provider-composer.js.map +1 -1
  130. package/dist/core/radius.d.ts +3 -0
  131. package/dist/core/radius.d.ts.map +1 -1
  132. package/dist/core/radius.js +6 -0
  133. package/dist/core/radius.js.map +1 -1
  134. package/dist/core/sdk.d.ts.map +1 -1
  135. package/dist/core/sdk.js +60 -38
  136. package/dist/core/sdk.js.map +1 -1
  137. package/dist/core/session-export.d.ts +6 -2
  138. package/dist/core/session-export.d.ts.map +1 -1
  139. package/dist/core/session-export.js +14 -13
  140. package/dist/core/session-export.js.map +1 -1
  141. package/dist/core/session-manager.d.ts +29 -6
  142. package/dist/core/session-manager.d.ts.map +1 -1
  143. package/dist/core/session-manager.js +159 -96
  144. package/dist/core/session-manager.js.map +1 -1
  145. package/dist/core/settings-manager.d.ts +20 -4
  146. package/dist/core/settings-manager.d.ts.map +1 -1
  147. package/dist/core/settings-manager.js +43 -7
  148. package/dist/core/settings-manager.js.map +1 -1
  149. package/dist/core/slash-commands.d.ts.map +1 -1
  150. package/dist/core/slash-commands.js +1 -0
  151. package/dist/core/slash-commands.js.map +1 -1
  152. package/dist/core/system-prompt.d.ts +49 -6
  153. package/dist/core/system-prompt.d.ts.map +1 -1
  154. package/dist/core/system-prompt.js +121 -92
  155. package/dist/core/system-prompt.js.map +1 -1
  156. package/dist/core/tools/bash.d.ts +2 -1
  157. package/dist/core/tools/bash.d.ts.map +1 -1
  158. package/dist/core/tools/bash.js +10 -4
  159. package/dist/core/tools/bash.js.map +1 -1
  160. package/dist/core/tools/edit.d.ts.map +1 -1
  161. package/dist/core/tools/edit.js +1 -2
  162. package/dist/core/tools/edit.js.map +1 -1
  163. package/dist/core/tools/read.d.ts.map +1 -1
  164. package/dist/core/tools/read.js +1 -2
  165. package/dist/core/tools/read.js.map +1 -1
  166. package/dist/core/tools/renderers/bash.d.ts.map +1 -1
  167. package/dist/core/tools/renderers/bash.js +9 -1
  168. package/dist/core/tools/renderers/bash.js.map +1 -1
  169. package/dist/core/tools/write.d.ts.map +1 -1
  170. package/dist/core/tools/write.js +1 -2
  171. package/dist/core/tools/write.js.map +1 -1
  172. package/dist/core/usage-totals.d.ts +1 -1
  173. package/dist/core/usage-totals.d.ts.map +1 -1
  174. package/dist/core/usage-totals.js +5 -1
  175. package/dist/core/usage-totals.js.map +1 -1
  176. package/dist/extensions/llama/client.d.ts +2 -0
  177. package/dist/extensions/llama/client.d.ts.map +1 -1
  178. package/dist/extensions/llama/client.js +7 -3
  179. package/dist/extensions/llama/client.js.map +1 -1
  180. package/dist/extensions/llama/provider.d.ts.map +1 -1
  181. package/dist/extensions/llama/provider.js +20 -5
  182. package/dist/extensions/llama/provider.js.map +1 -1
  183. package/dist/index.d.ts +3 -2
  184. package/dist/index.d.ts.map +1 -1
  185. package/dist/index.js.map +1 -1
  186. package/dist/main.d.ts.map +1 -1
  187. package/dist/main.js +13 -9
  188. package/dist/main.js.map +1 -1
  189. package/dist/migrations.d.ts.map +1 -1
  190. package/dist/migrations.js +2 -2
  191. package/dist/migrations.js.map +1 -1
  192. package/dist/modes/interactive/bug-report.d.ts +16 -0
  193. package/dist/modes/interactive/bug-report.d.ts.map +1 -0
  194. package/dist/modes/interactive/bug-report.js +206 -0
  195. package/dist/modes/interactive/bug-report.js.map +1 -0
  196. package/dist/modes/interactive/chat-viewport.d.ts.map +1 -1
  197. package/dist/modes/interactive/chat-viewport.js +1 -1
  198. package/dist/modes/interactive/chat-viewport.js.map +1 -1
  199. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  200. package/dist/modes/interactive/components/branch-summary-message.js +12 -5
  201. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  202. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  203. package/dist/modes/interactive/components/compaction-summary-message.js +12 -5
  204. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  205. package/dist/modes/interactive/components/custom-editor.d.ts +3 -3
  206. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  207. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  208. package/dist/modes/interactive/components/extension-editor.d.ts +4 -1
  209. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  210. package/dist/modes/interactive/components/extension-editor.js +7 -2
  211. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  212. package/dist/modes/interactive/components/extension-input.d.ts +2 -0
  213. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
  214. package/dist/modes/interactive/components/extension-input.js +6 -0
  215. package/dist/modes/interactive/components/extension-input.js.map +1 -1
  216. package/dist/modes/interactive/components/extension-selector.d.ts +1 -0
  217. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  218. package/dist/modes/interactive/components/extension-selector.js +4 -0
  219. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  220. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  221. package/dist/modes/interactive/components/footer.js +4 -1
  222. package/dist/modes/interactive/components/footer.js.map +1 -1
  223. package/dist/modes/interactive/components/session-selector.d.ts +5 -5
  224. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  225. package/dist/modes/interactive/components/session-selector.js +74 -48
  226. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  227. package/dist/modes/interactive/components/settings-selector.d.ts +3 -1
  228. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  229. package/dist/modes/interactive/components/settings-selector.js +11 -0
  230. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  231. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  232. package/dist/modes/interactive/components/skill-invocation-message.js +11 -4
  233. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  234. package/dist/modes/interactive/components/status-indicator.d.ts +2 -2
  235. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  236. package/dist/modes/interactive/components/status-indicator.js +7 -7
  237. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  238. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  239. package/dist/modes/interactive/components/tool-execution.js +18 -9
  240. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  241. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  242. package/dist/modes/interactive/components/tree-selector.js +2 -0
  243. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  244. package/dist/modes/interactive/interactive-mode.d.ts +15 -2
  245. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  246. package/dist/modes/interactive/interactive-mode.js +227 -84
  247. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  248. package/dist/modes/interactive/session-share.d.ts +2 -0
  249. package/dist/modes/interactive/session-share.d.ts.map +1 -1
  250. package/dist/modes/interactive/session-share.js +8 -4
  251. package/dist/modes/interactive/session-share.js.map +1 -1
  252. package/dist/modes/interactive/tui-renderer.d.ts.map +1 -1
  253. package/dist/modes/interactive/tui-renderer.js +2 -2
  254. package/dist/modes/interactive/tui-renderer.js.map +1 -1
  255. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  256. package/dist/modes/rpc/rpc-mode.js +2 -2
  257. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  258. package/dist/utils/clipboard-command.d.ts +7 -0
  259. package/dist/utils/clipboard-command.d.ts.map +1 -0
  260. package/dist/utils/clipboard-command.js +45 -0
  261. package/dist/utils/clipboard-command.js.map +1 -0
  262. package/dist/utils/clipboard-image.d.ts.map +1 -1
  263. package/dist/utils/clipboard-image.js +53 -81
  264. package/dist/utils/clipboard-image.js.map +1 -1
  265. package/dist/utils/clipboard.d.ts.map +1 -1
  266. package/dist/utils/clipboard.js +111 -121
  267. package/dist/utils/clipboard.js.map +1 -1
  268. package/dist/utils/version-check.d.ts.map +1 -1
  269. package/dist/utils/version-check.js +11 -4
  270. package/dist/utils/version-check.js.map +1 -1
  271. package/dist/utils/wsl.d.ts +3 -0
  272. package/dist/utils/wsl.d.ts.map +1 -0
  273. package/dist/utils/wsl.js +15 -0
  274. package/dist/utils/wsl.js.map +1 -0
  275. package/dist/utils/zip.d.ts +7 -0
  276. package/dist/utils/zip.d.ts.map +1 -0
  277. package/dist/utils/zip.js +60 -0
  278. package/dist/utils/zip.js.map +1 -0
  279. package/docs/compaction.md +39 -13
  280. package/docs/custom-provider.md +22 -13
  281. package/docs/development.md +4 -4
  282. package/docs/docs.json +4 -0
  283. package/docs/environment-variables.md +1 -0
  284. package/docs/extensions.md +57 -43
  285. package/docs/json.md +4 -4
  286. package/docs/models.md +33 -2
  287. package/docs/providers.md +10 -2
  288. package/docs/sdk.md +4 -2
  289. package/docs/security.md +1 -1
  290. package/docs/session-format.md +82 -40
  291. package/docs/sessions.md +27 -0
  292. package/docs/settings.md +60 -1
  293. package/docs/termux.md +0 -1
  294. package/docs/tui.md +2 -2
  295. package/docs/usage.md +1 -0
  296. package/examples/extensions/README.md +0 -1
  297. package/examples/extensions/custom-provider-anthropic/index.ts +18 -12
  298. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  299. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  300. package/examples/extensions/custom-provider-gitlab-duo/index.ts +2 -2
  301. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  302. package/examples/extensions/gondolin/package-lock.json +2 -2
  303. package/examples/extensions/gondolin/package.json +1 -1
  304. package/examples/extensions/prompt-customizer.ts +19 -67
  305. package/examples/extensions/sandbox/package-lock.json +2 -2
  306. package/examples/extensions/sandbox/package.json +1 -1
  307. package/examples/extensions/with-deps/package-lock.json +2 -2
  308. package/examples/extensions/with-deps/package.json +1 -1
  309. package/npm-shrinkwrap.json +435 -762
  310. package/package.json +17 -23
  311. package/dist/bundle/chunks/anthropic-messages-VWZZOSJQ.js +0 -6
  312. package/dist/bundle/chunks/azure-openai-responses-BJLAM6CD.js +0 -2
  313. package/dist/bundle/chunks/chunk-AXIIZGTV.js +0 -2
  314. package/dist/bundle/chunks/chunk-CLNPYIDP.js +0 -42
  315. package/dist/bundle/chunks/chunk-GMWCTUPB.js +0 -2
  316. package/dist/bundle/chunks/chunk-JJ2YFCJF.js +0 -1547
  317. package/dist/bundle/chunks/chunk-OUXLLA64.js +0 -11
  318. package/dist/bundle/chunks/chunk-U6ZMQKGD.js +0 -50
  319. package/dist/bundle/chunks/chunk-UAQELI3K.js +0 -2
  320. package/dist/bundle/chunks/google-generative-ai-Q2K7FBDI.js +0 -2
  321. package/dist/bundle/chunks/google-vertex-7UJBF4S7.js +0 -2
  322. package/dist/bundle/chunks/mistral-conversations-4M6BZBX6.js +0 -5
  323. package/dist/bundle/chunks/openai-codex-responses-R6VYZTVY.js +0 -10
  324. package/dist/bundle/chunks/openai-completions-EKZT2IH2.js +0 -7
  325. package/dist/bundle/chunks/openai-responses-TFDINO6W.js +0 -2
  326. package/dist/utils/clipboard-native.d.ts +0 -11
  327. package/dist/utils/clipboard-native.d.ts.map +0 -1
  328. package/dist/utils/clipboard-native.js +0 -20
  329. package/dist/utils/clipboard-native.js.map +0 -1
  330. package/examples/extensions/kimi-deferred-tools.ts +0 -61
@@ -1,8 +1,8 @@
1
- import { uuidv7 } from "@earendil-works/pi-ai";
1
+ import { getCurrentSystemMessage, uuidv7, } from "@earendil-works/pi-ai";
2
2
  import { randomUUID } from "crypto";
3
3
  import { appendFileSync, closeSync, createReadStream, existsSync, mkdirSync, openSync, readdirSync, readSync, statSync, writeFileSync, } from "fs";
4
4
  import { readdir, stat } from "fs/promises";
5
- import { join, resolve } from "path";
5
+ import { basename, join, resolve } from "path";
6
6
  import { createInterface } from "readline";
7
7
  import { StringDecoder } from "string_decoder";
8
8
  import { APP_NAME, getAgentDir as getDefaultAgentDir, getSessionsDir } from "../config.js";
@@ -168,6 +168,8 @@ export function sessionEntryToContextMessages(entry) {
168
168
  const message = entry.message;
169
169
  // Session files are parsed without validation; old versions, forks, or
170
170
  // hand-edited files can contain messages with null/missing content.
171
+ if (message.role === "system" && message.content == null)
172
+ return [{ ...message, content: "" }];
171
173
  if ((message.role === "user" || message.role === "assistant" || message.role === "toolResult") &&
172
174
  message.content == null) {
173
175
  return [{ ...message, content: [] }];
@@ -183,7 +185,8 @@ export function sessionEntryToContextMessages(entry) {
183
185
  return [createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp)];
184
186
  }
185
187
  if (entry.type === "compaction") {
186
- return [createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp)];
188
+ const summary = createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp);
189
+ return entry.systemMessage ? [entry.systemMessage, summary] : [summary];
187
190
  }
188
191
  return [];
189
192
  }
@@ -217,7 +220,7 @@ export function buildContextEntries(entries, leafId, byId) {
217
220
  if (entry.id === compaction.firstKeptEntryId) {
218
221
  foundFirstKept = true;
219
222
  }
220
- if (foundFirstKept) {
223
+ if (foundFirstKept && !(entry.type === "message" && entry.message.role === "system")) {
221
224
  contextEntries.push(entry);
222
225
  }
223
226
  }
@@ -399,14 +402,16 @@ export function findMostRecentSession(sessionDir, cwd) {
399
402
  const resolvedCwd = cwd ? resolvePath(cwd) : undefined;
400
403
  try {
401
404
  const files = readdirSync(resolvedSessionDir)
402
- .filter((f) => f.endsWith(".jsonl"))
403
- .map((f) => join(resolvedSessionDir, f))
404
- .map((path) => ({ path, header: readSessionHeaderForDiscovery(path) }))
405
- .filter((file) => file.header !== null &&
406
- (!resolvedCwd || sessionCwdMatches(getSessionHeaderCwd(file.header), resolvedCwd)))
407
- .map(({ path }) => ({ path, mtime: statSync(path).mtime }))
408
- .sort((a, b) => b.mtime.getTime() - a.mtime.getTime());
409
- return files[0]?.path || null;
405
+ .filter((file) => file.endsWith(".jsonl"))
406
+ .map((file) => join(resolvedSessionDir, file))
407
+ .map((path) => ({ path, mtime: statSync(path).mtimeMs }))
408
+ .sort((a, b) => b.mtime - a.mtime);
409
+ for (const { path } of files) {
410
+ const header = readSessionHeaderForDiscovery(path);
411
+ if (header && (!resolvedCwd || sessionCwdMatches(getSessionHeaderCwd(header), resolvedCwd)))
412
+ return path;
413
+ }
414
+ return null;
410
415
  }
411
416
  catch {
412
417
  // Directory access and stat races make recent-session discovery unavailable.
@@ -439,9 +444,9 @@ function getMessageActivityTime(entry) {
439
444
  const t = new Date(entry.timestamp).getTime();
440
445
  return Number.isNaN(t) ? undefined : t;
441
446
  }
442
- async function buildSessionInfo(filePath) {
447
+ async function buildSessionInfo(filePath, signal, fileStats) {
443
448
  try {
444
- const stats = await stat(filePath);
449
+ const stats = fileStats ?? (await stat(filePath));
445
450
  let header = null;
446
451
  let messageCount = 0;
447
452
  let firstMessage = "";
@@ -449,7 +454,7 @@ async function buildSessionInfo(filePath) {
449
454
  let name;
450
455
  let lastActivityTime;
451
456
  const rl = createInterface({
452
- input: createReadStream(filePath, { encoding: "utf8" }),
457
+ input: createReadStream(filePath, { encoding: "utf8", signal }),
453
458
  crlfDelay: Infinity,
454
459
  });
455
460
  for await (const line of rl) {
@@ -510,67 +515,63 @@ async function buildSessionInfo(filePath) {
510
515
  };
511
516
  }
512
517
  catch {
518
+ signal?.throwIfAborted();
513
519
  return null;
514
520
  }
515
521
  }
516
522
  const MAX_CONCURRENT_SESSION_INFO_LOADS = 10;
517
- async function buildSessionInfosWithConcurrency(files, onLoaded) {
518
- const results = new Array(files.length).fill(null);
519
- const inFlight = new Set();
523
+ const MAX_CONCURRENT_SESSION_DISCOVERY_LOADS = 64;
524
+ const CURRENT_SESSION_LIST_PUBLISH_INTERVAL = 10;
525
+ const ALL_SESSION_LIST_PUBLISH_INTERVAL = 100;
526
+ async function mapWithConcurrency(items, limit, map, signal) {
527
+ const results = new Array(items.length);
520
528
  let nextIndex = 0;
521
- const startNext = () => {
522
- const index = nextIndex++;
523
- const file = files[index];
524
- if (!file)
525
- return;
526
- let task;
527
- task = buildSessionInfo(file)
528
- .then((info) => {
529
- results[index] = info;
530
- })
531
- .catch(() => {
532
- results[index] = null;
533
- })
534
- .finally(() => {
535
- inFlight.delete(task);
536
- onLoaded();
537
- });
538
- inFlight.add(task);
539
- };
540
- while (nextIndex < files.length || inFlight.size > 0) {
541
- while (nextIndex < files.length && inFlight.size < MAX_CONCURRENT_SESSION_INFO_LOADS) {
542
- startNext();
543
- }
544
- if (inFlight.size > 0) {
545
- await Promise.race(inFlight);
529
+ const worker = async () => {
530
+ while (nextIndex < items.length) {
531
+ signal?.throwIfAborted();
532
+ const index = nextIndex++;
533
+ results[index] = await map(items[index], index);
546
534
  }
547
- }
535
+ };
536
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
548
537
  return results;
549
538
  }
550
- async function listSessionsFromDir(dir, onProgress, progressOffset = 0, progressTotal) {
551
- const sessions = [];
552
- if (!existsSync(dir)) {
553
- return sessions;
554
- }
539
+ function sortSessionInfos(sessions) {
540
+ return sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());
541
+ }
542
+ function buildSessionInfosWithConcurrency(files, onLoaded, signal) {
543
+ return mapWithConcurrency(files, MAX_CONCURRENT_SESSION_INFO_LOADS, async (file, index) => {
544
+ const info = await buildSessionInfo(file.path, signal, file.stats);
545
+ onLoaded(info, index);
546
+ return info;
547
+ }, signal);
548
+ }
549
+ async function listSessionsFromDir(dir, onProgress, signal) {
550
+ signal?.throwIfAborted();
551
+ if (!existsSync(dir))
552
+ return [];
555
553
  try {
556
554
  const dirEntries = await readdir(dir);
557
- const files = dirEntries.filter((f) => f.endsWith(".jsonl")).map((f) => join(dir, f));
558
- const total = progressTotal ?? files.length;
555
+ const files = dirEntries
556
+ .filter((file) => file.endsWith(".jsonl"))
557
+ .sort((a, b) => b.localeCompare(a))
558
+ .map((file) => ({ path: join(dir, file) }));
559
+ const total = files.length;
560
+ const partialSessions = [];
559
561
  let loaded = 0;
560
- const results = await buildSessionInfosWithConcurrency(files, () => {
562
+ const results = await buildSessionInfosWithConcurrency(files, (info) => {
561
563
  loaded++;
562
- onProgress?.(progressOffset + loaded, total);
563
- });
564
- for (const info of results) {
565
- if (info) {
566
- sessions.push(info);
567
- }
568
- }
564
+ if (info)
565
+ partialSessions.push(info);
566
+ const publishPartial = loaded === 1 || loaded % CURRENT_SESSION_LIST_PUBLISH_INTERVAL === 0 || loaded === files.length;
567
+ onProgress?.(loaded, total, publishPartial ? sortSessionInfos([...partialSessions]) : undefined);
568
+ }, signal);
569
+ return results.filter((info) => info !== null);
569
570
  }
570
571
  catch {
571
- // Return empty list on error
572
+ signal?.throwIfAborted();
573
+ return [];
572
574
  }
573
- return sessions;
574
575
  }
575
576
  /**
576
577
  * Manages conversation sessions as append-only trees stored in JSONL files.
@@ -814,19 +815,38 @@ export class SessionManager {
814
815
  this._appendEntry(entry);
815
816
  return entry.id;
816
817
  }
818
+ /** Append model-attributed usage that does not participate in LLM context. Returns the appended entry. */
819
+ appendUsage(kind, provider, model, usage, note) {
820
+ const entry = {
821
+ type: "usage",
822
+ id: generateId(this.byId),
823
+ parentId: this.leafId,
824
+ timestamp: new Date().toISOString(),
825
+ kind,
826
+ provider,
827
+ model,
828
+ usage,
829
+ ...(note ? { note } : {}),
830
+ };
831
+ this._appendEntry(entry);
832
+ return entry;
833
+ }
817
834
  /** Append a compaction summary as child of current leaf, then advance leaf. Returns entry id. */
818
835
  appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromHook, usage) {
836
+ const timestamp = new Date().toISOString();
837
+ const systemMessage = getCurrentSystemMessage(this.buildSessionContext().messages);
819
838
  const entry = {
820
839
  type: "compaction",
821
840
  id: generateId(this.byId),
822
841
  parentId: this.leafId,
823
- timestamp: new Date().toISOString(),
842
+ timestamp,
824
843
  summary,
825
844
  firstKeptEntryId,
826
845
  tokensBefore,
827
846
  details,
828
847
  usage,
829
848
  fromHook,
849
+ ...(systemMessage ? { systemMessage: { ...systemMessage, timestamp: new Date(timestamp).getTime() } } : {}),
830
850
  };
831
851
  this._appendEntry(entry);
832
852
  return entry.id;
@@ -1302,67 +1322,110 @@ export class SessionManager {
1302
1322
  }
1303
1323
  return new SessionManager(resolvedTargetCwd, dir, newSessionFile, true);
1304
1324
  }
1325
+ /**
1326
+ * Find an exact session ID without loading transcript bodies.
1327
+ * @param cwd Working directory (used to compute default session directory)
1328
+ * @param id Exact session ID
1329
+ * @param sessionDir Optional session directory. If omitted, uses default (~/.pi/agent/sessions/<encoded-cwd>/).
1330
+ */
1331
+ static findById(cwd, id, sessionDir) {
1332
+ const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);
1333
+ const filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd);
1334
+ const resolvedCwd = resolvePath(cwd);
1335
+ try {
1336
+ for (const file of readdirSync(dir)) {
1337
+ if (!file.endsWith(".jsonl"))
1338
+ continue;
1339
+ const path = join(dir, file);
1340
+ const header = readSessionHeaderForDiscovery(path);
1341
+ if (header?.id !== id)
1342
+ continue;
1343
+ if (filterCwd && !sessionCwdMatches(getSessionHeaderCwd(header), resolvedCwd))
1344
+ continue;
1345
+ return path;
1346
+ }
1347
+ }
1348
+ catch {
1349
+ // Exact session discovery is best-effort, matching list().
1350
+ }
1351
+ return undefined;
1352
+ }
1305
1353
  /**
1306
1354
  * List all sessions for a directory.
1307
1355
  * @param cwd Working directory (used to compute default session directory)
1308
1356
  * @param sessionDir Optional session directory. If omitted, uses default (~/.pi/agent/sessions/<encoded-cwd>/).
1309
1357
  * @param onProgress Optional callback for progress updates (loaded, total)
1310
1358
  */
1311
- static async list(cwd, sessionDir, onProgress) {
1359
+ static async list(cwd, sessionDir, onProgress, signal) {
1312
1360
  const dir = sessionDir ? normalizePath(sessionDir) : getDefaultSessionDir(cwd);
1313
1361
  const filterCwd = sessionDir !== undefined && dir !== getDefaultSessionDirPath(cwd);
1314
1362
  const resolvedCwd = resolvePath(cwd);
1315
- const sessions = (await listSessionsFromDir(dir, onProgress)).filter((session) => !filterCwd || sessionCwdMatches(session.cwd, resolvedCwd));
1316
- sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());
1317
- return sessions;
1318
- }
1319
- static async listAll(sessionDirOrOnProgress, onProgress) {
1363
+ const includeSession = (session) => !filterCwd || sessionCwdMatches(session.cwd, resolvedCwd);
1364
+ const progress = onProgress
1365
+ ? (loaded, total, partialSessions) => onProgress(loaded, total, partialSessions?.filter(includeSession))
1366
+ : undefined;
1367
+ const sessions = (await listSessionsFromDir(dir, progress, signal)).filter(includeSession);
1368
+ return sortSessionInfos(sessions);
1369
+ }
1370
+ static async listAll(sessionDirOrOnProgress, onProgressOrSignal, signal) {
1320
1371
  const customSessionDir = typeof sessionDirOrOnProgress === "string" ? normalizePath(sessionDirOrOnProgress) : undefined;
1321
- const progress = typeof sessionDirOrOnProgress === "function" ? sessionDirOrOnProgress : onProgress;
1372
+ const progress = typeof sessionDirOrOnProgress === "function"
1373
+ ? sessionDirOrOnProgress
1374
+ : typeof onProgressOrSignal === "function"
1375
+ ? onProgressOrSignal
1376
+ : undefined;
1377
+ const abortSignal = typeof sessionDirOrOnProgress === "string" || typeof onProgressOrSignal === "function"
1378
+ ? signal
1379
+ : (onProgressOrSignal ?? signal);
1380
+ abortSignal?.throwIfAborted();
1322
1381
  if (customSessionDir) {
1323
- const sessions = await listSessionsFromDir(customSessionDir, progress);
1324
- sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());
1325
- return sessions;
1382
+ return sortSessionInfos(await listSessionsFromDir(customSessionDir, progress, abortSignal));
1326
1383
  }
1327
1384
  const sessionsDir = getSessionsDir();
1328
1385
  try {
1329
- if (!existsSync(sessionsDir)) {
1386
+ if (!existsSync(sessionsDir))
1330
1387
  return [];
1331
- }
1332
1388
  const entries = await readdir(sessionsDir, { withFileTypes: true });
1333
1389
  const dirs = entries
1334
1390
  .filter((entry) => entry.isDirectory() || entry.isSymbolicLink())
1335
1391
  .map((entry) => join(sessionsDir, entry.name));
1336
- // Count total files first for accurate progress
1337
- let totalFiles = 0;
1338
- const dirFiles = [];
1339
- for (const dir of dirs) {
1392
+ const dirFiles = await mapWithConcurrency(dirs, MAX_CONCURRENT_SESSION_DISCOVERY_LOADS, async (dir) => {
1340
1393
  try {
1341
- const files = (await readdir(dir)).filter((f) => f.endsWith(".jsonl"));
1342
- dirFiles.push(files.map((f) => join(dir, f)));
1343
- totalFiles += files.length;
1394
+ return (await readdir(dir)).filter((file) => file.endsWith(".jsonl")).map((file) => join(dir, file));
1344
1395
  }
1345
1396
  catch {
1346
- dirFiles.push([]);
1397
+ return [];
1347
1398
  }
1348
- }
1349
- // Process all files with progress tracking
1350
- let loaded = 0;
1351
- const sessions = [];
1399
+ }, abortSignal);
1352
1400
  const allFiles = dirFiles.flat();
1353
- const results = await buildSessionInfosWithConcurrency(allFiles, () => {
1354
- loaded++;
1355
- progress?.(loaded, totalFiles);
1356
- });
1357
- for (const info of results) {
1358
- if (info) {
1359
- sessions.push(info);
1401
+ const candidates = await mapWithConcurrency(allFiles, MAX_CONCURRENT_SESSION_DISCOVERY_LOADS, async (path) => {
1402
+ try {
1403
+ return { path, stats: await stat(path) };
1360
1404
  }
1361
- }
1362
- sessions.sort((a, b) => b.modified.getTime() - a.modified.getTime());
1363
- return sessions;
1405
+ catch {
1406
+ return { path };
1407
+ }
1408
+ }, abortSignal);
1409
+ candidates.sort((a, b) => (b.stats?.mtimeMs ?? Number.NEGATIVE_INFINITY) - (a.stats?.mtimeMs ?? Number.NEGATIVE_INFINITY) ||
1410
+ basename(b.path).localeCompare(basename(a.path)));
1411
+ const totalFiles = candidates.length;
1412
+ let loaded = 0;
1413
+ let firstCandidateLoaded = false;
1414
+ const partialSessions = [];
1415
+ const results = await buildSessionInfosWithConcurrency(candidates, (info, index) => {
1416
+ loaded++;
1417
+ if (index === 0)
1418
+ firstCandidateLoaded = true;
1419
+ if (info)
1420
+ partialSessions.push(info);
1421
+ const publishPartial = firstCandidateLoaded &&
1422
+ (index === 0 || loaded % ALL_SESSION_LIST_PUBLISH_INTERVAL === 0 || loaded === totalFiles);
1423
+ progress?.(loaded, totalFiles, publishPartial ? sortSessionInfos([...partialSessions]) : undefined);
1424
+ }, abortSignal);
1425
+ return sortSessionInfos(results.filter((info) => info !== null));
1364
1426
  }
1365
1427
  catch {
1428
+ abortSignal?.throwIfAborted();
1366
1429
  return [];
1367
1430
  }
1368
1431
  }