@adhdev/daemon-core 0.9.82-rc.40 → 0.9.82-rc.401
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 +199 -0
- package/dist/cli-adapters/provider-cli-adapter.d.ts +125 -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 +14 -0
- package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
- package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
- package/dist/cli-adapters/terminal-screen.d.ts +4 -11
- package/dist/commands/chat-commands-debug-bundle.d.ts +14 -0
- package/dist/commands/chat-commands-read.d.ts +7 -0
- package/dist/commands/chat-commands-scope.d.ts +39 -0
- package/dist/commands/chat-commands-shared.d.ts +33 -0
- package/dist/commands/chat-commands-write.d.ts +14 -0
- package/dist/commands/chat-commands.d.ts +10 -23
- package/dist/commands/cli-manager.d.ts +15 -1
- package/dist/commands/handler.d.ts +125 -0
- package/dist/commands/high-family/index.d.ts +3 -0
- package/dist/commands/high-family/mesh-coordinator-launch.d.ts +2 -0
- package/dist/commands/high-family/mesh-events.d.ts +2 -0
- package/dist/commands/high-family/mesh-status.d.ts +2 -0
- package/dist/commands/high-family/types.d.ts +60 -0
- package/dist/commands/low-family/coordinator-prompt.d.ts +9 -0
- package/dist/commands/low-family/daemon-lifecycle.d.ts +2 -0
- package/dist/commands/low-family/diagnostics.d.ts +2 -0
- package/dist/commands/low-family/index.d.ts +3 -0
- package/dist/commands/low-family/mesh-ledger.d.ts +10 -0
- package/dist/commands/low-family/mesh-node-logs.d.ts +2 -0
- package/dist/commands/low-family/notification.d.ts +2 -0
- package/dist/commands/low-family/refine-config.d.ts +2 -0
- package/dist/commands/low-family/session-host.d.ts +2 -0
- package/dist/commands/low-family/spec-providerdev.d.ts +11 -0
- package/dist/commands/low-family/status-meta.d.ts +2 -0
- package/dist/commands/low-family/types.d.ts +33 -0
- package/dist/commands/med-family/cli-agent.d.ts +2 -0
- package/dist/commands/med-family/fast-forward.d.ts +2 -0
- package/dist/commands/med-family/ide.d.ts +10 -0
- package/dist/commands/med-family/index.d.ts +3 -0
- package/dist/commands/med-family/mesh-crud.d.ts +2 -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 +116 -0
- package/dist/commands/mesh-coordinator.d.ts +85 -1
- package/dist/commands/router.d.ts +256 -2
- package/dist/commands/upgrade-helper.d.ts +41 -1
- package/dist/config/chat-history.d.ts +9 -0
- package/dist/config/config.d.ts +5 -0
- package/dist/config/mesh-config.d.ts +77 -1
- package/dist/config/mesh-json-config.d.ts +299 -0
- package/dist/daemon/dev-server.d.ts +0 -2
- package/dist/detection/ide-detector.d.ts +13 -0
- package/dist/detection/win32-ide-version.d.ts +37 -0
- package/dist/git/change-impact-config.d.ts +159 -0
- package/dist/git/git-commands.d.ts +11 -1
- package/dist/git/git-diff.d.ts +6 -0
- package/dist/git/git-executor.d.ts +11 -0
- package/dist/git/git-status.d.ts +23 -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 +57 -13
- package/dist/index.js +45987 -17082
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +45750 -16986
- package/dist/index.mjs.map +1 -1
- package/dist/installer.d.ts +1 -4
- package/dist/ipc/local-ipc-server.d.ts +91 -0
- package/dist/launch.d.ts +1 -1
- package/dist/logging/async-batch-writer.d.ts +10 -0
- package/dist/logging/log-redactor.d.ts +24 -0
- package/dist/logging/log-tail-reader.d.ts +81 -0
- package/dist/logging/logger.d.ts +1 -1
- package/dist/mesh/contracts.d.ts +164 -0
- package/dist/mesh/coordinator-prompt.d.ts +89 -0
- package/dist/mesh/coordinator-registry.d.ts +59 -0
- package/dist/mesh/mesh-active-work.d.ts +174 -0
- package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
- package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
- package/dist/mesh/mesh-event-classify.d.ts +5 -0
- package/dist/mesh/mesh-event-forwarding.d.ts +19 -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 +55 -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 +9 -0
- package/dist/mesh/mesh-init.d.ts +86 -0
- package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -4
- package/dist/mesh/mesh-ledger.d.ts +77 -1
- package/dist/mesh/mesh-missions.d.ts +164 -0
- package/dist/mesh/mesh-node-identity.d.ts +289 -0
- package/dist/mesh/mesh-queue-assignment.d.ts +95 -0
- package/dist/mesh/mesh-reconcile-loop.d.ts +65 -0
- package/dist/mesh/mesh-refine-batch.d.ts +68 -0
- package/dist/mesh/mesh-refine-gates.d.ts +428 -0
- package/dist/mesh/mesh-refine-status.d.ts +62 -0
- package/dist/mesh/mesh-review-inbox.d.ts +90 -0
- package/dist/mesh/mesh-routing.d.ts +70 -0
- package/dist/mesh/mesh-runtime-store.d.ts +447 -0
- package/dist/mesh/mesh-scheduling-runtime.d.ts +78 -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 +247 -5
- package/dist/mesh/preview-freshness.d.ts +18 -0
- package/dist/mesh/refine-config.d.ts +216 -0
- package/dist/mesh/worktree-bootstrap-config.d.ts +145 -0
- package/dist/providers/acp-provider-instance.d.ts +5 -0
- package/dist/providers/approval-utils.d.ts +20 -0
- package/dist/providers/chat-message-normalization.d.ts +13 -1
- package/dist/providers/cli-provider-instance.d.ts +167 -3
- package/dist/providers/contracts.d.ts +139 -6
- package/dist/providers/external-sources.d.ts +71 -0
- package/dist/providers/manual-attendance.d.ts +63 -0
- package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
- package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
- package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
- package/dist/providers/native-history/constants.d.ts +12 -0
- package/dist/providers/native-history/dispatcher.d.ts +27 -0
- package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
- package/dist/providers/native-history/index.d.ts +13 -0
- package/dist/providers/provider-instance-manager.d.ts +14 -0
- package/dist/providers/provider-instance.d.ts +23 -1
- package/dist/providers/provider-loader.d.ts +26 -4
- package/dist/providers/provider-trust.d.ts +31 -0
- package/dist/providers/read-chat-contract.d.ts +29 -0
- package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
- package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
- package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
- package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
- package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
- package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
- package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
- package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
- package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
- package/dist/providers/sdk/v1/index.d.ts +30 -0
- package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
- package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
- package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
- package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
- package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
- package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
- package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
- package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
- package/dist/providers/spec/adapter.d.ts +91 -0
- package/dist/providers/spec/cli-adapter.d.ts +223 -0
- package/dist/providers/spec/evaluator.d.ts +45 -0
- package/dist/providers/spec/fsm-driver.d.ts +407 -0
- package/dist/providers/spec/fsm-evaluator.d.ts +76 -0
- package/dist/providers/spec/fsm-loader.d.ts +14 -0
- package/dist/providers/spec/fsm-types.d.ts +174 -0
- package/dist/providers/spec/native-history-executor.d.ts +41 -0
- package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
- package/dist/providers/spec/route.d.ts +4 -0
- package/dist/providers/spec/types.d.ts +222 -0
- package/dist/providers/status-monitor.d.ts +7 -7
- package/dist/providers/transcript-v2.d.ts +176 -0
- package/dist/providers/types/interactive-prompt.d.ts +84 -0
- package/dist/providers/working-dir.d.ts +17 -0
- package/dist/repo-mesh-types.d.ts +420 -13
- package/dist/runtime-defaults.d.ts +2 -0
- package/dist/sessions/registry.d.ts +6 -0
- package/dist/shared-types-extra.d.ts +2 -4
- package/dist/shared-types.d.ts +59 -2
- package/dist/status/normalize.d.ts +1 -1
- package/dist/status/normalize.js +1 -0
- package/dist/status/normalize.js.map +1 -1
- package/dist/status/normalize.mjs +1 -0
- package/dist/status/normalize.mjs.map +1 -1
- package/dist/status/reporter.d.ts +2 -0
- package/dist/status/snapshot.d.ts +26 -0
- package/dist/system/hash.d.ts +8 -0
- package/dist/system/load-better-sqlite3.d.ts +21 -0
- package/dist/types.d.ts +5 -0
- package/package.json +7 -3
- package/src/agent-stream/poller.ts +2 -3
- package/src/agent-stream/provider-adapter.ts +1 -1
- package/src/boot/daemon-lifecycle.ts +63 -12
- package/src/boot/process-hardening.ts +89 -0
- package/src/build-info.ts +73 -0
- package/src/chat/source-machine.ts +534 -0
- package/src/chat/source-resolver.ts +0 -0
- package/src/chat/subscription-updates.ts +20 -1
- package/src/cli-adapter-types.d.ts +3 -1
- package/src/cli-adapter-types.ts +68 -2
- package/src/cli-adapters/cli-script-runner.ts +421 -0
- package/src/cli-adapters/cli-state-engine.ts +1236 -0
- package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
- package/src/cli-adapters/provider-cli-adapter.ts +909 -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 +90 -0
- package/src/cli-adapters/session-host-transport.ts +2 -1
- package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
- package/src/cli-adapters/terminal-backends/types.ts +10 -3
- package/src/cli-adapters/terminal-screen.ts +16 -81
- package/src/commands/WINDOWS-UPGRADE-LOCK-FAILURE.md +198 -0
- package/src/commands/chat-commands-debug-bundle.ts +398 -0
- package/src/commands/chat-commands-read.ts +2327 -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 +880 -0
- package/src/commands/chat-commands.ts +19 -1841
- package/src/commands/cli-manager.ts +527 -26
- package/src/commands/handler.ts +841 -2
- package/src/commands/high-family/index.ts +28 -0
- package/src/commands/high-family/mesh-coordinator-launch.ts +673 -0
- package/src/commands/high-family/mesh-events.ts +80 -0
- package/src/commands/high-family/mesh-status.ts +678 -0
- package/src/commands/high-family/types.ts +76 -0
- package/src/commands/low-family/coordinator-prompt.ts +72 -0
- package/src/commands/low-family/daemon-lifecycle.ts +107 -0
- package/src/commands/low-family/diagnostics.ts +57 -0
- package/src/commands/low-family/index.ts +37 -0
- package/src/commands/low-family/mesh-ledger.ts +62 -0
- package/src/commands/low-family/mesh-node-logs.ts +87 -0
- package/src/commands/low-family/notification.ts +116 -0
- package/src/commands/low-family/refine-config.ts +106 -0
- package/src/commands/low-family/session-host.ts +274 -0
- package/src/commands/low-family/spec-providerdev.ts +217 -0
- package/src/commands/low-family/status-meta.ts +112 -0
- package/src/commands/low-family/types.ts +39 -0
- package/src/commands/med-family/cli-agent.ts +238 -0
- package/src/commands/med-family/fast-forward.ts +230 -0
- package/src/commands/med-family/ide.ts +163 -0
- package/src/commands/med-family/index.ts +37 -0
- package/src/commands/med-family/mesh-crud.ts +874 -0
- package/src/commands/med-family/mesh-host-pairing.ts +234 -0
- package/src/commands/med-family/mesh-queue.ts +131 -0
- package/src/commands/med-family/mesh-restart.ts +92 -0
- package/src/commands/med-family/types.ts +120 -0
- package/src/commands/mesh-coordinator.ts +334 -124
- package/src/commands/router.ts +2516 -3221
- package/src/commands/stream-commands.ts +8 -0
- package/src/commands/upgrade-helper.ts +310 -45
- package/src/config/chat-history.ts +483 -24
- package/src/config/config.ts +12 -0
- package/src/config/mesh-config.ts +353 -22
- package/src/config/mesh-json-config.ts +617 -0
- package/src/config/recent-activity.ts +8 -2
- 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 +55 -14
- package/src/git/git-diff.ts +81 -11
- package/src/git/git-executor.ts +12 -0
- package/src/git/git-status.ts +574 -43
- 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 +171 -12
- package/src/installer.d.ts +1 -1
- package/src/installer.ts +8 -6
- package/src/ipc/local-ipc-server.ts +278 -0
- package/src/launch.d.ts +1 -1
- package/src/launch.ts +37 -28
- package/src/logging/async-batch-writer.ts +55 -0
- package/src/logging/command-log.ts +7 -5
- package/src/logging/log-redactor.ts +100 -0
- package/src/logging/log-tail-reader.ts +341 -0
- package/src/logging/logger.ts +14 -7
- package/src/mesh/contracts.ts +338 -0
- package/src/mesh/coordinator-prompt.ts +381 -33
- package/src/mesh/coordinator-registry.ts +121 -0
- package/src/mesh/mesh-active-work.ts +645 -0
- package/src/mesh/mesh-coordinator-config.ts +97 -0
- package/src/mesh/mesh-delivery-policy.ts +315 -0
- package/src/mesh/mesh-event-classify.ts +51 -0
- package/src/mesh/mesh-event-forwarding.ts +1773 -0
- package/src/mesh/mesh-event-trace.ts +67 -0
- package/src/mesh/mesh-events-coordinator.ts +31 -0
- package/src/mesh/mesh-events-pending.ts +590 -0
- package/src/mesh/mesh-events-stale.ts +389 -0
- package/src/mesh/mesh-events-utils.ts +443 -0
- package/src/mesh/mesh-events.ts +32 -1035
- package/src/mesh/mesh-fast-forward.ts +839 -0
- package/src/mesh/mesh-host-ownership.ts +73 -0
- package/src/mesh/mesh-init.ts +260 -0
- package/src/mesh/mesh-ledger-reconciliation.ts +12 -7
- package/src/mesh/mesh-ledger.ts +596 -102
- package/src/mesh/mesh-missions.ts +322 -0
- package/src/mesh/mesh-node-identity.ts +1887 -0
- package/src/mesh/mesh-queue-assignment.ts +1738 -0
- package/src/mesh/mesh-reconcile-loop.ts +1554 -0
- package/src/mesh/mesh-refine-batch.ts +205 -0
- package/src/mesh/mesh-refine-gates.ts +1660 -0
- package/src/mesh/mesh-refine-status.ts +231 -0
- package/src/mesh/mesh-review-inbox.ts +307 -0
- package/src/mesh/mesh-routing.ts +291 -0
- package/src/mesh/mesh-runtime-store.ts +1835 -0
- package/src/mesh/mesh-scheduling-runtime.ts +201 -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 +1141 -141
- package/src/mesh/preview-freshness.ts +118 -0
- package/src/mesh/refine-config.ts +423 -0
- package/src/mesh/worktree-bootstrap-config.ts +369 -0
- package/src/providers/acp-provider-instance.ts +43 -10
- package/src/providers/approval-utils.d.ts +5 -0
- package/src/providers/approval-utils.ts +57 -5
- package/src/providers/chat-message-normalization.ts +46 -6
- package/src/providers/cli-provider-instance.ts +1624 -103
- package/src/providers/contracts.d.ts +55 -0
- package/src/providers/contracts.ts +150 -6
- package/src/providers/extension-provider-instance.ts +12 -7
- package/src/providers/external-sources.ts +218 -0
- package/src/providers/ide-provider-instance.ts +35 -12
- package/src/providers/manual-attendance.ts +85 -0
- package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
- package/src/providers/native-history/claude-cli-transcript.ts +396 -0
- package/src/providers/native-history/codex-cli-transcript.ts +479 -0
- package/src/providers/native-history/constants.ts +19 -0
- package/src/providers/native-history/dispatcher.ts +339 -0
- package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
- package/src/providers/native-history/index.ts +30 -0
- package/src/providers/provider-instance-manager.ts +30 -0
- package/src/providers/provider-instance.ts +19 -1
- package/src/providers/provider-loader.ts +668 -50
- package/src/providers/provider-schema.ts +87 -14
- package/src/providers/provider-trust.ts +114 -0
- package/src/providers/read-chat-contract.ts +76 -16
- package/src/providers/sdk/README.md +49 -0
- package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
- package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
- package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
- package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
- package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
- package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
- package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
- package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
- package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
- package/src/providers/sdk/v1/index.ts +152 -0
- package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
- package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
- package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
- package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
- package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
- package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
- package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
- package/src/providers/sdk/v1/types/cli/index.ts +365 -0
- package/src/providers/sdk/v1/types/common/index.ts +229 -0
- package/src/providers/sdk/v1/validators/index.ts +19 -0
- package/src/providers/sdk/v1/validators/manifest.ts +110 -0
- package/src/providers/sdk/v1/validators/taint.ts +309 -0
- package/src/providers/spec/adapter.ts +235 -0
- package/src/providers/spec/cli-adapter.ts +1056 -0
- package/src/providers/spec/evaluator.ts +407 -0
- package/src/providers/spec/fsm-driver.ts +1304 -0
- package/src/providers/spec/fsm-evaluator.ts +272 -0
- package/src/providers/spec/fsm-loader.ts +120 -0
- package/src/providers/spec/fsm-types.ts +273 -0
- package/src/providers/spec/native-history-executor.ts +1128 -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 +629 -14
- package/src/runtime-defaults.ts +39 -0
- package/src/sessions/registry.ts +6 -0
- package/src/shared-types-extra.ts +2 -4
- package/src/shared-types.d.ts +8 -0
- package/src/shared-types.ts +64 -1
- package/src/status/builders.ts +26 -6
- package/src/status/normalize.ts +2 -0
- package/src/status/reporter.ts +19 -1
- package/src/status/snapshot.ts +95 -26
- package/src/system/hash.ts +23 -0
- package/src/system/host-memory.ts +29 -12
- package/src/system/load-better-sqlite3.ts +68 -0
- package/src/types.ts +5 -0
- package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
- package/dist/mesh/mesh-sync.d.ts +0 -53
- package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
- package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
- package/src/mesh/mesh-sync.ts +0 -111
|
@@ -13,19 +13,25 @@ import { createRequire } from 'node:module';
|
|
|
13
13
|
import { normalizeInputEnvelope, type ProviderModule, flattenContent, type InputEnvelope, type InputPart } from './contracts.js';
|
|
14
14
|
import { assertProviderSupportsDeclaredInput, getEffectiveMessageInputSupport } from './provider-input-support.js';
|
|
15
15
|
import type { ProviderInstance, ProviderState, ProviderEvent, InstanceContext, ProviderErrorReason, HotChatSessionState, SessionModalState } from './provider-instance.js';
|
|
16
|
+
import { normalizeInteractivePrompt, normalizeInteractivePromptResponse, type InteractivePrompt } from './types/interactive-prompt.js';
|
|
16
17
|
import { ProviderCliAdapter } from '../cli-adapters/provider-cli-adapter.js';
|
|
18
|
+
import { shortHash } from '../system/hash.js';
|
|
17
19
|
import type { CliProviderModule } from '../cli-adapters/provider-cli-adapter.js';
|
|
20
|
+
import { createCliAdapter } from './spec/route.js';
|
|
18
21
|
import type { PtyRuntimeMetadata, PtyTransportFactory } from '../cli-adapters/pty-transport.js';
|
|
19
22
|
import { StatusMonitor } from './status-monitor.js';
|
|
20
23
|
import { ChatHistoryWriter, isNativeSourceCanonicalHistory, materializeProviderNativeHistory, readChatHistory, readProviderChatHistory } from '../config/chat-history.js';
|
|
21
24
|
import { LOG } from '../logging/logger.js';
|
|
25
|
+
import { traceMeshEventStage, traceMeshEventDrop } from '../mesh/mesh-event-trace.js';
|
|
22
26
|
import type { ChatMessage } from '../types.js';
|
|
23
27
|
import { buildPersistedProviderEffectMessage, normalizeProviderEffects } from './control-effects.js';
|
|
24
|
-
import { formatAutoApprovalMessage, pickApprovalButton } from './approval-utils.js';
|
|
28
|
+
import { formatAutoApprovalMessage, pickApprovalButton, hasNegativeApprovalOption, looksLikeActiveApprovalPromptText } from './approval-utils.js';
|
|
25
29
|
import { getCliScriptCommand, parseCliScriptResult } from './cli-script-results.js';
|
|
26
30
|
import { mergeProviderPatchState, resolveProviderStateSurface } from './provider-patch-state.js';
|
|
27
31
|
import { normalizeProviderSessionId } from './provider-session-id.js';
|
|
28
32
|
import { buildChatMessage, buildRuntimeSystemChatMessage, isUserFacingChatMessage, normalizeChatMessages, resolveChatMessageKind, extractFinalSummaryFromMessages } from './chat-message-normalization.js';
|
|
33
|
+
import { workingDirBasename } from './working-dir.js';
|
|
34
|
+
import { ManualAttendanceTracker } from './manual-attendance.js';
|
|
29
35
|
|
|
30
36
|
type PersistableCliHistoryMessage = {
|
|
31
37
|
role: string;
|
|
@@ -35,16 +41,114 @@ type PersistableCliHistoryMessage = {
|
|
|
35
41
|
receivedAt?: number;
|
|
36
42
|
};
|
|
37
43
|
|
|
44
|
+
// Status snapshots only ever surface the newest messages: the cloud 'live'
|
|
45
|
+
// profile drops chat messages entirely (loaded lazily via read_chat on
|
|
46
|
+
// subscribe) and the 'full' profile caps activeChat.messages to the last 60
|
|
47
|
+
// (see status/normalize.ts). Unread/completion markers walk only the tail.
|
|
48
|
+
// So getState()'s saved-history hydration — which runs once per resume/manual
|
|
49
|
+
// CLI session on every status report — must read only a bounded tail, not the
|
|
50
|
+
// entire transcript. A full MAX_SAFE_INTEGER read here makes the initial
|
|
51
|
+
// status report O(transcript) × N(sessions), which is the real cold first-
|
|
52
|
+
// connection bottleneck on chat-heavy machines. The window comfortably exceeds
|
|
53
|
+
// the 60-message snapshot cap so dedup/collapse at the boundary stays stable.
|
|
54
|
+
const STATUS_HYDRATION_TAIL_LIMIT = 200;
|
|
55
|
+
|
|
38
56
|
type CompletedDebouncePending = {
|
|
39
57
|
chatTitle: string;
|
|
40
58
|
duration: number;
|
|
41
59
|
timestamp: number;
|
|
42
60
|
firstObservedAt: number;
|
|
61
|
+
previousStatus: string;
|
|
43
62
|
loggedBlockReason?: string;
|
|
63
|
+
loggedTranscriptProbe?: boolean;
|
|
64
|
+
transcriptProbeHistory?: ExternalTranscriptProbe[];
|
|
65
|
+
// ARCH-REFACTOR R1: the taskId of the turn that produced this (debounced) completion,
|
|
66
|
+
// captured SYNCHRONOUSLY at the generating→idle transition. The actual completion
|
|
67
|
+
// event is emitted later by the debounce flush, by which point a follow-up task may
|
|
68
|
+
// already have started its own turn and overwritten engine.currentTurnTaskId — so the
|
|
69
|
+
// id must be snapshotted here, not re-read at flush time.
|
|
70
|
+
taskId?: string;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
function isIdleStatus(value: unknown): boolean {
|
|
74
|
+
const status = typeof value === 'string' ? value.trim().toLowerCase() : '';
|
|
75
|
+
return !status || status === 'idle' || status === 'ready';
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
function getMessageTime(message: unknown): number {
|
|
80
|
+
if (!message || typeof message !== 'object') return 0;
|
|
81
|
+
const record = message as { receivedAt?: unknown; timestamp?: unknown };
|
|
82
|
+
const value = Number(record.receivedAt ?? record.timestamp ?? 0);
|
|
83
|
+
return Number.isFinite(value) ? value : 0;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
type CompletedFinalizationBlock = {
|
|
87
|
+
reason: string;
|
|
88
|
+
terminal?: boolean;
|
|
89
|
+
allowTimeout?: boolean;
|
|
90
|
+
// (SETTLE-VALLEY) When set, suppress the CANON-C decoupled-immediate emit for this
|
|
91
|
+
// missing_final_assistant block and HOLD (retry up to COMPLETED_FINALIZATION_MAX_WAIT_MS)
|
|
92
|
+
// until the native transcript's final assistant turn arrives (block clears → genuine emit)
|
|
93
|
+
// or the worker resumes (resume guard cancels). Set only for the inter-approval idle valley
|
|
94
|
+
// of a native-history mesh worker, where an immediate weak emit would freeze a truncated
|
|
95
|
+
// preamble summary (evidenceLevel=insufficient) into the append-only ledger before the
|
|
96
|
+
// worker's next approval turn resumes. Independent of valley length.
|
|
97
|
+
holdForTranscript?: boolean;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
type CompletionFinalAssistantEvidence = {
|
|
101
|
+
present: boolean;
|
|
102
|
+
messages: unknown[];
|
|
103
|
+
source: 'parsed' | 'external-native' | 'unavailable';
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
type ExternalTranscriptProbe = {
|
|
107
|
+
readAt: number;
|
|
108
|
+
msgCount: number;
|
|
109
|
+
lastRole: string | null;
|
|
110
|
+
lastKind: string | null;
|
|
111
|
+
contentLen: number;
|
|
112
|
+
sourcePath: string | null;
|
|
113
|
+
sourceMtimeMs: number | null;
|
|
114
|
+
mtimeAgeMs: number | null;
|
|
44
115
|
};
|
|
45
116
|
|
|
46
117
|
const COMPLETED_FINALIZATION_RETRY_MS = 1000;
|
|
47
118
|
const COMPLETED_FINALIZATION_MAX_WAIT_MS = 30_000;
|
|
119
|
+
// (FALSEIDLE-BGCHILD-a) Minimum generating→idle settle window for native-history mesh worker
|
|
120
|
+
// sessions. Native-history providers (e.g. claude-cli) normally flush the completion with
|
|
121
|
+
// flushDelay=0 — the transcript is authoritative, so there is no reason to wait. But a worker
|
|
122
|
+
// turn that spawns a BACKGROUND child (e.g. `npm test &`, a backgrounded Bash tool) can paint
|
|
123
|
+
// a burst of child output, fall quiet, and have the screen parser read a PRIOR/intermediate
|
|
124
|
+
// standard assistant as if the turn were done — firing a false idle while the agent is in fact
|
|
125
|
+
// still generating (e.g. mid-commit). With flushDelay=0 there is no window for the resume guard
|
|
126
|
+
// in flushCompletedDebounceIfFinalized (latestVisibleStatus !== 'idle' → cancel) to observe the
|
|
127
|
+
// agent picking the turn back up. A short non-zero settle window restores that resume guard for
|
|
128
|
+
// mesh workers without delaying genuinely-finished turns beyond this bound. Scoped to mesh
|
|
129
|
+
// worker sessions so interactive native-history sessions keep the immediate flush.
|
|
130
|
+
// 4000ms (was 1500): live measurement showed the completion event can fire 1.6–3s
|
|
131
|
+
// BEFORE the worker's final-assistant turn lands in the transcript on a natural
|
|
132
|
+
// generating→idle completion (no approval modal), freezing a prior intermediate
|
|
133
|
+
// bubble as finalSummary (evidenceLevel=insufficient). The 68a3c324 waiting_approval
|
|
134
|
+
// hold only covers the approval-resolved valley; widening this settle window to 4000ms
|
|
135
|
+
// covers that race AND the ~3s waiting_approval valley within the settle bound.
|
|
136
|
+
const NATIVE_HISTORY_MESH_IDLE_SETTLE_MS = 4000;
|
|
137
|
+
// TASKBUBBLE-DUP: window during which an identical user-input ack (same trimmed
|
|
138
|
+
// content on the same instance) is treated as a redelivery of one dispatch and
|
|
139
|
+
// suppressed from the chat transcript. Matches the coordinator-side
|
|
140
|
+
// DUPLICATE_DISPATCH_WINDOW_MS (mesh-tools) so the daemon's bubble-level guard
|
|
141
|
+
// covers the same retry horizon as the MCP-level dispatch dedup.
|
|
142
|
+
const USER_INPUT_ACK_DEDUP_WINDOW_MS = 60_000;
|
|
143
|
+
|
|
144
|
+
/** Events that signal a dispatched mesh task has reached a terminal state.
|
|
145
|
+
* Detach the mesh assignment after emitting one of these so the worker's
|
|
146
|
+
* next unrelated turn doesn't impersonate another completion. */
|
|
147
|
+
const TERMINAL_MESH_EVENTS = new Set([
|
|
148
|
+
'agent:generating_completed',
|
|
149
|
+
'agent:stopped',
|
|
150
|
+
'agent:ready',
|
|
151
|
+
]);
|
|
48
152
|
|
|
49
153
|
const IMAGE_MIME_EXTENSIONS: Record<string, string> = {
|
|
50
154
|
'image/png': '.png',
|
|
@@ -120,7 +224,7 @@ function hasNonEmptyCliModalButtons(activeModal: unknown): boolean {
|
|
|
120
224
|
}
|
|
121
225
|
|
|
122
226
|
function isCliGeneratingLikeStatus(status: unknown): boolean {
|
|
123
|
-
return status === 'generating' || status === 'streaming' || status === 'long_generating' || status === 'starting';
|
|
227
|
+
return status === 'generating' || status === 'streaming' || status === 'no_progress' || status === 'long_generating' || status === 'starting';
|
|
124
228
|
}
|
|
125
229
|
|
|
126
230
|
export function buildCliStructuredInputPrompt(
|
|
@@ -300,24 +404,114 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
300
404
|
readonly type: string;
|
|
301
405
|
readonly category = 'cli' as const;
|
|
302
406
|
|
|
407
|
+
/**
|
|
408
|
+
* Quiet period an approval modal's signature must be stable before
|
|
409
|
+
* auto-approve sends the approve key. Guards against firing on a prompt
|
|
410
|
+
* that is still streaming into the PTY (the "resolves too fast" symptom):
|
|
411
|
+
* while the modal text/buttons are still changing, every frame yields a
|
|
412
|
+
* new signature and the settle clock restarts. Once the prompt finishes
|
|
413
|
+
* rendering the signature holds and the key is sent after this window.
|
|
414
|
+
* Bounded + small so genuine approvals stay timely. The FSM is already
|
|
415
|
+
* authoritative over the `waiting_approval` state; this only delays the
|
|
416
|
+
* keystroke until the modal *content* has settled.
|
|
417
|
+
*/
|
|
418
|
+
private static readonly AUTO_APPROVE_SETTLE_MS = 600;
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Busy-side hysteresis for the settle gate. A momentary `generating` flip
|
|
422
|
+
* while the SAME approval modal's button block is still on screen (its
|
|
423
|
+
* question line scrolled out of the captured frame, only the buttons + a
|
|
424
|
+
* residual `esc to interrupt` spinner remain) briefly reports
|
|
425
|
+
* status!=waiting_approval. Without hysteresis that flip wipes the settle
|
|
426
|
+
* clock, and the modal→generating→modal flap restarts the 600ms window
|
|
427
|
+
* every time so auto-approve never fires. We keep the in-progress settle
|
|
428
|
+
* gate warm across an inactive blip up to this bound; only once the modal
|
|
429
|
+
* has genuinely stayed gone this long (a real resolution → idle) is the
|
|
430
|
+
* gate cleared. Bounded so a genuinely new, later approval still re-settles
|
|
431
|
+
* from scratch rather than firing on a stale timestamp.
|
|
432
|
+
*/
|
|
433
|
+
private static readonly AUTO_APPROVE_GATE_HYSTERESIS_MS = 1500;
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* STATUS-MISMATCH: upper bound on how long the auto-approve→`generating` SURFACE
|
|
437
|
+
* mask may hide a worker's `waiting_approval` (status + activeModal) before we give
|
|
438
|
+
* up and surface the real prompt. The mask exists because auto-approve is expected
|
|
439
|
+
* to resolve the modal momentarily; but if it STALLS without ever calling
|
|
440
|
+
* resolveModal — the modal signature never settles for AUTO_APPROVE_SETTLE_MS (a
|
|
441
|
+
* perpetually-flapping/streaming prompt), no concrete modal is ever captured, or the
|
|
442
|
+
* modal is a picker/non-affirmative we never auto-pick — the mask would persist
|
|
443
|
+
* forever and read_chat / mesh_status / the dashboard would NEVER see the pending
|
|
444
|
+
* approval (the coordinator cannot mesh_approve what it cannot see). Once an episode
|
|
445
|
+
* exceeds this bound we stop masking. Generously larger than
|
|
446
|
+
* AUTO_APPROVE_SETTLE_MS (600) + AUTO_APPROVE_GATE_HYSTERESIS_MS (1500) so a
|
|
447
|
+
* legitimately slow-settling / blip-flapping prompt is never unmasked early; a
|
|
448
|
+
* genuine never-resolving stall surfaces within this window. The settle gate keeps
|
|
449
|
+
* running underneath, so a prompt that finally stabilises still auto-approves, and
|
|
450
|
+
* mesh_approve (raw FSM, unmasked) works throughout.
|
|
451
|
+
*/
|
|
452
|
+
private static readonly AUTO_APPROVE_MASK_STALL_MS = 4500;
|
|
453
|
+
|
|
303
454
|
private adapter: ProviderCliAdapter;
|
|
304
455
|
private context: InstanceContext | null = null;
|
|
305
456
|
private events: ProviderEvent[] = [];
|
|
306
457
|
private lastStatus: string = 'starting';
|
|
458
|
+
// Idempotency guard for the queue-claim agent:ready event. agent:ready is the
|
|
459
|
+
// sole signal the mesh coordinator's tryAssignQueueTask waits on to hand a
|
|
460
|
+
// queued task to this worker. It is emitted in two places: the boot-time
|
|
461
|
+
// starting→idle one-shot, and the readySeen re-arm below. This flag makes the
|
|
462
|
+
// event fire AT MOST ONCE per session so a worker is never claimed twice and a
|
|
463
|
+
// queued task is never double-dispatched/double-injected. Whichever path fires
|
|
464
|
+
// first sets it; the other becomes a no-op.
|
|
465
|
+
private agentReadyEmitted = false;
|
|
307
466
|
private generatingStartedAt: number = 0;
|
|
308
467
|
private settings: Record<string, any> = {};
|
|
309
468
|
private monitor: StatusMonitor;
|
|
310
469
|
private generatingDebounceTimer: NodeJS.Timeout | null = null;
|
|
311
470
|
private generatingDebouncePending: { chatTitle: string; timestamp: number } | null = null;
|
|
312
|
-
private
|
|
471
|
+
private lastApprovalEventFingerprint = '';
|
|
313
472
|
private autoApproveBusy = false;
|
|
314
473
|
private autoApproveBusyTimer: NodeJS.Timeout | null = null;
|
|
474
|
+
private lastAutoApprovalSignature = '';
|
|
475
|
+
// Settle gate: the approval modal's signature + the wall-clock when this
|
|
476
|
+
// exact signature was first observed. Auto-approve only fires once the
|
|
477
|
+
// SAME signature has been stable for AUTO_APPROVE_SETTLE_MS, so a prompt
|
|
478
|
+
// still streaming into the PTY (its buttons/message changing frame to
|
|
479
|
+
// frame) keeps resetting the timer and is never approved half-rendered.
|
|
480
|
+
private pendingAutoApprovalSignature = '';
|
|
481
|
+
private pendingAutoApprovalSince = 0;
|
|
482
|
+
private autoApproveSettleTimer: NodeJS.Timeout | null = null;
|
|
483
|
+
// Wall-clock when auto-approve first observed status!=waiting_approval while
|
|
484
|
+
// a settle gate was in progress. Drives AUTO_APPROVE_GATE_HYSTERESIS_MS so a
|
|
485
|
+
// brief generating flip does not immediately wipe the settle clock.
|
|
486
|
+
private autoApproveInactiveSince = 0;
|
|
487
|
+
// STATUS-MISMATCH: wall-clock when the CURRENT auto-approve episode (waiting_approval
|
|
488
|
+
// + shouldAutoApprove) first began wanting to mask. Unlike pendingAutoApprovalSince it
|
|
489
|
+
// is NOT reset when the modal signature changes (a still-streaming/flapping prompt) and
|
|
490
|
+
// survives the same hysteresis blips the settle gate does, so it measures the TRUE age
|
|
491
|
+
// of an unresolved auto-approve. Once it exceeds AUTO_APPROVE_MASK_STALL_MS the surface
|
|
492
|
+
// mask is dropped so the real waiting_approval surfaces. Cleared when the episode ends
|
|
493
|
+
// (modal genuinely gone, manual attendance takes over, or auto-approve fires).
|
|
494
|
+
private autoApproveMaskSince = 0;
|
|
495
|
+
// Provider-common manual-attendance signal: while a human is actively driving
|
|
496
|
+
// this session from the dashboard, auto-approve holds so they can take manual
|
|
497
|
+
// control. Background mesh workers are never attended → delegated auto-approve
|
|
498
|
+
// is unaffected.
|
|
499
|
+
private readonly manualAttendance = new ManualAttendanceTracker();
|
|
315
500
|
private controlValues: Record<string, string | number | boolean> = {};
|
|
316
501
|
private summaryMetadata: unknown = undefined;
|
|
317
502
|
private appliedEffectKeys = new Set<string>();
|
|
318
503
|
private historyWriter: ChatHistoryWriter;
|
|
319
504
|
private runtimeMessages: Array<{ key: string; message: ChatMessage }> = [];
|
|
320
505
|
private lastPersistedHistoryMessages: PersistableCliHistoryMessage[] = [];
|
|
506
|
+
private lastAcknowledgedUserInputAt = 0;
|
|
507
|
+
// TASKBUBBLE-DUP: per-content last-ack timestamps so the same dispatched
|
|
508
|
+
// prompt acked twice in quick succession (the worker buffers the first
|
|
509
|
+
// send during bootstrap/busy, then a redelivery — dispatch-confirm-timeout
|
|
510
|
+
// requeue or a reconcile re-dispatch — fires a SECOND send_chat before the
|
|
511
|
+
// outbound queue drains) collapses to ONE user bubble. Keyed on the trimmed
|
|
512
|
+
// content; an entry older than USER_INPUT_ACK_DEDUP_WINDOW_MS is treated as
|
|
513
|
+
// a fresh, intentional resend and is NOT suppressed.
|
|
514
|
+
private recentUserInputAcks = new Map<string, number>();
|
|
321
515
|
private lastNativeSourceCanonicalCheckAt = 0;
|
|
322
516
|
private lastNativeSourceCanonicalCacheKey: string | undefined = undefined;
|
|
323
517
|
private cachedSqliteDb: {
|
|
@@ -330,6 +524,7 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
330
524
|
private suppressIdleHistoryReplay = false;
|
|
331
525
|
private errorMessage: string | undefined = undefined;
|
|
332
526
|
private errorReason: ProviderErrorReason | undefined = undefined;
|
|
527
|
+
private activeInteractivePrompt: InteractivePrompt | null = null;
|
|
333
528
|
|
|
334
529
|
private presentationMode: 'terminal' | 'chat';
|
|
335
530
|
private providerSessionId?: string;
|
|
@@ -370,7 +565,10 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
370
565
|
this.providerSessionId = options?.providerSessionId;
|
|
371
566
|
this.launchMode = options?.launchMode || 'new';
|
|
372
567
|
this.onProviderSessionResolved = options?.onProviderSessionResolved;
|
|
373
|
-
this.adapter =
|
|
568
|
+
this.adapter = createCliAdapter(provider as CliProviderModule, workingDir, cliArgs, options?.extraEnv || {}, transportFactory) as ProviderCliAdapter;
|
|
569
|
+
if (this.providerSessionId) {
|
|
570
|
+
this.adapter.updateRuntimeMeta({ providerSessionId: this.providerSessionId });
|
|
571
|
+
}
|
|
374
572
|
this.monitor = new StatusMonitor();
|
|
375
573
|
this.historyWriter = new ChatHistoryWriter();
|
|
376
574
|
}
|
|
@@ -389,8 +587,8 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
389
587
|
this.adapter.updateRuntimeSettings?.(this.settings);
|
|
390
588
|
this.monitor.updateConfig({
|
|
391
589
|
approvalAlert: this.settings.approvalAlert !== false,
|
|
392
|
-
|
|
393
|
-
|
|
590
|
+
noProgressAlert: (this.settings.noProgressAlert ?? this.settings.longGeneratingAlert) !== false,
|
|
591
|
+
noProgressThresholdSec: this.settings.noProgressThresholdSec ?? this.settings.longGeneratingThresholdSec ?? 180,
|
|
394
592
|
});
|
|
395
593
|
|
|
396
594
|
// Server connection
|
|
@@ -412,7 +610,7 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
412
610
|
await this.adapter.spawn();
|
|
413
611
|
await this.enforceFreshSessionLaunchIfNeeded();
|
|
414
612
|
this.maybeAppendRuntimeRecoveryMessage(this.adapter.getRuntimeMetadata());
|
|
415
|
-
if (this.providerSessionId) {
|
|
613
|
+
if (this.providerSessionId && this.shouldHydrateExistingProviderHistory()) {
|
|
416
614
|
this.restorePersistedHistoryFromCurrentSession();
|
|
417
615
|
}
|
|
418
616
|
if (this.providerSessionId && this.launchMode === 'resume') {
|
|
@@ -486,14 +684,38 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
486
684
|
}
|
|
487
685
|
|
|
488
686
|
getState(): ProviderState {
|
|
687
|
+
// TODO(phase5-sandbox): JS override scripts (detectStatus, parseApproval,
|
|
688
|
+
// parseSession) are currently invoked by CliScriptRunner.invoke() via direct
|
|
689
|
+
// function calls — the scripts run in the daemon process with full Node.js
|
|
690
|
+
// access and no resource limits.
|
|
691
|
+
//
|
|
692
|
+
// When Phase 5 lands, CliScriptRunner should route these calls through a
|
|
693
|
+
// SandboxedScriptRunner (see providers/sdk/v1/sandbox/script-runner.ts) so
|
|
694
|
+
// that each call gets a fresh isolated-vm context with a 50 ms CPU limit and
|
|
695
|
+
// a 32 MB memory cap. The execution path to change is:
|
|
696
|
+
// CliScriptRunner.invoke() → SandboxedScriptRunner.run(scriptSource, context)
|
|
697
|
+
//
|
|
698
|
+
// This getState() call-site is NOT where the change goes — the wiring belongs
|
|
699
|
+
// in cli-script-runner.ts (CliScriptRunner.detectStatus / parseApproval /
|
|
700
|
+
// parseSession), with provider-loader.ts updated to store script source strings
|
|
701
|
+
// alongside the loaded function references for extended-legacy providers.
|
|
489
702
|
const adapterStatus = this.adapter.getStatus();
|
|
703
|
+
if (Object.prototype.hasOwnProperty.call(adapterStatus, 'activeInteractivePrompt')) {
|
|
704
|
+
this.activeInteractivePrompt = adapterStatus.activeInteractivePrompt ?? null;
|
|
705
|
+
}
|
|
490
706
|
let parsedStatus: any = null;
|
|
491
707
|
let parseErrorMessage: string | undefined;
|
|
492
708
|
if (typeof this.adapter.getScriptParsedStatus === 'function') {
|
|
493
709
|
try {
|
|
494
710
|
parsedStatus = this.adapter.getScriptParsedStatus() || null;
|
|
495
|
-
|
|
496
|
-
|
|
711
|
+
const parsedErrorMessage = typeof parsedStatus?.errorMessage === 'string' && parsedStatus.errorMessage.trim()
|
|
712
|
+
? parsedStatus.errorMessage.trim()
|
|
713
|
+
: undefined;
|
|
714
|
+
const parsedErrorReason = typeof parsedStatus?.errorReason === 'string' && parsedStatus.errorReason.trim()
|
|
715
|
+
? parsedStatus.errorReason.trim() as ProviderErrorReason
|
|
716
|
+
: undefined;
|
|
717
|
+
this.errorMessage = parsedErrorMessage;
|
|
718
|
+
this.errorReason = parsedErrorReason;
|
|
497
719
|
} catch (error: any) {
|
|
498
720
|
parseErrorMessage = error?.message || String(error);
|
|
499
721
|
this.errorMessage = parseErrorMessage;
|
|
@@ -503,22 +725,59 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
503
725
|
this.errorMessage = undefined;
|
|
504
726
|
this.errorReason = undefined;
|
|
505
727
|
}
|
|
506
|
-
const
|
|
507
|
-
const visibleStatus = parseErrorMessage
|
|
508
|
-
? 'error'
|
|
509
|
-
: (autoApproveActive ? 'generating' : adapterStatus.status);
|
|
510
|
-
const parsedProviderSessionId = normalizeProviderSessionId(
|
|
728
|
+
const adapterProviderSessionId = normalizeProviderSessionId(
|
|
511
729
|
this.provider,
|
|
512
|
-
typeof
|
|
730
|
+
typeof adapterStatus?.providerSessionId === 'string' ? adapterStatus.providerSessionId : '',
|
|
513
731
|
);
|
|
514
|
-
|
|
515
|
-
|
|
732
|
+
const nowMs = Date.now();
|
|
733
|
+
// STATUS-MISMATCH: maybeAutoApproveStatus still runs for its side effects (settle gate,
|
|
734
|
+
// resolveModal fire), but the SURFACE mask is dropped once the episode has stalled past
|
|
735
|
+
// AUTO_APPROVE_MASK_STALL_MS — otherwise a never-settling auto-approve hides the worker's
|
|
736
|
+
// waiting_approval + modal from read_chat/mesh_status/dashboard forever.
|
|
737
|
+
const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, nowMs)
|
|
738
|
+
&& !this.autoApproveMaskStalled(nowMs);
|
|
739
|
+
const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
|
|
740
|
+
let visibleStatus = parseErrorMessage || parsedStatus?.status === 'error'
|
|
741
|
+
? 'error'
|
|
742
|
+
: (autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status);
|
|
743
|
+
// getState() must agree with the status the FSM-driven detectStatusTransition()
|
|
744
|
+
// already committed to lastStatus. The adapter's own status is authoritative; we do
|
|
745
|
+
// not second-guess it with native-transcript shape. Only reconcile a generating-like
|
|
746
|
+
// read down to idle when our own lastStatus has already flipped idle (avoids a
|
|
747
|
+
// perpetual dashboard spinner during the brief window before the next getStatus()).
|
|
748
|
+
if (isCliGeneratingLikeStatus(visibleStatus) && this.lastStatus === 'idle') {
|
|
749
|
+
visibleStatus = 'idle';
|
|
516
750
|
}
|
|
517
751
|
const runtime = this.adapter.getRuntimeMetadata();
|
|
518
752
|
this.maybeAppendRuntimeRecoveryMessage(runtime);
|
|
519
753
|
let parsedMessages = Array.isArray(parsedStatus?.messages)
|
|
520
754
|
? parsedStatus.messages
|
|
521
755
|
: [];
|
|
756
|
+
const parsedProviderSessionId = normalizeProviderSessionId(
|
|
757
|
+
this.provider,
|
|
758
|
+
typeof parsedStatus?.providerSessionId === 'string' ? parsedStatus.providerSessionId : '',
|
|
759
|
+
);
|
|
760
|
+
const suppressFreshLaunchStartupReplay = this.shouldSuppressFreshLaunchStartupReplay(
|
|
761
|
+
parsedMessages,
|
|
762
|
+
parsedStatus,
|
|
763
|
+
adapterStatus,
|
|
764
|
+
parsedProviderSessionId,
|
|
765
|
+
);
|
|
766
|
+
if (adapterProviderSessionId && !suppressFreshLaunchStartupReplay) {
|
|
767
|
+
this.promoteProviderSessionId(adapterProviderSessionId);
|
|
768
|
+
}
|
|
769
|
+
if (parsedProviderSessionId && !suppressFreshLaunchStartupReplay) {
|
|
770
|
+
this.promoteProviderSessionId(parsedProviderSessionId);
|
|
771
|
+
}
|
|
772
|
+
if (suppressFreshLaunchStartupReplay) {
|
|
773
|
+
parsedMessages = [];
|
|
774
|
+
}
|
|
775
|
+
// Adapter runtime metadata is transport-owned and is not guaranteed to
|
|
776
|
+
// identify this conversation. Spec adapters historically exposed the
|
|
777
|
+
// provider spec id (for example "codex-cli") as runtimeId, which made
|
|
778
|
+
// concurrent sessions share one activeChat identity until their native
|
|
779
|
+
// provider session ids were discovered.
|
|
780
|
+
const activeChatId = this.providerSessionId || this.instanceId;
|
|
522
781
|
const historyMessageCount = Number.isFinite(parsedStatus?.historyMessageCount)
|
|
523
782
|
? Math.max(0, Number(parsedStatus.historyMessageCount))
|
|
524
783
|
: null;
|
|
@@ -528,9 +787,20 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
528
787
|
: [];
|
|
529
788
|
}
|
|
530
789
|
const mergedMessages = this.mergeConversationMessages(parsedMessages);
|
|
531
|
-
const canonicalBackedHistory = this.
|
|
790
|
+
const canonicalBackedHistory = this.shouldHydrateExistingProviderHistory()
|
|
791
|
+
? this.syncCanonicalSavedHistoryIfNeeded()
|
|
792
|
+
: false;
|
|
793
|
+
const statusMessages = canonicalBackedHistory && this.lastPersistedHistoryMessages.length > 0
|
|
794
|
+
? this.lastPersistedHistoryMessages.map((message) => ({
|
|
795
|
+
role: message.role,
|
|
796
|
+
content: message.content,
|
|
797
|
+
kind: message.kind,
|
|
798
|
+
senderName: message.senderName,
|
|
799
|
+
receivedAt: message.receivedAt,
|
|
800
|
+
}))
|
|
801
|
+
: mergedMessages;
|
|
532
802
|
|
|
533
|
-
const dirName = this.workingDir
|
|
803
|
+
const dirName = workingDirBasename(this.workingDir);
|
|
534
804
|
const parsedChatStatus = typeof parsedStatus?.status === 'string' && parsedStatus.status.trim()
|
|
535
805
|
? parsedStatus.status.trim()
|
|
536
806
|
: undefined;
|
|
@@ -542,7 +812,7 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
542
812
|
&& adapterStatus.status === 'idle'
|
|
543
813
|
&& parsedStatus?.status === 'idle';
|
|
544
814
|
let messagesToSave = parsedMessages;
|
|
545
|
-
if (!suppressStaleParsedBusyStatus && (parsedChatStatus === 'generating' || parsedChatStatus === 'long_generating')) {
|
|
815
|
+
if (!suppressStaleParsedBusyStatus && (parsedChatStatus === 'generating' || parsedChatStatus === 'no_progress' || parsedChatStatus === 'long_generating')) {
|
|
546
816
|
const lastIdx = messagesToSave.length - 1;
|
|
547
817
|
if (lastIdx >= 0 && messagesToSave[lastIdx]?.role === 'assistant') {
|
|
548
818
|
messagesToSave = messagesToSave.slice(0, lastIdx);
|
|
@@ -572,33 +842,48 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
572
842
|
}
|
|
573
843
|
}
|
|
574
844
|
|
|
575
|
-
this.applyProviderResponse(
|
|
845
|
+
this.applyProviderResponse(
|
|
846
|
+
suppressFreshLaunchStartupReplay && parsedStatus && typeof parsedStatus === 'object'
|
|
847
|
+
? { ...parsedStatus, providerSessionId: undefined }
|
|
848
|
+
: parsedStatus,
|
|
849
|
+
{ phase: 'immediate' },
|
|
850
|
+
);
|
|
576
851
|
const surface = resolveProviderStateSurface({
|
|
577
852
|
summaryMetadata: this.summaryMetadata as any,
|
|
578
853
|
controlValues: this.controlValues,
|
|
579
854
|
});
|
|
580
855
|
const activeChatStatus = parseErrorMessage
|
|
581
856
|
? 'error'
|
|
582
|
-
: autoApproveActive && parsedStatus?.status === 'waiting_approval'
|
|
857
|
+
: (autoApproveActive && parsedStatus?.status === 'waiting_approval') || autoApproveHoldIdle
|
|
583
858
|
? 'generating'
|
|
584
859
|
: (adapterStatus.status !== 'idle'
|
|
585
860
|
? visibleStatus
|
|
586
861
|
: (suppressStaleParsedBusyStatus ? visibleStatus : (parsedChatStatus || visibleStatus)));
|
|
587
862
|
|
|
863
|
+
// If an AskUserQuestion prompt is awaiting user input, overlay status as
|
|
864
|
+
// waiting_choice. This is distinct from waiting_approval (tool-use consent)
|
|
865
|
+
// — the engine's isWaitingForResponse state is unchanged, so completion
|
|
866
|
+
// tracking continues normally once the user responds.
|
|
867
|
+
const hasInteractivePrompt = !!this.activeInteractivePrompt;
|
|
868
|
+
const finalStatus = hasInteractivePrompt ? 'waiting_choice' : visibleStatus;
|
|
869
|
+
const finalChatStatus = hasInteractivePrompt ? 'waiting_choice' : activeChatStatus;
|
|
870
|
+
|
|
588
871
|
return {
|
|
589
872
|
type: this.type,
|
|
590
873
|
name: this.provider.name,
|
|
591
874
|
category: 'cli',
|
|
592
|
-
status:
|
|
875
|
+
status: finalStatus,
|
|
593
876
|
mode: this.presentationMode,
|
|
594
877
|
activeChat: {
|
|
595
|
-
id:
|
|
878
|
+
id: activeChatId,
|
|
596
879
|
title: parsedStatus?.title || dirName,
|
|
597
|
-
status:
|
|
598
|
-
messages:
|
|
599
|
-
activeModal: autoApproveActive ? null : (parsedStatus?.activeModal ?? adapterStatus.activeModal),
|
|
880
|
+
status: finalChatStatus,
|
|
881
|
+
messages: statusMessages,
|
|
882
|
+
activeModal: (autoApproveActive || autoApproveHoldIdle) ? null : (parsedStatus?.activeModal ?? adapterStatus.activeModal),
|
|
883
|
+
activeInteractivePrompt: this.activeInteractivePrompt,
|
|
600
884
|
inputContent: '',
|
|
601
885
|
},
|
|
886
|
+
activeInteractivePrompt: this.activeInteractivePrompt,
|
|
602
887
|
workspace: this.workingDir,
|
|
603
888
|
instanceId: this.instanceId,
|
|
604
889
|
providerSessionId: this.providerSessionId,
|
|
@@ -638,8 +923,12 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
638
923
|
|
|
639
924
|
getHotChatSessionState(): HotChatSessionState {
|
|
640
925
|
const adapterStatus = this.adapter.getStatus({ allowParse: false });
|
|
641
|
-
const
|
|
642
|
-
|
|
926
|
+
const nowMs = Date.now();
|
|
927
|
+
// STATUS-MISMATCH: drop the mask once the auto-approve episode has stalled (see getState).
|
|
928
|
+
const autoApproveActive = this.autoApproveEffectivelyActive(adapterStatus.status, nowMs)
|
|
929
|
+
&& !this.autoApproveMaskStalled(nowMs);
|
|
930
|
+
const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
|
|
931
|
+
const visibleStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status;
|
|
643
932
|
const runtime = this.adapter.getRuntimeMetadata();
|
|
644
933
|
return {
|
|
645
934
|
id: this.instanceId,
|
|
@@ -651,36 +940,198 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
651
940
|
};
|
|
652
941
|
}
|
|
653
942
|
|
|
654
|
-
getSessionModalState(): SessionModalState {
|
|
655
|
-
const adapterStatus = this.adapter.getStatus({ allowParse:
|
|
656
|
-
const
|
|
657
|
-
|
|
658
|
-
const
|
|
943
|
+
getSessionModalState(sessionId?: string): SessionModalState {
|
|
944
|
+
const adapterStatus = this.adapter.getStatus({ allowParse: true });
|
|
945
|
+
const nowMs = Date.now();
|
|
946
|
+
// STATUS-MISMATCH: drop the mask once the auto-approve episode has stalled (see getState).
|
|
947
|
+
const autoApproveActive = this.autoApproveEffectivelyActive(adapterStatus.status, nowMs)
|
|
948
|
+
&& !this.autoApproveMaskStalled(nowMs);
|
|
949
|
+
const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
|
|
950
|
+
const visibleStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status;
|
|
951
|
+
const dirName = workingDirBasename(this.workingDir);
|
|
659
952
|
return {
|
|
660
|
-
|
|
953
|
+
// Honor the caller-supplied sessionId — InstanceMgr rejects the
|
|
954
|
+
// projection when projected.id !== requested sessionId, and
|
|
955
|
+
// this.instanceId is the manager's internal key, not the public
|
|
956
|
+
// sessionId the dashboard subscribes by.
|
|
957
|
+
id: sessionId ?? this.instanceId,
|
|
661
958
|
status: visibleStatus,
|
|
662
959
|
title: dirName,
|
|
663
|
-
activeModal: autoApproveActive ? null : adapterStatus.activeModal,
|
|
960
|
+
activeModal: (autoApproveActive || autoApproveHoldIdle) ? null : adapterStatus.activeModal,
|
|
664
961
|
};
|
|
665
962
|
}
|
|
666
963
|
|
|
667
964
|
updateSettings(newSettings: Record<string, any>): void {
|
|
668
|
-
|
|
965
|
+
// Merge semantics: a key omitted from newSettings preserves its existing
|
|
966
|
+
// value, a key present in newSettings (even as false) overrides it.
|
|
967
|
+
//
|
|
968
|
+
// This is required because updateSettings has two callers with opposite
|
|
969
|
+
// intent:
|
|
970
|
+
// 1. Full re-injection — the dashboard toggle path (handleSetProviderSetting
|
|
971
|
+
// → getSettings → updateInstanceSettings) sends the COMPLETE settings
|
|
972
|
+
// object, so an explicit autoApprove:false must win.
|
|
973
|
+
// 2. Partial stamp — the mesh relay-safety stamp (router.ts agent_command,
|
|
974
|
+
// buildMeshWorkerRelayStamp) sends ONLY {meshNodeFor, meshNodeId,
|
|
975
|
+
// meshCoordinatorDaemonId, launchedByCoordinator} on every coordinator
|
|
976
|
+
// re-dispatch. It carries no autoApprove, so a full replacement would
|
|
977
|
+
// wipe the launch-time autoApprove:true the worker was started with,
|
|
978
|
+
// silently dropping every later approval to a manual gate until the
|
|
979
|
+
// machine-page toggle re-injected the full settings.
|
|
980
|
+
//
|
|
981
|
+
// A plain merge satisfies both: undefined keys fall through to the existing
|
|
982
|
+
// value (preserving launch-stamp settings like autoApprove + the mesh routing
|
|
983
|
+
// keys), explicit keys override. This subsumes the previous mesh-key preserve
|
|
984
|
+
// list, which only protected the routing keys and not autoApprove.
|
|
985
|
+
this.settings = { ...this.settings, ...newSettings };
|
|
669
986
|
this.adapter.updateRuntimeSettings?.(this.settings);
|
|
670
987
|
this.monitor.updateConfig({
|
|
671
988
|
approvalAlert: this.settings.approvalAlert !== false,
|
|
672
|
-
|
|
673
|
-
|
|
989
|
+
noProgressAlert: (this.settings.noProgressAlert ?? this.settings.longGeneratingAlert) !== false,
|
|
990
|
+
noProgressThresholdSec: this.settings.noProgressThresholdSec ?? this.settings.longGeneratingThresholdSec ?? 180,
|
|
674
991
|
});
|
|
675
992
|
}
|
|
676
993
|
|
|
994
|
+
/**
|
|
995
|
+
* Stamp a direct-dispatch mesh assignment on this instance.
|
|
996
|
+
* setupMeshEventForwarding reads settings.meshNodeFor + meshActiveTaskId to
|
|
997
|
+
* route generating_completed back to the originating coordinator. Without
|
|
998
|
+
* this stamp, mesh_send_task --direct targets a plain CLI session whose
|
|
999
|
+
* completion events silently drop because the forwarder has nothing to
|
|
1000
|
+
* match against.
|
|
1001
|
+
*/
|
|
1002
|
+
attachMeshAssignment(assignment: { meshId: string; nodeId?: string; taskId?: string; coordinatorDaemonId?: string; coordinatorSessionId?: string }): void {
|
|
1003
|
+
if (!assignment?.meshId) return;
|
|
1004
|
+
this.settings = {
|
|
1005
|
+
...this.settings,
|
|
1006
|
+
meshNodeFor: assignment.meshId,
|
|
1007
|
+
// WTCLAIM (A): track the bound node id under BOTH the active marker
|
|
1008
|
+
// (meshNodeId, cleared on detach) and a sticky marker (meshLastNodeId,
|
|
1009
|
+
// preserved across detach). The sticky marker lets a detached but still
|
|
1010
|
+
// coordinator-owned session be re-picked ONLY for the SAME node it served
|
|
1011
|
+
// — never auto-adopted for a sibling node (e.g. a cloned worktree) that
|
|
1012
|
+
// shares this daemon. See isMeshOwnedDelegateSession's post-detach gate.
|
|
1013
|
+
...(assignment.nodeId ? { meshNodeId: assignment.nodeId, meshLastNodeId: assignment.nodeId } : {}),
|
|
1014
|
+
...(assignment.taskId ? { meshActiveTaskId: assignment.taskId } : {}),
|
|
1015
|
+
...(assignment.coordinatorDaemonId ? { meshCoordinatorDaemonId: assignment.coordinatorDaemonId } : {}),
|
|
1016
|
+
// Session-level routing anchor: the originating coordinator session, so this
|
|
1017
|
+
// worker's completion events route back to the exact session that dispatched it.
|
|
1018
|
+
...(assignment.coordinatorSessionId ? { meshCoordinatorSessionId: assignment.coordinatorSessionId } : {}),
|
|
1019
|
+
};
|
|
1020
|
+
this.adapter.updateRuntimeSettings?.(this.settings);
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
/**
|
|
1024
|
+
* Clear a previously-attached mesh assignment after the task reaches a
|
|
1025
|
+
* terminal state. Leaving meshNodeFor pinned would route this session's
|
|
1026
|
+
* subsequent unrelated turns (e.g. ad-hoc dashboard chats) to the
|
|
1027
|
+
* coordinator as if they were task completions.
|
|
1028
|
+
*
|
|
1029
|
+
* MESHID-DROP-ON-DETACH (Fix C): a coordinator-LAUNCHED worker session
|
|
1030
|
+
* (launchedByCoordinator) holds its mesh membership (meshNodeFor / meshNodeId /
|
|
1031
|
+
* meshCoordinatorDaemonId) at the SESSION level — set once at launch
|
|
1032
|
+
* (mesh_launch_session / queue auto-launch), independent of any single task.
|
|
1033
|
+
* The original detach wiped meshNodeFor + meshNodeId together with the
|
|
1034
|
+
* task-level meshActiveTaskId, so the FIRST task completion stripped the
|
|
1035
|
+
* membership and EVERY subsequent completion forwarded with meshId absent —
|
|
1036
|
+
* resolveWorkerDelegateRouting fell to mesh_unresolved and the coordinator
|
|
1037
|
+
* rejected the forward "meshId required". For a launched member we therefore
|
|
1038
|
+
* clear ONLY the task-level marker (meshActiveTaskId) and preserve the
|
|
1039
|
+
* session-level membership so its next task's completion still resolves.
|
|
1040
|
+
* A task-less ad-hoc turn on a preserved-membership session is NOT misrouted:
|
|
1041
|
+
* its completion carries no taskId and the session holds no active assignment,
|
|
1042
|
+
* so the forwarder's WARMUPGAP guard skips the dispatch-row flip (it only
|
|
1043
|
+
* injects a benign task-less notification). A NON-launched session (a plain CLI
|
|
1044
|
+
* session adopted by mesh_send_task --direct, launchedByCoordinator falsy)
|
|
1045
|
+
* keeps the original full clear so an ad-hoc session is never left pinned.
|
|
1046
|
+
*/
|
|
1047
|
+
detachMeshAssignment(): void {
|
|
1048
|
+
if (!this.settings.meshNodeFor && !this.settings.meshActiveTaskId && !this.settings.meshNodeId) return;
|
|
1049
|
+
// Session-level member: keep membership, drop only the task-level marker.
|
|
1050
|
+
if (this.settings.launchedByCoordinator === true) {
|
|
1051
|
+
if (!this.settings.meshActiveTaskId) return;
|
|
1052
|
+
const { meshActiveTaskId, ...rest } = this.settings;
|
|
1053
|
+
void meshActiveTaskId;
|
|
1054
|
+
this.settings = rest;
|
|
1055
|
+
this.adapter.updateRuntimeSettings?.(this.settings);
|
|
1056
|
+
return;
|
|
1057
|
+
}
|
|
1058
|
+
const { meshNodeFor, meshNodeId, meshActiveTaskId, ...rest } = this.settings;
|
|
1059
|
+
void meshNodeFor; void meshActiveTaskId;
|
|
1060
|
+
// WTCLAIM (A): clear the active binding but PRESERVE the last bound node id
|
|
1061
|
+
// (meshLastNodeId) so a later sessionless dispatch can re-adopt this idle
|
|
1062
|
+
// session ONLY for the node it last served. Carry the id being cleared, or
|
|
1063
|
+
// keep an already-present sticky marker if meshNodeId was absent.
|
|
1064
|
+
const lastNodeId = (typeof meshNodeId === 'string' && meshNodeId.trim())
|
|
1065
|
+
? meshNodeId.trim()
|
|
1066
|
+
: (typeof rest.meshLastNodeId === 'string' && rest.meshLastNodeId.trim() ? rest.meshLastNodeId.trim() : undefined);
|
|
1067
|
+
this.settings = lastNodeId ? { ...rest, meshLastNodeId: lastNodeId } : rest;
|
|
1068
|
+
this.adapter.updateRuntimeSettings?.(this.settings);
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
/**
|
|
1072
|
+
* The resolved modal-park status of this session, or null when it is not
|
|
1073
|
+
* parked on a modal awaiting a human answer. Mirrors the overlay logic in
|
|
1074
|
+
* getState(): an active AskUserQuestion interactive prompt resolves to
|
|
1075
|
+
* waiting_choice; otherwise the adapter's waiting_approval (tool consent)
|
|
1076
|
+
* counts — UNLESS auto-approve will dismiss it, in which case the session is
|
|
1077
|
+
* effectively generating and is NOT modal-parked. This is the single signal
|
|
1078
|
+
* the mesh force-inject guard consults, and the same status string the
|
|
1079
|
+
* reconcile loop reads off get_status_metadata. Lowercase literals only —
|
|
1080
|
+
* the SessionStatus enum is forked across modules and waiting_choice is
|
|
1081
|
+
* absent from some of them.
|
|
1082
|
+
*/
|
|
1083
|
+
resolveModalParkStatus(): 'waiting_choice' | 'waiting_approval' | null {
|
|
1084
|
+
if (this.activeInteractivePrompt) return 'waiting_choice';
|
|
1085
|
+
let adapterStatus: { status?: string };
|
|
1086
|
+
try {
|
|
1087
|
+
adapterStatus = this.adapter.getStatus({ allowParse: false });
|
|
1088
|
+
} catch {
|
|
1089
|
+
return null;
|
|
1090
|
+
}
|
|
1091
|
+
// A session whose auto-approve is held by manual attendance IS parked on a
|
|
1092
|
+
// modal awaiting the human — autoApproveEffectivelyActive folds that in, so
|
|
1093
|
+
// the mesh force-inject guard correctly treats it as modal-parked. STATUS-MISMATCH:
|
|
1094
|
+
// a STALLED auto-approve (never resolving) is likewise effectively parked — treat it
|
|
1095
|
+
// as modal-parked so its events are held/surfaced rather than masked behind generating.
|
|
1096
|
+
if (adapterStatus.status === 'waiting_approval'
|
|
1097
|
+
&& (!this.autoApproveEffectivelyActive(adapterStatus.status) || this.autoApproveMaskStalled())) {
|
|
1098
|
+
return 'waiting_approval';
|
|
1099
|
+
}
|
|
1100
|
+
return null;
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
/** True when this session is parked on a modal awaiting a human answer. */
|
|
1104
|
+
isModalParked(): boolean {
|
|
1105
|
+
return this.resolveModalParkStatus() !== null;
|
|
1106
|
+
}
|
|
1107
|
+
|
|
677
1108
|
onEvent(event: string, data?: any): void {
|
|
678
1109
|
if (event === 'send_message') {
|
|
679
1110
|
const input = normalizeInputEnvelope(data);
|
|
680
1111
|
assertProviderSupportsDeclaredInput(this.provider, input);
|
|
681
1112
|
const promptText = buildCliStructuredInputPrompt(input);
|
|
682
1113
|
if (promptText) {
|
|
683
|
-
|
|
1114
|
+
// force:true bypasses the busy/generating send guard so terminal mesh
|
|
1115
|
+
// events (completion/failure/bootstrap) land in a coordinator session that
|
|
1116
|
+
// is itself parked in `generating` while awaiting that very event.
|
|
1117
|
+
// Without it the message is queued and only flushed on the coordinator's
|
|
1118
|
+
// own idle transition — which never happens until it receives the message.
|
|
1119
|
+
const force = data?.force === true;
|
|
1120
|
+
// Modal guard: a force-inject still writes raw keystrokes into the PTY,
|
|
1121
|
+
// bypassing the busy send-guard. If the coordinator is parked on a
|
|
1122
|
+
// harness modal (claude-cli AskUserQuestion → waiting_choice, or a
|
|
1123
|
+
// tool-consent waiting_approval), those keystrokes are consumed by the
|
|
1124
|
+
// modal's key handler and silently select a choice the user never made
|
|
1125
|
+
// (data corruption). Hold the force-inject in that narrow window —
|
|
1126
|
+
// the event stays queued and the reconcile loop redelivers it on the
|
|
1127
|
+
// next tick once the modal is resolved. We ONLY hold for the two modal
|
|
1128
|
+
// states; generating is still force-injected (that is the deadlock the
|
|
1129
|
+
// force path exists to break — see mesh-events-coordinator).
|
|
1130
|
+
if (force && this.isModalParked()) {
|
|
1131
|
+
LOG.info('CLI', `[${this.type}] force send_message held — coordinator parked on modal (${this.resolveModalParkStatus()})`);
|
|
1132
|
+
return;
|
|
1133
|
+
}
|
|
1134
|
+
void this.adapter.sendMessage(promptText, force ? { force: true } : {}).catch((e: any) => {
|
|
684
1135
|
LOG.warn('CLI', `[${this.type}] send_message failed: ${e?.message || e}`);
|
|
685
1136
|
});
|
|
686
1137
|
}
|
|
@@ -690,14 +1141,101 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
690
1141
|
void this.adapter.resolveAction(data).catch((e: any) => {
|
|
691
1142
|
LOG.warn('CLI', `[${this.type}] resolve_action failed: ${e?.message || e}`);
|
|
692
1143
|
});
|
|
1144
|
+
} else if (event === 'interactive_prompt' && data) {
|
|
1145
|
+
const prompt = normalizeInteractivePrompt(data);
|
|
1146
|
+
if (prompt) {
|
|
1147
|
+
this.activeInteractivePrompt = prompt;
|
|
1148
|
+
this.events.push({
|
|
1149
|
+
event: 'interactive_prompt',
|
|
1150
|
+
timestamp: Date.now(),
|
|
1151
|
+
promptId: prompt.promptId,
|
|
1152
|
+
});
|
|
1153
|
+
}
|
|
1154
|
+
} else if (event === 'interactive_prompt_response' && data) {
|
|
1155
|
+
try {
|
|
1156
|
+
const response = normalizeInteractivePromptResponse(data);
|
|
1157
|
+
if (this.activeInteractivePrompt?.promptId === response.promptId) {
|
|
1158
|
+
this.activeInteractivePrompt = null;
|
|
1159
|
+
}
|
|
1160
|
+
if (typeof this.adapter.setInteractivePromptResponse !== 'function') {
|
|
1161
|
+
LOG.warn('CLI', `[${this.type}] interactive_prompt_response ignored: adapter does not support interactive prompts`);
|
|
1162
|
+
return;
|
|
1163
|
+
}
|
|
1164
|
+
void this.adapter.setInteractivePromptResponse(response).catch((e: any) => {
|
|
1165
|
+
LOG.warn('CLI', `[${this.type}] interactive_prompt_response failed: ${e?.message || e}`);
|
|
1166
|
+
});
|
|
1167
|
+
} catch (e: any) {
|
|
1168
|
+
LOG.warn('CLI', `[${this.type}] invalid interactive_prompt_response: ${e?.message || e}`);
|
|
1169
|
+
}
|
|
693
1170
|
} else if (event === 'provider_state_patch' && data && typeof data === 'object') {
|
|
694
1171
|
this.applyProviderResponse(data, { phase: 'immediate' });
|
|
695
1172
|
}
|
|
696
1173
|
}
|
|
697
1174
|
|
|
1175
|
+
recordAcknowledgedUserInput(input: InputEnvelope | string): void {
|
|
1176
|
+
const content = typeof input === 'string'
|
|
1177
|
+
? input.trim()
|
|
1178
|
+
: buildCliStructuredInputPrompt(input).trim();
|
|
1179
|
+
if (!content) return;
|
|
1180
|
+
|
|
1181
|
+
const receivedAt = Date.now();
|
|
1182
|
+
|
|
1183
|
+
// TASKBUBBLE-DUP: collapse a redelivered dispatch to one bubble. A single
|
|
1184
|
+
// mesh_send_task can reach this instance as TWO send_chat calls when the
|
|
1185
|
+
// first injection is buffered during bootstrap/busy and a retry (dispatch-
|
|
1186
|
+
// confirm-timeout requeue, or a reconcile re-dispatch) fires before the
|
|
1187
|
+
// outbound queue drains. The previous dedupKey hashed receivedAt, so the
|
|
1188
|
+
// two acks produced different keys and BOTH bubbled. Suppress an identical
|
|
1189
|
+
// content ack seen within USER_INPUT_ACK_DEDUP_WINDOW_MS; a later resend of
|
|
1190
|
+
// the same text (beyond the window) is a genuine new turn and still shows.
|
|
1191
|
+
const ackContentKey = shortHash(`${this.instanceId}:${content}`, 24);
|
|
1192
|
+
const lastAckAt = this.recentUserInputAcks.get(ackContentKey);
|
|
1193
|
+
if (lastAckAt !== undefined && receivedAt - lastAckAt <= USER_INPUT_ACK_DEDUP_WINDOW_MS) {
|
|
1194
|
+
// Refresh the timestamp so a steady stream of redeliveries keeps
|
|
1195
|
+
// collapsing, and prune stale entries to bound the map size.
|
|
1196
|
+
this.recentUserInputAcks.set(ackContentKey, receivedAt);
|
|
1197
|
+
this.pruneRecentUserInputAcks(receivedAt);
|
|
1198
|
+
return;
|
|
1199
|
+
}
|
|
1200
|
+
this.recentUserInputAcks.set(ackContentKey, receivedAt);
|
|
1201
|
+
this.pruneRecentUserInputAcks(receivedAt);
|
|
1202
|
+
|
|
1203
|
+
this.lastAcknowledgedUserInputAt = receivedAt;
|
|
1204
|
+
// The runtimeMessages dedupKey stays per-call unique (includes receivedAt)
|
|
1205
|
+
// so a genuine resend of the same text after the window appends a fresh
|
|
1206
|
+
// bubble; redelivery within the window is already suppressed above.
|
|
1207
|
+
const dedupKey = `user_input_ack:${shortHash(`${this.instanceId}:${content}:${receivedAt}`, 24)}`;
|
|
1208
|
+
this.appendRuntimeMessage(buildChatMessage({
|
|
1209
|
+
role: 'user',
|
|
1210
|
+
senderName: 'User',
|
|
1211
|
+
kind: 'standard',
|
|
1212
|
+
content,
|
|
1213
|
+
receivedAt,
|
|
1214
|
+
timestamp: receivedAt,
|
|
1215
|
+
source: 'runtime_input_ack',
|
|
1216
|
+
meta: {
|
|
1217
|
+
runtimeInputAck: true,
|
|
1218
|
+
provider: this.type,
|
|
1219
|
+
workspace: this.workingDir,
|
|
1220
|
+
},
|
|
1221
|
+
} as ChatMessage), dedupKey);
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
/** Drop user-input ack entries older than the dedup window so the map can't grow unbounded. */
|
|
1225
|
+
private pruneRecentUserInputAcks(now: number): void {
|
|
1226
|
+
if (this.recentUserInputAcks.size <= 1) return;
|
|
1227
|
+
for (const [key, at] of this.recentUserInputAcks) {
|
|
1228
|
+
if (now - at > USER_INPUT_ACK_DEDUP_WINDOW_MS) this.recentUserInputAcks.delete(key);
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
|
|
698
1232
|
dispose(): void {
|
|
699
1233
|
this.adapter.shutdown();
|
|
700
1234
|
this.monitor.reset();
|
|
1235
|
+
// Cancel any armed auto-approve timers so a pending settle re-check
|
|
1236
|
+
// can't fire resolveModal/detectStatusTransition against a dead adapter.
|
|
1237
|
+
if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
|
|
1238
|
+
if (this.autoApproveBusyTimer) { clearTimeout(this.autoApproveBusyTimer); this.autoApproveBusyTimer = null; }
|
|
701
1239
|
this.appliedEffectKeys.clear();
|
|
702
1240
|
try { this.cachedSqliteDb?.close(); } catch { /* noop */ }
|
|
703
1241
|
this.cachedSqliteDb = null;
|
|
@@ -706,6 +1244,7 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
706
1244
|
|
|
707
1245
|
private completedDebounceTimer: NodeJS.Timeout | null = null;
|
|
708
1246
|
private completedDebouncePending: CompletedDebouncePending | null = null;
|
|
1247
|
+
private lastExternalCompletionProbe: ExternalTranscriptProbe | null = null;
|
|
709
1248
|
|
|
710
1249
|
private async enforceFreshSessionLaunchIfNeeded(): Promise<void> {
|
|
711
1250
|
const scriptName = getForcedNewSessionScriptName(this.provider, this.launchMode);
|
|
@@ -740,7 +1279,180 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
740
1279
|
const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
|
|
741
1280
|
const role = typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : '';
|
|
742
1281
|
const content = lastVisible ? flattenContent(lastVisible.content).trim() : '';
|
|
743
|
-
|
|
1282
|
+
if (role !== 'assistant' || !content) return false;
|
|
1283
|
+
// Guard: if the last assistant message looks like an active approval/input prompt,
|
|
1284
|
+
// it is not a real completion — the session is still awaiting user input.
|
|
1285
|
+
if (looksLikeActiveApprovalPromptText(content)) return false;
|
|
1286
|
+
return true;
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
private buildExternalTranscriptProbe(messages: unknown[], sourcePath?: string, sourceMtimeMs?: number): ExternalTranscriptProbe {
|
|
1290
|
+
const visibleMessages = messages.filter((message: any) => isUserFacingChatMessage(message as ChatMessage));
|
|
1291
|
+
const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
|
|
1292
|
+
const readAt = Date.now();
|
|
1293
|
+
const mtimeMs = Number(sourceMtimeMs) || 0;
|
|
1294
|
+
return {
|
|
1295
|
+
readAt,
|
|
1296
|
+
msgCount: messages.length,
|
|
1297
|
+
lastRole: typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : null,
|
|
1298
|
+
lastKind: typeof (lastVisible as any)?.kind === 'string' ? (lastVisible as any).kind : null,
|
|
1299
|
+
contentLen: lastVisible ? flattenContent(lastVisible.content).trim().length : 0,
|
|
1300
|
+
sourcePath: typeof sourcePath === 'string' && sourcePath ? sourcePath : null,
|
|
1301
|
+
sourceMtimeMs: mtimeMs || null,
|
|
1302
|
+
mtimeAgeMs: mtimeMs ? Math.max(0, readAt - mtimeMs) : null,
|
|
1303
|
+
};
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
private recordPendingTranscriptProbe(pending: CompletedDebouncePending): ExternalTranscriptProbe | null {
|
|
1307
|
+
const probe = this.lastExternalCompletionProbe;
|
|
1308
|
+
if (!probe) return null;
|
|
1309
|
+
const history = pending.transcriptProbeHistory || [];
|
|
1310
|
+
const last = history[history.length - 1];
|
|
1311
|
+
if (!last || last.readAt !== probe.readAt || last.msgCount !== probe.msgCount || last.lastRole !== probe.lastRole || last.contentLen !== probe.contentLen) {
|
|
1312
|
+
history.push(probe);
|
|
1313
|
+
pending.transcriptProbeHistory = history.slice(-5);
|
|
1314
|
+
}
|
|
1315
|
+
return probe;
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
private readExternalCompletionMessages(): unknown[] | null {
|
|
1319
|
+
const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
|
|
1320
|
+
if (!adapterOwnsMessagesElsewhere) return null;
|
|
1321
|
+
if (!this.providerSessionId) return null;
|
|
1322
|
+
if (!isNativeSourceCanonicalHistory(this.provider.nativeHistory)) return null;
|
|
1323
|
+
|
|
1324
|
+
if (this.lastExternalCompletionProbe?.sourcePath) {
|
|
1325
|
+
try { fs.statSync(this.lastExternalCompletionProbe.sourcePath); } catch { /* best-effort metadata refresh */ }
|
|
1326
|
+
}
|
|
1327
|
+
const restoredHistory = readProviderChatHistory(this.type, {
|
|
1328
|
+
canonicalHistory: this.provider.nativeHistory,
|
|
1329
|
+
historySessionId: this.providerSessionId,
|
|
1330
|
+
workspace: this.workingDir,
|
|
1331
|
+
offset: 0,
|
|
1332
|
+
limit: Number.MAX_SAFE_INTEGER,
|
|
1333
|
+
historyBehavior: this.provider.historyBehavior,
|
|
1334
|
+
scripts: this.provider.scripts as any,
|
|
1335
|
+
sessionStartedAtMs: this.startedAt,
|
|
1336
|
+
forceRefresh: true,
|
|
1337
|
+
});
|
|
1338
|
+
if (restoredHistory.source !== 'provider-native') {
|
|
1339
|
+
this.lastExternalCompletionProbe = null;
|
|
1340
|
+
return null;
|
|
1341
|
+
}
|
|
1342
|
+
this.lastExternalCompletionProbe = this.buildExternalTranscriptProbe(
|
|
1343
|
+
restoredHistory.messages,
|
|
1344
|
+
restoredHistory.sourcePath,
|
|
1345
|
+
restoredHistory.sourceMtimeMs,
|
|
1346
|
+
);
|
|
1347
|
+
return restoredHistory.messages;
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
private completionFinalAssistantEvidence(parsedMessages: unknown): CompletionFinalAssistantEvidence {
|
|
1351
|
+
if (this.completionHasFinalAssistantMessage(parsedMessages)) {
|
|
1352
|
+
return {
|
|
1353
|
+
present: true,
|
|
1354
|
+
messages: Array.isArray(parsedMessages) ? parsedMessages : [],
|
|
1355
|
+
source: 'parsed',
|
|
1356
|
+
};
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
const externalMessages = this.readExternalCompletionMessages();
|
|
1360
|
+
if (externalMessages) {
|
|
1361
|
+
return {
|
|
1362
|
+
present: this.completionHasFinalAssistantMessage(externalMessages),
|
|
1363
|
+
messages: externalMessages,
|
|
1364
|
+
source: 'external-native',
|
|
1365
|
+
};
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
return {
|
|
1369
|
+
present: false,
|
|
1370
|
+
messages: Array.isArray(parsedMessages) ? parsedMessages : [],
|
|
1371
|
+
source: 'unavailable',
|
|
1372
|
+
};
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
private completionFinalSummary(parsedMessages: unknown): string | undefined {
|
|
1376
|
+
// For native-source providers (claude-cli: chatMessagesOwnedExternally), the PTY
|
|
1377
|
+
// screen parse is NOT the source of truth for the final summary — the terminal
|
|
1378
|
+
// wraps/scrolls/clips text, so a screen-parsed assistant message is often a partial
|
|
1379
|
+
// prefix (e.g. 76 chars of a 112-char turn). The append-only native transcript holds
|
|
1380
|
+
// the complete turn. Prefer it whenever it yields a longer/complete summary; fall back
|
|
1381
|
+
// to the parsed screen only when the transcript is unavailable. This is the real cause
|
|
1382
|
+
// of the truncated finalSummary — independent of cloud vs standalone (it surfaces on
|
|
1383
|
+
// any short, fast-completing task where screen parse wins the race).
|
|
1384
|
+
const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
|
|
1385
|
+
const parsedSummary = extractFinalSummaryFromMessages(
|
|
1386
|
+
(this.completionHasFinalAssistantMessage(parsedMessages)
|
|
1387
|
+
? (Array.isArray(parsedMessages) ? parsedMessages : [])
|
|
1388
|
+
: []) as any,
|
|
1389
|
+
);
|
|
1390
|
+
if (adapterOwnsMessagesElsewhere) {
|
|
1391
|
+
const externalMessages = this.readExternalCompletionMessages();
|
|
1392
|
+
const externalSummary = externalMessages
|
|
1393
|
+
? extractFinalSummaryFromMessages(externalMessages as any)
|
|
1394
|
+
: '';
|
|
1395
|
+
// The transcript is authoritative for native-source providers. Use it unless it is
|
|
1396
|
+
// empty (not yet written) — only then fall back to whatever the screen parsed.
|
|
1397
|
+
if (externalSummary) return externalSummary;
|
|
1398
|
+
return parsedSummary || undefined;
|
|
1399
|
+
}
|
|
1400
|
+
return parsedSummary || undefined;
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
private buildCompletedFinalizationDiagnostic(args: {
|
|
1404
|
+
blockReason: string;
|
|
1405
|
+
latestStatus?: any;
|
|
1406
|
+
latestVisibleStatus: string;
|
|
1407
|
+
waitedMs: number;
|
|
1408
|
+
pending: CompletedDebouncePending;
|
|
1409
|
+
emittedAfterFinalizationTimeout: boolean;
|
|
1410
|
+
}): Record<string, unknown> {
|
|
1411
|
+
let parsed: any = null;
|
|
1412
|
+
let parseError: string | undefined;
|
|
1413
|
+
try {
|
|
1414
|
+
parsed = this.adapter.getScriptParsedStatus();
|
|
1415
|
+
} catch (error: any) {
|
|
1416
|
+
parseError = error?.message || String(error);
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
const evidence = this.completionFinalAssistantEvidence(parsed?.messages);
|
|
1420
|
+
if (evidence.source === 'external-native') {
|
|
1421
|
+
this.recordPendingTranscriptProbe(args.pending);
|
|
1422
|
+
}
|
|
1423
|
+
const visibleMessages = (Array.isArray(evidence.messages) ? evidence.messages : [])
|
|
1424
|
+
.filter((message: any) => isUserFacingChatMessage(message as ChatMessage));
|
|
1425
|
+
const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
|
|
1426
|
+
const lastVisibleRole = typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : null;
|
|
1427
|
+
const lastVisibleKind = typeof (lastVisible as any)?.kind === 'string' ? (lastVisible as any).kind : null;
|
|
1428
|
+
const lastVisibleContentLength = lastVisible ? flattenContent(lastVisible.content).trim().length : 0;
|
|
1429
|
+
|
|
1430
|
+
return {
|
|
1431
|
+
providerType: this.type,
|
|
1432
|
+
sessionId: this.instanceId,
|
|
1433
|
+
providerSessionId: this.providerSessionId || null,
|
|
1434
|
+
workspace: this.workingDir,
|
|
1435
|
+
blockReason: args.blockReason,
|
|
1436
|
+
emittedAfterFinalizationTimeout: args.emittedAfterFinalizationTimeout,
|
|
1437
|
+
waitedMs: args.waitedMs,
|
|
1438
|
+
maxWaitMs: COMPLETED_FINALIZATION_MAX_WAIT_MS,
|
|
1439
|
+
adapterStatus: typeof args.latestStatus?.status === 'string' ? args.latestStatus.status : null,
|
|
1440
|
+
latestVisibleStatus: args.latestVisibleStatus,
|
|
1441
|
+
parsedStatus: typeof parsed?.status === 'string' ? parsed.status : (parseError ? 'parse_error' : 'unknown'),
|
|
1442
|
+
parseError: parseError || undefined,
|
|
1443
|
+
finalAssistantPresent: evidence.present,
|
|
1444
|
+
finalAssistantEvidenceSource: evidence.source,
|
|
1445
|
+
visibleMessageCount: visibleMessages.length,
|
|
1446
|
+
lastVisibleRole,
|
|
1447
|
+
lastVisibleKind,
|
|
1448
|
+
lastVisibleContentLength,
|
|
1449
|
+
pendingStartedAt: this.generatingStartedAt || null,
|
|
1450
|
+
pendingFirstObservedAt: args.pending.firstObservedAt,
|
|
1451
|
+
pendingTimestamp: args.pending.timestamp,
|
|
1452
|
+
pendingDurationSec: args.pending.duration,
|
|
1453
|
+
previousBlockReason: args.pending.loggedBlockReason || null,
|
|
1454
|
+
transcriptProbeHistory: args.pending.transcriptProbeHistory || [],
|
|
1455
|
+
};
|
|
744
1456
|
}
|
|
745
1457
|
|
|
746
1458
|
private hasAdapterPendingResponse(): boolean {
|
|
@@ -765,41 +1477,206 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
765
1477
|
if (!isCliGeneratingLikeStatus(parsedRawStatus)) return false;
|
|
766
1478
|
if (adapterRawStatus !== 'idle') return false;
|
|
767
1479
|
if (hasNonEmptyCliModalButtons(parsedStatus?.activeModal ?? parsedStatus?.modal)) return false;
|
|
768
|
-
|
|
1480
|
+
if (this.hasAdapterPendingResponse()) return false;
|
|
1481
|
+
// Do not suppress when the adapter's raw response buffer is still non-empty.
|
|
1482
|
+
// This catches the case where isWaitingForResponse has already flipped to false
|
|
1483
|
+
// (so getPartialResponse() returns '') but the provider's native parser still
|
|
1484
|
+
// reports generating because it's parsing buffered content. Suppressing the
|
|
1485
|
+
// finalization block here would emit a false completion event while the provider
|
|
1486
|
+
// session is still actively processing its response stream.
|
|
1487
|
+
const adapterAny = this.adapter as any;
|
|
1488
|
+
if (typeof adapterAny?.responseBuffer === 'string' && adapterAny.responseBuffer.trim()) return false;
|
|
1489
|
+
return true;
|
|
769
1490
|
}
|
|
770
1491
|
|
|
771
|
-
private
|
|
772
|
-
if (latestVisibleStatus !== 'idle') return `status:${latestVisibleStatus}
|
|
1492
|
+
private getCompletedFinalizationBlock(latestVisibleStatus: string, pending: CompletedDebouncePending): CompletedFinalizationBlock | null {
|
|
1493
|
+
if (latestVisibleStatus !== 'idle') return { reason: `status:${latestVisibleStatus}`, terminal: true };
|
|
773
1494
|
|
|
774
1495
|
const adapterAny = this.adapter as any;
|
|
775
|
-
|
|
776
|
-
if (
|
|
1496
|
+
const approvalResolvedIdle = pending.previousStatus === 'waiting_approval';
|
|
1497
|
+
if (!approvalResolvedIdle) {
|
|
1498
|
+
if (adapterAny?.isWaitingForResponse === true) return { reason: 'adapter_waiting_for_response', terminal: true };
|
|
1499
|
+
if (adapterAny?.currentTurnScope) return { reason: 'adapter_turn_scope_active', terminal: true };
|
|
1500
|
+
if (this.hasAdapterPendingResponse()) return { reason: 'adapter_pending_response', terminal: true };
|
|
1501
|
+
}
|
|
777
1502
|
|
|
778
1503
|
const partial = typeof this.adapter.getPartialResponse === 'function'
|
|
779
1504
|
? this.adapter.getPartialResponse()
|
|
780
1505
|
: '';
|
|
781
|
-
if (typeof partial === 'string' && partial.trim()) return 'partial_response_pending';
|
|
1506
|
+
if (typeof partial === 'string' && partial.trim()) return { reason: 'partial_response_pending', terminal: true };
|
|
782
1507
|
|
|
783
1508
|
let parsed: any;
|
|
784
1509
|
try {
|
|
785
1510
|
parsed = this.adapter.getScriptParsedStatus();
|
|
786
1511
|
} catch (error: any) {
|
|
787
|
-
return `parse_error:${error?.message || String(error)}
|
|
1512
|
+
return { reason: `parse_error:${error?.message || String(error)}` };
|
|
788
1513
|
}
|
|
789
1514
|
|
|
790
1515
|
const parsedStatus = typeof parsed?.status === 'string' ? parsed.status : 'unknown';
|
|
791
|
-
if (parsedStatus !== 'idle')
|
|
792
|
-
|
|
793
|
-
|
|
1516
|
+
if (parsedStatus !== 'idle') {
|
|
1517
|
+
const adapterStatus = this.adapter.getStatus({ allowParse: false });
|
|
1518
|
+
if (this.shouldSuppressStaleParsedBusyStatus(parsed, adapterStatus)) return null;
|
|
1519
|
+
return { reason: `parsed_status:${parsedStatus}`, terminal: isCliGeneratingLikeStatus(parsedStatus) };
|
|
1520
|
+
}
|
|
1521
|
+
if (parsed?.activeModal || parsed?.modal) return { reason: 'parsed_modal_active', terminal: true };
|
|
1522
|
+
const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
|
|
1523
|
+
const finalAssistantEvidence = this.completionFinalAssistantEvidence(parsed?.messages);
|
|
1524
|
+
const allowMissingAssistantTimeout = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
|
|
1525
|
+
LOG.debug('CLI', `[${this.type}] finalAssistantEvidence: present=${finalAssistantEvidence.present} source=${finalAssistantEvidence.source} adapterOwnsMessagesElsewhere=${adapterOwnsMessagesElsewhere} parsedStatus=${parsedStatus}`);
|
|
1526
|
+
if (!finalAssistantEvidence.present) {
|
|
1527
|
+
if (adapterOwnsMessagesElsewhere) {
|
|
1528
|
+
if (finalAssistantEvidence.source === 'external-native') {
|
|
1529
|
+
const probe = this.recordPendingTranscriptProbe(pending);
|
|
1530
|
+
if (probe && !pending.loggedTranscriptProbe) {
|
|
1531
|
+
LOG.info('CLI', `[${this.type}] external transcript probe: msgCount=${probe.msgCount} lastRole=${probe.lastRole || 'none'} lastKind=${probe.lastKind || 'none'} contentLen=${probe.contentLen} sourceMtime=${probe.sourceMtimeMs ?? 'unknown'} mtimeAge=${probe.mtimeAgeMs ?? 'unknown'}ms`);
|
|
1532
|
+
pending.loggedTranscriptProbe = true;
|
|
1533
|
+
}
|
|
1534
|
+
LOG.debug('CLI', `[${this.type}] external-native probe result: lastRole=${probe?.lastRole} contentLen=${probe?.contentLen}`);
|
|
1535
|
+
if (probe?.lastRole === 'assistant' && (probe.contentLen ?? 0) > 0) {
|
|
1536
|
+
return null;
|
|
1537
|
+
}
|
|
1538
|
+
if (this.type === 'antigravity-cli') {
|
|
1539
|
+
return null;
|
|
1540
|
+
}
|
|
1541
|
+
// (SETTLE-VALLEY) The inter-approval idle valley: a native-history mesh worker
|
|
1542
|
+
// that resolved an approval and fell briefly idle (waiting_approval→idle) BEFORE
|
|
1543
|
+
// the next approval turn resumes. The live valley (~3s) is mostly covered by the
|
|
1544
|
+
// 4000ms NATIVE_HISTORY_MESH_IDLE_SETTLE_MS settle window, but a longer valley can
|
|
1545
|
+
// still let the flush run while the transcript's final assistant turn is not yet
|
|
1546
|
+
// written (source still the screen parse → finalAssistantPresent=false,
|
|
1547
|
+
// workerResult.source='default'). CANON-C would emit immediately here, freezing a
|
|
1548
|
+
// truncated preamble summary as evidenceLevel=insufficient. Instead HOLD: this
|
|
1549
|
+
// waiting_approval hold complements the settle window. Retry until the transcript finalizes
|
|
1550
|
+
// (block clears → genuine emit) or the worker resumes (resume guard cancels),
|
|
1551
|
+
// bounded by COMPLETED_FINALIZATION_MAX_WAIT_MS. Scoped to the approval-resolved
|
|
1552
|
+
// idle so a genuinely-finished background-child turn keeps the CANON-C immediate
|
|
1553
|
+
// emit (its transcript trails by a write, not by a whole resume).
|
|
1554
|
+
if (allowMissingAssistantTimeout && pending.previousStatus === 'waiting_approval') {
|
|
1555
|
+
return { reason: 'missing_final_assistant', terminal: false, holdForTranscript: true };
|
|
1556
|
+
}
|
|
1557
|
+
return { reason: 'missing_final_assistant', terminal: true, allowTimeout: allowMissingAssistantTimeout };
|
|
1558
|
+
}
|
|
1559
|
+
if ((this.provider as any).requiresFinalAssistantBeforeIdle === true) {
|
|
1560
|
+
return { reason: 'missing_final_assistant', terminal: true, allowTimeout: allowMissingAssistantTimeout };
|
|
1561
|
+
}
|
|
1562
|
+
} else {
|
|
1563
|
+
LOG.debug('CLI', `[${this.type}] missing_final_assistant (not ownsExternal) requiresFinalAssistant=${!!(this.provider as any).requiresFinalAssistantBeforeIdle}`);
|
|
1564
|
+
return {
|
|
1565
|
+
reason: 'missing_final_assistant',
|
|
1566
|
+
terminal: (this.provider as any).requiresFinalAssistantBeforeIdle === true,
|
|
1567
|
+
allowTimeout: allowMissingAssistantTimeout,
|
|
1568
|
+
};
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
// (FALSEIDLE-a) Structural approval-resolution gate. Runs BEFORE the brittle
|
|
1573
|
+
// screen-text heuristic below so it also catches modals whose text does not match
|
|
1574
|
+
// looksLikeActiveApprovalPromptText (e.g. claude-cli's cd / "untrusted hooks" prompt).
|
|
1575
|
+
const approvalResolutionBlock = this.approvalResolutionFinalizationBlock(pending);
|
|
1576
|
+
if (approvalResolutionBlock) return approvalResolutionBlock;
|
|
1577
|
+
|
|
1578
|
+
// Guard: if the screen still shows an approval/choice prompt as the last visible text,
|
|
1579
|
+
// the turn is not complete even if the parsed status says idle and there is an assistant
|
|
1580
|
+
// message. This catches the case where waiting_approval→idle transitions occur before
|
|
1581
|
+
// the modal has been resolved (e.g. the PTY rendered the prompt but no button press fired).
|
|
1582
|
+
try {
|
|
1583
|
+
const screenText = typeof (this.adapter as any).getScreenText === 'function'
|
|
1584
|
+
? String((this.adapter as any).getScreenText() || '')
|
|
1585
|
+
: '';
|
|
1586
|
+
if (screenText) {
|
|
1587
|
+
const tailLines = screenText.split(/\r?\n/).slice(-16).join('\n');
|
|
1588
|
+
if (looksLikeActiveApprovalPromptText(tailLines)) {
|
|
1589
|
+
return { reason: 'screen_shows_approval_prompt', terminal: approvalResolvedIdle };
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
} catch { /* defensive: screen text read is best-effort */ }
|
|
794
1593
|
|
|
795
1594
|
return null;
|
|
796
1595
|
}
|
|
797
1596
|
|
|
1597
|
+
// (FALSEIDLE-a) Positive, structural proof that the latest approval entry was resolved
|
|
1598
|
+
// through ADHDev. resolveModal() — driven by auto-approve, dashboard/mesh_approve, and
|
|
1599
|
+
// dev-cli-debug alike — advances the engine's lastResolvedEntrySeq to the current
|
|
1600
|
+
// approvalEntrySeq. So `lastResolvedEntrySeq >= approvalEntrySeq` (with a real entry,
|
|
1601
|
+
// approvalEntrySeq > 0) means the modal we last saw was actually answered. Absence of this
|
|
1602
|
+
// evidence after a waiting_approval→idle transition means the idle is suspect: the spec's
|
|
1603
|
+
// text-based approval→idle rule false-tripped while the modal is still unresolved.
|
|
1604
|
+
// Fails OPEN (returns true) when the seq fields are unavailable, so the gate can never wedge
|
|
1605
|
+
// a session on a provider/adapter that does not surface the counters.
|
|
1606
|
+
private hasApprovalResolutionEvidence(): boolean {
|
|
1607
|
+
try {
|
|
1608
|
+
const status = this.adapter.getStatus({ allowParse: false }) as any;
|
|
1609
|
+
const entrySeq = typeof status?.approvalEntrySeq === 'number' ? status.approvalEntrySeq : 0;
|
|
1610
|
+
if (entrySeq <= 0) return true;
|
|
1611
|
+
const resolvedSeq = typeof status?.lastResolvedEntrySeq === 'number' ? status.lastResolvedEntrySeq : undefined;
|
|
1612
|
+
if (resolvedSeq === undefined) return true;
|
|
1613
|
+
return resolvedSeq >= entrySeq;
|
|
1614
|
+
} catch {
|
|
1615
|
+
return true;
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
// (FALSEIDLE-a) Hold a completion that is the anomalous DIRECT waiting_approval→idle
|
|
1620
|
+
// transition with no positive resolution evidence. A genuinely resolved approval routes
|
|
1621
|
+
// through resolveModal → setStatus('generating'), so its completion's previousStatus is
|
|
1622
|
+
// 'generating' (not 'waiting_approval') and this gate never fires for it. Scoped to
|
|
1623
|
+
// delegated mesh/coordinator sessions — whose only modal-resolution path is auto-approve /
|
|
1624
|
+
// mesh_approve (both advance lastResolvedEntrySeq) — so an interactive local session, where
|
|
1625
|
+
// a human may answer the PTY prompt directly and leave no resolveModal record, is untouched.
|
|
1626
|
+
// Non-terminal: the hold is bounded by COMPLETED_FINALIZATION_MAX_WAIT_MS (30s), giving a
|
|
1627
|
+
// settling auto-approve time to fire and advance the seq, and guaranteeing no permanent wedge
|
|
1628
|
+
// if resolution ever happens via a path that does not record evidence.
|
|
1629
|
+
private approvalResolutionFinalizationBlock(pending: CompletedDebouncePending): CompletedFinalizationBlock | null {
|
|
1630
|
+
if (pending.previousStatus !== 'waiting_approval') return null;
|
|
1631
|
+
const meshContext = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
|
|
1632
|
+
if (!meshContext) return null;
|
|
1633
|
+
if (this.hasApprovalResolutionEvidence()) return null;
|
|
1634
|
+
return { reason: 'approval_resolution_unconfirmed', terminal: false };
|
|
1635
|
+
}
|
|
1636
|
+
|
|
798
1637
|
private scheduleCompletedDebounceFlush(delayMs: number): void {
|
|
799
1638
|
if (this.completedDebounceTimer) clearTimeout(this.completedDebounceTimer);
|
|
800
1639
|
this.completedDebounceTimer = setTimeout(() => this.flushCompletedDebounceIfFinalized(), delayMs);
|
|
801
1640
|
}
|
|
802
1641
|
|
|
1642
|
+
// EVTTRACE (observation-only): is this a mesh worker session whose completion
|
|
1643
|
+
// events must route to a coordinator? Used purely to gate trace logging so a
|
|
1644
|
+
// non-mesh CLI session's completions don't add EvtTrace noise. No decision logic.
|
|
1645
|
+
private isMeshWorkerSession(): boolean {
|
|
1646
|
+
return !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId
|
|
1647
|
+
|| this.settings.meshNodeId || this.settings.launchedByCoordinator);
|
|
1648
|
+
}
|
|
1649
|
+
|
|
1650
|
+
/**
|
|
1651
|
+
* ARCH-REFACTOR R1: the taskId to attribute the CURRENTLY-completing turn to.
|
|
1652
|
+
* Prefers the per-turn binding (engine.currentTurnTaskId, set when the turn was
|
|
1653
|
+
* submitted and surviving until the next turn starts) over the last-write-wins
|
|
1654
|
+
* session scalar (settings.meshActiveTaskId). The scalar is retained only as a
|
|
1655
|
+
* backward-compat alias for the "current/last assignment" and is the source of the
|
|
1656
|
+
* NOTIF-MISDELIVER / TASK-MSG-MISROUTE race: a second task attaching before this
|
|
1657
|
+
* turn completes overwrites it. Returns undefined for a non-task ad-hoc turn.
|
|
1658
|
+
*/
|
|
1659
|
+
private completingTurnTaskId(): string | undefined {
|
|
1660
|
+
const turnTaskId = this.adapter?.currentTurnTaskId;
|
|
1661
|
+
if (typeof turnTaskId === 'string' && turnTaskId.trim()) return turnTaskId;
|
|
1662
|
+
const scalar = this.settings.meshActiveTaskId;
|
|
1663
|
+
return typeof scalar === 'string' && scalar.trim() ? scalar : undefined;
|
|
1664
|
+
}
|
|
1665
|
+
|
|
1666
|
+
// EVTTRACE correlation context for this session's completion lifecycle. taskId is
|
|
1667
|
+
// the primary grep anchor; instanceId is the session fallback.
|
|
1668
|
+
private meshTraceCtx(event = 'agent:generating_completed'): Record<string, unknown> {
|
|
1669
|
+
return {
|
|
1670
|
+
// ARCH-REFACTOR R1: trace the per-turn taskId (falling back to the scalar) so
|
|
1671
|
+
// EvtTrace anchors on the same id the completion event actually carries.
|
|
1672
|
+
taskId: this.completingTurnTaskId(),
|
|
1673
|
+
sessionId: this.instanceId,
|
|
1674
|
+
nodeId: this.settings.meshNodeId,
|
|
1675
|
+
meshId: this.settings.meshNodeFor,
|
|
1676
|
+
event,
|
|
1677
|
+
};
|
|
1678
|
+
}
|
|
1679
|
+
|
|
803
1680
|
private flushCompletedDebounceIfFinalized(): void {
|
|
804
1681
|
const pending = this.completedDebouncePending;
|
|
805
1682
|
if (!pending) {
|
|
@@ -809,7 +1686,8 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
809
1686
|
|
|
810
1687
|
const latestStatus = this.adapter.getStatus({ allowParse: false });
|
|
811
1688
|
const latestAutoApproveActive = latestStatus.status === 'waiting_approval' && this.shouldAutoApprove();
|
|
812
|
-
const latestVisibleStatus = latestAutoApproveActive ? 'generating' : latestStatus.status;
|
|
1689
|
+
const latestVisibleStatus = latestAutoApproveActive || this.autoApproveBusy ? 'generating' : latestStatus.status;
|
|
1690
|
+
LOG.debug('CLI', `[${this.type}] flush attempt: adapterStatus=${latestStatus.status} latestVisible=${latestVisibleStatus} generatingStartedAt=${this.generatingStartedAt} isWaitingForResponse=${!!(this.adapter as any)?.isWaitingForResponse} hasPartial=${!!this.adapter.getPartialResponse?.()}`);
|
|
813
1691
|
if (latestVisibleStatus !== 'idle') {
|
|
814
1692
|
LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed ${latestVisibleStatus})`);
|
|
815
1693
|
this.completedDebouncePending = null;
|
|
@@ -817,84 +1695,414 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
817
1695
|
return;
|
|
818
1696
|
}
|
|
819
1697
|
|
|
820
|
-
const
|
|
821
|
-
if (
|
|
1698
|
+
const block = this.getCompletedFinalizationBlock(latestVisibleStatus, pending);
|
|
1699
|
+
if (block) {
|
|
1700
|
+
const blockReason = block.reason;
|
|
822
1701
|
const waitedMs = Date.now() - pending.firstObservedAt;
|
|
823
|
-
|
|
1702
|
+
// CANON-C (completion-gate decouple): a block carrying `allowTimeout` is the
|
|
1703
|
+
// transcript-evidence gate — the worker FSM has ALREADY reached idle and the only
|
|
1704
|
+
// thing missing is the append-only transcript's final assistant turn (a native-source
|
|
1705
|
+
// race: claude-cli owns its history externally and the file write trails the idle
|
|
1706
|
+
// transition). `allowTimeout` is set ONLY on the missing_final_assistant block, and
|
|
1707
|
+
// ONLY for mesh worker sessions (meshNodeFor / meshActiveTaskId / launchedByCoordinator).
|
|
1708
|
+
// The coordinator's sole path to learn this session is idle is agent:generating_completed,
|
|
1709
|
+
// so holding it up to COMPLETED_FINALIZATION_MAX_WAIT_MS (30s) leaves the coordinator
|
|
1710
|
+
// false-generating while the worker is done. Decouple the idle NOTIFICATION from the
|
|
1711
|
+
// transcript evidence: emit the completion immediately, marked weak
|
|
1712
|
+
// (completionDiagnostic.blockReason=missing_final_assistant, finalAssistantPresent=false).
|
|
1713
|
+
// The finalSummary is enriched on a SEPARATE path — the mesh reconcile loop reads the
|
|
1714
|
+
// transcript once written and re-emits a GENUINE completion (CANON-B weak→genuine
|
|
1715
|
+
// upgrade; buildPendingEventFingerprint keeps weak and genuine distinct so the enriched
|
|
1716
|
+
// one still surfaces, and isFalseIdleCompletion keeps the direct dispatch active until
|
|
1717
|
+
// then). All OTHER blocks (genuinely-busy adapter/partial/parsed states, transient
|
|
1718
|
+
// parse_error) keep the existing terminal-hold / 30s-retry behavior unchanged.
|
|
1719
|
+
//
|
|
1720
|
+
// (SETTLE-VALLEY) Exception: a `holdForTranscript` block is the inter-approval idle
|
|
1721
|
+
// valley of a native-history mesh worker (waiting_approval→idle that will resume into
|
|
1722
|
+
// the next approval). It deliberately does NOT carry allowTimeout, so it falls into the
|
|
1723
|
+
// hold-and-retry path below (terminal:false) rather than the CANON-C immediate emit —
|
|
1724
|
+
// the retry loop re-runs the resume guard each cycle, so when the worker resumes the
|
|
1725
|
+
// pending completion is cancelled, and when the transcript's final assistant arrives the
|
|
1726
|
+
// block clears for a GENUINE emit. This blocks the truncated weak (insufficient) summary
|
|
1727
|
+
// from ever being emitted during the valley, without depending on the valley's length.
|
|
1728
|
+
const isTranscriptEvidenceGate = block.allowTimeout === true;
|
|
1729
|
+
LOG.debug('CLI', `[${this.type}] finalization block: reason=${blockReason} terminal=${block.terminal} allowTimeout=${isTranscriptEvidenceGate} waitedMs=${waitedMs} maxWait=${COMPLETED_FINALIZATION_MAX_WAIT_MS}`);
|
|
1730
|
+
if (!isTranscriptEvidenceGate && (block.terminal || waitedMs < COMPLETED_FINALIZATION_MAX_WAIT_MS)) {
|
|
824
1731
|
if (pending.loggedBlockReason !== blockReason) {
|
|
825
1732
|
LOG.info('CLI', `[${this.type}] waiting to emit completed until transcript finalizes (${blockReason})`);
|
|
1733
|
+
// EVTTRACE: completion held by the finalization gate (CANON-C). Observation
|
|
1734
|
+
// only — does not change the hold decision above.
|
|
1735
|
+
if (this.isMeshWorkerSession()) {
|
|
1736
|
+
traceMeshEventDrop('completion_gate_hold', this.meshTraceCtx(), `${blockReason} waited=${waitedMs}ms`);
|
|
1737
|
+
}
|
|
826
1738
|
pending.loggedBlockReason = blockReason;
|
|
827
1739
|
}
|
|
828
1740
|
this.scheduleCompletedDebounceFlush(COMPLETED_FINALIZATION_RETRY_MS);
|
|
829
1741
|
return;
|
|
830
1742
|
}
|
|
831
|
-
|
|
1743
|
+
const emittedAfterFinalizationTimeout = waitedMs >= COMPLETED_FINALIZATION_MAX_WAIT_MS;
|
|
1744
|
+
const completionDiagnostic = this.buildCompletedFinalizationDiagnostic({
|
|
1745
|
+
blockReason,
|
|
1746
|
+
latestStatus,
|
|
1747
|
+
latestVisibleStatus,
|
|
1748
|
+
waitedMs,
|
|
1749
|
+
pending,
|
|
1750
|
+
emittedAfterFinalizationTimeout,
|
|
1751
|
+
});
|
|
1752
|
+
// Surface the CANON-C immediate-emit path distinctly so a delegated worker's idle
|
|
1753
|
+
// notification (transcript still pending) is not mistaken for a 30s-timeout fallback.
|
|
1754
|
+
(completionDiagnostic as Record<string, unknown>).decoupledImmediateEmit = isTranscriptEvidenceGate && !emittedAfterFinalizationTimeout;
|
|
1755
|
+
LOG.warn('CLI', `[${this.type}] emitting completed event (${isTranscriptEvidenceGate && !emittedAfterFinalizationTimeout ? 'CANON-C decoupled-immediate, transcript pending' : `after ${waitedMs}ms`}) without finalized assistant turn (${blockReason})`);
|
|
1756
|
+
// EVTTRACE: completion fired (forced past the finalization timeout / CANON-C decoupled-immediate).
|
|
1757
|
+
if (this.isMeshWorkerSession()) {
|
|
1758
|
+
traceMeshEventStage('fired', this.meshTraceCtx(), `forced after ${waitedMs}ms (${blockReason})`);
|
|
1759
|
+
}
|
|
1760
|
+
this.pushEvent({
|
|
1761
|
+
event: 'agent:generating_completed',
|
|
1762
|
+
chatTitle: pending.chatTitle,
|
|
1763
|
+
duration: pending.duration,
|
|
1764
|
+
timestamp: pending.timestamp,
|
|
1765
|
+
// ARCH-REFACTOR R1: attribute to the turn captured at idle-transition.
|
|
1766
|
+
...(pending.taskId ? { taskId: pending.taskId } : {}),
|
|
1767
|
+
// When finalization is forced past the timeout on a `parsed_status:` block
|
|
1768
|
+
// (the parser never confirmed a final assistant turn) we previously rode an
|
|
1769
|
+
// empty `finalSummary` unconditionally. That empty value propagates to the
|
|
1770
|
+
// mesh coordinator's mirror preview (meshSessionLastMessagePreview), leaving a
|
|
1771
|
+
// delegated session's inbox preview blank — or, for a LOCAL worktree session,
|
|
1772
|
+
// stuck on the dispatched user task. If the parser DID surface assistant text,
|
|
1773
|
+
// prefer it; only fall back to '' when no assistant summary can be derived.
|
|
1774
|
+
finalSummary: blockReason.startsWith('parsed_status:')
|
|
1775
|
+
? (this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages) ?? '')
|
|
1776
|
+
: this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages),
|
|
1777
|
+
completionDiagnostic,
|
|
1778
|
+
});
|
|
832
1779
|
this.completedDebouncePending = null;
|
|
833
1780
|
this.completedDebounceTimer = null;
|
|
834
1781
|
this.generatingStartedAt = 0;
|
|
1782
|
+
this.lastApprovalEventFingerprint = '';
|
|
835
1783
|
return;
|
|
836
1784
|
}
|
|
837
1785
|
|
|
838
1786
|
LOG.info('CLI', `[${this.type}] completed in ${pending.duration}s`);
|
|
1787
|
+
// EVTTRACE: completion fired (transcript finalized cleanly).
|
|
1788
|
+
if (this.isMeshWorkerSession()) {
|
|
1789
|
+
traceMeshEventStage('fired', this.meshTraceCtx(), `duration=${pending.duration}s`);
|
|
1790
|
+
}
|
|
839
1791
|
this.pushEvent({
|
|
840
1792
|
event: 'agent:generating_completed',
|
|
841
1793
|
chatTitle: pending.chatTitle,
|
|
842
1794
|
duration: pending.duration,
|
|
843
1795
|
timestamp: pending.timestamp,
|
|
844
|
-
|
|
1796
|
+
// ARCH-REFACTOR R1: attribute to the turn captured at idle-transition.
|
|
1797
|
+
...(pending.taskId ? { taskId: pending.taskId } : {}),
|
|
1798
|
+
finalSummary: this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages),
|
|
845
1799
|
});
|
|
846
1800
|
this.completedDebouncePending = null;
|
|
847
1801
|
this.completedDebounceTimer = null;
|
|
848
1802
|
this.generatingStartedAt = 0;
|
|
1803
|
+
this.lastApprovalEventFingerprint = '';
|
|
849
1804
|
}
|
|
850
1805
|
|
|
851
1806
|
private maybeAutoApproveStatus(adapterStatus: any, now = Date.now()): boolean {
|
|
1807
|
+
// Manual-attendance suppression (provider-common): when a human is
|
|
1808
|
+
// actively driving this session from the dashboard, hold auto-approve so
|
|
1809
|
+
// the modal stays visible and they can pick a button / use the controlbar
|
|
1810
|
+
// themselves. Return false (NOT auto-approving) so getState keeps the
|
|
1811
|
+
// modal surfaced. Clear any in-progress settle gate — a genuine fire
|
|
1812
|
+
// after the window lapses must re-settle from scratch — and arm a
|
|
1813
|
+
// re-check for the lapse moment, because the PTY may have gone silent and
|
|
1814
|
+
// would otherwise never re-drive this decision. Background mesh workers
|
|
1815
|
+
// are never attended, so their delegated auto-approve is untouched.
|
|
1816
|
+
if (adapterStatus?.status === 'waiting_approval'
|
|
1817
|
+
&& this.shouldAutoApprove()
|
|
1818
|
+
&& this.manualAttendance.isAttended(now)) {
|
|
1819
|
+
this.lastAutoApprovalSignature = '';
|
|
1820
|
+
this.pendingAutoApprovalSignature = '';
|
|
1821
|
+
this.pendingAutoApprovalSince = 0;
|
|
1822
|
+
this.autoApproveInactiveSince = 0;
|
|
1823
|
+
// Manual attendance takes over — the modal stays surfaced (maybeAutoApproveStatus
|
|
1824
|
+
// returns false), so end the mask episode.
|
|
1825
|
+
this.autoApproveMaskSince = 0;
|
|
1826
|
+
if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
|
|
1827
|
+
this.autoApproveSettleTimer = setTimeout(() => {
|
|
1828
|
+
this.autoApproveSettleTimer = null;
|
|
1829
|
+
this.recheckAutoApproveSettled();
|
|
1830
|
+
}, this.manualAttendance.remainingMs(now) + 20);
|
|
1831
|
+
return false;
|
|
1832
|
+
}
|
|
852
1833
|
const autoApproveActive = adapterStatus?.status === 'waiting_approval' && this.shouldAutoApprove();
|
|
853
1834
|
// Guard re-entry: onStatusChange/getState can observe the same modal multiple
|
|
854
1835
|
// times while the PTY absorbs the approval key. Without this flag, repeated
|
|
855
1836
|
// snapshots would write stray keys into the input once the modal dismisses.
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
1837
|
+
// However, Claude Code can present a second approval immediately after the
|
|
1838
|
+
// first. Resolve a changed modal signature even while the previous write is
|
|
1839
|
+
// still inside the short busy window.
|
|
1840
|
+
if (!autoApproveActive) {
|
|
1841
|
+
this.lastAutoApprovalSignature = '';
|
|
1842
|
+
// Hysteresis: if a settle gate is mid-progress, a momentary
|
|
1843
|
+
// status!=waiting_approval blip (a generating flip while the same
|
|
1844
|
+
// modal's button block is still on screen) must NOT wipe the settle
|
|
1845
|
+
// clock — otherwise the modal→generating→modal flap restarts the
|
|
1846
|
+
// 600ms window every time and auto-approve never fires. Keep the
|
|
1847
|
+
// gate warm for AUTO_APPROVE_GATE_HYSTERESIS_MS; re-arm a timer so
|
|
1848
|
+
// that if the modal does NOT come back the gate is cleared on the
|
|
1849
|
+
// re-check (a genuine resolution → idle frees the gate normally).
|
|
1850
|
+
if (this.pendingAutoApprovalSince) {
|
|
1851
|
+
if (!this.autoApproveInactiveSince) this.autoApproveInactiveSince = now;
|
|
1852
|
+
const goneForMs = now - this.autoApproveInactiveSince;
|
|
1853
|
+
if (goneForMs < CliProviderInstance.AUTO_APPROVE_GATE_HYSTERESIS_MS) {
|
|
1854
|
+
if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
|
|
1855
|
+
this.autoApproveSettleTimer = setTimeout(() => {
|
|
1856
|
+
this.autoApproveSettleTimer = null;
|
|
1857
|
+
this.recheckAutoApproveSettled();
|
|
1858
|
+
}, CliProviderInstance.AUTO_APPROVE_GATE_HYSTERESIS_MS - goneForMs + 20);
|
|
1859
|
+
return autoApproveActive;
|
|
1860
|
+
}
|
|
1861
|
+
}
|
|
1862
|
+
// Clear the settle gate so the next approval starts its own quiet
|
|
1863
|
+
// window from scratch (a stale timestamp would let it fire instantly).
|
|
1864
|
+
this.pendingAutoApprovalSignature = '';
|
|
1865
|
+
this.pendingAutoApprovalSince = 0;
|
|
1866
|
+
this.autoApproveInactiveSince = 0;
|
|
1867
|
+
// Modal has genuinely been gone past the hysteresis window → the episode ended;
|
|
1868
|
+
// end the mask episode too (a later approval starts a fresh stall clock).
|
|
1869
|
+
this.autoApproveMaskSince = 0;
|
|
1870
|
+
if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
|
|
1871
|
+
return autoApproveActive;
|
|
1872
|
+
}
|
|
1873
|
+
// Active approval observed — reset the inactivity tracker so a later
|
|
1874
|
+
// blip starts its hysteresis window fresh.
|
|
1875
|
+
this.autoApproveInactiveSince = 0;
|
|
1876
|
+
// STATUS-MISMATCH: start (or keep) the mask-stall clock for this episode. Set ONLY
|
|
1877
|
+
// when zero so it survives modal-signature changes and hysteresis blips — it measures
|
|
1878
|
+
// the true age of the unresolved auto-approve, not the per-signature settle window.
|
|
1879
|
+
if (!this.autoApproveMaskSince) this.autoApproveMaskSince = now;
|
|
1880
|
+
const modal = adapterStatus.activeModal;
|
|
1881
|
+
// (fix) Do not auto-approve when no concrete modal/buttons are present.
|
|
1882
|
+
// Claude TUI flaps between paints; without this guard adapterStatus
|
|
1883
|
+
// could report status=waiting_approval with activeModal=null (or with
|
|
1884
|
+
// an empty buttons array briefly) and we'd still call
|
|
1885
|
+
// resolveModal(-1) — which used to type "1" into the prompt
|
|
1886
|
+
// repeatedly. Skip until a real modal is captured.
|
|
1887
|
+
const buttons = Array.isArray(modal?.buttons)
|
|
1888
|
+
? modal.buttons.map((b: any) => String(b || '').trim()).filter(Boolean)
|
|
1889
|
+
: [];
|
|
1890
|
+
if (!modal || buttons.length === 0) {
|
|
1891
|
+
return autoApproveActive;
|
|
869
1892
|
}
|
|
1893
|
+
// Picker/confirm exclusion (provider-common). A /model or /mode picker is
|
|
1894
|
+
// surfaced with status=waiting_approval so the dashboard shows it, but it
|
|
1895
|
+
// has no "correct" answer to auto-pick — blindly selecting the first
|
|
1896
|
+
// option silently switches the model (the "always Opus, before I even
|
|
1897
|
+
// choose" bug). Two independent gates, BOTH must pass to fire:
|
|
1898
|
+
//
|
|
1899
|
+
// (1) modal_kind — the spec/FSM tells us this is an 'approval' modal,
|
|
1900
|
+
// not a 'picker'/'confirm'. A modal whose kind is unknown (legacy
|
|
1901
|
+
// adapter, or a spec that predates modal_kind) reads as 'approval'
|
|
1902
|
+
// so genuine approvals keep auto-approving; only an explicit
|
|
1903
|
+
// 'picker'/'confirm' is excluded here.
|
|
1904
|
+
// (2) structural anchor — a real approval offers an affirmative AND a
|
|
1905
|
+
// decline option (pickApprovalButton finds a positive that isn't a
|
|
1906
|
+
// decline, and hasNegativeApprovalOption confirms a No/Cancel/Deny
|
|
1907
|
+
// is present). A model picker ("1. Default 2. Opus 3. Sonnet")
|
|
1908
|
+
// has no decline, so even an un-migrated picker is caught here.
|
|
1909
|
+
//
|
|
1910
|
+
// Mirrors the SDK v1 detect-status approval heuristic (detect-status.ts).
|
|
1911
|
+
const modalKind = typeof modal?.kind === 'string' ? modal.kind : 'approval';
|
|
1912
|
+
if (modalKind !== 'approval') {
|
|
1913
|
+
// Picker/confirm — leave it for the user; keep the modal surfaced.
|
|
1914
|
+
return autoApproveActive;
|
|
1915
|
+
}
|
|
1916
|
+
const { index: buttonIndex, label: buttonLabel } = pickApprovalButton(buttons, this.provider);
|
|
1917
|
+
if (buttonIndex < 0 || !hasNegativeApprovalOption(buttons)) {
|
|
1918
|
+
// No affirmative matched, or no decline option present (→ not a real
|
|
1919
|
+
// consent prompt, e.g. a picker that slipped past the kind gate).
|
|
1920
|
+
// Surface the modal so the user decides; never pick blindly.
|
|
1921
|
+
return autoApproveActive;
|
|
1922
|
+
}
|
|
1923
|
+
// Modal *identity* signature — the question/button set only, NO volatile
|
|
1924
|
+
// counters. This is what the settle gate tracks: the FSM bumps
|
|
1925
|
+
// approvalEntrySeq on every fresh waiting_approval entry, and a
|
|
1926
|
+
// modal→generating→modal flap (the question line scrolled out of the
|
|
1927
|
+
// captured frame while the button block stays) re-enters and bumps it
|
|
1928
|
+
// again. Folding that seq into the settle signature made the 600ms
|
|
1929
|
+
// settle clock restart on every flap, so the modal never stayed stable
|
|
1930
|
+
// long enough to fire — the gate was never satisfied. Identity excludes
|
|
1931
|
+
// the seq so button/seq flap of the SAME modal keeps one settle clock.
|
|
1932
|
+
const modalSignature = [
|
|
1933
|
+
typeof modal?.message === 'string' ? modal.message.trim() : '',
|
|
1934
|
+
buttons.join('|'),
|
|
1935
|
+
buttonIndex,
|
|
1936
|
+
].join('::');
|
|
1937
|
+
// Busy-window re-entry guard still needs the seq: two DISTINCT
|
|
1938
|
+
// back-to-back approvals can carry identical message/buttons (common
|
|
1939
|
+
// with claude-cli). Without the seq their busy signatures collide and
|
|
1940
|
+
// the 5s busy-window guard below would swallow the second auto-approve,
|
|
1941
|
+
// leaving it stuck. The seq is bumped by the FSM on every fresh
|
|
1942
|
+
// waiting_approval entry, so a new approval always yields a new busy
|
|
1943
|
+
// signature and fires through.
|
|
1944
|
+
const approvalEntrySeq = typeof adapterStatus?.approvalEntrySeq === 'number'
|
|
1945
|
+
? adapterStatus.approvalEntrySeq
|
|
1946
|
+
: 0;
|
|
1947
|
+
const busySignature = `${approvalEntrySeq}::${modalSignature}`;
|
|
1948
|
+
// Already fired for this exact modal entry and still inside the busy
|
|
1949
|
+
// window — nothing to do (re-entry guard for repeated snapshots of one
|
|
1950
|
+
// modal).
|
|
1951
|
+
if (this.autoApproveBusy && busySignature === this.lastAutoApprovalSignature) {
|
|
1952
|
+
return autoApproveActive;
|
|
1953
|
+
}
|
|
1954
|
+
|
|
1955
|
+
// Settle gate: only fire once this modal identity has been stable for
|
|
1956
|
+
// AUTO_APPROVE_SETTLE_MS. A still-streaming prompt mutates its
|
|
1957
|
+
// message/buttons each frame → new identity → clock restarts, so we
|
|
1958
|
+
// never approve a half-rendered prompt (the "resolves too fast" bug).
|
|
1959
|
+
if (modalSignature !== this.pendingAutoApprovalSignature) {
|
|
1960
|
+
this.pendingAutoApprovalSignature = modalSignature;
|
|
1961
|
+
this.pendingAutoApprovalSince = now;
|
|
1962
|
+
}
|
|
1963
|
+
const settledForMs = now - this.pendingAutoApprovalSince;
|
|
1964
|
+
if (settledForMs < CliProviderInstance.AUTO_APPROVE_SETTLE_MS) {
|
|
1965
|
+
// Not yet settled. Arm a timer to re-check after the remaining quiet
|
|
1966
|
+
// window — the PTY may go silent once the prompt finishes painting,
|
|
1967
|
+
// so there is no guaranteed status-change frame to re-drive us.
|
|
1968
|
+
if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
|
|
1969
|
+
this.autoApproveSettleTimer = setTimeout(() => {
|
|
1970
|
+
this.autoApproveSettleTimer = null;
|
|
1971
|
+
this.recheckAutoApproveSettled();
|
|
1972
|
+
}, CliProviderInstance.AUTO_APPROVE_SETTLE_MS - settledForMs + 20);
|
|
1973
|
+
return autoApproveActive;
|
|
1974
|
+
}
|
|
1975
|
+
|
|
1976
|
+
// Settled — fire the approve key.
|
|
1977
|
+
if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
|
|
1978
|
+
this.autoApproveBusy = true;
|
|
1979
|
+
this.lastAutoApprovalSignature = busySignature;
|
|
1980
|
+
this.pendingAutoApprovalSignature = '';
|
|
1981
|
+
this.pendingAutoApprovalSince = 0;
|
|
1982
|
+
this.autoApproveInactiveSince = 0;
|
|
1983
|
+
// Fired (resolveModal in flight) — the episode resolved; end the mask-stall clock.
|
|
1984
|
+
this.autoApproveMaskSince = 0;
|
|
1985
|
+
if (this.autoApproveBusyTimer) clearTimeout(this.autoApproveBusyTimer);
|
|
1986
|
+
this.autoApproveBusyTimer = setTimeout(() => {
|
|
1987
|
+
this.autoApproveBusy = false;
|
|
1988
|
+
this.autoApproveBusyTimer = null;
|
|
1989
|
+
this.lastAutoApprovalSignature = '';
|
|
1990
|
+
}, 5000);
|
|
1991
|
+
this.recordAutoApproval(modal?.message, buttonLabel, now);
|
|
1992
|
+
setTimeout(() => {
|
|
1993
|
+
this.adapter.resolveModal(buttonIndex);
|
|
1994
|
+
}, 0);
|
|
870
1995
|
return autoApproveActive;
|
|
871
1996
|
}
|
|
872
1997
|
|
|
1998
|
+
/**
|
|
1999
|
+
* Re-drive the auto-approve check after the settle quiet window elapses.
|
|
2000
|
+
* The PTY may have gone silent once the approval prompt finished painting,
|
|
2001
|
+
* so no status-change frame is guaranteed to re-enter maybeAutoApproveStatus
|
|
2002
|
+
* — this timer-driven re-check picks up the now-settled modal and fires.
|
|
2003
|
+
* Deliberately lighter than detectStatusTransition(): it only re-evaluates
|
|
2004
|
+
* the approval decision; the next real PTY frame refreshes visible status.
|
|
2005
|
+
*/
|
|
2006
|
+
private recheckAutoApproveSettled(): void {
|
|
2007
|
+
try {
|
|
2008
|
+
const adapterStatus = this.adapter.getStatus({ allowParse: false });
|
|
2009
|
+
this.maybeAutoApproveStatus(adapterStatus, Date.now());
|
|
2010
|
+
} catch { /* adapter gone / transient — next frame retries */ }
|
|
2011
|
+
}
|
|
2012
|
+
|
|
2013
|
+
/**
|
|
2014
|
+
* Emit the queue-claim agent:ready event at most once per session. Both the
|
|
2015
|
+
* boot-time starting→idle one-shot and the fsmReadySeen re-arm call this; the
|
|
2016
|
+
* agentReadyEmitted guard ensures the second caller is a no-op so a worker is
|
|
2017
|
+
* never claimed twice and a queued task is never double-dispatched.
|
|
2018
|
+
*/
|
|
2019
|
+
private emitAgentReadyOnce(chatTitle: string, now: number): void {
|
|
2020
|
+
if (this.agentReadyEmitted) return;
|
|
2021
|
+
this.agentReadyEmitted = true;
|
|
2022
|
+
this.pushEvent({ event: 'agent:ready', chatTitle, timestamp: now });
|
|
2023
|
+
}
|
|
2024
|
+
|
|
873
2025
|
private detectStatusTransition(): void {
|
|
874
2026
|
const now = Date.now();
|
|
875
2027
|
// Status-change handling is a hot path: PTY output can fire it many times
|
|
876
2028
|
// during long-running CLI sessions. Keep this path on adapter-owned light
|
|
877
2029
|
// state only; rich provider parsing is reserved for getState/read_chat.
|
|
878
2030
|
const adapterStatus = this.adapter.getStatus({ allowParse: false });
|
|
2031
|
+
const adapterProviderSessionId = normalizeProviderSessionId(
|
|
2032
|
+
this.provider,
|
|
2033
|
+
typeof adapterStatus?.providerSessionId === 'string' ? adapterStatus.providerSessionId : '',
|
|
2034
|
+
);
|
|
2035
|
+
if (adapterProviderSessionId) {
|
|
2036
|
+
this.promoteProviderSessionId(adapterProviderSessionId);
|
|
2037
|
+
}
|
|
879
2038
|
const parsedStatus = null;
|
|
880
2039
|
const rawStatus = adapterStatus.status;
|
|
881
2040
|
const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, now);
|
|
882
|
-
|
|
883
|
-
|
|
2041
|
+
// During the autoApproveBusy window (2s after firing approval key), the PTY
|
|
2042
|
+
// can briefly report 'idle' before the next generating phase starts. Treat that
|
|
2043
|
+
// transient idle as 'generating' to suppress a spurious agent:generating_completed
|
|
2044
|
+
// push notification. The adapter's status is otherwise authoritative — native
|
|
2045
|
+
// transcript shape does NOT override the FSM's busy/idle decision.
|
|
2046
|
+
const autoApproveHoldIdle = this.autoApproveBusy && rawStatus === 'idle';
|
|
2047
|
+
const newStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : rawStatus;
|
|
2048
|
+
const dirName = workingDirBasename(this.workingDir);
|
|
884
2049
|
const chatTitle = `${this.provider.name} · ${dirName}`;
|
|
885
2050
|
const partial = this.adapter.getPartialResponse();
|
|
2051
|
+
// Liveness fingerprint for the no-progress watchdog. The parsed
|
|
2052
|
+
// assistant buffer (`partial`) alone goes static while a tool/build runs
|
|
2053
|
+
// — the assistant emits no tokens even though the PTY is actively
|
|
2054
|
+
// printing tool output — which made the watchdog false-fire a "stuck"
|
|
2055
|
+
// alert mid-turn. Fold in the adapter's raw-activity timestamps so any
|
|
2056
|
+
// visible terminal progress (lastScreenChangeAt) or raw PTY byte
|
|
2057
|
+
// (lastOutputAt) keeps the fingerprint moving. The watchdog then only
|
|
2058
|
+
// survives a genuine stall where nothing at all is happening.
|
|
886
2059
|
const progressFingerprint = newStatus === 'generating'
|
|
887
|
-
? `${partial || ''}`.slice(-2000)
|
|
2060
|
+
? `${`${partial || ''}`.slice(-2000)}::scr=${adapterStatus.lastScreenChangeAt ?? 0}::out=${adapterStatus.lastOutputAt ?? 0}`
|
|
888
2061
|
: undefined;
|
|
889
2062
|
|
|
890
2063
|
const previousStatus = this.lastStatus;
|
|
891
2064
|
if (newStatus !== this.lastStatus) {
|
|
892
2065
|
LOG.info('CLI', `[${this.type}] status: ${this.lastStatus} → ${newStatus}`);
|
|
893
|
-
|
|
2066
|
+
// GENERATING-MISSING (win32 fresh-worktree first-turn): a freshly-launched session
|
|
2067
|
+
// is in 'starting' until its startup-grace settles to idle. When the FIRST inject
|
|
2068
|
+
// lands inside that grace window, the adapter can report status DIRECTLY
|
|
2069
|
+
// starting → generating without an intervening 'idle' frame for
|
|
2070
|
+
// detectStatusTransition() to observe. Previously only the idle→generating arm
|
|
2071
|
+
// armed the bookkeeping, so a starting→generating frame fell straight through to the
|
|
2072
|
+
// bare `this.lastStatus = newStatus` update: generatingStartedAt stayed 0 and no
|
|
2073
|
+
// generating_started was queued. The fast turn's generating→idle completion was then
|
|
2074
|
+
// suppressed by the startup-blip guard below (generatingStartedAt===0 &&
|
|
2075
|
+
// !generatingDebouncePending) — so NO generating_started AND NO generating_completed
|
|
2076
|
+
// ever fired and the mesh coordinator never learned the worker went idle.
|
|
2077
|
+
//
|
|
2078
|
+
// We extend the idle→generating arm to also fire on starting→generating, BUT ONLY
|
|
2079
|
+
// when a real turn is in flight. The adapter script can also report 'generating' from
|
|
2080
|
+
// pure startup PTY noise (no task dispatched) — antigravity/codex/hermes-cli all
|
|
2081
|
+
// exercise that benign starting→generating→idle blip, which must NOT emit a
|
|
2082
|
+
// completion (see "startup-phase spurious completion suppression" tests).
|
|
2083
|
+
// hasAdapterPendingResponse() is the discriminator: a genuine inject sets the
|
|
2084
|
+
// adapter's isWaitingForResponse / currentTurnScope (or leaves a partial response),
|
|
2085
|
+
// whereas startup repaint noise leaves all of them empty. So an armed
|
|
2086
|
+
// starting→generating means "the worker actually started its first turn", and a
|
|
2087
|
+
// bare one stays a suppressed blip via the existing fall-through.
|
|
2088
|
+
const startingToGeneratingWithActiveTurn = this.lastStatus === 'starting'
|
|
2089
|
+
&& newStatus === 'generating'
|
|
2090
|
+
&& this.hasAdapterPendingResponse();
|
|
2091
|
+
if (((this.lastStatus === 'idle' && newStatus === 'generating') || startingToGeneratingWithActiveTurn)) {
|
|
2092
|
+
// If a completion event is already pending and the turn has ended
|
|
2093
|
+
// (generatingStartedAt===0), the PTY is painting its prompt area
|
|
2094
|
+
// after completing. Ignore this blip — do not cancel the pending
|
|
2095
|
+
// completion and do not advance lastStatus to generating. (On a true
|
|
2096
|
+
// starting→generating the session is fresh: completedDebouncePending is
|
|
2097
|
+
// null, so this blip guard is a no-op and we arm normally below.)
|
|
2098
|
+
if (this.completedDebouncePending && this.generatingStartedAt === 0) {
|
|
2099
|
+
LOG.debug('CLI', `[${this.type}] ignoring post-completion PTY generating blip (generatingStartedAt=0)`);
|
|
2100
|
+
return;
|
|
2101
|
+
}
|
|
894
2102
|
this.suppressIdleHistoryReplay = false;
|
|
895
2103
|
// Cancel any pending completed event (multi-step: idle→generating resume)
|
|
896
2104
|
if (this.completedDebouncePending) {
|
|
897
|
-
LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed generating)`);
|
|
2105
|
+
LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed generating) generatingStartedAt=${this.generatingStartedAt} isWaitingForResponse=${!!(this.adapter as any)?.isWaitingForResponse}`);
|
|
898
2106
|
if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
|
|
899
2107
|
this.completedDebouncePending = null;
|
|
900
2108
|
}
|
|
@@ -926,10 +2134,29 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
926
2134
|
if (!this.generatingStartedAt) this.generatingStartedAt = now;
|
|
927
2135
|
const modal = adapterStatus.activeModal;
|
|
928
2136
|
LOG.info('CLI', `[${this.type}] approval modal: "${modal?.message?.slice(0, 80) ?? 'none'}"`);
|
|
929
|
-
//
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
2137
|
+
// Include the FSM's approval entry seq, mirroring the auto-approve
|
|
2138
|
+
// path (maybeAutoApproveStatus) and resolveModal's sameEntryReResolve
|
|
2139
|
+
// guard. Two distinct back-to-back approvals can carry identical
|
|
2140
|
+
// message/buttons (very common with claude-cli's "Allow Bash
|
|
2141
|
+
// command?"). Without the seq their fingerprints collide and the dedup
|
|
2142
|
+
// below silently drops the second waiting_approval event — it is never
|
|
2143
|
+
// emitted, so it cannot even land in the pending inbox for a later
|
|
2144
|
+
// read_chat reconcile to recover. The seq is bumped by the FSM on every
|
|
2145
|
+
// fresh waiting_approval entry, so a new approval always yields a new
|
|
2146
|
+
// fingerprint and emits.
|
|
2147
|
+
const approvalEntrySeq = typeof adapterStatus?.approvalEntrySeq === 'number'
|
|
2148
|
+
? adapterStatus.approvalEntrySeq
|
|
2149
|
+
: 0;
|
|
2150
|
+
const approvalFingerprint = JSON.stringify({
|
|
2151
|
+
message: typeof modal?.message === 'string' ? modal.message.trim() : '',
|
|
2152
|
+
buttons: Array.isArray(modal?.buttons) ? modal.buttons.map((button: unknown) => String(button).trim()) : [],
|
|
2153
|
+
seq: approvalEntrySeq,
|
|
2154
|
+
});
|
|
2155
|
+
// PTY redraws repeat the same modal content; fingerprint dedup prevents duplicate events.
|
|
2156
|
+
// Do NOT also gate on lastStatus: consecutive approvals can arrive waiting_approval→waiting_approval
|
|
2157
|
+
// (e.g. antigravity-cli resolves one prompt and immediately shows the next) and would be silently dropped.
|
|
2158
|
+
if (approvalFingerprint !== this.lastApprovalEventFingerprint) {
|
|
2159
|
+
this.lastApprovalEventFingerprint = approvalFingerprint;
|
|
933
2160
|
this.appendRuntimeSystemMessage(
|
|
934
2161
|
this.formatApprovalRequestMessage(modal?.message, modal?.buttons),
|
|
935
2162
|
`approval_request:${now}`,
|
|
@@ -941,22 +2168,131 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
941
2168
|
modalButtons: modal?.buttons,
|
|
942
2169
|
});
|
|
943
2170
|
}
|
|
2171
|
+
} else if (newStatus === 'generating' && this.lastStatus === 'waiting_approval') {
|
|
2172
|
+
// Approval resolved and the agent resumed work. Defense-in-depth:
|
|
2173
|
+
// clear the approval emit fingerprint here too (not only on
|
|
2174
|
+
// completion at scheduleCompletedDebounceFlush). A subsequent
|
|
2175
|
+
// waiting_approval with the same modal content as the one just
|
|
2176
|
+
// resolved would otherwise collide with the stale fingerprint and be
|
|
2177
|
+
// dropped. The seq in the fingerprint already separates entries; this
|
|
2178
|
+
// reset is a belt-and-suspenders guard for the re-entry case.
|
|
2179
|
+
this.lastApprovalEventFingerprint = '';
|
|
944
2180
|
} else if (newStatus === 'idle' && (this.lastStatus === 'generating' || this.lastStatus === 'waiting_approval')) {
|
|
945
2181
|
const duration = this.generatingStartedAt ? Math.round((now - this.generatingStartedAt) / 1000) : 0;
|
|
946
|
-
//
|
|
2182
|
+
// Guard: if generatingStartedAt===0 and no debounce pending, the generating phase
|
|
2183
|
+
// was entered from 'starting' state (startup PTY noise), not from a real idle→generating
|
|
2184
|
+
// task dispatch. The idle→generating handler is the only code path that sets
|
|
2185
|
+
// generatingStartedAt and generatingDebouncePending, so both being absent means no
|
|
2186
|
+
// task was ever dispatched. Suppress the spurious completion event and fall through
|
|
2187
|
+
// to a simple lastStatus update.
|
|
2188
|
+
if (!this.generatingStartedAt && !this.generatingDebouncePending) {
|
|
2189
|
+
LOG.debug('CLI', `[${this.type}] suppressed startup-phase generating→idle blip (generatingStartedAt=0, no debounce pending)`);
|
|
2190
|
+
} else
|
|
2191
|
+
// If debounce still pending (generating lasted < 1s), cancel both UI events.
|
|
2192
|
+
// Still emit agent:generating_completed so mesh orchestration can record
|
|
2193
|
+
// task_completed for direct dispatches that complete faster than the debounce.
|
|
947
2194
|
if (this.generatingDebouncePending) {
|
|
948
|
-
|
|
2195
|
+
const shortDurationMs = this.generatingStartedAt ? now - this.generatingStartedAt : 0;
|
|
2196
|
+
LOG.info('CLI', `[${this.type}] suppressed short generating (${shortDurationMs}ms)`);
|
|
949
2197
|
if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
|
|
2198
|
+
// Emit completion for mesh task association even though the UI generating
|
|
2199
|
+
// started/completed pair is suppressed (too short for visible UI update).
|
|
2200
|
+
let shortFinalSummary: string | undefined;
|
|
2201
|
+
let shortEvidenceSource: CompletionFinalAssistantEvidence['source'] = 'unavailable';
|
|
2202
|
+
try {
|
|
2203
|
+
const parsedMessages = this.adapter?.getScriptParsedStatus()?.messages;
|
|
2204
|
+
const evidence = this.completionFinalAssistantEvidence(parsedMessages);
|
|
2205
|
+
shortEvidenceSource = evidence.source;
|
|
2206
|
+
shortFinalSummary = extractFinalSummaryFromMessages(evidence.messages as any);
|
|
2207
|
+
} catch { /* best-effort */ }
|
|
2208
|
+
// If a real response is confirmed, retroactively emit started so the chat
|
|
2209
|
+
// bubble appears even though the debounce suppressed the original event.
|
|
2210
|
+
if (shortFinalSummary) {
|
|
2211
|
+
this.pushEvent({ event: 'agent:generating_started', chatTitle, timestamp: now - shortDurationMs });
|
|
2212
|
+
}
|
|
950
2213
|
this.generatingDebouncePending = null;
|
|
951
2214
|
this.generatingStartedAt = 0;
|
|
2215
|
+
const missingEvidence = ((this.provider as any).requiresFinalAssistantBeforeIdle === true || shortEvidenceSource === 'external-native') && !shortFinalSummary;
|
|
2216
|
+
if (missingEvidence) {
|
|
2217
|
+
LOG.warn('CLI', `[${this.type}] short completion missing final assistant evidence (source=${shortEvidenceSource})`);
|
|
2218
|
+
}
|
|
2219
|
+
// When evidence is missing and there is no active mesh task context, suppress
|
|
2220
|
+
// the completion event. Providers with requiresFinalAssistantBeforeIdle or
|
|
2221
|
+
// external-native history must confirm a final assistant message before the
|
|
2222
|
+
// coordinator records task_completed. Only emit here if a mesh task is active
|
|
2223
|
+
// so the coordinator can apply its own timeout/retry logic.
|
|
2224
|
+
const hasMeshContext = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
|
|
2225
|
+
if (missingEvidence && !hasMeshContext) {
|
|
2226
|
+
LOG.info('CLI', `[${this.type}] short completion suppressed: missing final assistant evidence, no mesh context (source=${shortEvidenceSource})`);
|
|
2227
|
+
// completedDebouncePending intentionally left null — the session is now idle
|
|
2228
|
+
// with no confirmed turn, matching the startup-blip suppression semantics.
|
|
2229
|
+
// (No EvtTrace: not a mesh session, so nothing routes to a coordinator.)
|
|
2230
|
+
} else {
|
|
2231
|
+
// EVTTRACE: completion fired (short-generating idle path).
|
|
2232
|
+
if (this.isMeshWorkerSession()) {
|
|
2233
|
+
traceMeshEventStage('fired', this.meshTraceCtx(), `short-generating idle (source=${shortEvidenceSource})`);
|
|
2234
|
+
}
|
|
2235
|
+
this.pushEvent({
|
|
2236
|
+
event: 'agent:generating_completed',
|
|
2237
|
+
chatTitle,
|
|
2238
|
+
duration: 0,
|
|
2239
|
+
timestamp: now,
|
|
2240
|
+
finalSummary: shortFinalSummary,
|
|
2241
|
+
completionDiagnostic: {
|
|
2242
|
+
reason: 'short_generating_suppressed',
|
|
2243
|
+
shortDurationMs,
|
|
2244
|
+
finalAssistantEvidenceSource: shortEvidenceSource,
|
|
2245
|
+
...(missingEvidence ? { blockReason: 'missing_final_assistant' } : {}),
|
|
2246
|
+
},
|
|
2247
|
+
});
|
|
2248
|
+
}
|
|
952
2249
|
} else {
|
|
953
2250
|
// Debounce completed, then require the rich transcript path that read_chat
|
|
954
2251
|
// uses to show an idle turn whose last user-facing message is assistant.
|
|
955
|
-
this.completedDebouncePending = {
|
|
956
|
-
|
|
2252
|
+
this.completedDebouncePending = {
|
|
2253
|
+
chatTitle,
|
|
2254
|
+
duration,
|
|
2255
|
+
timestamp: now,
|
|
2256
|
+
firstObservedAt: now,
|
|
2257
|
+
previousStatus: this.lastStatus,
|
|
2258
|
+
// ARCH-REFACTOR R1: snapshot the completing turn's taskId NOW (sync),
|
|
2259
|
+
// before any follow-up task's flush can start a new turn and move
|
|
2260
|
+
// engine.currentTurnTaskId.
|
|
2261
|
+
...(this.completingTurnTaskId() ? { taskId: this.completingTurnTaskId() } : {}),
|
|
2262
|
+
};
|
|
2263
|
+
const ownsExternalHistory = !!(this.adapter as any)?.chatMessagesOwnedExternally;
|
|
2264
|
+
// (FALSEIDLE-BGCHILD-a) Native-history providers flush immediately (the
|
|
2265
|
+
// transcript is authoritative). For mesh worker sessions, give the
|
|
2266
|
+
// generating→idle transition a short settle window so a background-child
|
|
2267
|
+
// false idle (quiet after a backgrounded test/command while the parent turn
|
|
2268
|
+
// continues) gets caught by the resume guard in flushCompletedDebounceIfFinalized
|
|
2269
|
+
// instead of firing an early completion the coordinator can never correct.
|
|
2270
|
+
const meshWorkerSession = this.isMeshWorkerSession();
|
|
2271
|
+
const flushDelay = ownsExternalHistory
|
|
2272
|
+
? (meshWorkerSession ? NATIVE_HISTORY_MESH_IDLE_SETTLE_MS : 0)
|
|
2273
|
+
: 3000;
|
|
2274
|
+
LOG.debug('CLI', `[${this.type}] set completedDebouncePending duration=${duration}s ownsExternalHistory=${ownsExternalHistory} meshWorker=${meshWorkerSession} flushDelay=${flushDelay}ms generatingStartedAt=${this.generatingStartedAt}`);
|
|
2275
|
+
this.scheduleCompletedDebounceFlush(flushDelay);
|
|
957
2276
|
}
|
|
958
2277
|
} else if (newStatus === 'idle' && this.lastStatus === 'starting') {
|
|
959
|
-
this.
|
|
2278
|
+
this.emitAgentReadyOnce(chatTitle, now);
|
|
2279
|
+
} else if (newStatus === 'error') {
|
|
2280
|
+
if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
|
|
2281
|
+
this.generatingDebouncePending = null;
|
|
2282
|
+
if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
|
|
2283
|
+
this.completedDebouncePending = null;
|
|
2284
|
+
this.errorMessage = adapterStatus.errorMessage || this.errorMessage;
|
|
2285
|
+
this.errorReason = (adapterStatus.errorReason as ProviderErrorReason) || this.errorReason;
|
|
2286
|
+
this.pushEvent({
|
|
2287
|
+
event: 'agent:stopped',
|
|
2288
|
+
chatTitle,
|
|
2289
|
+
timestamp: now,
|
|
2290
|
+
finalSummary: adapterStatus.errorMessage || adapterStatus.errorReason || 'Provider reported an error',
|
|
2291
|
+
completionDiagnostic: {
|
|
2292
|
+
reason: adapterStatus.errorReason || 'provider_error',
|
|
2293
|
+
errorMessage: adapterStatus.errorMessage || undefined,
|
|
2294
|
+
},
|
|
2295
|
+
});
|
|
960
2296
|
} else if (newStatus === 'stopped') {
|
|
961
2297
|
// Cancel any pending debounce
|
|
962
2298
|
if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
|
|
@@ -968,6 +2304,28 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
968
2304
|
this.lastStatus = newStatus;
|
|
969
2305
|
}
|
|
970
2306
|
|
|
2307
|
+
// Re-arm the queue-claim agent:ready on the FSM's first GENUINE ready.
|
|
2308
|
+
//
|
|
2309
|
+
// The boot-time starting→idle one-shot above is the historical claim
|
|
2310
|
+
// trigger, but it is consumed too early for FSM-spec providers whose
|
|
2311
|
+
// INITIAL state already reports status 'idle' (e.g. antigravity-cli): the
|
|
2312
|
+
// adapter reports idle before maybeMarkReady has fired, so lastStatus
|
|
2313
|
+
// advances starting→idle while the prompt is not yet drawn and the worker
|
|
2314
|
+
// cannot yet claim. Subsequent state-driven idle frames are idle→idle (no
|
|
2315
|
+
// status change), so the one-shot never re-fires and the worker strands its
|
|
2316
|
+
// queued task — the coordinator then relaunch-loops every ~90s.
|
|
2317
|
+
//
|
|
2318
|
+
// The adapter surfaces fsmReadySeen=true exactly when the FSM reaches its
|
|
2319
|
+
// first non-initial idle (the prompt is genuinely up). On that signal we
|
|
2320
|
+
// emit agent:ready once more. emitAgentReadyOnce is idempotent (guarded by
|
|
2321
|
+
// agentReadyEmitted), so providers whose boot one-shot already landed on a
|
|
2322
|
+
// real ready (claude-cli / codex-cli / hermes-cli, which use a startup
|
|
2323
|
+
// grace and whose initial state is not idle) treat this as a no-op — no
|
|
2324
|
+
// double claim, no double task injection.
|
|
2325
|
+
if (newStatus === 'idle' && adapterStatus.fsmReadySeen === true && !this.agentReadyEmitted) {
|
|
2326
|
+
this.emitAgentReadyOnce(chatTitle, now);
|
|
2327
|
+
}
|
|
2328
|
+
|
|
971
2329
|
this.applyProviderResponse(parsedStatus, {
|
|
972
2330
|
phase: (newStatus === 'idle' && (previousStatus === 'generating' || previousStatus === 'waiting_approval'))
|
|
973
2331
|
? 'turn_completed'
|
|
@@ -976,8 +2334,43 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
976
2334
|
|
|
977
2335
|
// Monitor check (cooldown based notification, IDE/CLI common)
|
|
978
2336
|
const agentKey = `${this.type}:cli`;
|
|
979
|
-
|
|
2337
|
+
// Approval pending is detected from the raw adapter status, not `newStatus`:
|
|
2338
|
+
// auto-approve synthesizes `waiting_approval` → 'generating', which would
|
|
2339
|
+
// otherwise let the no-progress watchdog accumulate the approval wait.
|
|
2340
|
+
const approvalPending = rawStatus === 'waiting_approval';
|
|
2341
|
+
const monitorEvents = this.monitor.check(agentKey, newStatus, now, progressFingerprint, approvalPending);
|
|
2342
|
+
const monitorParsedStatus: any = parsedStatus;
|
|
980
2343
|
for (const me of monitorEvents) {
|
|
2344
|
+
if (
|
|
2345
|
+
me.type === 'monitor:no_progress'
|
|
2346
|
+
&& this.completionHasFinalAssistantMessage(monitorParsedStatus?.messages)
|
|
2347
|
+
&& !this.hasAdapterPendingResponse()
|
|
2348
|
+
&& !hasNonEmptyCliModalButtons(monitorParsedStatus?.activeModal ?? monitorParsedStatus?.modal)
|
|
2349
|
+
) {
|
|
2350
|
+
// EVTTRACE: completion fired (no-progress monitor reconciled to completion).
|
|
2351
|
+
if (this.isMeshWorkerSession()) {
|
|
2352
|
+
traceMeshEventStage('fired', this.meshTraceCtx(), 'no_progress_monitor_final_summary');
|
|
2353
|
+
}
|
|
2354
|
+
this.pushEvent({
|
|
2355
|
+
event: 'agent:generating_completed',
|
|
2356
|
+
chatTitle,
|
|
2357
|
+
duration: this.generatingStartedAt ? Math.round((now - this.generatingStartedAt) / 1000) : undefined,
|
|
2358
|
+
timestamp: me.timestamp,
|
|
2359
|
+
finalSummary: extractFinalSummaryFromMessages(monitorParsedStatus?.messages),
|
|
2360
|
+
completionDiagnostic: {
|
|
2361
|
+
providerType: this.type,
|
|
2362
|
+
sessionId: this.instanceId,
|
|
2363
|
+
providerSessionId: this.providerSessionId || null,
|
|
2364
|
+
reconciliationReason: 'no_progress_monitor_final_summary',
|
|
2365
|
+
finalAssistantPresent: true,
|
|
2366
|
+
},
|
|
2367
|
+
});
|
|
2368
|
+
this.generatingStartedAt = 0;
|
|
2369
|
+
// Cancel any pending debounce flush — monitor already fired completion.
|
|
2370
|
+
if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
|
|
2371
|
+
this.completedDebouncePending = null;
|
|
2372
|
+
continue;
|
|
2373
|
+
}
|
|
981
2374
|
this.pushEvent({ event: me.type, agentKey: me.agentKey, message: me.message, elapsedSec: me.elapsedSec, timestamp: me.timestamp });
|
|
982
2375
|
}
|
|
983
2376
|
}
|
|
@@ -997,15 +2390,61 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
997
2390
|
workspaceName: typeof event.workspaceName === 'string' && event.workspaceName.trim()
|
|
998
2391
|
? event.workspaceName
|
|
999
2392
|
: this.workingDir,
|
|
2393
|
+
// Carry the workspace under BOTH `workspace` and `workspaceName` so the
|
|
2394
|
+
// downstream mesh forward/merge path — which reads `workspace` — can
|
|
2395
|
+
// propagate it to the coordinator snapshot. Without `workspace` the live
|
|
2396
|
+
// event path delivers an empty workspace and the dashboard falls back to
|
|
2397
|
+
// the generic "Terminal (Mesh Node)" title.
|
|
2398
|
+
workspace: typeof event.workspace === 'string' && event.workspace.trim()
|
|
2399
|
+
? event.workspace
|
|
2400
|
+
: this.workingDir,
|
|
1000
2401
|
providerSessionId: typeof event.providerSessionId === 'string' && event.providerSessionId.trim()
|
|
1001
2402
|
? event.providerSessionId
|
|
1002
2403
|
: this.providerSessionId,
|
|
1003
2404
|
};
|
|
2405
|
+
// TASKIDLESS: stamp the mesh task primary key on lifecycle events emitted by
|
|
2406
|
+
// a mesh worker session. The consumer (updateDirectDispatchStatus) was switched
|
|
2407
|
+
// to key on task_id (CANON-B), but the producer never carried it — so every
|
|
2408
|
+
// forwarded metadataEvent.taskId arrived undefined and the coordinator fell back
|
|
2409
|
+
// to a session_id match, which can flip a sibling dispatch row. Surface it here so
|
|
2410
|
+
// updateDirectDispatchStatus hits the exact PK row and the session_id fallback is
|
|
2411
|
+
// never exercised. Non-mesh sessions get no taskId (regression guard) —
|
|
2412
|
+
// isMeshWorkerSession() gates the injection.
|
|
2413
|
+
//
|
|
2414
|
+
// ARCH-REFACTOR R1 (per-turn identity): resolution order is
|
|
2415
|
+
// (1) an explicit taskId already on the event — the debounce-flush completion
|
|
2416
|
+
// path stamps the taskId captured at the generating→idle transition (the
|
|
2417
|
+
// turn that actually produced this completion);
|
|
2418
|
+
// (2) the per-turn binding (engine.currentTurnTaskId) for synchronously-emitted
|
|
2419
|
+
// events whose turn is still the current one;
|
|
2420
|
+
// (3) the legacy session scalar (settings.meshActiveTaskId) as a last-resort
|
|
2421
|
+
// backward-compat alias.
|
|
2422
|
+
// The scalar is last because it is last-write-wins: a second task attaching while
|
|
2423
|
+
// this turn was still running overwrites it, which is the exact NOTIF-MISDELIVER /
|
|
2424
|
+
// TASK-MSG-MISROUTE race this refactor removes.
|
|
2425
|
+
if (this.isMeshWorkerSession()) {
|
|
2426
|
+
const existingTaskId = typeof enrichedEvent.taskId === 'string' && enrichedEvent.taskId.trim()
|
|
2427
|
+
? enrichedEvent.taskId
|
|
2428
|
+
: undefined;
|
|
2429
|
+
if (!existingTaskId) {
|
|
2430
|
+
const resolved = this.completingTurnTaskId();
|
|
2431
|
+
if (resolved) enrichedEvent.taskId = resolved;
|
|
2432
|
+
}
|
|
2433
|
+
}
|
|
1004
2434
|
if (this.context?.emitProviderEvent) {
|
|
1005
2435
|
this.context.emitProviderEvent(enrichedEvent);
|
|
1006
|
-
|
|
2436
|
+
} else {
|
|
2437
|
+
this.events.push(enrichedEvent);
|
|
2438
|
+
}
|
|
2439
|
+
// Auto-detach a direct-dispatch mesh assignment once the dispatched
|
|
2440
|
+
// task reaches a terminal state. Leaving meshNodeFor pinned would
|
|
2441
|
+
// route this session's next unrelated turn (a dashboard chat) into
|
|
2442
|
+
// the coordinator as if it were the completion of another task.
|
|
2443
|
+
// We schedule after the emit so the originating coordinator still
|
|
2444
|
+
// observes the completion event with its routing marker intact.
|
|
2445
|
+
if (TERMINAL_MESH_EVENTS.has(event.event) && this.settings.meshActiveTaskId) {
|
|
2446
|
+
try { this.detachMeshAssignment(); } catch { /* best-effort */ }
|
|
1007
2447
|
}
|
|
1008
|
-
this.events.push(enrichedEvent);
|
|
1009
2448
|
}
|
|
1010
2449
|
|
|
1011
2450
|
private flushEvents(): ProviderEvent[] {
|
|
@@ -1151,6 +2590,37 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
1151
2590
|
return false;
|
|
1152
2591
|
}
|
|
1153
2592
|
|
|
2593
|
+
/** @see ProviderInstance.noteManualInteraction */
|
|
2594
|
+
noteManualInteraction(now = Date.now()): void {
|
|
2595
|
+
this.manualAttendance.note(now);
|
|
2596
|
+
}
|
|
2597
|
+
|
|
2598
|
+
/**
|
|
2599
|
+
* Whether auto-approve should be treated as active *right now* for display
|
|
2600
|
+
* and firing decisions: the configured intent AND the user is not currently
|
|
2601
|
+
* attending this session by hand. When a human is attending, auto-approve is
|
|
2602
|
+
* held so the modal stays visible and they can drive it via the controlbar.
|
|
2603
|
+
* Provider-agnostic — the attendance signal is the command set, never any
|
|
2604
|
+
* CLI-specific modal text.
|
|
2605
|
+
*/
|
|
2606
|
+
private autoApproveEffectivelyActive(status: string | undefined, now = Date.now()): boolean {
|
|
2607
|
+
return status === 'waiting_approval'
|
|
2608
|
+
&& this.shouldAutoApprove()
|
|
2609
|
+
&& !this.manualAttendance.isAttended(now);
|
|
2610
|
+
}
|
|
2611
|
+
|
|
2612
|
+
// STATUS-MISMATCH: true once the current auto-approve episode has been masking
|
|
2613
|
+
// waiting_approval behind `generating` for longer than AUTO_APPROVE_MASK_STALL_MS without
|
|
2614
|
+
// resolving (the settle gate never fired). When stalled, the surface mask must be dropped
|
|
2615
|
+
// so read_chat / mesh_status / the dashboard see the real waiting_approval + modal (and a
|
|
2616
|
+
// coordinator can mesh_approve it). autoApproveMaskSince is maintained by
|
|
2617
|
+
// maybeAutoApproveStatus (driven by getState + the recheck timer during a waiting episode);
|
|
2618
|
+
// this read is side-effect-free so getStatusMetadata can consult it too.
|
|
2619
|
+
private autoApproveMaskStalled(now = Date.now()): boolean {
|
|
2620
|
+
return this.autoApproveMaskSince > 0
|
|
2621
|
+
&& now - this.autoApproveMaskSince > CliProviderInstance.AUTO_APPROVE_MASK_STALL_MS;
|
|
2622
|
+
}
|
|
2623
|
+
|
|
1154
2624
|
private recordAutoApproval(modalMessage?: string, buttonLabel?: string, now = Date.now()): void {
|
|
1155
2625
|
this.appendRuntimeSystemMessage(
|
|
1156
2626
|
formatAutoApprovalMessage(modalMessage, buttonLabel),
|
|
@@ -1238,7 +2708,7 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
1238
2708
|
receivedAt: normalizedMessage.receivedAt || normalizedMessage.timestamp,
|
|
1239
2709
|
historyDedupKey: dedupKey,
|
|
1240
2710
|
}],
|
|
1241
|
-
this.adapter.getScriptParsedStatus?.()?.title || this.workingDir
|
|
2711
|
+
this.adapter.getScriptParsedStatus?.()?.title || workingDirBasename(this.workingDir),
|
|
1242
2712
|
this.instanceId,
|
|
1243
2713
|
this.providerSessionId,
|
|
1244
2714
|
);
|
|
@@ -1258,12 +2728,28 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
1258
2728
|
index,
|
|
1259
2729
|
source: 'parsed',
|
|
1260
2730
|
}));
|
|
2731
|
+
const getRole = (message: ChatMessage): string => typeof message.role === 'string'
|
|
2732
|
+
? message.role.trim().toLowerCase()
|
|
2733
|
+
: '';
|
|
1261
2734
|
const runtimeEntries: MergeEntry[] = this.runtimeMessages.map((entry, index) => ({
|
|
1262
2735
|
message: entry.message,
|
|
1263
2736
|
index: parsedMessages.length + index,
|
|
1264
|
-
source: 'runtime',
|
|
2737
|
+
source: 'runtime' as const,
|
|
1265
2738
|
runtimeKey: entry.key,
|
|
1266
|
-
}))
|
|
2739
|
+
})).filter((entry) => {
|
|
2740
|
+
const meta = entry.message.meta && typeof entry.message.meta === 'object' && !Array.isArray(entry.message.meta)
|
|
2741
|
+
? entry.message.meta as Record<string, unknown>
|
|
2742
|
+
: {};
|
|
2743
|
+
if (meta.runtimeInputAck !== true) return true;
|
|
2744
|
+
const runtimeText = flattenContent(entry.message.content).replace(/\s+/g, ' ').trim();
|
|
2745
|
+
if (!runtimeText) return false;
|
|
2746
|
+
return !parsedEntries.some((parsedEntry) => {
|
|
2747
|
+
const parsedRole = getRole(parsedEntry.message);
|
|
2748
|
+
if (parsedRole !== 'user' && parsedRole !== 'human') return false;
|
|
2749
|
+
const parsedText = flattenContent(parsedEntry.message.content).replace(/\s+/g, ' ').trim();
|
|
2750
|
+
return parsedText === runtimeText;
|
|
2751
|
+
});
|
|
2752
|
+
});
|
|
1267
2753
|
const getTime = (message: ChatMessage): number => {
|
|
1268
2754
|
const value = typeof message.receivedAt === 'number'
|
|
1269
2755
|
? message.receivedAt
|
|
@@ -1273,9 +2759,6 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
1273
2759
|
return Number.isFinite(value) && value > 0 ? value : 0;
|
|
1274
2760
|
};
|
|
1275
2761
|
|
|
1276
|
-
const getRole = (message: ChatMessage): string => typeof message.role === 'string'
|
|
1277
|
-
? message.role.trim().toLowerCase()
|
|
1278
|
-
: '';
|
|
1279
2762
|
const isRuntimeOverlay = (entry: MergeEntry): boolean => {
|
|
1280
2763
|
if (entry.source !== 'runtime') return false;
|
|
1281
2764
|
const key = typeof entry.runtimeKey === 'string' ? entry.runtimeKey.trim().toLowerCase() : '';
|
|
@@ -1341,7 +2824,9 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
1341
2824
|
this.providerSessionId = nextSessionId;
|
|
1342
2825
|
this.historyWriter.promoteHistorySession(this.type, previousHistorySessionId, nextSessionId);
|
|
1343
2826
|
this.historyWriter.writeSessionStart(this.type, nextSessionId, this.workingDir, this.instanceId);
|
|
1344
|
-
this.
|
|
2827
|
+
if (this.shouldHydrateExistingProviderHistory()) {
|
|
2828
|
+
this.restorePersistedHistoryFromCurrentSession();
|
|
2829
|
+
}
|
|
1345
2830
|
this.adapter.updateRuntimeMeta({ providerSessionId: nextSessionId });
|
|
1346
2831
|
this.onProviderSessionResolved?.({
|
|
1347
2832
|
instanceId: this.instanceId,
|
|
@@ -1354,13 +2839,39 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
1354
2839
|
LOG.info('CLI', `[${this.type}] discovered provider session id: ${nextSessionId}`);
|
|
1355
2840
|
}
|
|
1356
2841
|
|
|
1357
|
-
private
|
|
2842
|
+
private shouldHydrateExistingProviderHistory(): boolean {
|
|
2843
|
+
return this.launchMode === 'resume' || this.launchMode === 'manual';
|
|
2844
|
+
}
|
|
2845
|
+
|
|
2846
|
+
private shouldSuppressFreshLaunchStartupReplay(parsedMessages: unknown[], parsedStatus: any, adapterStatus: any, parsedProviderSessionId = ''): boolean {
|
|
2847
|
+
if (this.launchMode !== 'new') return false;
|
|
2848
|
+
if (this.providerSessionId) return false;
|
|
2849
|
+
if (!Array.isArray(parsedMessages) || parsedMessages.length === 0) return false;
|
|
2850
|
+
if (!isIdleStatus(adapterStatus?.status) || !isIdleStatus(parsedStatus?.status)) return false;
|
|
2851
|
+
if (parsedProviderSessionId) return true;
|
|
2852
|
+
|
|
2853
|
+
const newestMessageAt = parsedMessages.reduce<number>((newest, message) => Math.max(newest, getMessageTime(message)), 0);
|
|
2854
|
+
|
|
2855
|
+
// Untimestamped idle parser output during a fresh launch is usually the
|
|
2856
|
+
// provider's last workspace transcript before a new turn exists.
|
|
2857
|
+
return newestMessageAt === 0;
|
|
2858
|
+
}
|
|
2859
|
+
|
|
2860
|
+
private syncCanonicalSavedHistoryIfNeeded(options: { full?: boolean } = {}): boolean {
|
|
1358
2861
|
if (!this.providerSessionId) return false;
|
|
1359
|
-
const canonicalHistory = this.provider.
|
|
2862
|
+
const canonicalHistory = this.provider.nativeHistory;
|
|
1360
2863
|
if (!canonicalHistory) return false;
|
|
1361
2864
|
|
|
2865
|
+
// Per-status-report hydration reads only a bounded tail (snapshot needs at
|
|
2866
|
+
// most the newest 60). The once-per-resume restore path passes full:true
|
|
2867
|
+
// because seedSessionHistory needs the COMPLETE transcript to seed dedup
|
|
2868
|
+
// state. The read-cache key encodes the window so the bounded and full
|
|
2869
|
+
// reads don't share/clobber each other's 2s cache entry.
|
|
2870
|
+
const limit = options.full ? Number.MAX_SAFE_INTEGER : STATUS_HYDRATION_TAIL_LIMIT;
|
|
2871
|
+
const windowTag = options.full ? 'full' : `tail:${STATUS_HYDRATION_TAIL_LIMIT}`;
|
|
2872
|
+
|
|
1362
2873
|
if (isNativeSourceCanonicalHistory(canonicalHistory)) {
|
|
1363
|
-
const cacheKey = [this.type, this.providerSessionId, this.workingDir].join('\0');
|
|
2874
|
+
const cacheKey = [this.type, this.providerSessionId, this.workingDir, windowTag].join('\0');
|
|
1364
2875
|
const now = Date.now();
|
|
1365
2876
|
if (cacheKey === this.lastNativeSourceCanonicalCacheKey && now - this.lastNativeSourceCanonicalCheckAt < 2_000) {
|
|
1366
2877
|
return true;
|
|
@@ -1373,7 +2884,7 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
1373
2884
|
historySessionId: this.providerSessionId,
|
|
1374
2885
|
workspace: this.workingDir,
|
|
1375
2886
|
offset: 0,
|
|
1376
|
-
limit
|
|
2887
|
+
limit,
|
|
1377
2888
|
historyBehavior: this.provider.historyBehavior,
|
|
1378
2889
|
scripts: this.provider.scripts as any,
|
|
1379
2890
|
});
|
|
@@ -1390,7 +2901,7 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
1390
2901
|
}
|
|
1391
2902
|
|
|
1392
2903
|
try {
|
|
1393
|
-
const cacheKey = [this.type, this.providerSessionId, this.workingDir, canonicalHistory.mode || 'materialized-mirror'].join('\0');
|
|
2904
|
+
const cacheKey = [this.type, this.providerSessionId, this.workingDir, canonicalHistory.mode || 'materialized-mirror', windowTag].join('\0');
|
|
1394
2905
|
const now = Date.now();
|
|
1395
2906
|
if (cacheKey === this.lastNativeSourceCanonicalCacheKey && now - this.lastNativeSourceCanonicalCheckAt < 2_000) {
|
|
1396
2907
|
return true;
|
|
@@ -1401,7 +2912,14 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
1401
2912
|
if (!materializeProviderNativeHistory(this.type, canonicalHistory, this.providerSessionId, this.workingDir, this.provider.scripts as any)) {
|
|
1402
2913
|
return false;
|
|
1403
2914
|
}
|
|
1404
|
-
|
|
2915
|
+
// Bounded by default: the per-status-report path only needs the newest
|
|
2916
|
+
// STATUS_HYDRATION_TAIL_LIMIT messages because the snapshot caps
|
|
2917
|
+
// activeChat.messages to the last 60 (status/normalize.ts) and loads
|
|
2918
|
+
// the rest lazily via read_chat on subscribe. The once-per-resume
|
|
2919
|
+
// restore path passes full:true so seedSessionHistory still sees the
|
|
2920
|
+
// COMPLETE transcript for prefix-dedup seeding. readChatHistory serves
|
|
2921
|
+
// a bounded limit as an O(tail) read.
|
|
2922
|
+
const restoredHistory = readChatHistory(this.type, 0, limit, this.providerSessionId, 0, this.provider.historyBehavior);
|
|
1405
2923
|
this.lastPersistedHistoryMessages = restoredHistory.messages.map((message) => ({
|
|
1406
2924
|
role: message.role,
|
|
1407
2925
|
content: message.content,
|
|
@@ -1417,10 +2935,13 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
1417
2935
|
|
|
1418
2936
|
private restorePersistedHistoryFromCurrentSession(): void {
|
|
1419
2937
|
if (!this.providerSessionId) return;
|
|
1420
|
-
|
|
1421
|
-
|
|
2938
|
+
// Restore is the once-per-resume seeding path: it needs the COMPLETE
|
|
2939
|
+
// transcript so seedSessionHistory can prime dedup state. Pass full so the
|
|
2940
|
+
// hydration read is unbounded here (and only here).
|
|
2941
|
+
this.syncCanonicalSavedHistoryIfNeeded({ full: true });
|
|
2942
|
+
const restoredHistory = isNativeSourceCanonicalHistory(this.provider.nativeHistory)
|
|
1422
2943
|
? readProviderChatHistory(this.type, {
|
|
1423
|
-
canonicalHistory: this.provider.
|
|
2944
|
+
canonicalHistory: this.provider.nativeHistory,
|
|
1424
2945
|
historySessionId: this.providerSessionId,
|
|
1425
2946
|
workspace: this.workingDir,
|
|
1426
2947
|
offset: 0,
|