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

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