@adhdev/daemon-core 0.9.82-rc.31 → 0.9.82-rc.310

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 (293) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +8 -0
  2. package/dist/boot/process-hardening.d.ts +50 -0
  3. package/dist/build-info.d.ts +37 -0
  4. package/dist/chat/source-machine.d.ts +166 -0
  5. package/dist/chat/source-resolver.d.ts +104 -0
  6. package/dist/chat/subscription-updates.d.ts +1 -0
  7. package/dist/cli-adapter-types.d.ts +23 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +198 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +106 -63
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  12. package/dist/cli-adapters/provider-cli-shared.d.ts +38 -0
  13. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  14. package/dist/cli-adapters/resolve-executable.d.ts +14 -0
  15. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  16. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  17. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  18. package/dist/commands/cli-manager.d.ts +2 -1
  19. package/dist/commands/handler.d.ts +110 -0
  20. package/dist/commands/mesh-coordinator.d.ts +85 -1
  21. package/dist/commands/router.d.ts +210 -1
  22. package/dist/config/chat-history.d.ts +9 -0
  23. package/dist/config/config.d.ts +5 -0
  24. package/dist/config/mesh-config.d.ts +72 -1
  25. package/dist/git/git-commands.d.ts +9 -1
  26. package/dist/git/git-diff.d.ts +6 -0
  27. package/dist/git/git-executor.d.ts +11 -0
  28. package/dist/git/git-status.d.ts +9 -0
  29. package/dist/git/git-types.d.ts +2 -50
  30. package/dist/index.d.ts +51 -12
  31. package/dist/index.js +38320 -16024
  32. package/dist/index.js.map +1 -1
  33. package/dist/index.mjs +38009 -15817
  34. package/dist/index.mjs.map +1 -1
  35. package/dist/installer.d.ts +1 -4
  36. package/dist/ipc/local-ipc-server.d.ts +91 -0
  37. package/dist/launch.d.ts +1 -1
  38. package/dist/logging/async-batch-writer.d.ts +10 -0
  39. package/dist/mesh/contracts.d.ts +164 -0
  40. package/dist/mesh/coordinator-prompt.d.ts +36 -0
  41. package/dist/mesh/coordinator-registry.d.ts +59 -0
  42. package/dist/mesh/mesh-active-work.d.ts +108 -0
  43. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  44. package/dist/mesh/mesh-events-coordinator.d.ts +138 -0
  45. package/dist/mesh/mesh-events-pending.d.ts +45 -0
  46. package/dist/mesh/mesh-events-stale.d.ts +40 -0
  47. package/dist/mesh/mesh-events-utils.d.ts +47 -0
  48. package/dist/mesh/mesh-events.d.ts +6 -49
  49. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  50. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  51. package/dist/mesh/mesh-init.d.ts +86 -0
  52. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
  53. package/dist/mesh/mesh-ledger.d.ts +77 -1
  54. package/dist/mesh/mesh-missions.d.ts +116 -0
  55. package/dist/mesh/mesh-reconcile-loop.d.ts +7 -0
  56. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  57. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  58. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  59. package/dist/mesh/mesh-routing.d.ts +70 -0
  60. package/dist/mesh/mesh-runtime-store.d.ts +377 -0
  61. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  62. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  63. package/dist/mesh/mesh-work-queue.d.ts +181 -5
  64. package/dist/mesh/preview-freshness.d.ts +18 -0
  65. package/dist/mesh/refine-config.d.ts +215 -0
  66. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  67. package/dist/providers/acp-provider-instance.d.ts +2 -0
  68. package/dist/providers/approval-utils.d.ts +13 -0
  69. package/dist/providers/cli-provider-instance.d.ts +61 -3
  70. package/dist/providers/contracts.d.ts +130 -6
  71. package/dist/providers/external-sources.d.ts +71 -0
  72. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  73. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  74. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  75. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  76. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  77. package/dist/providers/native-history/index.d.ts +13 -0
  78. package/dist/providers/provider-instance-manager.d.ts +13 -0
  79. package/dist/providers/provider-instance.d.ts +13 -1
  80. package/dist/providers/provider-loader.d.ts +26 -4
  81. package/dist/providers/provider-trust.d.ts +31 -0
  82. package/dist/providers/read-chat-contract.d.ts +29 -0
  83. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  84. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
  85. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  86. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  87. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  88. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  89. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  90. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  91. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  92. package/dist/providers/sdk/v1/index.d.ts +30 -0
  93. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  94. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  95. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  96. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  97. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  98. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  99. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  100. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  101. package/dist/providers/spec/adapter.d.ts +59 -0
  102. package/dist/providers/spec/cli-adapter.d.ts +186 -0
  103. package/dist/providers/spec/evaluator.d.ts +23 -0
  104. package/dist/providers/spec/fsm-driver.d.ts +278 -0
  105. package/dist/providers/spec/fsm-evaluator.d.ts +72 -0
  106. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  107. package/dist/providers/spec/fsm-types.d.ts +128 -0
  108. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  109. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  110. package/dist/providers/spec/route.d.ts +4 -0
  111. package/dist/providers/spec/types.d.ts +144 -0
  112. package/dist/providers/transcript-v2.d.ts +176 -0
  113. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  114. package/dist/repo-mesh-types.d.ts +203 -13
  115. package/dist/sessions/registry.d.ts +6 -0
  116. package/dist/shared-types-extra.d.ts +2 -4
  117. package/dist/shared-types.d.ts +42 -1
  118. package/dist/status/normalize.d.ts +1 -1
  119. package/dist/status/normalize.js +1 -0
  120. package/dist/status/normalize.js.map +1 -1
  121. package/dist/status/normalize.mjs +1 -0
  122. package/dist/status/normalize.mjs.map +1 -1
  123. package/dist/status/reporter.d.ts +2 -0
  124. package/dist/status/snapshot.d.ts +1 -0
  125. package/dist/types.d.ts +5 -0
  126. package/package.json +7 -3
  127. package/src/agent-stream/poller.ts +2 -3
  128. package/src/boot/daemon-lifecycle.ts +55 -12
  129. package/src/boot/process-hardening.ts +89 -0
  130. package/src/build-info.ts +73 -0
  131. package/src/chat/source-machine.ts +534 -0
  132. package/src/chat/source-resolver.ts +0 -0
  133. package/src/chat/subscription-updates.ts +20 -1
  134. package/src/cli-adapter-types.d.ts +1 -0
  135. package/src/cli-adapter-types.ts +22 -2
  136. package/src/cli-adapters/cli-script-runner.ts +421 -0
  137. package/src/cli-adapters/cli-state-engine.ts +1215 -0
  138. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  139. package/src/cli-adapters/provider-cli-adapter.ts +674 -1139
  140. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  141. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  142. package/src/cli-adapters/provider-cli-runtime.ts +3 -1
  143. package/src/cli-adapters/provider-cli-shared.d.ts +2 -0
  144. package/src/cli-adapters/provider-cli-shared.ts +68 -11
  145. package/src/cli-adapters/pty-transport.ts +2 -1
  146. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  147. package/src/cli-adapters/resolve-executable.ts +45 -0
  148. package/src/cli-adapters/session-host-transport.ts +2 -1
  149. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
  150. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  151. package/src/cli-adapters/terminal-screen.ts +16 -81
  152. package/src/commands/chat-commands.ts +1813 -60
  153. package/src/commands/cli-manager.ts +286 -14
  154. package/src/commands/handler.ts +809 -2
  155. package/src/commands/mesh-coordinator.ts +332 -122
  156. package/src/commands/router.ts +5911 -595
  157. package/src/commands/upgrade-helper.ts +29 -0
  158. package/src/config/chat-history.ts +474 -24
  159. package/src/config/config.ts +12 -0
  160. package/src/config/mesh-config.ts +303 -3
  161. package/src/config/recent-activity.ts +8 -2
  162. package/src/daemon/dev-auto-implement.ts +3 -2
  163. package/src/daemon/dev-cli-debug.ts +10 -1
  164. package/src/detection/ide-detector.ts +26 -16
  165. package/src/git/git-commands.ts +42 -12
  166. package/src/git/git-diff.ts +53 -0
  167. package/src/git/git-executor.ts +12 -0
  168. package/src/git/git-status.ts +302 -18
  169. package/src/git/git-types.ts +14 -62
  170. package/src/git/git-worktree.ts +8 -1
  171. package/src/index.ts +131 -11
  172. package/src/installer.d.ts +1 -1
  173. package/src/installer.ts +8 -6
  174. package/src/ipc/local-ipc-server.ts +278 -0
  175. package/src/launch.d.ts +1 -1
  176. package/src/launch.ts +37 -28
  177. package/src/logging/async-batch-writer.ts +55 -0
  178. package/src/logging/logger.ts +2 -1
  179. package/src/mesh/contracts.ts +329 -0
  180. package/src/mesh/coordinator-prompt.ts +234 -31
  181. package/src/mesh/coordinator-registry.ts +121 -0
  182. package/src/mesh/mesh-active-work.ts +469 -0
  183. package/src/mesh/mesh-delivery-policy.ts +315 -0
  184. package/src/mesh/mesh-events-coordinator.ts +1786 -0
  185. package/src/mesh/mesh-events-pending.ts +508 -0
  186. package/src/mesh/mesh-events-stale.ts +290 -0
  187. package/src/mesh/mesh-events-utils.ts +254 -0
  188. package/src/mesh/mesh-events.ts +30 -1035
  189. package/src/mesh/mesh-fast-forward.ts +839 -0
  190. package/src/mesh/mesh-host-ownership.ts +73 -0
  191. package/src/mesh/mesh-init.ts +260 -0
  192. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  193. package/src/mesh/mesh-ledger.ts +589 -102
  194. package/src/mesh/mesh-missions.ts +248 -0
  195. package/src/mesh/mesh-reconcile-loop.ts +466 -0
  196. package/src/mesh/mesh-refine-batch.ts +197 -0
  197. package/src/mesh/mesh-refine-status.ts +231 -0
  198. package/src/mesh/mesh-review-inbox.ts +307 -0
  199. package/src/mesh/mesh-routing.ts +291 -0
  200. package/src/mesh/mesh-runtime-store.ts +1513 -0
  201. package/src/mesh/mesh-task-stats.ts +154 -0
  202. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  203. package/src/mesh/mesh-work-queue.ts +604 -145
  204. package/src/mesh/preview-freshness.ts +118 -0
  205. package/src/mesh/refine-config.ts +403 -0
  206. package/src/mesh/worktree-bootstrap-config.ts +326 -0
  207. package/src/providers/acp-provider-instance.ts +15 -1
  208. package/src/providers/approval-utils.d.ts +4 -0
  209. package/src/providers/approval-utils.ts +47 -5
  210. package/src/providers/chat-message-normalization.ts +4 -11
  211. package/src/providers/cli-provider-instance.ts +953 -87
  212. package/src/providers/contracts.d.ts +55 -0
  213. package/src/providers/contracts.ts +141 -6
  214. package/src/providers/extension-provider-instance.ts +5 -1
  215. package/src/providers/external-sources.ts +218 -0
  216. package/src/providers/ide-provider-instance.ts +25 -6
  217. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  218. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  219. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  220. package/src/providers/native-history/dispatcher.ts +340 -0
  221. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  222. package/src/providers/native-history/index.ts +30 -0
  223. package/src/providers/provider-instance-manager.ts +30 -0
  224. package/src/providers/provider-instance.ts +10 -1
  225. package/src/providers/provider-loader.ts +584 -50
  226. package/src/providers/provider-schema.ts +87 -14
  227. package/src/providers/provider-trust.ts +114 -0
  228. package/src/providers/read-chat-contract.ts +76 -16
  229. package/src/providers/sdk/README.md +49 -0
  230. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  231. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  232. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  233. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  234. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  235. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  236. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  237. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  238. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  239. package/src/providers/sdk/v1/index.ts +152 -0
  240. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  241. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  242. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  243. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  244. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  245. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  246. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  247. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  248. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  249. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  250. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  251. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  252. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  253. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  254. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  255. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  256. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  257. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  258. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  259. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  260. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  261. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  262. package/src/providers/sdk/v1/validators/index.ts +19 -0
  263. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  264. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  265. package/src/providers/spec/adapter.ts +155 -0
  266. package/src/providers/spec/cli-adapter.ts +838 -0
  267. package/src/providers/spec/evaluator.ts +345 -0
  268. package/src/providers/spec/fsm-driver.ts +875 -0
  269. package/src/providers/spec/fsm-evaluator.ts +255 -0
  270. package/src/providers/spec/fsm-loader.ts +112 -0
  271. package/src/providers/spec/fsm-types.ts +222 -0
  272. package/src/providers/spec/native-history-executor.ts +943 -0
  273. package/src/providers/spec/pre-launch-trust.ts +104 -0
  274. package/src/providers/spec/route.ts +51 -0
  275. package/src/providers/spec/types.ts +189 -0
  276. package/src/providers/transcript-v2.ts +567 -0
  277. package/src/providers/types/interactive-prompt.ts +536 -0
  278. package/src/providers/version-archive.ts +38 -20
  279. package/src/repo-mesh-types.ts +257 -13
  280. package/src/sessions/registry.ts +6 -0
  281. package/src/shared-types-extra.ts +2 -4
  282. package/src/shared-types.ts +45 -1
  283. package/src/status/builders.ts +26 -6
  284. package/src/status/normalize.ts +2 -0
  285. package/src/status/reporter.ts +15 -0
  286. package/src/status/snapshot.ts +84 -25
  287. package/src/system/host-memory.ts +29 -12
  288. package/src/types.ts +5 -0
  289. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  290. package/dist/mesh/mesh-sync.d.ts +0 -53
  291. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  292. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  293. package/src/mesh/mesh-sync.ts +0 -111
@@ -169,6 +169,34 @@ export function buildPinnedGlobalInstallCommand(options: {
169
169
  };
170
170
  }
171
171
 
172
+ /**
173
+ * Build an env for the `npm install` child whose PATH is prefixed with the
174
+ * directory of the node binary currently running this helper.
175
+ *
176
+ * npm runs lifecycle scripts (e.g. adhdev's `preinstall` Node-version guard) by
177
+ * spawning a bare `node`, which resolves from PATH — NOT from the node that runs
178
+ * npm. On Windows a machine can have several node installs (e.g. a standalone
179
+ * `C:\Program Files\nodejs` ahead of an nvm-managed node on PATH). Without this,
180
+ * the guard sees the wrong (unsupported) node version and aborts the upgrade,
181
+ * even though npm/adhdev actually run under a supported node. Pinning the
182
+ * running node's dir to the front of PATH makes lifecycle scripts use the same
183
+ * node as the install itself.
184
+ */
185
+ function buildInstallEnvWithNodeOnPath(baseEnv: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
186
+ // The Node-version guard this works around only fires on Windows, so scope the
187
+ // PATH rewrite to win32 — POSIX keeps its env untouched.
188
+ if (process.platform !== 'win32') return { ...baseEnv };
189
+ const nodeBinDir = path.dirname(process.execPath);
190
+ if (!nodeBinDir) return { ...baseEnv };
191
+ const env: NodeJS.ProcessEnv = { ...baseEnv };
192
+ // Windows env keys are case-insensitive and conventionally spelled `Path`;
193
+ // prepend to the existing key (whatever its case) to avoid creating a dupe.
194
+ const pathKey = Object.keys(env).find((k) => k.toLowerCase() === 'path') || 'PATH';
195
+ const current = env[pathKey] || '';
196
+ env[pathKey] = current ? `${nodeBinDir};${current}` : nodeBinDir;
197
+ return env;
198
+ }
199
+
172
200
  export function getNpmExecOptions(platform: NodeJS.Platform = process.platform): NpmExecOptions {
173
201
  if (platform === 'win32') {
174
202
  return { shell: false, windowsHide: true };
@@ -375,6 +403,7 @@ async function runDaemonUpgradeHelper(payload: DaemonUpgradeHelperPayload): Prom
375
403
  encoding: 'utf8',
376
404
  stdio: 'pipe',
377
405
  maxBuffer: 20 * 1024 * 1024,
406
+ env: buildInstallEnvWithNodeOnPath(),
378
407
  ...installCommand.execOptions,
379
408
  },
380
409
  );
@@ -58,6 +58,40 @@ const savedHistoryFileSummaryCache = new Map<string, SavedHistoryFileSummaryCach
58
58
  const savedHistoryBackgroundRefresh = new Set<string>();
59
59
  const savedHistoryRollupInFlight = new Set<string>();
60
60
 
61
+ // Bounded-tail read cache. The dashboard re-subscribes and polls hot sessions
62
+ // every ~2.5s; without a cache each poll re-reads/parses/sorts the whole
63
+ // conversation just to slice a small tail. We key on (type, sessionId,
64
+ // pagination args) plus the on-disk size+mtime signature so an UNCHANGED
65
+ // session returns the previously computed tail in O(1) and only re-reads when a
66
+ // new message is appended (signature changes). The map is bounded by a small
67
+ // LRU to keep memory flat regardless of how many sessions are touched.
68
+ interface BoundedTailCacheEntry {
69
+ signature: string;
70
+ result: { messages: HistoryMessage[]; hasMore: boolean };
71
+ }
72
+
73
+ const BOUNDED_TAIL_CACHE_MAX_ENTRIES = 64;
74
+ const boundedTailReadCache = new Map<string, BoundedTailCacheEntry>();
75
+
76
+ function readBoundedTailCache(key: string, signature: string): { messages: HistoryMessage[]; hasMore: boolean } | null {
77
+ const cached = boundedTailReadCache.get(key);
78
+ if (!cached || cached.signature !== signature) return null;
79
+ // Refresh LRU recency.
80
+ boundedTailReadCache.delete(key);
81
+ boundedTailReadCache.set(key, cached);
82
+ return cached.result;
83
+ }
84
+
85
+ function writeBoundedTailCache(key: string, signature: string, result: { messages: HistoryMessage[]; hasMore: boolean }): void {
86
+ boundedTailReadCache.delete(key);
87
+ boundedTailReadCache.set(key, { signature, result });
88
+ while (boundedTailReadCache.size > BOUNDED_TAIL_CACHE_MAX_ENTRIES) {
89
+ const oldest = boundedTailReadCache.keys().next().value;
90
+ if (oldest === undefined) break;
91
+ boundedTailReadCache.delete(oldest);
92
+ }
93
+ }
94
+
61
95
  interface HistoryMessage {
62
96
  ts: string; // ISO timestamp
63
97
  receivedAt: number; // epoch ms
@@ -1180,6 +1214,324 @@ function pageHistoryRecords(
1180
1214
  return { messages: sliced, hasMore: startInclusive > 0 };
1181
1215
  }
1182
1216
 
1217
+ // A finite tail request can be served by reading only the newest files instead
1218
+ // of the whole conversation. Treat very large limits (e.g. MAX_SAFE_INTEGER, or
1219
+ // anything past a generous ceiling) as a full-history request so restore/seed
1220
+ // callers keep their existing behavior.
1221
+ const BOUNDED_TAIL_MAX_LIMIT = 5_000;
1222
+ // Slack added to the requested window before sorting/dedup/collapse so the
1223
+ // boundary message at the top of the tail dedupes/collapses identically to a
1224
+ // full read. Modest and bounded — it only widens the parse window, not output.
1225
+ const BOUNDED_TAIL_SLACK = 50;
1226
+
1227
+ function isBoundedTailRequest(limit: number, offset: number, excludeRecentCount: number): boolean {
1228
+ const numericLimit = Number(limit);
1229
+ if (!Number.isFinite(numericLimit) || numericLimit <= 0) return false;
1230
+ if (numericLimit > BOUNDED_TAIL_MAX_LIMIT) return false;
1231
+ const numericOffset = Number(offset);
1232
+ const numericExclude = Number(excludeRecentCount);
1233
+ if (!Number.isFinite(numericOffset) || !Number.isFinite(numericExclude)) return false;
1234
+ return true;
1235
+ }
1236
+
1237
+ // Byte threshold below which a file is small enough that reading the whole
1238
+ // thing is cheaper than seeking. Reverse-seek pays off only on large files.
1239
+ const REVERSE_TAIL_SMALL_FILE_BYTES = 64 * 1024;
1240
+ // Chunk size for backward reads. We read the file tail one chunk at a time
1241
+ // (newest bytes first) until we have collected enough complete lines.
1242
+ const REVERSE_TAIL_CHUNK_BYTES = 64 * 1024;
1243
+
1244
+ // Per-(file path) incremental tail cache. A hot session's daily JSONL file grows
1245
+ // append-only while it generates; the size+mtime signature on the bounded-tail
1246
+ // read cache therefore invalidates on every append and forces a full re-read.
1247
+ // Here we keep the most recently decoded tail LINES for a file plus the byte
1248
+ // length we read them from. When the file has only grown (append-only: size
1249
+ // increased, the previously-read prefix is unchanged) we read just the new bytes
1250
+ // from `size` onward and splice them onto the retained tail — no full re-parse.
1251
+ // Truncation/rotation (size shrank, or a fresh inode) drops the entry and falls
1252
+ // back to a full reverse-seek.
1253
+ interface IncrementalTailCacheEntry {
1254
+ // File length (bytes) we have already consumed into `lines`.
1255
+ size: number;
1256
+ mtimeMs: number;
1257
+ // Decoded complete lines (oldest-first) covering at least the tail window.
1258
+ // Bounded to TAIL_LINES_RETAINED so memory stays flat for huge files.
1259
+ lines: string[];
1260
+ // True when `lines` is the entire file (head reached), so older pages can
1261
+ // trust that nothing precedes the retained window.
1262
+ coversWholeFile: boolean;
1263
+ }
1264
+
1265
+ // How many trailing lines we retain per file. The bounded-tail caller never
1266
+ // asks for more than BOUNDED_TAIL_MAX_LIMIT + slack; keep a generous multiple so
1267
+ // repeated reads at the same window are served incrementally.
1268
+ const TAIL_LINES_RETAINED = BOUNDED_TAIL_MAX_LIMIT + 2 * BOUNDED_TAIL_SLACK;
1269
+ const INCREMENTAL_TAIL_CACHE_MAX_ENTRIES = 64;
1270
+ const incrementalTailCache = new Map<string, IncrementalTailCacheEntry>();
1271
+
1272
+ function evictIncrementalTailCache(): void {
1273
+ while (incrementalTailCache.size > INCREMENTAL_TAIL_CACHE_MAX_ENTRIES) {
1274
+ const oldest = incrementalTailCache.keys().next().value;
1275
+ if (oldest === undefined) break;
1276
+ incrementalTailCache.delete(oldest);
1277
+ }
1278
+ }
1279
+
1280
+ // Split a Buffer into complete lines plus a leftover head fragment, partitioning
1281
+ // only on the newline byte (0x0A). 0x0A never appears inside a multibyte UTF-8
1282
+ // sequence, so decoding each complete byte segment is boundary-safe. The leftover
1283
+ // (bytes before the first newline) is returned undecoded so a caller stitching
1284
+ // chunks together never splits a multibyte char.
1285
+ function splitBufferLines(buf: Buffer): { head: Buffer; lines: string[] } {
1286
+ const lines: string[] = [];
1287
+ let lineEnd = buf.length;
1288
+ let firstNewline = -1;
1289
+ for (let i = buf.length - 1; i >= 0; i--) {
1290
+ if (buf[i] !== 0x0a) continue;
1291
+ if (i + 1 < lineEnd) {
1292
+ lines.push(buf.toString('utf-8', i + 1, lineEnd));
1293
+ }
1294
+ lineEnd = i;
1295
+ firstNewline = i;
1296
+ }
1297
+ // Lines were collected newest-first; restore oldest-first for the segment
1298
+ // that follows the first (lowest-index) newline.
1299
+ lines.reverse();
1300
+ const head = firstNewline >= 0 ? buf.subarray(0, firstNewline) : buf;
1301
+ return { head, lines };
1302
+ }
1303
+
1304
+ // Read the last bytes of a file, newest-first, until we have at least `needed`
1305
+ // complete lines (or reach the start of the file). Returns lines oldest-first and
1306
+ // whether the whole file was consumed. Boundary-safe: lines are cut on the
1307
+ // newline byte only, so multibyte UTF-8 chars are never split, and a trailing
1308
+ // partial line (no terminating newline) is preserved as a complete final line.
1309
+ function readReverseTailLines(filePath: string, needed: number): { lines: string[]; coversWholeFile: boolean; size: number; mtimeMs: number } {
1310
+ const fd = fs.openSync(filePath, 'r');
1311
+ try {
1312
+ const stat = fs.fstatSync(fd);
1313
+ const size = stat.size;
1314
+ let position = size;
1315
+ // `carry` holds bytes belonging to a line that straddles the current
1316
+ // chunk boundary (its start is in an older, not-yet-read chunk).
1317
+ let carry: Buffer = Buffer.alloc(0);
1318
+ const collected: string[] = [];
1319
+
1320
+ while (position > 0 && collected.length < needed) {
1321
+ const chunkSize = Math.min(REVERSE_TAIL_CHUNK_BYTES, position);
1322
+ position -= chunkSize;
1323
+ const chunk = Buffer.alloc(chunkSize);
1324
+ fs.readSync(fd, chunk, 0, chunkSize, position);
1325
+ const combined = carry.length ? Buffer.concat([chunk, carry]) : chunk;
1326
+ const { head, lines } = splitBufferLines(combined);
1327
+ // `head` is the (possibly partial) line whose start lies further back;
1328
+ // hold it for the next (older) chunk to complete.
1329
+ carry = head;
1330
+ // `lines` are oldest-first within this combined buffer; prepend them
1331
+ // ahead of what we already collected (which is strictly newer).
1332
+ for (let i = lines.length - 1; i >= 0; i--) {
1333
+ collected.push(lines[i]);
1334
+ }
1335
+ }
1336
+
1337
+ const reachedStart = position <= 0;
1338
+ if (reachedStart && carry.length) {
1339
+ // Leftover head at the start of the file is itself a complete line.
1340
+ collected.push(carry.toString('utf-8'));
1341
+ }
1342
+ // `collected` is newest-first; restore oldest-first.
1343
+ collected.reverse();
1344
+ return { lines: collected, coversWholeFile: reachedStart, size, mtimeMs: stat.mtimeMs };
1345
+ } finally {
1346
+ fs.closeSync(fd);
1347
+ }
1348
+ }
1349
+
1350
+ // Return the tail lines (oldest-first) for a single history file, reading as
1351
+ // little of the file as possible. Strategy:
1352
+ // - Small files: one readFileSync (seeking is not worth the syscalls).
1353
+ // - Large files: reverse byte-seek for the newest `needed` lines.
1354
+ // - Append-only growth since the last read: read only the appended bytes and
1355
+ // splice them onto the retained tail (no full re-parse) — this is what keeps
1356
+ // a hot, still-generating session cheap to poll.
1357
+ // `needed` is a soft floor; we may return more (whole small files / retained
1358
+ // window). Lines include any trailing partial (unterminated) final line.
1359
+ function readFileTailLines(filePath: string, needed: number): { lines: string[]; coversWholeFile: boolean } {
1360
+ let stat: fs.Stats;
1361
+ try {
1362
+ stat = fs.statSync(filePath);
1363
+ } catch {
1364
+ return { lines: [], coversWholeFile: true };
1365
+ }
1366
+ const size = stat.size;
1367
+ const mtimeMs = stat.mtimeMs;
1368
+ if (size === 0) {
1369
+ incrementalTailCache.delete(filePath);
1370
+ return { lines: [], coversWholeFile: true };
1371
+ }
1372
+
1373
+ const cached = incrementalTailCache.get(filePath);
1374
+ if (cached) {
1375
+ if (cached.size === size && cached.mtimeMs === mtimeMs) {
1376
+ // Unchanged since last read — reuse retained tail. Refresh LRU.
1377
+ incrementalTailCache.delete(filePath);
1378
+ incrementalTailCache.set(filePath, cached);
1379
+ if (cached.coversWholeFile || cached.lines.length >= needed) {
1380
+ return { lines: cached.lines, coversWholeFile: cached.coversWholeFile };
1381
+ }
1382
+ // Retained window is smaller than this request needs; fall through
1383
+ // to a fresh reverse-seek for the larger window.
1384
+ } else if (size > cached.size) {
1385
+ // Append-only growth: the prefix [0, cached.size) is assumed
1386
+ // unchanged (JSONL is append-only). Read just the new bytes and
1387
+ // stitch them — but verify the byte at cached.size-1 is still the
1388
+ // newline that terminated our last retained line, so a rewrite that
1389
+ // happens to grow the file (compaction) is detected and rejected.
1390
+ const incremental = tryIncrementalTailGrowth(filePath, cached, size, mtimeMs, needed);
1391
+ if (incremental) return { lines: incremental.lines, coversWholeFile: incremental.coversWholeFile };
1392
+ }
1393
+ // size shrank (truncation/rotation) or incremental failed → drop & reload.
1394
+ incrementalTailCache.delete(filePath);
1395
+ }
1396
+
1397
+ if (size <= REVERSE_TAIL_SMALL_FILE_BYTES) {
1398
+ let content: string;
1399
+ try {
1400
+ content = fs.readFileSync(filePath, 'utf-8');
1401
+ } catch {
1402
+ return { lines: [], coversWholeFile: true };
1403
+ }
1404
+ const lines = content.split('\n');
1405
+ // A trailing newline yields a final empty element; drop only that one so
1406
+ // an unterminated partial last line is still preserved.
1407
+ if (lines.length && lines[lines.length - 1] === '') lines.pop();
1408
+ storeIncrementalTailCache(filePath, size, mtimeMs, lines, true);
1409
+ return { lines, coversWholeFile: true };
1410
+ }
1411
+
1412
+ let result: { lines: string[]; coversWholeFile: boolean; size: number; mtimeMs: number };
1413
+ try {
1414
+ result = readReverseTailLines(filePath, needed);
1415
+ } catch {
1416
+ return { lines: [], coversWholeFile: true };
1417
+ }
1418
+ storeIncrementalTailCache(filePath, result.size, result.mtimeMs, result.lines, result.coversWholeFile);
1419
+ return { lines: result.lines, coversWholeFile: result.coversWholeFile };
1420
+ }
1421
+
1422
+ // Read appended bytes [cached.size, size) and splice them onto the retained tail.
1423
+ // Returns null if the prior byte is not a newline (the retained tail did not end
1424
+ // on a record boundary, e.g. the file was rewritten) so the caller can full-reload.
1425
+ function tryIncrementalTailGrowth(
1426
+ filePath: string,
1427
+ cached: IncrementalTailCacheEntry,
1428
+ size: number,
1429
+ mtimeMs: number,
1430
+ needed: number,
1431
+ ): { lines: string[]; coversWholeFile: boolean } | null {
1432
+ const fd = fs.openSync(filePath, 'r');
1433
+ try {
1434
+ // Confirm the byte ending the previously-read prefix is still a newline.
1435
+ if (cached.size > 0) {
1436
+ const boundary = Buffer.alloc(1);
1437
+ fs.readSync(fd, boundary, 0, 1, cached.size - 1);
1438
+ if (boundary[0] !== 0x0a) return null;
1439
+ }
1440
+ const appendedLength = size - cached.size;
1441
+ const appended = Buffer.alloc(appendedLength);
1442
+ fs.readSync(fd, appended, 0, appendedLength, cached.size);
1443
+ const newLines = appended.toString('utf-8').split('\n');
1444
+ if (newLines.length && newLines[newLines.length - 1] === '') newLines.pop();
1445
+ const merged = cached.lines.concat(newLines);
1446
+ // Keep memory flat: retain only the trailing window.
1447
+ const trimmed = merged.length > TAIL_LINES_RETAINED
1448
+ ? merged.slice(merged.length - TAIL_LINES_RETAINED)
1449
+ : merged;
1450
+ const coversWholeFile = cached.coversWholeFile && trimmed.length === merged.length;
1451
+ storeIncrementalTailCache(filePath, size, mtimeMs, trimmed, coversWholeFile);
1452
+ if (coversWholeFile || trimmed.length >= needed) {
1453
+ return { lines: trimmed, coversWholeFile };
1454
+ }
1455
+ // Should not happen (we only grew), but be safe.
1456
+ return { lines: trimmed, coversWholeFile };
1457
+ } catch {
1458
+ return null;
1459
+ } finally {
1460
+ fs.closeSync(fd);
1461
+ }
1462
+ }
1463
+
1464
+ function storeIncrementalTailCache(filePath: string, size: number, mtimeMs: number, lines: string[], coversWholeFile: boolean): void {
1465
+ const retained = lines.length > TAIL_LINES_RETAINED ? lines.slice(lines.length - TAIL_LINES_RETAINED) : lines;
1466
+ const covers = coversWholeFile && retained.length === lines.length;
1467
+ incrementalTailCache.delete(filePath);
1468
+ incrementalTailCache.set(filePath, { size, mtimeMs, lines: retained, coversWholeFile: covers });
1469
+ evictIncrementalTailCache();
1470
+ }
1471
+
1472
+ // Read newest-first only as many files as needed to cover the requested window
1473
+ // plus slack. listHistoryFiles already returns files reversed (newest-first), so
1474
+ // we accumulate (de-duped) candidates from the end and stop once we have enough,
1475
+ // then hand the bounded window to pageHistoryRecords in chronological order.
1476
+ function readBoundedTailRecords(
1477
+ agentType: string,
1478
+ dir: string,
1479
+ files: string[],
1480
+ needed: number,
1481
+ ): { records: HistoryMessage[]; readAllFiles: boolean } {
1482
+ const collected: HistoryMessage[] = [];
1483
+ const seen = new Set<string>();
1484
+ let readAllFiles = true;
1485
+
1486
+ for (let f = 0; f < files.length; f++) {
1487
+ const filePath = path.join(dir, files[f]);
1488
+ // Read only the file tail needed to top up the window — for a large
1489
+ // single-day file this seeks the last `needed` lines instead of parsing
1490
+ // the whole file. We re-derive the per-file floor each iteration from how
1491
+ // many records are still missing (plus slack so dedup at the boundary is
1492
+ // stable), capped at `needed`.
1493
+ const remaining = Math.max(0, needed - collected.length);
1494
+ const perFileNeeded = Math.min(needed, remaining + BOUNDED_TAIL_SLACK);
1495
+ const { lines, coversWholeFile } = readFileTailLines(filePath, perFileNeeded);
1496
+ // Walk this file's tail lines newest-first so we fill the tail window from
1497
+ // the bottom. seen-dedup keeps the same first-wins-by-newest semantics the
1498
+ // full read produced (files are processed newest-first there too).
1499
+ for (let i = lines.length - 1; i >= 0; i--) {
1500
+ const line = lines[i];
1501
+ if (!line) continue;
1502
+ try {
1503
+ const parsed = JSON.parse(line) as HistoryMessage;
1504
+ const sanitizedMessage = sanitizeHistoryMessage(agentType, parsed);
1505
+ if (!sanitizedMessage) continue;
1506
+ const hash = buildHistoryMessageHash(agentType, sanitizedMessage);
1507
+ if (seen.has(hash)) continue;
1508
+ seen.add(hash);
1509
+ collected.push(sanitizedMessage);
1510
+ } catch { /* skip invalid lines */ }
1511
+ }
1512
+ // If we only read this file's tail (its head was not reached), older
1513
+ // messages remain within this very file — the conversation is NOT fully
1514
+ // represented even if this is the last file, so hasMore must stay true.
1515
+ if (!coversWholeFile) {
1516
+ readAllFiles = false;
1517
+ break;
1518
+ }
1519
+ // Stop once we have the window AND there is at least one more file (so a
1520
+ // potential older boundary message exists). If this is the last file we
1521
+ // fall through and mark the whole history as read.
1522
+ if (collected.length >= needed && f < files.length - 1) {
1523
+ readAllFiles = false;
1524
+ break;
1525
+ }
1526
+ }
1527
+
1528
+ // collected is newest-first across the bounded window; restore chronological
1529
+ // (oldest-first) order before paging. pageHistoryRecords re-sorts by
1530
+ // receivedAt regardless, so this is purely for stable input ordering.
1531
+ collected.reverse();
1532
+ return { records: collected, readAllFiles };
1533
+ }
1534
+
1183
1535
  export function readChatHistory(
1184
1536
  agentType: string,
1185
1537
  offset: number = 0,
@@ -1196,6 +1548,33 @@ export function readChatHistory(
1196
1548
  // JSONL file list — filter by persistent history key when specified
1197
1549
  const files = listHistoryFiles(dir, historySessionId);
1198
1550
 
1551
+ const bounded = isBoundedTailRequest(limit, offset, excludeRecentCount);
1552
+
1553
+ if (bounded) {
1554
+ const fileSignatures = buildSavedHistoryFileSignatureMap(dir, files);
1555
+ const cacheKey = `${sanitized}\0${historySessionId || ''}\0${offset}\0${limit}\0${excludeRecentCount}\0${historyBehavior?.collapseConsecutiveAssistantTurns ? '1' : '0'}`;
1556
+ const signature = buildSavedHistoryCacheSignature(files, fileSignatures);
1557
+ const cached = readBoundedTailCache(cacheKey, signature);
1558
+ if (cached) return cached;
1559
+
1560
+ // Window large enough that the top boundary dedupes/collapses the same
1561
+ // as a full read. hasMore reflects whether older messages exist beyond
1562
+ // the window we actually read.
1563
+ const numericLimit = Math.max(1, Number(limit));
1564
+ const numericOffset = Math.max(0, Number(offset));
1565
+ const numericExclude = Math.max(0, Number(excludeRecentCount));
1566
+ const needed = numericLimit + numericOffset + numericExclude + Math.max(BOUNDED_TAIL_SLACK, numericLimit);
1567
+ const { records, readAllFiles } = readBoundedTailRecords(agentType, dir, files, needed);
1568
+ const result = pageHistoryRecords(agentType, records, offset, limit, excludeRecentCount, historyBehavior);
1569
+ // If we read every file, the conversation is fully represented in the
1570
+ // window and pageHistoryRecords' hasMore is authoritative. If we
1571
+ // stopped early there are older messages we never read, so hasMore
1572
+ // must stay true regardless of the in-window slice position.
1573
+ const boundedResult = readAllFiles ? result : { messages: result.messages, hasMore: true };
1574
+ writeBoundedTailCache(cacheKey, signature, boundedResult);
1575
+ return boundedResult;
1576
+ }
1577
+
1199
1578
  const allMessages: HistoryMessage[] = [];
1200
1579
  const seen = new Set<string>();
1201
1580
 
@@ -1345,7 +1724,16 @@ function rewriteCanonicalSavedHistory(agentType: string, historySessionId: strin
1345
1724
 
1346
1725
  export type ProviderNativeHistoryScripts = Record<string, ((input: any) => any) | undefined>;
1347
1726
 
1348
- type ProviderNativeHistoryReadResult = { records: HistoryMessage[]; sourcePath: string; sourceMtimeMs: number };
1727
+ type ProviderNativeHistoryReadResult = {
1728
+ records: HistoryMessage[];
1729
+ sourcePath: string;
1730
+ sourceMtimeMs: number;
1731
+ providerSessionId?: string;
1732
+ workspace?: string;
1733
+ nativeHistoryCoverage?: string;
1734
+ partialReason?: string;
1735
+ unavailableReason?: string;
1736
+ };
1349
1737
 
1350
1738
  function getNativeHistoryScriptName(canonicalHistory: ProviderCanonicalHistoryConfig | undefined, key: 'readSession' | 'listSessions'): string {
1351
1739
  const configured = canonicalHistory?.scripts?.[key];
@@ -1367,19 +1755,42 @@ function normalizeProviderNativeHistoryRecords(agentType: string, historySession
1367
1755
  if (!Array.isArray(records)) return [];
1368
1756
  const normalizedSessionId = normalizeSavedHistorySessionId(historySessionId);
1369
1757
  return records
1370
- .map((record: any) => sanitizeHistoryMessage(agentType, {
1371
- ts: typeof record?.ts === 'string' ? record.ts : new Date(Number(record?.receivedAt) || Date.now()).toISOString(),
1372
- receivedAt: Number(record?.receivedAt) || Date.parse(record?.ts || '') || Date.now(),
1373
- role: record?.role,
1374
- content: String(record?.content || ''),
1375
- kind: record?.kind || (record?.role === 'system' ? 'session_start' : 'standard'),
1376
- senderName: record?.senderName,
1377
- agent: agentType,
1378
- instanceId: record?.instanceId,
1379
- historySessionId: normalizeSavedHistorySessionId(record?.historySessionId || normalizedSessionId),
1380
- sessionTitle: record?.sessionTitle,
1381
- workspace: record?.workspace,
1382
- } as HistoryMessage))
1758
+ .map((record: any) => {
1759
+ const base: HistoryMessage = {
1760
+ ts: typeof record?.ts === 'string' ? record.ts : new Date(Number(record?.receivedAt) || Date.now()).toISOString(),
1761
+ receivedAt: Number(record?.receivedAt) || Date.parse(record?.ts || '') || Date.now(),
1762
+ role: record?.role,
1763
+ content: String(record?.content || ''),
1764
+ kind: record?.kind || (record?.role === 'system' ? 'session_start' : 'standard'),
1765
+ senderName: record?.senderName,
1766
+ agent: agentType,
1767
+ instanceId: record?.instanceId,
1768
+ historySessionId: normalizeSavedHistorySessionId(record?.historySessionId || normalizedSessionId),
1769
+ sessionTitle: record?.sessionTitle,
1770
+ workspace: record?.workspace,
1771
+ } as HistoryMessage;
1772
+ // (A2.3 v2 identity passthrough) — if the producer (native_history.js)
1773
+ // emitted v2 stable identity, keep it across the sanitize layer so
1774
+ // downstream (chat-commands.ts normalizeNativeHistoryMessages) sees
1775
+ // the producer's contract output instead of recomputing from index
1776
+ // and content hash. v1 producers without these fields are unaffected.
1777
+ if (typeof record?.providerUnitKey === 'string' && record.providerUnitKey) {
1778
+ (base as any).providerUnitKey = record.providerUnitKey;
1779
+ }
1780
+ if (typeof record?.bubbleId === 'string' && record.bubbleId) {
1781
+ (base as any).bubbleId = record.bubbleId;
1782
+ }
1783
+ if (typeof record?.sequence === 'number' && Number.isFinite(record.sequence)) {
1784
+ (base as any).sequence = record.sequence;
1785
+ }
1786
+ if (typeof record?._turnKey === 'string' && record._turnKey) {
1787
+ (base as any)._turnKey = record._turnKey;
1788
+ }
1789
+ if (typeof record?.bubbleState === 'string' && record.bubbleState) {
1790
+ (base as any).bubbleState = record.bubbleState;
1791
+ }
1792
+ return sanitizeHistoryMessage(agentType, base);
1793
+ })
1383
1794
  .filter(Boolean) as HistoryMessage[];
1384
1795
  }
1385
1796
 
@@ -1387,27 +1798,41 @@ function callProviderNativeHistoryRead(
1387
1798
  agentType: string,
1388
1799
  canonicalHistory: ProviderCanonicalHistoryConfig | undefined,
1389
1800
  scripts: ProviderNativeHistoryScripts | undefined,
1390
- historySessionId: string,
1801
+ historySessionId: string | undefined,
1391
1802
  workspace?: string,
1803
+ excludeInProgressTurn?: boolean,
1804
+ sessionStartedAtMs?: number,
1805
+ envOverrides?: Record<string, string>,
1806
+ forceRefresh?: boolean,
1392
1807
  ): ProviderNativeHistoryReadResult | null {
1393
1808
  const fn = getProviderNativeHistoryScript(scripts, canonicalHistory, 'readSession');
1394
1809
  if (!fn) return null;
1810
+ const normalizedSessionId = normalizeSavedHistorySessionId(historySessionId || '');
1395
1811
  const result = fn({
1396
1812
  agentType,
1397
- sessionId: historySessionId,
1398
- historySessionId,
1813
+ sessionId: normalizedSessionId,
1814
+ historySessionId: normalizedSessionId,
1399
1815
  workspace,
1400
1816
  format: canonicalHistory?.format,
1401
1817
  watchPath: canonicalHistory?.watchPath,
1402
- args: { sessionId: historySessionId, historySessionId, workspace },
1818
+ excludeInProgressTurn: excludeInProgressTurn === true,
1819
+ sessionStartedAtMs,
1820
+ envOverrides,
1821
+ forceRefresh: forceRefresh === true,
1822
+ args: { sessionId: normalizedSessionId, historySessionId: normalizedSessionId, workspace, excludeInProgressTurn: excludeInProgressTurn === true, sessionStartedAtMs, envOverrides, forceRefresh: forceRefresh === true },
1403
1823
  });
1404
1824
  if (!result || typeof result !== 'object') return null;
1405
- const records = normalizeProviderNativeHistoryRecords(agentType, historySessionId, (result as any).messages || (result as any).records);
1825
+ const records = normalizeProviderNativeHistoryRecords(agentType, normalizedSessionId, (result as any).messages || (result as any).records);
1406
1826
  if (records.length === 0) return null;
1407
1827
  return {
1408
1828
  records,
1409
1829
  sourcePath: typeof (result as any).sourcePath === 'string' ? (result as any).sourcePath : '',
1410
1830
  sourceMtimeMs: Number((result as any).sourceMtimeMs) || 0,
1831
+ providerSessionId: typeof (result as any).providerSessionId === 'string' ? (result as any).providerSessionId.trim() : undefined,
1832
+ workspace: typeof (result as any).workspace === 'string' ? (result as any).workspace.trim() : undefined,
1833
+ nativeHistoryCoverage: typeof (result as any).nativeHistoryCoverage === 'string' ? (result as any).nativeHistoryCoverage.trim() : undefined,
1834
+ partialReason: typeof (result as any).partialReason === 'string' ? (result as any).partialReason.trim() : undefined,
1835
+ unavailableReason: typeof (result as any).unavailableReason === 'string' ? (result as any).unavailableReason.trim() : undefined,
1411
1836
  };
1412
1837
  }
1413
1838
 
@@ -1417,10 +1842,15 @@ function buildNativeHistoryReadResult(
1417
1842
  scripts: ProviderNativeHistoryScripts | undefined,
1418
1843
  historySessionId: string | undefined,
1419
1844
  workspace?: string,
1845
+ excludeInProgressTurn?: boolean,
1846
+ sessionStartedAtMs?: number,
1847
+ envOverrides?: Record<string, string>,
1848
+ forceRefresh?: boolean,
1420
1849
  ): ProviderNativeHistoryReadResult | null {
1421
1850
  const normalizedSessionId = normalizeSavedHistorySessionId(historySessionId || '');
1422
- if (!canonicalHistory || !normalizedSessionId || !isNativeSourceCanonicalHistory(canonicalHistory)) return null;
1423
- return callProviderNativeHistoryRead(agentType, canonicalHistory, scripts, normalizedSessionId, workspace);
1851
+ const normalizedWorkspace = typeof workspace === 'string' ? workspace.trim() : '';
1852
+ if (!canonicalHistory || (!normalizedSessionId && !normalizedWorkspace) || !isNativeSourceCanonicalHistory(canonicalHistory)) return null;
1853
+ return callProviderNativeHistoryRead(agentType, canonicalHistory, scripts, normalizedSessionId, workspace, excludeInProgressTurn, sessionStartedAtMs, envOverrides, forceRefresh);
1424
1854
  }
1425
1855
 
1426
1856
  function materializeNativeHistoryToMirror(
@@ -1476,16 +1906,36 @@ export function readProviderChatHistory(
1476
1906
  excludeRecentCount?: number;
1477
1907
  historyBehavior?: ProviderHistoryBehavior;
1478
1908
  scripts?: ProviderNativeHistoryScripts;
1909
+ excludeInProgressTurn?: boolean;
1910
+ sessionStartedAtMs?: number;
1911
+ envOverrides?: Record<string, string>;
1912
+ forceRefresh?: boolean;
1479
1913
  } = {},
1480
- ): { messages: HistoryMessage[]; hasMore: boolean; source: 'provider-native' | 'adhdev-mirror' | 'native-unavailable'; sourcePath?: string; sourceMtimeMs?: number } {
1481
- if (isNativeSourceCanonicalHistory(options.canonicalHistory) && options.historySessionId) {
1482
- const nativeResult = buildNativeHistoryReadResult(agentType, options.canonicalHistory, options.scripts, options.historySessionId, options.workspace);
1914
+ ): {
1915
+ messages: HistoryMessage[];
1916
+ hasMore: boolean;
1917
+ source: 'provider-native' | 'adhdev-mirror' | 'native-unavailable';
1918
+ sourcePath?: string;
1919
+ sourceMtimeMs?: number;
1920
+ providerSessionId?: string;
1921
+ workspace?: string;
1922
+ nativeHistoryCoverage?: string;
1923
+ partialReason?: string;
1924
+ unavailableReason?: string;
1925
+ } {
1926
+ if (isNativeSourceCanonicalHistory(options.canonicalHistory) && (options.historySessionId || options.workspace)) {
1927
+ const nativeResult = buildNativeHistoryReadResult(agentType, options.canonicalHistory, options.scripts, options.historySessionId, options.workspace, options.excludeInProgressTurn, options.sessionStartedAtMs, options.envOverrides, options.forceRefresh);
1483
1928
  if (!nativeResult) return { messages: [], hasMore: false, source: 'native-unavailable' };
1484
1929
  return {
1485
1930
  ...pageHistoryRecords(agentType, nativeResult.records, options.offset || 0, options.limit || 30, options.excludeRecentCount || 0, options.historyBehavior),
1486
1931
  source: 'provider-native',
1487
1932
  sourcePath: nativeResult.sourcePath,
1488
1933
  sourceMtimeMs: nativeResult.sourceMtimeMs,
1934
+ providerSessionId: nativeResult.providerSessionId,
1935
+ workspace: nativeResult.workspace,
1936
+ nativeHistoryCoverage: nativeResult.nativeHistoryCoverage,
1937
+ partialReason: nativeResult.partialReason,
1938
+ unavailableReason: nativeResult.unavailableReason,
1489
1939
  };
1490
1940
  }
1491
1941
  return {
@@ -272,6 +272,18 @@ export function getConfigDir(): string {
272
272
  return dir;
273
273
  }
274
274
 
275
+ /**
276
+ * Get the daemon runtime data directory (~/.adhdev/daemon/).
277
+ * Distinct from the user-config dir so runtime state can be cleared independently.
278
+ */
279
+ export function getDaemonDataDir(): string {
280
+ const dir = join(getConfigDir(), 'daemon');
281
+ if (!existsSync(dir)) {
282
+ mkdirSync(dir, { recursive: true });
283
+ }
284
+ return dir;
285
+ }
286
+
275
287
  /**
276
288
  * Get the config file path
277
289
  */