@adhdev/daemon-core 0.9.82-rc.46 → 0.9.82-rc.460
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 +25 -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 +64 -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 +48 -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 +152 -0
- package/dist/commands/mesh-coordinator.d.ts +85 -1
- package/dist/commands/router-refine.d.ts +137 -0
- package/dist/commands/router-worktree-cleanup.d.ts +133 -0
- package/dist/commands/router.d.ts +241 -12
- package/dist/commands/upgrade-helper.d.ts +41 -1
- package/dist/config/chat-history.d.ts +9 -0
- package/dist/config/config.d.ts +19 -0
- package/dist/config/mesh-config.d.ts +129 -1
- package/dist/config/mesh-json-config.d.ts +199 -0
- package/dist/config/registry-resolver.d.ts +54 -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 +12 -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 +67 -15
- package/dist/index.js +57943 -25340
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +57611 -25174
- 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/debug-config.d.ts +16 -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 +230 -0
- package/dist/mesh/coordinator-prompt.d.ts +76 -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 +7 -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 +113 -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 +133 -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 +306 -0
- package/dist/mesh/mesh-queue-assignment.d.ts +158 -0
- package/dist/mesh/mesh-reconcile-loop.d.ts +80 -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 +476 -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 +318 -5
- package/dist/mesh/preview-freshness.d.ts +28 -0
- package/dist/mesh/refine-config.d.ts +216 -0
- package/dist/mesh/worktree-bootstrap-config.d.ts +219 -0
- package/dist/providers/acp-provider-instance.d.ts +5 -0
- package/dist/providers/approval-utils.d.ts +45 -0
- package/dist/providers/chat-message-normalization.d.ts +58 -1
- package/dist/providers/cli-provider-instance.d.ts +290 -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 +79 -0
- package/dist/providers/native-history/antigravity-claim-registry.d.ts +28 -0
- package/dist/providers/native-history/antigravity-cli-transcript.d.ts +137 -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 +31 -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 +30 -1
- package/dist/providers/provider-loader.d.ts +42 -5
- 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 +98 -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 +449 -0
- package/dist/providers/spec/fsm-evaluator.d.ts +93 -0
- package/dist/providers/spec/fsm-loader.d.ts +14 -0
- package/dist/providers/spec/fsm-types.d.ts +202 -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 +519 -13
- package/dist/runtime-defaults.d.ts +2 -0
- package/dist/session-host/managed-host.d.ts +64 -0
- package/dist/session-host/runtime-surface.d.ts +10 -16
- package/dist/sessions/registry.d.ts +6 -0
- package/dist/shared-types-extra.d.ts +2 -4
- package/dist/shared-types.d.ts +86 -55
- 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 +11 -4
- package/src/agent-stream/poller.ts +2 -3
- package/src/agent-stream/provider-adapter.ts +1 -1
- package/src/boot/daemon-lifecycle.ts +65 -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/chat-commands-debug-bundle.ts +398 -0
- package/src/commands/chat-commands-read.ts +2488 -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 +596 -27
- package/src/commands/handler.ts +845 -2
- package/src/commands/high-family/index.ts +28 -0
- package/src/commands/high-family/mesh-coordinator-launch.ts +680 -0
- package/src/commands/high-family/mesh-events.ts +89 -0
- package/src/commands/high-family/mesh-status.ts +822 -0
- package/src/commands/high-family/types.ts +80 -0
- package/src/commands/low-family/coordinator-prompt.ts +72 -0
- package/src/commands/low-family/daemon-lifecycle.ts +120 -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 +241 -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 +1287 -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 +153 -0
- package/src/commands/mesh-coordinator.ts +334 -124
- package/src/commands/router-refine.ts +1711 -0
- package/src/commands/router-worktree-cleanup.ts +870 -0
- package/src/commands/router.ts +1025 -4070
- 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 +30 -0
- package/src/config/mesh-config.ts +619 -23
- package/src/config/mesh-json-config.ts +376 -0
- package/src/config/recent-activity.ts +8 -2
- package/src/config/registry-resolver.ts +100 -0
- 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 +78 -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 +200 -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/debug-config.ts +25 -0
- package/src/logging/debug-trace.ts +7 -2
- 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 +469 -0
- package/src/mesh/coordinator-prompt.ts +536 -34
- package/src/mesh/coordinator-registry.ts +121 -0
- package/src/mesh/mesh-active-work.ts +656 -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 +73 -0
- package/src/mesh/mesh-event-forwarding.ts +1932 -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 +766 -0
- package/src/mesh/mesh-events-stale.ts +440 -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 +856 -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 +873 -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 +1994 -0
- package/src/mesh/mesh-queue-assignment.ts +2233 -0
- package/src/mesh/mesh-reconcile-loop.ts +2390 -0
- package/src/mesh/mesh-refine-batch.ts +205 -0
- package/src/mesh/mesh-refine-gates.ts +1686 -0
- package/src/mesh/mesh-refine-status.ts +231 -0
- package/src/mesh/mesh-review-inbox.ts +308 -0
- package/src/mesh/mesh-routing.ts +291 -0
- package/src/mesh/mesh-runtime-store.ts +2026 -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 +1281 -141
- package/src/mesh/preview-freshness.ts +163 -0
- package/src/mesh/refine-config.ts +423 -0
- package/src/mesh/worktree-bootstrap-config.ts +599 -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 +99 -5
- package/src/providers/chat-message-normalization.ts +126 -4
- package/src/providers/cli-provider-instance.ts +2456 -107
- 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 +105 -0
- package/src/providers/native-history/antigravity-claim-registry.ts +131 -0
- package/src/providers/native-history/antigravity-cli-transcript.ts +1193 -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 +503 -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 +24 -1
- package/src/providers/provider-loader.ts +700 -55
- 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 +261 -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 +246 -0
- package/src/providers/spec/cli-adapter.ts +1064 -0
- package/src/providers/spec/evaluator.ts +407 -0
- package/src/providers/spec/fsm-driver.ts +1528 -0
- package/src/providers/spec/fsm-evaluator.ts +290 -0
- package/src/providers/spec/fsm-loader.ts +128 -0
- package/src/providers/spec/fsm-types.ts +301 -0
- package/src/providers/spec/native-history-executor.ts +1174 -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 +758 -14
- package/src/runtime-defaults.ts +39 -0
- package/src/session-host/managed-host.ts +218 -0
- package/src/session-host/runtime-surface.ts +20 -80
- 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 +124 -55
- 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,1246 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CliStateEngine — CLI provider status state machine
|
|
3
|
+
*
|
|
4
|
+
* Owns all status-transition logic, timer management, and script-driven
|
|
5
|
+
* evaluation. Reads buffer state from the transport and writes to PTY via
|
|
6
|
+
* the transport interface — adapter stays as pure I/O layer.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { LOG } from '../logging/logger.js';
|
|
10
|
+
import {
|
|
11
|
+
buildCliParseInput,
|
|
12
|
+
normalizeCliParsedMessages,
|
|
13
|
+
type TurnParseScope,
|
|
14
|
+
} from './provider-cli-parse.js';
|
|
15
|
+
import {
|
|
16
|
+
buildCliScreenSnapshot,
|
|
17
|
+
compactPromptText,
|
|
18
|
+
normalizePromptText,
|
|
19
|
+
promptLikelyVisible,
|
|
20
|
+
type CliChatMessage,
|
|
21
|
+
type CliProviderModule,
|
|
22
|
+
type CliSessionStatus,
|
|
23
|
+
type CliTraceEntry,
|
|
24
|
+
type ParsedSession,
|
|
25
|
+
} from './provider-cli-shared.js';
|
|
26
|
+
import type { CliScriptRunner } from './cli-script-runner.js';
|
|
27
|
+
|
|
28
|
+
// ─── Types ─────────────────────────────────────────────────────────────────
|
|
29
|
+
|
|
30
|
+
export interface CliBufferSnapshot {
|
|
31
|
+
accumulatedBuffer: string;
|
|
32
|
+
accumulatedRawBuffer: string;
|
|
33
|
+
recentOutputBuffer: string;
|
|
34
|
+
responseBuffer: string;
|
|
35
|
+
screenText: string;
|
|
36
|
+
parseScreenText: string;
|
|
37
|
+
workingDir: string;
|
|
38
|
+
providerSessionId: string | null;
|
|
39
|
+
runtimeSettings: Record<string, any>;
|
|
40
|
+
isWaitingForResponse: boolean;
|
|
41
|
+
currentTurnScope: TurnParseScope | null;
|
|
42
|
+
lastOutputAt: number;
|
|
43
|
+
lastNonEmptyOutputAt: number;
|
|
44
|
+
lastScreenChangeAt: number;
|
|
45
|
+
lastScreenSnapshot: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** What the engine needs from the transport layer */
|
|
49
|
+
export interface CliTransportAccess {
|
|
50
|
+
getSnapshot(): CliBufferSnapshot;
|
|
51
|
+
writeRaw(data: string | Buffer): void;
|
|
52
|
+
getApprovalKeyForIndex(buttonIndex: number): string | undefined;
|
|
53
|
+
flushOutboundQueue(): void;
|
|
54
|
+
isAlive(): boolean;
|
|
55
|
+
/** Optional: override script dispatch (used by tests to mock detection) */
|
|
56
|
+
runDetectStatus?(text: string): string | null;
|
|
57
|
+
/** Optional: override script dispatch (used by tests to mock approval) */
|
|
58
|
+
runParseApproval?(tail: string): { message: string; buttons: string[] } | null;
|
|
59
|
+
/** Optional: override full session parse (used by tests to mock parsing) */
|
|
60
|
+
runParseSession?(): ParsedSession | null;
|
|
61
|
+
/** Optional: provider type override — used when tests patch the adapter's cliType */
|
|
62
|
+
cliType?: string;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface CliStateEngineCallbacks {
|
|
66
|
+
onStatusChange(): void;
|
|
67
|
+
onApplyParsedSession(session: ParsedSession): void;
|
|
68
|
+
onTurnCompleted(): void;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
interface IdleFinishCandidate {
|
|
72
|
+
armedAt: number;
|
|
73
|
+
lastOutputAt: number;
|
|
74
|
+
lastScreenChangeAt: number;
|
|
75
|
+
responseEpoch: number;
|
|
76
|
+
assistantLength: number;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
interface SettledEvalContext {
|
|
80
|
+
now: number;
|
|
81
|
+
modal: { message: string; buttons: string[] } | null;
|
|
82
|
+
status: string;
|
|
83
|
+
parsedMessages: CliChatMessage[];
|
|
84
|
+
lastParsedAssistant: CliChatMessage | undefined;
|
|
85
|
+
parsedStatus: string | null;
|
|
86
|
+
prevStatus: string;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ─── Constants ─────────────────────────────────────────────────────────────
|
|
90
|
+
|
|
91
|
+
const SCRIPT_STATUS_DEBOUNCE_MS = 3000;
|
|
92
|
+
const MAX_FINISH_RETRIES = 2;
|
|
93
|
+
const FINISH_RETRY_DELAY_MS = 300;
|
|
94
|
+
const MAX_TRACE_ENTRIES = 250;
|
|
95
|
+
const APPROVAL_EXIT_TIMEOUT_MS = 60_000;
|
|
96
|
+
const IDLE_CONFIRMATION_GRACE_MS = 2_000;
|
|
97
|
+
|
|
98
|
+
// ─── Engine ────────────────────────────────────────────────────────────────
|
|
99
|
+
|
|
100
|
+
export class CliStateEngine {
|
|
101
|
+
// ── Status ───────────────────────────────────────
|
|
102
|
+
currentStatus: CliSessionStatus['status'] = 'starting';
|
|
103
|
+
isWaitingForResponse = false;
|
|
104
|
+
currentTurnScope: TurnParseScope | null = null;
|
|
105
|
+
// ARCH-REFACTOR R1 (per-turn task identity): the mesh taskId bound to the most
|
|
106
|
+
// recently STARTED turn. Unlike currentTurnScope (nulled the moment the turn
|
|
107
|
+
// settles, before the completion event is even built), this persists past
|
|
108
|
+
// completion and is only overwritten when the NEXT turn starts. That window is
|
|
109
|
+
// exactly what the completion path needs: when a turn settles to idle, this still
|
|
110
|
+
// holds THAT turn's taskId (the next task's turn cannot have started yet — it is
|
|
111
|
+
// queued in pendingOutbound and only flushed asynchronously after idle), so the
|
|
112
|
+
// completion event carries the correct id instead of the racy session scalar.
|
|
113
|
+
currentTurnTaskId: string | null = null;
|
|
114
|
+
// GENERATING-BOUNDARY (R4d): wall-clock when the most recently STARTED turn began
|
|
115
|
+
// (set by onTurnStarted, persists past completion until the next turn starts).
|
|
116
|
+
// The startup-grace idle-stayed synthesis anchors its window on when the FIRST turn
|
|
117
|
+
// STARTED — not on when it finished — so a turn dispatched a few seconds after the
|
|
118
|
+
// grace collapse and then running for a non-trivial duration is still attributed to
|
|
119
|
+
// the startup collapse even though its COMPLETION lands past a now-anchored window.
|
|
120
|
+
currentTurnStartedAt = 0;
|
|
121
|
+
activeModal: { message: string; buttons: string[] } | null = null;
|
|
122
|
+
|
|
123
|
+
// ── Approval ─────────────────────────────────────
|
|
124
|
+
lastApprovalResolvedAt = 0;
|
|
125
|
+
lastResolvedModalMessage = '';
|
|
126
|
+
/**
|
|
127
|
+
* Monotonic counter bumped every time the FSM *enters* waiting_approval
|
|
128
|
+
* with a freshly captured modal (see `applyWaitingApproval`). It is the
|
|
129
|
+
* single discriminator between "the same approval re-observed across TUI
|
|
130
|
+
* paint flaps" and "a genuinely new, distinct approval".
|
|
131
|
+
*
|
|
132
|
+
* The message-equality cooldown below (`lastResolvedModalMessage`) cannot
|
|
133
|
+
* tell these apart on its own: claude-cli routinely presents consecutive
|
|
134
|
+
* approvals whose modal message text is identical (e.g. two back-to-back
|
|
135
|
+
* Bash-command prompts). When that second approval arrived inside
|
|
136
|
+
* `approvalCooldown`, the message-equality guard silently swallowed the
|
|
137
|
+
* key write and the approval stuck forever — fatal under auto-approval.
|
|
138
|
+
*
|
|
139
|
+
* `approvalEntrySeq` increments on every fresh entry; `lastResolvedEntrySeq`
|
|
140
|
+
* records which entry the cooldown belongs to. We only short-circuit the
|
|
141
|
+
* write when we are still resolving *that same* entry — a new entry (new
|
|
142
|
+
* seq) is always a real, distinct approval and must be written.
|
|
143
|
+
*/
|
|
144
|
+
approvalEntrySeq = 0;
|
|
145
|
+
// Records which approval entry the last resolveModal() handled. Set unconditionally on
|
|
146
|
+
// every resolveModal (auto-approve fire, dashboard/mesh_approve, dev-cli-debug), so
|
|
147
|
+
// `lastResolvedEntrySeq >= approvalEntrySeq` is positive, ADHDev-side proof that the
|
|
148
|
+
// current/latest approval entry was actually resolved. Exposed via getStatus so the
|
|
149
|
+
// completion finalization gate (FALSEIDLE-a) can require resolution evidence before
|
|
150
|
+
// confirming a waiting_approval→idle transition. Public (read-only by convention).
|
|
151
|
+
lastResolvedEntrySeq = -1;
|
|
152
|
+
/**
|
|
153
|
+
* When the engine previously held a modal but the latest parse failed
|
|
154
|
+
* to extract one, we record the timestamp here and only drop the modal
|
|
155
|
+
* after the configured `approvalCooldown` to avoid flapping between
|
|
156
|
+
* waiting_approval and generating on every Claude TUI redraw — that
|
|
157
|
+
* flapping is what fed auto-approve a fresh modal signature on each
|
|
158
|
+
* paint and made the engine type "1" repeatedly into the prompt.
|
|
159
|
+
*/
|
|
160
|
+
modalLostAt = 0;
|
|
161
|
+
private approvalExitTimeout: NodeJS.Timeout | null = null;
|
|
162
|
+
|
|
163
|
+
// ── Response tracking ────────────────────────────
|
|
164
|
+
responseEpoch = 0;
|
|
165
|
+
submitPendingUntil = 0;
|
|
166
|
+
responseSettleIgnoreUntil = 0;
|
|
167
|
+
submitRetryUsed = false;
|
|
168
|
+
submitRetryPromptSnippet = '';
|
|
169
|
+
finishRetryCount = 0;
|
|
170
|
+
providerErrorMessage: string | null = null;
|
|
171
|
+
providerErrorReason: string | null = null;
|
|
172
|
+
|
|
173
|
+
// ── Timers ───────────────────────────────────────
|
|
174
|
+
private settleTimer: NodeJS.Timeout | null = null;
|
|
175
|
+
private idleTimeout: NodeJS.Timeout | null = null;
|
|
176
|
+
private finishRetryTimer: NodeJS.Timeout | null = null;
|
|
177
|
+
private providerErrorRetryTimer: NodeJS.Timeout | null = null;
|
|
178
|
+
private providerErrorRetryKey = '';
|
|
179
|
+
|
|
180
|
+
// ── Debounce ─────────────────────────────────────
|
|
181
|
+
pendingScriptStatus: 'generating' | 'waiting_approval' | null = null;
|
|
182
|
+
pendingScriptStatusSince = 0;
|
|
183
|
+
private pendingScriptStatusTimer: NodeJS.Timeout | null = null;
|
|
184
|
+
|
|
185
|
+
// ── Idle candidate ───────────────────────────────
|
|
186
|
+
private idleFinishCandidate: IdleFinishCandidate | null = null;
|
|
187
|
+
|
|
188
|
+
// ── Idle confirmation grace ──────────────────────
|
|
189
|
+
/**
|
|
190
|
+
* `finishResponse` produces the `generating → idle` transition that
|
|
191
|
+
* coordinators interpret as "task complete". Some providers (antigravity-
|
|
192
|
+
* cli observed in the wild) briefly paint a screen that looks like an
|
|
193
|
+
* idle prompt between tool result frames while still actively running,
|
|
194
|
+
* which fired `response_finished` and broke completion semantics.
|
|
195
|
+
* We defer the actual idle transition by IDLE_CONFIRMATION_GRACE_MS and
|
|
196
|
+
* cancel it if the scripted detection re-detects generating during that
|
|
197
|
+
* window — a true completion stays idle for many seconds, so a 2-second
|
|
198
|
+
* grace is sufficient to filter the paint blip.
|
|
199
|
+
*/
|
|
200
|
+
private pendingIdleFinishTimer: NodeJS.Timeout | null = null;
|
|
201
|
+
private pendingIdleFinishAt = 0;
|
|
202
|
+
|
|
203
|
+
// ── Status history (debug) ───────────────────────
|
|
204
|
+
private statusHistory: { status: string; at: number; trigger?: string }[] = [];
|
|
205
|
+
private traceEntries: CliTraceEntry[] = [];
|
|
206
|
+
private traceSeq = 0;
|
|
207
|
+
private traceSessionId = '';
|
|
208
|
+
|
|
209
|
+
constructor(
|
|
210
|
+
private readonly provider: CliProviderModule,
|
|
211
|
+
private readonly runner: CliScriptRunner,
|
|
212
|
+
private readonly transport: CliTransportAccess,
|
|
213
|
+
private readonly callbacks: CliStateEngineCallbacks,
|
|
214
|
+
private readonly timeouts: Required<NonNullable<CliProviderModule['timeouts']>>,
|
|
215
|
+
) {}
|
|
216
|
+
|
|
217
|
+
// ─── Public API ────────────────────────────────────────────────────────
|
|
218
|
+
|
|
219
|
+
setStatus(status: CliSessionStatus['status'], trigger?: string): void {
|
|
220
|
+
const prev = this.currentStatus;
|
|
221
|
+
if (prev === status) return;
|
|
222
|
+
this.currentStatus = status;
|
|
223
|
+
this.statusHistory.push({ status, at: Date.now(), trigger });
|
|
224
|
+
if (this.statusHistory.length > 50) this.statusHistory.shift();
|
|
225
|
+
this.recordTrace('status', { previousStatus: prev, trigger: trigger || null });
|
|
226
|
+
LOG.info('CLI', `[${this.provider.type}] status: ${prev} → ${status}${trigger ? ` (${trigger})` : ''}`);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
scheduleSettle(): void {
|
|
230
|
+
if (this.settleTimer) clearTimeout(this.settleTimer);
|
|
231
|
+
const epoch = this.responseEpoch;
|
|
232
|
+
const delay = Math.max(
|
|
233
|
+
this.timeouts.outputSettle,
|
|
234
|
+
this.submitPendingUntil > Date.now()
|
|
235
|
+
? (this.submitPendingUntil - Date.now()) + this.timeouts.outputSettle
|
|
236
|
+
: 0,
|
|
237
|
+
);
|
|
238
|
+
this.settleTimer = setTimeout(() => {
|
|
239
|
+
this.settleTimer = null;
|
|
240
|
+
if (epoch !== this.responseEpoch) return;
|
|
241
|
+
this.evaluateSettled(this.transport.getSnapshot());
|
|
242
|
+
}, delay);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Called from sendMessage in transport once a turn scope is established. */
|
|
246
|
+
onTurnStarted(turnScope: TurnParseScope): void {
|
|
247
|
+
this.isWaitingForResponse = true;
|
|
248
|
+
this.finishRetryCount = 0;
|
|
249
|
+
this.clearIdleFinishCandidate('send_message');
|
|
250
|
+
this.currentTurnScope = turnScope;
|
|
251
|
+
// ARCH-REFACTOR R1: bind this turn's mesh taskId. A task-less (ad-hoc dashboard)
|
|
252
|
+
// turn carries no taskId → null here, which correctly clears any prior task's id
|
|
253
|
+
// so an ad-hoc turn's completion is never stamped with a stale taskId.
|
|
254
|
+
this.currentTurnTaskId = typeof turnScope.taskId === 'string' && turnScope.taskId.trim()
|
|
255
|
+
? turnScope.taskId
|
|
256
|
+
: null;
|
|
257
|
+
// R4d: stamp the turn-start moment so the startup-grace idle-stayed synthesis can
|
|
258
|
+
// anchor its window on dispatch time rather than completion time.
|
|
259
|
+
this.currentTurnStartedAt = Date.now();
|
|
260
|
+
this.responseEpoch += 1;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Called when PTY exits */
|
|
264
|
+
onPtyExit(): void {
|
|
265
|
+
this.clearAllTimers();
|
|
266
|
+
this.setStatus('stopped', 'pty_exit');
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** Called when adapter starts up successfully */
|
|
270
|
+
onSpawnReady(): void {
|
|
271
|
+
this.setStatus('starting', 'pty_ready');
|
|
272
|
+
this.traceEntries = [];
|
|
273
|
+
this.traceSeq = 0;
|
|
274
|
+
this.traceSessionId = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
275
|
+
this.recordTrace('session_start', { providerType: this.provider.type });
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
resolveModal(buttonIndex: number): void {
|
|
279
|
+
const snap = this.transport.getSnapshot();
|
|
280
|
+
const parseApproval = typeof this.transport.runParseApproval === 'function'
|
|
281
|
+
? (s: CliBufferSnapshot) => this.transport.runParseApproval!(s.recentOutputBuffer.slice(-500))
|
|
282
|
+
: (s: CliBufferSnapshot) => this.runParseApproval(s);
|
|
283
|
+
let modal = this.activeModal ?? parseApproval(snap);
|
|
284
|
+
|
|
285
|
+
if (!modal && this.runner.hasParseSession()) {
|
|
286
|
+
try {
|
|
287
|
+
const parsed = this.runParseSession(snap) as any;
|
|
288
|
+
const parsedModal = parsed?.activeModal && Array.isArray(parsed.activeModal.buttons)
|
|
289
|
+
&& parsed.activeModal.buttons.some((b: any) => typeof b === 'string' && b.trim())
|
|
290
|
+
? parsed.activeModal : null;
|
|
291
|
+
if (parsed?.status === 'waiting_approval' && parsedModal) {
|
|
292
|
+
modal = parsedModal;
|
|
293
|
+
// No modal was held (`this.activeModal` was null above), so a
|
|
294
|
+
// freshly parsed approval here is a new entry by definition.
|
|
295
|
+
this.activeModal = parsedModal;
|
|
296
|
+
this.approvalEntrySeq++;
|
|
297
|
+
if (this.currentStatus !== 'waiting_approval') {
|
|
298
|
+
this.setStatus('waiting_approval', 'resolve_modal_parse');
|
|
299
|
+
this.callbacks.onStatusChange();
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
} catch { /* ignore parse failures */ }
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
if (!this.transport.isAlive()) return;
|
|
306
|
+
// (fix) Hard fail-safe: never write an approval key without a concrete
|
|
307
|
+
// modal that has buttons. The previous gate `currentStatus !== 'WA' &&
|
|
308
|
+
// !modal` let resolveModal proceed whenever status was still pinned to
|
|
309
|
+
// waiting_approval, even if parseApproval had returned null. Combined
|
|
310
|
+
// with auto-approve and Claude's modal flapping (status==WA but modal
|
|
311
|
+
// briefly null between paints) this typed "1" into the prompt over and
|
|
312
|
+
// over. Require a real modal with at least one button.
|
|
313
|
+
const buttonsValid = Array.isArray(modal?.buttons)
|
|
314
|
+
&& modal.buttons.some((b: any) => typeof b === 'string' && b.trim());
|
|
315
|
+
if (!modal || !buttonsValid) return;
|
|
316
|
+
|
|
317
|
+
const currentModalMessage = typeof modal?.message === 'string' ? modal.message.trim() : '';
|
|
318
|
+
const inCooldown = !!this.lastApprovalResolvedAt
|
|
319
|
+
&& (Date.now() - this.lastApprovalResolvedAt) < this.timeouts.approvalCooldown;
|
|
320
|
+
// (fix) Suppress the duplicate key-write ONLY when this is the *same*
|
|
321
|
+
// approval entry re-observed across TUI paint flaps — i.e. the FSM has
|
|
322
|
+
// not entered waiting_approval afresh since the last resolve
|
|
323
|
+
// (approvalEntrySeq unchanged). A new entry (bumped seq) is always a
|
|
324
|
+
// distinct approval and must be written, even within the cooldown
|
|
325
|
+
// window and even when its message text matches the previous one.
|
|
326
|
+
//
|
|
327
|
+
// Previously this gated on message equality alone, so consecutive
|
|
328
|
+
// claude-cli approvals that share message text (very common) had the
|
|
329
|
+
// second write swallowed — the approval stuck unresolved despite
|
|
330
|
+
// auto-approval being on.
|
|
331
|
+
const sameEntryReResolve = this.approvalEntrySeq === this.lastResolvedEntrySeq;
|
|
332
|
+
if (inCooldown && sameEntryReResolve && currentModalMessage === this.lastResolvedModalMessage) return;
|
|
333
|
+
|
|
334
|
+
this.clearIdleFinishCandidate('resolve_modal');
|
|
335
|
+
this.recordTrace('resolve_modal', { buttonIndex, activeModal: modal, approvalEntrySeq: this.approvalEntrySeq });
|
|
336
|
+
this.activeModal = null;
|
|
337
|
+
this.lastApprovalResolvedAt = Date.now();
|
|
338
|
+
this.lastResolvedModalMessage = currentModalMessage;
|
|
339
|
+
this.lastResolvedEntrySeq = this.approvalEntrySeq;
|
|
340
|
+
this.responseSettleIgnoreUntil = Date.now() + this.timeouts.outputSettle + 400;
|
|
341
|
+
if (this.approvalExitTimeout) { clearTimeout(this.approvalExitTimeout); this.approvalExitTimeout = null; }
|
|
342
|
+
this.setStatus('generating', 'approval_resolved');
|
|
343
|
+
this.callbacks.onStatusChange();
|
|
344
|
+
|
|
345
|
+
const approvalKey = this.transport.getApprovalKeyForIndex(buttonIndex);
|
|
346
|
+
if (approvalKey !== undefined) {
|
|
347
|
+
this.transport.writeRaw(approvalKey);
|
|
348
|
+
} else {
|
|
349
|
+
const DOWN = '\x1B[B';
|
|
350
|
+
const buttonCount = Array.isArray(modal?.buttons) ? modal.buttons.length : 0;
|
|
351
|
+
const clamped = buttonCount > 0
|
|
352
|
+
? Math.min(Math.max(0, buttonIndex), buttonCount - 1)
|
|
353
|
+
: Math.max(0, buttonIndex);
|
|
354
|
+
this.transport.writeRaw(DOWN.repeat(clamped) + '\r');
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
isApprovalRecentlyResolved(): boolean {
|
|
359
|
+
return !!(this.lastApprovalResolvedAt
|
|
360
|
+
&& (Date.now() - this.lastApprovalResolvedAt) < this.timeouts.approvalCooldown);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* Called from sendMessage before starting a new turn.
|
|
365
|
+
* Clears stale idle response state when the terminal looks idle and no modal is active.
|
|
366
|
+
*/
|
|
367
|
+
clearStaleIdleResponseGuard(reason: string, snap: CliBufferSnapshot): boolean {
|
|
368
|
+
const blockingModal = this.activeModal
|
|
369
|
+
?? (typeof this.transport.runParseApproval === 'function'
|
|
370
|
+
? this.transport.runParseApproval(snap.recentOutputBuffer.slice(-500))
|
|
371
|
+
: this.runParseApproval(snap));
|
|
372
|
+
const isIdle = (typeof this.transport.runDetectStatus === 'function'
|
|
373
|
+
? this.transport.runDetectStatus(snap.recentOutputBuffer)
|
|
374
|
+
: this.runDetectStatus(snap)) === 'idle';
|
|
375
|
+
if (!this.isWaitingForResponse || this.currentStatus !== 'idle' || !isIdle || !!blockingModal) {
|
|
376
|
+
return false;
|
|
377
|
+
}
|
|
378
|
+
this.clearAllTimers();
|
|
379
|
+
this.clearIdleFinishCandidate(reason);
|
|
380
|
+
this.isWaitingForResponse = false;
|
|
381
|
+
this.responseSettleIgnoreUntil = 0;
|
|
382
|
+
this.submitRetryUsed = false;
|
|
383
|
+
this.submitRetryPromptSnippet = '';
|
|
384
|
+
this.finishRetryCount = 0;
|
|
385
|
+
this.currentTurnScope = null;
|
|
386
|
+
this.activeModal = null;
|
|
387
|
+
this.recordTrace('stale_idle_response_cleared', { reason });
|
|
388
|
+
this.callbacks.onTurnCompleted();
|
|
389
|
+
return true;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Called from sendMessage before starting a new turn.
|
|
394
|
+
* Clears stale idle response state when the parsed session confirms idle with a final assistant message.
|
|
395
|
+
*/
|
|
396
|
+
clearParsedIdleResponseGuard(reason: string, parsedStatus: any, snap: CliBufferSnapshot): boolean {
|
|
397
|
+
const parsedRawStatus = typeof parsedStatus?.status === 'string' ? parsedStatus.status.trim() : '';
|
|
398
|
+
const parsedModal = parsedStatus?.activeModal ?? parsedStatus?.modal ?? null;
|
|
399
|
+
const blockingModal = this.activeModal
|
|
400
|
+
?? (typeof this.transport.runParseApproval === 'function'
|
|
401
|
+
? this.transport.runParseApproval(snap.recentOutputBuffer.slice(-500))
|
|
402
|
+
: this.runParseApproval(snap));
|
|
403
|
+
if (
|
|
404
|
+
!this.isWaitingForResponse
|
|
405
|
+
|| parsedRawStatus !== 'idle'
|
|
406
|
+
|| !!parsedModal
|
|
407
|
+
|| !!blockingModal
|
|
408
|
+
|| !this.parsedStatusHasFinalAssistantMessage(parsedStatus)
|
|
409
|
+
) {
|
|
410
|
+
return false;
|
|
411
|
+
}
|
|
412
|
+
this.clearAllTimers();
|
|
413
|
+
this.clearIdleFinishCandidate(reason);
|
|
414
|
+
this.isWaitingForResponse = false;
|
|
415
|
+
this.responseSettleIgnoreUntil = 0;
|
|
416
|
+
this.submitRetryUsed = false;
|
|
417
|
+
this.submitRetryPromptSnippet = '';
|
|
418
|
+
this.finishRetryCount = 0;
|
|
419
|
+
this.currentTurnScope = null;
|
|
420
|
+
this.activeModal = null;
|
|
421
|
+
this.setStatus('idle', reason);
|
|
422
|
+
this.recordTrace('parsed_idle_response_cleared', {
|
|
423
|
+
reason,
|
|
424
|
+
parsedStatus: parsedRawStatus,
|
|
425
|
+
parsedMessageCount: Array.isArray(parsedStatus?.messages) ? parsedStatus.messages.length : 0,
|
|
426
|
+
});
|
|
427
|
+
this.callbacks.onTurnCompleted();
|
|
428
|
+
return true;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
clearAllTimers(): void {
|
|
432
|
+
if (this.settleTimer) { clearTimeout(this.settleTimer); this.settleTimer = null; }
|
|
433
|
+
if (this.idleTimeout) { clearTimeout(this.idleTimeout); this.idleTimeout = null; }
|
|
434
|
+
if (this.approvalExitTimeout) { clearTimeout(this.approvalExitTimeout); this.approvalExitTimeout = null; }
|
|
435
|
+
if (this.finishRetryTimer) { clearTimeout(this.finishRetryTimer); this.finishRetryTimer = null; }
|
|
436
|
+
if (this.pendingScriptStatusTimer) { clearTimeout(this.pendingScriptStatusTimer); this.pendingScriptStatusTimer = null; }
|
|
437
|
+
if (this.providerErrorRetryTimer) { clearTimeout(this.providerErrorRetryTimer); this.providerErrorRetryTimer = null; }
|
|
438
|
+
if (this.pendingIdleFinishTimer) { clearTimeout(this.pendingIdleFinishTimer); this.pendingIdleFinishTimer = null; this.pendingIdleFinishAt = 0; }
|
|
439
|
+
this.providerErrorRetryKey = '';
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
resetActiveTurnState(): void {
|
|
443
|
+
this.clearAllTimers();
|
|
444
|
+
this.isWaitingForResponse = false;
|
|
445
|
+
this.responseSettleIgnoreUntil = 0;
|
|
446
|
+
this.submitRetryUsed = false;
|
|
447
|
+
this.submitRetryPromptSnippet = '';
|
|
448
|
+
this.finishRetryCount = 0;
|
|
449
|
+
this.currentTurnScope = null;
|
|
450
|
+
this.activeModal = null;
|
|
451
|
+
this.pendingScriptStatus = null;
|
|
452
|
+
this.pendingScriptStatusSince = 0;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
clearIdleFinishCandidate(reason: string): void {
|
|
456
|
+
if (!this.idleFinishCandidate) return;
|
|
457
|
+
this.recordTrace('idle_candidate_reset', { reason, candidate: this.idleFinishCandidate });
|
|
458
|
+
this.idleFinishCandidate = null;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
hasActionableApproval(startupModal?: { message: string; buttons: string[] } | null): boolean {
|
|
462
|
+
return !!(startupModal ?? this.activeModal);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
getTraceEntries(): CliTraceEntry[] { return this.traceEntries; }
|
|
466
|
+
getStatusHistory(): { status: string; at: number; trigger?: string }[] { return this.statusHistory; }
|
|
467
|
+
getTraceSessionId(): string { return this.traceSessionId; }
|
|
468
|
+
|
|
469
|
+
/** Record a trace entry from the transport layer (e.g. output events in debug mode). */
|
|
470
|
+
recordExternalTrace(type: string, payload: Record<string, any> = {}): void {
|
|
471
|
+
this.recordTrace(type, payload);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// ─── Script dispatch (builds inputs from snapshot) ──────────────────────
|
|
475
|
+
|
|
476
|
+
runDetectStatus(snap: CliBufferSnapshot): string | null {
|
|
477
|
+
const tail = snap.recentOutputBuffer.slice(-500);
|
|
478
|
+
return this.runner.detectStatus({
|
|
479
|
+
tail,
|
|
480
|
+
screenText: snap.screenText,
|
|
481
|
+
rawBuffer: snap.accumulatedRawBuffer,
|
|
482
|
+
isWaitingForResponse: snap.isWaitingForResponse,
|
|
483
|
+
screen: buildCliScreenSnapshot(snap.screenText),
|
|
484
|
+
tailScreen: buildCliScreenSnapshot(tail),
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
runParseApproval(snap: CliBufferSnapshot): { message: string; buttons: string[] } | null {
|
|
489
|
+
const tail = snap.recentOutputBuffer.slice(-500);
|
|
490
|
+
const buffer = snap.screenText || snap.accumulatedBuffer;
|
|
491
|
+
return this.runner.parseApproval({
|
|
492
|
+
buffer,
|
|
493
|
+
screenText: snap.screenText,
|
|
494
|
+
rawBuffer: snap.accumulatedRawBuffer,
|
|
495
|
+
tail,
|
|
496
|
+
screen: buildCliScreenSnapshot(snap.screenText),
|
|
497
|
+
bufferScreen: buildCliScreenSnapshot(buffer),
|
|
498
|
+
tailScreen: buildCliScreenSnapshot(tail),
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
runParseSession(snap: CliBufferSnapshot): ParsedSession | null {
|
|
503
|
+
// Allow transport to override session parsing (enables test mocking)
|
|
504
|
+
if (typeof this.transport.runParseSession === 'function') {
|
|
505
|
+
const session = this.transport.runParseSession();
|
|
506
|
+
if (session && typeof session === 'object') {
|
|
507
|
+
this.callbacks.onApplyParsedSession(session);
|
|
508
|
+
}
|
|
509
|
+
return session;
|
|
510
|
+
}
|
|
511
|
+
const tail = snap.recentOutputBuffer.slice(-500);
|
|
512
|
+
const input = buildCliParseInput({
|
|
513
|
+
accumulatedBuffer: snap.accumulatedBuffer,
|
|
514
|
+
accumulatedRawBuffer: snap.accumulatedRawBuffer,
|
|
515
|
+
recentOutputBuffer: snap.recentOutputBuffer,
|
|
516
|
+
terminalScreenText: snap.parseScreenText,
|
|
517
|
+
workingDir: snap.workingDir,
|
|
518
|
+
providerSessionId: snap.providerSessionId || undefined,
|
|
519
|
+
historySessionId: snap.providerSessionId || undefined,
|
|
520
|
+
baseMessages: [],
|
|
521
|
+
partialResponse: snap.responseBuffer,
|
|
522
|
+
isWaitingForResponse: snap.isWaitingForResponse,
|
|
523
|
+
scope: snap.currentTurnScope,
|
|
524
|
+
runtimeSettings: snap.runtimeSettings,
|
|
525
|
+
});
|
|
526
|
+
const session = this.runner.parseSession({
|
|
527
|
+
...input,
|
|
528
|
+
tail,
|
|
529
|
+
tailScreen: buildCliScreenSnapshot(tail),
|
|
530
|
+
});
|
|
531
|
+
if (session && typeof session === 'object') {
|
|
532
|
+
this.callbacks.onApplyParsedSession(session);
|
|
533
|
+
}
|
|
534
|
+
return session;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// ─── Core evaluation loop ───────────────────────────────────────────────
|
|
538
|
+
|
|
539
|
+
evaluateSettled(snap: CliBufferSnapshot): void {
|
|
540
|
+
const now = Date.now();
|
|
541
|
+
if (this.submitPendingUntil > now || this.responseSettleIgnoreUntil > now) {
|
|
542
|
+
const delayTime = Math.max(this.submitPendingUntil - now, this.responseSettleIgnoreUntil - now) + 50;
|
|
543
|
+
if (this.settleTimer) clearTimeout(this.settleTimer);
|
|
544
|
+
this.settleTimer = setTimeout(() => {
|
|
545
|
+
this.settleTimer = null;
|
|
546
|
+
this.evaluateSettled(this.transport.getSnapshot());
|
|
547
|
+
}, delayTime);
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
if (!this.isWaitingForResponse && !this.currentTurnScope && !this.activeModal && !this.runner.parseErrorMessage) {
|
|
552
|
+
const tail = snap.recentOutputBuffer;
|
|
553
|
+
const modal = this.runParseApproval(snap);
|
|
554
|
+
const lightweightStatus = this.runner.hasDetectStatus() ? this.runDetectStatus(snap) : null;
|
|
555
|
+
if (!modal && lightweightStatus === 'idle' && this.currentStatus === 'idle') return;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
const session = this.runParseSession(snap);
|
|
559
|
+
if (!session) return;
|
|
560
|
+
|
|
561
|
+
const { status, messages } = session;
|
|
562
|
+
const modal = (session as any).activeModal ?? session.modal ?? null;
|
|
563
|
+
const parsedStatus = (session as any).parsedStatus ?? null;
|
|
564
|
+
const parsedMessages = normalizeCliParsedMessages(messages, {
|
|
565
|
+
scope: null,
|
|
566
|
+
lastOutputAt: snap.lastOutputAt,
|
|
567
|
+
});
|
|
568
|
+
|
|
569
|
+
if (this.maybeCommitVisibleIdleTranscript(session, parsedMessages, snap)) return;
|
|
570
|
+
|
|
571
|
+
const lastParsedAssistant = [...parsedMessages].reverse().find((m) => m.role === 'assistant');
|
|
572
|
+
|
|
573
|
+
if (
|
|
574
|
+
this.currentTurnScope
|
|
575
|
+
&& !lastParsedAssistant
|
|
576
|
+
&& !this.submitRetryUsed
|
|
577
|
+
&& this.transport.isAlive()
|
|
578
|
+
&& !this.hasActionableApproval()
|
|
579
|
+
&& promptLikelyVisible(snap.screenText, normalizePromptText(this.submitRetryPromptSnippet || this.currentTurnScope?.prompt || ''))
|
|
580
|
+
&& !this.hasMeaningfulResponseBuffer(snap, normalizePromptText(this.submitRetryPromptSnippet || this.currentTurnScope?.prompt || ''))
|
|
581
|
+
) {
|
|
582
|
+
this.submitRetryUsed = true;
|
|
583
|
+
this.responseSettleIgnoreUntil = Date.now() + this.timeouts.outputSettle + 400;
|
|
584
|
+
LOG.info('CLI', `[${this.provider.type}] Retrying submit key from settled parser (no assistant yet)`);
|
|
585
|
+
this.transport.writeRaw('\r');
|
|
586
|
+
if (this.settleTimer) clearTimeout(this.settleTimer);
|
|
587
|
+
this.settleTimer = setTimeout(() => {
|
|
588
|
+
this.settleTimer = null;
|
|
589
|
+
this.evaluateSettled(this.transport.getSnapshot());
|
|
590
|
+
}, this.timeouts.outputSettle + 150);
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
if (!status) return;
|
|
595
|
+
|
|
596
|
+
const prevStatus = this.currentStatus;
|
|
597
|
+
const ctx: SettledEvalContext = { now, modal, status, parsedMessages, lastParsedAssistant, parsedStatus: parsedStatus || null, prevStatus };
|
|
598
|
+
|
|
599
|
+
if (!this.applyPendingScriptStatusDebounce(ctx)) return;
|
|
600
|
+
|
|
601
|
+
const recentInteractiveActivity = this.hasRecentInteractiveActivity(snap, now);
|
|
602
|
+
LOG.debug(
|
|
603
|
+
'CLI',
|
|
604
|
+
`[${this.provider.type}] settled diagnostics prompt=${JSON.stringify(this.currentTurnScope?.prompt || '').slice(0, 140)} status=${String(status || '')} parsedStatus=${String(parsedStatus || '')} parsedMsgCount=${parsedMessages.length} lastParsedAssistant=${JSON.stringify((lastParsedAssistant?.content || '').slice(0, 120)).slice(0, 160)} responseBuffer=${JSON.stringify((snap.responseBuffer || '').slice(0, 160)).slice(0, 220)} recentActivity=${recentInteractiveActivity}`
|
|
605
|
+
);
|
|
606
|
+
|
|
607
|
+
// recent_activity_hold protects an in-flight user turn from a false
|
|
608
|
+
// idle blip. It must NOT fire during startup — when the adapter has
|
|
609
|
+
// no currentTurnScope, there is no user turn to protect; the recent
|
|
610
|
+
// activity is just the CLI painting its welcome screen. Firing here
|
|
611
|
+
// produced the startup status flip the user reported
|
|
612
|
+
// (generating → idle → generating → idle within the first few seconds
|
|
613
|
+
// of claude-cli launch).
|
|
614
|
+
//
|
|
615
|
+
// When isWaitingForResponse=true and a currentTurnScope is alive, a
|
|
616
|
+
// PTY quiet period (>statusActivityHold ms without output) does NOT
|
|
617
|
+
// mean the response is done — claude-cli regularly pauses 2s+ between
|
|
618
|
+
// chunks during parsing/generation. recentInteractiveActivity going
|
|
619
|
+
// false during such a pause was the root cause of false-idle
|
|
620
|
+
// regressions. We hold generating whenever an active response turn is
|
|
621
|
+
// in flight (unconditionally, not just when there was recent output).
|
|
622
|
+
// The real completion gate is applyIdle's idleFinishCandidate +
|
|
623
|
+
// idleFinish timeout, which requires stable quiet AND a parsed
|
|
624
|
+
// assistant message.
|
|
625
|
+
//
|
|
626
|
+
// Fast-path exception: only release the hold if the parser shows a
|
|
627
|
+
// *current-turn* final standard assistant after the last user message,
|
|
628
|
+
// and it is not still streaming. Using !!lastParsedAssistant was too
|
|
629
|
+
// broad — it matched previous-turn assistant messages and caused
|
|
630
|
+
// false-idle between the first assistant text chunk and the first
|
|
631
|
+
// tool call (the agent outputs text, then immediately begins tool use;
|
|
632
|
+
// the gap between them hit this fast path and committed idle).
|
|
633
|
+
const hasFinalCurrentTurnAssistant = (() => {
|
|
634
|
+
if (parsedStatus !== 'idle') return false;
|
|
635
|
+
const msgs: any[] = Array.isArray(parsedMessages) ? parsedMessages : [];
|
|
636
|
+
let lastUserIdx = -1;
|
|
637
|
+
for (let i = msgs.length - 1; i >= 0; i--) {
|
|
638
|
+
if (msgs[i]?.role === 'user') { lastUserIdx = i; break; }
|
|
639
|
+
}
|
|
640
|
+
// No user message visible: fall back to any non-streaming standard assistant.
|
|
641
|
+
const searchSlice = lastUserIdx >= 0 ? msgs.slice(lastUserIdx + 1) : msgs;
|
|
642
|
+
return searchSlice.some((m: any) => {
|
|
643
|
+
if (!m || m.role !== 'assistant') return false;
|
|
644
|
+
if (typeof m.content !== 'string' || !m.content.trim()) return false;
|
|
645
|
+
const kind = typeof m.kind === 'string' && m.kind.trim() ? m.kind.trim() : 'standard';
|
|
646
|
+
return kind === 'standard' && m.meta?.streaming !== true;
|
|
647
|
+
});
|
|
648
|
+
})();
|
|
649
|
+
const shouldHoldGenerating = status === 'idle'
|
|
650
|
+
&& this.isWaitingForResponse
|
|
651
|
+
&& !!this.currentTurnScope
|
|
652
|
+
&& !modal
|
|
653
|
+
&& !hasFinalCurrentTurnAssistant;
|
|
654
|
+
|
|
655
|
+
if (shouldHoldGenerating) { this.applyHoldGenerating(ctx); return; }
|
|
656
|
+
if (status === 'error') {
|
|
657
|
+
if (this.maybeScheduleProviderErrorRetry(ctx, session, snap)) return;
|
|
658
|
+
this.applyError(ctx, session);
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
if (status === 'waiting_approval') { this.applyWaitingApproval(ctx); return; }
|
|
662
|
+
if (status === 'generating') { this.applyGenerating(ctx); return; }
|
|
663
|
+
if (status === 'idle') { this.applyIdle(ctx, snap, now); }
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
// ─── State transitions ──────────────────────────────────────────────────
|
|
667
|
+
|
|
668
|
+
private applyPendingScriptStatusDebounce(ctx: SettledEvalContext): boolean {
|
|
669
|
+
const { now, status, prevStatus } = ctx;
|
|
670
|
+
const shouldDebounce = prevStatus === 'idle' && !this.isWaitingForResponse
|
|
671
|
+
&& !this.currentTurnScope && (status === 'generating' || status === 'waiting_approval');
|
|
672
|
+
|
|
673
|
+
if (!shouldDebounce) {
|
|
674
|
+
this.pendingScriptStatus = null;
|
|
675
|
+
this.pendingScriptStatusSince = 0;
|
|
676
|
+
if (this.pendingScriptStatusTimer) { clearTimeout(this.pendingScriptStatusTimer); this.pendingScriptStatusTimer = null; }
|
|
677
|
+
return true;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
const armPending = (delayMs: number) => {
|
|
681
|
+
if (this.pendingScriptStatusTimer) clearTimeout(this.pendingScriptStatusTimer);
|
|
682
|
+
this.pendingScriptStatusTimer = setTimeout(() => {
|
|
683
|
+
this.pendingScriptStatusTimer = null;
|
|
684
|
+
this.evaluateSettled(this.transport.getSnapshot());
|
|
685
|
+
}, delayMs);
|
|
686
|
+
};
|
|
687
|
+
|
|
688
|
+
if (this.pendingScriptStatus !== status) {
|
|
689
|
+
this.pendingScriptStatus = status as 'generating' | 'waiting_approval';
|
|
690
|
+
this.pendingScriptStatusSince = now;
|
|
691
|
+
armPending(SCRIPT_STATUS_DEBOUNCE_MS);
|
|
692
|
+
return false;
|
|
693
|
+
}
|
|
694
|
+
const elapsed = now - this.pendingScriptStatusSince;
|
|
695
|
+
if (elapsed < SCRIPT_STATUS_DEBOUNCE_MS) { armPending(SCRIPT_STATUS_DEBOUNCE_MS - elapsed); return false; }
|
|
696
|
+
return true;
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
private applyHoldGenerating(ctx: SettledEvalContext): void {
|
|
700
|
+
this.clearIdleFinishCandidate('hold_generating_recent_activity');
|
|
701
|
+
this.setStatus('generating', 'recent_activity_hold');
|
|
702
|
+
if (this.idleTimeout) clearTimeout(this.idleTimeout);
|
|
703
|
+
this.idleTimeout = setTimeout(() => {
|
|
704
|
+
if (this.isWaitingForResponse && !this.hasActionableApproval()) {
|
|
705
|
+
if (this.shouldDeferIdleTimeoutFinish()) return;
|
|
706
|
+
this.finishResponse();
|
|
707
|
+
}
|
|
708
|
+
}, this.timeouts.generatingIdle);
|
|
709
|
+
this.callbacks.onStatusChange();
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
private applyWaitingApproval(ctx: SettledEvalContext): void {
|
|
713
|
+
const { modal } = ctx;
|
|
714
|
+
this.clearIdleFinishCandidate('waiting_approval');
|
|
715
|
+
const inCooldown = this.lastApprovalResolvedAt
|
|
716
|
+
&& (Date.now() - this.lastApprovalResolvedAt) < this.timeouts.approvalCooldown;
|
|
717
|
+
if (inCooldown && !modal) {
|
|
718
|
+
if (this.approvalExitTimeout) { clearTimeout(this.approvalExitTimeout); this.approvalExitTimeout = null; }
|
|
719
|
+
this.activeModal = null;
|
|
720
|
+
const reason = inCooldown ? 'approval_cooldown_non_actionable' : 'approval_prompt_gone_non_actionable';
|
|
721
|
+
if (this.isWaitingForResponse) {
|
|
722
|
+
this.setStatus('idle', reason);
|
|
723
|
+
if (this.idleTimeout) clearTimeout(this.idleTimeout);
|
|
724
|
+
this.idleTimeout = setTimeout(() => {
|
|
725
|
+
if (this.isWaitingForResponse && !this.hasActionableApproval()) {
|
|
726
|
+
if (this.shouldDeferIdleTimeoutFinish()) return;
|
|
727
|
+
this.finishResponse();
|
|
728
|
+
}
|
|
729
|
+
}, this.timeouts.generatingIdle);
|
|
730
|
+
} else {
|
|
731
|
+
this.setStatus('idle', reason);
|
|
732
|
+
}
|
|
733
|
+
this.callbacks.onStatusChange();
|
|
734
|
+
return;
|
|
735
|
+
}
|
|
736
|
+
// (fix) A *real* modal with valid buttons surfacing during the cooldown
|
|
737
|
+
// window is a genuinely new approval, not a trailing repaint of the one
|
|
738
|
+
// we just resolved — resolveModal cleared activeModal and flipped status
|
|
739
|
+
// to generating, so detectStatus only re-reports waiting_approval with a
|
|
740
|
+
// concrete modal when the CLI actually presents the next prompt.
|
|
741
|
+
// Previously this case fell through BOTH the `inCooldown && !modal`
|
|
742
|
+
// branch above and the `!inCooldown` branch below, so the FSM silently
|
|
743
|
+
// ignored the second approval — leaving it stuck unresolved under
|
|
744
|
+
// auto-approval. Capture it like any fresh entry (the modal-message
|
|
745
|
+
// cooldown still de-dupes the same approval inside resolveModal, now
|
|
746
|
+
// keyed on approvalEntrySeq). The `!modal` flap case stays gated by
|
|
747
|
+
// cooldown above; only an actionable new modal breaks through here.
|
|
748
|
+
if (!inCooldown || modal) {
|
|
749
|
+
if (!modal) {
|
|
750
|
+
LOG.warn('CLI', `[${this.provider.type}] detectStatus=waiting_approval but parseApproval returned null; ignoring`);
|
|
751
|
+
// (fix) If we previously surfaced waiting_approval but the
|
|
752
|
+
// modal extraction is now failing, eventually drop the modal
|
|
753
|
+
// and fall back to generating so the dashboard doesn't show
|
|
754
|
+
// a "waiting" badge with no buttons. BUT defer the transition
|
|
755
|
+
// for a hysteresis window — Claude TUI re-renders parts of
|
|
756
|
+
// the approval frame multiple times per second and the
|
|
757
|
+
// intermediate parses occasionally lose buttons for a single
|
|
758
|
+
// pass. Flapping the engine status WA → generating → WA →
|
|
759
|
+
// generating between paints fed auto-approve a fresh modal
|
|
760
|
+
// signature each time, which typed the approval key
|
|
761
|
+
// ("1") into the prompt repeatedly. Wait for the modal to
|
|
762
|
+
// stay gone for `approvalCooldown` before clearing.
|
|
763
|
+
if (this.currentStatus === 'waiting_approval' && this.activeModal) {
|
|
764
|
+
const lostAt = this.modalLostAt || Date.now();
|
|
765
|
+
if (!this.modalLostAt) this.modalLostAt = lostAt;
|
|
766
|
+
if (Date.now() - lostAt >= this.timeouts.approvalCooldown) {
|
|
767
|
+
this.activeModal = null;
|
|
768
|
+
this.modalLostAt = 0;
|
|
769
|
+
this.setStatus('generating', 'approval_lost_modal');
|
|
770
|
+
this.callbacks.onStatusChange();
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
this.modalLostAt = 0;
|
|
776
|
+
this.isWaitingForResponse = true;
|
|
777
|
+
this.setStatus('waiting_approval', 'script_detect');
|
|
778
|
+
// (fix) Don't overwrite an already-captured modal with a fresh
|
|
779
|
+
// re-parse on every evaluate — Claude TUI redraws option labels
|
|
780
|
+
// partially between paints (e.g. "Yes, and don't ask again for ..."
|
|
781
|
+
// is wider than the row and ships with a different trailing
|
|
782
|
+
// string each paint), which made the dashboard flap the modal
|
|
783
|
+
// signature continuously. Keep the first stable modal whose
|
|
784
|
+
// button count matches the latest parse; only swap when the
|
|
785
|
+
// shape clearly changed (different number of buttons → different
|
|
786
|
+
// approval).
|
|
787
|
+
const prev = this.activeModal;
|
|
788
|
+
const prevBtnCount = Array.isArray(prev?.buttons) ? prev!.buttons.length : 0;
|
|
789
|
+
const nextBtnCount = Array.isArray(modal.buttons) ? modal.buttons.length : 0;
|
|
790
|
+
if (!prev || prevBtnCount !== nextBtnCount) {
|
|
791
|
+
this.activeModal = modal;
|
|
792
|
+
// A fresh modal was captured (none held, or the button shape
|
|
793
|
+
// changed). This is a distinct approval entry — bump the seq so
|
|
794
|
+
// resolveModal's message-equality cooldown does not mistake it
|
|
795
|
+
// for a flap-repaint of the previously resolved approval.
|
|
796
|
+
this.approvalEntrySeq++;
|
|
797
|
+
this.callbacks.onStatusChange();
|
|
798
|
+
}
|
|
799
|
+
if (this.idleTimeout) clearTimeout(this.idleTimeout);
|
|
800
|
+
this.armApprovalExitTimeout();
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
private applyGenerating(ctx: SettledEvalContext): void {
|
|
805
|
+
const { modal, parsedMessages, lastParsedAssistant, parsedStatus, prevStatus } = ctx;
|
|
806
|
+
const noActiveTurn = !this.currentTurnScope;
|
|
807
|
+
// If the turn is already complete (isWaitingForResponse=false, no scope,
|
|
808
|
+
// no modal), PTY generating blips are just the CLI repainting its prompt.
|
|
809
|
+
// Check BEFORE cancelling the pending idle-finish timer — we don't want
|
|
810
|
+
// to cancel a scheduled idle transition just because the CLI blinked.
|
|
811
|
+
if (!this.isWaitingForResponse && noActiveTurn && !modal) return;
|
|
812
|
+
this.clearIdleFinishCandidate('generating');
|
|
813
|
+
// Cancel any pending grace-window idle transition. We have fresh
|
|
814
|
+
// evidence the provider is still generating; the previous
|
|
815
|
+
// finishResponse() was a paint blip, not a real completion.
|
|
816
|
+
this.cancelPendingIdleFinish('generating_signal_returned');
|
|
817
|
+
const snap = this.transport.getSnapshot();
|
|
818
|
+
const effectiveScreenText = snap.screenText || snap.accumulatedBuffer;
|
|
819
|
+
const looksIdleChrome = /(^|\n)\s*[❯›>]\s*(?:\n|$)/m.test(effectiveScreenText);
|
|
820
|
+
const parsedShowsLiveProgress = parsedStatus === 'generating' && !!lastParsedAssistant;
|
|
821
|
+
if (prevStatus === 'idle' && !this.isWaitingForResponse && noActiveTurn && !modal && looksIdleChrome && !parsedShowsLiveProgress) return;
|
|
822
|
+
if (prevStatus === 'waiting_approval') {
|
|
823
|
+
if (this.approvalExitTimeout) { clearTimeout(this.approvalExitTimeout); this.approvalExitTimeout = null; }
|
|
824
|
+
this.activeModal = null;
|
|
825
|
+
this.lastApprovalResolvedAt = Date.now();
|
|
826
|
+
}
|
|
827
|
+
if (!this.isWaitingForResponse) { this.isWaitingForResponse = true; }
|
|
828
|
+
this.setStatus('generating', 'script_detect');
|
|
829
|
+
if (this.idleTimeout) clearTimeout(this.idleTimeout);
|
|
830
|
+
this.idleTimeout = setTimeout(() => {
|
|
831
|
+
if (this.isWaitingForResponse) {
|
|
832
|
+
if (this.shouldDeferIdleTimeoutFinish()) return;
|
|
833
|
+
this.finishResponse();
|
|
834
|
+
}
|
|
835
|
+
}, this.timeouts.generatingIdle);
|
|
836
|
+
this.callbacks.onStatusChange();
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
private applyError(ctx: SettledEvalContext, session: ParsedSession): void {
|
|
840
|
+
this.clearIdleFinishCandidate('provider_error');
|
|
841
|
+
this.clearAllTimers();
|
|
842
|
+
this.isWaitingForResponse = false;
|
|
843
|
+
this.responseSettleIgnoreUntil = 0;
|
|
844
|
+
this.submitRetryUsed = false;
|
|
845
|
+
this.submitRetryPromptSnippet = '';
|
|
846
|
+
this.finishRetryCount = 0;
|
|
847
|
+
this.currentTurnScope = null;
|
|
848
|
+
this.activeModal = null;
|
|
849
|
+
this.providerErrorMessage = typeof session.errorMessage === 'string' && session.errorMessage.trim()
|
|
850
|
+
? session.errorMessage.trim() : 'Provider reported an error';
|
|
851
|
+
this.providerErrorReason = typeof session.errorReason === 'string' && session.errorReason.trim()
|
|
852
|
+
? session.errorReason.trim() : 'provider_error';
|
|
853
|
+
this.setStatus('error', this.providerErrorReason);
|
|
854
|
+
this.callbacks.onStatusChange();
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
private maybeScheduleProviderErrorRetry(ctx: SettledEvalContext, session: ParsedSession, snap: CliBufferSnapshot): boolean {
|
|
858
|
+
const retryPrompt = typeof (session as any).retryPrompt === 'string' ? String((session as any).retryPrompt).trim() : '';
|
|
859
|
+
const retryDelayMs = typeof (session as any).retryDelayMs === 'number' ? Number((session as any).retryDelayMs) : NaN;
|
|
860
|
+
if (!retryPrompt || !Number.isFinite(retryDelayMs) || retryDelayMs < 0 || !this.transport.isAlive()) return false;
|
|
861
|
+
|
|
862
|
+
const retryAttempt = typeof (session as any).retryAttempt === 'number' ? Number((session as any).retryAttempt) : 0;
|
|
863
|
+
const errorReason = typeof session.errorReason === 'string' && session.errorReason.trim() ? session.errorReason.trim() : 'provider_error';
|
|
864
|
+
const retryKey = `${errorReason}:${retryAttempt}:${retryPrompt}`;
|
|
865
|
+
if (this.providerErrorRetryTimer && this.providerErrorRetryKey === retryKey) return true;
|
|
866
|
+
|
|
867
|
+
if (this.providerErrorRetryTimer) clearTimeout(this.providerErrorRetryTimer);
|
|
868
|
+
this.providerErrorRetryKey = retryKey;
|
|
869
|
+
this.clearIdleFinishCandidate('provider_error_retry');
|
|
870
|
+
if (this.idleTimeout) { clearTimeout(this.idleTimeout); this.idleTimeout = null; }
|
|
871
|
+
if (this.approvalExitTimeout) { clearTimeout(this.approvalExitTimeout); this.approvalExitTimeout = null; }
|
|
872
|
+
this.providerErrorMessage = typeof session.errorMessage === 'string' && session.errorMessage.trim()
|
|
873
|
+
? session.errorMessage.trim() : 'Provider reported an error';
|
|
874
|
+
this.providerErrorReason = errorReason;
|
|
875
|
+
this.activeModal = null;
|
|
876
|
+
this.responseSettleIgnoreUntil = Date.now() + retryDelayMs + this.timeouts.outputSettle + 400;
|
|
877
|
+
this.setStatus('generating', 'provider_error_retry_scheduled');
|
|
878
|
+
this.callbacks.onStatusChange();
|
|
879
|
+
|
|
880
|
+
this.providerErrorRetryTimer = setTimeout(() => {
|
|
881
|
+
this.providerErrorRetryTimer = null;
|
|
882
|
+
this.providerErrorRetryKey = '';
|
|
883
|
+
if (!this.transport.isAlive()) return;
|
|
884
|
+
this.responseSettleIgnoreUntil = Date.now() + this.timeouts.outputSettle + 400;
|
|
885
|
+
this.submitRetryUsed = false;
|
|
886
|
+
this.transport.writeRaw(`${retryPrompt}\r`);
|
|
887
|
+
if (this.settleTimer) clearTimeout(this.settleTimer);
|
|
888
|
+
this.settleTimer = setTimeout(() => {
|
|
889
|
+
this.settleTimer = null;
|
|
890
|
+
this.evaluateSettled(this.transport.getSnapshot());
|
|
891
|
+
}, this.timeouts.outputSettle + 150);
|
|
892
|
+
}, retryDelayMs);
|
|
893
|
+
return true;
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
private applyIdle(ctx: SettledEvalContext, snap: CliBufferSnapshot, now: number): void {
|
|
897
|
+
const { modal, lastParsedAssistant, prevStatus } = ctx;
|
|
898
|
+
if (prevStatus === 'waiting_approval') {
|
|
899
|
+
if (this.approvalExitTimeout) { clearTimeout(this.approvalExitTimeout); this.approvalExitTimeout = null; }
|
|
900
|
+
this.activeModal = null;
|
|
901
|
+
this.lastApprovalResolvedAt = Date.now();
|
|
902
|
+
this.setStatus('idle', 'approval_prompt_gone_script_idle');
|
|
903
|
+
}
|
|
904
|
+
if (!this.isWaitingForResponse) {
|
|
905
|
+
if (prevStatus !== 'idle') {
|
|
906
|
+
this.clearIdleFinishCandidate('idle_without_response');
|
|
907
|
+
this.setStatus('idle', 'script_detect');
|
|
908
|
+
this.callbacks.onStatusChange();
|
|
909
|
+
}
|
|
910
|
+
return;
|
|
911
|
+
}
|
|
912
|
+
const quietForMs = snap.lastNonEmptyOutputAt ? (now - snap.lastNonEmptyOutputAt) : Number.MAX_SAFE_INTEGER;
|
|
913
|
+
const screenStableMs = snap.lastScreenChangeAt ? (now - snap.lastScreenChangeAt) : 0;
|
|
914
|
+
const hasAssistantTurn = !!lastParsedAssistant;
|
|
915
|
+
const assistantLength = (lastParsedAssistant as any)?.content?.length || 0;
|
|
916
|
+
const idleFinishConfirmMs = this.timeouts.idleFinishConfirm;
|
|
917
|
+
const idleQuietThresholdMs = Math.max(idleFinishConfirmMs, this.timeouts.outputSettle);
|
|
918
|
+
const idleReady = !modal && hasAssistantTurn && quietForMs >= idleQuietThresholdMs && screenStableMs >= idleFinishConfirmMs;
|
|
919
|
+
const candidate = this.idleFinishCandidate;
|
|
920
|
+
const candidateQuiet = !!candidate && candidate.responseEpoch === this.responseEpoch
|
|
921
|
+
&& candidate.lastOutputAt === snap.lastOutputAt
|
|
922
|
+
&& candidate.lastScreenChangeAt === snap.lastScreenChangeAt
|
|
923
|
+
&& assistantLength >= candidate.assistantLength
|
|
924
|
+
&& (now - candidate.armedAt) >= idleFinishConfirmMs;
|
|
925
|
+
|
|
926
|
+
if (idleReady && candidateQuiet) {
|
|
927
|
+
this.clearIdleFinishCandidate('finish_response');
|
|
928
|
+
if (this.idleTimeout) clearTimeout(this.idleTimeout);
|
|
929
|
+
this.finishResponse();
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
if (idleReady) {
|
|
934
|
+
if (!candidate) { this.armIdleFinishCandidate(snap, assistantLength); return; }
|
|
935
|
+
} else {
|
|
936
|
+
this.clearIdleFinishCandidate('idle_not_ready');
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
if (this.idleTimeout) clearTimeout(this.idleTimeout);
|
|
940
|
+
this.idleTimeout = setTimeout(() => {
|
|
941
|
+
if (this.isWaitingForResponse && !this.hasActionableApproval()) {
|
|
942
|
+
if (this.shouldDeferIdleTimeoutFinish()) return;
|
|
943
|
+
const parsed = this.runParseSession(this.transport.getSnapshot());
|
|
944
|
+
if (this.shouldDeferFinishForTranscript(parsed)) {
|
|
945
|
+
this.rescheduleTranscriptFinishCheck('transcript_idle_timeout_not_final');
|
|
946
|
+
return;
|
|
947
|
+
}
|
|
948
|
+
this.clearIdleFinishCandidate('idle_timeout_finish');
|
|
949
|
+
this.finishResponse();
|
|
950
|
+
}
|
|
951
|
+
}, this.timeouts.idleFinish);
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
finishResponse(): void {
|
|
955
|
+
if (this.submitPendingUntil > Date.now()) return;
|
|
956
|
+
if (this.responseSettleIgnoreUntil > Date.now()) return;
|
|
957
|
+
const snap = this.transport.getSnapshot();
|
|
958
|
+
const parsedBeforeFinish = this.runParseSession(snap);
|
|
959
|
+
if (this.shouldDeferFinishForTranscript(parsedBeforeFinish)) {
|
|
960
|
+
this.rescheduleTranscriptFinishCheck('transcript_finish_not_final');
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
963
|
+
this.clearIdleFinishCandidate('finish_response_enter');
|
|
964
|
+
const commitResult = this.commitCurrentTranscript(snap);
|
|
965
|
+
if (this.shouldRetryFinishResponse(snap, commitResult)) {
|
|
966
|
+
this.finishRetryCount += 1;
|
|
967
|
+
if (this.finishRetryTimer) clearTimeout(this.finishRetryTimer);
|
|
968
|
+
this.finishRetryTimer = setTimeout(() => {
|
|
969
|
+
this.finishRetryTimer = null;
|
|
970
|
+
if (this.isWaitingForResponse && !this.hasActionableApproval()) this.finishResponse();
|
|
971
|
+
}, FINISH_RETRY_DELAY_MS);
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
this.resetActiveTurnState();
|
|
975
|
+
this.callbacks.onTurnCompleted();
|
|
976
|
+
// Defer the actual `generating → idle` transition by a short grace
|
|
977
|
+
// window. If applyGenerating fires again before the grace expires —
|
|
978
|
+
// antigravity's tool-result paint blips do this — cancelPendingIdle
|
|
979
|
+
// Finish() drops the pending transition and we stay generating.
|
|
980
|
+
this.scheduleIdleFinish('response_finished');
|
|
981
|
+
this.transport.flushOutboundQueue();
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
private scheduleIdleFinish(reason: string): void {
|
|
985
|
+
// If we are already deferring, replace the schedule so the most
|
|
986
|
+
// recent finishResponse "wins". Reasons accumulate via the trigger.
|
|
987
|
+
if (this.pendingIdleFinishTimer) clearTimeout(this.pendingIdleFinishTimer);
|
|
988
|
+
this.pendingIdleFinishAt = Date.now() + IDLE_CONFIRMATION_GRACE_MS;
|
|
989
|
+
this.pendingIdleFinishTimer = setTimeout(() => {
|
|
990
|
+
this.pendingIdleFinishTimer = null;
|
|
991
|
+
this.pendingIdleFinishAt = 0;
|
|
992
|
+
// If a new user turn started during the grace window, we owe
|
|
993
|
+
// generating semantics to that turn — do not retroactively idle.
|
|
994
|
+
if (this.isWaitingForResponse) return;
|
|
995
|
+
// The timer firing without a cancelPendingIdleFinish call means
|
|
996
|
+
// no fresh applyGenerating happened during the grace window;
|
|
997
|
+
// the previous fake-blip is over. Commit the idle.
|
|
998
|
+
//
|
|
999
|
+
// Note: the previous "currentStatus === 'generating' → return"
|
|
1000
|
+
// guard caused stuck-generating sessions — finishResponse leaves
|
|
1001
|
+
// currentStatus='generating' on purpose (so the dashboard keeps
|
|
1002
|
+
// the spinner during the 2s grace), and then the timer fired
|
|
1003
|
+
// without cancellation but refused to commit because the very
|
|
1004
|
+
// status we are about to transition out of was still set.
|
|
1005
|
+
// Re-checking currentStatus there meant idle was unreachable.
|
|
1006
|
+
this.setStatus('idle', reason);
|
|
1007
|
+
this.callbacks.onStatusChange();
|
|
1008
|
+
}, IDLE_CONFIRMATION_GRACE_MS);
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
private cancelPendingIdleFinish(reason: string): void {
|
|
1012
|
+
if (!this.pendingIdleFinishTimer) return;
|
|
1013
|
+
clearTimeout(this.pendingIdleFinishTimer);
|
|
1014
|
+
this.pendingIdleFinishTimer = null;
|
|
1015
|
+
this.pendingIdleFinishAt = 0;
|
|
1016
|
+
this.recordTrace('idle_finish_cancelled', { trigger: reason });
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
// ─── Helpers ────────────────────────────────────────────────────────────
|
|
1020
|
+
|
|
1021
|
+
private armApprovalExitTimeout(): void {
|
|
1022
|
+
if (this.approvalExitTimeout) clearTimeout(this.approvalExitTimeout);
|
|
1023
|
+
this.approvalExitTimeout = setTimeout(() => {
|
|
1024
|
+
if (!this.hasActionableApproval()) return;
|
|
1025
|
+
const snap = this.transport.getSnapshot();
|
|
1026
|
+
const modal = typeof this.transport.runParseApproval === 'function'
|
|
1027
|
+
? this.transport.runParseApproval(snap.recentOutputBuffer.slice(-500))
|
|
1028
|
+
: this.runParseApproval(snap);
|
|
1029
|
+
const detectStatus = typeof this.transport.runDetectStatus === 'function'
|
|
1030
|
+
? this.transport.runDetectStatus(snap.recentOutputBuffer)
|
|
1031
|
+
: this.runDetectStatus(snap);
|
|
1032
|
+
const stillWaiting = detectStatus === 'waiting_approval' || !!modal;
|
|
1033
|
+
if (stillWaiting) {
|
|
1034
|
+
if (!modal) {
|
|
1035
|
+
LOG.warn('CLI', `[${this.provider.type}] approval timeout: no actionable modal; keeping fail-closed`);
|
|
1036
|
+
this.activeModal = null;
|
|
1037
|
+
this.callbacks.onStatusChange();
|
|
1038
|
+
this.armApprovalExitTimeout();
|
|
1039
|
+
return;
|
|
1040
|
+
}
|
|
1041
|
+
this.activeModal = modal;
|
|
1042
|
+
this.callbacks.onStatusChange();
|
|
1043
|
+
this.armApprovalExitTimeout();
|
|
1044
|
+
return;
|
|
1045
|
+
}
|
|
1046
|
+
LOG.warn('CLI', `[${this.provider.type}] Approval timeout — auto-clearing`);
|
|
1047
|
+
this.activeModal = null;
|
|
1048
|
+
this.lastApprovalResolvedAt = Date.now();
|
|
1049
|
+
this.setStatus('idle', 'approval_timeout');
|
|
1050
|
+
this.callbacks.onStatusChange();
|
|
1051
|
+
}, APPROVAL_EXIT_TIMEOUT_MS);
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
private armIdleFinishCandidate(snap: CliBufferSnapshot, assistantLength: number): void {
|
|
1055
|
+
const now = Date.now();
|
|
1056
|
+
this.idleFinishCandidate = {
|
|
1057
|
+
armedAt: now,
|
|
1058
|
+
lastOutputAt: snap.lastOutputAt,
|
|
1059
|
+
lastScreenChangeAt: snap.lastScreenChangeAt,
|
|
1060
|
+
responseEpoch: this.responseEpoch,
|
|
1061
|
+
assistantLength,
|
|
1062
|
+
};
|
|
1063
|
+
if (this.settleTimer) clearTimeout(this.settleTimer);
|
|
1064
|
+
this.settleTimer = setTimeout(() => {
|
|
1065
|
+
this.settleTimer = null;
|
|
1066
|
+
this.evaluateSettled(this.transport.getSnapshot());
|
|
1067
|
+
}, this.timeouts.idleFinishConfirm);
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
private shouldDeferIdleTimeoutFinish(): boolean {
|
|
1071
|
+
if (!this.isWaitingForResponse || this.hasActionableApproval()) return false;
|
|
1072
|
+
const snap = this.transport.getSnapshot();
|
|
1073
|
+
const detectFn = typeof this.transport.runDetectStatus === 'function'
|
|
1074
|
+
? () => this.transport.runDetectStatus!(snap.recentOutputBuffer)
|
|
1075
|
+
: () => this.runDetectStatus(snap);
|
|
1076
|
+
const latestStatus = detectFn() || this.currentStatus;
|
|
1077
|
+
if (latestStatus === 'generating') {
|
|
1078
|
+
this.evaluateSettled(snap);
|
|
1079
|
+
return true;
|
|
1080
|
+
}
|
|
1081
|
+
return false;
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
private hasRecentInteractiveActivity(snap: CliBufferSnapshot, now: number): boolean {
|
|
1085
|
+
const quietForMs = snap.lastNonEmptyOutputAt ? (now - snap.lastNonEmptyOutputAt) : Number.MAX_SAFE_INTEGER;
|
|
1086
|
+
const screenStableMs = snap.lastScreenChangeAt ? (now - snap.lastScreenChangeAt) : Number.MAX_SAFE_INTEGER;
|
|
1087
|
+
return quietForMs < this.timeouts.statusActivityHold || screenStableMs < this.timeouts.statusActivityHold;
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
private hasMeaningfulResponseBuffer(snap: CliBufferSnapshot, normalizedPromptSnippet: string): boolean {
|
|
1091
|
+
const raw = String(snap.responseBuffer || '').trim();
|
|
1092
|
+
if (!raw) return false;
|
|
1093
|
+
const normalizedPrompt = compactPromptText(normalizedPromptSnippet);
|
|
1094
|
+
if (!normalizedPrompt) return true;
|
|
1095
|
+
const normalizedBuffer = compactPromptText(raw);
|
|
1096
|
+
if (!normalizedBuffer) return false;
|
|
1097
|
+
if (normalizedBuffer === normalizedPrompt) return false;
|
|
1098
|
+
if (normalizedBuffer.startsWith(normalizedPrompt)) {
|
|
1099
|
+
const remainder = normalizedBuffer.slice(normalizedPrompt.length)
|
|
1100
|
+
.replace(/[─═\-]+/g, '')
|
|
1101
|
+
.replace(/⏵⏵accepteditson\([^)]*\)/gi, '')
|
|
1102
|
+
.replace(/esctointerrupt/gi, '')
|
|
1103
|
+
.replace(/❯/g, '')
|
|
1104
|
+
.replace(/^[\s\-–—:;,.!/?]+/, '')
|
|
1105
|
+
.trim();
|
|
1106
|
+
return remainder.length > 0;
|
|
1107
|
+
}
|
|
1108
|
+
return true;
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
private shouldDeferFinishForTranscript(parsed: any): boolean {
|
|
1112
|
+
// Honor only the explicit manifest opt-in. We used to also hard-code
|
|
1113
|
+
// codex-cli here, but that left codex sessions wedged in `generating`
|
|
1114
|
+
// whenever the PTY parser or native transcript missed the final
|
|
1115
|
+
// assistant line — a much more common failure mode than the original
|
|
1116
|
+
// background-tool race this was meant to guard against. If a provider
|
|
1117
|
+
// really needs the gate, the manifest can set
|
|
1118
|
+
// `requiresFinalAssistantBeforeIdle: true`.
|
|
1119
|
+
const requiresFinalAssistant = !!this.provider.requiresFinalAssistantBeforeIdle;
|
|
1120
|
+
if (!requiresFinalAssistant) return false;
|
|
1121
|
+
if (!this.isWaitingForResponse || !this.currentTurnScope || this.hasActionableApproval()) return false;
|
|
1122
|
+
const parsedStatus = typeof parsed?.status === 'string' ? parsed.status.trim() : '';
|
|
1123
|
+
if (parsedStatus !== 'idle') return true;
|
|
1124
|
+
if (parsed?.activeModal || parsed?.modal) return true;
|
|
1125
|
+
// For providers that own their history externally (e.g. SpecCliAdapter
|
|
1126
|
+
// reading native JSONL), parsed.messages only reflects PTY-visible
|
|
1127
|
+
// content which may include previous-turn assistant messages. Gate on
|
|
1128
|
+
// whether the *current turn* has a final assistant: find the last user
|
|
1129
|
+
// in parsed.messages, and check there is an assistant after it.
|
|
1130
|
+
// If no user found at all (e.g. PTY hid it), defer — the native-history
|
|
1131
|
+
// completion gate in cli-provider-instance will confirm via JSONL read.
|
|
1132
|
+
// For providers that own their history externally (e.g. SpecCliAdapter
|
|
1133
|
+
// reading native JSONL), parsed.messages may include previous-turn
|
|
1134
|
+
// assistant messages. Only an assistant that appears *after* the last
|
|
1135
|
+
// user message counts as evidence the current turn finished.
|
|
1136
|
+
const messages: any[] = Array.isArray(parsed?.messages) ? parsed.messages : [];
|
|
1137
|
+
let lastUserIdx = -1;
|
|
1138
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
1139
|
+
if (messages[i]?.role === 'user') { lastUserIdx = i; break; }
|
|
1140
|
+
}
|
|
1141
|
+
if (lastUserIdx < 0) {
|
|
1142
|
+
// No user message visible in PTY parser. Two sub-cases:
|
|
1143
|
+
// (a) messages is non-empty — some content was parsed but no user
|
|
1144
|
+
// line was found. Use the any-assistant fallback.
|
|
1145
|
+
// (b) messages is empty — the provider owns history externally
|
|
1146
|
+
// (e.g. SpecCliAdapter always returns []) and PTY gives us
|
|
1147
|
+
// nothing to judge. Do NOT defer here: deferring with empty
|
|
1148
|
+
// messages causes an infinite reschedule loop because
|
|
1149
|
+
// parsedStatusHasFinalStandardAssistantMessage also returns
|
|
1150
|
+
// false on empty input. Let cli-provider-instance's native-
|
|
1151
|
+
// history gate handle this case.
|
|
1152
|
+
if (messages.length === 0) return false;
|
|
1153
|
+
return !this.parsedStatusHasFinalStandardAssistantMessage(parsed);
|
|
1154
|
+
}
|
|
1155
|
+
// Check for a final standard assistant after the last user
|
|
1156
|
+
const hasCurrentTurnAssistant = messages.slice(lastUserIdx + 1).some((m: any) => {
|
|
1157
|
+
if (!m || m.role !== 'assistant') return false;
|
|
1158
|
+
if (typeof m.content !== 'string' || !m.content.trim()) return false;
|
|
1159
|
+
const kind = typeof m.kind === 'string' && m.kind.trim() ? m.kind.trim() : 'standard';
|
|
1160
|
+
return kind === 'standard' && m.meta?.streaming !== true;
|
|
1161
|
+
});
|
|
1162
|
+
return !hasCurrentTurnAssistant;
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
private rescheduleTranscriptFinishCheck(reason: string): void {
|
|
1166
|
+
this.clearIdleFinishCandidate(reason);
|
|
1167
|
+
this.setStatus('generating', reason);
|
|
1168
|
+
if (this.idleTimeout) clearTimeout(this.idleTimeout);
|
|
1169
|
+
this.idleTimeout = setTimeout(() => {
|
|
1170
|
+
if (!this.isWaitingForResponse || this.hasActionableApproval()) return;
|
|
1171
|
+
this.evaluateSettled(this.transport.getSnapshot());
|
|
1172
|
+
}, this.timeouts.idleFinishConfirm);
|
|
1173
|
+
this.recordTrace('transcript_finish_deferred', { reason });
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
private shouldRetryFinishResponse(snap: CliBufferSnapshot, commitResult: { hasAssistant: boolean; assistantContent: string }): boolean {
|
|
1177
|
+
if (!this.currentTurnScope) return false;
|
|
1178
|
+
if (this.hasActionableApproval()) return false;
|
|
1179
|
+
if (this.finishRetryCount >= MAX_FINISH_RETRIES) return false;
|
|
1180
|
+
if (commitResult.hasAssistant && commitResult.assistantContent.trim()) return false;
|
|
1181
|
+
if (this.runDetectStatus(snap) !== 'idle') return false;
|
|
1182
|
+
const now = Date.now();
|
|
1183
|
+
const quietForMs = snap.lastNonEmptyOutputAt ? (now - snap.lastNonEmptyOutputAt) : Number.MAX_SAFE_INTEGER;
|
|
1184
|
+
const screenStableMs = snap.lastScreenChangeAt ? (now - snap.lastScreenChangeAt) : 0;
|
|
1185
|
+
return quietForMs < 1200 || screenStableMs < 1200 || !commitResult.hasAssistant;
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
private commitCurrentTranscript(snap: CliBufferSnapshot): { hasAssistant: boolean; assistantContent: string } {
|
|
1189
|
+
const parsed = this.runParseSession(snap);
|
|
1190
|
+
if (parsed && Array.isArray(parsed.messages)) {
|
|
1191
|
+
const parsedMessages = normalizeCliParsedMessages(parsed.messages, { scope: null, lastOutputAt: snap.lastOutputAt });
|
|
1192
|
+
const lastAssistant = [...parsedMessages].reverse().find((m) => m.role === 'assistant');
|
|
1193
|
+
if (lastAssistant) return { hasAssistant: true, assistantContent: lastAssistant.content || '' };
|
|
1194
|
+
}
|
|
1195
|
+
return { hasAssistant: false, assistantContent: '' };
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
private maybeCommitVisibleIdleTranscript(session: ParsedSession, parsedMessages: CliChatMessage[], snap: CliBufferSnapshot): boolean {
|
|
1199
|
+
if (!this.provider.allowInputDuringGeneration) return false;
|
|
1200
|
+
if (!session || session.status !== 'idle' || !this.isWaitingForResponse || !this.currentTurnScope || this.activeModal || session.modal) return false;
|
|
1201
|
+
const visibleAssistant = [...parsedMessages].reverse().find((m) => m.role === 'assistant' && String(m.content || '').trim());
|
|
1202
|
+
if (!visibleAssistant) return false;
|
|
1203
|
+
this.resetActiveTurnState();
|
|
1204
|
+
this.callbacks.onTurnCompleted();
|
|
1205
|
+
this.setStatus('idle', 'script_idle_commit');
|
|
1206
|
+
this.callbacks.onStatusChange();
|
|
1207
|
+
this.transport.flushOutboundQueue();
|
|
1208
|
+
return true;
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
private parsedStatusHasFinalAssistantMessage(parsed: any): boolean {
|
|
1212
|
+
const messages = Array.isArray(parsed?.messages) ? parsed.messages : [];
|
|
1213
|
+
const last = [...messages].reverse().find((m: any) => {
|
|
1214
|
+
if (!m || m.role !== 'assistant') return false;
|
|
1215
|
+
return typeof m.content === 'string' && m.content.trim().length > 0;
|
|
1216
|
+
});
|
|
1217
|
+
return !!last;
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
private parsedStatusHasFinalStandardAssistantMessage(parsed: any): boolean {
|
|
1221
|
+
const messages = Array.isArray(parsed?.messages) ? parsed.messages : [];
|
|
1222
|
+
const last = [...messages].reverse().find((m: any) => {
|
|
1223
|
+
if (!m || m.role !== 'assistant') return false;
|
|
1224
|
+
if (typeof m.content !== 'string' || !m.content.trim()) return false;
|
|
1225
|
+
const kind = typeof m.kind === 'string' && m.kind.trim() ? m.kind.trim() : 'standard';
|
|
1226
|
+
return kind === 'standard' && m.meta?.streaming !== true;
|
|
1227
|
+
});
|
|
1228
|
+
return !!last;
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
private recordTrace(type: string, payload: Record<string, any> = {}): void {
|
|
1232
|
+
const entry: CliTraceEntry = {
|
|
1233
|
+
id: ++this.traceSeq,
|
|
1234
|
+
at: Date.now(),
|
|
1235
|
+
type,
|
|
1236
|
+
status: this.currentStatus,
|
|
1237
|
+
isWaitingForResponse: this.isWaitingForResponse,
|
|
1238
|
+
activeModal: this.activeModal ? { message: this.activeModal.message, buttons: [...this.activeModal.buttons] } : null,
|
|
1239
|
+
payload,
|
|
1240
|
+
};
|
|
1241
|
+
this.traceEntries.push(entry);
|
|
1242
|
+
if (this.traceEntries.length > MAX_TRACE_ENTRIES) {
|
|
1243
|
+
this.traceEntries.splice(0, this.traceEntries.length - MAX_TRACE_ENTRIES);
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
}
|