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