@adhdev/daemon-core 0.9.82-rc.21 → 0.9.82-rc.211
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 +1 -0
- package/dist/boot/process-hardening.d.ts +50 -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 +23 -2
- package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
- package/dist/cli-adapters/cli-state-engine.d.ts +178 -0
- package/dist/cli-adapters/provider-cli-adapter.d.ts +106 -63
- package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
- package/dist/cli-adapters/provider-cli-shared.d.ts +29 -0
- package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
- package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +3 -3
- package/dist/cli-adapters/terminal-backends/types.d.ts +1 -2
- package/dist/cli-adapters/terminal-screen.d.ts +2 -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 +32 -1
- package/dist/config/chat-history.d.ts +9 -0
- package/dist/config/config.d.ts +5 -0
- package/dist/config/mesh-config.d.ts +72 -1
- package/dist/git/git-commands.d.ts +9 -1
- package/dist/git/git-diff.d.ts +6 -0
- package/dist/git/git-types.d.ts +2 -0
- package/dist/index.d.ts +46 -11
- package/dist/index.js +35173 -15756
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +34880 -15556
- 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/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 +90 -0
- package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
- package/dist/mesh/mesh-events-coordinator.d.ts +151 -0
- package/dist/mesh/mesh-events-pending.d.ts +33 -0
- package/dist/mesh/mesh-events-stale.d.ts +40 -0
- package/dist/mesh/mesh-events-utils.d.ts +14 -0
- package/dist/mesh/mesh-events.d.ts +5 -40
- package/dist/mesh/mesh-fast-forward.d.ts +41 -0
- package/dist/mesh/mesh-host-ownership.d.ts +9 -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 +58 -0
- package/dist/mesh/mesh-refine-status.d.ts +26 -0
- package/dist/mesh/mesh-review-inbox.d.ts +90 -0
- package/dist/mesh/mesh-runtime-store.d.ts +324 -0
- package/dist/mesh/mesh-task-stats.d.ts +49 -0
- package/dist/mesh/mesh-work-queue.d.ts +137 -6
- package/dist/mesh/preview-freshness.d.ts +18 -0
- package/dist/mesh/refine-config.d.ts +215 -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/cli-provider-instance.d.ts +39 -3
- package/dist/providers/contracts.d.ts +130 -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 +12 -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 +52 -0
- package/dist/providers/spec/cli-adapter.d.ts +101 -0
- package/dist/providers/spec/driver.d.ts +225 -0
- package/dist/providers/spec/evaluator.d.ts +54 -0
- package/dist/providers/spec/loader.d.ts +15 -0
- package/dist/providers/spec/native-history-executor.d.ts +41 -0
- package/dist/providers/spec/route.d.ts +4 -0
- package/dist/providers/spec/schema.gen.d.ts +2025 -0
- package/dist/providers/spec/types.d.ts +302 -0
- package/dist/providers/transcript-v2.d.ts +176 -0
- package/dist/providers/types/interactive-prompt.d.ts +48 -0
- package/dist/repo-mesh-types.d.ts +109 -1
- package/dist/sessions/registry.d.ts +3 -0
- package/dist/shared-types-extra.d.ts +2 -4
- package/dist/shared-types.d.ts +42 -1
- 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 +1 -0
- package/dist/types.d.ts +5 -0
- package/package.json +6 -3
- package/src/agent-stream/poller.ts +2 -3
- package/src/boot/daemon-lifecycle.ts +22 -10
- package/src/boot/process-hardening.ts +89 -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 +22 -2
- package/src/cli-adapters/cli-script-runner.ts +421 -0
- package/src/cli-adapters/cli-state-engine.ts +1138 -0
- package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
- package/src/cli-adapters/provider-cli-adapter.ts +673 -1139
- 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 +3 -1
- package/src/cli-adapters/provider-cli-shared.d.ts +2 -0
- package/src/cli-adapters/provider-cli-shared.ts +59 -11
- package/src/cli-adapters/raw-terminal-io.ts +252 -0
- package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +35 -29
- package/src/cli-adapters/terminal-backends/types.ts +1 -3
- package/src/cli-adapters/terminal-screen.ts +11 -81
- package/src/commands/chat-commands.ts +1787 -60
- package/src/commands/cli-manager.ts +283 -14
- package/src/commands/handler.ts +809 -2
- package/src/commands/mesh-coordinator.ts +332 -122
- package/src/commands/router.ts +4198 -557
- package/src/config/chat-history.ts +95 -24
- package/src/config/config.ts +12 -0
- package/src/config/mesh-config.ts +280 -2
- 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/ide-detector.ts +26 -16
- package/src/git/git-commands.ts +42 -12
- package/src/git/git-diff.ts +53 -0
- package/src/git/git-status.ts +35 -6
- package/src/git/git-types.ts +2 -0
- package/src/git/git-worktree.ts +8 -1
- package/src/index.ts +126 -10
- 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/logger.ts +2 -1
- package/src/mesh/contracts.ts +329 -0
- package/src/mesh/coordinator-prompt.ts +218 -31
- package/src/mesh/coordinator-registry.ts +121 -0
- package/src/mesh/mesh-active-work.ts +437 -0
- package/src/mesh/mesh-delivery-policy.ts +315 -0
- package/src/mesh/mesh-events-coordinator.ts +1404 -0
- package/src/mesh/mesh-events-pending.ts +371 -0
- package/src/mesh/mesh-events-stale.ts +283 -0
- package/src/mesh/mesh-events-utils.ts +161 -0
- package/src/mesh/mesh-events.ts +24 -908
- package/src/mesh/mesh-fast-forward.ts +438 -0
- package/src/mesh/mesh-host-ownership.ts +73 -0
- package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
- package/src/mesh/mesh-ledger.ts +587 -102
- package/src/mesh/mesh-missions.ts +151 -0
- package/src/mesh/mesh-refine-status.ts +144 -0
- package/src/mesh/mesh-review-inbox.ts +307 -0
- package/src/mesh/mesh-runtime-store.ts +1305 -0
- package/src/mesh/mesh-task-stats.ts +154 -0
- package/src/mesh/mesh-work-queue.ts +490 -166
- package/src/mesh/preview-freshness.ts +118 -0
- package/src/mesh/refine-config.ts +403 -0
- package/src/mesh/worktree-bootstrap-config.ts +326 -0
- package/src/providers/acp-provider-instance.ts +15 -1
- package/src/providers/approval-utils.d.ts +4 -0
- package/src/providers/approval-utils.ts +47 -5
- package/src/providers/chat-message-normalization.ts +4 -11
- package/src/providers/cli-provider-instance.ts +833 -64
- package/src/providers/contracts.d.ts +55 -0
- package/src/providers/contracts.ts +141 -6
- package/src/providers/external-sources.ts +218 -0
- package/src/providers/ide-provider-instance.ts +19 -5
- 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 +419 -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 +582 -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 +138 -0
- package/src/providers/spec/cli-adapter.ts +626 -0
- package/src/providers/spec/driver.ts +922 -0
- package/src/providers/spec/evaluator.ts +597 -0
- package/src/providers/spec/loader.ts +324 -0
- package/src/providers/spec/native-history-executor.ts +939 -0
- package/src/providers/spec/route.ts +51 -0
- package/src/providers/spec/schema.gen.ts +691 -0
- package/src/providers/spec/schema.json +341 -0
- package/src/providers/spec/types.ts +356 -0
- package/src/providers/transcript-v2.ts +567 -0
- package/src/providers/types/interactive-prompt.ts +425 -0
- package/src/providers/version-archive.ts +38 -20
- package/src/repo-mesh-types.ts +119 -1
- package/src/sessions/registry.ts +3 -0
- package/src/shared-types-extra.ts +2 -4
- package/src/shared-types.ts +45 -1
- package/src/status/builders.ts +24 -6
- package/src/status/normalize.ts +2 -0
- package/src/status/reporter.ts +15 -0
- package/src/status/snapshot.ts +84 -25
- package/src/system/host-memory.ts +29 -12
- 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
|
@@ -12,11 +12,21 @@ import type { CliAdapter } from '../cli-adapter-types.js';
|
|
|
12
12
|
import { flattenContent, normalizeInputEnvelope, type InputEnvelope, type ProviderModule, type ProviderScripts } from '../providers/contracts.js';
|
|
13
13
|
import { assertProviderSupportsDeclaredInput, assertTextOnlyInput } from '../providers/provider-input-support.js';
|
|
14
14
|
import { validateReadChatResultPayload } from '../providers/read-chat-contract.js';
|
|
15
|
+
import { pickApprovalButton } from '../providers/approval-utils.js';
|
|
15
16
|
import type { ProviderInstance } from '../providers/provider-instance.js';
|
|
16
|
-
import { readProviderChatHistory } from '../config/chat-history.js';
|
|
17
|
+
import { isNativeSourceCanonicalHistory, readChatHistory, readProviderChatHistory } from '../config/chat-history.js';
|
|
18
|
+
import { getCoordinatorForSession } from '../mesh/coordinator-registry.js';
|
|
17
19
|
import { LOG, getRecentLogs } from '../logging/logger.js';
|
|
18
20
|
import { getRecentDebugTrace, recordDebugTrace } from '../logging/debug-trace.js';
|
|
19
21
|
import { buildChatMessageSignature, hashSignatureParts } from '../chat/chat-signatures.js';
|
|
22
|
+
import {
|
|
23
|
+
CHAT_SOURCE_REGISTRY,
|
|
24
|
+
buildV1NativePresentObservation,
|
|
25
|
+
chatSourceSessionKey,
|
|
26
|
+
type ChatSourceDecision,
|
|
27
|
+
type ChatSourceObservation,
|
|
28
|
+
type ChatSourceTransitionCause,
|
|
29
|
+
} from '../chat/source-resolver.js';
|
|
20
30
|
import type { ChatMessage } from '../types.js';
|
|
21
31
|
import type { SessionTransport } from '../shared-types.js';
|
|
22
32
|
import { filterUserFacingChatMessages, normalizeChatMessages } from '../providers/chat-message-normalization.js';
|
|
@@ -24,6 +34,25 @@ import { filterUserFacingChatMessages, normalizeChatMessages } from '../provider
|
|
|
24
34
|
const RECENT_SEND_WINDOW_MS = 1200;
|
|
25
35
|
export const READ_CHAT_PROVIDER_EVAL_TIMEOUT_MS = 25_000;
|
|
26
36
|
const HERMES_CLI_STARTING_SEND_SETTLE_MS = 2_000;
|
|
37
|
+
// (A2.2) CLI_NATIVE_HISTORY_FRESH_MS removed with isNativeHistoryFreshEnough.
|
|
38
|
+
// Hardcoded native-transcript provider allow-list. Deprecated. Kept only as a
|
|
39
|
+
// last-resort fallback when ProviderModule is not yet loaded; on every hit we
|
|
40
|
+
// warn so the dependency on this set is visible. A2 deletes the set entirely
|
|
41
|
+
// and routes solely through canonicalHistory.contractVersion +
|
|
42
|
+
// isNativeSourceCanonicalHistory().
|
|
43
|
+
const CLI_NATIVE_TRANSCRIPT_PROVIDERS = new Set(['codex-cli', 'claude-cli', 'hermes-cli', 'antigravity-cli']);
|
|
44
|
+
const warnedLegacyNativeAllowlistHits = new Set<string>();
|
|
45
|
+
function warnLegacyNativeAllowlistHit(providerType: string): void {
|
|
46
|
+
if (warnedLegacyNativeAllowlistHits.has(providerType)) return;
|
|
47
|
+
warnedLegacyNativeAllowlistHits.add(providerType);
|
|
48
|
+
// eslint-disable-next-line no-console
|
|
49
|
+
console.warn(
|
|
50
|
+
`[chat-commands] supportsCliNativeTranscript fell back to the hardcoded `
|
|
51
|
+
+ `CLI_NATIVE_TRANSCRIPT_PROVIDERS set for "${providerType}". `
|
|
52
|
+
+ `The provider module was unavailable or did not declare canonicalHistory. `
|
|
53
|
+
+ `Set canonicalHistory.contractVersion in the provider.json to remove this dependency.`,
|
|
54
|
+
);
|
|
55
|
+
}
|
|
27
56
|
const recentSendByTarget = new Map<string, number>();
|
|
28
57
|
|
|
29
58
|
interface ApprovalSelectableInstance extends ProviderInstance {
|
|
@@ -32,6 +61,7 @@ interface ApprovalSelectableInstance extends ProviderInstance {
|
|
|
32
61
|
|
|
33
62
|
interface RuntimeChatMessageMerger extends ProviderInstance {
|
|
34
63
|
mergeRuntimeChatMessages?(messages: ChatMessage[]): ChatMessage[];
|
|
64
|
+
recordAcknowledgedUserInput?(input: InputEnvelope | string): void;
|
|
35
65
|
}
|
|
36
66
|
|
|
37
67
|
type LegacyStringScript = (params?: Record<string, unknown> | string) => string;
|
|
@@ -48,6 +78,16 @@ function getTargetedCliAdapter(h: CommandHelpers, args: any, providerType?: stri
|
|
|
48
78
|
return h.getCliAdapter(args?.targetSessionId || providerType || h.currentSession?.providerType || h.currentManagerKey);
|
|
49
79
|
}
|
|
50
80
|
|
|
81
|
+
function getExplicitHistorySessionId(args: any): string | undefined {
|
|
82
|
+
const explicit = typeof args?.historySessionId === 'string' ? args.historySessionId.trim() : '';
|
|
83
|
+
if (explicit) return explicit;
|
|
84
|
+
|
|
85
|
+
const explicitProviderSessionId = typeof args?.providerSessionId === 'string' ? args.providerSessionId.trim() : '';
|
|
86
|
+
if (explicitProviderSessionId) return explicitProviderSessionId;
|
|
87
|
+
|
|
88
|
+
return undefined;
|
|
89
|
+
}
|
|
90
|
+
|
|
51
91
|
function getTargetInstance(h: CommandHelpers, args: any): ApprovalSelectableInstance | null {
|
|
52
92
|
const targetSessionId = typeof args?.targetSessionId === 'string' ? args.targetSessionId.trim() : '';
|
|
53
93
|
const sessionId = targetSessionId || h.currentSession?.sessionId || '';
|
|
@@ -139,19 +179,82 @@ async function waitOnceForFreshHermesCliStart(adapter: CliAdapter, log: (msg: st
|
|
|
139
179
|
}
|
|
140
180
|
|
|
141
181
|
function getHistorySessionId(h: CommandHelpers, args: any): string | undefined {
|
|
142
|
-
const explicit =
|
|
182
|
+
const explicit = getExplicitHistorySessionId(args);
|
|
143
183
|
if (explicit) return explicit;
|
|
144
184
|
|
|
145
|
-
const explicitProviderSessionId = typeof args?.providerSessionId === 'string' ? args.providerSessionId.trim() : '';
|
|
146
|
-
if (explicitProviderSessionId) return explicitProviderSessionId;
|
|
147
|
-
|
|
148
185
|
const targetSessionId = typeof args?.targetSessionId === 'string' ? args.targetSessionId.trim() : '';
|
|
149
186
|
if (!targetSessionId) return undefined;
|
|
150
187
|
|
|
151
|
-
const
|
|
188
|
+
const session = h.ctx.sessionRegistry?.get(targetSessionId) as any;
|
|
189
|
+
const registeredProviderSessionId = typeof session?.providerSessionId === 'string' ? session.providerSessionId.trim() : '';
|
|
190
|
+
if (registeredProviderSessionId) return registeredProviderSessionId;
|
|
191
|
+
|
|
192
|
+
const instance = getTargetInstance(h, args);
|
|
152
193
|
const state = instance?.getState?.();
|
|
153
194
|
const providerSessionId = typeof state?.providerSessionId === 'string' ? state.providerSessionId.trim() : '';
|
|
154
|
-
|
|
195
|
+
if (providerSessionId) return providerSessionId;
|
|
196
|
+
|
|
197
|
+
const currentSession = h.currentSession as any;
|
|
198
|
+
if (currentSession?.sessionId === targetSessionId) {
|
|
199
|
+
const currentProviderSessionId = typeof currentSession.providerSessionId === 'string'
|
|
200
|
+
? currentSession.providerSessionId.trim()
|
|
201
|
+
: '';
|
|
202
|
+
if (currentProviderSessionId) return currentProviderSessionId;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
return targetSessionId;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function resolveCliNativeHistorySessionId(args: any, currentHistorySessionId: string | undefined, parsedProviderSessionId: string | undefined): string | undefined {
|
|
209
|
+
const explicit = getExplicitHistorySessionId(args);
|
|
210
|
+
if (explicit) return explicit;
|
|
211
|
+
|
|
212
|
+
const parsed = typeof parsedProviderSessionId === 'string' ? parsedProviderSessionId.trim() : '';
|
|
213
|
+
const current = typeof currentHistorySessionId === 'string' ? currentHistorySessionId.trim() : '';
|
|
214
|
+
const targetSessionId = typeof args?.targetSessionId === 'string' ? args.targetSessionId.trim() : '';
|
|
215
|
+
|
|
216
|
+
// getHistorySessionId falls back to the runtime session id when no native
|
|
217
|
+
// handle has been registered yet. For live CLI adapters the parser may
|
|
218
|
+
// already know the provider-native handle; prefer it over the runtime id so
|
|
219
|
+
// exact native reads do not miss the worker transcript and fall back to PTY
|
|
220
|
+
// or same-workspace history.
|
|
221
|
+
if (parsed && (!current || current === targetSessionId)) return parsed;
|
|
222
|
+
return current || parsed || undefined;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function shouldSkipLiveCliNativeHistoryWithoutProviderSession(args: {
|
|
226
|
+
adapter?: CliAdapter | null;
|
|
227
|
+
providerType?: string;
|
|
228
|
+
readChatArgs: any;
|
|
229
|
+
nativeHistorySessionId?: string;
|
|
230
|
+
parsedProviderSessionId?: string;
|
|
231
|
+
}): boolean {
|
|
232
|
+
const explicit = getExplicitHistorySessionId(args.readChatArgs);
|
|
233
|
+
if (explicit) return false;
|
|
234
|
+
|
|
235
|
+
const targetSessionId = typeof args.readChatArgs?.targetSessionId === 'string'
|
|
236
|
+
? args.readChatArgs.targetSessionId.trim()
|
|
237
|
+
: '';
|
|
238
|
+
if (!targetSessionId) return false;
|
|
239
|
+
|
|
240
|
+
const resolved = typeof args.nativeHistorySessionId === 'string'
|
|
241
|
+
? args.nativeHistorySessionId.trim()
|
|
242
|
+
: '';
|
|
243
|
+
if (!resolved || resolved !== targetSessionId) return false;
|
|
244
|
+
|
|
245
|
+
const parsed = typeof args.parsedProviderSessionId === 'string'
|
|
246
|
+
? args.parsedProviderSessionId.trim()
|
|
247
|
+
: '';
|
|
248
|
+
if (parsed) return false;
|
|
249
|
+
|
|
250
|
+
const cliType = args.adapter?.cliType || args.providerType || '';
|
|
251
|
+
if (cliType !== 'codex-cli') return false;
|
|
252
|
+
|
|
253
|
+
// A live Codex session starts with only the daemon runtime UUID. That UUID
|
|
254
|
+
// is not the provider-native rollout id, so using it for native history
|
|
255
|
+
// lets the file picker fall back to the newest same-workspace transcript
|
|
256
|
+
// and makes concurrent fresh sessions all show the same old conversation.
|
|
257
|
+
return !!args.adapter;
|
|
155
258
|
}
|
|
156
259
|
|
|
157
260
|
function getInteractionId(args: any): string | undefined {
|
|
@@ -221,6 +324,967 @@ function normalizeReadChatMessages(payload: Record<string, any>): ChatMessage[]
|
|
|
221
324
|
return normalizeChatMessages(messages);
|
|
222
325
|
}
|
|
223
326
|
|
|
327
|
+
function getMessageNewestReceivedAt(messages: Array<{ receivedAt?: unknown; timestamp?: unknown }>): number {
|
|
328
|
+
let newest = 0;
|
|
329
|
+
for (const message of messages) {
|
|
330
|
+
const receivedAt = Number(message?.receivedAt ?? message?.timestamp ?? 0);
|
|
331
|
+
if (Number.isFinite(receivedAt) && receivedAt > newest) newest = receivedAt;
|
|
332
|
+
}
|
|
333
|
+
return newest;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function readHistorySessionIdFromMessages(messages: ChatMessage[]): string | undefined {
|
|
337
|
+
for (const message of messages as Array<ChatMessage & { historySessionId?: unknown }>) {
|
|
338
|
+
const historySessionId = typeof message?.historySessionId === 'string' ? message.historySessionId.trim() : '';
|
|
339
|
+
if (historySessionId) return historySessionId;
|
|
340
|
+
}
|
|
341
|
+
return undefined;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function shouldPreserveNativeIdentity(providerType: string, sessionId: string, message: ChatMessage): boolean {
|
|
345
|
+
const providerUnitKey = typeof message.providerUnitKey === 'string' ? message.providerUnitKey.trim() : '';
|
|
346
|
+
const turnKey = typeof message._turnKey === 'string' ? message._turnKey.trim() : '';
|
|
347
|
+
if (!providerUnitKey) return false;
|
|
348
|
+
// (A2.3) v2 stamped identity is producer-owned and globally stable; trust it
|
|
349
|
+
// unconditionally. Producers may omit _turnKey (the daemon recomputes it
|
|
350
|
+
// from the current ordering), so do not require turnKey for v2 messages.
|
|
351
|
+
if (providerUnitKey.startsWith('v2:') || providerUnitKey.startsWith('v2-pty:')) {
|
|
352
|
+
return true;
|
|
353
|
+
}
|
|
354
|
+
// v1 identity always required both keys to be present.
|
|
355
|
+
if (!turnKey) return false;
|
|
356
|
+
if (providerType === 'hermes-cli' && sessionId) {
|
|
357
|
+
return providerUnitKey.startsWith(`${providerType}:native:${sessionId}:`)
|
|
358
|
+
&& turnKey.startsWith(`${providerType}:native-turn:${sessionId}:`);
|
|
359
|
+
}
|
|
360
|
+
return true;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* Drop the synthetic "user" message some CLIs surface in their native
|
|
365
|
+
* transcript when the daemon injects a coordinator system prompt
|
|
366
|
+
* (codex puts the AGENTS.md / developer_instructions block in as
|
|
367
|
+
* role=user; agy/claude/hermes have similar artifacts). The user can
|
|
368
|
+
* opt back into seeing it via the provider setting
|
|
369
|
+
* `showCoordinatorSystemPrompt`. Default is off — the prompt is still
|
|
370
|
+
* fully visible from the chat-header ⓘ "Session info" dialog.
|
|
371
|
+
*
|
|
372
|
+
* Matching rules:
|
|
373
|
+
* 1. Setting must be off (default).
|
|
374
|
+
* 2. There must be a registered coordinator entry for the session.
|
|
375
|
+
* 3. The candidate message is filtered when its role is user OR
|
|
376
|
+
* system and its content either contains the prompt body verbatim,
|
|
377
|
+
* OR contains the well-known coordinator marker
|
|
378
|
+
* `adhdev-mesh-coordinator-prompt`. The marker covers context-file
|
|
379
|
+
* cases (agy AGENTS.md / gemini GEMINI.md) where the CLI may wrap
|
|
380
|
+
* its own preamble around our block. Verbatim-content covers
|
|
381
|
+
* codex's developer_instructions echo.
|
|
382
|
+
*
|
|
383
|
+
* Returns the messages array unchanged when none of the rules match,
|
|
384
|
+
* so this is safe to apply unconditionally to every read_chat result.
|
|
385
|
+
*/
|
|
386
|
+
function maybeHideCoordinatorPromptMessage(
|
|
387
|
+
h: CommandHelpers,
|
|
388
|
+
providerType: string,
|
|
389
|
+
sessionId: string | undefined,
|
|
390
|
+
messages: ChatMessage[],
|
|
391
|
+
): ChatMessage[] {
|
|
392
|
+
if (!Array.isArray(messages) || messages.length === 0) return messages;
|
|
393
|
+
if (!sessionId) return messages;
|
|
394
|
+
const loader = h.ctx?.providerLoader;
|
|
395
|
+
if (!loader) return messages;
|
|
396
|
+
let showSetting: unknown = undefined;
|
|
397
|
+
try {
|
|
398
|
+
showSetting = (loader as any).getSettingValue?.(providerType, 'showCoordinatorSystemPrompt');
|
|
399
|
+
} catch { /* unknown setting key for this provider — fall through */ }
|
|
400
|
+
if (showSetting === true) return messages;
|
|
401
|
+
const coord = getCoordinatorForSession(sessionId);
|
|
402
|
+
if (!coord) return messages;
|
|
403
|
+
const promptBody = typeof coord.systemPrompt === 'string' ? coord.systemPrompt : '';
|
|
404
|
+
const MARKER = 'adhdev-mesh-coordinator-prompt';
|
|
405
|
+
const filtered = messages.filter(m => {
|
|
406
|
+
const role = String((m as any)?.role || '').toLowerCase();
|
|
407
|
+
if (role !== 'user' && role !== 'system') return true;
|
|
408
|
+
const content = flattenContent((m as any)?.content);
|
|
409
|
+
if (!content) return true;
|
|
410
|
+
if (content.includes(MARKER)) return false;
|
|
411
|
+
if (promptBody && content.includes(promptBody.slice(0, Math.min(400, promptBody.length)))) return false;
|
|
412
|
+
return true;
|
|
413
|
+
});
|
|
414
|
+
if (filtered.length !== messages.length) {
|
|
415
|
+
LOG.debug('ChatFilter', `[${providerType}] hid ${messages.length - filtered.length} coordinator-prompt message(s) from ${sessionId}`);
|
|
416
|
+
}
|
|
417
|
+
return filtered;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Convenience wrapper used at every native-history call site: normalize +
|
|
422
|
+
* conditionally drop the coordinator system-prompt message. Avoids
|
|
423
|
+
* duplicating the filter at four read_chat code paths.
|
|
424
|
+
*/
|
|
425
|
+
function normalizeAndFilterNativeHistory(
|
|
426
|
+
h: CommandHelpers,
|
|
427
|
+
providerType: string,
|
|
428
|
+
args: any,
|
|
429
|
+
messages: ChatMessage[],
|
|
430
|
+
nativeSessionId?: string,
|
|
431
|
+
): ChatMessage[] {
|
|
432
|
+
const normalized = normalizeNativeHistoryMessages(providerType, messages, nativeSessionId);
|
|
433
|
+
const sessionId = typeof args?.targetSessionId === 'string' ? args.targetSessionId
|
|
434
|
+
: typeof args?.sessionId === 'string' ? args.sessionId
|
|
435
|
+
: undefined;
|
|
436
|
+
return maybeHideCoordinatorPromptMessage(h, providerType, sessionId, normalized);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function normalizeNativeHistoryMessages(providerType: string, messages: ChatMessage[], nativeSessionId?: string): ChatMessage[] {
|
|
440
|
+
let turnIndex = 0;
|
|
441
|
+
return normalizeChatMessages(messages).map((message, index) => {
|
|
442
|
+
const role = typeof message.role === 'string' ? message.role.trim().toLowerCase() : '';
|
|
443
|
+
const kind = typeof message.kind === 'string' && message.kind.trim() ? message.kind.trim() : (role === 'system' ? 'system' : 'standard');
|
|
444
|
+
if ((role === 'user' || role === 'human') && index > 0) turnIndex += 1;
|
|
445
|
+
const historySessionId = typeof (message as any).historySessionId === 'string'
|
|
446
|
+
? (message as any).historySessionId.trim()
|
|
447
|
+
: '';
|
|
448
|
+
const contentHash = hashSignatureParts([
|
|
449
|
+
providerType,
|
|
450
|
+
historySessionId,
|
|
451
|
+
String(message.receivedAt || message.timestamp || index),
|
|
452
|
+
role,
|
|
453
|
+
kind,
|
|
454
|
+
flattenContent(message.content),
|
|
455
|
+
]).slice(0, 12);
|
|
456
|
+
const nativeIdentitySessionId = historySessionId || (typeof nativeSessionId === 'string' ? nativeSessionId.trim() : '');
|
|
457
|
+
const preserveNativeIdentity = shouldPreserveNativeIdentity(providerType, nativeIdentitySessionId, message);
|
|
458
|
+
const existingProviderUnitKey = typeof message.providerUnitKey === 'string' ? message.providerUnitKey.trim() : '';
|
|
459
|
+
const existingTurnKey = typeof message._turnKey === 'string' ? message._turnKey.trim() : '';
|
|
460
|
+
const providerUnitKey = preserveNativeIdentity
|
|
461
|
+
? existingProviderUnitKey
|
|
462
|
+
: `${providerType}:native:${nativeIdentitySessionId || 'workspace'}:${index}:${role || 'message'}:${kind}:${contentHash}`;
|
|
463
|
+
const meta = message.meta && typeof message.meta === 'object' ? message.meta as Record<string, unknown> : undefined;
|
|
464
|
+
const isSystemSessionStart = role === 'system' || kind === 'system' || kind === 'session_start';
|
|
465
|
+
const isActivity = role === 'assistant' && (kind === 'tool' || kind === 'terminal' || kind === 'thought');
|
|
466
|
+
// (A2.3) sequence emit. Producer-supplied wins (v2-stamped messages
|
|
467
|
+
// bring their own monotonic sequence); otherwise derive from
|
|
468
|
+
// receivedAt/timestamp; otherwise positional. Always present on the
|
|
469
|
+
// output so consumers (ChatSourceMachine) have a stable ordering key.
|
|
470
|
+
const existingSequence = typeof (message as any).sequence === 'number'
|
|
471
|
+
&& Number.isFinite((message as any).sequence)
|
|
472
|
+
? (message as any).sequence
|
|
473
|
+
: null;
|
|
474
|
+
const tsCandidate = Number(message.receivedAt || message.timestamp || 0);
|
|
475
|
+
const sequence = existingSequence !== null
|
|
476
|
+
? existingSequence
|
|
477
|
+
: (tsCandidate > 0 ? tsCandidate : index);
|
|
478
|
+
return {
|
|
479
|
+
...message,
|
|
480
|
+
role: role === 'human' ? 'user' : (role || 'assistant'),
|
|
481
|
+
kind: isSystemSessionStart ? 'system' : kind,
|
|
482
|
+
...(nativeIdentitySessionId ? { historySessionId: nativeIdentitySessionId } : {}),
|
|
483
|
+
providerUnitKey,
|
|
484
|
+
bubbleId: typeof message.bubbleId === 'string' && message.bubbleId.trim()
|
|
485
|
+
&& preserveNativeIdentity
|
|
486
|
+
? message.bubbleId.trim()
|
|
487
|
+
: `bubble:${providerUnitKey}`,
|
|
488
|
+
sequence,
|
|
489
|
+
_turnKey: preserveNativeIdentity
|
|
490
|
+
? existingTurnKey
|
|
491
|
+
: `${providerType}:native-turn:${nativeIdentitySessionId || 'workspace'}:${turnIndex}`,
|
|
492
|
+
bubbleState: message.bubbleState || 'final',
|
|
493
|
+
...(isSystemSessionStart ? {
|
|
494
|
+
visibility: message.visibility || 'hidden',
|
|
495
|
+
transcriptVisibility: message.transcriptVisibility || 'hidden',
|
|
496
|
+
audience: message.audience || 'internal',
|
|
497
|
+
source: message.source || 'runtime_status',
|
|
498
|
+
} : isActivity ? {
|
|
499
|
+
source: message.source || (kind === 'terminal' ? 'terminal_command' : 'tool_call'),
|
|
500
|
+
meta: { ...meta, label: message.senderName || meta?.label || (kind === 'terminal' ? 'Terminal' : 'Tool') },
|
|
501
|
+
} : {
|
|
502
|
+
source: message.source || (role === 'assistant' ? 'assistant_text' : undefined),
|
|
503
|
+
}),
|
|
504
|
+
} as ChatMessage;
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
function buildCliMessageSourceProvenance(args: {
|
|
509
|
+
selected: 'native-history' | 'pty-parser';
|
|
510
|
+
provider: string;
|
|
511
|
+
nativeHandle?: string;
|
|
512
|
+
sessionWorkspace?: string;
|
|
513
|
+
intendedWorkspace?: string;
|
|
514
|
+
transcriptWorkspace?: string;
|
|
515
|
+
fallbackReason?: string;
|
|
516
|
+
nativeSource?: string;
|
|
517
|
+
sourcePath?: string;
|
|
518
|
+
sourceMtimeMs?: number;
|
|
519
|
+
nativeHistoryCoverage?: string;
|
|
520
|
+
partialReason?: string;
|
|
521
|
+
unavailableReason?: string;
|
|
522
|
+
nativeMessages?: ChatMessage[];
|
|
523
|
+
ptyMessages?: ChatMessage[];
|
|
524
|
+
returnedMessages?: ChatMessage[];
|
|
525
|
+
safeMapping?: boolean;
|
|
526
|
+
freshEnough?: boolean;
|
|
527
|
+
ptyStatusApprovalOnly?: boolean;
|
|
528
|
+
}): Record<string, unknown> {
|
|
529
|
+
const sourceMtimeMs = Number(args.sourceMtimeMs || 0);
|
|
530
|
+
const sourceMtimeAgeMs = sourceMtimeMs > 0 ? Math.max(0, Date.now() - sourceMtimeMs) : undefined;
|
|
531
|
+
const nativeMessages = args.nativeMessages || [];
|
|
532
|
+
const ptyMessages = args.ptyMessages || [];
|
|
533
|
+
const returnedMessages = args.returnedMessages || [];
|
|
534
|
+
const identityStatus = args.selected === 'native-history'
|
|
535
|
+
? 'safe'
|
|
536
|
+
: args.fallbackReason === 'native_history_not_safely_mapped'
|
|
537
|
+
? 'ambiguous_session_identity'
|
|
538
|
+
: args.fallbackReason?.startsWith('native_history_unavailable')
|
|
539
|
+
? 'transcript_unmapped'
|
|
540
|
+
: undefined;
|
|
541
|
+
return {
|
|
542
|
+
selected: args.selected,
|
|
543
|
+
provider: args.provider,
|
|
544
|
+
providerType: args.provider,
|
|
545
|
+
...(identityStatus ? { identityStatus } : {}),
|
|
546
|
+
...(args.nativeHandle ? { nativeHandle: args.nativeHandle } : {}),
|
|
547
|
+
...(args.nativeHandle ? { nativeSessionId: args.nativeHandle } : {}),
|
|
548
|
+
...(args.sessionWorkspace ? { sessionWorkspace: args.sessionWorkspace } : {}),
|
|
549
|
+
...(args.intendedWorkspace ? { intendedWorkspace: args.intendedWorkspace } : {}),
|
|
550
|
+
...(args.transcriptWorkspace ? { transcriptWorkspace: args.transcriptWorkspace } : {}),
|
|
551
|
+
...(args.fallbackReason ? { fallbackReason: args.fallbackReason } : {}),
|
|
552
|
+
...(args.nativeSource ? { nativeSource: args.nativeSource } : {}),
|
|
553
|
+
...(args.sourcePath ? { sourcePath: args.sourcePath } : {}),
|
|
554
|
+
...(args.nativeHistoryCoverage ? { nativeHistoryCoverage: args.nativeHistoryCoverage } : {}),
|
|
555
|
+
...(args.partialReason ? { partialReason: args.partialReason } : {}),
|
|
556
|
+
...(args.unavailableReason ? { unavailableReason: args.unavailableReason } : {}),
|
|
557
|
+
ptyStatusApprovalOnly: args.ptyStatusApprovalOnly === true,
|
|
558
|
+
staleness: {
|
|
559
|
+
sourceMtimeMs: sourceMtimeMs || undefined,
|
|
560
|
+
sourceMtimeAgeMs,
|
|
561
|
+
nativeNewestMessageAt: getMessageNewestReceivedAt(nativeMessages),
|
|
562
|
+
ptyNewestMessageAt: getMessageNewestReceivedAt(ptyMessages),
|
|
563
|
+
freshEnough: args.freshEnough === true,
|
|
564
|
+
},
|
|
565
|
+
coverage: {
|
|
566
|
+
nativeMessageCount: nativeMessages.length,
|
|
567
|
+
ptyMessageCount: ptyMessages.length,
|
|
568
|
+
returnedMessageCount: returnedMessages.length,
|
|
569
|
+
safeMapping: args.safeMapping === true,
|
|
570
|
+
// true when PTY message bodies are suppressed and must not be treated as
|
|
571
|
+
// chat content. PTY may still contribute status/approval/screen evidence.
|
|
572
|
+
ptyMessagesSuppressed: args.selected === 'native-history' || args.ptyStatusApprovalOnly === true,
|
|
573
|
+
},
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* Map a ChatSourceMachine transition cause back to the v1 messageSource
|
|
579
|
+
* `fallbackReason` vocabulary so legacy consumers (web-cloud, tests, mesh
|
|
580
|
+
* debug bundles) keep parsing strings they already know. A3 replaces the
|
|
581
|
+
* caller surface with stateTransition/lockState, after which this map can be
|
|
582
|
+
* deleted.
|
|
583
|
+
*
|
|
584
|
+
* Returns undefined when the cause does not correspond to a fallback (i.e.
|
|
585
|
+
* the source is native-history and there is nothing to explain).
|
|
586
|
+
*/
|
|
587
|
+
function causeToLegacyFallbackReason(
|
|
588
|
+
cause: ChatSourceTransitionCause,
|
|
589
|
+
selected: 'native-history' | 'pty-parser',
|
|
590
|
+
extraDetail?: { unavailableReason?: string; nativeSource?: string },
|
|
591
|
+
): string | undefined {
|
|
592
|
+
if (selected === 'native-history') return undefined;
|
|
593
|
+
switch (cause) {
|
|
594
|
+
case 'initial':
|
|
595
|
+
return 'native_history_not_checked';
|
|
596
|
+
case 'native_progressed':
|
|
597
|
+
// Selected pty-parser despite a progressed observation — that
|
|
598
|
+
// means we held PtyOnly stickily (peak unmet or non-superset).
|
|
599
|
+
return 'native_history_not_selected';
|
|
600
|
+
case 'native_regressed_shrunk':
|
|
601
|
+
return 'native_history_empty';
|
|
602
|
+
case 'native_regressed_unsafe_mapping':
|
|
603
|
+
return 'native_history_not_safely_mapped';
|
|
604
|
+
case 'native_regressed_coverage_partial':
|
|
605
|
+
return 'native_history_partial';
|
|
606
|
+
case 'native_regressed_coverage_unavailable':
|
|
607
|
+
return 'native_history_unavailable';
|
|
608
|
+
case 'native_unavailable_read_error':
|
|
609
|
+
return extraDetail?.unavailableReason
|
|
610
|
+
? `native_history_unavailable:${extraDetail.unavailableReason}`
|
|
611
|
+
: 'native_history_unavailable';
|
|
612
|
+
case 'native_unavailable_provider_unsupported':
|
|
613
|
+
return 'provider_native_transcript_not_supported';
|
|
614
|
+
case 'native_unavailable_empty':
|
|
615
|
+
return 'native_history_empty';
|
|
616
|
+
case 'native_unavailable_not_native_source':
|
|
617
|
+
return extraDetail?.nativeSource
|
|
618
|
+
? `native_history_source_${extraDetail.nativeSource}`
|
|
619
|
+
: 'native_history_unavailable';
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* Translate a native-history fetch result + provider/adapter context into a
|
|
625
|
+
* ChatSourceObservation and drive ChatSourceRegistry. Returns the decision
|
|
626
|
+
* together with the legacy messageSource payload so call sites can produce
|
|
627
|
+
* a v1-compatible response without duplicating the registry plumbing.
|
|
628
|
+
*
|
|
629
|
+
* This is the replacement for the 300-line if-ladder that previously lived
|
|
630
|
+
* inline in handleReadChat. It is intentionally split out for two reasons:
|
|
631
|
+
* (1) we will call it from two places (CLI adapter branch + history-only
|
|
632
|
+
* branch) instead of duplicating the ladder, (2) tests can drive it with
|
|
633
|
+
* synthetic native-history results to verify the cause→fallbackReason
|
|
634
|
+
* mapping without booting the whole readChat pipeline.
|
|
635
|
+
*/
|
|
636
|
+
function decideCliReadChatSource(args: {
|
|
637
|
+
providerType: string;
|
|
638
|
+
provider?: ProviderModule;
|
|
639
|
+
sessionId: string;
|
|
640
|
+
nativeHistoryResult: any | null;
|
|
641
|
+
nativeHistoryError?: unknown;
|
|
642
|
+
safeMapping: boolean;
|
|
643
|
+
trustedExactNativeIdentity?: boolean;
|
|
644
|
+
sessionWorkspace?: string;
|
|
645
|
+
intendedWorkspace?: string;
|
|
646
|
+
ptyMessages: ChatMessage[];
|
|
647
|
+
ptyStatusApprovalOnly: boolean;
|
|
648
|
+
}): {
|
|
649
|
+
decision: ChatSourceDecision;
|
|
650
|
+
messageSource: Record<string, unknown>;
|
|
651
|
+
nativeMessages: ChatMessage[];
|
|
652
|
+
nativeSelected: boolean;
|
|
653
|
+
} {
|
|
654
|
+
const supportsNative = supportsCliNativeTranscript(args.providerType, args.provider);
|
|
655
|
+
const observation = buildObservationForCli(args, supportsNative);
|
|
656
|
+
const sessionKey = chatSourceSessionKey(args.providerType, args.sessionId);
|
|
657
|
+
let decision = CHAT_SOURCE_REGISTRY.observe(sessionKey, observation);
|
|
658
|
+
|
|
659
|
+
// A restored runtime can briefly expose different native slices while the
|
|
660
|
+
// provider transcript settles (for example, startup/system rows may be
|
|
661
|
+
// filtered after the first read). The source machine correctly treats a
|
|
662
|
+
// shrinking slice as regression, but an exact provider-session lookup with
|
|
663
|
+
// no PTY transcript has no safer fallback. Re-bootstrap only this proven
|
|
664
|
+
// identity so the chat does not disappear after daemon restart.
|
|
665
|
+
if (
|
|
666
|
+
decision.selected === 'pty-parser'
|
|
667
|
+
&& args.trustedExactNativeIdentity === true
|
|
668
|
+
&& args.safeMapping
|
|
669
|
+
&& args.ptyMessages.length === 0
|
|
670
|
+
&& observation.kind === 'native_present'
|
|
671
|
+
&& observation.coverage !== 'partial'
|
|
672
|
+
&& observation.messages.length > 0
|
|
673
|
+
) {
|
|
674
|
+
CHAT_SOURCE_REGISTRY.clear(sessionKey);
|
|
675
|
+
decision = CHAT_SOURCE_REGISTRY.observe(sessionKey, observation);
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
const nativeMessages: ChatMessage[] = observation.kind === 'native_present'
|
|
679
|
+
? extractNativeMessagesFromResult(args.providerType, args.nativeHistoryResult)
|
|
680
|
+
: [];
|
|
681
|
+
|
|
682
|
+
const nativeSource = typeof args.nativeHistoryResult?.source === 'string'
|
|
683
|
+
? args.nativeHistoryResult.source
|
|
684
|
+
: undefined;
|
|
685
|
+
const sourcePath = typeof args.nativeHistoryResult?.sourcePath === 'string'
|
|
686
|
+
? args.nativeHistoryResult.sourcePath
|
|
687
|
+
: undefined;
|
|
688
|
+
const sourceMtimeMs = typeof args.nativeHistoryResult?.sourceMtimeMs === 'number'
|
|
689
|
+
? args.nativeHistoryResult.sourceMtimeMs
|
|
690
|
+
: undefined;
|
|
691
|
+
const coverageHint = typeof args.nativeHistoryResult?.nativeHistoryCoverage === 'string'
|
|
692
|
+
? args.nativeHistoryResult.nativeHistoryCoverage
|
|
693
|
+
: undefined;
|
|
694
|
+
const partialReason = typeof args.nativeHistoryResult?.partialReason === 'string'
|
|
695
|
+
? args.nativeHistoryResult.partialReason
|
|
696
|
+
: undefined;
|
|
697
|
+
const unavailableReason = typeof args.nativeHistoryResult?.unavailableReason === 'string'
|
|
698
|
+
? args.nativeHistoryResult.unavailableReason
|
|
699
|
+
: args.nativeHistoryError
|
|
700
|
+
? `error:${(args.nativeHistoryError as any)?.message || String(args.nativeHistoryError)}`
|
|
701
|
+
: undefined;
|
|
702
|
+
const nativeHandle = typeof args.nativeHistoryResult?.providerSessionId === 'string'
|
|
703
|
+
? args.nativeHistoryResult.providerSessionId
|
|
704
|
+
: undefined;
|
|
705
|
+
const transcriptWorkspace = typeof args.nativeHistoryResult?.workspace === 'string'
|
|
706
|
+
? args.nativeHistoryResult.workspace
|
|
707
|
+
: nativeMessages.map((m: any) => typeof m?.workspace === 'string' ? m.workspace.trim() : '').find(Boolean);
|
|
708
|
+
|
|
709
|
+
const fallbackReason = causeToLegacyFallbackReason(decision.transition.cause, decision.selected, {
|
|
710
|
+
unavailableReason,
|
|
711
|
+
nativeSource: nativeSource && nativeSource !== 'provider-native' ? nativeSource : undefined,
|
|
712
|
+
});
|
|
713
|
+
|
|
714
|
+
// ptyStatusApprovalOnly: when the machine selected native-history we
|
|
715
|
+
// suppress PTY content so the dashboard does not double-show messages
|
|
716
|
+
// already in the native transcript. When the machine selected
|
|
717
|
+
// pty-parser, PTY is the authoritative source — do NOT suppress it.
|
|
718
|
+
// Callers used to hard-code this to `nativeSelected first = true` which
|
|
719
|
+
// suppressed PTY content even when native was empty/unavailable, leaving
|
|
720
|
+
// the dashboard with zero visible messages (the codex generating/waiting
|
|
721
|
+
// approval stuck state). Trust the machine here, not the caller hint.
|
|
722
|
+
const ptyStatusApprovalOnly = decision.selected === 'native-history'
|
|
723
|
+
? true
|
|
724
|
+
: args.ptyStatusApprovalOnly;
|
|
725
|
+
|
|
726
|
+
const messageSource = buildCliMessageSourceProvenance({
|
|
727
|
+
selected: decision.selected,
|
|
728
|
+
provider: args.providerType,
|
|
729
|
+
nativeHandle,
|
|
730
|
+
sessionWorkspace: args.sessionWorkspace,
|
|
731
|
+
intendedWorkspace: args.intendedWorkspace,
|
|
732
|
+
transcriptWorkspace,
|
|
733
|
+
fallbackReason,
|
|
734
|
+
nativeSource,
|
|
735
|
+
sourcePath,
|
|
736
|
+
sourceMtimeMs,
|
|
737
|
+
nativeHistoryCoverage: coverageHint,
|
|
738
|
+
partialReason,
|
|
739
|
+
unavailableReason,
|
|
740
|
+
nativeMessages,
|
|
741
|
+
ptyMessages: args.ptyMessages,
|
|
742
|
+
returnedMessages: decision.selected === 'native-history' ? nativeMessages : args.ptyMessages,
|
|
743
|
+
safeMapping: args.safeMapping,
|
|
744
|
+
// freshEnough is a v1 concept the machine does not model directly.
|
|
745
|
+
// We surface lockState.locked here so v1 consumers reading
|
|
746
|
+
// staleness.freshEnough still get a meaningful boolean.
|
|
747
|
+
freshEnough: decision.lockState.locked,
|
|
748
|
+
ptyStatusApprovalOnly,
|
|
749
|
+
});
|
|
750
|
+
|
|
751
|
+
return {
|
|
752
|
+
decision,
|
|
753
|
+
messageSource,
|
|
754
|
+
nativeMessages,
|
|
755
|
+
nativeSelected: decision.selected === 'native-history',
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
function buildObservationForCli(
|
|
760
|
+
args: {
|
|
761
|
+
providerType: string;
|
|
762
|
+
sessionId: string;
|
|
763
|
+
nativeHistoryResult: any | null;
|
|
764
|
+
nativeHistoryError?: unknown;
|
|
765
|
+
safeMapping: boolean;
|
|
766
|
+
},
|
|
767
|
+
supportsNative: boolean,
|
|
768
|
+
): ChatSourceObservation {
|
|
769
|
+
if (!supportsNative) {
|
|
770
|
+
return { kind: 'native_unavailable', reason: 'provider_not_supported' };
|
|
771
|
+
}
|
|
772
|
+
if (args.nativeHistoryError) {
|
|
773
|
+
return { kind: 'native_unavailable', reason: 'read_error' };
|
|
774
|
+
}
|
|
775
|
+
const result = args.nativeHistoryResult;
|
|
776
|
+
if (!result || typeof result !== 'object') {
|
|
777
|
+
return { kind: 'native_unavailable', reason: 'read_error' };
|
|
778
|
+
}
|
|
779
|
+
const source = typeof result.source === 'string' ? result.source : '';
|
|
780
|
+
if (source && source !== 'provider-native') {
|
|
781
|
+
// 'native-unavailable' or other producer-side declined source.
|
|
782
|
+
return { kind: 'native_unavailable', reason: source === 'native-unavailable' ? 'empty' : 'not_native_source' };
|
|
783
|
+
}
|
|
784
|
+
const messages = Array.isArray(result.messages) ? result.messages : [];
|
|
785
|
+
if (messages.length === 0) {
|
|
786
|
+
return { kind: 'native_unavailable', reason: 'empty' };
|
|
787
|
+
}
|
|
788
|
+
const coverage = typeof result.nativeHistoryCoverage === 'string'
|
|
789
|
+
? result.nativeHistoryCoverage
|
|
790
|
+
: 'tail';
|
|
791
|
+
if (coverage === 'unavailable') {
|
|
792
|
+
return { kind: 'native_unavailable', reason: 'coverage_unavailable' };
|
|
793
|
+
}
|
|
794
|
+
return buildV1NativePresentObservation({
|
|
795
|
+
providerType: args.providerType,
|
|
796
|
+
sessionId: args.sessionId,
|
|
797
|
+
messages,
|
|
798
|
+
coverage: coverage === 'full' || coverage === 'tail' || coverage === 'current-turn' || coverage === 'partial'
|
|
799
|
+
? coverage
|
|
800
|
+
: 'tail',
|
|
801
|
+
safeMapping: args.safeMapping,
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
function extractNativeMessagesFromResult(providerType: string, result: any): ChatMessage[] {
|
|
806
|
+
if (!result || !Array.isArray(result.messages)) return [];
|
|
807
|
+
return normalizeNativeHistoryMessages(
|
|
808
|
+
providerType,
|
|
809
|
+
result.messages as ChatMessage[],
|
|
810
|
+
typeof result.providerSessionId === 'string' ? result.providerSessionId : undefined,
|
|
811
|
+
);
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
/**
|
|
815
|
+
* ptyStatusApprovalOnly is true when the daemon should treat PTY content as
|
|
816
|
+
* status/approval signal only (not as chat messages). v1 set this to `true`
|
|
817
|
+
* whenever native-history was selected as the source, and `false` otherwise.
|
|
818
|
+
* The machine equivalent: when native is the source we want PTY suppressed.
|
|
819
|
+
*/
|
|
820
|
+
function primaryPtyApprovalOnlyFor(_cliType: string, nativeSelected: boolean): boolean {
|
|
821
|
+
return nativeSelected;
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
/**
|
|
825
|
+
* Codex-only unsafe-native fallback: when the primary native fetch produced
|
|
826
|
+
* unsafe-mapping data, v1 attempted to recover by reading exact runtime
|
|
827
|
+
* mirror messages, runtime input ACK messages, or by trusting the current-
|
|
828
|
+
* runtime PTY when safely attributed. None of this is the machine's
|
|
829
|
+
* responsibility — the machine already decided pty-parser. This helper
|
|
830
|
+
* preserves the daemon-side message selection and annotates messageSource.
|
|
831
|
+
*/
|
|
832
|
+
function applyUnsafeNativeDaemonFallback(args: {
|
|
833
|
+
providerType: string;
|
|
834
|
+
adapter: CliAdapter;
|
|
835
|
+
helpers: CommandHelpers;
|
|
836
|
+
readChatArgs: any;
|
|
837
|
+
sessionWorkspace?: string;
|
|
838
|
+
intendedWorkspace?: string;
|
|
839
|
+
ptyMessages: ChatMessage[];
|
|
840
|
+
nativeHistoryLimit: number;
|
|
841
|
+
provider?: ProviderModule;
|
|
842
|
+
messageSourceRef: { set(value: Record<string, unknown>): void; get(): Record<string, unknown> };
|
|
843
|
+
apply(selection: {
|
|
844
|
+
messages: ChatMessage[];
|
|
845
|
+
transcriptAuthority?: 'provider' | 'daemon';
|
|
846
|
+
coverage?: 'full' | 'tail' | 'current-turn';
|
|
847
|
+
status?: string;
|
|
848
|
+
}): void;
|
|
849
|
+
activeModal: unknown;
|
|
850
|
+
returnedStatus: string;
|
|
851
|
+
coverage?: 'full' | 'tail' | 'current-turn';
|
|
852
|
+
}): void {
|
|
853
|
+
if (args.adapter.cliType !== 'codex-cli') {
|
|
854
|
+
// Only codex-cli had v1 daemon mirror recovery. Other providers skip.
|
|
855
|
+
return;
|
|
856
|
+
}
|
|
857
|
+
const ms = args.messageSourceRef.get();
|
|
858
|
+
const fallbackReason = typeof ms.fallbackReason === 'string' ? ms.fallbackReason : '';
|
|
859
|
+
if (!isUnsafeNativeTranscriptFallback(fallbackReason)) {
|
|
860
|
+
return;
|
|
861
|
+
}
|
|
862
|
+
const safeCurrentRuntimePtyMessages = isCurrentRuntimePtySafelyAttributed({
|
|
863
|
+
adapter: args.adapter,
|
|
864
|
+
helpers: args.helpers,
|
|
865
|
+
readChatArgs: args.readChatArgs,
|
|
866
|
+
sessionWorkspace: args.sessionWorkspace,
|
|
867
|
+
intendedWorkspace: args.intendedWorkspace,
|
|
868
|
+
ptyMessages: args.ptyMessages,
|
|
869
|
+
});
|
|
870
|
+
if (safeCurrentRuntimePtyMessages) {
|
|
871
|
+
args.apply({
|
|
872
|
+
messages: args.ptyMessages,
|
|
873
|
+
transcriptAuthority: 'daemon',
|
|
874
|
+
coverage: args.coverage || 'current-turn',
|
|
875
|
+
status: args.returnedStatus,
|
|
876
|
+
});
|
|
877
|
+
const next = { ...ms, selectedDaemonSource: 'current-runtime-pty', transcriptAuthority: 'daemon', runtimeMappingSafe: true };
|
|
878
|
+
args.messageSourceRef.set(next);
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
const safeRuntimeAckMessages = selectRuntimeInputAckMessages(args.ptyMessages);
|
|
882
|
+
if (safeRuntimeAckMessages.length > 0) {
|
|
883
|
+
args.apply({
|
|
884
|
+
messages: safeRuntimeAckMessages,
|
|
885
|
+
transcriptAuthority: 'daemon',
|
|
886
|
+
coverage: 'tail',
|
|
887
|
+
status: coerceUnsafeNativeFallbackStatus(args.returnedStatus, args.activeModal),
|
|
888
|
+
});
|
|
889
|
+
const next = { ...ms, ptyStatusApprovalOnly: true };
|
|
890
|
+
args.messageSourceRef.set(next);
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
const exactRuntimeMirrorMessages = readExactRuntimeMirrorMessages({
|
|
894
|
+
providerType: args.providerType,
|
|
895
|
+
targetSessionId: typeof args.readChatArgs?.targetSessionId === 'string' ? args.readChatArgs.targetSessionId : undefined,
|
|
896
|
+
currentSessionId: typeof (args.helpers.currentSession as any)?.sessionId === 'string' ? (args.helpers.currentSession as any).sessionId : undefined,
|
|
897
|
+
tailLimit: args.nativeHistoryLimit,
|
|
898
|
+
historyBehavior: args.provider?.historyBehavior,
|
|
899
|
+
});
|
|
900
|
+
if (exactRuntimeMirrorMessages.length > 0) {
|
|
901
|
+
args.apply({
|
|
902
|
+
messages: exactRuntimeMirrorMessages,
|
|
903
|
+
transcriptAuthority: 'daemon',
|
|
904
|
+
coverage: 'tail',
|
|
905
|
+
status: coerceUnsafeNativeFallbackStatus(args.returnedStatus, args.activeModal),
|
|
906
|
+
});
|
|
907
|
+
const next = { ...ms, selectedDaemonSource: 'exact-runtime-mirror', transcriptAuthority: 'daemon', ptyStatusApprovalOnly: true };
|
|
908
|
+
args.messageSourceRef.set(next);
|
|
909
|
+
return;
|
|
910
|
+
}
|
|
911
|
+
// No daemon mirror available — keep PTY messages as-is (still pty-parser
|
|
912
|
+
// selection); just coerce status for waiting_approval consistency.
|
|
913
|
+
args.apply({
|
|
914
|
+
messages: args.ptyMessages,
|
|
915
|
+
coverage: args.coverage,
|
|
916
|
+
status: coerceUnsafeNativeFallbackStatus(args.returnedStatus, args.activeModal),
|
|
917
|
+
});
|
|
918
|
+
const next = { ...ms, ptyStatusApprovalOnly: true };
|
|
919
|
+
args.messageSourceRef.set(next);
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
// (A2.2) buildNativeHistoryFallbackReason removed. ChatSourceMachine emits a
|
|
923
|
+
// ChatSourceTransitionCause; causeToLegacyFallbackReason maps it back to the
|
|
924
|
+
// v1 vocabulary for response compatibility. A3 deletes the v1 vocabulary
|
|
925
|
+
// entirely and surfaces stateTransition/lockState directly.
|
|
926
|
+
|
|
927
|
+
function isUnsafeNativeTranscriptFallback(reason?: string): boolean {
|
|
928
|
+
const value = String(reason || '').trim();
|
|
929
|
+
return value.startsWith('native_history_unavailable')
|
|
930
|
+
|| value === 'native_history_not_safely_mapped'
|
|
931
|
+
|| value === 'native_history_stale'
|
|
932
|
+
|| value === 'native_history_partial';
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
function coerceUnsafeNativeFallbackStatus(status: string, activeModal: unknown): string {
|
|
936
|
+
if (status === 'waiting_approval' && activeModal) return status;
|
|
937
|
+
return 'idle';
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
function isRuntimeInputAckMessage(message: ChatMessage | undefined): boolean {
|
|
941
|
+
if (!message || typeof message !== 'object') return false;
|
|
942
|
+
const role = String((message as any).role || '').trim().toLowerCase();
|
|
943
|
+
if (role !== 'user' && role !== 'human') return false;
|
|
944
|
+
const meta = (message as any).meta;
|
|
945
|
+
return !!meta && typeof meta === 'object' && !Array.isArray(meta) && meta.runtimeInputAck === true;
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
function selectRuntimeInputAckMessages(messages: ChatMessage[]): ChatMessage[] {
|
|
949
|
+
return messages.filter((message) => isRuntimeInputAckMessage(message));
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
function readExactRuntimeMirrorMessages(args: {
|
|
953
|
+
providerType: string;
|
|
954
|
+
targetSessionId?: string;
|
|
955
|
+
currentSessionId?: string;
|
|
956
|
+
tailLimit: number;
|
|
957
|
+
historyBehavior?: ProviderModule['historyBehavior'];
|
|
958
|
+
}): ChatMessage[] {
|
|
959
|
+
const targetSessionId = String(args.targetSessionId || '').trim();
|
|
960
|
+
const currentSessionId = String(args.currentSessionId || '').trim();
|
|
961
|
+
if (!targetSessionId || targetSessionId !== currentSessionId) return [];
|
|
962
|
+
|
|
963
|
+
const history = readChatHistory(
|
|
964
|
+
args.providerType,
|
|
965
|
+
0,
|
|
966
|
+
Math.max(args.tailLimit || 0, 200),
|
|
967
|
+
targetSessionId,
|
|
968
|
+
0,
|
|
969
|
+
args.historyBehavior,
|
|
970
|
+
);
|
|
971
|
+
return normalizeChatMessages((history.messages || []) as ChatMessage[])
|
|
972
|
+
.filter((message) => {
|
|
973
|
+
const historySessionId = String((message as any).historySessionId || '').trim();
|
|
974
|
+
const instanceId = String((message as any).instanceId || '').trim();
|
|
975
|
+
return historySessionId === targetSessionId || instanceId === targetSessionId;
|
|
976
|
+
});
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
function normalizeComparableWorkspace(value: unknown): string {
|
|
980
|
+
const text = typeof value === 'string' ? value.trim() : '';
|
|
981
|
+
if (!text) return '';
|
|
982
|
+
return path.resolve(text);
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
function isCurrentRuntimePtySafelyAttributed(args: {
|
|
986
|
+
adapter: CliAdapter;
|
|
987
|
+
helpers: CommandHelpers;
|
|
988
|
+
readChatArgs: any;
|
|
989
|
+
sessionWorkspace?: string;
|
|
990
|
+
intendedWorkspace?: string;
|
|
991
|
+
ptyMessages: ChatMessage[];
|
|
992
|
+
}): boolean {
|
|
993
|
+
if (args.adapter.cliType !== 'codex-cli') return false;
|
|
994
|
+
if (!Array.isArray(args.ptyMessages) || args.ptyMessages.length === 0) return false;
|
|
995
|
+
const targetSessionId = typeof args.readChatArgs?.targetSessionId === 'string'
|
|
996
|
+
? args.readChatArgs.targetSessionId.trim()
|
|
997
|
+
: '';
|
|
998
|
+
const currentSession = args.helpers.currentSession as any;
|
|
999
|
+
const currentSessionId = typeof currentSession?.sessionId === 'string'
|
|
1000
|
+
? currentSession.sessionId.trim()
|
|
1001
|
+
: '';
|
|
1002
|
+
if (!targetSessionId || !currentSessionId || targetSessionId !== currentSessionId) return false;
|
|
1003
|
+
|
|
1004
|
+
const runtimeMeta = typeof (args.adapter as any).getRuntimeMetadata === 'function'
|
|
1005
|
+
? (args.adapter as any).getRuntimeMetadata()
|
|
1006
|
+
: null;
|
|
1007
|
+
const runtimeId = typeof runtimeMeta?.runtimeId === 'string' ? runtimeMeta.runtimeId.trim() : '';
|
|
1008
|
+
if (!runtimeId || runtimeId !== targetSessionId) return false;
|
|
1009
|
+
const surfaceKind = typeof runtimeMeta?.surfaceKind === 'string' ? runtimeMeta.surfaceKind : '';
|
|
1010
|
+
if (surfaceKind === 'inactive_record' || surfaceKind === 'recovery_snapshot') return false;
|
|
1011
|
+
|
|
1012
|
+
const sessionWorkspace = normalizeComparableWorkspace(args.sessionWorkspace);
|
|
1013
|
+
const adapterWorkspace = normalizeComparableWorkspace(args.adapter.workingDir);
|
|
1014
|
+
if (!sessionWorkspace || !adapterWorkspace || sessionWorkspace !== adapterWorkspace) return false;
|
|
1015
|
+
const intendedWorkspace = normalizeComparableWorkspace(args.intendedWorkspace);
|
|
1016
|
+
if (intendedWorkspace && intendedWorkspace !== sessionWorkspace) return false;
|
|
1017
|
+
|
|
1018
|
+
const registryEntry = args.helpers.ctx?.sessionRegistry?.get?.(targetSessionId) as any;
|
|
1019
|
+
const registryInstanceKey = typeof registryEntry?.adapterKey === 'string' && registryEntry.adapterKey.trim()
|
|
1020
|
+
? registryEntry.adapterKey.trim()
|
|
1021
|
+
: typeof registryEntry?.instanceKey === 'string' && registryEntry.instanceKey.trim()
|
|
1022
|
+
? registryEntry.instanceKey.trim()
|
|
1023
|
+
: '';
|
|
1024
|
+
if (registryInstanceKey) {
|
|
1025
|
+
const targetInstance = args.helpers.ctx?.instanceManager?.getInstance?.(registryInstanceKey);
|
|
1026
|
+
if (targetInstance) {
|
|
1027
|
+
const instanceType = typeof (targetInstance as any).type === 'string' ? (targetInstance as any).type : '';
|
|
1028
|
+
if (instanceType && instanceType !== args.adapter.cliType) return false;
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
return true;
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
function supportsCliNativeTranscript(providerType: string, provider?: ProviderModule): boolean {
|
|
1036
|
+
// Preferred path: the provider module declares canonicalHistory in its
|
|
1037
|
+
// provider.json. We trust that declaration regardless of the legacy
|
|
1038
|
+
// allow-list. A2 will additionally require canonicalHistory.contractVersion
|
|
1039
|
+
// to be a supported value (transcript-v2.ts).
|
|
1040
|
+
if (provider?.category === 'cli' && isNativeSourceCanonicalHistory(provider?.nativeHistory)) {
|
|
1041
|
+
return true;
|
|
1042
|
+
}
|
|
1043
|
+
// Last-resort fallback for early call sites where the provider module is
|
|
1044
|
+
// not yet loaded. Warn once per provider type so this dependency is visible
|
|
1045
|
+
// and can be removed in A2.
|
|
1046
|
+
if (CLI_NATIVE_TRANSCRIPT_PROVIDERS.has(providerType)) {
|
|
1047
|
+
warnLegacyNativeAllowlistHit(providerType);
|
|
1048
|
+
return true;
|
|
1049
|
+
}
|
|
1050
|
+
return false;
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
function getComparableVisibleText(message: ChatMessage | undefined): string {
|
|
1054
|
+
if (!message) return '';
|
|
1055
|
+
const role = String((message as any).role || '').trim().toLowerCase();
|
|
1056
|
+
if (role !== 'user' && role !== 'assistant') return '';
|
|
1057
|
+
const kind = String((message as any).kind || 'standard').trim().toLowerCase();
|
|
1058
|
+
if (kind && kind !== 'standard') return '';
|
|
1059
|
+
const content = flattenContent((message as any).content).replace(/\s+/g, ' ').trim();
|
|
1060
|
+
return content;
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
function hasOverlappingVisibleConversationText(nativeMessages: ChatMessage[], ptyMessages: ChatMessage[]): boolean {
|
|
1064
|
+
const nativeTexts = nativeMessages.map(getComparableVisibleText).filter(Boolean);
|
|
1065
|
+
const ptyTexts = ptyMessages.map(getComparableVisibleText).filter(Boolean);
|
|
1066
|
+
if (nativeTexts.length === 0 || ptyTexts.length === 0) return false;
|
|
1067
|
+
for (const nativeText of nativeTexts) {
|
|
1068
|
+
for (const ptyText of ptyTexts) {
|
|
1069
|
+
if (nativeText === ptyText) return true;
|
|
1070
|
+
const shorter = nativeText.length <= ptyText.length ? nativeText : ptyText;
|
|
1071
|
+
const longer = nativeText.length <= ptyText.length ? ptyText : nativeText;
|
|
1072
|
+
if (shorter.length >= 32 && longer.includes(shorter)) return true;
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
return false;
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
function hasSafeNativeHistoryMapping(args: {
|
|
1079
|
+
historySessionId?: string;
|
|
1080
|
+
providerSessionId?: string;
|
|
1081
|
+
workspace?: string;
|
|
1082
|
+
nativeMessages: ChatMessage[];
|
|
1083
|
+
ptyMessages?: ChatMessage[];
|
|
1084
|
+
requireWorkspaceContentOverlap?: boolean;
|
|
1085
|
+
}): boolean {
|
|
1086
|
+
const isCoordinatorTranscript = args.nativeMessages.some((m: any) => {
|
|
1087
|
+
const text = typeof m?.content === 'string' ? m.content : JSON.stringify(m?.content || '');
|
|
1088
|
+
return text.includes('mesh_send_task') || text.includes('mesh_status') || text.includes('mesh_read_chat') || text.includes('mesh_launch_session');
|
|
1089
|
+
});
|
|
1090
|
+
|
|
1091
|
+
const explicitSessionId = String(args.historySessionId || args.providerSessionId || '').trim();
|
|
1092
|
+
if (explicitSessionId) {
|
|
1093
|
+
const expectedWorkspace = normalizeComparableWorkspace(args.workspace);
|
|
1094
|
+
const declaredWorkspaces = args.nativeMessages
|
|
1095
|
+
.map((message: any) => normalizeComparableWorkspace(message?.workspace))
|
|
1096
|
+
.filter(Boolean);
|
|
1097
|
+
if (
|
|
1098
|
+
expectedWorkspace
|
|
1099
|
+
&& declaredWorkspaces.length > 0
|
|
1100
|
+
&& !declaredWorkspaces.some((workspace) => workspace === expectedWorkspace)
|
|
1101
|
+
) {
|
|
1102
|
+
return false;
|
|
1103
|
+
}
|
|
1104
|
+
const messageSessionIds = args.nativeMessages
|
|
1105
|
+
.map((message: any) => typeof message?.historySessionId === 'string' ? message.historySessionId.trim() : '')
|
|
1106
|
+
.filter(Boolean);
|
|
1107
|
+
if (messageSessionIds.length > 0) {
|
|
1108
|
+
return messageSessionIds.some((id) => id === explicitSessionId);
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
// Messages carry no historySessionId — cannot confirm they belong to the requested session.
|
|
1112
|
+
// Only allow a coordinator transcript that is also confirmed by the PTY side; otherwise
|
|
1113
|
+
// fail closed so a same-workspace session's history is never silently accepted.
|
|
1114
|
+
if (isCoordinatorTranscript && args.ptyMessages && args.ptyMessages.length > 0) {
|
|
1115
|
+
const ptyHasCoordinator = args.ptyMessages.some((m: any) => {
|
|
1116
|
+
const text = typeof m?.content === 'string' ? m.content : JSON.stringify(m?.content || '');
|
|
1117
|
+
return text.includes('mesh_send_task') || text.includes('mesh_status') || text.includes('mesh_read_chat');
|
|
1118
|
+
});
|
|
1119
|
+
return ptyHasCoordinator;
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
// No historySessionId in messages and no coordinator cross-check: fail closed.
|
|
1123
|
+
// Workspace-only matching must not override an explicit session identity.
|
|
1124
|
+
return false;
|
|
1125
|
+
}
|
|
1126
|
+
const workspace = String(args.workspace || '').trim();
|
|
1127
|
+
if (!workspace) return false;
|
|
1128
|
+
const workspaceMatches = args.nativeMessages.some((message: any) => String(message?.workspace || '').trim() === workspace);
|
|
1129
|
+
if (!workspaceMatches) return false;
|
|
1130
|
+
|
|
1131
|
+
if (isCoordinatorTranscript && args.ptyMessages && args.ptyMessages.length > 0) {
|
|
1132
|
+
const ptyHasCoordinator = args.ptyMessages.some((m: any) => {
|
|
1133
|
+
const text = typeof m?.content === 'string' ? m.content : JSON.stringify(m?.content || '');
|
|
1134
|
+
return text.includes('mesh_send_task') || text.includes('mesh_status') || text.includes('mesh_read_chat');
|
|
1135
|
+
});
|
|
1136
|
+
if (!ptyHasCoordinator) {
|
|
1137
|
+
return false;
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
if (!args.requireWorkspaceContentOverlap) return true;
|
|
1142
|
+
return hasOverlappingVisibleConversationText(args.nativeMessages, args.ptyMessages || []);
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
// Provenance boundary: workspace-only native history lookup is never safe
|
|
1146
|
+
// because multiple concurrent sessions sharing the same cwd would alias each
|
|
1147
|
+
// other. historySessionId (the provider-native session key) is required to
|
|
1148
|
+
// establish ownership. hasSafeNativeHistoryMapping() enforces the same
|
|
1149
|
+
// invariant after the read; both guards must hold for native history to be used.
|
|
1150
|
+
/**
|
|
1151
|
+
* Pull the session's spawnedAtMs out of the registry. Native-history
|
|
1152
|
+
* file pickers use it as a "files older than this can't be from this
|
|
1153
|
+
* session" floor; without it a fresh dashboard view would inherit the
|
|
1154
|
+
* previous session's transcript whenever its file happened to be the
|
|
1155
|
+
* newest match. Returns undefined when the session isn't registered
|
|
1156
|
+
* (e.g. read_chat before the live session was wired up) — the executor
|
|
1157
|
+
* treats undefined as "no floor".
|
|
1158
|
+
*/
|
|
1159
|
+
function sessionStartedAtMsFromRegistry(h: CommandHelpers, targetSessionId: string | undefined): number | undefined {
|
|
1160
|
+
const sid = typeof targetSessionId === 'string' ? targetSessionId.trim() : '';
|
|
1161
|
+
if (!sid) return undefined;
|
|
1162
|
+
const target = h.ctx?.sessionRegistry?.get?.(sid);
|
|
1163
|
+
return typeof target?.spawnedAtMs === 'number' ? target.spawnedAtMs : undefined;
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
/**
|
|
1167
|
+
* Pull the env vars the daemon set when it spawned this session's CLI.
|
|
1168
|
+
* Mesh coordinator points hermes at a per-coordinator HERMES_HOME so
|
|
1169
|
+
* the native-history reader needs that override to find the right
|
|
1170
|
+
* state.db; without it the reader sees ~/.hermes/state.db and misses
|
|
1171
|
+
* every coordinator-session transcript.
|
|
1172
|
+
*
|
|
1173
|
+
* Returns undefined when no SpecCliAdapter is in play (legacy
|
|
1174
|
+
* providers / CDP) or when the adapter exposes no spawn env.
|
|
1175
|
+
*/
|
|
1176
|
+
function sessionSpawnEnvFromAdapter(h: CommandHelpers, targetSessionId: string | undefined): Record<string, string> | undefined {
|
|
1177
|
+
const adapter = getTargetedCliAdapter(h, { targetSessionId }, undefined);
|
|
1178
|
+
if (!adapter || typeof adapter.getRuntimeMetadata !== 'function') return undefined;
|
|
1179
|
+
const meta = adapter.getRuntimeMetadata() as Record<string, unknown> | undefined;
|
|
1180
|
+
const env = meta && typeof meta === 'object' ? (meta as Record<string, unknown>).spawnedEnv : undefined;
|
|
1181
|
+
return env && typeof env === 'object' ? env as Record<string, string> : undefined;
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
|
|
1185
|
+
function readCliProviderNativeHistory(agentStr: string, args: {
|
|
1186
|
+
canonicalHistory?: ProviderModule['canonicalHistory'];
|
|
1187
|
+
historySessionId?: string;
|
|
1188
|
+
workspace?: string;
|
|
1189
|
+
offset: number;
|
|
1190
|
+
limit: number;
|
|
1191
|
+
excludeRecentCount: number;
|
|
1192
|
+
historyBehavior?: ProviderModule['historyBehavior'];
|
|
1193
|
+
scripts?: ProviderScripts;
|
|
1194
|
+
excludeInProgressTurn?: boolean;
|
|
1195
|
+
sessionStartedAtMs?: number;
|
|
1196
|
+
envOverrides?: Record<string, string>;
|
|
1197
|
+
}): ReturnType<typeof readProviderChatHistory> & { lookup: 'session' | 'workspace' } {
|
|
1198
|
+
const canBindFromLiveSession = !args.historySessionId
|
|
1199
|
+
&& typeof args.sessionStartedAtMs === 'number'
|
|
1200
|
+
&& args.sessionStartedAtMs > 0
|
|
1201
|
+
&& typeof args.workspace === 'string'
|
|
1202
|
+
&& args.workspace.trim().length > 0;
|
|
1203
|
+
if (!args.historySessionId && !canBindFromLiveSession) {
|
|
1204
|
+
return {
|
|
1205
|
+
messages: [],
|
|
1206
|
+
hasMore: false,
|
|
1207
|
+
source: 'native-unavailable',
|
|
1208
|
+
unavailableReason: 'native_history_workspace_only_lookup_unsafe',
|
|
1209
|
+
lookup: 'session',
|
|
1210
|
+
} as ReturnType<typeof readProviderChatHistory> & { lookup: 'session' | 'workspace' };
|
|
1211
|
+
}
|
|
1212
|
+
const sessionHistory = readProviderChatHistory(agentStr, {
|
|
1213
|
+
canonicalHistory: args.canonicalHistory,
|
|
1214
|
+
historySessionId: args.historySessionId,
|
|
1215
|
+
workspace: args.workspace,
|
|
1216
|
+
offset: args.offset,
|
|
1217
|
+
limit: args.limit,
|
|
1218
|
+
excludeRecentCount: args.excludeRecentCount,
|
|
1219
|
+
historyBehavior: args.historyBehavior,
|
|
1220
|
+
scripts: args.scripts as any,
|
|
1221
|
+
excludeInProgressTurn: args.excludeInProgressTurn,
|
|
1222
|
+
sessionStartedAtMs: args.sessionStartedAtMs,
|
|
1223
|
+
envOverrides: args.envOverrides,
|
|
1224
|
+
});
|
|
1225
|
+
const boundProviderSessionId = typeof (sessionHistory as any)?.providerSessionId === 'string'
|
|
1226
|
+
? (sessionHistory as any).providerSessionId.trim()
|
|
1227
|
+
: '';
|
|
1228
|
+
// A fresh live session can be bound without a provider id when the native
|
|
1229
|
+
// reader matched both cwd and session_meta.timestamp to spawnedAtMs.
|
|
1230
|
+
return {
|
|
1231
|
+
...(sessionHistory as any),
|
|
1232
|
+
lookup: args.historySessionId || (canBindFromLiveSession && boundProviderSessionId)
|
|
1233
|
+
? 'session'
|
|
1234
|
+
: 'workspace',
|
|
1235
|
+
};
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
function readLiveCodexWorkspaceNativeHistory(agentStr: string, args: {
|
|
1239
|
+
canonicalHistory?: ProviderModule['canonicalHistory'];
|
|
1240
|
+
workspace?: string;
|
|
1241
|
+
offset: number;
|
|
1242
|
+
limit: number;
|
|
1243
|
+
excludeRecentCount: number;
|
|
1244
|
+
historyBehavior?: ProviderModule['historyBehavior'];
|
|
1245
|
+
scripts?: ProviderScripts;
|
|
1246
|
+
}): (ReturnType<typeof readProviderChatHistory> & { lookup: 'workspace' }) | null {
|
|
1247
|
+
if (agentStr !== 'codex-cli') return null;
|
|
1248
|
+
const workspace = typeof args.workspace === 'string' ? args.workspace.trim() : '';
|
|
1249
|
+
if (!workspace) return null;
|
|
1250
|
+
const history = readProviderChatHistory(agentStr, {
|
|
1251
|
+
canonicalHistory: args.canonicalHistory,
|
|
1252
|
+
workspace,
|
|
1253
|
+
offset: args.offset,
|
|
1254
|
+
limit: args.limit,
|
|
1255
|
+
excludeRecentCount: args.excludeRecentCount,
|
|
1256
|
+
historyBehavior: args.historyBehavior,
|
|
1257
|
+
scripts: args.scripts as any,
|
|
1258
|
+
});
|
|
1259
|
+
return { ...(history as any), lookup: 'workspace' };
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
// (A2.2) isNativeHistoryFreshEnough removed. The v1 freshness comparison
|
|
1263
|
+
// (native_newest vs pty_newest with a 5-minute mtime grace window) was the
|
|
1264
|
+
// direct cause of the plipping behaviour: PTY arrived every turn so native
|
|
1265
|
+
// looked stale by default. ChatSourceMachine never compares native vs PTY
|
|
1266
|
+
// freshness — the lock holds across arbitrary PTY arrival. See
|
|
1267
|
+
// chat/source-machine.ts for the new semantics.
|
|
1268
|
+
|
|
1269
|
+
function shouldPreserveReadChatPayloadField(key: string): boolean {
|
|
1270
|
+
return key === 'messageSource' || key === 'transcriptProvenance';
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
function updateMessageSourceReturnedCount(value: unknown, returnedMessageCount: number): unknown {
|
|
1274
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return value;
|
|
1275
|
+
const record = value as Record<string, unknown>;
|
|
1276
|
+
const coverage = record.coverage && typeof record.coverage === 'object' && !Array.isArray(record.coverage)
|
|
1277
|
+
? record.coverage as Record<string, unknown>
|
|
1278
|
+
: undefined;
|
|
1279
|
+
if (!coverage) return value;
|
|
1280
|
+
return {
|
|
1281
|
+
...record,
|
|
1282
|
+
coverage: {
|
|
1283
|
+
...coverage,
|
|
1284
|
+
returnedMessageCount,
|
|
1285
|
+
},
|
|
1286
|
+
};
|
|
1287
|
+
}
|
|
224
1288
|
|
|
225
1289
|
function deriveHistoryDedupKey(message: ChatMessage & { _unitKey?: string; _turnKey?: string }): string | undefined {
|
|
226
1290
|
const unitKey = typeof message._unitKey === 'string' ? message._unitKey.trim() : '';
|
|
@@ -281,11 +1345,20 @@ function normalizeReadChatCommandStatus(status: unknown, activeModal: unknown):
|
|
|
281
1345
|
}
|
|
282
1346
|
switch (raw) {
|
|
283
1347
|
case 'starting':
|
|
284
|
-
return hasNonEmptyModalButtons(activeModal) ? 'waiting_approval' : '
|
|
1348
|
+
return hasNonEmptyModalButtons(activeModal) ? 'waiting_approval' : 'starting';
|
|
285
1349
|
case 'stopped':
|
|
286
1350
|
case 'disconnected':
|
|
287
1351
|
case 'not_monitored':
|
|
288
1352
|
return 'error';
|
|
1353
|
+
case 'waiting_approval':
|
|
1354
|
+
// The contract validator requires activeModal+buttons whenever
|
|
1355
|
+
// status is waiting_approval. If a producer/coercer set this
|
|
1356
|
+
// status without staging the modal yet (a race we hit with
|
|
1357
|
+
// codex-cli during tool approval setup), downgrade to a
|
|
1358
|
+
// generating-like status so readChat still returns successfully.
|
|
1359
|
+
// The next poll will pick up the modal once the provider has
|
|
1360
|
+
// emitted it.
|
|
1361
|
+
return hasNonEmptyModalButtons(activeModal) ? 'waiting_approval' : 'generating';
|
|
289
1362
|
default:
|
|
290
1363
|
return raw;
|
|
291
1364
|
}
|
|
@@ -295,6 +1368,25 @@ function isGeneratingLikeStatus(status: unknown): boolean {
|
|
|
295
1368
|
return status === 'generating' || status === 'streaming' || status === 'long_generating' || status === 'starting';
|
|
296
1369
|
}
|
|
297
1370
|
|
|
1371
|
+
function hasVisibleAssistantMessage(messages: unknown[] | undefined): boolean {
|
|
1372
|
+
if (!Array.isArray(messages)) return false;
|
|
1373
|
+
return messages.some((message: any) => {
|
|
1374
|
+
if (!message || message.role !== 'assistant') return false;
|
|
1375
|
+
const kind = typeof message.kind === 'string' ? message.kind : 'standard';
|
|
1376
|
+
if (kind !== 'standard') return false;
|
|
1377
|
+
return String(message.content || '').trim().length > 0;
|
|
1378
|
+
});
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
function hasFinalVisibleAssistantMessage(messages: unknown[] | undefined): boolean {
|
|
1382
|
+
if (!Array.isArray(messages)) return false;
|
|
1383
|
+
const visible = filterUserFacingChatMessages(messages as ChatMessage[]);
|
|
1384
|
+
const last = visible[visible.length - 1] as ChatMessage | undefined;
|
|
1385
|
+
const role = typeof last?.role === 'string' ? last.role.trim().toLowerCase() : '';
|
|
1386
|
+
const content = last ? flattenContent(last.content).trim() : '';
|
|
1387
|
+
return (role === 'assistant' || role === 'model') && content.length > 0;
|
|
1388
|
+
}
|
|
1389
|
+
|
|
298
1390
|
function shouldTrustCliAdapterTerminalStatus(parsedStatus: unknown, activeModal: unknown, adapter: CliAdapter, adapterStatus: any): boolean {
|
|
299
1391
|
if (!isGeneratingLikeStatus(parsedStatus)) return false;
|
|
300
1392
|
if (hasNonEmptyModalButtons(activeModal)) return false;
|
|
@@ -304,7 +1396,26 @@ function shouldTrustCliAdapterTerminalStatus(parsedStatus: unknown, activeModal:
|
|
|
304
1396
|
return true;
|
|
305
1397
|
}
|
|
306
1398
|
|
|
307
|
-
function normalizeCliReadChatStatus(parsedStatus: unknown, activeModal: unknown, adapter: CliAdapter, adapterStatus: any): string {
|
|
1399
|
+
function normalizeCliReadChatStatus(parsedStatus: unknown, activeModal: unknown, adapter: CliAdapter, adapterStatus: any, parsedMessages?: unknown[]): string {
|
|
1400
|
+
const adapterRawStatus = typeof adapterStatus?.status === 'string' ? adapterStatus.status.trim() : '';
|
|
1401
|
+
if (adapterRawStatus === 'starting'
|
|
1402
|
+
&& isGeneratingLikeStatus(parsedStatus)
|
|
1403
|
+
&& !hasNonEmptyModalButtons(activeModal)
|
|
1404
|
+
&& Array.isArray(parsedMessages)
|
|
1405
|
+
&& parsedMessages.length === 0
|
|
1406
|
+
&& Array.isArray(adapterStatus?.messages)
|
|
1407
|
+
&& adapterStatus.messages.length === 0
|
|
1408
|
+
&& !(typeof adapter.isProcessing === 'function' && adapter.isProcessing())) {
|
|
1409
|
+
return 'starting';
|
|
1410
|
+
}
|
|
1411
|
+
if (
|
|
1412
|
+
isGeneratingLikeStatus(adapterRawStatus)
|
|
1413
|
+
&& parsedStatus === 'idle'
|
|
1414
|
+
&& !hasNonEmptyModalButtons(activeModal)
|
|
1415
|
+
&& !hasVisibleAssistantMessage(parsedMessages)
|
|
1416
|
+
) {
|
|
1417
|
+
return adapterRawStatus;
|
|
1418
|
+
}
|
|
308
1419
|
if (shouldTrustCliAdapterTerminalStatus(parsedStatus, activeModal, adapter, adapterStatus)) return 'idle';
|
|
309
1420
|
return typeof parsedStatus === 'string' && parsedStatus.trim() ? parsedStatus : 'idle';
|
|
310
1421
|
}
|
|
@@ -325,7 +1436,65 @@ function finalizeStreamingMessagesWhenIdle(messages: ChatMessage[], status: stri
|
|
|
325
1436
|
});
|
|
326
1437
|
}
|
|
327
1438
|
|
|
328
|
-
|
|
1439
|
+
/**
|
|
1440
|
+
* Collapse adjacent PTY messages whose canonical (whitespace-stripped)
|
|
1441
|
+
* content is identical, OR whose turn key + role/kind match.
|
|
1442
|
+
*
|
|
1443
|
+
* The PTY parser of some providers (hermes-cli observed in the wild)
|
|
1444
|
+
* emits the same logical assistant turn twice when the terminal re-wraps
|
|
1445
|
+
* the text at a different column. The two emissions differ in newline
|
|
1446
|
+
* position — and sometimes in a single inserted space next to punctuation
|
|
1447
|
+
* (e.g. `(수정 2개), upstream` vs `(수정 2개 ), upstream`), so a simple
|
|
1448
|
+
* `\s+ -> ' '` normalize cannot collapse them.
|
|
1449
|
+
*
|
|
1450
|
+
* Strategy:
|
|
1451
|
+
* 1. If both messages carry the same _turnKey + role + kind, they are
|
|
1452
|
+
* the same logical turn by construction. Collapse.
|
|
1453
|
+
* 2. Otherwise compare with all whitespace stripped — wrap variants
|
|
1454
|
+
* collapse to identical strings.
|
|
1455
|
+
*
|
|
1456
|
+
* Native-history paths run through pageHistoryRecords and already
|
|
1457
|
+
* collapse on a normalized signature; this helper is the PTY equivalent
|
|
1458
|
+
* the readChat sync path was missing.
|
|
1459
|
+
*/
|
|
1460
|
+
function collapseAdjacentDuplicateChatMessages(messages: ChatMessage[]): ChatMessage[] {
|
|
1461
|
+
if (!Array.isArray(messages) || messages.length <= 1) return messages;
|
|
1462
|
+
const result: ChatMessage[] = [];
|
|
1463
|
+
let prevRoleKind = '';
|
|
1464
|
+
let prevStripped = '';
|
|
1465
|
+
for (const message of messages) {
|
|
1466
|
+
const role = typeof message.role === 'string' ? message.role : '';
|
|
1467
|
+
const kind = typeof message.kind === 'string' ? message.kind : 'standard';
|
|
1468
|
+
const content = typeof message.content === 'string'
|
|
1469
|
+
? message.content
|
|
1470
|
+
: (Array.isArray(message.content) ? message.content.map((p: any) => typeof p?.text === 'string' ? p.text : '').join('') : '');
|
|
1471
|
+
const strippedContent = content.replace(/\s+/g, '');
|
|
1472
|
+
// Empty content or system messages are passed through untouched.
|
|
1473
|
+
if (!strippedContent || role === 'system') {
|
|
1474
|
+
result.push(message);
|
|
1475
|
+
prevRoleKind = '';
|
|
1476
|
+
prevStripped = '';
|
|
1477
|
+
continue;
|
|
1478
|
+
}
|
|
1479
|
+
const roleKind = `${role}:${kind}`;
|
|
1480
|
+
const sameStripped = strippedContent === prevStripped && roleKind === prevRoleKind;
|
|
1481
|
+
if (result.length > 0 && sameStripped) {
|
|
1482
|
+
// Adjacent duplicate after stripping all whitespace. Keep the
|
|
1483
|
+
// *later* copy because PTY's last emission usually has the most
|
|
1484
|
+
// complete formatting.
|
|
1485
|
+
result[result.length - 1] = message;
|
|
1486
|
+
prevRoleKind = roleKind;
|
|
1487
|
+
prevStripped = strippedContent;
|
|
1488
|
+
continue;
|
|
1489
|
+
}
|
|
1490
|
+
result.push(message);
|
|
1491
|
+
prevRoleKind = roleKind;
|
|
1492
|
+
prevStripped = strippedContent;
|
|
1493
|
+
}
|
|
1494
|
+
return result;
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
function buildReadChatCommandResult(payload: Record<string, any>, args: any, h?: CommandHelpers): CommandResult {
|
|
329
1498
|
let validatedPayload: Record<string, any>;
|
|
330
1499
|
const debugReadChat = payload?.debugReadChat && typeof payload.debugReadChat === 'object'
|
|
331
1500
|
? payload.debugReadChat
|
|
@@ -339,9 +1508,32 @@ function buildReadChatCommandResult(payload: Record<string, any>, args: any): Co
|
|
|
339
1508
|
return { success: false, error: error?.message || String(error) };
|
|
340
1509
|
}
|
|
341
1510
|
const messages = normalizeReadChatMessages(validatedPayload);
|
|
342
|
-
|
|
1511
|
+
// Last-mile coordinator-prompt filter. Different read_chat code paths
|
|
1512
|
+
// produce the final messages array (native-history main path, codex
|
|
1513
|
+
// exact-runtime-mirror fallback, daemon-side pty-parser, etc), so
|
|
1514
|
+
// applying it here means we don't have to thread the filter through
|
|
1515
|
+
// every one. Driven by the provider setting `showCoordinatorSystemPrompt`
|
|
1516
|
+
// + the coordinator-registry entry for the target session.
|
|
1517
|
+
const sessionIdHint = typeof args?.targetSessionId === 'string' ? args.targetSessionId
|
|
1518
|
+
: typeof args?.sessionId === 'string' ? args.sessionId
|
|
1519
|
+
: '';
|
|
1520
|
+
const providerHint = typeof args?.cliType === 'string' ? args.cliType
|
|
1521
|
+
: typeof args?.providerType === 'string' ? args.providerType
|
|
1522
|
+
: typeof args?.agentType === 'string' ? args.agentType
|
|
1523
|
+
: '';
|
|
1524
|
+
const filteredMessages = h
|
|
1525
|
+
? maybeHideCoordinatorPromptMessage(h, providerHint, sessionIdHint, messages)
|
|
1526
|
+
: messages;
|
|
1527
|
+
const visibleMessages = filterUserFacingChatMessages(filteredMessages);
|
|
343
1528
|
const sync = buildFullTail(visibleMessages, normalizeReadChatTailLimit(args));
|
|
344
1529
|
const hiddenMsgCount = Math.max(0, messages.length - visibleMessages.length);
|
|
1530
|
+
const preservedPayloadFields = Object.fromEntries(Object.entries(payload).filter(([key]) => shouldPreserveReadChatPayloadField(key)));
|
|
1531
|
+
if (preservedPayloadFields.messageSource) {
|
|
1532
|
+
preservedPayloadFields.messageSource = updateMessageSourceReturnedCount(preservedPayloadFields.messageSource, sync.messages.length);
|
|
1533
|
+
}
|
|
1534
|
+
if (preservedPayloadFields.transcriptProvenance) {
|
|
1535
|
+
preservedPayloadFields.transcriptProvenance = updateMessageSourceReturnedCount(preservedPayloadFields.transcriptProvenance, sync.messages.length);
|
|
1536
|
+
}
|
|
345
1537
|
const returnedDebugReadChat = debugReadChat
|
|
346
1538
|
? {
|
|
347
1539
|
...debugReadChat,
|
|
@@ -356,6 +1548,7 @@ function buildReadChatCommandResult(payload: Record<string, any>, args: any): Co
|
|
|
356
1548
|
return {
|
|
357
1549
|
success: true,
|
|
358
1550
|
...validatedPayload,
|
|
1551
|
+
...preservedPayloadFields,
|
|
359
1552
|
messages: sync.messages,
|
|
360
1553
|
totalMessages: sync.totalMessages,
|
|
361
1554
|
...(returnedDebugReadChat ? { debugReadChat: returnedDebugReadChat } : {}),
|
|
@@ -456,7 +1649,7 @@ function summarizeProviderForDebug(provider: ProviderModule | undefined): Record
|
|
|
456
1649
|
name: provider.name,
|
|
457
1650
|
category: provider.category,
|
|
458
1651
|
version: (provider as any).version,
|
|
459
|
-
canonicalHistory: provider.
|
|
1652
|
+
canonicalHistory: provider.nativeHistory,
|
|
460
1653
|
historyBehavior: provider.historyBehavior,
|
|
461
1654
|
webviewMatchText: provider.webviewMatchText,
|
|
462
1655
|
scriptNames: scripts,
|
|
@@ -508,8 +1701,10 @@ function summarizeStateForDebug(state: any): Record<string, unknown> | null {
|
|
|
508
1701
|
title: activeChat.title,
|
|
509
1702
|
messageCount: Array.isArray(activeChat.messages) ? activeChat.messages.length : undefined,
|
|
510
1703
|
activeModal: activeChat.activeModal,
|
|
1704
|
+
activeInteractivePrompt: activeChat.activeInteractivePrompt ?? null,
|
|
511
1705
|
messagesTail: Array.isArray(activeChat.messages) ? activeChat.messages.slice(-10) : undefined,
|
|
512
1706
|
} : null,
|
|
1707
|
+
activeInteractivePrompt: (state as { activeInteractivePrompt?: unknown }).activeInteractivePrompt ?? null,
|
|
513
1708
|
controlValues: state.controlValues,
|
|
514
1709
|
summaryMetadata: state.summaryMetadata,
|
|
515
1710
|
};
|
|
@@ -584,6 +1779,8 @@ function buildChatDebugBundleSummary(bundle: Record<string, unknown>): Record<st
|
|
|
584
1779
|
adapterStatus: debugReadChat.adapterStatus,
|
|
585
1780
|
parsedStatus: debugReadChat.parsedStatus,
|
|
586
1781
|
returnedStatus: debugReadChat.returnedStatus,
|
|
1782
|
+
selectedMessageSource: debugReadChat.selectedMessageSource,
|
|
1783
|
+
messageSource: debugReadChat.messageSource,
|
|
587
1784
|
parsedMsgCount: debugReadChat.parsedMsgCount,
|
|
588
1785
|
returnedMsgCount: debugReadChat.returnedMsgCount,
|
|
589
1786
|
shouldPreferAdapterMessages: debugReadChat.shouldPreferAdapterMessages,
|
|
@@ -646,11 +1843,20 @@ export async function handleGetChatDebugBundle(h: CommandHelpers, args: any): Pr
|
|
|
646
1843
|
providerSessionId: readResult.providerSessionId,
|
|
647
1844
|
transcriptAuthority: readResult.transcriptAuthority,
|
|
648
1845
|
coverage: readResult.coverage,
|
|
1846
|
+
messageSource: readResult.messageSource,
|
|
1847
|
+
transcriptProvenance: readResult.transcriptProvenance,
|
|
649
1848
|
activeModal: readResult.activeModal,
|
|
650
1849
|
messagesTail: Array.isArray(readResult.messages) ? readResult.messages.slice(-20) : [],
|
|
651
1850
|
debugReadChat: readResult.debugReadChat,
|
|
652
1851
|
}
|
|
653
|
-
: {
|
|
1852
|
+
: {
|
|
1853
|
+
success: false,
|
|
1854
|
+
error: readResult.error,
|
|
1855
|
+
code: readResult.code,
|
|
1856
|
+
messageSource: readResult.messageSource,
|
|
1857
|
+
transcriptProvenance: readResult.transcriptProvenance,
|
|
1858
|
+
debugReadChat: readResult.debugReadChat,
|
|
1859
|
+
};
|
|
654
1860
|
} catch (error: any) {
|
|
655
1861
|
readChat = { success: false, error: error?.message || String(error) };
|
|
656
1862
|
}
|
|
@@ -693,6 +1899,9 @@ export async function handleGetChatDebugBundle(h: CommandHelpers, args: any): Pr
|
|
|
693
1899
|
ready: typeof adapter.isReady === 'function' ? adapter.isReady() : undefined,
|
|
694
1900
|
processing: typeof adapter.isProcessing === 'function' ? adapter.isProcessing() : undefined,
|
|
695
1901
|
debugSnapshot: adapterDebugSnapshot,
|
|
1902
|
+
scriptInvocationTrace: typeof (adapter as any).getScriptInvocationTrace === 'function'
|
|
1903
|
+
? (adapter as any).getScriptInvocationTrace()
|
|
1904
|
+
: undefined,
|
|
696
1905
|
} : null,
|
|
697
1906
|
readChat,
|
|
698
1907
|
frontend: args?.frontendSnapshot && typeof args.frontendSnapshot === 'object' ? args.frontendSnapshot : null,
|
|
@@ -817,16 +2026,58 @@ export async function handleChatHistory(h: CommandHelpers, args: any): Promise<C
|
|
|
817
2026
|
: typeof (h.currentSession as any)?.workspace === 'string'
|
|
818
2027
|
? (h.currentSession as any).workspace
|
|
819
2028
|
: undefined;
|
|
820
|
-
const
|
|
821
|
-
|
|
822
|
-
historySessionId
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
2029
|
+
const exactNativeHistoryScope = Boolean(
|
|
2030
|
+
(typeof args?.targetSessionId === 'string' && args.targetSessionId.trim())
|
|
2031
|
+
|| (typeof args?.historySessionId === 'string' && args.historySessionId.trim())
|
|
2032
|
+
|| (typeof args?.providerSessionId === 'string' && args.providerSessionId.trim())
|
|
2033
|
+
);
|
|
2034
|
+
const result = supportsCliNativeTranscript(agentStr, provider) && isNativeSourceCanonicalHistory(provider?.nativeHistory)
|
|
2035
|
+
? readCliProviderNativeHistory(agentStr, {
|
|
2036
|
+
canonicalHistory: provider?.nativeHistory,
|
|
2037
|
+
historySessionId,
|
|
2038
|
+
workspace,
|
|
2039
|
+
offset: offset || 0,
|
|
2040
|
+
limit: limit || 30,
|
|
2041
|
+
excludeRecentCount,
|
|
2042
|
+
historyBehavior: provider?.historyBehavior,
|
|
2043
|
+
scripts: provider?.scripts as any,
|
|
2044
|
+
sessionStartedAtMs: sessionStartedAtMsFromRegistry(h, args?.targetSessionId),
|
|
2045
|
+
envOverrides: sessionSpawnEnvFromAdapter(h, args?.targetSessionId),
|
|
2046
|
+
})
|
|
2047
|
+
: readProviderChatHistory(agentStr, {
|
|
2048
|
+
canonicalHistory: provider?.nativeHistory,
|
|
2049
|
+
historySessionId,
|
|
2050
|
+
workspace,
|
|
2051
|
+
offset: offset || 0,
|
|
2052
|
+
limit: limit || 30,
|
|
2053
|
+
excludeRecentCount,
|
|
2054
|
+
historyBehavior: provider?.historyBehavior,
|
|
2055
|
+
scripts: provider?.scripts as any,
|
|
2056
|
+
});
|
|
2057
|
+
if (supportsCliNativeTranscript(agentStr, provider) && isNativeSourceCanonicalHistory(provider?.nativeHistory)) {
|
|
2058
|
+
const lookup = (result as any).lookup === 'workspace' ? 'workspace' : 'session';
|
|
2059
|
+
const messages = Array.isArray((result as any).messages)
|
|
2060
|
+
? normalizeAndFilterNativeHistory(h, agentStr, args, (result as any).messages as ChatMessage[], (result as any)?.providerSessionId)
|
|
2061
|
+
: [];
|
|
2062
|
+
const historyProviderSessionId = typeof (result as any)?.providerSessionId === 'string'
|
|
2063
|
+
? (result as any).providerSessionId
|
|
2064
|
+
: readHistorySessionIdFromMessages(messages) || historySessionId;
|
|
2065
|
+
const safeMapping = hasSafeNativeHistoryMapping({
|
|
2066
|
+
historySessionId: lookup === 'workspace' ? undefined : historySessionId,
|
|
2067
|
+
providerSessionId: lookup === 'workspace' ? undefined : historyProviderSessionId,
|
|
2068
|
+
workspace,
|
|
2069
|
+
nativeMessages: messages,
|
|
2070
|
+
});
|
|
2071
|
+
if ((result as any).source === 'provider-native' && messages.length > 0 && !safeMapping) {
|
|
2072
|
+
return {
|
|
2073
|
+
success: true,
|
|
2074
|
+
messages: [],
|
|
2075
|
+
hasMore: false,
|
|
2076
|
+
source: 'native-unavailable',
|
|
2077
|
+
agent: agentStr,
|
|
2078
|
+
};
|
|
2079
|
+
}
|
|
2080
|
+
}
|
|
830
2081
|
return { success: true, ...result, agent: agentStr };
|
|
831
2082
|
} catch (e: any) {
|
|
832
2083
|
return { success: false, error: e.message };
|
|
@@ -834,7 +2085,25 @@ export async function handleChatHistory(h: CommandHelpers, args: any): Promise<C
|
|
|
834
2085
|
}
|
|
835
2086
|
|
|
836
2087
|
export async function handleReadChat(h: CommandHelpers, args: any): Promise<CommandResult> {
|
|
837
|
-
|
|
2088
|
+
// Resolve provider in order: explicit agentType/providerType > registered session.
|
|
2089
|
+
// Without this fallback, callers that only have a sessionId (e.g. a chat tail
|
|
2090
|
+
// controller that just got handed a session ID over WS) get an empty result
|
|
2091
|
+
// because getProvider(undefined) returns undefined and the rest of the pipeline
|
|
2092
|
+
// bails. This makes the UI look like the session "disappeared".
|
|
2093
|
+
let providerHint: string | undefined = args?.agentType || args?.providerType;
|
|
2094
|
+
if (!providerHint) {
|
|
2095
|
+
const targetSessionId = typeof args?.targetSessionId === 'string' ? args.targetSessionId.trim() : '';
|
|
2096
|
+
if (targetSessionId) {
|
|
2097
|
+
const session = (h.ctx as any)?.sessionRegistry?.get?.(targetSessionId);
|
|
2098
|
+
if (session && typeof session.providerType === 'string') {
|
|
2099
|
+
providerHint = session.providerType;
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
if (!providerHint && h.currentSession?.providerType) {
|
|
2103
|
+
providerHint = h.currentSession.providerType;
|
|
2104
|
+
}
|
|
2105
|
+
}
|
|
2106
|
+
const provider = h.getProvider(providerHint);
|
|
838
2107
|
const transport = getTargetTransport(h, provider);
|
|
839
2108
|
const historySessionId = getHistorySessionId(h, args);
|
|
840
2109
|
|
|
@@ -874,66 +2143,499 @@ export async function handleReadChat(h: CommandHelpers, args: any): Promise<Comm
|
|
|
874
2143
|
? parsedRecord.coverage
|
|
875
2144
|
: undefined;
|
|
876
2145
|
const activeModal = parsedRecord.activeModal ?? parsedRecord.modal ?? null;
|
|
877
|
-
const returnedStatus = normalizeCliReadChatStatus(parsedRecord.status, activeModal, adapter, adapterStatus);
|
|
2146
|
+
const returnedStatus = normalizeCliReadChatStatus(parsedRecord.status, activeModal, adapter, adapterStatus, parsedRecord.messages);
|
|
878
2147
|
const runtimeMessageMerger = getTargetInstance(h, args) as RuntimeChatMessageMerger | null;
|
|
879
|
-
const parsedMessages =
|
|
2148
|
+
const parsedMessages = collapseAdjacentDuplicateChatMessages(
|
|
2149
|
+
finalizeStreamingMessagesWhenIdle(parsedRecord.messages as ChatMessage[], returnedStatus),
|
|
2150
|
+
);
|
|
880
2151
|
const returnedMessages = runtimeMessageMerger?.category === 'cli'
|
|
881
2152
|
&& runtimeMessageMerger.type === adapter.cliType
|
|
882
2153
|
&& typeof runtimeMessageMerger.mergeRuntimeChatMessages === 'function'
|
|
883
2154
|
? runtimeMessageMerger.mergeRuntimeChatMessages(parsedMessages)
|
|
884
2155
|
: parsedMessages;
|
|
2156
|
+
const providerType = provider?.type || adapter.cliType;
|
|
2157
|
+
let selectedMessages = returnedMessages;
|
|
2158
|
+
let selectedTitle = title;
|
|
2159
|
+
let selectedProviderSessionId = providerSessionId;
|
|
2160
|
+
let selectedTranscriptAuthority = transcriptAuthority;
|
|
2161
|
+
let selectedCoverage = coverage;
|
|
2162
|
+
let selectedStatus = returnedStatus;
|
|
2163
|
+
const sessionWorkspace = typeof (h.currentSession as any)?.workspace === 'string'
|
|
2164
|
+
? (h.currentSession as any).workspace
|
|
2165
|
+
: typeof adapter.workingDir === 'string'
|
|
2166
|
+
? adapter.workingDir
|
|
2167
|
+
: undefined;
|
|
2168
|
+
const intendedWorkspace = typeof args?.workspace === 'string' ? args.workspace : undefined;
|
|
2169
|
+
// ───────────────────────────────────────────────────────────
|
|
2170
|
+
// Chat source decision via ChatSourceMachine (A2 big-bang).
|
|
2171
|
+
// Replaces the ~300-line if-ladder that mixed source decision
|
|
2172
|
+
// with native fetch, anchor mutation, and runtime mirror
|
|
2173
|
+
// selection. The machine decides only between native-history
|
|
2174
|
+
// and pty-parser; downstream selection of which message array
|
|
2175
|
+
// to surface stays here.
|
|
2176
|
+
//
|
|
2177
|
+
// Behavioural changes vs v1:
|
|
2178
|
+
// - No more nativeHistoryAnchoredAt mutation on the adapter.
|
|
2179
|
+
// Lock state lives in CHAT_SOURCE_REGISTRY keyed by
|
|
2180
|
+
// (providerType, sessionId).
|
|
2181
|
+
// - No PTY-vs-native freshness comparison. The lock holds
|
|
2182
|
+
// across arbitrary PTY arrival; only native regression /
|
|
2183
|
+
// unavailability unlocks. This is the plipping fix.
|
|
2184
|
+
// - 6 trigger strings (native_history_partial / _stale /
|
|
2185
|
+
// _not_safely_mapped / _empty / _error / _unavailable)
|
|
2186
|
+
// collapse to 3 events with diagnostic causes preserved
|
|
2187
|
+
// and mapped back to legacy fallbackReason strings for
|
|
2188
|
+
// response compatibility.
|
|
2189
|
+
// - Codex live-workspace native probe and unsafe-native
|
|
2190
|
+
// daemon mirror fallbacks are preserved as additional
|
|
2191
|
+
// input rounds to the machine; they were never the source
|
|
2192
|
+
// decision itself, they were retries.
|
|
2193
|
+
// ───────────────────────────────────────────────────────────
|
|
2194
|
+
|
|
2195
|
+
const supportsNative = supportsCliNativeTranscript(providerType, provider)
|
|
2196
|
+
&& isNativeSourceCanonicalHistory(provider?.nativeHistory);
|
|
2197
|
+
const agentStr = provider?.type || args?.agentType || getCurrentProviderType(h, adapter.cliType);
|
|
2198
|
+
const workspace = sessionWorkspace;
|
|
2199
|
+
const nativeHistoryLimit = Math.max(
|
|
2200
|
+
normalizeReadChatTailLimit(args) || 0,
|
|
2201
|
+
returnedMessages.length,
|
|
2202
|
+
200,
|
|
2203
|
+
);
|
|
2204
|
+
const nativeHistorySessionId = supportsNative
|
|
2205
|
+
? resolveCliNativeHistorySessionId(args, historySessionId, providerSessionId)
|
|
2206
|
+
: undefined;
|
|
2207
|
+
const targetSessionId = typeof args?.targetSessionId === 'string' ? args.targetSessionId.trim() : '';
|
|
2208
|
+
const skipLiveNativeHistoryWithoutProviderSession = shouldSkipLiveCliNativeHistoryWithoutProviderSession({
|
|
2209
|
+
adapter,
|
|
2210
|
+
providerType,
|
|
2211
|
+
readChatArgs: args,
|
|
2212
|
+
nativeHistorySessionId,
|
|
2213
|
+
parsedProviderSessionId: providerSessionId,
|
|
2214
|
+
});
|
|
2215
|
+
const nativeHistoryReadSessionId = skipLiveNativeHistoryWithoutProviderSession
|
|
2216
|
+
? undefined
|
|
2217
|
+
: nativeHistorySessionId;
|
|
2218
|
+
const exactNativeHistoryScope = Boolean(
|
|
2219
|
+
(typeof args?.historySessionId === 'string' && args.historySessionId.trim())
|
|
2220
|
+
|| (typeof args?.providerSessionId === 'string' && args.providerSessionId.trim())
|
|
2221
|
+
|| providerSessionId
|
|
2222
|
+
|| (nativeHistoryReadSessionId && nativeHistoryReadSessionId !== targetSessionId)
|
|
2223
|
+
|| ((h.currentSession as any)?.sessionId === args?.targetSessionId && typeof (h.currentSession as any)?.providerSessionId === 'string' && (h.currentSession as any).providerSessionId.trim())
|
|
2224
|
+
);
|
|
2225
|
+
|
|
2226
|
+
// 1. Fetch native history (or skip if provider does not support it).
|
|
2227
|
+
let nativeHistory: any | null = null;
|
|
2228
|
+
let nativeHistoryError: unknown | undefined;
|
|
2229
|
+
if (supportsNative) {
|
|
2230
|
+
try {
|
|
2231
|
+
nativeHistory = readCliProviderNativeHistory(agentStr, {
|
|
2232
|
+
canonicalHistory: provider?.nativeHistory,
|
|
2233
|
+
historySessionId: nativeHistoryReadSessionId,
|
|
2234
|
+
workspace,
|
|
2235
|
+
offset: 0,
|
|
2236
|
+
limit: nativeHistoryLimit,
|
|
2237
|
+
excludeRecentCount: 0,
|
|
2238
|
+
historyBehavior: provider?.historyBehavior,
|
|
2239
|
+
scripts: provider?.scripts as any,
|
|
2240
|
+
excludeInProgressTurn: returnedStatus === 'waiting_approval',
|
|
2241
|
+
sessionStartedAtMs: sessionStartedAtMsFromRegistry(h, args?.targetSessionId),
|
|
2242
|
+
envOverrides: sessionSpawnEnvFromAdapter(h, args?.targetSessionId),
|
|
2243
|
+
});
|
|
2244
|
+
} catch (error: any) {
|
|
2245
|
+
nativeHistoryError = error;
|
|
2246
|
+
nativeHistory = null;
|
|
2247
|
+
}
|
|
2248
|
+
}
|
|
2249
|
+
|
|
2250
|
+
// 2. Compute safeMapping with the same rules the v1 code used so the
|
|
2251
|
+
// machine sees the same observation it always would have.
|
|
2252
|
+
let nativeMessages: ChatMessage[] = nativeHistory && Array.isArray(nativeHistory.messages)
|
|
2253
|
+
? normalizeAndFilterNativeHistory(h, agentStr, args, nativeHistory.messages as ChatMessage[], nativeHistory.providerSessionId)
|
|
2254
|
+
: [];
|
|
2255
|
+
const sessionStartedAtMs = sessionStartedAtMsFromRegistry(h, args?.targetSessionId);
|
|
2256
|
+
let historyProviderSessionId = typeof nativeHistory?.providerSessionId === 'string'
|
|
2257
|
+
? nativeHistory.providerSessionId
|
|
2258
|
+
: readHistorySessionIdFromMessages(nativeMessages) || nativeHistoryReadSessionId || historySessionId;
|
|
2259
|
+
let lookup = nativeHistory?.lookup === 'workspace' ? 'workspace' : 'session';
|
|
2260
|
+
let nativeHistorySessionForMapping = adapter.cliType === 'antigravity-cli'
|
|
2261
|
+
&& historyProviderSessionId
|
|
2262
|
+
&& nativeHistoryReadSessionId
|
|
2263
|
+
&& historyProviderSessionId !== nativeHistoryReadSessionId
|
|
2264
|
+
? undefined
|
|
2265
|
+
: nativeHistoryReadSessionId;
|
|
2266
|
+
let safeMapping = supportsNative && nativeHistory
|
|
2267
|
+
? hasSafeNativeHistoryMapping({
|
|
2268
|
+
historySessionId: lookup === 'workspace' ? undefined : nativeHistorySessionForMapping,
|
|
2269
|
+
providerSessionId: lookup === 'workspace' ? undefined : historyProviderSessionId || providerSessionId,
|
|
2270
|
+
workspace,
|
|
2271
|
+
nativeMessages,
|
|
2272
|
+
ptyMessages: returnedMessages,
|
|
2273
|
+
requireWorkspaceContentOverlap: lookup === 'workspace' && !exactNativeHistoryScope,
|
|
2274
|
+
})
|
|
2275
|
+
: false;
|
|
2276
|
+
if (skipLiveNativeHistoryWithoutProviderSession && (!safeMapping || returnedMessages.length === 0)) {
|
|
2277
|
+
nativeHistory = null;
|
|
2278
|
+
nativeMessages = [];
|
|
2279
|
+
historyProviderSessionId = undefined;
|
|
2280
|
+
lookup = 'session';
|
|
2281
|
+
safeMapping = false;
|
|
2282
|
+
}
|
|
2283
|
+
const mayRetryUnsafeAutoDetectedCodexSession = adapter.cliType === 'codex-cli'
|
|
2284
|
+
&& !getExplicitHistorySessionId(args)
|
|
2285
|
+
&& Boolean(sessionStartedAtMs && sessionStartedAtMs > 0)
|
|
2286
|
+
&& !skipLiveNativeHistoryWithoutProviderSession
|
|
2287
|
+
&& !safeMapping;
|
|
2288
|
+
if (mayRetryUnsafeAutoDetectedCodexSession) {
|
|
2289
|
+
try {
|
|
2290
|
+
nativeHistory = readCliProviderNativeHistory(agentStr, {
|
|
2291
|
+
canonicalHistory: provider?.nativeHistory,
|
|
2292
|
+
historySessionId: undefined,
|
|
2293
|
+
workspace,
|
|
2294
|
+
offset: 0,
|
|
2295
|
+
limit: nativeHistoryLimit,
|
|
2296
|
+
excludeRecentCount: 0,
|
|
2297
|
+
historyBehavior: provider?.historyBehavior,
|
|
2298
|
+
scripts: provider?.scripts as any,
|
|
2299
|
+
excludeInProgressTurn: returnedStatus === 'waiting_approval',
|
|
2300
|
+
sessionStartedAtMs,
|
|
2301
|
+
envOverrides: sessionSpawnEnvFromAdapter(h, args?.targetSessionId),
|
|
2302
|
+
});
|
|
2303
|
+
nativeHistoryError = undefined;
|
|
2304
|
+
nativeMessages = nativeHistory && Array.isArray(nativeHistory.messages)
|
|
2305
|
+
? normalizeAndFilterNativeHistory(h, agentStr, args, nativeHistory.messages as ChatMessage[], nativeHistory.providerSessionId)
|
|
2306
|
+
: [];
|
|
2307
|
+
historyProviderSessionId = typeof nativeHistory?.providerSessionId === 'string'
|
|
2308
|
+
? nativeHistory.providerSessionId
|
|
2309
|
+
: readHistorySessionIdFromMessages(nativeMessages);
|
|
2310
|
+
lookup = nativeHistory?.lookup === 'workspace' ? 'workspace' : 'session';
|
|
2311
|
+
nativeHistorySessionForMapping = undefined;
|
|
2312
|
+
safeMapping = supportsNative && nativeHistory
|
|
2313
|
+
? hasSafeNativeHistoryMapping({
|
|
2314
|
+
historySessionId: lookup === 'workspace' ? undefined : historyProviderSessionId,
|
|
2315
|
+
providerSessionId: lookup === 'workspace' ? undefined : historyProviderSessionId,
|
|
2316
|
+
workspace,
|
|
2317
|
+
nativeMessages,
|
|
2318
|
+
ptyMessages: returnedMessages,
|
|
2319
|
+
requireWorkspaceContentOverlap: lookup === 'workspace' && !exactNativeHistoryScope,
|
|
2320
|
+
})
|
|
2321
|
+
: false;
|
|
2322
|
+
} catch (error: any) {
|
|
2323
|
+
nativeHistoryError = error;
|
|
2324
|
+
nativeHistory = null;
|
|
2325
|
+
nativeMessages = [];
|
|
2326
|
+
historyProviderSessionId = undefined;
|
|
2327
|
+
safeMapping = false;
|
|
2328
|
+
}
|
|
2329
|
+
}
|
|
2330
|
+
const trustedExactNativeIdentity = lookup !== 'workspace'
|
|
2331
|
+
&& Boolean(nativeHistoryReadSessionId)
|
|
2332
|
+
&& Boolean(historyProviderSessionId)
|
|
2333
|
+
&& nativeHistoryReadSessionId === historyProviderSessionId;
|
|
2334
|
+
|
|
2335
|
+
// 3. Drive ChatSourceMachine — one observation per readChat call,
|
|
2336
|
+
// keyed by (providerType, sessionKey-for-this-call). targetSessionId
|
|
2337
|
+
// is the most specific session anchor we have; fall back to
|
|
2338
|
+
// historySessionId so we never leak state across distinct sessions.
|
|
2339
|
+
const machineSessionKey = String(
|
|
2340
|
+
args?.targetSessionId
|
|
2341
|
+
|| providerSessionId
|
|
2342
|
+
|| historySessionId
|
|
2343
|
+
|| (h.currentSession as any)?.sessionId
|
|
2344
|
+
|| ''
|
|
2345
|
+
);
|
|
2346
|
+
const primary = decideCliReadChatSource({
|
|
2347
|
+
providerType,
|
|
2348
|
+
provider,
|
|
2349
|
+
sessionId: machineSessionKey,
|
|
2350
|
+
nativeHistoryResult: nativeHistory,
|
|
2351
|
+
nativeHistoryError,
|
|
2352
|
+
safeMapping,
|
|
2353
|
+
trustedExactNativeIdentity,
|
|
2354
|
+
sessionWorkspace,
|
|
2355
|
+
intendedWorkspace,
|
|
2356
|
+
ptyMessages: returnedMessages,
|
|
2357
|
+
// Start with PTY visible; decideCliReadChatSource flips this
|
|
2358
|
+
// to true when the machine actually selects native-history.
|
|
2359
|
+
ptyStatusApprovalOnly: false,
|
|
2360
|
+
});
|
|
2361
|
+
let messageSource: Record<string, unknown> = primary.messageSource;
|
|
2362
|
+
|
|
2363
|
+
if (primary.nativeSelected) {
|
|
2364
|
+
selectedMessages = finalizeStreamingMessagesWhenIdle(primary.nativeMessages, returnedStatus);
|
|
2365
|
+
selectedProviderSessionId = historyProviderSessionId || providerSessionId;
|
|
2366
|
+
selectedTranscriptAuthority = 'provider';
|
|
2367
|
+
selectedCoverage = nativeHistory?.hasMore ? 'tail' : 'full';
|
|
2368
|
+
if (selectedProviderSessionId && selectedProviderSessionId !== providerSessionId) {
|
|
2369
|
+
adapter.updateRuntimeMeta?.({ providerSessionId: selectedProviderSessionId });
|
|
2370
|
+
}
|
|
2371
|
+
} else if (supportsNative) {
|
|
2372
|
+
// Native not selected. Two preserved v1 fallbacks before settling
|
|
2373
|
+
// on PTY: (a) Codex-only live workspace native probe; (b) unsafe-
|
|
2374
|
+
// native daemon mirror selection. The machine sees each retry as
|
|
2375
|
+
// an additional observation.
|
|
2376
|
+
const liveCurrentRuntimePtySafe = isCurrentRuntimePtySafelyAttributed({
|
|
2377
|
+
adapter,
|
|
2378
|
+
helpers: h,
|
|
2379
|
+
readChatArgs: args,
|
|
2380
|
+
sessionWorkspace,
|
|
2381
|
+
intendedWorkspace,
|
|
2382
|
+
ptyMessages: returnedMessages,
|
|
2383
|
+
});
|
|
2384
|
+
const mayProbeLiveCodexWorkspaceNative = adapter.cliType === 'codex-cli'
|
|
2385
|
+
&& liveCurrentRuntimePtySafe
|
|
2386
|
+
&& !(typeof args?.providerSessionId === 'string' && args.providerSessionId.trim())
|
|
2387
|
+
&& !(providerSessionId && providerSessionId.trim())
|
|
2388
|
+
&& !nativeHistoryReadSessionId
|
|
2389
|
+
&& (!historyProviderSessionId || historyProviderSessionId === nativeHistoryReadSessionId || historyProviderSessionId === historySessionId)
|
|
2390
|
+
&& !skipLiveNativeHistoryWithoutProviderSession;
|
|
2391
|
+
const liveWorkspaceNativeHistory = mayProbeLiveCodexWorkspaceNative
|
|
2392
|
+
? readLiveCodexWorkspaceNativeHistory(agentStr, {
|
|
2393
|
+
canonicalHistory: provider?.nativeHistory,
|
|
2394
|
+
workspace,
|
|
2395
|
+
offset: 0,
|
|
2396
|
+
limit: nativeHistoryLimit,
|
|
2397
|
+
excludeRecentCount: 0,
|
|
2398
|
+
historyBehavior: provider?.historyBehavior,
|
|
2399
|
+
scripts: provider?.scripts as any,
|
|
2400
|
+
})
|
|
2401
|
+
: null;
|
|
2402
|
+
const liveWorkspaceNativeMessages = Array.isArray((liveWorkspaceNativeHistory as any)?.messages)
|
|
2403
|
+
? normalizeAndFilterNativeHistory(h, agentStr, args, (liveWorkspaceNativeHistory as any).messages as ChatMessage[], (liveWorkspaceNativeHistory as any)?.providerSessionId)
|
|
2404
|
+
: [];
|
|
2405
|
+
const liveWorkspaceNativeProviderSessionId = typeof (liveWorkspaceNativeHistory as any)?.providerSessionId === 'string'
|
|
2406
|
+
? (liveWorkspaceNativeHistory as any).providerSessionId
|
|
2407
|
+
: readHistorySessionIdFromMessages(liveWorkspaceNativeMessages);
|
|
2408
|
+
const liveWorkspaceNativeSafeMapping = liveWorkspaceNativeMessages.length > 0
|
|
2409
|
+
&& hasSafeNativeHistoryMapping({
|
|
2410
|
+
workspace,
|
|
2411
|
+
nativeMessages: liveWorkspaceNativeMessages,
|
|
2412
|
+
ptyMessages: returnedMessages,
|
|
2413
|
+
requireWorkspaceContentOverlap: true,
|
|
2414
|
+
});
|
|
2415
|
+
if (liveWorkspaceNativeHistory) {
|
|
2416
|
+
const liveDecision = decideCliReadChatSource({
|
|
2417
|
+
providerType,
|
|
2418
|
+
provider,
|
|
2419
|
+
// Distinct session key so a transient codex live-probe does not
|
|
2420
|
+
// clobber the primary session's lock. The machine treats this
|
|
2421
|
+
// as its own session; the primary session's state is untouched.
|
|
2422
|
+
sessionId: `${machineSessionKey}::live-workspace`,
|
|
2423
|
+
nativeHistoryResult: liveWorkspaceNativeHistory,
|
|
2424
|
+
safeMapping: liveWorkspaceNativeSafeMapping,
|
|
2425
|
+
sessionWorkspace,
|
|
2426
|
+
intendedWorkspace,
|
|
2427
|
+
ptyMessages: returnedMessages,
|
|
2428
|
+
ptyStatusApprovalOnly: true,
|
|
2429
|
+
});
|
|
2430
|
+
if (liveDecision.nativeSelected) {
|
|
2431
|
+
selectedMessages = finalizeStreamingMessagesWhenIdle(liveDecision.nativeMessages, returnedStatus);
|
|
2432
|
+
selectedProviderSessionId = liveWorkspaceNativeProviderSessionId || providerSessionId;
|
|
2433
|
+
selectedTranscriptAuthority = 'provider';
|
|
2434
|
+
selectedCoverage = (liveWorkspaceNativeHistory as any).hasMore ? 'tail' : 'full';
|
|
2435
|
+
if (selectedProviderSessionId && selectedProviderSessionId !== providerSessionId) {
|
|
2436
|
+
adapter.updateRuntimeMeta?.({ providerSessionId: selectedProviderSessionId });
|
|
2437
|
+
}
|
|
2438
|
+
messageSource = liveDecision.messageSource;
|
|
2439
|
+
(messageSource as any).selectedDaemonSource = 'live-workspace-native-history';
|
|
2440
|
+
(messageSource as any).runtimeMappingSafe = true;
|
|
2441
|
+
} else {
|
|
2442
|
+
// Live probe also rejected: apply unsafe-native daemon mirror
|
|
2443
|
+
// selection (codex-only) using the primary decision's
|
|
2444
|
+
// fallbackReason.
|
|
2445
|
+
applyUnsafeNativeDaemonFallback({
|
|
2446
|
+
providerType,
|
|
2447
|
+
adapter,
|
|
2448
|
+
helpers: h,
|
|
2449
|
+
readChatArgs: args,
|
|
2450
|
+
sessionWorkspace,
|
|
2451
|
+
intendedWorkspace,
|
|
2452
|
+
ptyMessages: returnedMessages,
|
|
2453
|
+
nativeHistoryLimit,
|
|
2454
|
+
provider,
|
|
2455
|
+
messageSourceRef: { set(value) { messageSource = value; }, get() { return messageSource; } },
|
|
2456
|
+
apply(selection) {
|
|
2457
|
+
selectedMessages = selection.messages;
|
|
2458
|
+
selectedTranscriptAuthority = selection.transcriptAuthority;
|
|
2459
|
+
selectedCoverage = selection.coverage ?? coverage;
|
|
2460
|
+
selectedStatus = selection.status ?? returnedStatus;
|
|
2461
|
+
},
|
|
2462
|
+
activeModal,
|
|
2463
|
+
returnedStatus,
|
|
2464
|
+
coverage,
|
|
2465
|
+
});
|
|
2466
|
+
}
|
|
2467
|
+
} else {
|
|
2468
|
+
applyUnsafeNativeDaemonFallback({
|
|
2469
|
+
providerType,
|
|
2470
|
+
adapter,
|
|
2471
|
+
helpers: h,
|
|
2472
|
+
readChatArgs: args,
|
|
2473
|
+
sessionWorkspace,
|
|
2474
|
+
intendedWorkspace,
|
|
2475
|
+
ptyMessages: returnedMessages,
|
|
2476
|
+
nativeHistoryLimit,
|
|
2477
|
+
provider,
|
|
2478
|
+
messageSourceRef: { set(value) { messageSource = value; }, get() { return messageSource; } },
|
|
2479
|
+
apply(selection) {
|
|
2480
|
+
selectedMessages = selection.messages;
|
|
2481
|
+
selectedTranscriptAuthority = selection.transcriptAuthority;
|
|
2482
|
+
selectedCoverage = selection.coverage ?? coverage;
|
|
2483
|
+
selectedStatus = selection.status ?? returnedStatus;
|
|
2484
|
+
},
|
|
2485
|
+
activeModal,
|
|
2486
|
+
returnedStatus,
|
|
2487
|
+
coverage,
|
|
2488
|
+
});
|
|
2489
|
+
}
|
|
2490
|
+
}
|
|
2491
|
+
if (
|
|
2492
|
+
isGeneratingLikeStatus(selectedStatus)
|
|
2493
|
+
&& selectedTranscriptAuthority === 'provider'
|
|
2494
|
+
&& !hasNonEmptyModalButtons(activeModal)
|
|
2495
|
+
&& hasFinalVisibleAssistantMessage(selectedMessages)
|
|
2496
|
+
) {
|
|
2497
|
+
selectedStatus = 'idle';
|
|
2498
|
+
selectedMessages = finalizeStreamingMessagesWhenIdle(selectedMessages, selectedStatus);
|
|
2499
|
+
messageSource = {
|
|
2500
|
+
...messageSource,
|
|
2501
|
+
statusReconciled: {
|
|
2502
|
+
from: returnedStatus,
|
|
2503
|
+
to: 'idle',
|
|
2504
|
+
reason: 'provider_native_final_assistant',
|
|
2505
|
+
},
|
|
2506
|
+
};
|
|
2507
|
+
}
|
|
885
2508
|
LOG.debug('Command', `[read_chat] cli-like parsed provider=${adapter.cliType} target=${String(args?.targetSessionId || '')} adapterStatus=${String(adapterStatus.status || '')} parsedStatus=${String(parsedRecord.status || '')} parsedMsgCount=${parsedRecord.messages.length} returnedMsgCount=${returnedMessages.length}`);
|
|
886
2509
|
return buildReadChatCommandResult({
|
|
887
|
-
messages:
|
|
888
|
-
status:
|
|
2510
|
+
messages: selectedMessages,
|
|
2511
|
+
status: selectedStatus,
|
|
889
2512
|
activeModal,
|
|
2513
|
+
messageSource,
|
|
2514
|
+
transcriptProvenance: messageSource,
|
|
890
2515
|
debugReadChat: {
|
|
891
2516
|
provider: adapter.cliType,
|
|
892
2517
|
targetSessionId: String(args?.targetSessionId || ''),
|
|
893
2518
|
adapterStatus: String(adapterStatus.status || ''),
|
|
894
2519
|
parsedStatus: String(parsedRecord.status || ''),
|
|
895
|
-
returnedStatus: String(
|
|
896
|
-
|
|
2520
|
+
returnedStatus: String(selectedStatus || ''),
|
|
2521
|
+
selectedMessageSource: (messageSource as any).selected,
|
|
2522
|
+
messageSource,
|
|
2523
|
+
shouldPreferAdapterMessages: supportsCliNativeTranscript(providerType, provider)
|
|
2524
|
+
&& isNativeSourceCanonicalHistory(provider?.nativeHistory)
|
|
2525
|
+
&& (messageSource as any).selected !== 'native-history'
|
|
2526
|
+
&& typeof (messageSource as any).fallbackReason === 'string'
|
|
2527
|
+
&& (messageSource as any).fallbackReason.startsWith('native_history_')
|
|
2528
|
+
&& (messageSource as any).fallbackReason !== 'native_history_not_checked'
|
|
2529
|
+
&& !isUnsafeNativeTranscriptFallback((messageSource as any).fallbackReason)
|
|
2530
|
+
&& !(selectedTranscriptAuthority === 'provider' && selectedCoverage === 'full'),
|
|
897
2531
|
parsedMsgCount: parsedRecord.messages.length,
|
|
898
|
-
returnedMsgCount:
|
|
2532
|
+
returnedMsgCount: selectedMessages.length,
|
|
899
2533
|
},
|
|
900
|
-
...(
|
|
901
|
-
...(
|
|
902
|
-
...(
|
|
903
|
-
...(
|
|
904
|
-
}, args);
|
|
2534
|
+
...(selectedTitle ? { title: selectedTitle } : {}),
|
|
2535
|
+
...(selectedProviderSessionId ? { providerSessionId: selectedProviderSessionId } : {}),
|
|
2536
|
+
...(selectedTranscriptAuthority ? { transcriptAuthority: selectedTranscriptAuthority } : {}),
|
|
2537
|
+
...(selectedCoverage ? { coverage: selectedCoverage } : {}),
|
|
2538
|
+
}, args, h);
|
|
905
2539
|
}
|
|
2540
|
+
// History-only path (no adapter). Same source-decision contract as
|
|
2541
|
+
// the adapter path above, but with no PTY messages — the machine
|
|
2542
|
+
// simply decides whether native is usable; if not we return the
|
|
2543
|
+
// history we have plus a `native_history_not_safely_available`
|
|
2544
|
+
// error response when the provider requires native source.
|
|
906
2545
|
const historyLimit = normalizeReadChatTailLimit(args);
|
|
907
2546
|
try {
|
|
908
2547
|
const agentStr = provider?.type || args?.agentType || getCurrentProviderType(h);
|
|
909
|
-
const workspace = typeof
|
|
910
|
-
?
|
|
911
|
-
:
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
2548
|
+
const workspace = typeof (h.currentSession as any)?.workspace === 'string'
|
|
2549
|
+
? (h.currentSession as any).workspace
|
|
2550
|
+
: undefined;
|
|
2551
|
+
const intendedWorkspace = typeof args?.workspace === 'string' ? args.workspace : undefined;
|
|
2552
|
+
const supportsNative = supportsCliNativeTranscript(agentStr, provider)
|
|
2553
|
+
&& isNativeSourceCanonicalHistory(provider?.nativeHistory);
|
|
2554
|
+
const history = supportsNative
|
|
2555
|
+
? readCliProviderNativeHistory(agentStr, {
|
|
2556
|
+
canonicalHistory: provider?.nativeHistory,
|
|
2557
|
+
historySessionId,
|
|
2558
|
+
workspace,
|
|
2559
|
+
offset: 0,
|
|
2560
|
+
limit: historyLimit,
|
|
2561
|
+
excludeRecentCount: 0,
|
|
2562
|
+
historyBehavior: provider?.historyBehavior,
|
|
2563
|
+
scripts: provider?.scripts as any,
|
|
2564
|
+
sessionStartedAtMs: sessionStartedAtMsFromRegistry(h, args?.targetSessionId),
|
|
2565
|
+
envOverrides: sessionSpawnEnvFromAdapter(h, args?.targetSessionId),
|
|
2566
|
+
})
|
|
2567
|
+
: readProviderChatHistory(agentStr, {
|
|
2568
|
+
canonicalHistory: provider?.nativeHistory,
|
|
2569
|
+
historySessionId,
|
|
2570
|
+
workspace,
|
|
2571
|
+
offset: 0,
|
|
2572
|
+
limit: historyLimit,
|
|
2573
|
+
excludeRecentCount: 0,
|
|
2574
|
+
historyBehavior: provider?.historyBehavior,
|
|
2575
|
+
scripts: provider?.scripts as any,
|
|
2576
|
+
});
|
|
2577
|
+
const lookup = (history as any)?.lookup === 'workspace' ? 'workspace' : 'session';
|
|
2578
|
+
const historyMessages = Array.isArray((history as any)?.messages)
|
|
2579
|
+
? normalizeAndFilterNativeHistory(h, agentStr, args, (history as any).messages as ChatMessage[], (history as any)?.providerSessionId)
|
|
2580
|
+
: [];
|
|
924
2581
|
const historyProviderSessionId = typeof (history as any)?.providerSessionId === 'string'
|
|
925
2582
|
? (history as any).providerSessionId
|
|
926
|
-
: historySessionId;
|
|
2583
|
+
: readHistorySessionIdFromMessages(historyMessages) || historySessionId;
|
|
2584
|
+
const safeMapping = supportsNative
|
|
2585
|
+
? hasSafeNativeHistoryMapping({
|
|
2586
|
+
historySessionId: lookup === 'workspace' ? undefined : historySessionId,
|
|
2587
|
+
providerSessionId: lookup === 'workspace' ? undefined : historyProviderSessionId,
|
|
2588
|
+
workspace,
|
|
2589
|
+
nativeMessages: historyMessages,
|
|
2590
|
+
})
|
|
2591
|
+
: false;
|
|
2592
|
+
const trustedExactNativeIdentity = lookup !== 'workspace'
|
|
2593
|
+
&& Boolean(historySessionId)
|
|
2594
|
+
&& Boolean(historyProviderSessionId)
|
|
2595
|
+
&& historySessionId === historyProviderSessionId;
|
|
2596
|
+
|
|
2597
|
+
const machineSessionKey = String(
|
|
2598
|
+
args?.targetSessionId
|
|
2599
|
+
|| historyProviderSessionId
|
|
2600
|
+
|| historySessionId
|
|
2601
|
+
|| (h.currentSession as any)?.sessionId
|
|
2602
|
+
|| ''
|
|
2603
|
+
);
|
|
2604
|
+
const decision = decideCliReadChatSource({
|
|
2605
|
+
providerType: agentStr,
|
|
2606
|
+
provider,
|
|
2607
|
+
sessionId: machineSessionKey,
|
|
2608
|
+
nativeHistoryResult: history,
|
|
2609
|
+
safeMapping,
|
|
2610
|
+
trustedExactNativeIdentity,
|
|
2611
|
+
sessionWorkspace: workspace,
|
|
2612
|
+
intendedWorkspace,
|
|
2613
|
+
ptyMessages: [],
|
|
2614
|
+
ptyStatusApprovalOnly: false,
|
|
2615
|
+
});
|
|
2616
|
+
|
|
2617
|
+
if (supportsNative && !decision.nativeSelected) {
|
|
2618
|
+
return {
|
|
2619
|
+
success: false,
|
|
2620
|
+
code: 'native_history_not_safely_available',
|
|
2621
|
+
error: 'Provider-native history was not safely available for the requested CLI session.',
|
|
2622
|
+
providerSessionId: historyProviderSessionId,
|
|
2623
|
+
messageSource: decision.messageSource,
|
|
2624
|
+
transcriptProvenance: decision.messageSource,
|
|
2625
|
+
};
|
|
2626
|
+
}
|
|
927
2627
|
return buildReadChatCommandResult({
|
|
928
|
-
messages:
|
|
2628
|
+
messages: historyMessages,
|
|
929
2629
|
status: 'idle',
|
|
2630
|
+
messageSource: decision.messageSource,
|
|
2631
|
+
transcriptProvenance: decision.messageSource,
|
|
930
2632
|
...(typeof (history as any)?.title === 'string' ? { title: (history as any).title } : {}),
|
|
931
2633
|
...(historyProviderSessionId ? { providerSessionId: historyProviderSessionId } : {}),
|
|
932
2634
|
...(((provider?.historyBehavior as any)?.transcriptAuthority === 'provider' || (provider?.historyBehavior as any)?.transcriptAuthority === 'daemon')
|
|
933
2635
|
? { transcriptAuthority: (provider?.historyBehavior as any).transcriptAuthority }
|
|
934
2636
|
: {}),
|
|
935
2637
|
coverage: 'tail',
|
|
936
|
-
}, args);
|
|
2638
|
+
}, args, h);
|
|
937
2639
|
} catch (error: any) {
|
|
938
2640
|
return { success: false, error: error?.message || `${transport} adapter not found` };
|
|
939
2641
|
}
|
|
@@ -973,7 +2675,7 @@ export async function handleReadChat(h: CommandHelpers, args: any): Promise<Comm
|
|
|
973
2675
|
args?.targetSessionId,
|
|
974
2676
|
historySessionId,
|
|
975
2677
|
);
|
|
976
|
-
return buildReadChatCommandResult(validated as Record<string, any>, args);
|
|
2678
|
+
return buildReadChatCommandResult(validated as Record<string, any>, args, h);
|
|
977
2679
|
}
|
|
978
2680
|
if (!extensionReadChatError) {
|
|
979
2681
|
extensionReadChatError = 'extension read_chat returned a non-object payload';
|
|
@@ -1012,7 +2714,7 @@ export async function handleReadChat(h: CommandHelpers, args: any): Promise<Comm
|
|
|
1012
2714
|
messages: stream.messages || [],
|
|
1013
2715
|
status: stream.status,
|
|
1014
2716
|
agentType: stream.agentType,
|
|
1015
|
-
}, args);
|
|
2717
|
+
}, args, h);
|
|
1016
2718
|
}
|
|
1017
2719
|
}
|
|
1018
2720
|
}
|
|
@@ -1052,7 +2754,7 @@ export async function handleReadChat(h: CommandHelpers, args: any): Promise<Comm
|
|
|
1052
2754
|
args?.targetSessionId,
|
|
1053
2755
|
historySessionId,
|
|
1054
2756
|
);
|
|
1055
|
-
return buildReadChatCommandResult(validated as Record<string, any>, args);
|
|
2757
|
+
return buildReadChatCommandResult(validated as Record<string, any>, args, h);
|
|
1056
2758
|
}
|
|
1057
2759
|
if (!webviewReadChatError) {
|
|
1058
2760
|
webviewReadChatError = 'webview read_chat returned a non-object payload';
|
|
@@ -1102,7 +2804,7 @@ export async function handleReadChat(h: CommandHelpers, args: any): Promise<Comm
|
|
|
1102
2804
|
args?.targetSessionId,
|
|
1103
2805
|
historySessionId,
|
|
1104
2806
|
);
|
|
1105
|
-
return buildReadChatCommandResult(validated as Record<string, any>, args);
|
|
2807
|
+
return buildReadChatCommandResult(validated as Record<string, any>, args, h);
|
|
1106
2808
|
}
|
|
1107
2809
|
if (!ideReadChatError) {
|
|
1108
2810
|
ideReadChatError = 'ide read_chat returned a non-object payload';
|
|
@@ -1184,8 +2886,24 @@ export async function handleSendChat(h: CommandHelpers, args: any): Promise<Comm
|
|
|
1184
2886
|
assertTextOnlyInput(provider, input);
|
|
1185
2887
|
if (!text) return { success: false, error: 'text required for PTY send' };
|
|
1186
2888
|
await waitOnceForFreshHermesCliStart(adapter, _log);
|
|
1187
|
-
|
|
1188
|
-
|
|
2889
|
+
const forceSend = args?.force === true || args?.forceSend === true;
|
|
2890
|
+
if (forceSend && typeof adapter.forceSendMessage === 'function') {
|
|
2891
|
+
await adapter.forceSendMessage(text);
|
|
2892
|
+
} else if (forceSend) {
|
|
2893
|
+
await adapter.sendMessage(text, { force: true });
|
|
2894
|
+
} else {
|
|
2895
|
+
await adapter.sendMessage(text);
|
|
2896
|
+
}
|
|
2897
|
+
const target = getTargetInstance(h, args) as RuntimeChatMessageMerger | null;
|
|
2898
|
+
if (target?.category === 'cli'
|
|
2899
|
+
&& target.type === adapter.cliType
|
|
2900
|
+
&& typeof target.recordAcknowledgedUserInput === 'function') {
|
|
2901
|
+
target.recordAcknowledgedUserInput(input);
|
|
2902
|
+
}
|
|
2903
|
+
return {
|
|
2904
|
+
..._logSendSuccess(`${transport}-adapter`, adapter.cliType),
|
|
2905
|
+
...(forceSend ? { forceSent: true } : {}),
|
|
2906
|
+
};
|
|
1189
2907
|
} catch (e: any) {
|
|
1190
2908
|
return { success: false, error: `${transport} send failed: ${e.message}` };
|
|
1191
2909
|
}
|
|
@@ -1742,9 +3460,18 @@ export async function handleResolveAction(h: CommandHelpers, args: any): Promise
|
|
|
1742
3460
|
if (buttonIndex < 0 && (action === 'always' || /always/i.test(button))) {
|
|
1743
3461
|
buttonIndex = buttons.findIndex(b => /always/i.test(b));
|
|
1744
3462
|
}
|
|
3463
|
+
if (buttonIndex < 0 && (action === 'approve' || action === 'accept')) {
|
|
3464
|
+
buttonIndex = pickApprovalButton(buttons, provider).index;
|
|
3465
|
+
}
|
|
1745
3466
|
if (buttonIndex < 0) {
|
|
1746
3467
|
return { success: false, error: 'Approval action did not match any visible button' };
|
|
1747
3468
|
}
|
|
3469
|
+
// Idempotency: if the adapter already resolved this approval within cooldown, report
|
|
3470
|
+
// stale_prompt rather than writing a second key to the PTY.
|
|
3471
|
+
if (typeof adapter.isApprovalRecentlyResolved === 'function' && adapter.isApprovalRecentlyResolved()) {
|
|
3472
|
+
LOG.info('Command', `[resolveAction] CLI PTY → stale_prompt (already resolved within cooldown)`);
|
|
3473
|
+
return { success: true, stalePrompt: true, buttonIndex, button: buttons[buttonIndex] ?? button };
|
|
3474
|
+
}
|
|
1748
3475
|
if (typeof adapter.resolveModal === 'function') {
|
|
1749
3476
|
adapter.resolveModal(buttonIndex);
|
|
1750
3477
|
} else {
|