@adhdev/daemon-core 0.9.82-rc.34 → 0.9.82-rc.341
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 +8 -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 +46 -2
- package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
- package/dist/cli-adapters/cli-state-engine.d.ts +198 -0
- package/dist/cli-adapters/provider-cli-adapter.d.ts +116 -64
- package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
- package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
- package/dist/cli-adapters/provider-cli-shared.d.ts +53 -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/cli-manager.d.ts +2 -1
- package/dist/commands/handler.d.ts +110 -0
- package/dist/commands/mesh-coordinator.d.ts +85 -1
- package/dist/commands/router.d.ts +308 -1
- package/dist/commands/upgrade-helper.d.ts +12 -0
- 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/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/index.d.ts +2 -0
- package/dist/index.d.ts +52 -13
- package/dist/index.js +42012 -17098
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +41683 -16890
- 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 +46 -0
- package/dist/mesh/contracts.d.ts +164 -0
- package/dist/mesh/coordinator-prompt.d.ts +36 -0
- package/dist/mesh/coordinator-registry.d.ts +59 -0
- package/dist/mesh/mesh-active-work.d.ts +174 -0
- package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
- package/dist/mesh/mesh-events-coordinator.d.ts +169 -0
- package/dist/mesh/mesh-events-pending.d.ts +45 -0
- package/dist/mesh/mesh-events-stale.d.ts +40 -0
- package/dist/mesh/mesh-events-utils.d.ts +66 -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 -3
- package/dist/mesh/mesh-ledger.d.ts +77 -1
- package/dist/mesh/mesh-missions.d.ts +116 -0
- package/dist/mesh/mesh-reconcile-loop.d.ts +7 -0
- package/dist/mesh/mesh-refine-batch.d.ts +68 -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 +418 -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-work-queue.d.ts +208 -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 +135 -0
- package/dist/providers/acp-provider-instance.d.ts +2 -0
- package/dist/providers/approval-utils.d.ts +13 -0
- package/dist/providers/chat-message-normalization.d.ts +12 -0
- package/dist/providers/cli-provider-instance.d.ts +76 -3
- package/dist/providers/contracts.d.ts +139 -6
- package/dist/providers/external-sources.d.ts +71 -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/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 +13 -0
- package/dist/providers/provider-instance.d.ts +13 -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 +85 -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 +69 -0
- package/dist/providers/spec/cli-adapter.d.ts +217 -0
- package/dist/providers/spec/evaluator.d.ts +23 -0
- package/dist/providers/spec/fsm-driver.d.ts +306 -0
- package/dist/providers/spec/fsm-evaluator.d.ts +72 -0
- package/dist/providers/spec/fsm-loader.d.ts +14 -0
- package/dist/providers/spec/fsm-types.d.ts +144 -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 +180 -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 +295 -13
- 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/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 +55 -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 +1 -0
- package/src/cli-adapter-types.ts +47 -2
- package/src/cli-adapters/cli-script-runner.ts +421 -0
- package/src/cli-adapters/cli-state-engine.ts +1215 -0
- package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
- package/src/cli-adapters/provider-cli-adapter.ts +774 -1141
- package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
- package/src/cli-adapters/provider-cli-parse.ts +13 -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 +100 -11
- package/src/cli-adapters/pty-transport.ts +2 -1
- 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/chat-commands.ts +1823 -62
- package/src/commands/cli-manager.ts +286 -14
- package/src/commands/handler.ts +809 -2
- package/src/commands/mesh-coordinator.ts +332 -122
- package/src/commands/router.ts +7433 -1317
- package/src/commands/stream-commands.ts +8 -0
- package/src/commands/upgrade-helper.ts +81 -30
- package/src/config/chat-history.ts +483 -24
- package/src/config/config.ts +12 -0
- package/src/config/mesh-config.ts +388 -6
- 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/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 +53 -0
- 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 +8 -1
- package/src/git/index.ts +16 -0
- package/src/index.ts +146 -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/log-redactor.ts +100 -0
- package/src/logging/log-tail-reader.ts +220 -0
- package/src/logging/logger.ts +2 -1
- package/src/mesh/contracts.ts +329 -0
- package/src/mesh/coordinator-prompt.ts +234 -31
- package/src/mesh/coordinator-registry.ts +121 -0
- package/src/mesh/mesh-active-work.ts +623 -0
- package/src/mesh/mesh-delivery-policy.ts +315 -0
- package/src/mesh/mesh-events-coordinator.ts +2144 -0
- package/src/mesh/mesh-events-pending.ts +508 -0
- package/src/mesh/mesh-events-stale.ts +290 -0
- package/src/mesh/mesh-events-utils.ts +300 -0
- package/src/mesh/mesh-events.ts +30 -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 -5
- package/src/mesh/mesh-ledger.ts +589 -102
- package/src/mesh/mesh-missions.ts +248 -0
- package/src/mesh/mesh-reconcile-loop.ts +822 -0
- package/src/mesh/mesh-refine-batch.ts +197 -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 +1626 -0
- package/src/mesh/mesh-task-stats.ts +154 -0
- package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
- package/src/mesh/mesh-work-queue.ts +888 -141
- package/src/mesh/preview-freshness.ts +118 -0
- package/src/mesh/refine-config.ts +423 -0
- package/src/mesh/worktree-bootstrap-config.ts +331 -0
- package/src/providers/acp-provider-instance.ts +25 -9
- package/src/providers/approval-utils.d.ts +4 -0
- package/src/providers/approval-utils.ts +47 -5
- package/src/providers/chat-message-normalization.ts +45 -5
- package/src/providers/cli-provider-instance.ts +1038 -99
- 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/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/dispatcher.ts +340 -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 +10 -1
- package/src/providers/provider-loader.ts +670 -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 +262 -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 +168 -0
- package/src/providers/spec/cli-adapter.ts +986 -0
- package/src/providers/spec/evaluator.ts +345 -0
- package/src/providers/spec/fsm-driver.ts +1015 -0
- package/src/providers/spec/fsm-evaluator.ts +255 -0
- package/src/providers/spec/fsm-loader.ts +120 -0
- package/src/providers/spec/fsm-types.ts +238 -0
- package/src/providers/spec/native-history-executor.ts +1136 -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 +226 -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 +378 -14
- 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/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,22 @@ 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';
|
|
17
18
|
import type { CliProviderModule } from '../cli-adapters/provider-cli-adapter.js';
|
|
19
|
+
import { createCliAdapter } from './spec/route.js';
|
|
18
20
|
import type { PtyRuntimeMetadata, PtyTransportFactory } from '../cli-adapters/pty-transport.js';
|
|
19
21
|
import { StatusMonitor } from './status-monitor.js';
|
|
20
22
|
import { ChatHistoryWriter, isNativeSourceCanonicalHistory, materializeProviderNativeHistory, readChatHistory, readProviderChatHistory } from '../config/chat-history.js';
|
|
21
23
|
import { LOG } from '../logging/logger.js';
|
|
22
24
|
import type { ChatMessage } from '../types.js';
|
|
23
25
|
import { buildPersistedProviderEffectMessage, normalizeProviderEffects } from './control-effects.js';
|
|
24
|
-
import { formatAutoApprovalMessage, pickApprovalButton } from './approval-utils.js';
|
|
26
|
+
import { formatAutoApprovalMessage, pickApprovalButton, pickAutoApprovalButton, looksLikeActiveApprovalPromptText } from './approval-utils.js';
|
|
25
27
|
import { getCliScriptCommand, parseCliScriptResult } from './cli-script-results.js';
|
|
26
28
|
import { mergeProviderPatchState, resolveProviderStateSurface } from './provider-patch-state.js';
|
|
27
29
|
import { normalizeProviderSessionId } from './provider-session-id.js';
|
|
28
30
|
import { buildChatMessage, buildRuntimeSystemChatMessage, isUserFacingChatMessage, normalizeChatMessages, resolveChatMessageKind, extractFinalSummaryFromMessages } from './chat-message-normalization.js';
|
|
31
|
+
import { workingDirBasename } from './working-dir.js';
|
|
29
32
|
|
|
30
33
|
type PersistableCliHistoryMessage = {
|
|
31
34
|
role: string;
|
|
@@ -35,17 +38,77 @@ type PersistableCliHistoryMessage = {
|
|
|
35
38
|
receivedAt?: number;
|
|
36
39
|
};
|
|
37
40
|
|
|
41
|
+
// Status snapshots only ever surface the newest messages: the cloud 'live'
|
|
42
|
+
// profile drops chat messages entirely (loaded lazily via read_chat on
|
|
43
|
+
// subscribe) and the 'full' profile caps activeChat.messages to the last 60
|
|
44
|
+
// (see status/normalize.ts). Unread/completion markers walk only the tail.
|
|
45
|
+
// So getState()'s saved-history hydration — which runs once per resume/manual
|
|
46
|
+
// CLI session on every status report — must read only a bounded tail, not the
|
|
47
|
+
// entire transcript. A full MAX_SAFE_INTEGER read here makes the initial
|
|
48
|
+
// status report O(transcript) × N(sessions), which is the real cold first-
|
|
49
|
+
// connection bottleneck on chat-heavy machines. The window comfortably exceeds
|
|
50
|
+
// the 60-message snapshot cap so dedup/collapse at the boundary stays stable.
|
|
51
|
+
const STATUS_HYDRATION_TAIL_LIMIT = 200;
|
|
52
|
+
|
|
38
53
|
type CompletedDebouncePending = {
|
|
39
54
|
chatTitle: string;
|
|
40
55
|
duration: number;
|
|
41
56
|
timestamp: number;
|
|
42
57
|
firstObservedAt: number;
|
|
58
|
+
previousStatus: string;
|
|
43
59
|
loggedBlockReason?: string;
|
|
60
|
+
loggedTranscriptProbe?: boolean;
|
|
61
|
+
transcriptProbeHistory?: ExternalTranscriptProbe[];
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
function isIdleStatus(value: unknown): boolean {
|
|
65
|
+
const status = typeof value === 'string' ? value.trim().toLowerCase() : '';
|
|
66
|
+
return !status || status === 'idle' || status === 'ready';
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
function getMessageTime(message: unknown): number {
|
|
71
|
+
if (!message || typeof message !== 'object') return 0;
|
|
72
|
+
const record = message as { receivedAt?: unknown; timestamp?: unknown };
|
|
73
|
+
const value = Number(record.receivedAt ?? record.timestamp ?? 0);
|
|
74
|
+
return Number.isFinite(value) ? value : 0;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
type CompletedFinalizationBlock = {
|
|
78
|
+
reason: string;
|
|
79
|
+
terminal?: boolean;
|
|
80
|
+
allowTimeout?: boolean;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
type CompletionFinalAssistantEvidence = {
|
|
84
|
+
present: boolean;
|
|
85
|
+
messages: unknown[];
|
|
86
|
+
source: 'parsed' | 'external-native' | 'unavailable';
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
type ExternalTranscriptProbe = {
|
|
90
|
+
readAt: number;
|
|
91
|
+
msgCount: number;
|
|
92
|
+
lastRole: string | null;
|
|
93
|
+
lastKind: string | null;
|
|
94
|
+
contentLen: number;
|
|
95
|
+
sourcePath: string | null;
|
|
96
|
+
sourceMtimeMs: number | null;
|
|
97
|
+
mtimeAgeMs: number | null;
|
|
44
98
|
};
|
|
45
99
|
|
|
46
100
|
const COMPLETED_FINALIZATION_RETRY_MS = 1000;
|
|
47
101
|
const COMPLETED_FINALIZATION_MAX_WAIT_MS = 30_000;
|
|
48
102
|
|
|
103
|
+
/** Events that signal a dispatched mesh task has reached a terminal state.
|
|
104
|
+
* Detach the mesh assignment after emitting one of these so the worker's
|
|
105
|
+
* next unrelated turn doesn't impersonate another completion. */
|
|
106
|
+
const TERMINAL_MESH_EVENTS = new Set([
|
|
107
|
+
'agent:generating_completed',
|
|
108
|
+
'agent:stopped',
|
|
109
|
+
'agent:ready',
|
|
110
|
+
]);
|
|
111
|
+
|
|
49
112
|
const IMAGE_MIME_EXTENSIONS: Record<string, string> = {
|
|
50
113
|
'image/png': '.png',
|
|
51
114
|
'image/jpeg': '.jpg',
|
|
@@ -120,7 +183,7 @@ function hasNonEmptyCliModalButtons(activeModal: unknown): boolean {
|
|
|
120
183
|
}
|
|
121
184
|
|
|
122
185
|
function isCliGeneratingLikeStatus(status: unknown): boolean {
|
|
123
|
-
return status === 'generating' || status === 'streaming' || status === 'long_generating' || status === 'starting';
|
|
186
|
+
return status === 'generating' || status === 'streaming' || status === 'no_progress' || status === 'long_generating' || status === 'starting';
|
|
124
187
|
}
|
|
125
188
|
|
|
126
189
|
export function buildCliStructuredInputPrompt(
|
|
@@ -300,6 +363,19 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
300
363
|
readonly type: string;
|
|
301
364
|
readonly category = 'cli' as const;
|
|
302
365
|
|
|
366
|
+
/**
|
|
367
|
+
* Quiet period an approval modal's signature must be stable before
|
|
368
|
+
* auto-approve sends the approve key. Guards against firing on a prompt
|
|
369
|
+
* that is still streaming into the PTY (the "resolves too fast" symptom):
|
|
370
|
+
* while the modal text/buttons are still changing, every frame yields a
|
|
371
|
+
* new signature and the settle clock restarts. Once the prompt finishes
|
|
372
|
+
* rendering the signature holds and the key is sent after this window.
|
|
373
|
+
* Bounded + small so genuine approvals stay timely. The FSM is already
|
|
374
|
+
* authoritative over the `waiting_approval` state; this only delays the
|
|
375
|
+
* keystroke until the modal *content* has settled.
|
|
376
|
+
*/
|
|
377
|
+
private static readonly AUTO_APPROVE_SETTLE_MS = 600;
|
|
378
|
+
|
|
303
379
|
private adapter: ProviderCliAdapter;
|
|
304
380
|
private context: InstanceContext | null = null;
|
|
305
381
|
private events: ProviderEvent[] = [];
|
|
@@ -309,15 +385,25 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
309
385
|
private monitor: StatusMonitor;
|
|
310
386
|
private generatingDebounceTimer: NodeJS.Timeout | null = null;
|
|
311
387
|
private generatingDebouncePending: { chatTitle: string; timestamp: number } | null = null;
|
|
312
|
-
private
|
|
388
|
+
private lastApprovalEventFingerprint = '';
|
|
313
389
|
private autoApproveBusy = false;
|
|
314
390
|
private autoApproveBusyTimer: NodeJS.Timeout | null = null;
|
|
391
|
+
private lastAutoApprovalSignature = '';
|
|
392
|
+
// Settle gate: the approval modal's signature + the wall-clock when this
|
|
393
|
+
// exact signature was first observed. Auto-approve only fires once the
|
|
394
|
+
// SAME signature has been stable for AUTO_APPROVE_SETTLE_MS, so a prompt
|
|
395
|
+
// still streaming into the PTY (its buttons/message changing frame to
|
|
396
|
+
// frame) keeps resetting the timer and is never approved half-rendered.
|
|
397
|
+
private pendingAutoApprovalSignature = '';
|
|
398
|
+
private pendingAutoApprovalSince = 0;
|
|
399
|
+
private autoApproveSettleTimer: NodeJS.Timeout | null = null;
|
|
315
400
|
private controlValues: Record<string, string | number | boolean> = {};
|
|
316
401
|
private summaryMetadata: unknown = undefined;
|
|
317
402
|
private appliedEffectKeys = new Set<string>();
|
|
318
403
|
private historyWriter: ChatHistoryWriter;
|
|
319
404
|
private runtimeMessages: Array<{ key: string; message: ChatMessage }> = [];
|
|
320
405
|
private lastPersistedHistoryMessages: PersistableCliHistoryMessage[] = [];
|
|
406
|
+
private lastAcknowledgedUserInputAt = 0;
|
|
321
407
|
private lastNativeSourceCanonicalCheckAt = 0;
|
|
322
408
|
private lastNativeSourceCanonicalCacheKey: string | undefined = undefined;
|
|
323
409
|
private cachedSqliteDb: {
|
|
@@ -330,6 +416,7 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
330
416
|
private suppressIdleHistoryReplay = false;
|
|
331
417
|
private errorMessage: string | undefined = undefined;
|
|
332
418
|
private errorReason: ProviderErrorReason | undefined = undefined;
|
|
419
|
+
private activeInteractivePrompt: InteractivePrompt | null = null;
|
|
333
420
|
|
|
334
421
|
private presentationMode: 'terminal' | 'chat';
|
|
335
422
|
private providerSessionId?: string;
|
|
@@ -370,7 +457,10 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
370
457
|
this.providerSessionId = options?.providerSessionId;
|
|
371
458
|
this.launchMode = options?.launchMode || 'new';
|
|
372
459
|
this.onProviderSessionResolved = options?.onProviderSessionResolved;
|
|
373
|
-
this.adapter =
|
|
460
|
+
this.adapter = createCliAdapter(provider as CliProviderModule, workingDir, cliArgs, options?.extraEnv || {}, transportFactory) as ProviderCliAdapter;
|
|
461
|
+
if (this.providerSessionId) {
|
|
462
|
+
this.adapter.updateRuntimeMeta({ providerSessionId: this.providerSessionId });
|
|
463
|
+
}
|
|
374
464
|
this.monitor = new StatusMonitor();
|
|
375
465
|
this.historyWriter = new ChatHistoryWriter();
|
|
376
466
|
}
|
|
@@ -389,8 +479,8 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
389
479
|
this.adapter.updateRuntimeSettings?.(this.settings);
|
|
390
480
|
this.monitor.updateConfig({
|
|
391
481
|
approvalAlert: this.settings.approvalAlert !== false,
|
|
392
|
-
|
|
393
|
-
|
|
482
|
+
noProgressAlert: (this.settings.noProgressAlert ?? this.settings.longGeneratingAlert) !== false,
|
|
483
|
+
noProgressThresholdSec: this.settings.noProgressThresholdSec ?? this.settings.longGeneratingThresholdSec ?? 180,
|
|
394
484
|
});
|
|
395
485
|
|
|
396
486
|
// Server connection
|
|
@@ -412,7 +502,7 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
412
502
|
await this.adapter.spawn();
|
|
413
503
|
await this.enforceFreshSessionLaunchIfNeeded();
|
|
414
504
|
this.maybeAppendRuntimeRecoveryMessage(this.adapter.getRuntimeMetadata());
|
|
415
|
-
if (this.providerSessionId) {
|
|
505
|
+
if (this.providerSessionId && this.shouldHydrateExistingProviderHistory()) {
|
|
416
506
|
this.restorePersistedHistoryFromCurrentSession();
|
|
417
507
|
}
|
|
418
508
|
if (this.providerSessionId && this.launchMode === 'resume') {
|
|
@@ -486,14 +576,38 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
486
576
|
}
|
|
487
577
|
|
|
488
578
|
getState(): ProviderState {
|
|
579
|
+
// TODO(phase5-sandbox): JS override scripts (detectStatus, parseApproval,
|
|
580
|
+
// parseSession) are currently invoked by CliScriptRunner.invoke() via direct
|
|
581
|
+
// function calls — the scripts run in the daemon process with full Node.js
|
|
582
|
+
// access and no resource limits.
|
|
583
|
+
//
|
|
584
|
+
// When Phase 5 lands, CliScriptRunner should route these calls through a
|
|
585
|
+
// SandboxedScriptRunner (see providers/sdk/v1/sandbox/script-runner.ts) so
|
|
586
|
+
// that each call gets a fresh isolated-vm context with a 50 ms CPU limit and
|
|
587
|
+
// a 32 MB memory cap. The execution path to change is:
|
|
588
|
+
// CliScriptRunner.invoke() → SandboxedScriptRunner.run(scriptSource, context)
|
|
589
|
+
//
|
|
590
|
+
// This getState() call-site is NOT where the change goes — the wiring belongs
|
|
591
|
+
// in cli-script-runner.ts (CliScriptRunner.detectStatus / parseApproval /
|
|
592
|
+
// parseSession), with provider-loader.ts updated to store script source strings
|
|
593
|
+
// alongside the loaded function references for extended-legacy providers.
|
|
489
594
|
const adapterStatus = this.adapter.getStatus();
|
|
595
|
+
if (Object.prototype.hasOwnProperty.call(adapterStatus, 'activeInteractivePrompt')) {
|
|
596
|
+
this.activeInteractivePrompt = adapterStatus.activeInteractivePrompt ?? null;
|
|
597
|
+
}
|
|
490
598
|
let parsedStatus: any = null;
|
|
491
599
|
let parseErrorMessage: string | undefined;
|
|
492
600
|
if (typeof this.adapter.getScriptParsedStatus === 'function') {
|
|
493
601
|
try {
|
|
494
602
|
parsedStatus = this.adapter.getScriptParsedStatus() || null;
|
|
495
|
-
|
|
496
|
-
|
|
603
|
+
const parsedErrorMessage = typeof parsedStatus?.errorMessage === 'string' && parsedStatus.errorMessage.trim()
|
|
604
|
+
? parsedStatus.errorMessage.trim()
|
|
605
|
+
: undefined;
|
|
606
|
+
const parsedErrorReason = typeof parsedStatus?.errorReason === 'string' && parsedStatus.errorReason.trim()
|
|
607
|
+
? parsedStatus.errorReason.trim() as ProviderErrorReason
|
|
608
|
+
: undefined;
|
|
609
|
+
this.errorMessage = parsedErrorMessage;
|
|
610
|
+
this.errorReason = parsedErrorReason;
|
|
497
611
|
} catch (error: any) {
|
|
498
612
|
parseErrorMessage = error?.message || String(error);
|
|
499
613
|
this.errorMessage = parseErrorMessage;
|
|
@@ -503,22 +617,53 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
503
617
|
this.errorMessage = undefined;
|
|
504
618
|
this.errorReason = undefined;
|
|
505
619
|
}
|
|
506
|
-
const
|
|
507
|
-
const visibleStatus = parseErrorMessage
|
|
508
|
-
? 'error'
|
|
509
|
-
: (autoApproveActive ? 'generating' : adapterStatus.status);
|
|
510
|
-
const parsedProviderSessionId = normalizeProviderSessionId(
|
|
620
|
+
const adapterProviderSessionId = normalizeProviderSessionId(
|
|
511
621
|
this.provider,
|
|
512
|
-
typeof
|
|
622
|
+
typeof adapterStatus?.providerSessionId === 'string' ? adapterStatus.providerSessionId : '',
|
|
513
623
|
);
|
|
514
|
-
|
|
515
|
-
|
|
624
|
+
const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, Date.now());
|
|
625
|
+
const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
|
|
626
|
+
let visibleStatus = parseErrorMessage || parsedStatus?.status === 'error'
|
|
627
|
+
? 'error'
|
|
628
|
+
: (autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status);
|
|
629
|
+
// getState() must agree with the status the FSM-driven detectStatusTransition()
|
|
630
|
+
// already committed to lastStatus. The adapter's own status is authoritative; we do
|
|
631
|
+
// not second-guess it with native-transcript shape. Only reconcile a generating-like
|
|
632
|
+
// read down to idle when our own lastStatus has already flipped idle (avoids a
|
|
633
|
+
// perpetual dashboard spinner during the brief window before the next getStatus()).
|
|
634
|
+
if (isCliGeneratingLikeStatus(visibleStatus) && this.lastStatus === 'idle') {
|
|
635
|
+
visibleStatus = 'idle';
|
|
516
636
|
}
|
|
517
637
|
const runtime = this.adapter.getRuntimeMetadata();
|
|
518
638
|
this.maybeAppendRuntimeRecoveryMessage(runtime);
|
|
519
639
|
let parsedMessages = Array.isArray(parsedStatus?.messages)
|
|
520
640
|
? parsedStatus.messages
|
|
521
641
|
: [];
|
|
642
|
+
const parsedProviderSessionId = normalizeProviderSessionId(
|
|
643
|
+
this.provider,
|
|
644
|
+
typeof parsedStatus?.providerSessionId === 'string' ? parsedStatus.providerSessionId : '',
|
|
645
|
+
);
|
|
646
|
+
const suppressFreshLaunchStartupReplay = this.shouldSuppressFreshLaunchStartupReplay(
|
|
647
|
+
parsedMessages,
|
|
648
|
+
parsedStatus,
|
|
649
|
+
adapterStatus,
|
|
650
|
+
parsedProviderSessionId,
|
|
651
|
+
);
|
|
652
|
+
if (adapterProviderSessionId && !suppressFreshLaunchStartupReplay) {
|
|
653
|
+
this.promoteProviderSessionId(adapterProviderSessionId);
|
|
654
|
+
}
|
|
655
|
+
if (parsedProviderSessionId && !suppressFreshLaunchStartupReplay) {
|
|
656
|
+
this.promoteProviderSessionId(parsedProviderSessionId);
|
|
657
|
+
}
|
|
658
|
+
if (suppressFreshLaunchStartupReplay) {
|
|
659
|
+
parsedMessages = [];
|
|
660
|
+
}
|
|
661
|
+
// Adapter runtime metadata is transport-owned and is not guaranteed to
|
|
662
|
+
// identify this conversation. Spec adapters historically exposed the
|
|
663
|
+
// provider spec id (for example "codex-cli") as runtimeId, which made
|
|
664
|
+
// concurrent sessions share one activeChat identity until their native
|
|
665
|
+
// provider session ids were discovered.
|
|
666
|
+
const activeChatId = this.providerSessionId || this.instanceId;
|
|
522
667
|
const historyMessageCount = Number.isFinite(parsedStatus?.historyMessageCount)
|
|
523
668
|
? Math.max(0, Number(parsedStatus.historyMessageCount))
|
|
524
669
|
: null;
|
|
@@ -528,9 +673,20 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
528
673
|
: [];
|
|
529
674
|
}
|
|
530
675
|
const mergedMessages = this.mergeConversationMessages(parsedMessages);
|
|
531
|
-
const canonicalBackedHistory = this.
|
|
676
|
+
const canonicalBackedHistory = this.shouldHydrateExistingProviderHistory()
|
|
677
|
+
? this.syncCanonicalSavedHistoryIfNeeded()
|
|
678
|
+
: false;
|
|
679
|
+
const statusMessages = canonicalBackedHistory && this.lastPersistedHistoryMessages.length > 0
|
|
680
|
+
? this.lastPersistedHistoryMessages.map((message) => ({
|
|
681
|
+
role: message.role,
|
|
682
|
+
content: message.content,
|
|
683
|
+
kind: message.kind,
|
|
684
|
+
senderName: message.senderName,
|
|
685
|
+
receivedAt: message.receivedAt,
|
|
686
|
+
}))
|
|
687
|
+
: mergedMessages;
|
|
532
688
|
|
|
533
|
-
const dirName = this.workingDir
|
|
689
|
+
const dirName = workingDirBasename(this.workingDir);
|
|
534
690
|
const parsedChatStatus = typeof parsedStatus?.status === 'string' && parsedStatus.status.trim()
|
|
535
691
|
? parsedStatus.status.trim()
|
|
536
692
|
: undefined;
|
|
@@ -542,7 +698,7 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
542
698
|
&& adapterStatus.status === 'idle'
|
|
543
699
|
&& parsedStatus?.status === 'idle';
|
|
544
700
|
let messagesToSave = parsedMessages;
|
|
545
|
-
if (!suppressStaleParsedBusyStatus && (parsedChatStatus === 'generating' || parsedChatStatus === 'long_generating')) {
|
|
701
|
+
if (!suppressStaleParsedBusyStatus && (parsedChatStatus === 'generating' || parsedChatStatus === 'no_progress' || parsedChatStatus === 'long_generating')) {
|
|
546
702
|
const lastIdx = messagesToSave.length - 1;
|
|
547
703
|
if (lastIdx >= 0 && messagesToSave[lastIdx]?.role === 'assistant') {
|
|
548
704
|
messagesToSave = messagesToSave.slice(0, lastIdx);
|
|
@@ -572,33 +728,48 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
572
728
|
}
|
|
573
729
|
}
|
|
574
730
|
|
|
575
|
-
this.applyProviderResponse(
|
|
731
|
+
this.applyProviderResponse(
|
|
732
|
+
suppressFreshLaunchStartupReplay && parsedStatus && typeof parsedStatus === 'object'
|
|
733
|
+
? { ...parsedStatus, providerSessionId: undefined }
|
|
734
|
+
: parsedStatus,
|
|
735
|
+
{ phase: 'immediate' },
|
|
736
|
+
);
|
|
576
737
|
const surface = resolveProviderStateSurface({
|
|
577
738
|
summaryMetadata: this.summaryMetadata as any,
|
|
578
739
|
controlValues: this.controlValues,
|
|
579
740
|
});
|
|
580
741
|
const activeChatStatus = parseErrorMessage
|
|
581
742
|
? 'error'
|
|
582
|
-
: autoApproveActive && parsedStatus?.status === 'waiting_approval'
|
|
743
|
+
: (autoApproveActive && parsedStatus?.status === 'waiting_approval') || autoApproveHoldIdle
|
|
583
744
|
? 'generating'
|
|
584
745
|
: (adapterStatus.status !== 'idle'
|
|
585
746
|
? visibleStatus
|
|
586
747
|
: (suppressStaleParsedBusyStatus ? visibleStatus : (parsedChatStatus || visibleStatus)));
|
|
587
748
|
|
|
749
|
+
// If an AskUserQuestion prompt is awaiting user input, overlay status as
|
|
750
|
+
// waiting_choice. This is distinct from waiting_approval (tool-use consent)
|
|
751
|
+
// — the engine's isWaitingForResponse state is unchanged, so completion
|
|
752
|
+
// tracking continues normally once the user responds.
|
|
753
|
+
const hasInteractivePrompt = !!this.activeInteractivePrompt;
|
|
754
|
+
const finalStatus = hasInteractivePrompt ? 'waiting_choice' : visibleStatus;
|
|
755
|
+
const finalChatStatus = hasInteractivePrompt ? 'waiting_choice' : activeChatStatus;
|
|
756
|
+
|
|
588
757
|
return {
|
|
589
758
|
type: this.type,
|
|
590
759
|
name: this.provider.name,
|
|
591
760
|
category: 'cli',
|
|
592
|
-
status:
|
|
761
|
+
status: finalStatus,
|
|
593
762
|
mode: this.presentationMode,
|
|
594
763
|
activeChat: {
|
|
595
|
-
id:
|
|
764
|
+
id: activeChatId,
|
|
596
765
|
title: parsedStatus?.title || dirName,
|
|
597
|
-
status:
|
|
598
|
-
messages:
|
|
599
|
-
activeModal: autoApproveActive ? null : (parsedStatus?.activeModal ?? adapterStatus.activeModal),
|
|
766
|
+
status: finalChatStatus,
|
|
767
|
+
messages: statusMessages,
|
|
768
|
+
activeModal: (autoApproveActive || autoApproveHoldIdle) ? null : (parsedStatus?.activeModal ?? adapterStatus.activeModal),
|
|
769
|
+
activeInteractivePrompt: this.activeInteractivePrompt,
|
|
600
770
|
inputContent: '',
|
|
601
771
|
},
|
|
772
|
+
activeInteractivePrompt: this.activeInteractivePrompt,
|
|
602
773
|
workspace: this.workingDir,
|
|
603
774
|
instanceId: this.instanceId,
|
|
604
775
|
providerSessionId: this.providerSessionId,
|
|
@@ -639,7 +810,8 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
639
810
|
getHotChatSessionState(): HotChatSessionState {
|
|
640
811
|
const adapterStatus = this.adapter.getStatus({ allowParse: false });
|
|
641
812
|
const autoApproveActive = adapterStatus.status === 'waiting_approval' && this.shouldAutoApprove();
|
|
642
|
-
const
|
|
813
|
+
const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
|
|
814
|
+
const visibleStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status;
|
|
643
815
|
const runtime = this.adapter.getRuntimeMetadata();
|
|
644
816
|
return {
|
|
645
817
|
id: this.instanceId,
|
|
@@ -651,36 +823,146 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
651
823
|
};
|
|
652
824
|
}
|
|
653
825
|
|
|
654
|
-
getSessionModalState(): SessionModalState {
|
|
655
|
-
const adapterStatus = this.adapter.getStatus({ allowParse:
|
|
826
|
+
getSessionModalState(sessionId?: string): SessionModalState {
|
|
827
|
+
const adapterStatus = this.adapter.getStatus({ allowParse: true });
|
|
656
828
|
const autoApproveActive = adapterStatus.status === 'waiting_approval' && this.shouldAutoApprove();
|
|
657
|
-
const
|
|
658
|
-
const
|
|
829
|
+
const autoApproveHoldIdle = this.autoApproveBusy && adapterStatus.status === 'idle';
|
|
830
|
+
const visibleStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : adapterStatus.status;
|
|
831
|
+
const dirName = workingDirBasename(this.workingDir);
|
|
659
832
|
return {
|
|
660
|
-
|
|
833
|
+
// Honor the caller-supplied sessionId — InstanceMgr rejects the
|
|
834
|
+
// projection when projected.id !== requested sessionId, and
|
|
835
|
+
// this.instanceId is the manager's internal key, not the public
|
|
836
|
+
// sessionId the dashboard subscribes by.
|
|
837
|
+
id: sessionId ?? this.instanceId,
|
|
661
838
|
status: visibleStatus,
|
|
662
839
|
title: dirName,
|
|
663
|
-
activeModal: autoApproveActive ? null : adapterStatus.activeModal,
|
|
840
|
+
activeModal: (autoApproveActive || autoApproveHoldIdle) ? null : adapterStatus.activeModal,
|
|
664
841
|
};
|
|
665
842
|
}
|
|
666
843
|
|
|
667
844
|
updateSettings(newSettings: Record<string, any>): void {
|
|
668
|
-
|
|
845
|
+
// Merge semantics: a key omitted from newSettings preserves its existing
|
|
846
|
+
// value, a key present in newSettings (even as false) overrides it.
|
|
847
|
+
//
|
|
848
|
+
// This is required because updateSettings has two callers with opposite
|
|
849
|
+
// intent:
|
|
850
|
+
// 1. Full re-injection — the dashboard toggle path (handleSetProviderSetting
|
|
851
|
+
// → getSettings → updateInstanceSettings) sends the COMPLETE settings
|
|
852
|
+
// object, so an explicit autoApprove:false must win.
|
|
853
|
+
// 2. Partial stamp — the mesh relay-safety stamp (router.ts agent_command,
|
|
854
|
+
// buildMeshWorkerRelayStamp) sends ONLY {meshNodeFor, meshNodeId,
|
|
855
|
+
// meshCoordinatorDaemonId, launchedByCoordinator} on every coordinator
|
|
856
|
+
// re-dispatch. It carries no autoApprove, so a full replacement would
|
|
857
|
+
// wipe the launch-time autoApprove:true the worker was started with,
|
|
858
|
+
// silently dropping every later approval to a manual gate until the
|
|
859
|
+
// machine-page toggle re-injected the full settings.
|
|
860
|
+
//
|
|
861
|
+
// A plain merge satisfies both: undefined keys fall through to the existing
|
|
862
|
+
// value (preserving launch-stamp settings like autoApprove + the mesh routing
|
|
863
|
+
// keys), explicit keys override. This subsumes the previous mesh-key preserve
|
|
864
|
+
// list, which only protected the routing keys and not autoApprove.
|
|
865
|
+
this.settings = { ...this.settings, ...newSettings };
|
|
669
866
|
this.adapter.updateRuntimeSettings?.(this.settings);
|
|
670
867
|
this.monitor.updateConfig({
|
|
671
868
|
approvalAlert: this.settings.approvalAlert !== false,
|
|
672
|
-
|
|
673
|
-
|
|
869
|
+
noProgressAlert: (this.settings.noProgressAlert ?? this.settings.longGeneratingAlert) !== false,
|
|
870
|
+
noProgressThresholdSec: this.settings.noProgressThresholdSec ?? this.settings.longGeneratingThresholdSec ?? 180,
|
|
674
871
|
});
|
|
675
872
|
}
|
|
676
873
|
|
|
874
|
+
/**
|
|
875
|
+
* Stamp a direct-dispatch mesh assignment on this instance.
|
|
876
|
+
* setupMeshEventForwarding reads settings.meshNodeFor + meshActiveTaskId to
|
|
877
|
+
* route generating_completed back to the originating coordinator. Without
|
|
878
|
+
* this stamp, mesh_send_task --direct targets a plain CLI session whose
|
|
879
|
+
* completion events silently drop because the forwarder has nothing to
|
|
880
|
+
* match against.
|
|
881
|
+
*/
|
|
882
|
+
attachMeshAssignment(assignment: { meshId: string; nodeId?: string; taskId?: string; coordinatorDaemonId?: string }): void {
|
|
883
|
+
if (!assignment?.meshId) return;
|
|
884
|
+
this.settings = {
|
|
885
|
+
...this.settings,
|
|
886
|
+
meshNodeFor: assignment.meshId,
|
|
887
|
+
...(assignment.nodeId ? { meshNodeId: assignment.nodeId } : {}),
|
|
888
|
+
...(assignment.taskId ? { meshActiveTaskId: assignment.taskId } : {}),
|
|
889
|
+
...(assignment.coordinatorDaemonId ? { meshCoordinatorDaemonId: assignment.coordinatorDaemonId } : {}),
|
|
890
|
+
};
|
|
891
|
+
this.adapter.updateRuntimeSettings?.(this.settings);
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
/**
|
|
895
|
+
* Clear a previously-attached mesh assignment after the task reaches a
|
|
896
|
+
* terminal state. Leaving meshNodeFor pinned would route this session's
|
|
897
|
+
* subsequent unrelated turns (e.g. ad-hoc dashboard chats) to the
|
|
898
|
+
* coordinator as if they were task completions.
|
|
899
|
+
*/
|
|
900
|
+
detachMeshAssignment(): void {
|
|
901
|
+
if (!this.settings.meshNodeFor && !this.settings.meshActiveTaskId && !this.settings.meshNodeId) return;
|
|
902
|
+
const { meshNodeFor, meshNodeId, meshActiveTaskId, ...rest } = this.settings;
|
|
903
|
+
void meshNodeFor; void meshNodeId; void meshActiveTaskId;
|
|
904
|
+
this.settings = rest;
|
|
905
|
+
this.adapter.updateRuntimeSettings?.(this.settings);
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
/**
|
|
909
|
+
* The resolved modal-park status of this session, or null when it is not
|
|
910
|
+
* parked on a modal awaiting a human answer. Mirrors the overlay logic in
|
|
911
|
+
* getState(): an active AskUserQuestion interactive prompt resolves to
|
|
912
|
+
* waiting_choice; otherwise the adapter's waiting_approval (tool consent)
|
|
913
|
+
* counts — UNLESS auto-approve will dismiss it, in which case the session is
|
|
914
|
+
* effectively generating and is NOT modal-parked. This is the single signal
|
|
915
|
+
* the mesh force-inject guard consults, and the same status string the
|
|
916
|
+
* reconcile loop reads off get_status_metadata. Lowercase literals only —
|
|
917
|
+
* the SessionStatus enum is forked across modules and waiting_choice is
|
|
918
|
+
* absent from some of them.
|
|
919
|
+
*/
|
|
920
|
+
resolveModalParkStatus(): 'waiting_choice' | 'waiting_approval' | null {
|
|
921
|
+
if (this.activeInteractivePrompt) return 'waiting_choice';
|
|
922
|
+
let adapterStatus: { status?: string };
|
|
923
|
+
try {
|
|
924
|
+
adapterStatus = this.adapter.getStatus({ allowParse: false });
|
|
925
|
+
} catch {
|
|
926
|
+
return null;
|
|
927
|
+
}
|
|
928
|
+
if (adapterStatus.status === 'waiting_approval' && !this.shouldAutoApprove()) {
|
|
929
|
+
return 'waiting_approval';
|
|
930
|
+
}
|
|
931
|
+
return null;
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
/** True when this session is parked on a modal awaiting a human answer. */
|
|
935
|
+
isModalParked(): boolean {
|
|
936
|
+
return this.resolveModalParkStatus() !== null;
|
|
937
|
+
}
|
|
938
|
+
|
|
677
939
|
onEvent(event: string, data?: any): void {
|
|
678
940
|
if (event === 'send_message') {
|
|
679
941
|
const input = normalizeInputEnvelope(data);
|
|
680
942
|
assertProviderSupportsDeclaredInput(this.provider, input);
|
|
681
943
|
const promptText = buildCliStructuredInputPrompt(input);
|
|
682
944
|
if (promptText) {
|
|
683
|
-
|
|
945
|
+
// force:true bypasses the busy/generating send guard so terminal mesh
|
|
946
|
+
// events (completion/failure/bootstrap) land in a coordinator session that
|
|
947
|
+
// is itself parked in `generating` while awaiting that very event.
|
|
948
|
+
// Without it the message is queued and only flushed on the coordinator's
|
|
949
|
+
// own idle transition — which never happens until it receives the message.
|
|
950
|
+
const force = data?.force === true;
|
|
951
|
+
// Modal guard: a force-inject still writes raw keystrokes into the PTY,
|
|
952
|
+
// bypassing the busy send-guard. If the coordinator is parked on a
|
|
953
|
+
// harness modal (claude-cli AskUserQuestion → waiting_choice, or a
|
|
954
|
+
// tool-consent waiting_approval), those keystrokes are consumed by the
|
|
955
|
+
// modal's key handler and silently select a choice the user never made
|
|
956
|
+
// (data corruption). Hold the force-inject in that narrow window —
|
|
957
|
+
// the event stays queued and the reconcile loop redelivers it on the
|
|
958
|
+
// next tick once the modal is resolved. We ONLY hold for the two modal
|
|
959
|
+
// states; generating is still force-injected (that is the deadlock the
|
|
960
|
+
// force path exists to break — see mesh-events-coordinator).
|
|
961
|
+
if (force && this.isModalParked()) {
|
|
962
|
+
LOG.info('CLI', `[${this.type}] force send_message held — coordinator parked on modal (${this.resolveModalParkStatus()})`);
|
|
963
|
+
return;
|
|
964
|
+
}
|
|
965
|
+
void this.adapter.sendMessage(promptText, force ? { force: true } : {}).catch((e: any) => {
|
|
684
966
|
LOG.warn('CLI', `[${this.type}] send_message failed: ${e?.message || e}`);
|
|
685
967
|
});
|
|
686
968
|
}
|
|
@@ -690,14 +972,73 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
690
972
|
void this.adapter.resolveAction(data).catch((e: any) => {
|
|
691
973
|
LOG.warn('CLI', `[${this.type}] resolve_action failed: ${e?.message || e}`);
|
|
692
974
|
});
|
|
975
|
+
} else if (event === 'interactive_prompt' && data) {
|
|
976
|
+
const prompt = normalizeInteractivePrompt(data);
|
|
977
|
+
if (prompt) {
|
|
978
|
+
this.activeInteractivePrompt = prompt;
|
|
979
|
+
this.events.push({
|
|
980
|
+
event: 'interactive_prompt',
|
|
981
|
+
timestamp: Date.now(),
|
|
982
|
+
promptId: prompt.promptId,
|
|
983
|
+
});
|
|
984
|
+
}
|
|
985
|
+
} else if (event === 'interactive_prompt_response' && data) {
|
|
986
|
+
try {
|
|
987
|
+
const response = normalizeInteractivePromptResponse(data);
|
|
988
|
+
if (this.activeInteractivePrompt?.promptId === response.promptId) {
|
|
989
|
+
this.activeInteractivePrompt = null;
|
|
990
|
+
}
|
|
991
|
+
if (typeof this.adapter.setInteractivePromptResponse !== 'function') {
|
|
992
|
+
LOG.warn('CLI', `[${this.type}] interactive_prompt_response ignored: adapter does not support interactive prompts`);
|
|
993
|
+
return;
|
|
994
|
+
}
|
|
995
|
+
void this.adapter.setInteractivePromptResponse(response).catch((e: any) => {
|
|
996
|
+
LOG.warn('CLI', `[${this.type}] interactive_prompt_response failed: ${e?.message || e}`);
|
|
997
|
+
});
|
|
998
|
+
} catch (e: any) {
|
|
999
|
+
LOG.warn('CLI', `[${this.type}] invalid interactive_prompt_response: ${e?.message || e}`);
|
|
1000
|
+
}
|
|
693
1001
|
} else if (event === 'provider_state_patch' && data && typeof data === 'object') {
|
|
694
1002
|
this.applyProviderResponse(data, { phase: 'immediate' });
|
|
695
1003
|
}
|
|
696
1004
|
}
|
|
697
1005
|
|
|
1006
|
+
recordAcknowledgedUserInput(input: InputEnvelope | string): void {
|
|
1007
|
+
const content = typeof input === 'string'
|
|
1008
|
+
? input.trim()
|
|
1009
|
+
: buildCliStructuredInputPrompt(input).trim();
|
|
1010
|
+
if (!content) return;
|
|
1011
|
+
|
|
1012
|
+
const receivedAt = Date.now();
|
|
1013
|
+
this.lastAcknowledgedUserInputAt = receivedAt;
|
|
1014
|
+
const dedupKey = `user_input_ack:${crypto
|
|
1015
|
+
.createHash('sha256')
|
|
1016
|
+
.update(`${this.instanceId}:${content}:${receivedAt}`)
|
|
1017
|
+
.digest('hex')
|
|
1018
|
+
.slice(0, 24)}`;
|
|
1019
|
+
this.appendRuntimeMessage(buildChatMessage({
|
|
1020
|
+
role: 'user',
|
|
1021
|
+
senderName: 'User',
|
|
1022
|
+
kind: 'standard',
|
|
1023
|
+
content,
|
|
1024
|
+
receivedAt,
|
|
1025
|
+
timestamp: receivedAt,
|
|
1026
|
+
source: 'runtime_input_ack',
|
|
1027
|
+
meta: {
|
|
1028
|
+
runtimeInputAck: true,
|
|
1029
|
+
provider: this.type,
|
|
1030
|
+
workspace: this.workingDir,
|
|
1031
|
+
},
|
|
1032
|
+
} as ChatMessage), dedupKey);
|
|
1033
|
+
}
|
|
1034
|
+
|
|
698
1035
|
dispose(): void {
|
|
699
1036
|
this.adapter.shutdown();
|
|
700
1037
|
this.monitor.reset();
|
|
1038
|
+
// Cancel any armed auto-approve timers so a pending settle re-check
|
|
1039
|
+
// can't fire resolveModal/detectStatusTransition against a dead adapter.
|
|
1040
|
+
if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
|
|
1041
|
+
if (this.autoApproveBusyTimer) { clearTimeout(this.autoApproveBusyTimer); this.autoApproveBusyTimer = null; }
|
|
701
1042
|
this.appliedEffectKeys.clear();
|
|
702
1043
|
try { this.cachedSqliteDb?.close(); } catch { /* noop */ }
|
|
703
1044
|
this.cachedSqliteDb = null;
|
|
@@ -706,6 +1047,7 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
706
1047
|
|
|
707
1048
|
private completedDebounceTimer: NodeJS.Timeout | null = null;
|
|
708
1049
|
private completedDebouncePending: CompletedDebouncePending | null = null;
|
|
1050
|
+
private lastExternalCompletionProbe: ExternalTranscriptProbe | null = null;
|
|
709
1051
|
|
|
710
1052
|
private async enforceFreshSessionLaunchIfNeeded(): Promise<void> {
|
|
711
1053
|
const scriptName = getForcedNewSessionScriptName(this.provider, this.launchMode);
|
|
@@ -740,7 +1082,180 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
740
1082
|
const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
|
|
741
1083
|
const role = typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : '';
|
|
742
1084
|
const content = lastVisible ? flattenContent(lastVisible.content).trim() : '';
|
|
743
|
-
|
|
1085
|
+
if (role !== 'assistant' || !content) return false;
|
|
1086
|
+
// Guard: if the last assistant message looks like an active approval/input prompt,
|
|
1087
|
+
// it is not a real completion — the session is still awaiting user input.
|
|
1088
|
+
if (looksLikeActiveApprovalPromptText(content)) return false;
|
|
1089
|
+
return true;
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
private buildExternalTranscriptProbe(messages: unknown[], sourcePath?: string, sourceMtimeMs?: number): ExternalTranscriptProbe {
|
|
1093
|
+
const visibleMessages = messages.filter((message: any) => isUserFacingChatMessage(message as ChatMessage));
|
|
1094
|
+
const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
|
|
1095
|
+
const readAt = Date.now();
|
|
1096
|
+
const mtimeMs = Number(sourceMtimeMs) || 0;
|
|
1097
|
+
return {
|
|
1098
|
+
readAt,
|
|
1099
|
+
msgCount: messages.length,
|
|
1100
|
+
lastRole: typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : null,
|
|
1101
|
+
lastKind: typeof (lastVisible as any)?.kind === 'string' ? (lastVisible as any).kind : null,
|
|
1102
|
+
contentLen: lastVisible ? flattenContent(lastVisible.content).trim().length : 0,
|
|
1103
|
+
sourcePath: typeof sourcePath === 'string' && sourcePath ? sourcePath : null,
|
|
1104
|
+
sourceMtimeMs: mtimeMs || null,
|
|
1105
|
+
mtimeAgeMs: mtimeMs ? Math.max(0, readAt - mtimeMs) : null,
|
|
1106
|
+
};
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
private recordPendingTranscriptProbe(pending: CompletedDebouncePending): ExternalTranscriptProbe | null {
|
|
1110
|
+
const probe = this.lastExternalCompletionProbe;
|
|
1111
|
+
if (!probe) return null;
|
|
1112
|
+
const history = pending.transcriptProbeHistory || [];
|
|
1113
|
+
const last = history[history.length - 1];
|
|
1114
|
+
if (!last || last.readAt !== probe.readAt || last.msgCount !== probe.msgCount || last.lastRole !== probe.lastRole || last.contentLen !== probe.contentLen) {
|
|
1115
|
+
history.push(probe);
|
|
1116
|
+
pending.transcriptProbeHistory = history.slice(-5);
|
|
1117
|
+
}
|
|
1118
|
+
return probe;
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
private readExternalCompletionMessages(): unknown[] | null {
|
|
1122
|
+
const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
|
|
1123
|
+
if (!adapterOwnsMessagesElsewhere) return null;
|
|
1124
|
+
if (!this.providerSessionId) return null;
|
|
1125
|
+
if (!isNativeSourceCanonicalHistory(this.provider.nativeHistory)) return null;
|
|
1126
|
+
|
|
1127
|
+
if (this.lastExternalCompletionProbe?.sourcePath) {
|
|
1128
|
+
try { fs.statSync(this.lastExternalCompletionProbe.sourcePath); } catch { /* best-effort metadata refresh */ }
|
|
1129
|
+
}
|
|
1130
|
+
const restoredHistory = readProviderChatHistory(this.type, {
|
|
1131
|
+
canonicalHistory: this.provider.nativeHistory,
|
|
1132
|
+
historySessionId: this.providerSessionId,
|
|
1133
|
+
workspace: this.workingDir,
|
|
1134
|
+
offset: 0,
|
|
1135
|
+
limit: Number.MAX_SAFE_INTEGER,
|
|
1136
|
+
historyBehavior: this.provider.historyBehavior,
|
|
1137
|
+
scripts: this.provider.scripts as any,
|
|
1138
|
+
sessionStartedAtMs: this.startedAt,
|
|
1139
|
+
forceRefresh: true,
|
|
1140
|
+
});
|
|
1141
|
+
if (restoredHistory.source !== 'provider-native') {
|
|
1142
|
+
this.lastExternalCompletionProbe = null;
|
|
1143
|
+
return null;
|
|
1144
|
+
}
|
|
1145
|
+
this.lastExternalCompletionProbe = this.buildExternalTranscriptProbe(
|
|
1146
|
+
restoredHistory.messages,
|
|
1147
|
+
restoredHistory.sourcePath,
|
|
1148
|
+
restoredHistory.sourceMtimeMs,
|
|
1149
|
+
);
|
|
1150
|
+
return restoredHistory.messages;
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
private completionFinalAssistantEvidence(parsedMessages: unknown): CompletionFinalAssistantEvidence {
|
|
1154
|
+
if (this.completionHasFinalAssistantMessage(parsedMessages)) {
|
|
1155
|
+
return {
|
|
1156
|
+
present: true,
|
|
1157
|
+
messages: Array.isArray(parsedMessages) ? parsedMessages : [],
|
|
1158
|
+
source: 'parsed',
|
|
1159
|
+
};
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
const externalMessages = this.readExternalCompletionMessages();
|
|
1163
|
+
if (externalMessages) {
|
|
1164
|
+
return {
|
|
1165
|
+
present: this.completionHasFinalAssistantMessage(externalMessages),
|
|
1166
|
+
messages: externalMessages,
|
|
1167
|
+
source: 'external-native',
|
|
1168
|
+
};
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
return {
|
|
1172
|
+
present: false,
|
|
1173
|
+
messages: Array.isArray(parsedMessages) ? parsedMessages : [],
|
|
1174
|
+
source: 'unavailable',
|
|
1175
|
+
};
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
private completionFinalSummary(parsedMessages: unknown): string | undefined {
|
|
1179
|
+
// For native-source providers (claude-cli: chatMessagesOwnedExternally), the PTY
|
|
1180
|
+
// screen parse is NOT the source of truth for the final summary — the terminal
|
|
1181
|
+
// wraps/scrolls/clips text, so a screen-parsed assistant message is often a partial
|
|
1182
|
+
// prefix (e.g. 76 chars of a 112-char turn). The append-only native transcript holds
|
|
1183
|
+
// the complete turn. Prefer it whenever it yields a longer/complete summary; fall back
|
|
1184
|
+
// to the parsed screen only when the transcript is unavailable. This is the real cause
|
|
1185
|
+
// of the truncated finalSummary — independent of cloud vs standalone (it surfaces on
|
|
1186
|
+
// any short, fast-completing task where screen parse wins the race).
|
|
1187
|
+
const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
|
|
1188
|
+
const parsedSummary = extractFinalSummaryFromMessages(
|
|
1189
|
+
(this.completionHasFinalAssistantMessage(parsedMessages)
|
|
1190
|
+
? (Array.isArray(parsedMessages) ? parsedMessages : [])
|
|
1191
|
+
: []) as any,
|
|
1192
|
+
);
|
|
1193
|
+
if (adapterOwnsMessagesElsewhere) {
|
|
1194
|
+
const externalMessages = this.readExternalCompletionMessages();
|
|
1195
|
+
const externalSummary = externalMessages
|
|
1196
|
+
? extractFinalSummaryFromMessages(externalMessages as any)
|
|
1197
|
+
: '';
|
|
1198
|
+
// The transcript is authoritative for native-source providers. Use it unless it is
|
|
1199
|
+
// empty (not yet written) — only then fall back to whatever the screen parsed.
|
|
1200
|
+
if (externalSummary) return externalSummary;
|
|
1201
|
+
return parsedSummary || undefined;
|
|
1202
|
+
}
|
|
1203
|
+
return parsedSummary || undefined;
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
private buildCompletedFinalizationDiagnostic(args: {
|
|
1207
|
+
blockReason: string;
|
|
1208
|
+
latestStatus?: any;
|
|
1209
|
+
latestVisibleStatus: string;
|
|
1210
|
+
waitedMs: number;
|
|
1211
|
+
pending: CompletedDebouncePending;
|
|
1212
|
+
emittedAfterFinalizationTimeout: boolean;
|
|
1213
|
+
}): Record<string, unknown> {
|
|
1214
|
+
let parsed: any = null;
|
|
1215
|
+
let parseError: string | undefined;
|
|
1216
|
+
try {
|
|
1217
|
+
parsed = this.adapter.getScriptParsedStatus();
|
|
1218
|
+
} catch (error: any) {
|
|
1219
|
+
parseError = error?.message || String(error);
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
const evidence = this.completionFinalAssistantEvidence(parsed?.messages);
|
|
1223
|
+
if (evidence.source === 'external-native') {
|
|
1224
|
+
this.recordPendingTranscriptProbe(args.pending);
|
|
1225
|
+
}
|
|
1226
|
+
const visibleMessages = (Array.isArray(evidence.messages) ? evidence.messages : [])
|
|
1227
|
+
.filter((message: any) => isUserFacingChatMessage(message as ChatMessage));
|
|
1228
|
+
const lastVisible = visibleMessages[visibleMessages.length - 1] as ChatMessage | undefined;
|
|
1229
|
+
const lastVisibleRole = typeof lastVisible?.role === 'string' ? lastVisible.role.trim().toLowerCase() : null;
|
|
1230
|
+
const lastVisibleKind = typeof (lastVisible as any)?.kind === 'string' ? (lastVisible as any).kind : null;
|
|
1231
|
+
const lastVisibleContentLength = lastVisible ? flattenContent(lastVisible.content).trim().length : 0;
|
|
1232
|
+
|
|
1233
|
+
return {
|
|
1234
|
+
providerType: this.type,
|
|
1235
|
+
sessionId: this.instanceId,
|
|
1236
|
+
providerSessionId: this.providerSessionId || null,
|
|
1237
|
+
workspace: this.workingDir,
|
|
1238
|
+
blockReason: args.blockReason,
|
|
1239
|
+
emittedAfterFinalizationTimeout: args.emittedAfterFinalizationTimeout,
|
|
1240
|
+
waitedMs: args.waitedMs,
|
|
1241
|
+
maxWaitMs: COMPLETED_FINALIZATION_MAX_WAIT_MS,
|
|
1242
|
+
adapterStatus: typeof args.latestStatus?.status === 'string' ? args.latestStatus.status : null,
|
|
1243
|
+
latestVisibleStatus: args.latestVisibleStatus,
|
|
1244
|
+
parsedStatus: typeof parsed?.status === 'string' ? parsed.status : (parseError ? 'parse_error' : 'unknown'),
|
|
1245
|
+
parseError: parseError || undefined,
|
|
1246
|
+
finalAssistantPresent: evidence.present,
|
|
1247
|
+
finalAssistantEvidenceSource: evidence.source,
|
|
1248
|
+
visibleMessageCount: visibleMessages.length,
|
|
1249
|
+
lastVisibleRole,
|
|
1250
|
+
lastVisibleKind,
|
|
1251
|
+
lastVisibleContentLength,
|
|
1252
|
+
pendingStartedAt: this.generatingStartedAt || null,
|
|
1253
|
+
pendingFirstObservedAt: args.pending.firstObservedAt,
|
|
1254
|
+
pendingTimestamp: args.pending.timestamp,
|
|
1255
|
+
pendingDurationSec: args.pending.duration,
|
|
1256
|
+
previousBlockReason: args.pending.loggedBlockReason || null,
|
|
1257
|
+
transcriptProbeHistory: args.pending.transcriptProbeHistory || [],
|
|
1258
|
+
};
|
|
744
1259
|
}
|
|
745
1260
|
|
|
746
1261
|
private hasAdapterPendingResponse(): boolean {
|
|
@@ -765,32 +1280,97 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
765
1280
|
if (!isCliGeneratingLikeStatus(parsedRawStatus)) return false;
|
|
766
1281
|
if (adapterRawStatus !== 'idle') return false;
|
|
767
1282
|
if (hasNonEmptyCliModalButtons(parsedStatus?.activeModal ?? parsedStatus?.modal)) return false;
|
|
768
|
-
|
|
1283
|
+
if (this.hasAdapterPendingResponse()) return false;
|
|
1284
|
+
// Do not suppress when the adapter's raw response buffer is still non-empty.
|
|
1285
|
+
// This catches the case where isWaitingForResponse has already flipped to false
|
|
1286
|
+
// (so getPartialResponse() returns '') but the provider's native parser still
|
|
1287
|
+
// reports generating because it's parsing buffered content. Suppressing the
|
|
1288
|
+
// finalization block here would emit a false completion event while the provider
|
|
1289
|
+
// session is still actively processing its response stream.
|
|
1290
|
+
const adapterAny = this.adapter as any;
|
|
1291
|
+
if (typeof adapterAny?.responseBuffer === 'string' && adapterAny.responseBuffer.trim()) return false;
|
|
1292
|
+
return true;
|
|
769
1293
|
}
|
|
770
1294
|
|
|
771
|
-
private
|
|
772
|
-
if (latestVisibleStatus !== 'idle') return `status:${latestVisibleStatus}
|
|
1295
|
+
private getCompletedFinalizationBlock(latestVisibleStatus: string, pending: CompletedDebouncePending): CompletedFinalizationBlock | null {
|
|
1296
|
+
if (latestVisibleStatus !== 'idle') return { reason: `status:${latestVisibleStatus}`, terminal: true };
|
|
773
1297
|
|
|
774
1298
|
const adapterAny = this.adapter as any;
|
|
775
|
-
|
|
776
|
-
if (
|
|
1299
|
+
const approvalResolvedIdle = pending.previousStatus === 'waiting_approval';
|
|
1300
|
+
if (!approvalResolvedIdle) {
|
|
1301
|
+
if (adapterAny?.isWaitingForResponse === true) return { reason: 'adapter_waiting_for_response', terminal: true };
|
|
1302
|
+
if (adapterAny?.currentTurnScope) return { reason: 'adapter_turn_scope_active', terminal: true };
|
|
1303
|
+
if (this.hasAdapterPendingResponse()) return { reason: 'adapter_pending_response', terminal: true };
|
|
1304
|
+
}
|
|
777
1305
|
|
|
778
1306
|
const partial = typeof this.adapter.getPartialResponse === 'function'
|
|
779
1307
|
? this.adapter.getPartialResponse()
|
|
780
1308
|
: '';
|
|
781
|
-
if (typeof partial === 'string' && partial.trim()) return 'partial_response_pending';
|
|
1309
|
+
if (typeof partial === 'string' && partial.trim()) return { reason: 'partial_response_pending', terminal: true };
|
|
782
1310
|
|
|
783
1311
|
let parsed: any;
|
|
784
1312
|
try {
|
|
785
1313
|
parsed = this.adapter.getScriptParsedStatus();
|
|
786
1314
|
} catch (error: any) {
|
|
787
|
-
return `parse_error:${error?.message || String(error)}
|
|
1315
|
+
return { reason: `parse_error:${error?.message || String(error)}` };
|
|
788
1316
|
}
|
|
789
1317
|
|
|
790
1318
|
const parsedStatus = typeof parsed?.status === 'string' ? parsed.status : 'unknown';
|
|
791
|
-
if (parsedStatus !== 'idle')
|
|
792
|
-
|
|
793
|
-
|
|
1319
|
+
if (parsedStatus !== 'idle') {
|
|
1320
|
+
const adapterStatus = this.adapter.getStatus({ allowParse: false });
|
|
1321
|
+
if (this.shouldSuppressStaleParsedBusyStatus(parsed, adapterStatus)) return null;
|
|
1322
|
+
return { reason: `parsed_status:${parsedStatus}`, terminal: isCliGeneratingLikeStatus(parsedStatus) };
|
|
1323
|
+
}
|
|
1324
|
+
if (parsed?.activeModal || parsed?.modal) return { reason: 'parsed_modal_active', terminal: true };
|
|
1325
|
+
const adapterOwnsMessagesElsewhere = (this.adapter as any)?.chatMessagesOwnedExternally === true;
|
|
1326
|
+
const finalAssistantEvidence = this.completionFinalAssistantEvidence(parsed?.messages);
|
|
1327
|
+
const allowMissingAssistantTimeout = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
|
|
1328
|
+
LOG.debug('CLI', `[${this.type}] finalAssistantEvidence: present=${finalAssistantEvidence.present} source=${finalAssistantEvidence.source} adapterOwnsMessagesElsewhere=${adapterOwnsMessagesElsewhere} parsedStatus=${parsedStatus}`);
|
|
1329
|
+
if (!finalAssistantEvidence.present) {
|
|
1330
|
+
if (adapterOwnsMessagesElsewhere) {
|
|
1331
|
+
if (finalAssistantEvidence.source === 'external-native') {
|
|
1332
|
+
const probe = this.recordPendingTranscriptProbe(pending);
|
|
1333
|
+
if (probe && !pending.loggedTranscriptProbe) {
|
|
1334
|
+
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`);
|
|
1335
|
+
pending.loggedTranscriptProbe = true;
|
|
1336
|
+
}
|
|
1337
|
+
LOG.debug('CLI', `[${this.type}] external-native probe result: lastRole=${probe?.lastRole} contentLen=${probe?.contentLen}`);
|
|
1338
|
+
if (probe?.lastRole === 'assistant' && (probe.contentLen ?? 0) > 0) {
|
|
1339
|
+
return null;
|
|
1340
|
+
}
|
|
1341
|
+
if (this.type === 'antigravity-cli') {
|
|
1342
|
+
return null;
|
|
1343
|
+
}
|
|
1344
|
+
return { reason: 'missing_final_assistant', terminal: true, allowTimeout: allowMissingAssistantTimeout };
|
|
1345
|
+
}
|
|
1346
|
+
if ((this.provider as any).requiresFinalAssistantBeforeIdle === true) {
|
|
1347
|
+
return { reason: 'missing_final_assistant', terminal: true, allowTimeout: allowMissingAssistantTimeout };
|
|
1348
|
+
}
|
|
1349
|
+
} else {
|
|
1350
|
+
LOG.debug('CLI', `[${this.type}] missing_final_assistant (not ownsExternal) requiresFinalAssistant=${!!(this.provider as any).requiresFinalAssistantBeforeIdle}`);
|
|
1351
|
+
return {
|
|
1352
|
+
reason: 'missing_final_assistant',
|
|
1353
|
+
terminal: (this.provider as any).requiresFinalAssistantBeforeIdle === true,
|
|
1354
|
+
allowTimeout: allowMissingAssistantTimeout,
|
|
1355
|
+
};
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
// Guard: if the screen still shows an approval/choice prompt as the last visible text,
|
|
1360
|
+
// the turn is not complete even if the parsed status says idle and there is an assistant
|
|
1361
|
+
// message. This catches the case where waiting_approval→idle transitions occur before
|
|
1362
|
+
// the modal has been resolved (e.g. the PTY rendered the prompt but no button press fired).
|
|
1363
|
+
try {
|
|
1364
|
+
const screenText = typeof (this.adapter as any).getScreenText === 'function'
|
|
1365
|
+
? String((this.adapter as any).getScreenText() || '')
|
|
1366
|
+
: '';
|
|
1367
|
+
if (screenText) {
|
|
1368
|
+
const tailLines = screenText.split(/\r?\n/).slice(-16).join('\n');
|
|
1369
|
+
if (looksLikeActiveApprovalPromptText(tailLines)) {
|
|
1370
|
+
return { reason: 'screen_shows_approval_prompt', terminal: approvalResolvedIdle };
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
} catch { /* defensive: screen text read is best-effort */ }
|
|
794
1374
|
|
|
795
1375
|
return null;
|
|
796
1376
|
}
|
|
@@ -809,7 +1389,8 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
809
1389
|
|
|
810
1390
|
const latestStatus = this.adapter.getStatus({ allowParse: false });
|
|
811
1391
|
const latestAutoApproveActive = latestStatus.status === 'waiting_approval' && this.shouldAutoApprove();
|
|
812
|
-
const latestVisibleStatus = latestAutoApproveActive ? 'generating' : latestStatus.status;
|
|
1392
|
+
const latestVisibleStatus = latestAutoApproveActive || this.autoApproveBusy ? 'generating' : latestStatus.status;
|
|
1393
|
+
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
1394
|
if (latestVisibleStatus !== 'idle') {
|
|
814
1395
|
LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed ${latestVisibleStatus})`);
|
|
815
1396
|
this.completedDebouncePending = null;
|
|
@@ -817,10 +1398,12 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
817
1398
|
return;
|
|
818
1399
|
}
|
|
819
1400
|
|
|
820
|
-
const
|
|
821
|
-
if (
|
|
1401
|
+
const block = this.getCompletedFinalizationBlock(latestVisibleStatus, pending);
|
|
1402
|
+
if (block) {
|
|
1403
|
+
const blockReason = block.reason;
|
|
822
1404
|
const waitedMs = Date.now() - pending.firstObservedAt;
|
|
823
|
-
|
|
1405
|
+
LOG.debug('CLI', `[${this.type}] finalization block: reason=${blockReason} terminal=${block.terminal} waitedMs=${waitedMs} maxWait=${COMPLETED_FINALIZATION_MAX_WAIT_MS}`);
|
|
1406
|
+
if ((block.terminal && !block.allowTimeout) || waitedMs < COMPLETED_FINALIZATION_MAX_WAIT_MS) {
|
|
824
1407
|
if (pending.loggedBlockReason !== blockReason) {
|
|
825
1408
|
LOG.info('CLI', `[${this.type}] waiting to emit completed until transcript finalizes (${blockReason})`);
|
|
826
1409
|
pending.loggedBlockReason = blockReason;
|
|
@@ -828,10 +1411,36 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
828
1411
|
this.scheduleCompletedDebounceFlush(COMPLETED_FINALIZATION_RETRY_MS);
|
|
829
1412
|
return;
|
|
830
1413
|
}
|
|
831
|
-
|
|
1414
|
+
const completionDiagnostic = this.buildCompletedFinalizationDiagnostic({
|
|
1415
|
+
blockReason,
|
|
1416
|
+
latestStatus,
|
|
1417
|
+
latestVisibleStatus,
|
|
1418
|
+
waitedMs,
|
|
1419
|
+
pending,
|
|
1420
|
+
emittedAfterFinalizationTimeout: true,
|
|
1421
|
+
});
|
|
1422
|
+
LOG.warn('CLI', `[${this.type}] emitting completed event after ${waitedMs}ms without finalized assistant turn (${blockReason})`);
|
|
1423
|
+
this.pushEvent({
|
|
1424
|
+
event: 'agent:generating_completed',
|
|
1425
|
+
chatTitle: pending.chatTitle,
|
|
1426
|
+
duration: pending.duration,
|
|
1427
|
+
timestamp: pending.timestamp,
|
|
1428
|
+
// When finalization is forced past the timeout on a `parsed_status:` block
|
|
1429
|
+
// (the parser never confirmed a final assistant turn) we previously rode an
|
|
1430
|
+
// empty `finalSummary` unconditionally. That empty value propagates to the
|
|
1431
|
+
// mesh coordinator's mirror preview (meshSessionLastMessagePreview), leaving a
|
|
1432
|
+
// delegated session's inbox preview blank — or, for a LOCAL worktree session,
|
|
1433
|
+
// stuck on the dispatched user task. If the parser DID surface assistant text,
|
|
1434
|
+
// prefer it; only fall back to '' when no assistant summary can be derived.
|
|
1435
|
+
finalSummary: blockReason.startsWith('parsed_status:')
|
|
1436
|
+
? (this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages) ?? '')
|
|
1437
|
+
: this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages),
|
|
1438
|
+
completionDiagnostic,
|
|
1439
|
+
});
|
|
832
1440
|
this.completedDebouncePending = null;
|
|
833
1441
|
this.completedDebounceTimer = null;
|
|
834
1442
|
this.generatingStartedAt = 0;
|
|
1443
|
+
this.lastApprovalEventFingerprint = '';
|
|
835
1444
|
return;
|
|
836
1445
|
}
|
|
837
1446
|
|
|
@@ -841,11 +1450,12 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
841
1450
|
chatTitle: pending.chatTitle,
|
|
842
1451
|
duration: pending.duration,
|
|
843
1452
|
timestamp: pending.timestamp,
|
|
844
|
-
finalSummary:
|
|
1453
|
+
finalSummary: this.completionFinalSummary(this.adapter?.getScriptParsedStatus()?.messages),
|
|
845
1454
|
});
|
|
846
1455
|
this.completedDebouncePending = null;
|
|
847
1456
|
this.completedDebounceTimer = null;
|
|
848
1457
|
this.generatingStartedAt = 0;
|
|
1458
|
+
this.lastApprovalEventFingerprint = '';
|
|
849
1459
|
}
|
|
850
1460
|
|
|
851
1461
|
private maybeAutoApproveStatus(adapterStatus: any, now = Date.now()): boolean {
|
|
@@ -853,48 +1463,168 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
853
1463
|
// Guard re-entry: onStatusChange/getState can observe the same modal multiple
|
|
854
1464
|
// times while the PTY absorbs the approval key. Without this flag, repeated
|
|
855
1465
|
// snapshots would write stray keys into the input once the modal dismisses.
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
this.
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
1466
|
+
// However, Claude Code can present a second approval immediately after the
|
|
1467
|
+
// first. Resolve a changed modal signature even while the previous write is
|
|
1468
|
+
// still inside the short busy window.
|
|
1469
|
+
if (!autoApproveActive) {
|
|
1470
|
+
this.lastAutoApprovalSignature = '';
|
|
1471
|
+
// Clear the settle gate so the next approval starts its own quiet
|
|
1472
|
+
// window from scratch (a stale timestamp would let it fire instantly).
|
|
1473
|
+
this.pendingAutoApprovalSignature = '';
|
|
1474
|
+
this.pendingAutoApprovalSince = 0;
|
|
1475
|
+
if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
|
|
1476
|
+
return autoApproveActive;
|
|
1477
|
+
}
|
|
1478
|
+
const modal = adapterStatus.activeModal;
|
|
1479
|
+
// (fix) Do not auto-approve when no concrete modal/buttons are present.
|
|
1480
|
+
// Claude TUI flaps between paints; without this guard adapterStatus
|
|
1481
|
+
// could report status=waiting_approval with activeModal=null (or with
|
|
1482
|
+
// an empty buttons array briefly) and we'd still call
|
|
1483
|
+
// resolveModal(-1) — which used to type "1" into the prompt
|
|
1484
|
+
// repeatedly. Skip until a real modal is captured.
|
|
1485
|
+
const buttons = Array.isArray(modal?.buttons)
|
|
1486
|
+
? modal.buttons.map((b: any) => String(b || '').trim()).filter(Boolean)
|
|
1487
|
+
: [];
|
|
1488
|
+
if (!modal || buttons.length === 0) {
|
|
1489
|
+
return autoApproveActive;
|
|
1490
|
+
}
|
|
1491
|
+
const { index: buttonIndex, label: buttonLabel } = pickAutoApprovalButton(buttons);
|
|
1492
|
+
if (buttonIndex < 0) {
|
|
1493
|
+
// No concrete button matched — don't pick a random index, just
|
|
1494
|
+
// surface the modal so the user can decide.
|
|
1495
|
+
return autoApproveActive;
|
|
1496
|
+
}
|
|
1497
|
+
// Include the FSM's approval entry seq: two distinct back-to-back
|
|
1498
|
+
// approvals can carry identical message/buttons (common with
|
|
1499
|
+
// claude-cli). Without the seq their signatures collide and the 5s
|
|
1500
|
+
// busy-window re-entry guard below swallows the second auto-approve,
|
|
1501
|
+
// leaving it stuck. The seq is bumped by the FSM on every fresh
|
|
1502
|
+
// waiting_approval entry, so a new approval always yields a new
|
|
1503
|
+
// signature and fires through.
|
|
1504
|
+
const approvalEntrySeq = typeof adapterStatus?.approvalEntrySeq === 'number'
|
|
1505
|
+
? adapterStatus.approvalEntrySeq
|
|
1506
|
+
: 0;
|
|
1507
|
+
const signature = [
|
|
1508
|
+
approvalEntrySeq,
|
|
1509
|
+
typeof modal?.message === 'string' ? modal.message.trim() : '',
|
|
1510
|
+
buttons.join('|'),
|
|
1511
|
+
buttonIndex,
|
|
1512
|
+
].join('::');
|
|
1513
|
+
// Already fired for this exact modal and still inside the busy window —
|
|
1514
|
+
// nothing to do (re-entry guard for repeated snapshots of one modal).
|
|
1515
|
+
if (this.autoApproveBusy && signature === this.lastAutoApprovalSignature) {
|
|
1516
|
+
return autoApproveActive;
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
// Settle gate: only fire once this exact signature has been stable for
|
|
1520
|
+
// AUTO_APPROVE_SETTLE_MS. A still-streaming prompt mutates its
|
|
1521
|
+
// message/buttons each frame → new signature → clock restarts, so we
|
|
1522
|
+
// never approve a half-rendered prompt (the "resolves too fast" bug).
|
|
1523
|
+
if (signature !== this.pendingAutoApprovalSignature) {
|
|
1524
|
+
this.pendingAutoApprovalSignature = signature;
|
|
1525
|
+
this.pendingAutoApprovalSince = now;
|
|
1526
|
+
}
|
|
1527
|
+
const settledForMs = now - this.pendingAutoApprovalSince;
|
|
1528
|
+
if (settledForMs < CliProviderInstance.AUTO_APPROVE_SETTLE_MS) {
|
|
1529
|
+
// Not yet settled. Arm a timer to re-check after the remaining quiet
|
|
1530
|
+
// window — the PTY may go silent once the prompt finishes painting,
|
|
1531
|
+
// so there is no guaranteed status-change frame to re-drive us.
|
|
1532
|
+
if (this.autoApproveSettleTimer) clearTimeout(this.autoApproveSettleTimer);
|
|
1533
|
+
this.autoApproveSettleTimer = setTimeout(() => {
|
|
1534
|
+
this.autoApproveSettleTimer = null;
|
|
1535
|
+
this.recheckAutoApproveSettled();
|
|
1536
|
+
}, CliProviderInstance.AUTO_APPROVE_SETTLE_MS - settledForMs + 20);
|
|
1537
|
+
return autoApproveActive;
|
|
869
1538
|
}
|
|
1539
|
+
|
|
1540
|
+
// Settled — fire the approve key.
|
|
1541
|
+
if (this.autoApproveSettleTimer) { clearTimeout(this.autoApproveSettleTimer); this.autoApproveSettleTimer = null; }
|
|
1542
|
+
this.autoApproveBusy = true;
|
|
1543
|
+
this.lastAutoApprovalSignature = signature;
|
|
1544
|
+
this.pendingAutoApprovalSignature = '';
|
|
1545
|
+
this.pendingAutoApprovalSince = 0;
|
|
1546
|
+
if (this.autoApproveBusyTimer) clearTimeout(this.autoApproveBusyTimer);
|
|
1547
|
+
this.autoApproveBusyTimer = setTimeout(() => {
|
|
1548
|
+
this.autoApproveBusy = false;
|
|
1549
|
+
this.autoApproveBusyTimer = null;
|
|
1550
|
+
this.lastAutoApprovalSignature = '';
|
|
1551
|
+
}, 5000);
|
|
1552
|
+
this.recordAutoApproval(modal?.message, buttonLabel, now);
|
|
1553
|
+
setTimeout(() => {
|
|
1554
|
+
this.adapter.resolveModal(buttonIndex);
|
|
1555
|
+
}, 0);
|
|
870
1556
|
return autoApproveActive;
|
|
871
1557
|
}
|
|
872
1558
|
|
|
1559
|
+
/**
|
|
1560
|
+
* Re-drive the auto-approve check after the settle quiet window elapses.
|
|
1561
|
+
* The PTY may have gone silent once the approval prompt finished painting,
|
|
1562
|
+
* so no status-change frame is guaranteed to re-enter maybeAutoApproveStatus
|
|
1563
|
+
* — this timer-driven re-check picks up the now-settled modal and fires.
|
|
1564
|
+
* Deliberately lighter than detectStatusTransition(): it only re-evaluates
|
|
1565
|
+
* the approval decision; the next real PTY frame refreshes visible status.
|
|
1566
|
+
*/
|
|
1567
|
+
private recheckAutoApproveSettled(): void {
|
|
1568
|
+
try {
|
|
1569
|
+
const adapterStatus = this.adapter.getStatus({ allowParse: false });
|
|
1570
|
+
this.maybeAutoApproveStatus(adapterStatus, Date.now());
|
|
1571
|
+
} catch { /* adapter gone / transient — next frame retries */ }
|
|
1572
|
+
}
|
|
1573
|
+
|
|
873
1574
|
private detectStatusTransition(): void {
|
|
874
1575
|
const now = Date.now();
|
|
875
1576
|
// Status-change handling is a hot path: PTY output can fire it many times
|
|
876
1577
|
// during long-running CLI sessions. Keep this path on adapter-owned light
|
|
877
1578
|
// state only; rich provider parsing is reserved for getState/read_chat.
|
|
878
1579
|
const adapterStatus = this.adapter.getStatus({ allowParse: false });
|
|
1580
|
+
const adapterProviderSessionId = normalizeProviderSessionId(
|
|
1581
|
+
this.provider,
|
|
1582
|
+
typeof adapterStatus?.providerSessionId === 'string' ? adapterStatus.providerSessionId : '',
|
|
1583
|
+
);
|
|
1584
|
+
if (adapterProviderSessionId) {
|
|
1585
|
+
this.promoteProviderSessionId(adapterProviderSessionId);
|
|
1586
|
+
}
|
|
879
1587
|
const parsedStatus = null;
|
|
880
1588
|
const rawStatus = adapterStatus.status;
|
|
881
1589
|
const autoApproveActive = this.maybeAutoApproveStatus(adapterStatus, now);
|
|
882
|
-
|
|
883
|
-
|
|
1590
|
+
// During the autoApproveBusy window (2s after firing approval key), the PTY
|
|
1591
|
+
// can briefly report 'idle' before the next generating phase starts. Treat that
|
|
1592
|
+
// transient idle as 'generating' to suppress a spurious agent:generating_completed
|
|
1593
|
+
// push notification. The adapter's status is otherwise authoritative — native
|
|
1594
|
+
// transcript shape does NOT override the FSM's busy/idle decision.
|
|
1595
|
+
const autoApproveHoldIdle = this.autoApproveBusy && rawStatus === 'idle';
|
|
1596
|
+
const newStatus = autoApproveActive || autoApproveHoldIdle ? 'generating' : rawStatus;
|
|
1597
|
+
const dirName = workingDirBasename(this.workingDir);
|
|
884
1598
|
const chatTitle = `${this.provider.name} · ${dirName}`;
|
|
885
1599
|
const partial = this.adapter.getPartialResponse();
|
|
1600
|
+
// Liveness fingerprint for the no-progress watchdog. The parsed
|
|
1601
|
+
// assistant buffer (`partial`) alone goes static while a tool/build runs
|
|
1602
|
+
// — the assistant emits no tokens even though the PTY is actively
|
|
1603
|
+
// printing tool output — which made the watchdog false-fire a "stuck"
|
|
1604
|
+
// alert mid-turn. Fold in the adapter's raw-activity timestamps so any
|
|
1605
|
+
// visible terminal progress (lastScreenChangeAt) or raw PTY byte
|
|
1606
|
+
// (lastOutputAt) keeps the fingerprint moving. The watchdog then only
|
|
1607
|
+
// survives a genuine stall where nothing at all is happening.
|
|
886
1608
|
const progressFingerprint = newStatus === 'generating'
|
|
887
|
-
? `${partial || ''}`.slice(-2000)
|
|
1609
|
+
? `${`${partial || ''}`.slice(-2000)}::scr=${adapterStatus.lastScreenChangeAt ?? 0}::out=${adapterStatus.lastOutputAt ?? 0}`
|
|
888
1610
|
: undefined;
|
|
889
1611
|
|
|
890
1612
|
const previousStatus = this.lastStatus;
|
|
891
1613
|
if (newStatus !== this.lastStatus) {
|
|
892
1614
|
LOG.info('CLI', `[${this.type}] status: ${this.lastStatus} → ${newStatus}`);
|
|
893
1615
|
if (this.lastStatus === 'idle' && newStatus === 'generating') {
|
|
1616
|
+
// If a completion event is already pending and the turn has ended
|
|
1617
|
+
// (generatingStartedAt===0), the PTY is painting its prompt area
|
|
1618
|
+
// after completing. Ignore this blip — do not cancel the pending
|
|
1619
|
+
// completion and do not advance lastStatus to generating.
|
|
1620
|
+
if (this.completedDebouncePending && this.generatingStartedAt === 0) {
|
|
1621
|
+
LOG.debug('CLI', `[${this.type}] ignoring post-completion PTY generating blip (generatingStartedAt=0)`);
|
|
1622
|
+
return;
|
|
1623
|
+
}
|
|
894
1624
|
this.suppressIdleHistoryReplay = false;
|
|
895
1625
|
// Cancel any pending completed event (multi-step: idle→generating resume)
|
|
896
1626
|
if (this.completedDebouncePending) {
|
|
897
|
-
LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed generating)`);
|
|
1627
|
+
LOG.info('CLI', `[${this.type}] cancelled pending completed (resumed generating) generatingStartedAt=${this.generatingStartedAt} isWaitingForResponse=${!!(this.adapter as any)?.isWaitingForResponse}`);
|
|
898
1628
|
if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
|
|
899
1629
|
this.completedDebouncePending = null;
|
|
900
1630
|
}
|
|
@@ -926,10 +1656,29 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
926
1656
|
if (!this.generatingStartedAt) this.generatingStartedAt = now;
|
|
927
1657
|
const modal = adapterStatus.activeModal;
|
|
928
1658
|
LOG.info('CLI', `[${this.type}] approval modal: "${modal?.message?.slice(0, 80) ?? 'none'}"`);
|
|
929
|
-
//
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
1659
|
+
// Include the FSM's approval entry seq, mirroring the auto-approve
|
|
1660
|
+
// path (maybeAutoApproveStatus) and resolveModal's sameEntryReResolve
|
|
1661
|
+
// guard. Two distinct back-to-back approvals can carry identical
|
|
1662
|
+
// message/buttons (very common with claude-cli's "Allow Bash
|
|
1663
|
+
// command?"). Without the seq their fingerprints collide and the dedup
|
|
1664
|
+
// below silently drops the second waiting_approval event — it is never
|
|
1665
|
+
// emitted, so it cannot even land in the pending inbox for a later
|
|
1666
|
+
// read_chat reconcile to recover. The seq is bumped by the FSM on every
|
|
1667
|
+
// fresh waiting_approval entry, so a new approval always yields a new
|
|
1668
|
+
// fingerprint and emits.
|
|
1669
|
+
const approvalEntrySeq = typeof adapterStatus?.approvalEntrySeq === 'number'
|
|
1670
|
+
? adapterStatus.approvalEntrySeq
|
|
1671
|
+
: 0;
|
|
1672
|
+
const approvalFingerprint = JSON.stringify({
|
|
1673
|
+
message: typeof modal?.message === 'string' ? modal.message.trim() : '',
|
|
1674
|
+
buttons: Array.isArray(modal?.buttons) ? modal.buttons.map((button: unknown) => String(button).trim()) : [],
|
|
1675
|
+
seq: approvalEntrySeq,
|
|
1676
|
+
});
|
|
1677
|
+
// PTY redraws repeat the same modal content; fingerprint dedup prevents duplicate events.
|
|
1678
|
+
// Do NOT also gate on lastStatus: consecutive approvals can arrive waiting_approval→waiting_approval
|
|
1679
|
+
// (e.g. antigravity-cli resolves one prompt and immediately shows the next) and would be silently dropped.
|
|
1680
|
+
if (approvalFingerprint !== this.lastApprovalEventFingerprint) {
|
|
1681
|
+
this.lastApprovalEventFingerprint = approvalFingerprint;
|
|
933
1682
|
this.appendRuntimeSystemMessage(
|
|
934
1683
|
this.formatApprovalRequestMessage(modal?.message, modal?.buttons),
|
|
935
1684
|
`approval_request:${now}`,
|
|
@@ -941,22 +1690,113 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
941
1690
|
modalButtons: modal?.buttons,
|
|
942
1691
|
});
|
|
943
1692
|
}
|
|
1693
|
+
} else if (newStatus === 'generating' && this.lastStatus === 'waiting_approval') {
|
|
1694
|
+
// Approval resolved and the agent resumed work. Defense-in-depth:
|
|
1695
|
+
// clear the approval emit fingerprint here too (not only on
|
|
1696
|
+
// completion at scheduleCompletedDebounceFlush). A subsequent
|
|
1697
|
+
// waiting_approval with the same modal content as the one just
|
|
1698
|
+
// resolved would otherwise collide with the stale fingerprint and be
|
|
1699
|
+
// dropped. The seq in the fingerprint already separates entries; this
|
|
1700
|
+
// reset is a belt-and-suspenders guard for the re-entry case.
|
|
1701
|
+
this.lastApprovalEventFingerprint = '';
|
|
944
1702
|
} else if (newStatus === 'idle' && (this.lastStatus === 'generating' || this.lastStatus === 'waiting_approval')) {
|
|
945
1703
|
const duration = this.generatingStartedAt ? Math.round((now - this.generatingStartedAt) / 1000) : 0;
|
|
946
|
-
//
|
|
1704
|
+
// Guard: if generatingStartedAt===0 and no debounce pending, the generating phase
|
|
1705
|
+
// was entered from 'starting' state (startup PTY noise), not from a real idle→generating
|
|
1706
|
+
// task dispatch. The idle→generating handler is the only code path that sets
|
|
1707
|
+
// generatingStartedAt and generatingDebouncePending, so both being absent means no
|
|
1708
|
+
// task was ever dispatched. Suppress the spurious completion event and fall through
|
|
1709
|
+
// to a simple lastStatus update.
|
|
1710
|
+
if (!this.generatingStartedAt && !this.generatingDebouncePending) {
|
|
1711
|
+
LOG.debug('CLI', `[${this.type}] suppressed startup-phase generating→idle blip (generatingStartedAt=0, no debounce pending)`);
|
|
1712
|
+
} else
|
|
1713
|
+
// If debounce still pending (generating lasted < 1s), cancel both UI events.
|
|
1714
|
+
// Still emit agent:generating_completed so mesh orchestration can record
|
|
1715
|
+
// task_completed for direct dispatches that complete faster than the debounce.
|
|
947
1716
|
if (this.generatingDebouncePending) {
|
|
948
|
-
|
|
1717
|
+
const shortDurationMs = this.generatingStartedAt ? now - this.generatingStartedAt : 0;
|
|
1718
|
+
LOG.info('CLI', `[${this.type}] suppressed short generating (${shortDurationMs}ms)`);
|
|
949
1719
|
if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
|
|
1720
|
+
// Emit completion for mesh task association even though the UI generating
|
|
1721
|
+
// started/completed pair is suppressed (too short for visible UI update).
|
|
1722
|
+
let shortFinalSummary: string | undefined;
|
|
1723
|
+
let shortEvidenceSource: CompletionFinalAssistantEvidence['source'] = 'unavailable';
|
|
1724
|
+
try {
|
|
1725
|
+
const parsedMessages = this.adapter?.getScriptParsedStatus()?.messages;
|
|
1726
|
+
const evidence = this.completionFinalAssistantEvidence(parsedMessages);
|
|
1727
|
+
shortEvidenceSource = evidence.source;
|
|
1728
|
+
shortFinalSummary = extractFinalSummaryFromMessages(evidence.messages as any);
|
|
1729
|
+
} catch { /* best-effort */ }
|
|
1730
|
+
// If a real response is confirmed, retroactively emit started so the chat
|
|
1731
|
+
// bubble appears even though the debounce suppressed the original event.
|
|
1732
|
+
if (shortFinalSummary) {
|
|
1733
|
+
this.pushEvent({ event: 'agent:generating_started', chatTitle, timestamp: now - shortDurationMs });
|
|
1734
|
+
}
|
|
950
1735
|
this.generatingDebouncePending = null;
|
|
951
1736
|
this.generatingStartedAt = 0;
|
|
1737
|
+
const missingEvidence = ((this.provider as any).requiresFinalAssistantBeforeIdle === true || shortEvidenceSource === 'external-native') && !shortFinalSummary;
|
|
1738
|
+
if (missingEvidence) {
|
|
1739
|
+
LOG.warn('CLI', `[${this.type}] short completion missing final assistant evidence (source=${shortEvidenceSource})`);
|
|
1740
|
+
}
|
|
1741
|
+
// When evidence is missing and there is no active mesh task context, suppress
|
|
1742
|
+
// the completion event. Providers with requiresFinalAssistantBeforeIdle or
|
|
1743
|
+
// external-native history must confirm a final assistant message before the
|
|
1744
|
+
// coordinator records task_completed. Only emit here if a mesh task is active
|
|
1745
|
+
// so the coordinator can apply its own timeout/retry logic.
|
|
1746
|
+
const hasMeshContext = !!(this.settings.meshNodeFor || this.settings.meshActiveTaskId || this.settings.launchedByCoordinator);
|
|
1747
|
+
if (missingEvidence && !hasMeshContext) {
|
|
1748
|
+
LOG.info('CLI', `[${this.type}] short completion suppressed: missing final assistant evidence, no mesh context (source=${shortEvidenceSource})`);
|
|
1749
|
+
// completedDebouncePending intentionally left null — the session is now idle
|
|
1750
|
+
// with no confirmed turn, matching the startup-blip suppression semantics.
|
|
1751
|
+
} else {
|
|
1752
|
+
this.pushEvent({
|
|
1753
|
+
event: 'agent:generating_completed',
|
|
1754
|
+
chatTitle,
|
|
1755
|
+
duration: 0,
|
|
1756
|
+
timestamp: now,
|
|
1757
|
+
finalSummary: shortFinalSummary,
|
|
1758
|
+
completionDiagnostic: {
|
|
1759
|
+
reason: 'short_generating_suppressed',
|
|
1760
|
+
shortDurationMs,
|
|
1761
|
+
finalAssistantEvidenceSource: shortEvidenceSource,
|
|
1762
|
+
...(missingEvidence ? { blockReason: 'missing_final_assistant' } : {}),
|
|
1763
|
+
},
|
|
1764
|
+
});
|
|
1765
|
+
}
|
|
952
1766
|
} else {
|
|
953
1767
|
// Debounce completed, then require the rich transcript path that read_chat
|
|
954
1768
|
// uses to show an idle turn whose last user-facing message is assistant.
|
|
955
|
-
this.completedDebouncePending = {
|
|
956
|
-
|
|
1769
|
+
this.completedDebouncePending = {
|
|
1770
|
+
chatTitle,
|
|
1771
|
+
duration,
|
|
1772
|
+
timestamp: now,
|
|
1773
|
+
firstObservedAt: now,
|
|
1774
|
+
previousStatus: this.lastStatus,
|
|
1775
|
+
};
|
|
1776
|
+
const ownsExternalHistory = !!(this.adapter as any)?.chatMessagesOwnedExternally;
|
|
1777
|
+
const flushDelay = ownsExternalHistory ? 0 : 3000;
|
|
1778
|
+
LOG.debug('CLI', `[${this.type}] set completedDebouncePending duration=${duration}s ownsExternalHistory=${ownsExternalHistory} flushDelay=${flushDelay}ms generatingStartedAt=${this.generatingStartedAt}`);
|
|
1779
|
+
this.scheduleCompletedDebounceFlush(flushDelay);
|
|
957
1780
|
}
|
|
958
1781
|
} else if (newStatus === 'idle' && this.lastStatus === 'starting') {
|
|
959
1782
|
this.pushEvent({ event: 'agent:ready', chatTitle, timestamp: now });
|
|
1783
|
+
} else if (newStatus === 'error') {
|
|
1784
|
+
if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
|
|
1785
|
+
this.generatingDebouncePending = null;
|
|
1786
|
+
if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
|
|
1787
|
+
this.completedDebouncePending = null;
|
|
1788
|
+
this.errorMessage = adapterStatus.errorMessage || this.errorMessage;
|
|
1789
|
+
this.errorReason = (adapterStatus.errorReason as ProviderErrorReason) || this.errorReason;
|
|
1790
|
+
this.pushEvent({
|
|
1791
|
+
event: 'agent:stopped',
|
|
1792
|
+
chatTitle,
|
|
1793
|
+
timestamp: now,
|
|
1794
|
+
finalSummary: adapterStatus.errorMessage || adapterStatus.errorReason || 'Provider reported an error',
|
|
1795
|
+
completionDiagnostic: {
|
|
1796
|
+
reason: adapterStatus.errorReason || 'provider_error',
|
|
1797
|
+
errorMessage: adapterStatus.errorMessage || undefined,
|
|
1798
|
+
},
|
|
1799
|
+
});
|
|
960
1800
|
} else if (newStatus === 'stopped') {
|
|
961
1801
|
// Cancel any pending debounce
|
|
962
1802
|
if (this.generatingDebounceTimer) { clearTimeout(this.generatingDebounceTimer); this.generatingDebounceTimer = null; }
|
|
@@ -976,8 +1816,39 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
976
1816
|
|
|
977
1817
|
// Monitor check (cooldown based notification, IDE/CLI common)
|
|
978
1818
|
const agentKey = `${this.type}:cli`;
|
|
979
|
-
|
|
1819
|
+
// Approval pending is detected from the raw adapter status, not `newStatus`:
|
|
1820
|
+
// auto-approve synthesizes `waiting_approval` → 'generating', which would
|
|
1821
|
+
// otherwise let the no-progress watchdog accumulate the approval wait.
|
|
1822
|
+
const approvalPending = rawStatus === 'waiting_approval';
|
|
1823
|
+
const monitorEvents = this.monitor.check(agentKey, newStatus, now, progressFingerprint, approvalPending);
|
|
1824
|
+
const monitorParsedStatus: any = parsedStatus;
|
|
980
1825
|
for (const me of monitorEvents) {
|
|
1826
|
+
if (
|
|
1827
|
+
me.type === 'monitor:no_progress'
|
|
1828
|
+
&& this.completionHasFinalAssistantMessage(monitorParsedStatus?.messages)
|
|
1829
|
+
&& !this.hasAdapterPendingResponse()
|
|
1830
|
+
&& !hasNonEmptyCliModalButtons(monitorParsedStatus?.activeModal ?? monitorParsedStatus?.modal)
|
|
1831
|
+
) {
|
|
1832
|
+
this.pushEvent({
|
|
1833
|
+
event: 'agent:generating_completed',
|
|
1834
|
+
chatTitle,
|
|
1835
|
+
duration: this.generatingStartedAt ? Math.round((now - this.generatingStartedAt) / 1000) : undefined,
|
|
1836
|
+
timestamp: me.timestamp,
|
|
1837
|
+
finalSummary: extractFinalSummaryFromMessages(monitorParsedStatus?.messages),
|
|
1838
|
+
completionDiagnostic: {
|
|
1839
|
+
providerType: this.type,
|
|
1840
|
+
sessionId: this.instanceId,
|
|
1841
|
+
providerSessionId: this.providerSessionId || null,
|
|
1842
|
+
reconciliationReason: 'no_progress_monitor_final_summary',
|
|
1843
|
+
finalAssistantPresent: true,
|
|
1844
|
+
},
|
|
1845
|
+
});
|
|
1846
|
+
this.generatingStartedAt = 0;
|
|
1847
|
+
// Cancel any pending debounce flush — monitor already fired completion.
|
|
1848
|
+
if (this.completedDebounceTimer) { clearTimeout(this.completedDebounceTimer); this.completedDebounceTimer = null; }
|
|
1849
|
+
this.completedDebouncePending = null;
|
|
1850
|
+
continue;
|
|
1851
|
+
}
|
|
981
1852
|
this.pushEvent({ event: me.type, agentKey: me.agentKey, message: me.message, elapsedSec: me.elapsedSec, timestamp: me.timestamp });
|
|
982
1853
|
}
|
|
983
1854
|
}
|
|
@@ -997,15 +1868,32 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
997
1868
|
workspaceName: typeof event.workspaceName === 'string' && event.workspaceName.trim()
|
|
998
1869
|
? event.workspaceName
|
|
999
1870
|
: this.workingDir,
|
|
1871
|
+
// Carry the workspace under BOTH `workspace` and `workspaceName` so the
|
|
1872
|
+
// downstream mesh forward/merge path — which reads `workspace` — can
|
|
1873
|
+
// propagate it to the coordinator snapshot. Without `workspace` the live
|
|
1874
|
+
// event path delivers an empty workspace and the dashboard falls back to
|
|
1875
|
+
// the generic "Terminal (Mesh Node)" title.
|
|
1876
|
+
workspace: typeof event.workspace === 'string' && event.workspace.trim()
|
|
1877
|
+
? event.workspace
|
|
1878
|
+
: this.workingDir,
|
|
1000
1879
|
providerSessionId: typeof event.providerSessionId === 'string' && event.providerSessionId.trim()
|
|
1001
1880
|
? event.providerSessionId
|
|
1002
1881
|
: this.providerSessionId,
|
|
1003
1882
|
};
|
|
1004
1883
|
if (this.context?.emitProviderEvent) {
|
|
1005
1884
|
this.context.emitProviderEvent(enrichedEvent);
|
|
1006
|
-
|
|
1885
|
+
} else {
|
|
1886
|
+
this.events.push(enrichedEvent);
|
|
1887
|
+
}
|
|
1888
|
+
// Auto-detach a direct-dispatch mesh assignment once the dispatched
|
|
1889
|
+
// task reaches a terminal state. Leaving meshNodeFor pinned would
|
|
1890
|
+
// route this session's next unrelated turn (a dashboard chat) into
|
|
1891
|
+
// the coordinator as if it were the completion of another task.
|
|
1892
|
+
// We schedule after the emit so the originating coordinator still
|
|
1893
|
+
// observes the completion event with its routing marker intact.
|
|
1894
|
+
if (TERMINAL_MESH_EVENTS.has(event.event) && this.settings.meshActiveTaskId) {
|
|
1895
|
+
try { this.detachMeshAssignment(); } catch { /* best-effort */ }
|
|
1007
1896
|
}
|
|
1008
|
-
this.events.push(enrichedEvent);
|
|
1009
1897
|
}
|
|
1010
1898
|
|
|
1011
1899
|
private flushEvents(): ProviderEvent[] {
|
|
@@ -1238,7 +2126,7 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
1238
2126
|
receivedAt: normalizedMessage.receivedAt || normalizedMessage.timestamp,
|
|
1239
2127
|
historyDedupKey: dedupKey,
|
|
1240
2128
|
}],
|
|
1241
|
-
this.adapter.getScriptParsedStatus?.()?.title || this.workingDir
|
|
2129
|
+
this.adapter.getScriptParsedStatus?.()?.title || workingDirBasename(this.workingDir),
|
|
1242
2130
|
this.instanceId,
|
|
1243
2131
|
this.providerSessionId,
|
|
1244
2132
|
);
|
|
@@ -1258,12 +2146,28 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
1258
2146
|
index,
|
|
1259
2147
|
source: 'parsed',
|
|
1260
2148
|
}));
|
|
2149
|
+
const getRole = (message: ChatMessage): string => typeof message.role === 'string'
|
|
2150
|
+
? message.role.trim().toLowerCase()
|
|
2151
|
+
: '';
|
|
1261
2152
|
const runtimeEntries: MergeEntry[] = this.runtimeMessages.map((entry, index) => ({
|
|
1262
2153
|
message: entry.message,
|
|
1263
2154
|
index: parsedMessages.length + index,
|
|
1264
|
-
source: 'runtime',
|
|
2155
|
+
source: 'runtime' as const,
|
|
1265
2156
|
runtimeKey: entry.key,
|
|
1266
|
-
}))
|
|
2157
|
+
})).filter((entry) => {
|
|
2158
|
+
const meta = entry.message.meta && typeof entry.message.meta === 'object' && !Array.isArray(entry.message.meta)
|
|
2159
|
+
? entry.message.meta as Record<string, unknown>
|
|
2160
|
+
: {};
|
|
2161
|
+
if (meta.runtimeInputAck !== true) return true;
|
|
2162
|
+
const runtimeText = flattenContent(entry.message.content).replace(/\s+/g, ' ').trim();
|
|
2163
|
+
if (!runtimeText) return false;
|
|
2164
|
+
return !parsedEntries.some((parsedEntry) => {
|
|
2165
|
+
const parsedRole = getRole(parsedEntry.message);
|
|
2166
|
+
if (parsedRole !== 'user' && parsedRole !== 'human') return false;
|
|
2167
|
+
const parsedText = flattenContent(parsedEntry.message.content).replace(/\s+/g, ' ').trim();
|
|
2168
|
+
return parsedText === runtimeText;
|
|
2169
|
+
});
|
|
2170
|
+
});
|
|
1267
2171
|
const getTime = (message: ChatMessage): number => {
|
|
1268
2172
|
const value = typeof message.receivedAt === 'number'
|
|
1269
2173
|
? message.receivedAt
|
|
@@ -1273,9 +2177,6 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
1273
2177
|
return Number.isFinite(value) && value > 0 ? value : 0;
|
|
1274
2178
|
};
|
|
1275
2179
|
|
|
1276
|
-
const getRole = (message: ChatMessage): string => typeof message.role === 'string'
|
|
1277
|
-
? message.role.trim().toLowerCase()
|
|
1278
|
-
: '';
|
|
1279
2180
|
const isRuntimeOverlay = (entry: MergeEntry): boolean => {
|
|
1280
2181
|
if (entry.source !== 'runtime') return false;
|
|
1281
2182
|
const key = typeof entry.runtimeKey === 'string' ? entry.runtimeKey.trim().toLowerCase() : '';
|
|
@@ -1341,7 +2242,9 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
1341
2242
|
this.providerSessionId = nextSessionId;
|
|
1342
2243
|
this.historyWriter.promoteHistorySession(this.type, previousHistorySessionId, nextSessionId);
|
|
1343
2244
|
this.historyWriter.writeSessionStart(this.type, nextSessionId, this.workingDir, this.instanceId);
|
|
1344
|
-
this.
|
|
2245
|
+
if (this.shouldHydrateExistingProviderHistory()) {
|
|
2246
|
+
this.restorePersistedHistoryFromCurrentSession();
|
|
2247
|
+
}
|
|
1345
2248
|
this.adapter.updateRuntimeMeta({ providerSessionId: nextSessionId });
|
|
1346
2249
|
this.onProviderSessionResolved?.({
|
|
1347
2250
|
instanceId: this.instanceId,
|
|
@@ -1354,13 +2257,39 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
1354
2257
|
LOG.info('CLI', `[${this.type}] discovered provider session id: ${nextSessionId}`);
|
|
1355
2258
|
}
|
|
1356
2259
|
|
|
1357
|
-
private
|
|
2260
|
+
private shouldHydrateExistingProviderHistory(): boolean {
|
|
2261
|
+
return this.launchMode === 'resume' || this.launchMode === 'manual';
|
|
2262
|
+
}
|
|
2263
|
+
|
|
2264
|
+
private shouldSuppressFreshLaunchStartupReplay(parsedMessages: unknown[], parsedStatus: any, adapterStatus: any, parsedProviderSessionId = ''): boolean {
|
|
2265
|
+
if (this.launchMode !== 'new') return false;
|
|
2266
|
+
if (this.providerSessionId) return false;
|
|
2267
|
+
if (!Array.isArray(parsedMessages) || parsedMessages.length === 0) return false;
|
|
2268
|
+
if (!isIdleStatus(adapterStatus?.status) || !isIdleStatus(parsedStatus?.status)) return false;
|
|
2269
|
+
if (parsedProviderSessionId) return true;
|
|
2270
|
+
|
|
2271
|
+
const newestMessageAt = parsedMessages.reduce<number>((newest, message) => Math.max(newest, getMessageTime(message)), 0);
|
|
2272
|
+
|
|
2273
|
+
// Untimestamped idle parser output during a fresh launch is usually the
|
|
2274
|
+
// provider's last workspace transcript before a new turn exists.
|
|
2275
|
+
return newestMessageAt === 0;
|
|
2276
|
+
}
|
|
2277
|
+
|
|
2278
|
+
private syncCanonicalSavedHistoryIfNeeded(options: { full?: boolean } = {}): boolean {
|
|
1358
2279
|
if (!this.providerSessionId) return false;
|
|
1359
|
-
const canonicalHistory = this.provider.
|
|
2280
|
+
const canonicalHistory = this.provider.nativeHistory;
|
|
1360
2281
|
if (!canonicalHistory) return false;
|
|
1361
2282
|
|
|
2283
|
+
// Per-status-report hydration reads only a bounded tail (snapshot needs at
|
|
2284
|
+
// most the newest 60). The once-per-resume restore path passes full:true
|
|
2285
|
+
// because seedSessionHistory needs the COMPLETE transcript to seed dedup
|
|
2286
|
+
// state. The read-cache key encodes the window so the bounded and full
|
|
2287
|
+
// reads don't share/clobber each other's 2s cache entry.
|
|
2288
|
+
const limit = options.full ? Number.MAX_SAFE_INTEGER : STATUS_HYDRATION_TAIL_LIMIT;
|
|
2289
|
+
const windowTag = options.full ? 'full' : `tail:${STATUS_HYDRATION_TAIL_LIMIT}`;
|
|
2290
|
+
|
|
1362
2291
|
if (isNativeSourceCanonicalHistory(canonicalHistory)) {
|
|
1363
|
-
const cacheKey = [this.type, this.providerSessionId, this.workingDir].join('\0');
|
|
2292
|
+
const cacheKey = [this.type, this.providerSessionId, this.workingDir, windowTag].join('\0');
|
|
1364
2293
|
const now = Date.now();
|
|
1365
2294
|
if (cacheKey === this.lastNativeSourceCanonicalCacheKey && now - this.lastNativeSourceCanonicalCheckAt < 2_000) {
|
|
1366
2295
|
return true;
|
|
@@ -1373,7 +2302,7 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
1373
2302
|
historySessionId: this.providerSessionId,
|
|
1374
2303
|
workspace: this.workingDir,
|
|
1375
2304
|
offset: 0,
|
|
1376
|
-
limit
|
|
2305
|
+
limit,
|
|
1377
2306
|
historyBehavior: this.provider.historyBehavior,
|
|
1378
2307
|
scripts: this.provider.scripts as any,
|
|
1379
2308
|
});
|
|
@@ -1390,7 +2319,7 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
1390
2319
|
}
|
|
1391
2320
|
|
|
1392
2321
|
try {
|
|
1393
|
-
const cacheKey = [this.type, this.providerSessionId, this.workingDir, canonicalHistory.mode || 'materialized-mirror'].join('\0');
|
|
2322
|
+
const cacheKey = [this.type, this.providerSessionId, this.workingDir, canonicalHistory.mode || 'materialized-mirror', windowTag].join('\0');
|
|
1394
2323
|
const now = Date.now();
|
|
1395
2324
|
if (cacheKey === this.lastNativeSourceCanonicalCacheKey && now - this.lastNativeSourceCanonicalCheckAt < 2_000) {
|
|
1396
2325
|
return true;
|
|
@@ -1401,7 +2330,14 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
1401
2330
|
if (!materializeProviderNativeHistory(this.type, canonicalHistory, this.providerSessionId, this.workingDir, this.provider.scripts as any)) {
|
|
1402
2331
|
return false;
|
|
1403
2332
|
}
|
|
1404
|
-
|
|
2333
|
+
// Bounded by default: the per-status-report path only needs the newest
|
|
2334
|
+
// STATUS_HYDRATION_TAIL_LIMIT messages because the snapshot caps
|
|
2335
|
+
// activeChat.messages to the last 60 (status/normalize.ts) and loads
|
|
2336
|
+
// the rest lazily via read_chat on subscribe. The once-per-resume
|
|
2337
|
+
// restore path passes full:true so seedSessionHistory still sees the
|
|
2338
|
+
// COMPLETE transcript for prefix-dedup seeding. readChatHistory serves
|
|
2339
|
+
// a bounded limit as an O(tail) read.
|
|
2340
|
+
const restoredHistory = readChatHistory(this.type, 0, limit, this.providerSessionId, 0, this.provider.historyBehavior);
|
|
1405
2341
|
this.lastPersistedHistoryMessages = restoredHistory.messages.map((message) => ({
|
|
1406
2342
|
role: message.role,
|
|
1407
2343
|
content: message.content,
|
|
@@ -1417,10 +2353,13 @@ export class CliProviderInstance implements ProviderInstance {
|
|
|
1417
2353
|
|
|
1418
2354
|
private restorePersistedHistoryFromCurrentSession(): void {
|
|
1419
2355
|
if (!this.providerSessionId) return;
|
|
1420
|
-
|
|
1421
|
-
|
|
2356
|
+
// Restore is the once-per-resume seeding path: it needs the COMPLETE
|
|
2357
|
+
// transcript so seedSessionHistory can prime dedup state. Pass full so the
|
|
2358
|
+
// hydration read is unbounded here (and only here).
|
|
2359
|
+
this.syncCanonicalSavedHistoryIfNeeded({ full: true });
|
|
2360
|
+
const restoredHistory = isNativeSourceCanonicalHistory(this.provider.nativeHistory)
|
|
1422
2361
|
? readProviderChatHistory(this.type, {
|
|
1423
|
-
canonicalHistory: this.provider.
|
|
2362
|
+
canonicalHistory: this.provider.nativeHistory,
|
|
1424
2363
|
historySessionId: this.providerSessionId,
|
|
1425
2364
|
workspace: this.workingDir,
|
|
1426
2365
|
offset: 0,
|