@adhdev/daemon-core 0.9.82-rc.43 → 0.9.82-rc.430

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 (425) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +9 -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 +68 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +200 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +126 -64
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +5 -0
  12. package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
  13. package/dist/cli-adapters/provider-cli-shared.d.ts +74 -0
  14. package/dist/cli-adapters/pty-write-chunking.d.ts +34 -0
  15. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  16. package/dist/cli-adapters/resolve-executable.d.ts +69 -0
  17. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  18. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  19. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  20. package/dist/commands/chat-commands-debug-bundle.d.ts +14 -0
  21. package/dist/commands/chat-commands-read.d.ts +7 -0
  22. package/dist/commands/chat-commands-scope.d.ts +39 -0
  23. package/dist/commands/chat-commands-shared.d.ts +33 -0
  24. package/dist/commands/chat-commands-write.d.ts +14 -0
  25. package/dist/commands/chat-commands.d.ts +10 -23
  26. package/dist/commands/cli-manager.d.ts +15 -1
  27. package/dist/commands/handler.d.ts +125 -0
  28. package/dist/commands/high-family/index.d.ts +3 -0
  29. package/dist/commands/high-family/mesh-coordinator-launch.d.ts +2 -0
  30. package/dist/commands/high-family/mesh-events.d.ts +2 -0
  31. package/dist/commands/high-family/mesh-status.d.ts +2 -0
  32. package/dist/commands/high-family/types.d.ts +60 -0
  33. package/dist/commands/low-family/coordinator-prompt.d.ts +9 -0
  34. package/dist/commands/low-family/daemon-lifecycle.d.ts +2 -0
  35. package/dist/commands/low-family/diagnostics.d.ts +2 -0
  36. package/dist/commands/low-family/index.d.ts +3 -0
  37. package/dist/commands/low-family/mesh-ledger.d.ts +10 -0
  38. package/dist/commands/low-family/mesh-node-logs.d.ts +2 -0
  39. package/dist/commands/low-family/notification.d.ts +2 -0
  40. package/dist/commands/low-family/refine-config.d.ts +2 -0
  41. package/dist/commands/low-family/session-host.d.ts +2 -0
  42. package/dist/commands/low-family/spec-providerdev.d.ts +11 -0
  43. package/dist/commands/low-family/status-meta.d.ts +2 -0
  44. package/dist/commands/low-family/types.d.ts +33 -0
  45. package/dist/commands/med-family/cli-agent.d.ts +2 -0
  46. package/dist/commands/med-family/fast-forward.d.ts +2 -0
  47. package/dist/commands/med-family/ide.d.ts +10 -0
  48. package/dist/commands/med-family/index.d.ts +3 -0
  49. package/dist/commands/med-family/mesh-crud.d.ts +29 -0
  50. package/dist/commands/med-family/mesh-host-pairing.d.ts +2 -0
  51. package/dist/commands/med-family/mesh-queue.d.ts +2 -0
  52. package/dist/commands/med-family/mesh-restart.d.ts +2 -0
  53. package/dist/commands/med-family/types.d.ts +142 -0
  54. package/dist/commands/mesh-coordinator.d.ts +85 -1
  55. package/dist/commands/router.d.ts +276 -2
  56. package/dist/commands/upgrade-helper.d.ts +41 -1
  57. package/dist/config/chat-history.d.ts +9 -0
  58. package/dist/config/config.d.ts +5 -0
  59. package/dist/config/mesh-config.d.ts +100 -1
  60. package/dist/config/mesh-json-config.d.ts +199 -0
  61. package/dist/config/repo-settings.d.ts +77 -0
  62. package/dist/daemon/dev-server.d.ts +0 -2
  63. package/dist/detection/ide-detector.d.ts +13 -0
  64. package/dist/detection/win32-ide-version.d.ts +37 -0
  65. package/dist/git/change-impact-config.d.ts +159 -0
  66. package/dist/git/git-commands.d.ts +11 -1
  67. package/dist/git/git-diff.d.ts +6 -0
  68. package/dist/git/git-executor.d.ts +11 -0
  69. package/dist/git/git-status.d.ts +57 -0
  70. package/dist/git/git-types.d.ts +2 -50
  71. package/dist/git/git-worktree.d.ts +71 -1
  72. package/dist/git/index.d.ts +3 -1
  73. package/dist/index.d.ts +64 -14
  74. package/dist/index.js +49391 -19228
  75. package/dist/index.js.map +1 -1
  76. package/dist/index.mjs +48574 -18570
  77. package/dist/index.mjs.map +1 -1
  78. package/dist/installer.d.ts +1 -4
  79. package/dist/ipc/local-ipc-server.d.ts +91 -0
  80. package/dist/launch.d.ts +1 -1
  81. package/dist/logging/async-batch-writer.d.ts +10 -0
  82. package/dist/logging/log-redactor.d.ts +24 -0
  83. package/dist/logging/log-tail-reader.d.ts +81 -0
  84. package/dist/logging/logger.d.ts +1 -1
  85. package/dist/mesh/contracts.d.ts +164 -0
  86. package/dist/mesh/coordinator-prompt.d.ts +89 -0
  87. package/dist/mesh/coordinator-registry.d.ts +59 -0
  88. package/dist/mesh/mesh-active-work.d.ts +174 -0
  89. package/dist/mesh/mesh-clone-grace.d.ts +8 -0
  90. package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
  91. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  92. package/dist/mesh/mesh-event-classify.d.ts +5 -0
  93. package/dist/mesh/mesh-event-forwarding.d.ts +41 -0
  94. package/dist/mesh/mesh-event-trace.d.ts +21 -0
  95. package/dist/mesh/mesh-events-coordinator.d.ts +4 -0
  96. package/dist/mesh/mesh-events-pending.d.ts +69 -0
  97. package/dist/mesh/mesh-events-stale.d.ts +61 -0
  98. package/dist/mesh/mesh-events-utils.d.ts +75 -0
  99. package/dist/mesh/mesh-events.d.ts +6 -49
  100. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  101. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  102. package/dist/mesh/mesh-init.d.ts +86 -0
  103. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -4
  104. package/dist/mesh/mesh-ledger.d.ts +77 -1
  105. package/dist/mesh/mesh-magi-status.d.ts +63 -0
  106. package/dist/mesh/mesh-missions.d.ts +189 -0
  107. package/dist/mesh/mesh-node-identity.d.ts +289 -0
  108. package/dist/mesh/mesh-queue-assignment.d.ts +113 -0
  109. package/dist/mesh/mesh-reconcile-loop.d.ts +65 -0
  110. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  111. package/dist/mesh/mesh-refine-gates.d.ts +428 -0
  112. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  113. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  114. package/dist/mesh/mesh-routing.d.ts +70 -0
  115. package/dist/mesh/mesh-runtime-store.d.ts +450 -0
  116. package/dist/mesh/mesh-scheduling-runtime.d.ts +78 -0
  117. package/dist/mesh/mesh-task-inflight.d.ts +46 -0
  118. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  119. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  120. package/dist/mesh/mesh-warmup-deadline.d.ts +68 -0
  121. package/dist/mesh/mesh-work-queue.d.ts +290 -5
  122. package/dist/mesh/preview-freshness.d.ts +18 -0
  123. package/dist/mesh/refine-config.d.ts +216 -0
  124. package/dist/mesh/worktree-bootstrap-config.d.ts +145 -0
  125. package/dist/providers/acp-provider-instance.d.ts +5 -0
  126. package/dist/providers/approval-utils.d.ts +20 -0
  127. package/dist/providers/chat-message-normalization.d.ts +31 -1
  128. package/dist/providers/cli-provider-instance.d.ts +221 -3
  129. package/dist/providers/contracts.d.ts +139 -6
  130. package/dist/providers/external-sources.d.ts +71 -0
  131. package/dist/providers/manual-attendance.d.ts +63 -0
  132. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  133. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  134. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  135. package/dist/providers/native-history/constants.d.ts +12 -0
  136. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  137. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  138. package/dist/providers/native-history/index.d.ts +13 -0
  139. package/dist/providers/provider-instance-manager.d.ts +29 -0
  140. package/dist/providers/provider-instance.d.ts +23 -1
  141. package/dist/providers/provider-loader.d.ts +26 -4
  142. package/dist/providers/provider-trust.d.ts +31 -0
  143. package/dist/providers/read-chat-contract.d.ts +29 -0
  144. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  145. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
  146. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  147. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  148. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  149. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  150. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  151. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  152. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  153. package/dist/providers/sdk/v1/index.d.ts +30 -0
  154. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  155. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  156. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  157. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  158. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  159. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  160. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  161. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  162. package/dist/providers/spec/adapter.d.ts +91 -0
  163. package/dist/providers/spec/cli-adapter.d.ts +223 -0
  164. package/dist/providers/spec/evaluator.d.ts +45 -0
  165. package/dist/providers/spec/fsm-driver.d.ts +422 -0
  166. package/dist/providers/spec/fsm-evaluator.d.ts +76 -0
  167. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  168. package/dist/providers/spec/fsm-types.d.ts +174 -0
  169. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  170. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  171. package/dist/providers/spec/route.d.ts +4 -0
  172. package/dist/providers/spec/types.d.ts +222 -0
  173. package/dist/providers/status-monitor.d.ts +7 -7
  174. package/dist/providers/transcript-v2.d.ts +176 -0
  175. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  176. package/dist/providers/working-dir.d.ts +17 -0
  177. package/dist/repo-mesh-types.d.ts +501 -13
  178. package/dist/runtime-defaults.d.ts +2 -0
  179. package/dist/sessions/registry.d.ts +6 -0
  180. package/dist/shared-types-extra.d.ts +2 -4
  181. package/dist/shared-types.d.ts +59 -2
  182. package/dist/status/normalize.d.ts +1 -1
  183. package/dist/status/normalize.js +1 -0
  184. package/dist/status/normalize.js.map +1 -1
  185. package/dist/status/normalize.mjs +1 -0
  186. package/dist/status/normalize.mjs.map +1 -1
  187. package/dist/status/reporter.d.ts +2 -0
  188. package/dist/status/snapshot.d.ts +26 -0
  189. package/dist/system/hash.d.ts +8 -0
  190. package/dist/system/load-better-sqlite3.d.ts +21 -0
  191. package/dist/types.d.ts +5 -0
  192. package/package.json +7 -3
  193. package/src/agent-stream/poller.ts +2 -3
  194. package/src/agent-stream/provider-adapter.ts +1 -1
  195. package/src/boot/daemon-lifecycle.ts +63 -12
  196. package/src/boot/process-hardening.ts +89 -0
  197. package/src/build-info.ts +73 -0
  198. package/src/chat/source-machine.ts +534 -0
  199. package/src/chat/source-resolver.ts +0 -0
  200. package/src/chat/subscription-updates.ts +20 -1
  201. package/src/cli-adapter-types.d.ts +3 -1
  202. package/src/cli-adapter-types.ts +68 -2
  203. package/src/cli-adapters/cli-script-runner.ts +421 -0
  204. package/src/cli-adapters/cli-state-engine.ts +1246 -0
  205. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  206. package/src/cli-adapters/provider-cli-adapter.ts +914 -1144
  207. package/src/cli-adapters/provider-cli-parse.d.ts +2 -0
  208. package/src/cli-adapters/provider-cli-parse.ts +19 -0
  209. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  210. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  211. package/src/cli-adapters/provider-cli-shared.ts +121 -11
  212. package/src/cli-adapters/pty-transport.ts +2 -1
  213. package/src/cli-adapters/pty-write-chunking.ts +106 -0
  214. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  215. package/src/cli-adapters/resolve-executable.ts +204 -0
  216. package/src/cli-adapters/session-host-transport.ts +2 -1
  217. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +63 -29
  218. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  219. package/src/cli-adapters/terminal-screen.ts +16 -81
  220. package/src/commands/WINDOWS-UPGRADE-LOCK-FAILURE.md +198 -0
  221. package/src/commands/chat-commands-debug-bundle.ts +398 -0
  222. package/src/commands/chat-commands-read.ts +2327 -0
  223. package/src/commands/chat-commands-scope.ts +54 -0
  224. package/src/commands/chat-commands-shared.ts +114 -0
  225. package/src/commands/chat-commands-write.ts +891 -0
  226. package/src/commands/chat-commands.ts +19 -1841
  227. package/src/commands/cli-manager.ts +544 -26
  228. package/src/commands/handler.ts +841 -2
  229. package/src/commands/high-family/index.ts +28 -0
  230. package/src/commands/high-family/mesh-coordinator-launch.ts +678 -0
  231. package/src/commands/high-family/mesh-events.ts +80 -0
  232. package/src/commands/high-family/mesh-status.ts +710 -0
  233. package/src/commands/high-family/types.ts +76 -0
  234. package/src/commands/low-family/coordinator-prompt.ts +72 -0
  235. package/src/commands/low-family/daemon-lifecycle.ts +107 -0
  236. package/src/commands/low-family/diagnostics.ts +57 -0
  237. package/src/commands/low-family/index.ts +37 -0
  238. package/src/commands/low-family/mesh-ledger.ts +62 -0
  239. package/src/commands/low-family/mesh-node-logs.ts +87 -0
  240. package/src/commands/low-family/notification.ts +116 -0
  241. package/src/commands/low-family/refine-config.ts +106 -0
  242. package/src/commands/low-family/session-host.ts +274 -0
  243. package/src/commands/low-family/spec-providerdev.ts +217 -0
  244. package/src/commands/low-family/status-meta.ts +112 -0
  245. package/src/commands/low-family/types.ts +39 -0
  246. package/src/commands/med-family/cli-agent.ts +238 -0
  247. package/src/commands/med-family/fast-forward.ts +230 -0
  248. package/src/commands/med-family/ide.ts +163 -0
  249. package/src/commands/med-family/index.ts +37 -0
  250. package/src/commands/med-family/mesh-crud.ts +1066 -0
  251. package/src/commands/med-family/mesh-host-pairing.ts +234 -0
  252. package/src/commands/med-family/mesh-queue.ts +167 -0
  253. package/src/commands/med-family/mesh-restart.ts +92 -0
  254. package/src/commands/med-family/types.ts +143 -0
  255. package/src/commands/mesh-coordinator.ts +334 -124
  256. package/src/commands/router.ts +2711 -3254
  257. package/src/commands/stream-commands.ts +8 -0
  258. package/src/commands/upgrade-helper.ts +310 -45
  259. package/src/config/chat-history.ts +483 -24
  260. package/src/config/config.ts +12 -0
  261. package/src/config/mesh-config.ts +495 -22
  262. package/src/config/mesh-json-config.ts +376 -0
  263. package/src/config/recent-activity.ts +8 -2
  264. package/src/config/repo-settings.ts +111 -0
  265. package/src/daemon/dev-auto-implement.ts +3 -2
  266. package/src/daemon/dev-cli-debug.ts +10 -1
  267. package/src/daemon/dev-server.ts +0 -541
  268. package/src/detection/cli-detector.ts +28 -9
  269. package/src/detection/ide-detector.ts +55 -16
  270. package/src/detection/win32-ide-version.ts +106 -0
  271. package/src/git/change-impact-config.ts +354 -0
  272. package/src/git/git-commands.ts +59 -15
  273. package/src/git/git-diff.ts +81 -11
  274. package/src/git/git-executor.ts +12 -0
  275. package/src/git/git-status.ts +767 -48
  276. package/src/git/git-types.ts +14 -62
  277. package/src/git/git-worktree.ts +261 -4
  278. package/src/git/index.ts +17 -0
  279. package/src/index.ts +194 -12
  280. package/src/installer.d.ts +1 -1
  281. package/src/installer.ts +8 -6
  282. package/src/ipc/local-ipc-server.ts +278 -0
  283. package/src/launch.d.ts +1 -1
  284. package/src/launch.ts +37 -28
  285. package/src/logging/async-batch-writer.ts +55 -0
  286. package/src/logging/command-log.ts +7 -5
  287. package/src/logging/log-redactor.ts +100 -0
  288. package/src/logging/log-tail-reader.ts +341 -0
  289. package/src/logging/logger.ts +14 -7
  290. package/src/mesh/contracts.ts +338 -0
  291. package/src/mesh/coordinator-prompt.ts +381 -33
  292. package/src/mesh/coordinator-registry.ts +121 -0
  293. package/src/mesh/mesh-active-work.ts +645 -0
  294. package/src/mesh/mesh-clone-grace.ts +68 -0
  295. package/src/mesh/mesh-coordinator-config.ts +97 -0
  296. package/src/mesh/mesh-delivery-policy.ts +315 -0
  297. package/src/mesh/mesh-event-classify.ts +51 -0
  298. package/src/mesh/mesh-event-forwarding.ts +1888 -0
  299. package/src/mesh/mesh-event-trace.ts +67 -0
  300. package/src/mesh/mesh-events-coordinator.ts +32 -0
  301. package/src/mesh/mesh-events-pending.ts +656 -0
  302. package/src/mesh/mesh-events-stale.ts +389 -0
  303. package/src/mesh/mesh-events-utils.ts +443 -0
  304. package/src/mesh/mesh-events.ts +33 -1035
  305. package/src/mesh/mesh-fast-forward.ts +843 -0
  306. package/src/mesh/mesh-host-ownership.ts +73 -0
  307. package/src/mesh/mesh-init.ts +260 -0
  308. package/src/mesh/mesh-ledger-reconciliation.ts +12 -7
  309. package/src/mesh/mesh-ledger.ts +656 -102
  310. package/src/mesh/mesh-magi-status.ts +223 -0
  311. package/src/mesh/mesh-missions.ts +449 -0
  312. package/src/mesh/mesh-node-identity.ts +1887 -0
  313. package/src/mesh/mesh-queue-assignment.ts +1918 -0
  314. package/src/mesh/mesh-reconcile-loop.ts +1780 -0
  315. package/src/mesh/mesh-refine-batch.ts +205 -0
  316. package/src/mesh/mesh-refine-gates.ts +1673 -0
  317. package/src/mesh/mesh-refine-status.ts +231 -0
  318. package/src/mesh/mesh-review-inbox.ts +307 -0
  319. package/src/mesh/mesh-routing.ts +291 -0
  320. package/src/mesh/mesh-runtime-store.ts +1853 -0
  321. package/src/mesh/mesh-scheduling-runtime.ts +198 -0
  322. package/src/mesh/mesh-task-inflight.ts +70 -0
  323. package/src/mesh/mesh-task-stats.ts +161 -0
  324. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  325. package/src/mesh/mesh-warmup-deadline.ts +152 -0
  326. package/src/mesh/mesh-work-queue.ts +1243 -141
  327. package/src/mesh/preview-freshness.ts +118 -0
  328. package/src/mesh/refine-config.ts +423 -0
  329. package/src/mesh/worktree-bootstrap-config.ts +450 -0
  330. package/src/providers/acp-provider-instance.ts +43 -10
  331. package/src/providers/approval-utils.d.ts +5 -0
  332. package/src/providers/approval-utils.ts +57 -5
  333. package/src/providers/chat-message-normalization.ts +92 -4
  334. package/src/providers/cli-provider-instance.ts +1933 -104
  335. package/src/providers/contracts.d.ts +55 -0
  336. package/src/providers/contracts.ts +150 -6
  337. package/src/providers/extension-provider-instance.ts +12 -7
  338. package/src/providers/external-sources.ts +218 -0
  339. package/src/providers/ide-provider-instance.ts +35 -12
  340. package/src/providers/manual-attendance.ts +85 -0
  341. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  342. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  343. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  344. package/src/providers/native-history/constants.ts +19 -0
  345. package/src/providers/native-history/dispatcher.ts +339 -0
  346. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  347. package/src/providers/native-history/index.ts +30 -0
  348. package/src/providers/provider-instance-manager.ts +71 -0
  349. package/src/providers/provider-instance.ts +19 -1
  350. package/src/providers/provider-loader.ts +668 -50
  351. package/src/providers/provider-schema.ts +87 -14
  352. package/src/providers/provider-trust.ts +114 -0
  353. package/src/providers/read-chat-contract.ts +76 -16
  354. package/src/providers/sdk/README.md +49 -0
  355. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  356. package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
  357. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  358. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  359. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  360. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  361. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  362. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  363. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  364. package/src/providers/sdk/v1/index.ts +152 -0
  365. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  366. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  367. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  368. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  369. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  370. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  371. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  372. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  373. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  374. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  375. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  376. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  377. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  378. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  379. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  380. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  381. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  382. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  383. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  384. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  385. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  386. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  387. package/src/providers/sdk/v1/validators/index.ts +19 -0
  388. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  389. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  390. package/src/providers/spec/adapter.ts +235 -0
  391. package/src/providers/spec/cli-adapter.ts +1056 -0
  392. package/src/providers/spec/evaluator.ts +407 -0
  393. package/src/providers/spec/fsm-driver.ts +1410 -0
  394. package/src/providers/spec/fsm-evaluator.ts +272 -0
  395. package/src/providers/spec/fsm-loader.ts +120 -0
  396. package/src/providers/spec/fsm-types.ts +273 -0
  397. package/src/providers/spec/native-history-executor.ts +1128 -0
  398. package/src/providers/spec/pre-launch-trust.ts +104 -0
  399. package/src/providers/spec/route.ts +51 -0
  400. package/src/providers/spec/types.ts +262 -0
  401. package/src/providers/status-monitor.d.ts +7 -7
  402. package/src/providers/status-monitor.ts +37 -22
  403. package/src/providers/transcript-v2.ts +567 -0
  404. package/src/providers/types/interactive-prompt.ts +536 -0
  405. package/src/providers/version-archive.ts +64 -24
  406. package/src/providers/working-dir.ts +23 -0
  407. package/src/repo-mesh-types.ts +740 -14
  408. package/src/runtime-defaults.ts +39 -0
  409. package/src/sessions/registry.ts +6 -0
  410. package/src/shared-types-extra.ts +2 -4
  411. package/src/shared-types.d.ts +8 -0
  412. package/src/shared-types.ts +64 -1
  413. package/src/status/builders.ts +26 -6
  414. package/src/status/normalize.ts +2 -0
  415. package/src/status/reporter.ts +19 -1
  416. package/src/status/snapshot.ts +95 -26
  417. package/src/system/hash.ts +23 -0
  418. package/src/system/host-memory.ts +29 -12
  419. package/src/system/load-better-sqlite3.ts +68 -0
  420. package/src/types.ts +5 -0
  421. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  422. package/dist/mesh/mesh-sync.d.ts +0 -53
  423. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  424. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  425. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,1128 @@
1
+ /**
2
+ * Declarative native-history executor.
3
+ *
4
+ * Reads a spec.json's `native_history.source` block and turns it into a
5
+ * NativeHistoryResult by talking directly to the on-disk store (jsonl
6
+ * file or sqlite db). No per-provider TypeScript reader required —
7
+ * adding a new provider is just authoring spec.json.
8
+ *
9
+ * Two source kinds:
10
+ * - jsonl — newest matching file inside a path (with variable expansion)
11
+ * + jsonpath-lite map for each record
12
+ * - sqlite — read-only better-sqlite3 handle, two queries (session pick
13
+ * + message fetch) + jsonpath-lite map for each row
14
+ *
15
+ * Exotic formats can still ship a provider-local reader via
16
+ * `native_history.override_path` — the dispatcher in provider-loader picks
17
+ * that path instead of calling this executor.
18
+ */
19
+ 'use strict';
20
+
21
+ import * as fs from 'node:fs';
22
+ import * as os from 'node:os';
23
+ import * as path from 'node:path';
24
+ import { LOG } from '../../logging/logger.js';
25
+ import { loadBetterSqlite3 } from '../../system/load-better-sqlite3.js';
26
+ import type {
27
+ NativeHistoryConfig,
28
+ NativeHistoryJsonlSource,
29
+ NativeHistoryMessageMap,
30
+ NativeHistorySqliteSource,
31
+ NativeHistoryToolMap,
32
+ } from './types.js';
33
+ import { SPAWN_BIND_GRACE_MS } from '../native-history/constants.js';
34
+
35
+ export interface NativeHistoryInput {
36
+ agentType?: string;
37
+ sessionId?: string;
38
+ providerSessionId?: string;
39
+ historySessionId?: string;
40
+ workspace?: string;
41
+ /** Daemon-side wall clock at the moment the session was registered.
42
+ * Native-history file lookups use this as the lower bound: any file
43
+ * whose mtime is before the current session started can't be from
44
+ * this session, so it's excluded from newest-recent matching. The
45
+ * caller (chat-history pipeline) populates this from the session
46
+ * registry; specs/executor never need to know how it's sourced. */
47
+ sessionStartedAtMs?: number;
48
+ /** Env overrides the daemon set on the spawned CLI. The mesh
49
+ * coordinator points hermes at a per-coordinator HERMES_HOME so
50
+ * the hermes process writes its state.db into a tmp directory
51
+ * instead of ~/.hermes. expandPath consults this map before
52
+ * process.env so the native-history reader follows the spawned
53
+ * child's view of HERMES_HOME / similar overrides; without it
54
+ * the reader would always look at ~/.hermes and miss every
55
+ * coordinator-session transcript. */
56
+ envOverrides?: Record<string, string>;
57
+ args?: Record<string, unknown>;
58
+ }
59
+
60
+ export interface NativeHistoryMessage {
61
+ role: 'user' | 'assistant' | 'system';
62
+ content: string;
63
+ receivedAt: number;
64
+ kind?: string;
65
+ workspace?: string;
66
+ }
67
+
68
+ export interface NativeHistoryResult {
69
+ messages: NativeHistoryMessage[];
70
+ providerSessionId?: string;
71
+ sourcePath: string;
72
+ sourceMtimeMs: number;
73
+ nativeHistoryCoverage?: 'full' | 'partial' | 'best-effort';
74
+ workspace?: string;
75
+ }
76
+
77
+ const UUID_RE = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i;
78
+
79
+ export function executeNativeHistory(cfg: NativeHistoryConfig, input: NativeHistoryInput): NativeHistoryResult | null {
80
+ if (!cfg?.source) return null;
81
+ if (cfg.source.kind === 'jsonl') return executeJsonl(cfg.source, input);
82
+ if (cfg.source.kind === 'sqlite') return executeSqlite(cfg.source, input);
83
+ return null;
84
+ }
85
+
86
+ // ────────────────────────────────────────────────────────────────────────────
87
+ // JSONL
88
+ // ────────────────────────────────────────────────────────────────────────────
89
+
90
+ function executeJsonl(src: NativeHistoryJsonlSource, input: NativeHistoryInput): NativeHistoryResult | null {
91
+ const resolved = expandPath(src.path, input);
92
+ if (!resolved) return null;
93
+
94
+ const windowMs = typeof src.recent_window_ms === 'number' ? src.recent_window_ms : 5 * 60_000;
95
+ const filePat = src.file_pattern ? globToRegex(src.file_pattern) : /.*\.jsonl$/;
96
+ const requestedSessionId = readRequestedSessionId(input);
97
+
98
+ // path can be:
99
+ // - a concrete file → used as-is
100
+ // - a concrete dir → newest matching file inside recent_window_ms
101
+ // - a path with `*` or `**` segments → walk all dirs that match the
102
+ // glob, pick the newest matching file across all matches. Lets
103
+ // specs like ~/.gemini/antigravity-cli/brain/*/.system_generated/logs
104
+ // resolve transparently without a per-provider override.
105
+ // The session-start cutoff guarantees a fresh dashboard view can't
106
+ // pick up a transcript file from a session that ended before this
107
+ // one started. recent_window_ms only controls how far back we'd
108
+ // otherwise look for a matching file; the session-start floor wins
109
+ // when it's later.
110
+ const sessionFloor = typeof input.sessionStartedAtMs === 'number' ? input.sessionStartedAtMs : 0;
111
+ // When multiple concurrent CLI sessions in the same workspace each create
112
+ // their own rollout (e.g. two codex-cli sessions both writing into
113
+ // ~/.codex/sessions/{date}), `newestRecentFile` picks the same file for
114
+ // every reader and the daemon sessions cross-alias each other. Prefer
115
+ // session-meta-aware matching: the candidate whose meta.cwd matches the
116
+ // workspace AND whose meta.timestamp is closest to (or within
117
+ // spawnGraceMs of) the daemon's spawn time wins. Falls back to mtime
118
+ // ordering when no candidate exposes a usable session_meta.
119
+ const workspaceHint = typeof input.workspace === 'string' && input.workspace.trim() ? input.workspace.trim() : '';
120
+ let sourcePath: string | null = null;
121
+ if (resolved.includes('*')) {
122
+ sourcePath = pickExactSessionFileAcrossGlob(resolved, filePat, requestedSessionId)
123
+ || pickSessionBoundFileAcrossGlob(resolved, filePat, windowMs, sessionFloor, workspaceHint)
124
+ || newestRecentFileAcrossGlob(resolved, filePat, windowMs, sessionFloor);
125
+ } else {
126
+ let stat: fs.Stats | null = null;
127
+ try { stat = fs.statSync(resolved); } catch { /* fall through to date-walk fallback */ }
128
+ if (stat && stat.isFile()) {
129
+ sourcePath = resolved;
130
+ } else if (stat && stat.isDirectory()) {
131
+ sourcePath = pickExactSessionFile(resolved, filePat, requestedSessionId)
132
+ || (requestedSessionId ? null : pickSessionBoundFile(resolved, filePat, windowMs, sessionFloor, workspaceHint))
133
+ || (requestedSessionId ? null : newestRecentFile(resolved, filePat, windowMs, sessionFloor));
134
+ }
135
+ // Date-templated directories (e.g. ~/.codex/sessions/{yyyy}/{mm}/{dd})
136
+ // can drift from the provider's chosen calendar day because CLIs
137
+ // disagree on local-vs-UTC date buckets. Search nearby date dirs
138
+ // before falling back to non-exact matching.
139
+ if (!sourcePath && hasDateTemplateSegment(src.path)) {
140
+ sourcePath = pickExactSessionFileAcrossDateWindow(src.path, input, filePat, requestedSessionId)
141
+ || (requestedSessionId ? null : pickSessionBoundFileAcrossDateWindow(src.path, input, filePat, windowMs, sessionFloor, workspaceHint))
142
+ || (requestedSessionId ? null : newestRecentFileAcrossDateWindow(src.path, input, filePat, windowMs, sessionFloor));
143
+ }
144
+ // Raw-workspace slug candidate: `resolved` derives its {cwd*} slug from
145
+ // fs.realpathSync(workspace). On Windows realpath normalizes the path
146
+ // (drive-letter case D:↔d:, \\?\ long-path prefix, junction expansion)
147
+ // so the slug can diverge from the one the CLI actually wrote — and the
148
+ // concrete path above then misses with ENOENT. Retry with the slug built
149
+ // from the RAW workspace string before falling back to a scan; it's the
150
+ // cheap fix when realpath divergence is the only problem.
151
+ if (!sourcePath && !hasDateTemplateSegment(src.path)) {
152
+ const resolvedRaw = expandPath(src.path, input, { skipWorkspaceRealpath: true });
153
+ if (resolvedRaw && resolvedRaw !== resolved) {
154
+ try {
155
+ const rawStat = fs.statSync(resolvedRaw);
156
+ if (rawStat.isFile()) sourcePath = resolvedRaw;
157
+ else if (rawStat.isDirectory()) {
158
+ sourcePath = pickExactSessionFile(resolvedRaw, filePat, requestedSessionId)
159
+ || (requestedSessionId ? null : newestRecentFile(resolvedRaw, filePat, windowMs, sessionFloor));
160
+ }
161
+ } catch { /* raw slug also missed — fall through to scan */ }
162
+ }
163
+ }
164
+ // Last-resort scan: the slug-derived directory missed entirely (the
165
+ // dominant Windows failure: realpath/raw slug both diverge from the CLI's
166
+ // on-disk project dir → 0 messages, no PTY fallback for native-source
167
+ // providers). When we have an exact session id, walk the projects root
168
+ // for `<sessionId>.jsonl` regardless of which project subdir holds it.
169
+ // The session id is a UUID, so basename matching is unambiguous; mirrors
170
+ // the standalone reader's scan (claude-cli-transcript.ts resolveTranscriptPath).
171
+ if (!sourcePath && requestedSessionId) {
172
+ sourcePath = scanProjectsRootForSessionFile(src.path, input, requestedSessionId);
173
+ }
174
+ }
175
+ if (!sourcePath) {
176
+ // Was silent before — a slug miss produced 0 messages with no trace, so
177
+ // a live read_chat returning empty was indistinguishable from "no file"
178
+ // vs "wrong path". Log the attempted concrete path + both slug variants
179
+ // so the failure mode is greppable in daemon logs.
180
+ const wsRaw = typeof input.workspace === 'string' ? input.workspace : '';
181
+ let wsReal = wsRaw;
182
+ try { if (wsRaw) wsReal = fs.realpathSync(wsRaw); } catch { /* keep raw */ }
183
+ LOG.debug('NativeHistory', `jsonl unresolved: tried=${JSON.stringify(resolved)} sessionId=${requestedSessionId || '(none)'} wsRaw=${JSON.stringify(wsRaw)} wsReal=${JSON.stringify(wsReal)} rawSlug=${JSON.stringify(claudeProjectDirName(wsRaw))} realSlug=${JSON.stringify(claudeProjectDirName(wsReal))} (concrete miss + raw-slug retry + projects scan all failed)`);
184
+ return null;
185
+ }
186
+
187
+ const mtime = safeMtimeMs(sourcePath);
188
+ const lines = readJsonlLines(sourcePath);
189
+ if (lines.length === 0) return null;
190
+ const transcriptWorkspace = readSessionMetaWorkspace(lines);
191
+
192
+ // session id: filename uuid or extracted from first record
193
+ let providerSessionId: string | undefined;
194
+ if (src.session_id_from === 'first_record' && src.session_id_path) {
195
+ const v = jsonPathGet(lines[0], src.session_id_path);
196
+ if (typeof v === 'string' && v) providerSessionId = v;
197
+ } else if (src.session_id_from === 'filename_uuid' || !src.session_id_from) {
198
+ const m = path.basename(sourcePath).match(UUID_RE);
199
+ if (m) providerSessionId = m[1];
200
+ }
201
+
202
+ const requested = requestedSessionId || '';
203
+ if (requested && providerSessionId && providerSessionId !== requested) return null;
204
+
205
+ const filter = src.message_filter ? compileWhere(src.message_filter.where) : null;
206
+ const messages: NativeHistoryMessage[] = [];
207
+ for (let i = 0; i < lines.length; i += 1) {
208
+ const rec = lines[i];
209
+ if (filter && !filter(rec)) continue;
210
+ for (const msg of projectMessages(rec, src.message_map, i, lines.length, mtime)) {
211
+ if (transcriptWorkspace) msg.workspace = transcriptWorkspace;
212
+ messages.push(msg);
213
+ }
214
+ }
215
+ if (messages.length === 0) return null;
216
+
217
+ return {
218
+ messages,
219
+ providerSessionId,
220
+ sourcePath,
221
+ sourceMtimeMs: mtime,
222
+ nativeHistoryCoverage: 'full',
223
+ workspace: transcriptWorkspace,
224
+ };
225
+ }
226
+
227
+ function readSessionMetaWorkspace(lines: any[]): string | undefined {
228
+ for (const record of lines.slice(0, 5)) {
229
+ if (String(record?.type ?? '') !== 'session_meta') continue;
230
+ const cwd = typeof record?.payload?.cwd === 'string' ? record.payload.cwd.trim() : '';
231
+ if (cwd) return cwd;
232
+ }
233
+ return undefined;
234
+ }
235
+
236
+ function readJsonlLines(p: string): any[] {
237
+ let text: string;
238
+ try { text = fs.readFileSync(p, 'utf8'); } catch { return []; }
239
+ const out: any[] = [];
240
+ for (const line of text.split('\n')) {
241
+ const trimmed = line.trim();
242
+ if (!trimmed) continue;
243
+ try { out.push(JSON.parse(trimmed)); } catch { /* skip malformed line */ }
244
+ }
245
+ return out;
246
+ }
247
+
248
+ // ────────────────────────────────────────────────────────────────────────────
249
+ // SQLite
250
+ // ────────────────────────────────────────────────────────────────────────────
251
+
252
+ function executeSqlite(src: NativeHistorySqliteSource, input: NativeHistoryInput): NativeHistoryResult | null {
253
+ const resolved = expandPath(src.path, input);
254
+ if (!resolved || !fs.existsSync(resolved)) return null;
255
+
256
+ let Database: any;
257
+ try {
258
+ Database = loadBetterSqlite3();
259
+ } catch { return null; }
260
+
261
+ let db: any;
262
+ try { db = new Database(resolved, { readonly: true, fileMustExist: true }); }
263
+ catch { return null; }
264
+
265
+ try {
266
+ let sessionRow: any;
267
+ try {
268
+ // session_query may reference `?` to receive the session's
269
+ // start-time floor in seconds (e.g. WHERE started_at >= ?).
270
+ // That gives spec authors a robust way to keep prior-session
271
+ // rows out of a fresh dashboard view without inventing their
272
+ // own time arithmetic in SQL. When the caller didn't pass a
273
+ // session floor (i.e. no live session is associated with the
274
+ // call), we use 0 so spec queries that bind `?` still produce
275
+ // a sane result rather than choking the whole executor.
276
+ const sessionFloorSeconds = typeof input.sessionStartedAtMs === 'number'
277
+ ? Math.floor(input.sessionStartedAtMs / 1000)
278
+ : 0;
279
+ const stmt = db.prepare(src.session_query);
280
+ try {
281
+ sessionRow = stmt.get(sessionFloorSeconds);
282
+ } catch {
283
+ sessionRow = stmt.get();
284
+ }
285
+ } catch { return null; }
286
+ if (!sessionRow) return null;
287
+ // First column of the first row is the session id.
288
+ const sessionIdRaw = Object.values(sessionRow)[0];
289
+ const sessionId = sessionIdRaw == null ? '' : String(sessionIdRaw);
290
+ if (!sessionId) return null;
291
+
292
+ const requested = input.providerSessionId || '';
293
+ if (requested && sessionId !== requested) return null;
294
+
295
+ const messageRows: any[] = db.prepare(src.message_query).all(sessionId);
296
+ if (!messageRows || messageRows.length === 0) return null;
297
+
298
+ const mtime = safeMtimeMs(resolved);
299
+ const messages: NativeHistoryMessage[] = [];
300
+ for (let i = 0; i < messageRows.length; i += 1) {
301
+ for (const msg of projectMessages(messageRows[i], src.message_map, i, messageRows.length, mtime)) {
302
+ messages.push(msg);
303
+ }
304
+ }
305
+ if (messages.length === 0) return null;
306
+
307
+ return {
308
+ messages,
309
+ providerSessionId: sessionId,
310
+ sourcePath: resolved,
311
+ sourceMtimeMs: mtime,
312
+ nativeHistoryCoverage: 'full',
313
+ };
314
+ } finally {
315
+ try { db.close(); } catch { /* ignore */ }
316
+ }
317
+ }
318
+
319
+ // ────────────────────────────────────────────────────────────────────────────
320
+ // Path expansion + globbing
321
+ // ────────────────────────────────────────────────────────────────────────────
322
+
323
+ function expandPath(template: string, input: NativeHistoryInput, opts?: { skipWorkspaceRealpath?: boolean }): string | null {
324
+ if (!template) return null;
325
+ let out = template;
326
+ if (out.startsWith('~/') || out === '~') {
327
+ out = path.join(os.homedir(), out.slice(2));
328
+ }
329
+ // ${VAR} expands from envOverrides (the spawned child's view) first,
330
+ // then process.env. ${VAR:-fallback} keeps the bash-style default
331
+ // so spec authors can say e.g. ${HERMES_HOME:-~/.hermes}/state.db
332
+ // and have it work both for coordinator-launched sessions (where
333
+ // HERMES_HOME is set to a tmpdir) and normal sessions.
334
+ out = out.replace(/\$\{([A-Z_][A-Z0-9_]*)(?::-(.*?))?\}/g, (_m, name, fallback) => {
335
+ const v = input.envOverrides?.[name] ?? process.env[name];
336
+ return v != null && v !== '' ? v : (fallback ?? '');
337
+ });
338
+ // Re-expand ~ in case the fallback used it.
339
+ if (out.startsWith('~/')) out = path.join(os.homedir(), out.slice(2));
340
+ const now = new Date();
341
+ // Claude writes per-cwd transcripts under the resolved path and replaces
342
+ // every non-alphanumeric project-path character except `_` and `-` with
343
+ // `-`. Realpath also handles aliases such as /tmp -> /private/tmp.
344
+ const workspaceRaw = input.workspace ?? '';
345
+ let workspaceResolved = workspaceRaw;
346
+ // The caller may request the RAW slug (skip realpath) to recover from
347
+ // Windows realpath normalization diverging the {cwd*} slug from the dir
348
+ // the CLI actually created. Default keeps realpath (handles /tmp ->
349
+ // /private/tmp aliasing that the CLI itself resolves on macOS).
350
+ if (workspaceRaw && !opts?.skipWorkspaceRealpath) {
351
+ try { workspaceResolved = fs.realpathSync(workspaceRaw); }
352
+ catch { /* path may not exist yet — keep the raw value */ }
353
+ }
354
+ const vars: Record<string, string> = {
355
+ cwd: workspaceResolved,
356
+ cwd_dashed: workspaceResolved.replace(/\//g, '-'),
357
+ cwd_claude_project: claudeProjectDirName(workspaceResolved),
358
+ session_id: input.providerSessionId || input.sessionId || input.historySessionId || '',
359
+ yyyy: String(now.getFullYear()),
360
+ mm: String(now.getMonth() + 1).padStart(2, '0'),
361
+ dd: String(now.getDate()).padStart(2, '0'),
362
+ };
363
+ // Replace {var}. If a referenced variable is empty (e.g. session_id
364
+ // before the agent has allocated one), return null so the caller
365
+ // doesn't accidentally fall through to an unrelated newest-file
366
+ // match. Wildcards (`*`) are explicitly allowed to pass — the dir
367
+ // glob walker handles them separately.
368
+ let missing = false;
369
+ out = out.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_m, name) => {
370
+ const v = vars[name] ?? '';
371
+ if (!v) missing = true;
372
+ return v;
373
+ });
374
+ if (missing) return null;
375
+ return out;
376
+ }
377
+
378
+ function claudeProjectDirName(workspace: string): string {
379
+ return workspace.replace(/[^A-Za-z0-9_-]/g, '-');
380
+ }
381
+
382
+ /**
383
+ * Last-resort lookup for a transcript by its exact session id, ignoring the
384
+ * per-cwd slug entirely. The slug-derived directory above can miss completely
385
+ * when the CLI's on-disk project dir disagrees with the slug we reconstruct
386
+ * (notably on Windows, where fs.realpathSync normalizes drive-letter case and
387
+ * adds a \\?\ prefix). Since the session id is a UUID, scanning the projects
388
+ * root for `<sessionId>.jsonl` is unambiguous.
389
+ *
390
+ * Derives the scan base from the template's segments up to (but excluding) the
391
+ * first one that references a per-session variable ({cwd*} or {session_id}) —
392
+ * e.g. `~/.claude/projects/{cwd_claude_project}/{session_id}.jsonl` → scan
393
+ * `~/.claude/projects`. Returns the matching file path, or null.
394
+ */
395
+ function scanProjectsRootForSessionFile(template: string, input: NativeHistoryInput, requestedSessionId: string): string | null {
396
+ if (!requestedSessionId) return null;
397
+ // Resolve the leading static portion of the template (everything before the
398
+ // first {var} segment) into a concrete base directory.
399
+ let head = template;
400
+ if (head.startsWith('~/') || head === '~') head = path.join(os.homedir(), head.slice(2));
401
+ const segs = head.split('/');
402
+ const baseParts: string[] = [];
403
+ for (const seg of segs) {
404
+ if (/[{}*?]/.test(seg)) break;
405
+ baseParts.push(seg);
406
+ }
407
+ const base = baseParts.join('/');
408
+ if (!base) return null;
409
+ let baseStat: fs.Stats | null = null;
410
+ try { baseStat = fs.statSync(base); } catch { return null; }
411
+ if (!baseStat.isDirectory()) return null;
412
+
413
+ const needle = `${requestedSessionId.toLowerCase()}.jsonl`;
414
+ // Bounded walk: project layouts are <root>/<projectDir>/<uuid>.jsonl, so a
415
+ // shallow scan (root + one level of subdirs) suffices and avoids walking an
416
+ // unbounded tree. Check the root itself first, then each immediate subdir.
417
+ const dirsToScan: string[] = [base];
418
+ try {
419
+ for (const entry of fs.readdirSync(base, { withFileTypes: true })) {
420
+ if (entry.isDirectory()) dirsToScan.push(path.join(base, entry.name));
421
+ }
422
+ } catch { /* readdir failed — fall back to scanning base only */ }
423
+
424
+ for (const dir of dirsToScan) {
425
+ let entries: fs.Dirent[];
426
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { continue; }
427
+ for (const entry of entries) {
428
+ if (!entry.isFile()) continue;
429
+ if (entry.name.toLowerCase() !== needle) continue;
430
+ const found = path.join(dir, entry.name);
431
+ LOG.debug('NativeHistory', `jsonl scan-fallback hit: sessionId=${requestedSessionId} resolved via projects-root scan → ${JSON.stringify(found)} (slug-derived path missed; likely realpath/slug divergence)`);
432
+ return found;
433
+ }
434
+ }
435
+ return null;
436
+ }
437
+
438
+ function globToRegex(pattern: string): RegExp {
439
+ // Minimal glob: `*` → `[^/]*`, `?` → `[^/]`, `.` → `\.`. Anchored.
440
+ const re = pattern
441
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
442
+ .replace(/\*/g, '[^/]*')
443
+ .replace(/\?/g, '[^/]');
444
+ return new RegExp(`^${re}$`);
445
+ }
446
+
447
+ /**
448
+ * Resolve a path with `*` segments to all concrete directories that match,
449
+ * then pick the newest file inside any of them. `*` matches one path
450
+ * component (no slashes); `**` matches zero or more components. Filenames
451
+ * are matched against `pattern`, not the glob — file_pattern is the right
452
+ * place for the leaf match.
453
+ */
454
+ function expandDirGlob(template: string): string[] {
455
+ const parts = template.split('/');
456
+ let dirs: string[] = parts[0] === '' ? ['/'] : [parts[0]];
457
+ for (let i = 1; i < parts.length; i += 1) {
458
+ const seg = parts[i];
459
+ if (!seg) continue;
460
+ const next: string[] = [];
461
+ if (seg === '**') {
462
+ for (const d of dirs) walkAllDirs(d, next);
463
+ dirs = next;
464
+ continue;
465
+ }
466
+ if (seg.includes('*') || seg.includes('?')) {
467
+ const re = globToRegex(seg);
468
+ for (const d of dirs) {
469
+ let entries: fs.Dirent[];
470
+ try { entries = fs.readdirSync(d, { withFileTypes: true }); } catch { continue; }
471
+ for (const e of entries) {
472
+ if (e.isDirectory() && re.test(e.name)) next.push(path.join(d, e.name));
473
+ }
474
+ }
475
+ } else {
476
+ for (const d of dirs) {
477
+ const candidate = path.join(d, seg);
478
+ let stat: fs.Stats | null = null;
479
+ try { stat = fs.statSync(candidate); } catch { continue; }
480
+ if (stat.isDirectory()) next.push(candidate);
481
+ }
482
+ }
483
+ dirs = next;
484
+ }
485
+ return dirs;
486
+ }
487
+
488
+ function walkAllDirs(root: string, out: string[]): void {
489
+ let entries: fs.Dirent[];
490
+ try { entries = fs.readdirSync(root, { withFileTypes: true }); } catch { return; }
491
+ out.push(root);
492
+ for (const e of entries) {
493
+ if (e.isDirectory()) walkAllDirs(path.join(root, e.name), out);
494
+ }
495
+ }
496
+
497
+ function newestRecentFileAcrossGlob(template: string, pattern: RegExp, windowMs: number, sessionFloorMs = 0): string | null {
498
+ const dirs = expandDirGlob(template);
499
+ const cutoff = Math.max(Date.now() - windowMs, sessionFloorMs);
500
+ let best: { p: string; mtime: number } | null = null;
501
+ for (const d of dirs) {
502
+ let entries: fs.Dirent[];
503
+ try { entries = fs.readdirSync(d, { withFileTypes: true }); } catch { continue; }
504
+ for (const e of entries) {
505
+ if (!e.isFile() || !pattern.test(e.name)) continue;
506
+ const p = path.join(d, e.name);
507
+ const mtime = safeMtimeMs(p);
508
+ if (mtime < cutoff) continue;
509
+ if (!best || mtime > best.mtime) best = { p, mtime };
510
+ }
511
+ }
512
+ return best ? best.p : null;
513
+ }
514
+
515
+ function hasDateTemplateSegment(template: string): boolean {
516
+ return /\{yyyy\}|\{mm\}|\{dd\}/.test(template);
517
+ }
518
+
519
+ /**
520
+ * Walk nearby local calendar days of a date-templated path (e.g.
521
+ * `~/.codex/sessions/{yyyy}/{mm}/{dd}`) and return the newest matching
522
+ * file across all of them. Providers differ on local-vs-UTC date buckets,
523
+ * so today's expanded dir alone can miss a live transcript.
524
+ */
525
+ function newestRecentFileAcrossDateWindow(
526
+ template: string,
527
+ input: NativeHistoryInput,
528
+ pattern: RegExp,
529
+ windowMs: number,
530
+ sessionFloorMs: number,
531
+ ): string | null {
532
+ const cutoff = Math.max(Date.now() - windowMs, sessionFloorMs);
533
+ let best: { p: string; mtime: number } | null = null;
534
+ for (const dayOffset of [0, -1, 1, -2, 2]) {
535
+ const dayMs = Date.now() + dayOffset * 24 * 60 * 60 * 1000;
536
+ const dayInput: NativeHistoryInput = { ...input, sessionStartedAtMs: sessionFloorMs };
537
+ const resolved = expandPathForDate(template, dayInput, new Date(dayMs));
538
+ if (!resolved) continue;
539
+ let entries: fs.Dirent[];
540
+ try { entries = fs.readdirSync(resolved, { withFileTypes: true }); } catch { continue; }
541
+ for (const e of entries) {
542
+ if (!e.isFile() || !pattern.test(e.name)) continue;
543
+ const p = path.join(resolved, e.name);
544
+ const mtime = safeMtimeMs(p);
545
+ if (mtime < cutoff) continue;
546
+ if (!best || mtime > best.mtime) best = { p, mtime };
547
+ }
548
+ }
549
+ return best ? best.p : null;
550
+ }
551
+
552
+ function expandPathForDate(template: string, input: NativeHistoryInput, day: Date): string | null {
553
+ // Reuse expandPath logic but stamp {yyyy}/{mm}/{dd} from the given day.
554
+ if (!template) return null;
555
+ let out = template;
556
+ if (out.startsWith('~/') || out === '~') {
557
+ out = path.join(os.homedir(), out.slice(2));
558
+ }
559
+ out = out.replace(/\$\{([A-Z_][A-Z0-9_]*)(?::-(.*?))?\}/g, (_m, name, fallback) => {
560
+ const v = input.envOverrides?.[name] ?? process.env[name];
561
+ return v != null && v !== '' ? v : (fallback ?? '');
562
+ });
563
+ if (out.startsWith('~/')) out = path.join(os.homedir(), out.slice(2));
564
+ const workspaceRaw = input.workspace ?? '';
565
+ let workspaceResolved = workspaceRaw;
566
+ if (workspaceRaw) {
567
+ try { workspaceResolved = fs.realpathSync(workspaceRaw); } catch { /* keep raw */ }
568
+ }
569
+ const vars: Record<string, string> = {
570
+ cwd: workspaceResolved,
571
+ cwd_dashed: workspaceResolved.replace(/\//g, '-'),
572
+ cwd_claude_project: claudeProjectDirName(workspaceResolved),
573
+ session_id: input.providerSessionId || input.sessionId || input.historySessionId || '',
574
+ yyyy: String(day.getFullYear()),
575
+ mm: String(day.getMonth() + 1).padStart(2, '0'),
576
+ dd: String(day.getDate()).padStart(2, '0'),
577
+ };
578
+ let missing = false;
579
+ out = out.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, (_m, name) => {
580
+ const v = vars[name] ?? '';
581
+ if (!v) missing = true;
582
+ return v;
583
+ });
584
+ if (missing) return null;
585
+ return out;
586
+ }
587
+
588
+ function newestRecentFile(dir: string, pattern: RegExp, windowMs: number, sessionFloorMs = 0): string | null {
589
+ let entries: fs.Dirent[];
590
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return null; }
591
+ const cutoff = Math.max(Date.now() - windowMs, sessionFloorMs);
592
+ let best: { p: string; mtime: number } | null = null;
593
+ for (const e of entries) {
594
+ if (!e.isFile() || !pattern.test(e.name)) continue;
595
+ const p = path.join(dir, e.name);
596
+ const mtime = safeMtimeMs(p);
597
+ if (mtime < cutoff) continue;
598
+ if (!best || mtime > best.mtime) best = { p, mtime };
599
+ }
600
+ return best ? best.p : null;
601
+ }
602
+
603
+ function safeMtimeMs(p: string): number {
604
+ try { return Math.floor(fs.statSync(p).mtimeMs); } catch { return 0; }
605
+ }
606
+
607
+ function readRequestedSessionId(input: NativeHistoryInput): string {
608
+ const raw = input.providerSessionId || input.sessionId || input.historySessionId || '';
609
+ const value = typeof raw === 'string' ? raw.trim() : '';
610
+ return UUID_RE.test(value) ? value : '';
611
+ }
612
+
613
+ function filenameUuid(filePath: string): string {
614
+ const match = path.basename(filePath).match(UUID_RE);
615
+ return match?.[1] || '';
616
+ }
617
+
618
+ function pickExactSessionFile(dir: string, pattern: RegExp, requestedSessionId: string): string | null {
619
+ if (!requestedSessionId) return null;
620
+ const files = listMatchingFiles(dir, pattern)
621
+ .filter(p => filenameUuid(p).toLowerCase() === requestedSessionId.toLowerCase())
622
+ .sort((a, b) => safeMtimeMs(b) - safeMtimeMs(a));
623
+ return files[0] || null;
624
+ }
625
+
626
+ function pickExactSessionFileAcrossGlob(template: string, pattern: RegExp, requestedSessionId: string): string | null {
627
+ if (!requestedSessionId) return null;
628
+ const dirs = expandDirGlob(template);
629
+ const matches: string[] = [];
630
+ for (const d of dirs) {
631
+ const found = pickExactSessionFile(d, pattern, requestedSessionId);
632
+ if (found) matches.push(found);
633
+ }
634
+ matches.sort((a, b) => safeMtimeMs(b) - safeMtimeMs(a));
635
+ return matches[0] || null;
636
+ }
637
+
638
+ function pickExactSessionFileAcrossDateWindow(
639
+ template: string,
640
+ input: NativeHistoryInput,
641
+ pattern: RegExp,
642
+ requestedSessionId: string,
643
+ ): string | null {
644
+ if (!requestedSessionId) return null;
645
+ const matches: string[] = [];
646
+ for (const dayOffset of [0, -1, 1, -2, 2]) {
647
+ const dayMs = Date.now() + dayOffset * 24 * 60 * 60 * 1000;
648
+ const resolved = expandPathForDate(template, input, new Date(dayMs));
649
+ if (!resolved) continue;
650
+ const found = pickExactSessionFile(resolved, pattern, requestedSessionId);
651
+ if (found) matches.push(found);
652
+ }
653
+ matches.sort((a, b) => safeMtimeMs(b) - safeMtimeMs(a));
654
+ return matches[0] || null;
655
+ }
656
+
657
+ // ────────────────────────────────────────────────────────────────────────────
658
+ // Per-session rollout binding
659
+ //
660
+ // Reads the first JSONL line of a candidate file and returns a `session_meta`
661
+ // payload if present. Codex-cli writes
662
+ // {"timestamp":"...","type":"session_meta","payload":{"id":...,"cwd":...,
663
+ // "timestamp":"..."}}
664
+ // as the first record. Other providers that don't follow this convention
665
+ // return null and fall back to the mtime-based picker.
666
+ // ────────────────────────────────────────────────────────────────────────────
667
+
668
+ interface CandidateMeta {
669
+ cwd?: string;
670
+ sessionTimestampMs?: number;
671
+ }
672
+
673
+ function readCandidateSessionMeta(filePath: string): CandidateMeta | null {
674
+ try {
675
+ // Read only the first line — meta is always the first JSONL record
676
+ // and full file reads here would scale O(files × file_size).
677
+ const fd = fs.openSync(filePath, 'r');
678
+ try {
679
+ const buf = Buffer.alloc(8192);
680
+ const bytes = fs.readSync(fd, buf, 0, buf.length, 0);
681
+ if (bytes <= 0) return null;
682
+ const text = buf.subarray(0, bytes).toString('utf8');
683
+ const nl = text.indexOf('\n');
684
+ const firstLine = (nl >= 0 ? text.slice(0, nl) : text).trim();
685
+ if (!firstLine) return null;
686
+ const parsed = JSON.parse(firstLine) as Record<string, unknown>;
687
+ if (String(parsed.type ?? '') !== 'session_meta') return null;
688
+ const payload = parsed.payload && typeof parsed.payload === 'object'
689
+ ? (parsed.payload as Record<string, unknown>)
690
+ : null;
691
+ if (!payload) return null;
692
+ const cwd = typeof payload.cwd === 'string' ? payload.cwd : undefined;
693
+ const tsRaw = payload.timestamp;
694
+ const tsMs = typeof tsRaw === 'string'
695
+ ? Date.parse(tsRaw)
696
+ : typeof tsRaw === 'number'
697
+ ? (tsRaw < 1e12 ? Math.floor(tsRaw * 1000) : Math.floor(tsRaw))
698
+ : NaN;
699
+ return {
700
+ cwd,
701
+ sessionTimestampMs: Number.isFinite(tsMs) ? tsMs : undefined,
702
+ };
703
+ } finally {
704
+ fs.closeSync(fd);
705
+ }
706
+ } catch {
707
+ return null;
708
+ }
709
+ }
710
+
711
+ function pickBoundFromEntries(
712
+ candidatePaths: string[],
713
+ sessionFloorMs: number,
714
+ workspaceHint: string,
715
+ ): string | null {
716
+ if (!sessionFloorMs || !workspaceHint || candidatePaths.length === 0) return null;
717
+ // Resolve workspaceHint to handle macOS /tmp → /private/tmp aliasing, the
718
+ // same way expandPath does for the template substitution. Without this
719
+ // the daemon's `/Users/foo/repo` and codex's `/private/Users/foo/repo`
720
+ // never compare equal and disambiguation silently fails.
721
+ let workspaceResolved = workspaceHint;
722
+ try { workspaceResolved = fs.realpathSync(workspaceHint); } catch { /* keep raw */ }
723
+ let best: { p: string; diff: number } | null = null;
724
+ for (const p of candidatePaths) {
725
+ const meta = readCandidateSessionMeta(p);
726
+ if (!meta || !meta.cwd || meta.sessionTimestampMs == null) continue;
727
+ let candidateCwd = meta.cwd;
728
+ try { candidateCwd = fs.realpathSync(meta.cwd); } catch { /* keep raw */ }
729
+ if (candidateCwd !== workspaceResolved && meta.cwd !== workspaceHint) continue;
730
+ const diff = Math.abs(meta.sessionTimestampMs - sessionFloorMs);
731
+ if (diff > SPAWN_BIND_GRACE_MS) continue;
732
+ if (!best || diff < best.diff) best = { p, diff };
733
+ }
734
+ return best ? best.p : null;
735
+ }
736
+
737
+ function listMatchingFiles(dir: string, pattern: RegExp): string[] {
738
+ let entries: fs.Dirent[];
739
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return []; }
740
+ const out: string[] = [];
741
+ for (const e of entries) {
742
+ if (!e.isFile() || !pattern.test(e.name)) continue;
743
+ out.push(path.join(dir, e.name));
744
+ }
745
+ return out;
746
+ }
747
+
748
+ function pickSessionBoundFile(
749
+ dir: string,
750
+ pattern: RegExp,
751
+ windowMs: number,
752
+ sessionFloorMs: number,
753
+ workspaceHint: string,
754
+ ): string | null {
755
+ if (!sessionFloorMs || !workspaceHint) return null;
756
+ const cutoff = Math.max(Date.now() - windowMs, sessionFloorMs - SPAWN_BIND_GRACE_MS);
757
+ const files = listMatchingFiles(dir, pattern).filter(p => safeMtimeMs(p) >= cutoff);
758
+ return pickBoundFromEntries(files, sessionFloorMs, workspaceHint);
759
+ }
760
+
761
+ function pickSessionBoundFileAcrossGlob(
762
+ template: string,
763
+ pattern: RegExp,
764
+ windowMs: number,
765
+ sessionFloorMs: number,
766
+ workspaceHint: string,
767
+ ): string | null {
768
+ if (!sessionFloorMs || !workspaceHint) return null;
769
+ const dirs = expandDirGlob(template);
770
+ const cutoff = Math.max(Date.now() - windowMs, sessionFloorMs - SPAWN_BIND_GRACE_MS);
771
+ const files: string[] = [];
772
+ for (const d of dirs) {
773
+ for (const p of listMatchingFiles(d, pattern)) {
774
+ if (safeMtimeMs(p) >= cutoff) files.push(p);
775
+ }
776
+ }
777
+ return pickBoundFromEntries(files, sessionFloorMs, workspaceHint);
778
+ }
779
+
780
+ function pickSessionBoundFileAcrossDateWindow(
781
+ template: string,
782
+ input: NativeHistoryInput,
783
+ pattern: RegExp,
784
+ windowMs: number,
785
+ sessionFloorMs: number,
786
+ workspaceHint: string,
787
+ ): string | null {
788
+ if (!sessionFloorMs || !workspaceHint) return null;
789
+ const cutoff = Math.max(Date.now() - windowMs, sessionFloorMs - SPAWN_BIND_GRACE_MS);
790
+ const files: string[] = [];
791
+ for (const dayOffset of [0, -1, 1, -2, 2]) {
792
+ const dayMs = sessionFloorMs + dayOffset * 24 * 60 * 60 * 1000;
793
+ const dayInput: NativeHistoryInput = { ...input, sessionStartedAtMs: sessionFloorMs };
794
+ const resolved = expandPathForDate(template, dayInput, new Date(dayMs));
795
+ if (!resolved) continue;
796
+ for (const p of listMatchingFiles(resolved, pattern)) {
797
+ if (safeMtimeMs(p) >= cutoff) files.push(p);
798
+ }
799
+ }
800
+ return pickBoundFromEntries(files, sessionFloorMs, workspaceHint);
801
+ }
802
+
803
+ // ────────────────────────────────────────────────────────────────────────────
804
+ // jsonpath-lite + projection
805
+ // ────────────────────────────────────────────────────────────────────────────
806
+
807
+ /**
808
+ * Resolve `$.a.b[0].c` against a record. Strings without leading `$` are
809
+ * literals. Supports `||` fallback between paths so a single message_map
810
+ * entry can pick the first non-empty value across alternative locations
811
+ * (e.g. agy's content vs. thinking).
812
+ */
813
+ function jsonPathGet(record: any, expr: string): unknown {
814
+ if (typeof expr !== 'string') return undefined;
815
+ if (expr.includes('||')) {
816
+ for (const alt of expr.split('||')) {
817
+ const v = jsonPathGet(record, alt.trim());
818
+ if (v != null && v !== '') return v;
819
+ }
820
+ return undefined;
821
+ }
822
+ if (!expr.startsWith('$')) return expr;
823
+ let cur: any = record;
824
+ let i = 1;
825
+ while (i < expr.length && cur != null) {
826
+ const ch = expr[i];
827
+ if (ch === '.') { i += 1; continue; }
828
+ if (ch === '[') {
829
+ const close = expr.indexOf(']', i);
830
+ if (close < 0) return undefined;
831
+ const idx = Number(expr.slice(i + 1, close));
832
+ if (!Number.isInteger(idx)) return undefined;
833
+ cur = cur[idx];
834
+ i = close + 1;
835
+ continue;
836
+ }
837
+ let end = i;
838
+ while (end < expr.length && expr[end] !== '.' && expr[end] !== '[') end += 1;
839
+ const key = expr.slice(i, end);
840
+ cur = cur[key];
841
+ i = end;
842
+ }
843
+ return cur;
844
+ }
845
+
846
+ /**
847
+ * Project one on-disk record into zero or more transcript messages.
848
+ *
849
+ * A record yields at most one text bubble (the prose turn) plus — when the
850
+ * spec declares `message_map.tools` — one `kind:'tool'` bubble per tool-call
851
+ * or tool-result content block. Without `tools`, behaviour is identical to
852
+ * the old single-message projection: text-only, tool blocks dropped.
853
+ */
854
+ function projectMessages(record: any, map: NativeHistoryMessageMap, index: number, total: number, sourceMtimeMs: number): NativeHistoryMessage[] {
855
+ const roleRaw = jsonPathGet(record, map.role);
856
+ const role = normalizeRole(roleRaw);
857
+
858
+ // Records are passed in chronological order (oldest → newest), so the
859
+ // last record's receivedAt should be ~sourceMtimeMs (when the file was
860
+ // last touched) and earlier records should walk backwards. Earlier
861
+ // version had this inverted, which made the dashboard render bubbles
862
+ // in reverse order and produce the "chat jumping" effect.
863
+ let receivedAt = sourceMtimeMs - ((total - 1 - index) * 1000);
864
+ if (map.timestamp_ms) {
865
+ const tsRaw = jsonPathGet(record, map.timestamp_ms);
866
+ const parsed = parseTimestamp(tsRaw);
867
+ if (parsed != null) receivedAt = parsed;
868
+ }
869
+ const kindRaw = map.kind ? jsonPathGet(record, map.kind) : undefined;
870
+ const kind = typeof kindRaw === 'string' && kindRaw ? kindRaw : 'standard';
871
+
872
+ const out: NativeHistoryMessage[] = [];
873
+
874
+ // Two transcript shapes carry tool activity:
875
+ // - record-level: the whole record IS a tool call/result (codex stores
876
+ // each function_call / function_call_output as its own jsonl record).
877
+ // - block-nested: tool blocks live inside the message's content array
878
+ // (claude stores tool_use / tool_result as content blocks).
879
+ // When the spec opts into `tools`, try the record itself first; if it's a
880
+ // tool record we emit only that bubble (it has no prose). Otherwise emit
881
+ // the text bubble plus a tool bubble per matching content block.
882
+ if (map.tools) {
883
+ const recordTool = projectToolBlock(record, role, map.tools);
884
+ if (recordTool) {
885
+ out.push({ ...recordTool, receivedAt });
886
+ return out;
887
+ }
888
+ }
889
+
890
+ const contentRaw = jsonPathGet(record, map.content);
891
+ const content = cleanContent(stringifyContent(contentRaw), map);
892
+ if (content) out.push({ role, content, receivedAt, kind });
893
+
894
+ // Block-nested tool bubbles are ordered just after the text bubble of the
895
+ // same record by nudging receivedAt forward a millisecond per bubble, so a
896
+ // turn's prose still renders before its tool activity without colliding
897
+ // with the next record's timestamp.
898
+ if (map.tools && Array.isArray(contentRaw)) {
899
+ let nudge = 1;
900
+ for (const block of contentRaw) {
901
+ const tool = projectToolBlock(block, role, map.tools);
902
+ if (tool) {
903
+ out.push({ ...tool, receivedAt: receivedAt + nudge });
904
+ nudge += 1;
905
+ }
906
+ }
907
+ }
908
+
909
+ return out;
910
+ }
911
+
912
+ /** Apply content_strip / content_unwrap tag surgery and trim. */
913
+ function cleanContent(input: string, map: NativeHistoryMessageMap): string {
914
+ let content = input;
915
+ if (content && map.content_strip) {
916
+ for (const tag of map.content_strip) {
917
+ const safeTag = tag.replace(/[.+^${}()|[\]\\]/g, '\\$&');
918
+ const re = new RegExp(`<${safeTag}\\b[^>]*>[\\s\\S]*?<\\/${safeTag}\\s*>`, 'gi');
919
+ content = content.replace(re, '');
920
+ }
921
+ }
922
+ if (content && map.content_unwrap) {
923
+ for (const tag of map.content_unwrap) {
924
+ const safeTag = tag.replace(/[.+^${}()|[\]\\]/g, '\\$&');
925
+ const open = new RegExp(`<${safeTag}\\b[^>]*>`, 'gi');
926
+ const close = new RegExp(`<\\/${safeTag}\\s*>`, 'gi');
927
+ content = content.replace(open, '').replace(close, '');
928
+ }
929
+ }
930
+ return content ? content.trim() : '';
931
+ }
932
+
933
+ const DEFAULT_TOOL_CALL_TYPES = ['tool_use', 'function_call', 'custom_tool_call'];
934
+ const DEFAULT_TOOL_RESULT_TYPES = ['tool_result', 'function_call_output', 'custom_tool_call_output'];
935
+
936
+ /**
937
+ * Turn a single content block into a `kind:'tool'` message, or null if the
938
+ * block is not a tool call/result. Field locations come from the spec's
939
+ * `tools` map with Anthropic-block defaults.
940
+ *
941
+ * Both tool calls and tool results render on the assistant side: a tool call
942
+ * is the agent's action, and a tool result is part of the agent's work, not a
943
+ * user turn (claude/codex persist results under the user / no role, which would
944
+ * otherwise misattribute them). Calls render as `↗ {name}: {one-line args}`,
945
+ * results as `↘ {one-line result}`. The `role` param is accepted for symmetry
946
+ * but tool bubbles are always assistant.
947
+ */
948
+ function projectToolBlock(block: any, role: 'user' | 'assistant' | 'system', tmap: NativeHistoryToolMap): NativeHistoryMessage | null {
949
+ void role;
950
+ if (block == null || typeof block !== 'object') return null;
951
+ const typeVal = String(jsonPathGet(block, tmap.block_type || '$.type') ?? '');
952
+ if (!typeVal) return null;
953
+ const callTypes = tmap.call_types ?? DEFAULT_TOOL_CALL_TYPES;
954
+ const resultTypes = tmap.result_types ?? DEFAULT_TOOL_RESULT_TYPES;
955
+
956
+ if (callTypes.includes(typeVal)) {
957
+ const name = String(jsonPathGet(block, tmap.call_name || '$.name') ?? 'tool').trim() || 'tool';
958
+ const args = oneLine(stringifyContent(jsonPathGet(block, tmap.call_args || '$.input')), 240);
959
+ const content = args ? `↗ ${name}: ${args}` : `↗ ${name}`;
960
+ return { role: 'assistant', content, receivedAt: 0, kind: 'tool' };
961
+ }
962
+ if (resultTypes.includes(typeVal)) {
963
+ const result = oneLine(stringifyContent(jsonPathGet(block, tmap.result_content || '$.content')), 600);
964
+ if (!result) return null;
965
+ return { role: 'assistant', content: `↘ ${result}`, receivedAt: 0, kind: 'tool' };
966
+ }
967
+ return null;
968
+ }
969
+
970
+ /** Collapse whitespace to single spaces and cap length for a tool summary. */
971
+ function oneLine(s: string, max: number): string {
972
+ const flat = s.replace(/\s+/g, ' ').trim();
973
+ return flat.length > max ? flat.slice(0, max - 1) + '…' : flat;
974
+ }
975
+
976
+ /**
977
+ * Coerce a timestamp value to epoch milliseconds. Accepts:
978
+ * - number (ms or seconds — heuristic: < 1e12 means seconds)
979
+ * - ISO 8601 string ("2026-06-05T01:25:28Z")
980
+ * - numeric string
981
+ *
982
+ * Returns null when the value can't be parsed; caller falls back to the
983
+ * monotonic-by-index estimate.
984
+ */
985
+ function parseTimestamp(v: unknown): number | null {
986
+ if (v == null) return null;
987
+ if (typeof v === 'number' && Number.isFinite(v) && v > 0) {
988
+ return v < 1e12 ? Math.floor(v * 1000) : Math.floor(v);
989
+ }
990
+ if (typeof v === 'string' && v) {
991
+ const trimmed = v.trim();
992
+ const asNum = Number(trimmed);
993
+ if (Number.isFinite(asNum) && asNum > 0) {
994
+ return asNum < 1e12 ? Math.floor(asNum * 1000) : Math.floor(asNum);
995
+ }
996
+ const parsed = Date.parse(trimmed);
997
+ if (Number.isFinite(parsed)) return parsed;
998
+ }
999
+ return null;
1000
+ }
1001
+
1002
+ function normalizeRole(r: unknown): 'user' | 'assistant' | 'system' {
1003
+ const s = String(r ?? '').toLowerCase();
1004
+ if (s === 'user' || s === 'human' || s === 'user_explicit') return 'user';
1005
+ if (s === 'assistant' || s === 'ai' || s === 'model') return 'assistant';
1006
+ if (s === 'tool' || s === 'tool_result' || s === 'function') return 'assistant';
1007
+ return 'system';
1008
+ }
1009
+
1010
+ /**
1011
+ * Coerce a content value to a plain string the dashboard can render.
1012
+ *
1013
+ * Many providers ship structured content (claude messages are arrays of
1014
+ * typed blocks: text / tool_use / tool_result). We collapse those to
1015
+ * their text-bearing parts so the dashboard doesn't show raw JSON
1016
+ * fragments in the transcript. Tool calls/results are intentionally
1017
+ * dropped — the daemon's chat schema is for user-visible turns.
1018
+ *
1019
+ * Order of attempts:
1020
+ * 1. string → as-is
1021
+ * 2. array of blocks → join the `text` field of each
1022
+ * block that has one; if none have
1023
+ * a text field, fall through
1024
+ * 3. object with a top-level `text` → that string
1025
+ * 4. last resort → JSON.stringify
1026
+ */
1027
+ function stringifyContent(v: unknown): string {
1028
+ if (v == null) return '';
1029
+ if (typeof v === 'string') return v;
1030
+ if (Array.isArray(v)) {
1031
+ const parts: string[] = [];
1032
+ for (const block of v) {
1033
+ if (block == null) continue;
1034
+ if (typeof block === 'string') { parts.push(block); continue; }
1035
+ if (typeof block === 'object') {
1036
+ const t = (block as any).text;
1037
+ if (typeof t === 'string' && t) { parts.push(t); continue; }
1038
+ // tool_use / tool_result / image / etc — skip from the
1039
+ // user-facing transcript. They re-surface via the
1040
+ // adapter's tool-event channel if/when that's wired.
1041
+ }
1042
+ }
1043
+ if (parts.length > 0) return parts.join('\n');
1044
+ return '';
1045
+ }
1046
+ if (typeof v === 'object') {
1047
+ const t = (v as any).text;
1048
+ if (typeof t === 'string') return t;
1049
+ }
1050
+ try { return JSON.stringify(v); } catch { return String(v); }
1051
+ }
1052
+
1053
+ // ────────────────────────────────────────────────────────────────────────────
1054
+ // where-clause mini-language
1055
+ //
1056
+ // Grammar (intentionally tiny — keep spec readable):
1057
+ // expr := term (('&&' | '||') term)*
1058
+ // term := path op literal
1059
+ // op := '==' | '!=' | '>' | '<' | '>=' | '<='
1060
+ // path := jsonpath like '$.foo.bar[0].baz'
1061
+ // literal := string ('"…"' or "'…'") | number | true | false | null
1062
+ //
1063
+ // No grouping, no negation. If you need more, write a real reader file
1064
+ // behind `native_history.override_path`.
1065
+ // ────────────────────────────────────────────────────────────────────────────
1066
+
1067
+ interface WhereTerm { path: string; op: string; lit: unknown; negate?: boolean }
1068
+
1069
+ function compileWhere(src: string): (record: any) => boolean {
1070
+ const ors: WhereTerm[][] = [];
1071
+ for (const orChunk of src.split('||')) {
1072
+ const ands: WhereTerm[] = [];
1073
+ for (const andChunk of orChunk.split('&&')) {
1074
+ const term = parseTerm(andChunk.trim());
1075
+ if (term) ands.push(term);
1076
+ }
1077
+ if (ands.length > 0) ors.push(ands);
1078
+ }
1079
+ return (record: any) => ors.some(ands => ands.every(t => evalTerm(t, record)));
1080
+ }
1081
+
1082
+ function parseTerm(src: string): WhereTerm | null {
1083
+ let s = src.trim();
1084
+ let negate = false;
1085
+ if (s.startsWith('!')) { negate = true; s = s.slice(1).trim(); }
1086
+ // Function-call form: startsWith($.x, "y") / endsWith($.x, "y") / contains($.x, "y")
1087
+ const fnMatch = s.match(/^(startsWith|endsWith|contains)\s*\(\s*(.+?)\s*,\s*(.+?)\s*\)$/);
1088
+ if (fnMatch) {
1089
+ const [, op, pathExpr, litExpr] = fnMatch;
1090
+ return { path: pathExpr, op, lit: parseLiteral(litExpr), negate };
1091
+ }
1092
+ // Binary comparison: <path> <op> <literal>
1093
+ const opMatch = s.match(/^(.+?)\s*(==|!=|>=|<=|>|<)\s*(.+)$/);
1094
+ if (!opMatch) return null;
1095
+ const [, lhs, op, rhsRaw] = opMatch;
1096
+ return { path: lhs.trim(), op, lit: parseLiteral(rhsRaw.trim()), negate };
1097
+ }
1098
+
1099
+ function parseLiteral(src: string): unknown {
1100
+ if (src === 'true') return true;
1101
+ if (src === 'false') return false;
1102
+ if (src === 'null') return null;
1103
+ if ((src.startsWith('"') && src.endsWith('"')) || (src.startsWith("'") && src.endsWith("'"))) {
1104
+ return src.slice(1, -1);
1105
+ }
1106
+ const n = Number(src);
1107
+ if (!Number.isNaN(n)) return n;
1108
+ return src; // bareword — treated as string
1109
+ }
1110
+
1111
+ function evalTerm(t: WhereTerm, record: any): boolean {
1112
+ const lhs = jsonPathGet(record, t.path);
1113
+ const lit = t.lit;
1114
+ let result: boolean;
1115
+ switch (t.op) {
1116
+ case '==': result = lhs === lit; break;
1117
+ case '!=': result = lhs !== lit; break;
1118
+ case '>': result = Number(lhs) > Number(lit); break;
1119
+ case '<': result = Number(lhs) < Number(lit); break;
1120
+ case '>=': result = Number(lhs) >= Number(lit); break;
1121
+ case '<=': result = Number(lhs) <= Number(lit); break;
1122
+ case 'startsWith': result = typeof lhs === 'string' && typeof lit === 'string' && lhs.startsWith(lit); break;
1123
+ case 'endsWith': result = typeof lhs === 'string' && typeof lit === 'string' && lhs.endsWith(lit); break;
1124
+ case 'contains': result = typeof lhs === 'string' && typeof lit === 'string' && lhs.includes(lit); break;
1125
+ default: result = false;
1126
+ }
1127
+ return t.negate ? !result : result;
1128
+ }