@adhdev/daemon-core 0.9.82-rc.17 → 0.9.82-rc.170
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/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 +22 -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/commands/handler.d.ts +110 -0
- package/dist/commands/mesh-coordinator.d.ts +72 -1
- package/dist/commands/router.d.ts +22 -0
- package/dist/config/chat-history.d.ts +7 -0
- package/dist/config/config.d.ts +5 -0
- package/dist/config/mesh-config.d.ts +71 -1
- package/dist/git/git-commands.d.ts +5 -1
- package/dist/index.d.ts +35 -6
- package/dist/index.js +18621 -3760
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +18525 -3732
- 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/beads-db.d.ts +72 -0
- package/dist/mesh/contracts.d.ts +164 -0
- package/dist/mesh/coordinator-prompt.d.ts +30 -0
- package/dist/mesh/coordinator-registry.d.ts +59 -0
- package/dist/mesh/mesh-active-work.d.ts +90 -0
- package/dist/mesh/mesh-events.d.ts +96 -5
- package/dist/mesh/mesh-fast-forward.d.ts +39 -0
- package/dist/mesh/mesh-host-ownership.d.ts +9 -0
- package/dist/mesh/mesh-ledger.d.ts +58 -1
- package/dist/mesh/mesh-refine-status.d.ts +26 -0
- package/dist/mesh/mesh-work-queue.d.ts +44 -5
- package/dist/mesh/preview-freshness.d.ts +18 -0
- package/dist/mesh/refine-config.d.ts +193 -0
- package/dist/mesh/worktree-bootstrap-config.d.ts +113 -0
- package/dist/providers/approval-utils.d.ts +13 -0
- package/dist/providers/cli-provider-instance.d.ts +9 -3
- package/dist/providers/contracts.d.ts +98 -5
- 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 +24 -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.d.ts +3 -0
- 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 +169 -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 +56 -0
- package/dist/providers/spec/cli-adapter.d.ts +95 -0
- package/dist/providers/spec/driver.d.ts +149 -0
- package/dist/providers/spec/evaluator.d.ts +47 -0
- package/dist/providers/spec/loader.d.ts +14 -0
- package/dist/providers/spec/native-history-executor.d.ts +39 -0
- package/dist/providers/spec/route.d.ts +4 -0
- package/dist/providers/spec/schema.gen.d.ts +511 -0
- package/dist/providers/spec/types.d.ts +212 -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 +100 -1
- package/dist/sessions/registry.d.ts +3 -0
- package/dist/shared-types.d.ts +42 -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 +7 -2
- package/src/agent-stream/poller.ts +2 -3
- package/src/boot/daemon-lifecycle.ts +17 -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 +14 -1
- package/src/cli-adapter-types.d.ts +1 -0
- package/src/cli-adapter-types.ts +21 -2
- package/src/cli-adapters/cli-script-runner.ts +421 -0
- package/src/cli-adapters/cli-state-engine.ts +1086 -0
- package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
- package/src/cli-adapters/provider-cli-adapter.ts +670 -1137
- 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 +17 -1
- package/src/cli-adapters/terminal-backends/xterm-backend.ts +8 -1
- package/src/commands/chat-commands.ts +1597 -60
- package/src/commands/cli-manager.ts +214 -3
- package/src/commands/handler.ts +809 -2
- package/src/commands/mesh-coordinator.ts +231 -127
- package/src/commands/router.ts +3559 -502
- package/src/config/chat-history.ts +87 -24
- package/src/config/config.ts +12 -0
- package/src/config/mesh-config.ts +264 -2
- package/src/config/recent-activity.ts +8 -2
- package/src/daemon/dev-cli-debug.ts +10 -1
- package/src/detection/ide-detector.ts +26 -16
- package/src/git/git-commands.ts +17 -5
- package/src/git/git-worktree.ts +8 -1
- package/src/index.ts +113 -5
- 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/beads-db.ts +479 -0
- package/src/mesh/contracts.ts +329 -0
- package/src/mesh/coordinator-prompt.ts +204 -30
- package/src/mesh/coordinator-registry.ts +121 -0
- package/src/mesh/mesh-active-work.ts +437 -0
- package/src/mesh/mesh-events.ts +879 -61
- package/src/mesh/mesh-fast-forward.ts +430 -0
- package/src/mesh/mesh-host-ownership.ts +73 -0
- package/src/mesh/mesh-ledger.ts +457 -104
- package/src/mesh/mesh-refine-status.ts +144 -0
- package/src/mesh/mesh-work-queue.ts +216 -158
- package/src/mesh/preview-freshness.ts +118 -0
- package/src/mesh/refine-config.ts +366 -0
- package/src/mesh/worktree-bootstrap-config.ts +247 -0
- 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 +452 -54
- package/src/providers/contracts.ts +105 -5
- 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 +227 -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.ts +3 -0
- package/src/providers/provider-loader.ts +585 -50
- package/src/providers/provider-schema.ts +31 -13
- 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 +458 -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 +210 -0
- package/src/providers/sdk/v1/validators/index.ts +19 -0
- package/src/providers/sdk/v1/validators/manifest.ts +110 -0
- package/src/providers/sdk/v1/validators/taint.ts +309 -0
- package/src/providers/spec/adapter.ts +168 -0
- package/src/providers/spec/cli-adapter.ts +430 -0
- package/src/providers/spec/driver.ts +502 -0
- package/src/providers/spec/evaluator.ts +298 -0
- package/src/providers/spec/loader.ts +130 -0
- package/src/providers/spec/native-history-executor.ts +623 -0
- package/src/providers/spec/route.ts +51 -0
- package/src/providers/spec/schema.gen.ts +511 -0
- package/src/providers/spec/schema.json +211 -0
- package/src/providers/spec/types.ts +231 -0
- package/src/providers/transcript-v2.ts +567 -0
- package/src/providers/types/interactive-prompt.ts +297 -0
- package/src/providers/version-archive.ts +38 -20
- package/src/repo-mesh-types.ts +110 -1
- package/src/sessions/registry.ts +3 -0
- package/src/shared-types.ts +45 -1
- package/src/status/builders.ts +24 -6
- 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
|
@@ -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,47 @@ 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;
|
|
155
223
|
}
|
|
156
224
|
|
|
157
225
|
function getInteractionId(args: any): string | undefined {
|
|
@@ -221,6 +289,923 @@ function normalizeReadChatMessages(payload: Record<string, any>): ChatMessage[]
|
|
|
221
289
|
return normalizeChatMessages(messages);
|
|
222
290
|
}
|
|
223
291
|
|
|
292
|
+
function getMessageNewestReceivedAt(messages: Array<{ receivedAt?: unknown; timestamp?: unknown }>): number {
|
|
293
|
+
let newest = 0;
|
|
294
|
+
for (const message of messages) {
|
|
295
|
+
const receivedAt = Number(message?.receivedAt ?? message?.timestamp ?? 0);
|
|
296
|
+
if (Number.isFinite(receivedAt) && receivedAt > newest) newest = receivedAt;
|
|
297
|
+
}
|
|
298
|
+
return newest;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function readHistorySessionIdFromMessages(messages: ChatMessage[]): string | undefined {
|
|
302
|
+
for (const message of messages as Array<ChatMessage & { historySessionId?: unknown }>) {
|
|
303
|
+
const historySessionId = typeof message?.historySessionId === 'string' ? message.historySessionId.trim() : '';
|
|
304
|
+
if (historySessionId) return historySessionId;
|
|
305
|
+
}
|
|
306
|
+
return undefined;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function shouldPreserveNativeIdentity(providerType: string, sessionId: string, message: ChatMessage): boolean {
|
|
310
|
+
const providerUnitKey = typeof message.providerUnitKey === 'string' ? message.providerUnitKey.trim() : '';
|
|
311
|
+
const turnKey = typeof message._turnKey === 'string' ? message._turnKey.trim() : '';
|
|
312
|
+
if (!providerUnitKey) return false;
|
|
313
|
+
// (A2.3) v2 stamped identity is producer-owned and globally stable; trust it
|
|
314
|
+
// unconditionally. Producers may omit _turnKey (the daemon recomputes it
|
|
315
|
+
// from the current ordering), so do not require turnKey for v2 messages.
|
|
316
|
+
if (providerUnitKey.startsWith('v2:') || providerUnitKey.startsWith('v2-pty:')) {
|
|
317
|
+
return true;
|
|
318
|
+
}
|
|
319
|
+
// v1 identity always required both keys to be present.
|
|
320
|
+
if (!turnKey) return false;
|
|
321
|
+
if (providerType === 'hermes-cli' && sessionId) {
|
|
322
|
+
return providerUnitKey.startsWith(`${providerType}:native:${sessionId}:`)
|
|
323
|
+
&& turnKey.startsWith(`${providerType}:native-turn:${sessionId}:`);
|
|
324
|
+
}
|
|
325
|
+
return true;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Drop the synthetic "user" message some CLIs surface in their native
|
|
330
|
+
* transcript when the daemon injects a coordinator system prompt
|
|
331
|
+
* (codex puts the AGENTS.md / developer_instructions block in as
|
|
332
|
+
* role=user; agy/claude/hermes have similar artifacts). The user can
|
|
333
|
+
* opt back into seeing it via the provider setting
|
|
334
|
+
* `showCoordinatorSystemPrompt`. Default is off — the prompt is still
|
|
335
|
+
* fully visible from the chat-header ⓘ "Session info" dialog.
|
|
336
|
+
*
|
|
337
|
+
* Matching rules:
|
|
338
|
+
* 1. Setting must be off (default).
|
|
339
|
+
* 2. There must be a registered coordinator entry for the session.
|
|
340
|
+
* 3. The candidate message is filtered when its role is user OR
|
|
341
|
+
* system and its content either contains the prompt body verbatim,
|
|
342
|
+
* OR contains the well-known coordinator marker
|
|
343
|
+
* `adhdev-mesh-coordinator-prompt`. The marker covers context-file
|
|
344
|
+
* cases (agy AGENTS.md / gemini GEMINI.md) where the CLI may wrap
|
|
345
|
+
* its own preamble around our block. Verbatim-content covers
|
|
346
|
+
* codex's developer_instructions echo.
|
|
347
|
+
*
|
|
348
|
+
* Returns the messages array unchanged when none of the rules match,
|
|
349
|
+
* so this is safe to apply unconditionally to every read_chat result.
|
|
350
|
+
*/
|
|
351
|
+
function maybeHideCoordinatorPromptMessage(
|
|
352
|
+
h: CommandHelpers,
|
|
353
|
+
providerType: string,
|
|
354
|
+
sessionId: string | undefined,
|
|
355
|
+
messages: ChatMessage[],
|
|
356
|
+
): ChatMessage[] {
|
|
357
|
+
if (!Array.isArray(messages) || messages.length === 0) return messages;
|
|
358
|
+
if (!sessionId) return messages;
|
|
359
|
+
const loader = h.ctx?.providerLoader;
|
|
360
|
+
if (!loader) return messages;
|
|
361
|
+
let showSetting: unknown = undefined;
|
|
362
|
+
try {
|
|
363
|
+
showSetting = (loader as any).getSettingValue?.(providerType, 'showCoordinatorSystemPrompt');
|
|
364
|
+
} catch { /* unknown setting key for this provider — fall through */ }
|
|
365
|
+
if (showSetting === true) return messages;
|
|
366
|
+
const coord = getCoordinatorForSession(sessionId);
|
|
367
|
+
if (!coord) return messages;
|
|
368
|
+
const promptBody = typeof coord.systemPrompt === 'string' ? coord.systemPrompt : '';
|
|
369
|
+
const MARKER = 'adhdev-mesh-coordinator-prompt';
|
|
370
|
+
const filtered = messages.filter(m => {
|
|
371
|
+
const role = String((m as any)?.role || '').toLowerCase();
|
|
372
|
+
if (role !== 'user' && role !== 'system') return true;
|
|
373
|
+
const content = flattenContent((m as any)?.content);
|
|
374
|
+
if (!content) return true;
|
|
375
|
+
if (content.includes(MARKER)) return false;
|
|
376
|
+
if (promptBody && content.includes(promptBody.slice(0, Math.min(400, promptBody.length)))) return false;
|
|
377
|
+
return true;
|
|
378
|
+
});
|
|
379
|
+
if (filtered.length !== messages.length) {
|
|
380
|
+
LOG.debug('ChatFilter', `[${providerType}] hid ${messages.length - filtered.length} coordinator-prompt message(s) from ${sessionId}`);
|
|
381
|
+
}
|
|
382
|
+
return filtered;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* Convenience wrapper used at every native-history call site: normalize +
|
|
387
|
+
* conditionally drop the coordinator system-prompt message. Avoids
|
|
388
|
+
* duplicating the filter at four read_chat code paths.
|
|
389
|
+
*/
|
|
390
|
+
function normalizeAndFilterNativeHistory(
|
|
391
|
+
h: CommandHelpers,
|
|
392
|
+
providerType: string,
|
|
393
|
+
args: any,
|
|
394
|
+
messages: ChatMessage[],
|
|
395
|
+
nativeSessionId?: string,
|
|
396
|
+
): ChatMessage[] {
|
|
397
|
+
const normalized = normalizeNativeHistoryMessages(providerType, messages, nativeSessionId);
|
|
398
|
+
const sessionId = typeof args?.targetSessionId === 'string' ? args.targetSessionId
|
|
399
|
+
: typeof args?.sessionId === 'string' ? args.sessionId
|
|
400
|
+
: undefined;
|
|
401
|
+
return maybeHideCoordinatorPromptMessage(h, providerType, sessionId, normalized);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function normalizeNativeHistoryMessages(providerType: string, messages: ChatMessage[], nativeSessionId?: string): ChatMessage[] {
|
|
405
|
+
let turnIndex = 0;
|
|
406
|
+
return normalizeChatMessages(messages).map((message, index) => {
|
|
407
|
+
const role = typeof message.role === 'string' ? message.role.trim().toLowerCase() : '';
|
|
408
|
+
const kind = typeof message.kind === 'string' && message.kind.trim() ? message.kind.trim() : (role === 'system' ? 'system' : 'standard');
|
|
409
|
+
if ((role === 'user' || role === 'human') && index > 0) turnIndex += 1;
|
|
410
|
+
const historySessionId = typeof (message as any).historySessionId === 'string'
|
|
411
|
+
? (message as any).historySessionId.trim()
|
|
412
|
+
: '';
|
|
413
|
+
const contentHash = hashSignatureParts([
|
|
414
|
+
providerType,
|
|
415
|
+
historySessionId,
|
|
416
|
+
String(message.receivedAt || message.timestamp || index),
|
|
417
|
+
role,
|
|
418
|
+
kind,
|
|
419
|
+
flattenContent(message.content),
|
|
420
|
+
]).slice(0, 12);
|
|
421
|
+
const nativeIdentitySessionId = historySessionId || (typeof nativeSessionId === 'string' ? nativeSessionId.trim() : '');
|
|
422
|
+
const preserveNativeIdentity = shouldPreserveNativeIdentity(providerType, nativeIdentitySessionId, message);
|
|
423
|
+
const existingProviderUnitKey = typeof message.providerUnitKey === 'string' ? message.providerUnitKey.trim() : '';
|
|
424
|
+
const existingTurnKey = typeof message._turnKey === 'string' ? message._turnKey.trim() : '';
|
|
425
|
+
const providerUnitKey = preserveNativeIdentity
|
|
426
|
+
? existingProviderUnitKey
|
|
427
|
+
: `${providerType}:native:${nativeIdentitySessionId || 'workspace'}:${index}:${role || 'message'}:${kind}:${contentHash}`;
|
|
428
|
+
const meta = message.meta && typeof message.meta === 'object' ? message.meta as Record<string, unknown> : undefined;
|
|
429
|
+
const isSystemSessionStart = role === 'system' || kind === 'system' || kind === 'session_start';
|
|
430
|
+
const isActivity = role === 'assistant' && (kind === 'tool' || kind === 'terminal' || kind === 'thought');
|
|
431
|
+
// (A2.3) sequence emit. Producer-supplied wins (v2-stamped messages
|
|
432
|
+
// bring their own monotonic sequence); otherwise derive from
|
|
433
|
+
// receivedAt/timestamp; otherwise positional. Always present on the
|
|
434
|
+
// output so consumers (ChatSourceMachine) have a stable ordering key.
|
|
435
|
+
const existingSequence = typeof (message as any).sequence === 'number'
|
|
436
|
+
&& Number.isFinite((message as any).sequence)
|
|
437
|
+
? (message as any).sequence
|
|
438
|
+
: null;
|
|
439
|
+
const tsCandidate = Number(message.receivedAt || message.timestamp || 0);
|
|
440
|
+
const sequence = existingSequence !== null
|
|
441
|
+
? existingSequence
|
|
442
|
+
: (tsCandidate > 0 ? tsCandidate : index);
|
|
443
|
+
return {
|
|
444
|
+
...message,
|
|
445
|
+
role: role === 'human' ? 'user' : (role || 'assistant'),
|
|
446
|
+
kind: isSystemSessionStart ? 'system' : kind,
|
|
447
|
+
providerUnitKey,
|
|
448
|
+
bubbleId: typeof message.bubbleId === 'string' && message.bubbleId.trim()
|
|
449
|
+
&& preserveNativeIdentity
|
|
450
|
+
? message.bubbleId.trim()
|
|
451
|
+
: `bubble:${providerUnitKey}`,
|
|
452
|
+
sequence,
|
|
453
|
+
_turnKey: preserveNativeIdentity
|
|
454
|
+
? existingTurnKey
|
|
455
|
+
: `${providerType}:native-turn:${nativeIdentitySessionId || 'workspace'}:${turnIndex}`,
|
|
456
|
+
bubbleState: message.bubbleState || 'final',
|
|
457
|
+
...(isSystemSessionStart ? {
|
|
458
|
+
visibility: message.visibility || 'hidden',
|
|
459
|
+
transcriptVisibility: message.transcriptVisibility || 'hidden',
|
|
460
|
+
audience: message.audience || 'internal',
|
|
461
|
+
source: message.source || 'runtime_status',
|
|
462
|
+
} : isActivity ? {
|
|
463
|
+
source: message.source || (kind === 'terminal' ? 'terminal_command' : 'tool_call'),
|
|
464
|
+
meta: { ...meta, label: message.senderName || meta?.label || (kind === 'terminal' ? 'Terminal' : 'Tool') },
|
|
465
|
+
} : {
|
|
466
|
+
source: message.source || (role === 'assistant' ? 'assistant_text' : undefined),
|
|
467
|
+
}),
|
|
468
|
+
} as ChatMessage;
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function buildCliMessageSourceProvenance(args: {
|
|
473
|
+
selected: 'native-history' | 'pty-parser';
|
|
474
|
+
provider: string;
|
|
475
|
+
nativeHandle?: string;
|
|
476
|
+
sessionWorkspace?: string;
|
|
477
|
+
intendedWorkspace?: string;
|
|
478
|
+
transcriptWorkspace?: string;
|
|
479
|
+
fallbackReason?: string;
|
|
480
|
+
nativeSource?: string;
|
|
481
|
+
sourcePath?: string;
|
|
482
|
+
sourceMtimeMs?: number;
|
|
483
|
+
nativeHistoryCoverage?: string;
|
|
484
|
+
partialReason?: string;
|
|
485
|
+
unavailableReason?: string;
|
|
486
|
+
nativeMessages?: ChatMessage[];
|
|
487
|
+
ptyMessages?: ChatMessage[];
|
|
488
|
+
returnedMessages?: ChatMessage[];
|
|
489
|
+
safeMapping?: boolean;
|
|
490
|
+
freshEnough?: boolean;
|
|
491
|
+
ptyStatusApprovalOnly?: boolean;
|
|
492
|
+
}): Record<string, unknown> {
|
|
493
|
+
const sourceMtimeMs = Number(args.sourceMtimeMs || 0);
|
|
494
|
+
const sourceMtimeAgeMs = sourceMtimeMs > 0 ? Math.max(0, Date.now() - sourceMtimeMs) : undefined;
|
|
495
|
+
const nativeMessages = args.nativeMessages || [];
|
|
496
|
+
const ptyMessages = args.ptyMessages || [];
|
|
497
|
+
const returnedMessages = args.returnedMessages || [];
|
|
498
|
+
const identityStatus = args.selected === 'native-history'
|
|
499
|
+
? 'safe'
|
|
500
|
+
: args.fallbackReason === 'native_history_not_safely_mapped'
|
|
501
|
+
? 'ambiguous_session_identity'
|
|
502
|
+
: args.fallbackReason?.startsWith('native_history_unavailable')
|
|
503
|
+
? 'transcript_unmapped'
|
|
504
|
+
: undefined;
|
|
505
|
+
return {
|
|
506
|
+
selected: args.selected,
|
|
507
|
+
provider: args.provider,
|
|
508
|
+
providerType: args.provider,
|
|
509
|
+
...(identityStatus ? { identityStatus } : {}),
|
|
510
|
+
...(args.nativeHandle ? { nativeHandle: args.nativeHandle } : {}),
|
|
511
|
+
...(args.nativeHandle ? { nativeSessionId: args.nativeHandle } : {}),
|
|
512
|
+
...(args.sessionWorkspace ? { sessionWorkspace: args.sessionWorkspace } : {}),
|
|
513
|
+
...(args.intendedWorkspace ? { intendedWorkspace: args.intendedWorkspace } : {}),
|
|
514
|
+
...(args.transcriptWorkspace ? { transcriptWorkspace: args.transcriptWorkspace } : {}),
|
|
515
|
+
...(args.fallbackReason ? { fallbackReason: args.fallbackReason } : {}),
|
|
516
|
+
...(args.nativeSource ? { nativeSource: args.nativeSource } : {}),
|
|
517
|
+
...(args.sourcePath ? { sourcePath: args.sourcePath } : {}),
|
|
518
|
+
...(args.nativeHistoryCoverage ? { nativeHistoryCoverage: args.nativeHistoryCoverage } : {}),
|
|
519
|
+
...(args.partialReason ? { partialReason: args.partialReason } : {}),
|
|
520
|
+
...(args.unavailableReason ? { unavailableReason: args.unavailableReason } : {}),
|
|
521
|
+
ptyStatusApprovalOnly: args.ptyStatusApprovalOnly === true,
|
|
522
|
+
staleness: {
|
|
523
|
+
sourceMtimeMs: sourceMtimeMs || undefined,
|
|
524
|
+
sourceMtimeAgeMs,
|
|
525
|
+
nativeNewestMessageAt: getMessageNewestReceivedAt(nativeMessages),
|
|
526
|
+
ptyNewestMessageAt: getMessageNewestReceivedAt(ptyMessages),
|
|
527
|
+
freshEnough: args.freshEnough === true,
|
|
528
|
+
},
|
|
529
|
+
coverage: {
|
|
530
|
+
nativeMessageCount: nativeMessages.length,
|
|
531
|
+
ptyMessageCount: ptyMessages.length,
|
|
532
|
+
returnedMessageCount: returnedMessages.length,
|
|
533
|
+
safeMapping: args.safeMapping === true,
|
|
534
|
+
// true when PTY message bodies are suppressed and must not be treated as
|
|
535
|
+
// chat content. PTY may still contribute status/approval/screen evidence.
|
|
536
|
+
ptyMessagesSuppressed: args.selected === 'native-history' || args.ptyStatusApprovalOnly === true,
|
|
537
|
+
},
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Map a ChatSourceMachine transition cause back to the v1 messageSource
|
|
543
|
+
* `fallbackReason` vocabulary so legacy consumers (web-cloud, tests, mesh
|
|
544
|
+
* debug bundles) keep parsing strings they already know. A3 replaces the
|
|
545
|
+
* caller surface with stateTransition/lockState, after which this map can be
|
|
546
|
+
* deleted.
|
|
547
|
+
*
|
|
548
|
+
* Returns undefined when the cause does not correspond to a fallback (i.e.
|
|
549
|
+
* the source is native-history and there is nothing to explain).
|
|
550
|
+
*/
|
|
551
|
+
function causeToLegacyFallbackReason(
|
|
552
|
+
cause: ChatSourceTransitionCause,
|
|
553
|
+
selected: 'native-history' | 'pty-parser',
|
|
554
|
+
extraDetail?: { unavailableReason?: string; nativeSource?: string },
|
|
555
|
+
): string | undefined {
|
|
556
|
+
if (selected === 'native-history') return undefined;
|
|
557
|
+
switch (cause) {
|
|
558
|
+
case 'initial':
|
|
559
|
+
return 'native_history_not_checked';
|
|
560
|
+
case 'native_progressed':
|
|
561
|
+
// Selected pty-parser despite a progressed observation — that
|
|
562
|
+
// means we held PtyOnly stickily (peak unmet or non-superset).
|
|
563
|
+
return 'native_history_not_selected';
|
|
564
|
+
case 'native_regressed_shrunk':
|
|
565
|
+
return 'native_history_empty';
|
|
566
|
+
case 'native_regressed_unsafe_mapping':
|
|
567
|
+
return 'native_history_not_safely_mapped';
|
|
568
|
+
case 'native_regressed_coverage_partial':
|
|
569
|
+
return 'native_history_partial';
|
|
570
|
+
case 'native_regressed_coverage_unavailable':
|
|
571
|
+
return 'native_history_unavailable';
|
|
572
|
+
case 'native_unavailable_read_error':
|
|
573
|
+
return extraDetail?.unavailableReason
|
|
574
|
+
? `native_history_unavailable:${extraDetail.unavailableReason}`
|
|
575
|
+
: 'native_history_unavailable';
|
|
576
|
+
case 'native_unavailable_provider_unsupported':
|
|
577
|
+
return 'provider_native_transcript_not_supported';
|
|
578
|
+
case 'native_unavailable_empty':
|
|
579
|
+
return 'native_history_empty';
|
|
580
|
+
case 'native_unavailable_not_native_source':
|
|
581
|
+
return extraDetail?.nativeSource
|
|
582
|
+
? `native_history_source_${extraDetail.nativeSource}`
|
|
583
|
+
: 'native_history_unavailable';
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/**
|
|
588
|
+
* Translate a native-history fetch result + provider/adapter context into a
|
|
589
|
+
* ChatSourceObservation and drive ChatSourceRegistry. Returns the decision
|
|
590
|
+
* together with the legacy messageSource payload so call sites can produce
|
|
591
|
+
* a v1-compatible response without duplicating the registry plumbing.
|
|
592
|
+
*
|
|
593
|
+
* This is the replacement for the 300-line if-ladder that previously lived
|
|
594
|
+
* inline in handleReadChat. It is intentionally split out for two reasons:
|
|
595
|
+
* (1) we will call it from two places (CLI adapter branch + history-only
|
|
596
|
+
* branch) instead of duplicating the ladder, (2) tests can drive it with
|
|
597
|
+
* synthetic native-history results to verify the cause→fallbackReason
|
|
598
|
+
* mapping without booting the whole readChat pipeline.
|
|
599
|
+
*/
|
|
600
|
+
function decideCliReadChatSource(args: {
|
|
601
|
+
providerType: string;
|
|
602
|
+
provider?: ProviderModule;
|
|
603
|
+
sessionId: string;
|
|
604
|
+
nativeHistoryResult: any | null;
|
|
605
|
+
nativeHistoryError?: unknown;
|
|
606
|
+
safeMapping: boolean;
|
|
607
|
+
sessionWorkspace?: string;
|
|
608
|
+
intendedWorkspace?: string;
|
|
609
|
+
ptyMessages: ChatMessage[];
|
|
610
|
+
ptyStatusApprovalOnly: boolean;
|
|
611
|
+
}): {
|
|
612
|
+
decision: ChatSourceDecision;
|
|
613
|
+
messageSource: Record<string, unknown>;
|
|
614
|
+
nativeMessages: ChatMessage[];
|
|
615
|
+
nativeSelected: boolean;
|
|
616
|
+
} {
|
|
617
|
+
const supportsNative = supportsCliNativeTranscript(args.providerType, args.provider);
|
|
618
|
+
const observation = buildObservationForCli(args, supportsNative);
|
|
619
|
+
const sessionKey = chatSourceSessionKey(args.providerType, args.sessionId);
|
|
620
|
+
const decision = CHAT_SOURCE_REGISTRY.observe(sessionKey, observation);
|
|
621
|
+
|
|
622
|
+
const nativeMessages: ChatMessage[] = observation.kind === 'native_present'
|
|
623
|
+
? extractNativeMessagesFromResult(args.providerType, args.nativeHistoryResult)
|
|
624
|
+
: [];
|
|
625
|
+
|
|
626
|
+
const nativeSource = typeof args.nativeHistoryResult?.source === 'string'
|
|
627
|
+
? args.nativeHistoryResult.source
|
|
628
|
+
: undefined;
|
|
629
|
+
const sourcePath = typeof args.nativeHistoryResult?.sourcePath === 'string'
|
|
630
|
+
? args.nativeHistoryResult.sourcePath
|
|
631
|
+
: undefined;
|
|
632
|
+
const sourceMtimeMs = typeof args.nativeHistoryResult?.sourceMtimeMs === 'number'
|
|
633
|
+
? args.nativeHistoryResult.sourceMtimeMs
|
|
634
|
+
: undefined;
|
|
635
|
+
const coverageHint = typeof args.nativeHistoryResult?.nativeHistoryCoverage === 'string'
|
|
636
|
+
? args.nativeHistoryResult.nativeHistoryCoverage
|
|
637
|
+
: undefined;
|
|
638
|
+
const partialReason = typeof args.nativeHistoryResult?.partialReason === 'string'
|
|
639
|
+
? args.nativeHistoryResult.partialReason
|
|
640
|
+
: undefined;
|
|
641
|
+
const unavailableReason = typeof args.nativeHistoryResult?.unavailableReason === 'string'
|
|
642
|
+
? args.nativeHistoryResult.unavailableReason
|
|
643
|
+
: args.nativeHistoryError
|
|
644
|
+
? `error:${(args.nativeHistoryError as any)?.message || String(args.nativeHistoryError)}`
|
|
645
|
+
: undefined;
|
|
646
|
+
const nativeHandle = typeof args.nativeHistoryResult?.providerSessionId === 'string'
|
|
647
|
+
? args.nativeHistoryResult.providerSessionId
|
|
648
|
+
: undefined;
|
|
649
|
+
const transcriptWorkspace = typeof args.nativeHistoryResult?.workspace === 'string'
|
|
650
|
+
? args.nativeHistoryResult.workspace
|
|
651
|
+
: nativeMessages.map((m: any) => typeof m?.workspace === 'string' ? m.workspace.trim() : '').find(Boolean);
|
|
652
|
+
|
|
653
|
+
const fallbackReason = causeToLegacyFallbackReason(decision.transition.cause, decision.selected, {
|
|
654
|
+
unavailableReason,
|
|
655
|
+
nativeSource: nativeSource && nativeSource !== 'provider-native' ? nativeSource : undefined,
|
|
656
|
+
});
|
|
657
|
+
|
|
658
|
+
// ptyStatusApprovalOnly: when the machine selected native-history we
|
|
659
|
+
// suppress PTY content so the dashboard does not double-show messages
|
|
660
|
+
// already in the native transcript. When the machine selected
|
|
661
|
+
// pty-parser, PTY is the authoritative source — do NOT suppress it.
|
|
662
|
+
// Callers used to hard-code this to `nativeSelected first = true` which
|
|
663
|
+
// suppressed PTY content even when native was empty/unavailable, leaving
|
|
664
|
+
// the dashboard with zero visible messages (the codex generating/waiting
|
|
665
|
+
// approval stuck state). Trust the machine here, not the caller hint.
|
|
666
|
+
const ptyStatusApprovalOnly = decision.selected === 'native-history'
|
|
667
|
+
? true
|
|
668
|
+
: args.ptyStatusApprovalOnly;
|
|
669
|
+
|
|
670
|
+
const messageSource = buildCliMessageSourceProvenance({
|
|
671
|
+
selected: decision.selected,
|
|
672
|
+
provider: args.providerType,
|
|
673
|
+
nativeHandle,
|
|
674
|
+
sessionWorkspace: args.sessionWorkspace,
|
|
675
|
+
intendedWorkspace: args.intendedWorkspace,
|
|
676
|
+
transcriptWorkspace,
|
|
677
|
+
fallbackReason,
|
|
678
|
+
nativeSource,
|
|
679
|
+
sourcePath,
|
|
680
|
+
sourceMtimeMs,
|
|
681
|
+
nativeHistoryCoverage: coverageHint,
|
|
682
|
+
partialReason,
|
|
683
|
+
unavailableReason,
|
|
684
|
+
nativeMessages,
|
|
685
|
+
ptyMessages: args.ptyMessages,
|
|
686
|
+
returnedMessages: decision.selected === 'native-history' ? nativeMessages : args.ptyMessages,
|
|
687
|
+
safeMapping: args.safeMapping,
|
|
688
|
+
// freshEnough is a v1 concept the machine does not model directly.
|
|
689
|
+
// We surface lockState.locked here so v1 consumers reading
|
|
690
|
+
// staleness.freshEnough still get a meaningful boolean.
|
|
691
|
+
freshEnough: decision.lockState.locked,
|
|
692
|
+
ptyStatusApprovalOnly,
|
|
693
|
+
});
|
|
694
|
+
|
|
695
|
+
return {
|
|
696
|
+
decision,
|
|
697
|
+
messageSource,
|
|
698
|
+
nativeMessages,
|
|
699
|
+
nativeSelected: decision.selected === 'native-history',
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
function buildObservationForCli(
|
|
704
|
+
args: {
|
|
705
|
+
providerType: string;
|
|
706
|
+
sessionId: string;
|
|
707
|
+
nativeHistoryResult: any | null;
|
|
708
|
+
nativeHistoryError?: unknown;
|
|
709
|
+
safeMapping: boolean;
|
|
710
|
+
},
|
|
711
|
+
supportsNative: boolean,
|
|
712
|
+
): ChatSourceObservation {
|
|
713
|
+
if (!supportsNative) {
|
|
714
|
+
return { kind: 'native_unavailable', reason: 'provider_not_supported' };
|
|
715
|
+
}
|
|
716
|
+
if (args.nativeHistoryError) {
|
|
717
|
+
return { kind: 'native_unavailable', reason: 'read_error' };
|
|
718
|
+
}
|
|
719
|
+
const result = args.nativeHistoryResult;
|
|
720
|
+
if (!result || typeof result !== 'object') {
|
|
721
|
+
return { kind: 'native_unavailable', reason: 'read_error' };
|
|
722
|
+
}
|
|
723
|
+
const source = typeof result.source === 'string' ? result.source : '';
|
|
724
|
+
if (source && source !== 'provider-native') {
|
|
725
|
+
// 'native-unavailable' or other producer-side declined source.
|
|
726
|
+
return { kind: 'native_unavailable', reason: source === 'native-unavailable' ? 'empty' : 'not_native_source' };
|
|
727
|
+
}
|
|
728
|
+
const messages = Array.isArray(result.messages) ? result.messages : [];
|
|
729
|
+
if (messages.length === 0) {
|
|
730
|
+
return { kind: 'native_unavailable', reason: 'empty' };
|
|
731
|
+
}
|
|
732
|
+
const coverage = typeof result.nativeHistoryCoverage === 'string'
|
|
733
|
+
? result.nativeHistoryCoverage
|
|
734
|
+
: 'tail';
|
|
735
|
+
if (coverage === 'unavailable') {
|
|
736
|
+
return { kind: 'native_unavailable', reason: 'coverage_unavailable' };
|
|
737
|
+
}
|
|
738
|
+
return buildV1NativePresentObservation({
|
|
739
|
+
providerType: args.providerType,
|
|
740
|
+
sessionId: args.sessionId,
|
|
741
|
+
messages,
|
|
742
|
+
coverage: coverage === 'full' || coverage === 'tail' || coverage === 'current-turn' || coverage === 'partial'
|
|
743
|
+
? coverage
|
|
744
|
+
: 'tail',
|
|
745
|
+
safeMapping: args.safeMapping,
|
|
746
|
+
});
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
function extractNativeMessagesFromResult(providerType: string, result: any): ChatMessage[] {
|
|
750
|
+
if (!result || !Array.isArray(result.messages)) return [];
|
|
751
|
+
return normalizeNativeHistoryMessages(
|
|
752
|
+
providerType,
|
|
753
|
+
result.messages as ChatMessage[],
|
|
754
|
+
typeof result.providerSessionId === 'string' ? result.providerSessionId : undefined,
|
|
755
|
+
);
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/**
|
|
759
|
+
* ptyStatusApprovalOnly is true when the daemon should treat PTY content as
|
|
760
|
+
* status/approval signal only (not as chat messages). v1 set this to `true`
|
|
761
|
+
* whenever native-history was selected as the source, and `false` otherwise.
|
|
762
|
+
* The machine equivalent: when native is the source we want PTY suppressed.
|
|
763
|
+
*/
|
|
764
|
+
function primaryPtyApprovalOnlyFor(_cliType: string, nativeSelected: boolean): boolean {
|
|
765
|
+
return nativeSelected;
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
/**
|
|
769
|
+
* Codex-only unsafe-native fallback: when the primary native fetch produced
|
|
770
|
+
* unsafe-mapping data, v1 attempted to recover by reading exact runtime
|
|
771
|
+
* mirror messages, runtime input ACK messages, or by trusting the current-
|
|
772
|
+
* runtime PTY when safely attributed. None of this is the machine's
|
|
773
|
+
* responsibility — the machine already decided pty-parser. This helper
|
|
774
|
+
* preserves the daemon-side message selection and annotates messageSource.
|
|
775
|
+
*/
|
|
776
|
+
function applyUnsafeNativeDaemonFallback(args: {
|
|
777
|
+
providerType: string;
|
|
778
|
+
adapter: CliAdapter;
|
|
779
|
+
helpers: CommandHelpers;
|
|
780
|
+
readChatArgs: any;
|
|
781
|
+
sessionWorkspace?: string;
|
|
782
|
+
intendedWorkspace?: string;
|
|
783
|
+
ptyMessages: ChatMessage[];
|
|
784
|
+
nativeHistoryLimit: number;
|
|
785
|
+
provider?: ProviderModule;
|
|
786
|
+
messageSourceRef: { set(value: Record<string, unknown>): void; get(): Record<string, unknown> };
|
|
787
|
+
apply(selection: {
|
|
788
|
+
messages: ChatMessage[];
|
|
789
|
+
transcriptAuthority?: 'provider' | 'daemon';
|
|
790
|
+
coverage?: 'full' | 'tail' | 'current-turn';
|
|
791
|
+
status?: string;
|
|
792
|
+
}): void;
|
|
793
|
+
activeModal: unknown;
|
|
794
|
+
returnedStatus: string;
|
|
795
|
+
coverage?: 'full' | 'tail' | 'current-turn';
|
|
796
|
+
}): void {
|
|
797
|
+
if (args.adapter.cliType !== 'codex-cli') {
|
|
798
|
+
// Only codex-cli had v1 daemon mirror recovery. Other providers skip.
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
801
|
+
const ms = args.messageSourceRef.get();
|
|
802
|
+
const fallbackReason = typeof ms.fallbackReason === 'string' ? ms.fallbackReason : '';
|
|
803
|
+
if (!isUnsafeNativeTranscriptFallback(fallbackReason)) {
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
const safeCurrentRuntimePtyMessages = isCurrentRuntimePtySafelyAttributed({
|
|
807
|
+
adapter: args.adapter,
|
|
808
|
+
helpers: args.helpers,
|
|
809
|
+
readChatArgs: args.readChatArgs,
|
|
810
|
+
sessionWorkspace: args.sessionWorkspace,
|
|
811
|
+
intendedWorkspace: args.intendedWorkspace,
|
|
812
|
+
ptyMessages: args.ptyMessages,
|
|
813
|
+
});
|
|
814
|
+
if (safeCurrentRuntimePtyMessages) {
|
|
815
|
+
args.apply({
|
|
816
|
+
messages: args.ptyMessages,
|
|
817
|
+
transcriptAuthority: 'daemon',
|
|
818
|
+
coverage: args.coverage || 'current-turn',
|
|
819
|
+
status: args.returnedStatus,
|
|
820
|
+
});
|
|
821
|
+
const next = { ...ms, selectedDaemonSource: 'current-runtime-pty', transcriptAuthority: 'daemon', runtimeMappingSafe: true };
|
|
822
|
+
args.messageSourceRef.set(next);
|
|
823
|
+
return;
|
|
824
|
+
}
|
|
825
|
+
const safeRuntimeAckMessages = selectRuntimeInputAckMessages(args.ptyMessages);
|
|
826
|
+
if (safeRuntimeAckMessages.length > 0) {
|
|
827
|
+
args.apply({
|
|
828
|
+
messages: safeRuntimeAckMessages,
|
|
829
|
+
transcriptAuthority: 'daemon',
|
|
830
|
+
coverage: 'tail',
|
|
831
|
+
status: coerceUnsafeNativeFallbackStatus(args.returnedStatus, args.activeModal),
|
|
832
|
+
});
|
|
833
|
+
const next = { ...ms, ptyStatusApprovalOnly: true };
|
|
834
|
+
args.messageSourceRef.set(next);
|
|
835
|
+
return;
|
|
836
|
+
}
|
|
837
|
+
const exactRuntimeMirrorMessages = readExactRuntimeMirrorMessages({
|
|
838
|
+
providerType: args.providerType,
|
|
839
|
+
targetSessionId: typeof args.readChatArgs?.targetSessionId === 'string' ? args.readChatArgs.targetSessionId : undefined,
|
|
840
|
+
currentSessionId: typeof (args.helpers.currentSession as any)?.sessionId === 'string' ? (args.helpers.currentSession as any).sessionId : undefined,
|
|
841
|
+
tailLimit: args.nativeHistoryLimit,
|
|
842
|
+
historyBehavior: args.provider?.historyBehavior,
|
|
843
|
+
});
|
|
844
|
+
if (exactRuntimeMirrorMessages.length > 0) {
|
|
845
|
+
args.apply({
|
|
846
|
+
messages: exactRuntimeMirrorMessages,
|
|
847
|
+
transcriptAuthority: 'daemon',
|
|
848
|
+
coverage: 'tail',
|
|
849
|
+
status: coerceUnsafeNativeFallbackStatus(args.returnedStatus, args.activeModal),
|
|
850
|
+
});
|
|
851
|
+
const next = { ...ms, selectedDaemonSource: 'exact-runtime-mirror', transcriptAuthority: 'daemon', ptyStatusApprovalOnly: true };
|
|
852
|
+
args.messageSourceRef.set(next);
|
|
853
|
+
return;
|
|
854
|
+
}
|
|
855
|
+
// No daemon mirror available — keep PTY messages as-is (still pty-parser
|
|
856
|
+
// selection); just coerce status for waiting_approval consistency.
|
|
857
|
+
args.apply({
|
|
858
|
+
messages: args.ptyMessages,
|
|
859
|
+
coverage: args.coverage,
|
|
860
|
+
status: coerceUnsafeNativeFallbackStatus(args.returnedStatus, args.activeModal),
|
|
861
|
+
});
|
|
862
|
+
const next = { ...ms, ptyStatusApprovalOnly: true };
|
|
863
|
+
args.messageSourceRef.set(next);
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
// (A2.2) buildNativeHistoryFallbackReason removed. ChatSourceMachine emits a
|
|
867
|
+
// ChatSourceTransitionCause; causeToLegacyFallbackReason maps it back to the
|
|
868
|
+
// v1 vocabulary for response compatibility. A3 deletes the v1 vocabulary
|
|
869
|
+
// entirely and surfaces stateTransition/lockState directly.
|
|
870
|
+
|
|
871
|
+
function isUnsafeNativeTranscriptFallback(reason?: string): boolean {
|
|
872
|
+
const value = String(reason || '').trim();
|
|
873
|
+
return value.startsWith('native_history_unavailable')
|
|
874
|
+
|| value === 'native_history_not_safely_mapped'
|
|
875
|
+
|| value === 'native_history_stale'
|
|
876
|
+
|| value === 'native_history_partial';
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
function coerceUnsafeNativeFallbackStatus(status: string, activeModal: unknown): string {
|
|
880
|
+
if (status === 'waiting_approval' && activeModal) return status;
|
|
881
|
+
return 'idle';
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
function isRuntimeInputAckMessage(message: ChatMessage | undefined): boolean {
|
|
885
|
+
if (!message || typeof message !== 'object') return false;
|
|
886
|
+
const role = String((message as any).role || '').trim().toLowerCase();
|
|
887
|
+
if (role !== 'user' && role !== 'human') return false;
|
|
888
|
+
const meta = (message as any).meta;
|
|
889
|
+
return !!meta && typeof meta === 'object' && !Array.isArray(meta) && meta.runtimeInputAck === true;
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
function selectRuntimeInputAckMessages(messages: ChatMessage[]): ChatMessage[] {
|
|
893
|
+
return messages.filter((message) => isRuntimeInputAckMessage(message));
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
function readExactRuntimeMirrorMessages(args: {
|
|
897
|
+
providerType: string;
|
|
898
|
+
targetSessionId?: string;
|
|
899
|
+
currentSessionId?: string;
|
|
900
|
+
tailLimit: number;
|
|
901
|
+
historyBehavior?: ProviderModule['historyBehavior'];
|
|
902
|
+
}): ChatMessage[] {
|
|
903
|
+
const targetSessionId = String(args.targetSessionId || '').trim();
|
|
904
|
+
const currentSessionId = String(args.currentSessionId || '').trim();
|
|
905
|
+
if (!targetSessionId || targetSessionId !== currentSessionId) return [];
|
|
906
|
+
|
|
907
|
+
const history = readChatHistory(
|
|
908
|
+
args.providerType,
|
|
909
|
+
0,
|
|
910
|
+
Math.max(args.tailLimit || 0, 200),
|
|
911
|
+
targetSessionId,
|
|
912
|
+
0,
|
|
913
|
+
args.historyBehavior,
|
|
914
|
+
);
|
|
915
|
+
return normalizeChatMessages((history.messages || []) as ChatMessage[])
|
|
916
|
+
.filter((message) => {
|
|
917
|
+
const historySessionId = String((message as any).historySessionId || '').trim();
|
|
918
|
+
const instanceId = String((message as any).instanceId || '').trim();
|
|
919
|
+
return historySessionId === targetSessionId || instanceId === targetSessionId;
|
|
920
|
+
});
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
function normalizeComparableWorkspace(value: unknown): string {
|
|
924
|
+
const text = typeof value === 'string' ? value.trim() : '';
|
|
925
|
+
if (!text) return '';
|
|
926
|
+
return path.resolve(text);
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
function isCurrentRuntimePtySafelyAttributed(args: {
|
|
930
|
+
adapter: CliAdapter;
|
|
931
|
+
helpers: CommandHelpers;
|
|
932
|
+
readChatArgs: any;
|
|
933
|
+
sessionWorkspace?: string;
|
|
934
|
+
intendedWorkspace?: string;
|
|
935
|
+
ptyMessages: ChatMessage[];
|
|
936
|
+
}): boolean {
|
|
937
|
+
if (args.adapter.cliType !== 'codex-cli') return false;
|
|
938
|
+
if (!Array.isArray(args.ptyMessages) || args.ptyMessages.length === 0) return false;
|
|
939
|
+
const targetSessionId = typeof args.readChatArgs?.targetSessionId === 'string'
|
|
940
|
+
? args.readChatArgs.targetSessionId.trim()
|
|
941
|
+
: '';
|
|
942
|
+
const currentSession = args.helpers.currentSession as any;
|
|
943
|
+
const currentSessionId = typeof currentSession?.sessionId === 'string'
|
|
944
|
+
? currentSession.sessionId.trim()
|
|
945
|
+
: '';
|
|
946
|
+
if (!targetSessionId || !currentSessionId || targetSessionId !== currentSessionId) return false;
|
|
947
|
+
|
|
948
|
+
const runtimeMeta = typeof (args.adapter as any).getRuntimeMetadata === 'function'
|
|
949
|
+
? (args.adapter as any).getRuntimeMetadata()
|
|
950
|
+
: null;
|
|
951
|
+
const runtimeId = typeof runtimeMeta?.runtimeId === 'string' ? runtimeMeta.runtimeId.trim() : '';
|
|
952
|
+
if (!runtimeId || runtimeId !== targetSessionId) return false;
|
|
953
|
+
const surfaceKind = typeof runtimeMeta?.surfaceKind === 'string' ? runtimeMeta.surfaceKind : '';
|
|
954
|
+
if (surfaceKind === 'inactive_record' || surfaceKind === 'recovery_snapshot') return false;
|
|
955
|
+
|
|
956
|
+
const sessionWorkspace = normalizeComparableWorkspace(args.sessionWorkspace);
|
|
957
|
+
const adapterWorkspace = normalizeComparableWorkspace(args.adapter.workingDir);
|
|
958
|
+
if (!sessionWorkspace || !adapterWorkspace || sessionWorkspace !== adapterWorkspace) return false;
|
|
959
|
+
const intendedWorkspace = normalizeComparableWorkspace(args.intendedWorkspace);
|
|
960
|
+
if (intendedWorkspace && intendedWorkspace !== sessionWorkspace) return false;
|
|
961
|
+
|
|
962
|
+
const registryEntry = args.helpers.ctx?.sessionRegistry?.get?.(targetSessionId) as any;
|
|
963
|
+
const registryInstanceKey = typeof registryEntry?.adapterKey === 'string' && registryEntry.adapterKey.trim()
|
|
964
|
+
? registryEntry.adapterKey.trim()
|
|
965
|
+
: typeof registryEntry?.instanceKey === 'string' && registryEntry.instanceKey.trim()
|
|
966
|
+
? registryEntry.instanceKey.trim()
|
|
967
|
+
: '';
|
|
968
|
+
if (registryInstanceKey) {
|
|
969
|
+
const targetInstance = args.helpers.ctx?.instanceManager?.getInstance?.(registryInstanceKey);
|
|
970
|
+
if (targetInstance) {
|
|
971
|
+
const instanceType = typeof (targetInstance as any).type === 'string' ? (targetInstance as any).type : '';
|
|
972
|
+
if (instanceType && instanceType !== args.adapter.cliType) return false;
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
return true;
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
function supportsCliNativeTranscript(providerType: string, provider?: ProviderModule): boolean {
|
|
980
|
+
// Preferred path: the provider module declares canonicalHistory in its
|
|
981
|
+
// provider.json. We trust that declaration regardless of the legacy
|
|
982
|
+
// allow-list. A2 will additionally require canonicalHistory.contractVersion
|
|
983
|
+
// to be a supported value (transcript-v2.ts).
|
|
984
|
+
if (provider?.category === 'cli' && isNativeSourceCanonicalHistory(provider?.nativeHistory)) {
|
|
985
|
+
return true;
|
|
986
|
+
}
|
|
987
|
+
// Last-resort fallback for early call sites where the provider module is
|
|
988
|
+
// not yet loaded. Warn once per provider type so this dependency is visible
|
|
989
|
+
// and can be removed in A2.
|
|
990
|
+
if (CLI_NATIVE_TRANSCRIPT_PROVIDERS.has(providerType)) {
|
|
991
|
+
warnLegacyNativeAllowlistHit(providerType);
|
|
992
|
+
return true;
|
|
993
|
+
}
|
|
994
|
+
return false;
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
function getComparableVisibleText(message: ChatMessage | undefined): string {
|
|
998
|
+
if (!message) return '';
|
|
999
|
+
const role = String((message as any).role || '').trim().toLowerCase();
|
|
1000
|
+
if (role !== 'user' && role !== 'assistant') return '';
|
|
1001
|
+
const kind = String((message as any).kind || 'standard').trim().toLowerCase();
|
|
1002
|
+
if (kind && kind !== 'standard') return '';
|
|
1003
|
+
const content = flattenContent((message as any).content).replace(/\s+/g, ' ').trim();
|
|
1004
|
+
return content;
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
function hasOverlappingVisibleConversationText(nativeMessages: ChatMessage[], ptyMessages: ChatMessage[]): boolean {
|
|
1008
|
+
const nativeTexts = nativeMessages.map(getComparableVisibleText).filter(Boolean);
|
|
1009
|
+
const ptyTexts = ptyMessages.map(getComparableVisibleText).filter(Boolean);
|
|
1010
|
+
if (nativeTexts.length === 0 || ptyTexts.length === 0) return false;
|
|
1011
|
+
for (const nativeText of nativeTexts) {
|
|
1012
|
+
for (const ptyText of ptyTexts) {
|
|
1013
|
+
if (nativeText === ptyText) return true;
|
|
1014
|
+
const shorter = nativeText.length <= ptyText.length ? nativeText : ptyText;
|
|
1015
|
+
const longer = nativeText.length <= ptyText.length ? ptyText : nativeText;
|
|
1016
|
+
if (shorter.length >= 32 && longer.includes(shorter)) return true;
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
return false;
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
function hasSafeNativeHistoryMapping(args: {
|
|
1023
|
+
historySessionId?: string;
|
|
1024
|
+
providerSessionId?: string;
|
|
1025
|
+
workspace?: string;
|
|
1026
|
+
nativeMessages: ChatMessage[];
|
|
1027
|
+
ptyMessages?: ChatMessage[];
|
|
1028
|
+
requireWorkspaceContentOverlap?: boolean;
|
|
1029
|
+
}): boolean {
|
|
1030
|
+
const isCoordinatorTranscript = args.nativeMessages.some((m: any) => {
|
|
1031
|
+
const text = typeof m?.content === 'string' ? m.content : JSON.stringify(m?.content || '');
|
|
1032
|
+
return text.includes('mesh_send_task') || text.includes('mesh_status') || text.includes('mesh_read_chat') || text.includes('mesh_launch_session');
|
|
1033
|
+
});
|
|
1034
|
+
|
|
1035
|
+
const explicitSessionId = String(args.historySessionId || args.providerSessionId || '').trim();
|
|
1036
|
+
if (explicitSessionId) {
|
|
1037
|
+
const messageSessionIds = args.nativeMessages
|
|
1038
|
+
.map((message: any) => typeof message?.historySessionId === 'string' ? message.historySessionId.trim() : '')
|
|
1039
|
+
.filter(Boolean);
|
|
1040
|
+
if (messageSessionIds.length > 0) {
|
|
1041
|
+
return messageSessionIds.some((id) => id === explicitSessionId);
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
// Messages carry no historySessionId — cannot confirm they belong to the requested session.
|
|
1045
|
+
// Only allow a coordinator transcript that is also confirmed by the PTY side; otherwise
|
|
1046
|
+
// fail closed so a same-workspace session's history is never silently accepted.
|
|
1047
|
+
if (isCoordinatorTranscript && args.ptyMessages && args.ptyMessages.length > 0) {
|
|
1048
|
+
const ptyHasCoordinator = args.ptyMessages.some((m: any) => {
|
|
1049
|
+
const text = typeof m?.content === 'string' ? m.content : JSON.stringify(m?.content || '');
|
|
1050
|
+
return text.includes('mesh_send_task') || text.includes('mesh_status') || text.includes('mesh_read_chat');
|
|
1051
|
+
});
|
|
1052
|
+
return ptyHasCoordinator;
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
// No historySessionId in messages and no coordinator cross-check: fail closed.
|
|
1056
|
+
// Workspace-only matching must not override an explicit session identity.
|
|
1057
|
+
return false;
|
|
1058
|
+
}
|
|
1059
|
+
const workspace = String(args.workspace || '').trim();
|
|
1060
|
+
if (!workspace) return false;
|
|
1061
|
+
const workspaceMatches = args.nativeMessages.some((message: any) => String(message?.workspace || '').trim() === workspace);
|
|
1062
|
+
if (!workspaceMatches) return false;
|
|
1063
|
+
|
|
1064
|
+
if (isCoordinatorTranscript && args.ptyMessages && args.ptyMessages.length > 0) {
|
|
1065
|
+
const ptyHasCoordinator = args.ptyMessages.some((m: any) => {
|
|
1066
|
+
const text = typeof m?.content === 'string' ? m.content : JSON.stringify(m?.content || '');
|
|
1067
|
+
return text.includes('mesh_send_task') || text.includes('mesh_status') || text.includes('mesh_read_chat');
|
|
1068
|
+
});
|
|
1069
|
+
if (!ptyHasCoordinator) {
|
|
1070
|
+
return false;
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
if (!args.requireWorkspaceContentOverlap) return true;
|
|
1075
|
+
return hasOverlappingVisibleConversationText(args.nativeMessages, args.ptyMessages || []);
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
// Provenance boundary: workspace-only native history lookup is never safe
|
|
1079
|
+
// because multiple concurrent sessions sharing the same cwd would alias each
|
|
1080
|
+
// other. historySessionId (the provider-native session key) is required to
|
|
1081
|
+
// establish ownership. hasSafeNativeHistoryMapping() enforces the same
|
|
1082
|
+
// invariant after the read; both guards must hold for native history to be used.
|
|
1083
|
+
/**
|
|
1084
|
+
* Pull the session's spawnedAtMs out of the registry. Native-history
|
|
1085
|
+
* file pickers use it as a "files older than this can't be from this
|
|
1086
|
+
* session" floor; without it a fresh dashboard view would inherit the
|
|
1087
|
+
* previous session's transcript whenever its file happened to be the
|
|
1088
|
+
* newest match. Returns undefined when the session isn't registered
|
|
1089
|
+
* (e.g. read_chat before the live session was wired up) — the executor
|
|
1090
|
+
* treats undefined as "no floor".
|
|
1091
|
+
*/
|
|
1092
|
+
function sessionStartedAtMsFromRegistry(h: CommandHelpers, targetSessionId: string | undefined): number | undefined {
|
|
1093
|
+
const sid = typeof targetSessionId === 'string' ? targetSessionId.trim() : '';
|
|
1094
|
+
if (!sid) return undefined;
|
|
1095
|
+
const target = h.ctx?.sessionRegistry?.get?.(sid);
|
|
1096
|
+
return typeof target?.spawnedAtMs === 'number' ? target.spawnedAtMs : undefined;
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
/**
|
|
1100
|
+
* Pull the env vars the daemon set when it spawned this session's CLI.
|
|
1101
|
+
* Mesh coordinator points hermes at a per-coordinator HERMES_HOME so
|
|
1102
|
+
* the native-history reader needs that override to find the right
|
|
1103
|
+
* state.db; without it the reader sees ~/.hermes/state.db and misses
|
|
1104
|
+
* every coordinator-session transcript.
|
|
1105
|
+
*
|
|
1106
|
+
* Returns undefined when no SpecCliAdapter is in play (legacy
|
|
1107
|
+
* providers / CDP) or when the adapter exposes no spawn env.
|
|
1108
|
+
*/
|
|
1109
|
+
function sessionSpawnEnvFromAdapter(h: CommandHelpers, targetSessionId: string | undefined): Record<string, string> | undefined {
|
|
1110
|
+
const adapter = getTargetedCliAdapter(h, { targetSessionId }, undefined);
|
|
1111
|
+
if (!adapter || typeof adapter.getRuntimeMetadata !== 'function') return undefined;
|
|
1112
|
+
const meta = adapter.getRuntimeMetadata() as Record<string, unknown> | undefined;
|
|
1113
|
+
const env = meta && typeof meta === 'object' ? (meta as Record<string, unknown>).spawnedEnv : undefined;
|
|
1114
|
+
return env && typeof env === 'object' ? env as Record<string, string> : undefined;
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
|
|
1118
|
+
function readCliProviderNativeHistory(agentStr: string, args: {
|
|
1119
|
+
canonicalHistory?: ProviderModule['canonicalHistory'];
|
|
1120
|
+
historySessionId?: string;
|
|
1121
|
+
workspace?: string;
|
|
1122
|
+
offset: number;
|
|
1123
|
+
limit: number;
|
|
1124
|
+
excludeRecentCount: number;
|
|
1125
|
+
historyBehavior?: ProviderModule['historyBehavior'];
|
|
1126
|
+
scripts?: ProviderScripts;
|
|
1127
|
+
excludeInProgressTurn?: boolean;
|
|
1128
|
+
sessionStartedAtMs?: number;
|
|
1129
|
+
envOverrides?: Record<string, string>;
|
|
1130
|
+
}): ReturnType<typeof readProviderChatHistory> & { lookup: 'session' | 'workspace' } {
|
|
1131
|
+
if (!args.historySessionId) {
|
|
1132
|
+
return {
|
|
1133
|
+
messages: [],
|
|
1134
|
+
hasMore: false,
|
|
1135
|
+
source: 'native-unavailable',
|
|
1136
|
+
unavailableReason: 'native_history_workspace_only_lookup_unsafe',
|
|
1137
|
+
lookup: 'session',
|
|
1138
|
+
} as ReturnType<typeof readProviderChatHistory> & { lookup: 'session' | 'workspace' };
|
|
1139
|
+
}
|
|
1140
|
+
const sessionHistory = readProviderChatHistory(agentStr, {
|
|
1141
|
+
canonicalHistory: args.canonicalHistory,
|
|
1142
|
+
historySessionId: args.historySessionId,
|
|
1143
|
+
workspace: args.workspace,
|
|
1144
|
+
offset: args.offset,
|
|
1145
|
+
limit: args.limit,
|
|
1146
|
+
excludeRecentCount: args.excludeRecentCount,
|
|
1147
|
+
historyBehavior: args.historyBehavior,
|
|
1148
|
+
scripts: args.scripts as any,
|
|
1149
|
+
excludeInProgressTurn: args.excludeInProgressTurn,
|
|
1150
|
+
sessionStartedAtMs: args.sessionStartedAtMs,
|
|
1151
|
+
envOverrides: args.envOverrides,
|
|
1152
|
+
});
|
|
1153
|
+
// Native transcripts are keyed by provider/runtime session identity. Falling
|
|
1154
|
+
// back to workspace makes concurrent local Codex/Hermes sessions alias each
|
|
1155
|
+
// other when they share the same cwd.
|
|
1156
|
+
return { ...(sessionHistory as any), lookup: 'session' };
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1159
|
+
function readLiveCodexWorkspaceNativeHistory(agentStr: string, args: {
|
|
1160
|
+
canonicalHistory?: ProviderModule['canonicalHistory'];
|
|
1161
|
+
workspace?: string;
|
|
1162
|
+
offset: number;
|
|
1163
|
+
limit: number;
|
|
1164
|
+
excludeRecentCount: number;
|
|
1165
|
+
historyBehavior?: ProviderModule['historyBehavior'];
|
|
1166
|
+
scripts?: ProviderScripts;
|
|
1167
|
+
}): (ReturnType<typeof readProviderChatHistory> & { lookup: 'workspace' }) | null {
|
|
1168
|
+
if (agentStr !== 'codex-cli') return null;
|
|
1169
|
+
const workspace = typeof args.workspace === 'string' ? args.workspace.trim() : '';
|
|
1170
|
+
if (!workspace) return null;
|
|
1171
|
+
const history = readProviderChatHistory(agentStr, {
|
|
1172
|
+
canonicalHistory: args.canonicalHistory,
|
|
1173
|
+
workspace,
|
|
1174
|
+
offset: args.offset,
|
|
1175
|
+
limit: args.limit,
|
|
1176
|
+
excludeRecentCount: args.excludeRecentCount,
|
|
1177
|
+
historyBehavior: args.historyBehavior,
|
|
1178
|
+
scripts: args.scripts as any,
|
|
1179
|
+
});
|
|
1180
|
+
return { ...(history as any), lookup: 'workspace' };
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
// (A2.2) isNativeHistoryFreshEnough removed. The v1 freshness comparison
|
|
1184
|
+
// (native_newest vs pty_newest with a 5-minute mtime grace window) was the
|
|
1185
|
+
// direct cause of the plipping behaviour: PTY arrived every turn so native
|
|
1186
|
+
// looked stale by default. ChatSourceMachine never compares native vs PTY
|
|
1187
|
+
// freshness — the lock holds across arbitrary PTY arrival. See
|
|
1188
|
+
// chat/source-machine.ts for the new semantics.
|
|
1189
|
+
|
|
1190
|
+
function shouldPreserveReadChatPayloadField(key: string): boolean {
|
|
1191
|
+
return key === 'messageSource' || key === 'transcriptProvenance';
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
function updateMessageSourceReturnedCount(value: unknown, returnedMessageCount: number): unknown {
|
|
1195
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return value;
|
|
1196
|
+
const record = value as Record<string, unknown>;
|
|
1197
|
+
const coverage = record.coverage && typeof record.coverage === 'object' && !Array.isArray(record.coverage)
|
|
1198
|
+
? record.coverage as Record<string, unknown>
|
|
1199
|
+
: undefined;
|
|
1200
|
+
if (!coverage) return value;
|
|
1201
|
+
return {
|
|
1202
|
+
...record,
|
|
1203
|
+
coverage: {
|
|
1204
|
+
...coverage,
|
|
1205
|
+
returnedMessageCount,
|
|
1206
|
+
},
|
|
1207
|
+
};
|
|
1208
|
+
}
|
|
224
1209
|
|
|
225
1210
|
function deriveHistoryDedupKey(message: ChatMessage & { _unitKey?: string; _turnKey?: string }): string | undefined {
|
|
226
1211
|
const unitKey = typeof message._unitKey === 'string' ? message._unitKey.trim() : '';
|
|
@@ -281,11 +1266,20 @@ function normalizeReadChatCommandStatus(status: unknown, activeModal: unknown):
|
|
|
281
1266
|
}
|
|
282
1267
|
switch (raw) {
|
|
283
1268
|
case 'starting':
|
|
284
|
-
return hasNonEmptyModalButtons(activeModal) ? 'waiting_approval' : '
|
|
1269
|
+
return hasNonEmptyModalButtons(activeModal) ? 'waiting_approval' : 'starting';
|
|
285
1270
|
case 'stopped':
|
|
286
1271
|
case 'disconnected':
|
|
287
1272
|
case 'not_monitored':
|
|
288
1273
|
return 'error';
|
|
1274
|
+
case 'waiting_approval':
|
|
1275
|
+
// The contract validator requires activeModal+buttons whenever
|
|
1276
|
+
// status is waiting_approval. If a producer/coercer set this
|
|
1277
|
+
// status without staging the modal yet (a race we hit with
|
|
1278
|
+
// codex-cli during tool approval setup), downgrade to a
|
|
1279
|
+
// generating-like status so readChat still returns successfully.
|
|
1280
|
+
// The next poll will pick up the modal once the provider has
|
|
1281
|
+
// emitted it.
|
|
1282
|
+
return hasNonEmptyModalButtons(activeModal) ? 'waiting_approval' : 'generating';
|
|
289
1283
|
default:
|
|
290
1284
|
return raw;
|
|
291
1285
|
}
|
|
@@ -295,6 +1289,16 @@ function isGeneratingLikeStatus(status: unknown): boolean {
|
|
|
295
1289
|
return status === 'generating' || status === 'streaming' || status === 'long_generating' || status === 'starting';
|
|
296
1290
|
}
|
|
297
1291
|
|
|
1292
|
+
function hasVisibleAssistantMessage(messages: unknown[] | undefined): boolean {
|
|
1293
|
+
if (!Array.isArray(messages)) return false;
|
|
1294
|
+
return messages.some((message: any) => {
|
|
1295
|
+
if (!message || message.role !== 'assistant') return false;
|
|
1296
|
+
const kind = typeof message.kind === 'string' ? message.kind : 'standard';
|
|
1297
|
+
if (kind !== 'standard') return false;
|
|
1298
|
+
return String(message.content || '').trim().length > 0;
|
|
1299
|
+
});
|
|
1300
|
+
}
|
|
1301
|
+
|
|
298
1302
|
function shouldTrustCliAdapterTerminalStatus(parsedStatus: unknown, activeModal: unknown, adapter: CliAdapter, adapterStatus: any): boolean {
|
|
299
1303
|
if (!isGeneratingLikeStatus(parsedStatus)) return false;
|
|
300
1304
|
if (hasNonEmptyModalButtons(activeModal)) return false;
|
|
@@ -304,7 +1308,26 @@ function shouldTrustCliAdapterTerminalStatus(parsedStatus: unknown, activeModal:
|
|
|
304
1308
|
return true;
|
|
305
1309
|
}
|
|
306
1310
|
|
|
307
|
-
function normalizeCliReadChatStatus(parsedStatus: unknown, activeModal: unknown, adapter: CliAdapter, adapterStatus: any): string {
|
|
1311
|
+
function normalizeCliReadChatStatus(parsedStatus: unknown, activeModal: unknown, adapter: CliAdapter, adapterStatus: any, parsedMessages?: unknown[]): string {
|
|
1312
|
+
const adapterRawStatus = typeof adapterStatus?.status === 'string' ? adapterStatus.status.trim() : '';
|
|
1313
|
+
if (adapterRawStatus === 'starting'
|
|
1314
|
+
&& isGeneratingLikeStatus(parsedStatus)
|
|
1315
|
+
&& !hasNonEmptyModalButtons(activeModal)
|
|
1316
|
+
&& Array.isArray(parsedMessages)
|
|
1317
|
+
&& parsedMessages.length === 0
|
|
1318
|
+
&& Array.isArray(adapterStatus?.messages)
|
|
1319
|
+
&& adapterStatus.messages.length === 0
|
|
1320
|
+
&& !(typeof adapter.isProcessing === 'function' && adapter.isProcessing())) {
|
|
1321
|
+
return 'starting';
|
|
1322
|
+
}
|
|
1323
|
+
if (
|
|
1324
|
+
isGeneratingLikeStatus(adapterRawStatus)
|
|
1325
|
+
&& parsedStatus === 'idle'
|
|
1326
|
+
&& !hasNonEmptyModalButtons(activeModal)
|
|
1327
|
+
&& !hasVisibleAssistantMessage(parsedMessages)
|
|
1328
|
+
) {
|
|
1329
|
+
return adapterRawStatus;
|
|
1330
|
+
}
|
|
308
1331
|
if (shouldTrustCliAdapterTerminalStatus(parsedStatus, activeModal, adapter, adapterStatus)) return 'idle';
|
|
309
1332
|
return typeof parsedStatus === 'string' && parsedStatus.trim() ? parsedStatus : 'idle';
|
|
310
1333
|
}
|
|
@@ -325,7 +1348,65 @@ function finalizeStreamingMessagesWhenIdle(messages: ChatMessage[], status: stri
|
|
|
325
1348
|
});
|
|
326
1349
|
}
|
|
327
1350
|
|
|
328
|
-
|
|
1351
|
+
/**
|
|
1352
|
+
* Collapse adjacent PTY messages whose canonical (whitespace-stripped)
|
|
1353
|
+
* content is identical, OR whose turn key + role/kind match.
|
|
1354
|
+
*
|
|
1355
|
+
* The PTY parser of some providers (hermes-cli observed in the wild)
|
|
1356
|
+
* emits the same logical assistant turn twice when the terminal re-wraps
|
|
1357
|
+
* the text at a different column. The two emissions differ in newline
|
|
1358
|
+
* position — and sometimes in a single inserted space next to punctuation
|
|
1359
|
+
* (e.g. `(수정 2개), upstream` vs `(수정 2개 ), upstream`), so a simple
|
|
1360
|
+
* `\s+ -> ' '` normalize cannot collapse them.
|
|
1361
|
+
*
|
|
1362
|
+
* Strategy:
|
|
1363
|
+
* 1. If both messages carry the same _turnKey + role + kind, they are
|
|
1364
|
+
* the same logical turn by construction. Collapse.
|
|
1365
|
+
* 2. Otherwise compare with all whitespace stripped — wrap variants
|
|
1366
|
+
* collapse to identical strings.
|
|
1367
|
+
*
|
|
1368
|
+
* Native-history paths run through pageHistoryRecords and already
|
|
1369
|
+
* collapse on a normalized signature; this helper is the PTY equivalent
|
|
1370
|
+
* the readChat sync path was missing.
|
|
1371
|
+
*/
|
|
1372
|
+
function collapseAdjacentDuplicateChatMessages(messages: ChatMessage[]): ChatMessage[] {
|
|
1373
|
+
if (!Array.isArray(messages) || messages.length <= 1) return messages;
|
|
1374
|
+
const result: ChatMessage[] = [];
|
|
1375
|
+
let prevRoleKind = '';
|
|
1376
|
+
let prevStripped = '';
|
|
1377
|
+
for (const message of messages) {
|
|
1378
|
+
const role = typeof message.role === 'string' ? message.role : '';
|
|
1379
|
+
const kind = typeof message.kind === 'string' ? message.kind : 'standard';
|
|
1380
|
+
const content = typeof message.content === 'string'
|
|
1381
|
+
? message.content
|
|
1382
|
+
: (Array.isArray(message.content) ? message.content.map((p: any) => typeof p?.text === 'string' ? p.text : '').join('') : '');
|
|
1383
|
+
const strippedContent = content.replace(/\s+/g, '');
|
|
1384
|
+
// Empty content or system messages are passed through untouched.
|
|
1385
|
+
if (!strippedContent || role === 'system') {
|
|
1386
|
+
result.push(message);
|
|
1387
|
+
prevRoleKind = '';
|
|
1388
|
+
prevStripped = '';
|
|
1389
|
+
continue;
|
|
1390
|
+
}
|
|
1391
|
+
const roleKind = `${role}:${kind}`;
|
|
1392
|
+
const sameStripped = strippedContent === prevStripped && roleKind === prevRoleKind;
|
|
1393
|
+
if (result.length > 0 && sameStripped) {
|
|
1394
|
+
// Adjacent duplicate after stripping all whitespace. Keep the
|
|
1395
|
+
// *later* copy because PTY's last emission usually has the most
|
|
1396
|
+
// complete formatting.
|
|
1397
|
+
result[result.length - 1] = message;
|
|
1398
|
+
prevRoleKind = roleKind;
|
|
1399
|
+
prevStripped = strippedContent;
|
|
1400
|
+
continue;
|
|
1401
|
+
}
|
|
1402
|
+
result.push(message);
|
|
1403
|
+
prevRoleKind = roleKind;
|
|
1404
|
+
prevStripped = strippedContent;
|
|
1405
|
+
}
|
|
1406
|
+
return result;
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
function buildReadChatCommandResult(payload: Record<string, any>, args: any, h?: CommandHelpers): CommandResult {
|
|
329
1410
|
let validatedPayload: Record<string, any>;
|
|
330
1411
|
const debugReadChat = payload?.debugReadChat && typeof payload.debugReadChat === 'object'
|
|
331
1412
|
? payload.debugReadChat
|
|
@@ -339,9 +1420,32 @@ function buildReadChatCommandResult(payload: Record<string, any>, args: any): Co
|
|
|
339
1420
|
return { success: false, error: error?.message || String(error) };
|
|
340
1421
|
}
|
|
341
1422
|
const messages = normalizeReadChatMessages(validatedPayload);
|
|
342
|
-
|
|
1423
|
+
// Last-mile coordinator-prompt filter. Different read_chat code paths
|
|
1424
|
+
// produce the final messages array (native-history main path, codex
|
|
1425
|
+
// exact-runtime-mirror fallback, daemon-side pty-parser, etc), so
|
|
1426
|
+
// applying it here means we don't have to thread the filter through
|
|
1427
|
+
// every one. Driven by the provider setting `showCoordinatorSystemPrompt`
|
|
1428
|
+
// + the coordinator-registry entry for the target session.
|
|
1429
|
+
const sessionIdHint = typeof args?.targetSessionId === 'string' ? args.targetSessionId
|
|
1430
|
+
: typeof args?.sessionId === 'string' ? args.sessionId
|
|
1431
|
+
: '';
|
|
1432
|
+
const providerHint = typeof args?.cliType === 'string' ? args.cliType
|
|
1433
|
+
: typeof args?.providerType === 'string' ? args.providerType
|
|
1434
|
+
: typeof args?.agentType === 'string' ? args.agentType
|
|
1435
|
+
: '';
|
|
1436
|
+
const filteredMessages = h
|
|
1437
|
+
? maybeHideCoordinatorPromptMessage(h, providerHint, sessionIdHint, messages)
|
|
1438
|
+
: messages;
|
|
1439
|
+
const visibleMessages = filterUserFacingChatMessages(filteredMessages);
|
|
343
1440
|
const sync = buildFullTail(visibleMessages, normalizeReadChatTailLimit(args));
|
|
344
1441
|
const hiddenMsgCount = Math.max(0, messages.length - visibleMessages.length);
|
|
1442
|
+
const preservedPayloadFields = Object.fromEntries(Object.entries(payload).filter(([key]) => shouldPreserveReadChatPayloadField(key)));
|
|
1443
|
+
if (preservedPayloadFields.messageSource) {
|
|
1444
|
+
preservedPayloadFields.messageSource = updateMessageSourceReturnedCount(preservedPayloadFields.messageSource, sync.messages.length);
|
|
1445
|
+
}
|
|
1446
|
+
if (preservedPayloadFields.transcriptProvenance) {
|
|
1447
|
+
preservedPayloadFields.transcriptProvenance = updateMessageSourceReturnedCount(preservedPayloadFields.transcriptProvenance, sync.messages.length);
|
|
1448
|
+
}
|
|
345
1449
|
const returnedDebugReadChat = debugReadChat
|
|
346
1450
|
? {
|
|
347
1451
|
...debugReadChat,
|
|
@@ -356,6 +1460,7 @@ function buildReadChatCommandResult(payload: Record<string, any>, args: any): Co
|
|
|
356
1460
|
return {
|
|
357
1461
|
success: true,
|
|
358
1462
|
...validatedPayload,
|
|
1463
|
+
...preservedPayloadFields,
|
|
359
1464
|
messages: sync.messages,
|
|
360
1465
|
totalMessages: sync.totalMessages,
|
|
361
1466
|
...(returnedDebugReadChat ? { debugReadChat: returnedDebugReadChat } : {}),
|
|
@@ -456,7 +1561,7 @@ function summarizeProviderForDebug(provider: ProviderModule | undefined): Record
|
|
|
456
1561
|
name: provider.name,
|
|
457
1562
|
category: provider.category,
|
|
458
1563
|
version: (provider as any).version,
|
|
459
|
-
canonicalHistory: provider.
|
|
1564
|
+
canonicalHistory: provider.nativeHistory,
|
|
460
1565
|
historyBehavior: provider.historyBehavior,
|
|
461
1566
|
webviewMatchText: provider.webviewMatchText,
|
|
462
1567
|
scriptNames: scripts,
|
|
@@ -584,6 +1689,8 @@ function buildChatDebugBundleSummary(bundle: Record<string, unknown>): Record<st
|
|
|
584
1689
|
adapterStatus: debugReadChat.adapterStatus,
|
|
585
1690
|
parsedStatus: debugReadChat.parsedStatus,
|
|
586
1691
|
returnedStatus: debugReadChat.returnedStatus,
|
|
1692
|
+
selectedMessageSource: debugReadChat.selectedMessageSource,
|
|
1693
|
+
messageSource: debugReadChat.messageSource,
|
|
587
1694
|
parsedMsgCount: debugReadChat.parsedMsgCount,
|
|
588
1695
|
returnedMsgCount: debugReadChat.returnedMsgCount,
|
|
589
1696
|
shouldPreferAdapterMessages: debugReadChat.shouldPreferAdapterMessages,
|
|
@@ -646,11 +1753,20 @@ export async function handleGetChatDebugBundle(h: CommandHelpers, args: any): Pr
|
|
|
646
1753
|
providerSessionId: readResult.providerSessionId,
|
|
647
1754
|
transcriptAuthority: readResult.transcriptAuthority,
|
|
648
1755
|
coverage: readResult.coverage,
|
|
1756
|
+
messageSource: readResult.messageSource,
|
|
1757
|
+
transcriptProvenance: readResult.transcriptProvenance,
|
|
649
1758
|
activeModal: readResult.activeModal,
|
|
650
1759
|
messagesTail: Array.isArray(readResult.messages) ? readResult.messages.slice(-20) : [],
|
|
651
1760
|
debugReadChat: readResult.debugReadChat,
|
|
652
1761
|
}
|
|
653
|
-
: {
|
|
1762
|
+
: {
|
|
1763
|
+
success: false,
|
|
1764
|
+
error: readResult.error,
|
|
1765
|
+
code: readResult.code,
|
|
1766
|
+
messageSource: readResult.messageSource,
|
|
1767
|
+
transcriptProvenance: readResult.transcriptProvenance,
|
|
1768
|
+
debugReadChat: readResult.debugReadChat,
|
|
1769
|
+
};
|
|
654
1770
|
} catch (error: any) {
|
|
655
1771
|
readChat = { success: false, error: error?.message || String(error) };
|
|
656
1772
|
}
|
|
@@ -693,6 +1809,9 @@ export async function handleGetChatDebugBundle(h: CommandHelpers, args: any): Pr
|
|
|
693
1809
|
ready: typeof adapter.isReady === 'function' ? adapter.isReady() : undefined,
|
|
694
1810
|
processing: typeof adapter.isProcessing === 'function' ? adapter.isProcessing() : undefined,
|
|
695
1811
|
debugSnapshot: adapterDebugSnapshot,
|
|
1812
|
+
scriptInvocationTrace: typeof (adapter as any).getScriptInvocationTrace === 'function'
|
|
1813
|
+
? (adapter as any).getScriptInvocationTrace()
|
|
1814
|
+
: undefined,
|
|
696
1815
|
} : null,
|
|
697
1816
|
readChat,
|
|
698
1817
|
frontend: args?.frontendSnapshot && typeof args.frontendSnapshot === 'object' ? args.frontendSnapshot : null,
|
|
@@ -817,16 +1936,58 @@ export async function handleChatHistory(h: CommandHelpers, args: any): Promise<C
|
|
|
817
1936
|
: typeof (h.currentSession as any)?.workspace === 'string'
|
|
818
1937
|
? (h.currentSession as any).workspace
|
|
819
1938
|
: undefined;
|
|
820
|
-
const
|
|
821
|
-
|
|
822
|
-
historySessionId
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
1939
|
+
const exactNativeHistoryScope = Boolean(
|
|
1940
|
+
(typeof args?.targetSessionId === 'string' && args.targetSessionId.trim())
|
|
1941
|
+
|| (typeof args?.historySessionId === 'string' && args.historySessionId.trim())
|
|
1942
|
+
|| (typeof args?.providerSessionId === 'string' && args.providerSessionId.trim())
|
|
1943
|
+
);
|
|
1944
|
+
const result = supportsCliNativeTranscript(agentStr, provider) && isNativeSourceCanonicalHistory(provider?.nativeHistory)
|
|
1945
|
+
? readCliProviderNativeHistory(agentStr, {
|
|
1946
|
+
canonicalHistory: provider?.nativeHistory,
|
|
1947
|
+
historySessionId,
|
|
1948
|
+
workspace,
|
|
1949
|
+
offset: offset || 0,
|
|
1950
|
+
limit: limit || 30,
|
|
1951
|
+
excludeRecentCount,
|
|
1952
|
+
historyBehavior: provider?.historyBehavior,
|
|
1953
|
+
scripts: provider?.scripts as any,
|
|
1954
|
+
sessionStartedAtMs: sessionStartedAtMsFromRegistry(h, args?.targetSessionId),
|
|
1955
|
+
envOverrides: sessionSpawnEnvFromAdapter(h, args?.targetSessionId),
|
|
1956
|
+
})
|
|
1957
|
+
: readProviderChatHistory(agentStr, {
|
|
1958
|
+
canonicalHistory: provider?.nativeHistory,
|
|
1959
|
+
historySessionId,
|
|
1960
|
+
workspace,
|
|
1961
|
+
offset: offset || 0,
|
|
1962
|
+
limit: limit || 30,
|
|
1963
|
+
excludeRecentCount,
|
|
1964
|
+
historyBehavior: provider?.historyBehavior,
|
|
1965
|
+
scripts: provider?.scripts as any,
|
|
1966
|
+
});
|
|
1967
|
+
if (supportsCliNativeTranscript(agentStr, provider) && isNativeSourceCanonicalHistory(provider?.nativeHistory)) {
|
|
1968
|
+
const lookup = (result as any).lookup === 'workspace' ? 'workspace' : 'session';
|
|
1969
|
+
const messages = Array.isArray((result as any).messages)
|
|
1970
|
+
? normalizeAndFilterNativeHistory(h, agentStr, args, (result as any).messages as ChatMessage[], (result as any)?.providerSessionId)
|
|
1971
|
+
: [];
|
|
1972
|
+
const historyProviderSessionId = typeof (result as any)?.providerSessionId === 'string'
|
|
1973
|
+
? (result as any).providerSessionId
|
|
1974
|
+
: readHistorySessionIdFromMessages(messages) || historySessionId;
|
|
1975
|
+
const safeMapping = hasSafeNativeHistoryMapping({
|
|
1976
|
+
historySessionId: lookup === 'workspace' ? undefined : historySessionId,
|
|
1977
|
+
providerSessionId: lookup === 'workspace' ? undefined : historyProviderSessionId,
|
|
1978
|
+
workspace,
|
|
1979
|
+
nativeMessages: messages,
|
|
1980
|
+
});
|
|
1981
|
+
if ((result as any).source === 'provider-native' && messages.length > 0 && !safeMapping) {
|
|
1982
|
+
return {
|
|
1983
|
+
success: true,
|
|
1984
|
+
messages: [],
|
|
1985
|
+
hasMore: false,
|
|
1986
|
+
source: 'native-unavailable',
|
|
1987
|
+
agent: agentStr,
|
|
1988
|
+
};
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
830
1991
|
return { success: true, ...result, agent: agentStr };
|
|
831
1992
|
} catch (e: any) {
|
|
832
1993
|
return { success: false, error: e.message };
|
|
@@ -834,7 +1995,25 @@ export async function handleChatHistory(h: CommandHelpers, args: any): Promise<C
|
|
|
834
1995
|
}
|
|
835
1996
|
|
|
836
1997
|
export async function handleReadChat(h: CommandHelpers, args: any): Promise<CommandResult> {
|
|
837
|
-
|
|
1998
|
+
// Resolve provider in order: explicit agentType/providerType > registered session.
|
|
1999
|
+
// Without this fallback, callers that only have a sessionId (e.g. a chat tail
|
|
2000
|
+
// controller that just got handed a session ID over WS) get an empty result
|
|
2001
|
+
// because getProvider(undefined) returns undefined and the rest of the pipeline
|
|
2002
|
+
// bails. This makes the UI look like the session "disappeared".
|
|
2003
|
+
let providerHint: string | undefined = args?.agentType || args?.providerType;
|
|
2004
|
+
if (!providerHint) {
|
|
2005
|
+
const targetSessionId = typeof args?.targetSessionId === 'string' ? args.targetSessionId.trim() : '';
|
|
2006
|
+
if (targetSessionId) {
|
|
2007
|
+
const session = (h.ctx as any)?.sessionRegistry?.get?.(targetSessionId);
|
|
2008
|
+
if (session && typeof session.providerType === 'string') {
|
|
2009
|
+
providerHint = session.providerType;
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
if (!providerHint && h.currentSession?.providerType) {
|
|
2013
|
+
providerHint = h.currentSession.providerType;
|
|
2014
|
+
}
|
|
2015
|
+
}
|
|
2016
|
+
const provider = h.getProvider(providerHint);
|
|
838
2017
|
const transport = getTargetTransport(h, provider);
|
|
839
2018
|
const historySessionId = getHistorySessionId(h, args);
|
|
840
2019
|
|
|
@@ -874,66 +2053,399 @@ export async function handleReadChat(h: CommandHelpers, args: any): Promise<Comm
|
|
|
874
2053
|
? parsedRecord.coverage
|
|
875
2054
|
: undefined;
|
|
876
2055
|
const activeModal = parsedRecord.activeModal ?? parsedRecord.modal ?? null;
|
|
877
|
-
const returnedStatus = normalizeCliReadChatStatus(parsedRecord.status, activeModal, adapter, adapterStatus);
|
|
2056
|
+
const returnedStatus = normalizeCliReadChatStatus(parsedRecord.status, activeModal, adapter, adapterStatus, parsedRecord.messages);
|
|
878
2057
|
const runtimeMessageMerger = getTargetInstance(h, args) as RuntimeChatMessageMerger | null;
|
|
879
|
-
const parsedMessages =
|
|
2058
|
+
const parsedMessages = collapseAdjacentDuplicateChatMessages(
|
|
2059
|
+
finalizeStreamingMessagesWhenIdle(parsedRecord.messages as ChatMessage[], returnedStatus),
|
|
2060
|
+
);
|
|
880
2061
|
const returnedMessages = runtimeMessageMerger?.category === 'cli'
|
|
881
2062
|
&& runtimeMessageMerger.type === adapter.cliType
|
|
882
2063
|
&& typeof runtimeMessageMerger.mergeRuntimeChatMessages === 'function'
|
|
883
2064
|
? runtimeMessageMerger.mergeRuntimeChatMessages(parsedMessages)
|
|
884
2065
|
: parsedMessages;
|
|
2066
|
+
const providerType = provider?.type || adapter.cliType;
|
|
2067
|
+
let selectedMessages = returnedMessages;
|
|
2068
|
+
let selectedTitle = title;
|
|
2069
|
+
let selectedProviderSessionId = providerSessionId;
|
|
2070
|
+
let selectedTranscriptAuthority = transcriptAuthority;
|
|
2071
|
+
let selectedCoverage = coverage;
|
|
2072
|
+
let selectedStatus = returnedStatus;
|
|
2073
|
+
const sessionWorkspace = typeof (h.currentSession as any)?.workspace === 'string'
|
|
2074
|
+
? (h.currentSession as any).workspace
|
|
2075
|
+
: typeof adapter.workingDir === 'string'
|
|
2076
|
+
? adapter.workingDir
|
|
2077
|
+
: undefined;
|
|
2078
|
+
const intendedWorkspace = typeof args?.workspace === 'string' ? args.workspace : undefined;
|
|
2079
|
+
// ───────────────────────────────────────────────────────────
|
|
2080
|
+
// Chat source decision via ChatSourceMachine (A2 big-bang).
|
|
2081
|
+
// Replaces the ~300-line if-ladder that mixed source decision
|
|
2082
|
+
// with native fetch, anchor mutation, and runtime mirror
|
|
2083
|
+
// selection. The machine decides only between native-history
|
|
2084
|
+
// and pty-parser; downstream selection of which message array
|
|
2085
|
+
// to surface stays here.
|
|
2086
|
+
//
|
|
2087
|
+
// Behavioural changes vs v1:
|
|
2088
|
+
// - No more nativeHistoryAnchoredAt mutation on the adapter.
|
|
2089
|
+
// Lock state lives in CHAT_SOURCE_REGISTRY keyed by
|
|
2090
|
+
// (providerType, sessionId).
|
|
2091
|
+
// - No PTY-vs-native freshness comparison. The lock holds
|
|
2092
|
+
// across arbitrary PTY arrival; only native regression /
|
|
2093
|
+
// unavailability unlocks. This is the plipping fix.
|
|
2094
|
+
// - 6 trigger strings (native_history_partial / _stale /
|
|
2095
|
+
// _not_safely_mapped / _empty / _error / _unavailable)
|
|
2096
|
+
// collapse to 3 events with diagnostic causes preserved
|
|
2097
|
+
// and mapped back to legacy fallbackReason strings for
|
|
2098
|
+
// response compatibility.
|
|
2099
|
+
// - Codex live-workspace native probe and unsafe-native
|
|
2100
|
+
// daemon mirror fallbacks are preserved as additional
|
|
2101
|
+
// input rounds to the machine; they were never the source
|
|
2102
|
+
// decision itself, they were retries.
|
|
2103
|
+
// ───────────────────────────────────────────────────────────
|
|
2104
|
+
|
|
2105
|
+
const supportsNative = supportsCliNativeTranscript(providerType, provider)
|
|
2106
|
+
&& isNativeSourceCanonicalHistory(provider?.nativeHistory);
|
|
2107
|
+
const agentStr = provider?.type || args?.agentType || getCurrentProviderType(h, adapter.cliType);
|
|
2108
|
+
const workspace = sessionWorkspace;
|
|
2109
|
+
const nativeHistoryLimit = Math.max(
|
|
2110
|
+
normalizeReadChatTailLimit(args) || 0,
|
|
2111
|
+
returnedMessages.length,
|
|
2112
|
+
200,
|
|
2113
|
+
);
|
|
2114
|
+
const nativeHistorySessionId = supportsNative
|
|
2115
|
+
? resolveCliNativeHistorySessionId(args, historySessionId, providerSessionId)
|
|
2116
|
+
: undefined;
|
|
2117
|
+
const targetSessionId = typeof args?.targetSessionId === 'string' ? args.targetSessionId.trim() : '';
|
|
2118
|
+
const exactNativeHistoryScope = Boolean(
|
|
2119
|
+
(typeof args?.historySessionId === 'string' && args.historySessionId.trim())
|
|
2120
|
+
|| (typeof args?.providerSessionId === 'string' && args.providerSessionId.trim())
|
|
2121
|
+
|| providerSessionId
|
|
2122
|
+
|| (nativeHistorySessionId && nativeHistorySessionId !== targetSessionId)
|
|
2123
|
+
|| ((h.currentSession as any)?.sessionId === args?.targetSessionId && typeof (h.currentSession as any)?.providerSessionId === 'string' && (h.currentSession as any).providerSessionId.trim())
|
|
2124
|
+
);
|
|
2125
|
+
|
|
2126
|
+
// 1. Fetch native history (or skip if provider does not support it).
|
|
2127
|
+
let nativeHistory: any | null = null;
|
|
2128
|
+
let nativeHistoryError: unknown | undefined;
|
|
2129
|
+
if (supportsNative) {
|
|
2130
|
+
try {
|
|
2131
|
+
nativeHistory = readCliProviderNativeHistory(agentStr, {
|
|
2132
|
+
canonicalHistory: provider?.nativeHistory,
|
|
2133
|
+
historySessionId: nativeHistorySessionId,
|
|
2134
|
+
workspace,
|
|
2135
|
+
offset: 0,
|
|
2136
|
+
limit: nativeHistoryLimit,
|
|
2137
|
+
excludeRecentCount: 0,
|
|
2138
|
+
historyBehavior: provider?.historyBehavior,
|
|
2139
|
+
scripts: provider?.scripts as any,
|
|
2140
|
+
excludeInProgressTurn: returnedStatus === 'waiting_approval',
|
|
2141
|
+
sessionStartedAtMs: sessionStartedAtMsFromRegistry(h, args?.targetSessionId),
|
|
2142
|
+
envOverrides: sessionSpawnEnvFromAdapter(h, args?.targetSessionId),
|
|
2143
|
+
});
|
|
2144
|
+
} catch (error: any) {
|
|
2145
|
+
nativeHistoryError = error;
|
|
2146
|
+
nativeHistory = null;
|
|
2147
|
+
}
|
|
2148
|
+
}
|
|
2149
|
+
|
|
2150
|
+
// 2. Compute safeMapping with the same rules the v1 code used so the
|
|
2151
|
+
// machine sees the same observation it always would have.
|
|
2152
|
+
const nativeMessages: ChatMessage[] = nativeHistory && Array.isArray(nativeHistory.messages)
|
|
2153
|
+
? normalizeAndFilterNativeHistory(h, agentStr, args, nativeHistory.messages as ChatMessage[], nativeHistory.providerSessionId)
|
|
2154
|
+
: [];
|
|
2155
|
+
const historyProviderSessionId = typeof nativeHistory?.providerSessionId === 'string'
|
|
2156
|
+
? nativeHistory.providerSessionId
|
|
2157
|
+
: readHistorySessionIdFromMessages(nativeMessages) || nativeHistorySessionId || historySessionId;
|
|
2158
|
+
const lookup = nativeHistory?.lookup === 'workspace' ? 'workspace' : 'session';
|
|
2159
|
+
const nativeHistorySessionForMapping = adapter.cliType === 'antigravity-cli'
|
|
2160
|
+
&& historyProviderSessionId
|
|
2161
|
+
&& nativeHistorySessionId
|
|
2162
|
+
&& historyProviderSessionId !== nativeHistorySessionId
|
|
2163
|
+
? undefined
|
|
2164
|
+
: nativeHistorySessionId;
|
|
2165
|
+
const safeMapping = supportsNative && nativeHistory
|
|
2166
|
+
? hasSafeNativeHistoryMapping({
|
|
2167
|
+
historySessionId: lookup === 'workspace' ? undefined : nativeHistorySessionForMapping,
|
|
2168
|
+
providerSessionId: lookup === 'workspace' ? undefined : historyProviderSessionId || providerSessionId,
|
|
2169
|
+
workspace,
|
|
2170
|
+
nativeMessages,
|
|
2171
|
+
ptyMessages: returnedMessages,
|
|
2172
|
+
requireWorkspaceContentOverlap: lookup === 'workspace' && !exactNativeHistoryScope,
|
|
2173
|
+
})
|
|
2174
|
+
: false;
|
|
2175
|
+
|
|
2176
|
+
// 3. Drive ChatSourceMachine — one observation per readChat call,
|
|
2177
|
+
// keyed by (providerType, sessionKey-for-this-call). targetSessionId
|
|
2178
|
+
// is the most specific session anchor we have; fall back to
|
|
2179
|
+
// historySessionId so we never leak state across distinct sessions.
|
|
2180
|
+
const machineSessionKey = String(
|
|
2181
|
+
args?.targetSessionId
|
|
2182
|
+
|| providerSessionId
|
|
2183
|
+
|| historySessionId
|
|
2184
|
+
|| (h.currentSession as any)?.sessionId
|
|
2185
|
+
|| ''
|
|
2186
|
+
);
|
|
2187
|
+
const primary = decideCliReadChatSource({
|
|
2188
|
+
providerType,
|
|
2189
|
+
provider,
|
|
2190
|
+
sessionId: machineSessionKey,
|
|
2191
|
+
nativeHistoryResult: nativeHistory,
|
|
2192
|
+
nativeHistoryError,
|
|
2193
|
+
safeMapping,
|
|
2194
|
+
sessionWorkspace,
|
|
2195
|
+
intendedWorkspace,
|
|
2196
|
+
ptyMessages: returnedMessages,
|
|
2197
|
+
// Start with PTY visible; decideCliReadChatSource flips this
|
|
2198
|
+
// to true when the machine actually selects native-history.
|
|
2199
|
+
ptyStatusApprovalOnly: false,
|
|
2200
|
+
});
|
|
2201
|
+
let messageSource: Record<string, unknown> = primary.messageSource;
|
|
2202
|
+
|
|
2203
|
+
if (primary.nativeSelected) {
|
|
2204
|
+
selectedMessages = finalizeStreamingMessagesWhenIdle(primary.nativeMessages, returnedStatus);
|
|
2205
|
+
selectedProviderSessionId = historyProviderSessionId || providerSessionId;
|
|
2206
|
+
selectedTranscriptAuthority = 'provider';
|
|
2207
|
+
selectedCoverage = nativeHistory?.hasMore ? 'tail' : 'full';
|
|
2208
|
+
} else if (supportsNative) {
|
|
2209
|
+
// Native not selected. Two preserved v1 fallbacks before settling
|
|
2210
|
+
// on PTY: (a) Codex-only live workspace native probe; (b) unsafe-
|
|
2211
|
+
// native daemon mirror selection. The machine sees each retry as
|
|
2212
|
+
// an additional observation.
|
|
2213
|
+
const liveCurrentRuntimePtySafe = isCurrentRuntimePtySafelyAttributed({
|
|
2214
|
+
adapter,
|
|
2215
|
+
helpers: h,
|
|
2216
|
+
readChatArgs: args,
|
|
2217
|
+
sessionWorkspace,
|
|
2218
|
+
intendedWorkspace,
|
|
2219
|
+
ptyMessages: returnedMessages,
|
|
2220
|
+
});
|
|
2221
|
+
const mayProbeLiveCodexWorkspaceNative = adapter.cliType === 'codex-cli'
|
|
2222
|
+
&& liveCurrentRuntimePtySafe
|
|
2223
|
+
&& !(typeof args?.providerSessionId === 'string' && args.providerSessionId.trim())
|
|
2224
|
+
&& !(providerSessionId && providerSessionId.trim())
|
|
2225
|
+
&& (!historyProviderSessionId || historyProviderSessionId === nativeHistorySessionId || historyProviderSessionId === historySessionId);
|
|
2226
|
+
const liveWorkspaceNativeHistory = mayProbeLiveCodexWorkspaceNative
|
|
2227
|
+
? readLiveCodexWorkspaceNativeHistory(agentStr, {
|
|
2228
|
+
canonicalHistory: provider?.nativeHistory,
|
|
2229
|
+
workspace,
|
|
2230
|
+
offset: 0,
|
|
2231
|
+
limit: nativeHistoryLimit,
|
|
2232
|
+
excludeRecentCount: 0,
|
|
2233
|
+
historyBehavior: provider?.historyBehavior,
|
|
2234
|
+
scripts: provider?.scripts as any,
|
|
2235
|
+
})
|
|
2236
|
+
: null;
|
|
2237
|
+
const liveWorkspaceNativeMessages = Array.isArray((liveWorkspaceNativeHistory as any)?.messages)
|
|
2238
|
+
? normalizeAndFilterNativeHistory(h, agentStr, args, (liveWorkspaceNativeHistory as any).messages as ChatMessage[], (liveWorkspaceNativeHistory as any)?.providerSessionId)
|
|
2239
|
+
: [];
|
|
2240
|
+
const liveWorkspaceNativeProviderSessionId = typeof (liveWorkspaceNativeHistory as any)?.providerSessionId === 'string'
|
|
2241
|
+
? (liveWorkspaceNativeHistory as any).providerSessionId
|
|
2242
|
+
: readHistorySessionIdFromMessages(liveWorkspaceNativeMessages);
|
|
2243
|
+
const liveWorkspaceNativeSafeMapping = liveWorkspaceNativeMessages.length > 0
|
|
2244
|
+
&& hasSafeNativeHistoryMapping({
|
|
2245
|
+
workspace,
|
|
2246
|
+
nativeMessages: liveWorkspaceNativeMessages,
|
|
2247
|
+
ptyMessages: returnedMessages,
|
|
2248
|
+
requireWorkspaceContentOverlap: true,
|
|
2249
|
+
});
|
|
2250
|
+
if (liveWorkspaceNativeHistory) {
|
|
2251
|
+
const liveDecision = decideCliReadChatSource({
|
|
2252
|
+
providerType,
|
|
2253
|
+
provider,
|
|
2254
|
+
// Distinct session key so a transient codex live-probe does not
|
|
2255
|
+
// clobber the primary session's lock. The machine treats this
|
|
2256
|
+
// as its own session; the primary session's state is untouched.
|
|
2257
|
+
sessionId: `${machineSessionKey}::live-workspace`,
|
|
2258
|
+
nativeHistoryResult: liveWorkspaceNativeHistory,
|
|
2259
|
+
safeMapping: liveWorkspaceNativeSafeMapping,
|
|
2260
|
+
sessionWorkspace,
|
|
2261
|
+
intendedWorkspace,
|
|
2262
|
+
ptyMessages: returnedMessages,
|
|
2263
|
+
ptyStatusApprovalOnly: true,
|
|
2264
|
+
});
|
|
2265
|
+
if (liveDecision.nativeSelected) {
|
|
2266
|
+
selectedMessages = finalizeStreamingMessagesWhenIdle(liveDecision.nativeMessages, returnedStatus);
|
|
2267
|
+
selectedProviderSessionId = liveWorkspaceNativeProviderSessionId || providerSessionId;
|
|
2268
|
+
selectedTranscriptAuthority = 'provider';
|
|
2269
|
+
selectedCoverage = (liveWorkspaceNativeHistory as any).hasMore ? 'tail' : 'full';
|
|
2270
|
+
messageSource = liveDecision.messageSource;
|
|
2271
|
+
(messageSource as any).selectedDaemonSource = 'live-workspace-native-history';
|
|
2272
|
+
(messageSource as any).runtimeMappingSafe = true;
|
|
2273
|
+
} else {
|
|
2274
|
+
// Live probe also rejected: apply unsafe-native daemon mirror
|
|
2275
|
+
// selection (codex-only) using the primary decision's
|
|
2276
|
+
// fallbackReason.
|
|
2277
|
+
applyUnsafeNativeDaemonFallback({
|
|
2278
|
+
providerType,
|
|
2279
|
+
adapter,
|
|
2280
|
+
helpers: h,
|
|
2281
|
+
readChatArgs: args,
|
|
2282
|
+
sessionWorkspace,
|
|
2283
|
+
intendedWorkspace,
|
|
2284
|
+
ptyMessages: returnedMessages,
|
|
2285
|
+
nativeHistoryLimit,
|
|
2286
|
+
provider,
|
|
2287
|
+
messageSourceRef: { set(value) { messageSource = value; }, get() { return messageSource; } },
|
|
2288
|
+
apply(selection) {
|
|
2289
|
+
selectedMessages = selection.messages;
|
|
2290
|
+
selectedTranscriptAuthority = selection.transcriptAuthority;
|
|
2291
|
+
selectedCoverage = selection.coverage ?? coverage;
|
|
2292
|
+
selectedStatus = selection.status ?? returnedStatus;
|
|
2293
|
+
},
|
|
2294
|
+
activeModal,
|
|
2295
|
+
returnedStatus,
|
|
2296
|
+
coverage,
|
|
2297
|
+
});
|
|
2298
|
+
}
|
|
2299
|
+
} else {
|
|
2300
|
+
applyUnsafeNativeDaemonFallback({
|
|
2301
|
+
providerType,
|
|
2302
|
+
adapter,
|
|
2303
|
+
helpers: h,
|
|
2304
|
+
readChatArgs: args,
|
|
2305
|
+
sessionWorkspace,
|
|
2306
|
+
intendedWorkspace,
|
|
2307
|
+
ptyMessages: returnedMessages,
|
|
2308
|
+
nativeHistoryLimit,
|
|
2309
|
+
provider,
|
|
2310
|
+
messageSourceRef: { set(value) { messageSource = value; }, get() { return messageSource; } },
|
|
2311
|
+
apply(selection) {
|
|
2312
|
+
selectedMessages = selection.messages;
|
|
2313
|
+
selectedTranscriptAuthority = selection.transcriptAuthority;
|
|
2314
|
+
selectedCoverage = selection.coverage ?? coverage;
|
|
2315
|
+
selectedStatus = selection.status ?? returnedStatus;
|
|
2316
|
+
},
|
|
2317
|
+
activeModal,
|
|
2318
|
+
returnedStatus,
|
|
2319
|
+
coverage,
|
|
2320
|
+
});
|
|
2321
|
+
}
|
|
2322
|
+
}
|
|
885
2323
|
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
2324
|
return buildReadChatCommandResult({
|
|
887
|
-
messages:
|
|
888
|
-
status:
|
|
2325
|
+
messages: selectedMessages,
|
|
2326
|
+
status: selectedStatus,
|
|
889
2327
|
activeModal,
|
|
2328
|
+
messageSource,
|
|
2329
|
+
transcriptProvenance: messageSource,
|
|
890
2330
|
debugReadChat: {
|
|
891
2331
|
provider: adapter.cliType,
|
|
892
2332
|
targetSessionId: String(args?.targetSessionId || ''),
|
|
893
2333
|
adapterStatus: String(adapterStatus.status || ''),
|
|
894
2334
|
parsedStatus: String(parsedRecord.status || ''),
|
|
895
|
-
returnedStatus: String(
|
|
896
|
-
|
|
2335
|
+
returnedStatus: String(selectedStatus || ''),
|
|
2336
|
+
selectedMessageSource: (messageSource as any).selected,
|
|
2337
|
+
messageSource,
|
|
2338
|
+
shouldPreferAdapterMessages: supportsCliNativeTranscript(providerType, provider)
|
|
2339
|
+
&& isNativeSourceCanonicalHistory(provider?.nativeHistory)
|
|
2340
|
+
&& (messageSource as any).selected !== 'native-history'
|
|
2341
|
+
&& typeof (messageSource as any).fallbackReason === 'string'
|
|
2342
|
+
&& (messageSource as any).fallbackReason.startsWith('native_history_')
|
|
2343
|
+
&& (messageSource as any).fallbackReason !== 'native_history_not_checked'
|
|
2344
|
+
&& !isUnsafeNativeTranscriptFallback((messageSource as any).fallbackReason)
|
|
2345
|
+
&& !(selectedTranscriptAuthority === 'provider' && selectedCoverage === 'full'),
|
|
897
2346
|
parsedMsgCount: parsedRecord.messages.length,
|
|
898
|
-
returnedMsgCount:
|
|
2347
|
+
returnedMsgCount: selectedMessages.length,
|
|
899
2348
|
},
|
|
900
|
-
...(
|
|
901
|
-
...(
|
|
902
|
-
...(
|
|
903
|
-
...(
|
|
904
|
-
}, args);
|
|
2349
|
+
...(selectedTitle ? { title: selectedTitle } : {}),
|
|
2350
|
+
...(selectedProviderSessionId ? { providerSessionId: selectedProviderSessionId } : {}),
|
|
2351
|
+
...(selectedTranscriptAuthority ? { transcriptAuthority: selectedTranscriptAuthority } : {}),
|
|
2352
|
+
...(selectedCoverage ? { coverage: selectedCoverage } : {}),
|
|
2353
|
+
}, args, h);
|
|
905
2354
|
}
|
|
2355
|
+
// History-only path (no adapter). Same source-decision contract as
|
|
2356
|
+
// the adapter path above, but with no PTY messages — the machine
|
|
2357
|
+
// simply decides whether native is usable; if not we return the
|
|
2358
|
+
// history we have plus a `native_history_not_safely_available`
|
|
2359
|
+
// error response when the provider requires native source.
|
|
906
2360
|
const historyLimit = normalizeReadChatTailLimit(args);
|
|
907
2361
|
try {
|
|
908
2362
|
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
|
-
|
|
2363
|
+
const workspace = typeof (h.currentSession as any)?.workspace === 'string'
|
|
2364
|
+
? (h.currentSession as any).workspace
|
|
2365
|
+
: undefined;
|
|
2366
|
+
const intendedWorkspace = typeof args?.workspace === 'string' ? args.workspace : undefined;
|
|
2367
|
+
const supportsNative = supportsCliNativeTranscript(agentStr, provider)
|
|
2368
|
+
&& isNativeSourceCanonicalHistory(provider?.nativeHistory);
|
|
2369
|
+
const history = supportsNative
|
|
2370
|
+
? readCliProviderNativeHistory(agentStr, {
|
|
2371
|
+
canonicalHistory: provider?.nativeHistory,
|
|
2372
|
+
historySessionId,
|
|
2373
|
+
workspace,
|
|
2374
|
+
offset: 0,
|
|
2375
|
+
limit: historyLimit,
|
|
2376
|
+
excludeRecentCount: 0,
|
|
2377
|
+
historyBehavior: provider?.historyBehavior,
|
|
2378
|
+
scripts: provider?.scripts as any,
|
|
2379
|
+
sessionStartedAtMs: sessionStartedAtMsFromRegistry(h, args?.targetSessionId),
|
|
2380
|
+
envOverrides: sessionSpawnEnvFromAdapter(h, args?.targetSessionId),
|
|
2381
|
+
})
|
|
2382
|
+
: readProviderChatHistory(agentStr, {
|
|
2383
|
+
canonicalHistory: provider?.nativeHistory,
|
|
2384
|
+
historySessionId,
|
|
2385
|
+
workspace,
|
|
2386
|
+
offset: 0,
|
|
2387
|
+
limit: historyLimit,
|
|
2388
|
+
excludeRecentCount: 0,
|
|
2389
|
+
historyBehavior: provider?.historyBehavior,
|
|
2390
|
+
scripts: provider?.scripts as any,
|
|
2391
|
+
});
|
|
2392
|
+
const lookup = (history as any)?.lookup === 'workspace' ? 'workspace' : 'session';
|
|
2393
|
+
const historyMessages = Array.isArray((history as any)?.messages)
|
|
2394
|
+
? normalizeAndFilterNativeHistory(h, agentStr, args, (history as any).messages as ChatMessage[], (history as any)?.providerSessionId)
|
|
2395
|
+
: [];
|
|
924
2396
|
const historyProviderSessionId = typeof (history as any)?.providerSessionId === 'string'
|
|
925
2397
|
? (history as any).providerSessionId
|
|
926
|
-
: historySessionId;
|
|
2398
|
+
: readHistorySessionIdFromMessages(historyMessages) || historySessionId;
|
|
2399
|
+
const safeMapping = supportsNative
|
|
2400
|
+
? hasSafeNativeHistoryMapping({
|
|
2401
|
+
historySessionId: lookup === 'workspace' ? undefined : historySessionId,
|
|
2402
|
+
providerSessionId: lookup === 'workspace' ? undefined : historyProviderSessionId,
|
|
2403
|
+
workspace,
|
|
2404
|
+
nativeMessages: historyMessages,
|
|
2405
|
+
})
|
|
2406
|
+
: false;
|
|
2407
|
+
|
|
2408
|
+
const machineSessionKey = String(
|
|
2409
|
+
args?.targetSessionId
|
|
2410
|
+
|| historyProviderSessionId
|
|
2411
|
+
|| historySessionId
|
|
2412
|
+
|| (h.currentSession as any)?.sessionId
|
|
2413
|
+
|| ''
|
|
2414
|
+
);
|
|
2415
|
+
const decision = decideCliReadChatSource({
|
|
2416
|
+
providerType: agentStr,
|
|
2417
|
+
provider,
|
|
2418
|
+
sessionId: machineSessionKey,
|
|
2419
|
+
nativeHistoryResult: history,
|
|
2420
|
+
safeMapping,
|
|
2421
|
+
sessionWorkspace: workspace,
|
|
2422
|
+
intendedWorkspace,
|
|
2423
|
+
ptyMessages: [],
|
|
2424
|
+
ptyStatusApprovalOnly: false,
|
|
2425
|
+
});
|
|
2426
|
+
|
|
2427
|
+
if (supportsNative && !decision.nativeSelected) {
|
|
2428
|
+
return {
|
|
2429
|
+
success: false,
|
|
2430
|
+
code: 'native_history_not_safely_available',
|
|
2431
|
+
error: 'Provider-native history was not safely available for the requested CLI session.',
|
|
2432
|
+
providerSessionId: historyProviderSessionId,
|
|
2433
|
+
messageSource: decision.messageSource,
|
|
2434
|
+
transcriptProvenance: decision.messageSource,
|
|
2435
|
+
};
|
|
2436
|
+
}
|
|
927
2437
|
return buildReadChatCommandResult({
|
|
928
|
-
messages:
|
|
2438
|
+
messages: historyMessages,
|
|
929
2439
|
status: 'idle',
|
|
2440
|
+
messageSource: decision.messageSource,
|
|
2441
|
+
transcriptProvenance: decision.messageSource,
|
|
930
2442
|
...(typeof (history as any)?.title === 'string' ? { title: (history as any).title } : {}),
|
|
931
2443
|
...(historyProviderSessionId ? { providerSessionId: historyProviderSessionId } : {}),
|
|
932
2444
|
...(((provider?.historyBehavior as any)?.transcriptAuthority === 'provider' || (provider?.historyBehavior as any)?.transcriptAuthority === 'daemon')
|
|
933
2445
|
? { transcriptAuthority: (provider?.historyBehavior as any).transcriptAuthority }
|
|
934
2446
|
: {}),
|
|
935
2447
|
coverage: 'tail',
|
|
936
|
-
}, args);
|
|
2448
|
+
}, args, h);
|
|
937
2449
|
} catch (error: any) {
|
|
938
2450
|
return { success: false, error: error?.message || `${transport} adapter not found` };
|
|
939
2451
|
}
|
|
@@ -973,7 +2485,7 @@ export async function handleReadChat(h: CommandHelpers, args: any): Promise<Comm
|
|
|
973
2485
|
args?.targetSessionId,
|
|
974
2486
|
historySessionId,
|
|
975
2487
|
);
|
|
976
|
-
return buildReadChatCommandResult(validated as Record<string, any>, args);
|
|
2488
|
+
return buildReadChatCommandResult(validated as Record<string, any>, args, h);
|
|
977
2489
|
}
|
|
978
2490
|
if (!extensionReadChatError) {
|
|
979
2491
|
extensionReadChatError = 'extension read_chat returned a non-object payload';
|
|
@@ -1012,7 +2524,7 @@ export async function handleReadChat(h: CommandHelpers, args: any): Promise<Comm
|
|
|
1012
2524
|
messages: stream.messages || [],
|
|
1013
2525
|
status: stream.status,
|
|
1014
2526
|
agentType: stream.agentType,
|
|
1015
|
-
}, args);
|
|
2527
|
+
}, args, h);
|
|
1016
2528
|
}
|
|
1017
2529
|
}
|
|
1018
2530
|
}
|
|
@@ -1052,7 +2564,7 @@ export async function handleReadChat(h: CommandHelpers, args: any): Promise<Comm
|
|
|
1052
2564
|
args?.targetSessionId,
|
|
1053
2565
|
historySessionId,
|
|
1054
2566
|
);
|
|
1055
|
-
return buildReadChatCommandResult(validated as Record<string, any>, args);
|
|
2567
|
+
return buildReadChatCommandResult(validated as Record<string, any>, args, h);
|
|
1056
2568
|
}
|
|
1057
2569
|
if (!webviewReadChatError) {
|
|
1058
2570
|
webviewReadChatError = 'webview read_chat returned a non-object payload';
|
|
@@ -1102,7 +2614,7 @@ export async function handleReadChat(h: CommandHelpers, args: any): Promise<Comm
|
|
|
1102
2614
|
args?.targetSessionId,
|
|
1103
2615
|
historySessionId,
|
|
1104
2616
|
);
|
|
1105
|
-
return buildReadChatCommandResult(validated as Record<string, any>, args);
|
|
2617
|
+
return buildReadChatCommandResult(validated as Record<string, any>, args, h);
|
|
1106
2618
|
}
|
|
1107
2619
|
if (!ideReadChatError) {
|
|
1108
2620
|
ideReadChatError = 'ide read_chat returned a non-object payload';
|
|
@@ -1184,8 +2696,24 @@ export async function handleSendChat(h: CommandHelpers, args: any): Promise<Comm
|
|
|
1184
2696
|
assertTextOnlyInput(provider, input);
|
|
1185
2697
|
if (!text) return { success: false, error: 'text required for PTY send' };
|
|
1186
2698
|
await waitOnceForFreshHermesCliStart(adapter, _log);
|
|
1187
|
-
|
|
1188
|
-
|
|
2699
|
+
const forceSend = args?.force === true || args?.forceSend === true;
|
|
2700
|
+
if (forceSend && typeof adapter.forceSendMessage === 'function') {
|
|
2701
|
+
await adapter.forceSendMessage(text);
|
|
2702
|
+
} else if (forceSend) {
|
|
2703
|
+
await adapter.sendMessage(text, { force: true });
|
|
2704
|
+
} else {
|
|
2705
|
+
await adapter.sendMessage(text);
|
|
2706
|
+
}
|
|
2707
|
+
const target = getTargetInstance(h, args) as RuntimeChatMessageMerger | null;
|
|
2708
|
+
if (target?.category === 'cli'
|
|
2709
|
+
&& target.type === adapter.cliType
|
|
2710
|
+
&& typeof target.recordAcknowledgedUserInput === 'function') {
|
|
2711
|
+
target.recordAcknowledgedUserInput(input);
|
|
2712
|
+
}
|
|
2713
|
+
return {
|
|
2714
|
+
..._logSendSuccess(`${transport}-adapter`, adapter.cliType),
|
|
2715
|
+
...(forceSend ? { forceSent: true } : {}),
|
|
2716
|
+
};
|
|
1189
2717
|
} catch (e: any) {
|
|
1190
2718
|
return { success: false, error: `${transport} send failed: ${e.message}` };
|
|
1191
2719
|
}
|
|
@@ -1742,9 +3270,18 @@ export async function handleResolveAction(h: CommandHelpers, args: any): Promise
|
|
|
1742
3270
|
if (buttonIndex < 0 && (action === 'always' || /always/i.test(button))) {
|
|
1743
3271
|
buttonIndex = buttons.findIndex(b => /always/i.test(b));
|
|
1744
3272
|
}
|
|
3273
|
+
if (buttonIndex < 0 && (action === 'approve' || action === 'accept')) {
|
|
3274
|
+
buttonIndex = pickApprovalButton(buttons, provider).index;
|
|
3275
|
+
}
|
|
1745
3276
|
if (buttonIndex < 0) {
|
|
1746
3277
|
return { success: false, error: 'Approval action did not match any visible button' };
|
|
1747
3278
|
}
|
|
3279
|
+
// Idempotency: if the adapter already resolved this approval within cooldown, report
|
|
3280
|
+
// stale_prompt rather than writing a second key to the PTY.
|
|
3281
|
+
if (typeof adapter.isApprovalRecentlyResolved === 'function' && adapter.isApprovalRecentlyResolved()) {
|
|
3282
|
+
LOG.info('Command', `[resolveAction] CLI PTY → stale_prompt (already resolved within cooldown)`);
|
|
3283
|
+
return { success: true, stalePrompt: true, buttonIndex, button: buttons[buttonIndex] ?? button };
|
|
3284
|
+
}
|
|
1748
3285
|
if (typeof adapter.resolveModal === 'function') {
|
|
1749
3286
|
adapter.resolveModal(buttonIndex);
|
|
1750
3287
|
} else {
|