@adhdev/daemon-core 0.9.82-rc.8 → 0.9.82-rc.80

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.
Files changed (73) hide show
  1. package/dist/cli-adapters/provider-cli-adapter.d.ts +2 -0
  2. package/dist/cli-adapters/provider-cli-parse.d.ts +1 -0
  3. package/dist/cli-adapters/provider-cli-shared.d.ts +2 -0
  4. package/dist/commands/router.d.ts +22 -0
  5. package/dist/config/mesh-config.d.ts +66 -1
  6. package/dist/git/git-commands.d.ts +1 -0
  7. package/dist/git/git-status.d.ts +5 -0
  8. package/dist/git/git-types.d.ts +10 -0
  9. package/dist/index.d.ts +13 -6
  10. package/dist/index.js +4936 -1171
  11. package/dist/index.js.map +1 -1
  12. package/dist/index.mjs +4900 -1157
  13. package/dist/index.mjs.map +1 -1
  14. package/dist/installer.d.ts +1 -4
  15. package/dist/launch.d.ts +1 -1
  16. package/dist/logging/async-batch-writer.d.ts +10 -0
  17. package/dist/mesh/beads-db.d.ts +18 -0
  18. package/dist/mesh/mesh-active-work.d.ts +51 -0
  19. package/dist/mesh/mesh-events.d.ts +29 -5
  20. package/dist/mesh/mesh-fast-forward.d.ts +39 -0
  21. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  22. package/dist/mesh/mesh-ledger.d.ts +38 -1
  23. package/dist/mesh/mesh-work-queue.d.ts +27 -5
  24. package/dist/mesh/refine-config.d.ts +119 -0
  25. package/dist/providers/chat-message-normalization.d.ts +1 -0
  26. package/dist/providers/cli-provider-instance.d.ts +2 -1
  27. package/dist/repo-mesh-types.d.ts +39 -0
  28. package/dist/status/reporter.d.ts +2 -0
  29. package/package.json +3 -1
  30. package/src/boot/daemon-lifecycle.ts +1 -0
  31. package/src/cli-adapters/provider-cli-adapter.ts +91 -3
  32. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  33. package/src/cli-adapters/provider-cli-parse.ts +4 -0
  34. package/src/cli-adapters/provider-cli-runtime.ts +3 -1
  35. package/src/cli-adapters/provider-cli-shared.d.ts +2 -0
  36. package/src/cli-adapters/provider-cli-shared.ts +20 -10
  37. package/src/commands/chat-commands.ts +242 -7
  38. package/src/commands/cli-manager.ts +63 -0
  39. package/src/commands/handler.ts +8 -1
  40. package/src/commands/mesh-coordinator.ts +13 -143
  41. package/src/commands/router.ts +2435 -414
  42. package/src/config/chat-history.ts +9 -7
  43. package/src/config/mesh-config.ts +244 -1
  44. package/src/daemon/dev-cli-debug.ts +10 -1
  45. package/src/detection/ide-detector.ts +26 -16
  46. package/src/git/git-commands.ts +3 -3
  47. package/src/git/git-status.ts +97 -6
  48. package/src/git/git-summary.ts +3 -0
  49. package/src/git/git-types.ts +11 -0
  50. package/src/index.ts +31 -5
  51. package/src/installer.d.ts +1 -1
  52. package/src/installer.ts +8 -6
  53. package/src/launch.d.ts +1 -1
  54. package/src/launch.ts +37 -28
  55. package/src/logging/async-batch-writer.ts +55 -0
  56. package/src/logging/logger.ts +2 -1
  57. package/src/mesh/beads-db.ts +176 -0
  58. package/src/mesh/coordinator-prompt.ts +27 -7
  59. package/src/mesh/mesh-active-work.ts +222 -0
  60. package/src/mesh/mesh-events.ts +342 -47
  61. package/src/mesh/mesh-fast-forward.ts +430 -0
  62. package/src/mesh/mesh-host-ownership.ts +73 -0
  63. package/src/mesh/mesh-ledger.ts +138 -1
  64. package/src/mesh/mesh-work-queue.ts +199 -137
  65. package/src/mesh/refine-config.ts +306 -0
  66. package/src/providers/chat-message-normalization.ts +3 -1
  67. package/src/providers/cli-provider-instance.ts +91 -13
  68. package/src/providers/ide-provider-instance.ts +17 -3
  69. package/src/providers/provider-loader.ts +10 -4
  70. package/src/providers/version-archive.ts +38 -20
  71. package/src/repo-mesh-types.ts +43 -0
  72. package/src/status/reporter.ts +15 -0
  73. package/src/system/host-memory.ts +29 -12
@@ -761,6 +761,17 @@ export class ProviderCliAdapter implements CliAdapter {
761
761
  if (stableMs < 2000) return;
762
762
 
763
763
  const startupModal = this.runParseApproval(this.recentOutputBuffer);
764
+ const startupStatus = this.runDetectStatus(screenText || this.recentOutputBuffer);
765
+ if (!startupModal && startupStatus !== 'idle') {
766
+ this.recordTrace('startup_settle_deferred', {
767
+ trigger,
768
+ startupStatus,
769
+ stableMs,
770
+ screenText: summarizeCliTraceText(screenText, 500),
771
+ });
772
+ this.scheduleStartupSettleCheck();
773
+ return;
774
+ }
764
775
  this.startupParseGate = false;
765
776
  if (this.startupSettleTimer) {
766
777
  clearTimeout(this.startupSettleTimer);
@@ -956,6 +967,38 @@ export class ProviderCliAdapter implements CliAdapter {
956
967
  return true;
957
968
  }
958
969
 
970
+ private clearParsedIdleResponseGuard(reason: string, parsedStatus: any): boolean {
971
+ const parsedRawStatus = typeof parsedStatus?.status === 'string' ? parsedStatus.status.trim() : '';
972
+ const parsedModal = parsedStatus?.activeModal ?? parsedStatus?.modal ?? null;
973
+ const blockingModal = this.activeModal || this.runParseApproval(this.recentOutputBuffer);
974
+ if (
975
+ !this.isWaitingForResponse
976
+ || parsedRawStatus !== 'idle'
977
+ || !!parsedModal
978
+ || !!blockingModal
979
+ || !this.parsedStatusHasFinalAssistantMessage(parsedStatus)
980
+ ) {
981
+ return false;
982
+ }
983
+ this.clearAllTimers();
984
+ this.clearIdleFinishCandidate(reason);
985
+ this.responseBuffer = '';
986
+ this.isWaitingForResponse = false;
987
+ this.responseSettleIgnoreUntil = 0;
988
+ this.submitRetryUsed = false;
989
+ this.submitRetryPromptSnippet = '';
990
+ this.finishRetryCount = 0;
991
+ this.currentTurnScope = null;
992
+ this.activeModal = null;
993
+ this.setStatus('idle', reason);
994
+ this.recordTrace('parsed_idle_response_cleared', {
995
+ reason,
996
+ parsedStatus: parsedRawStatus,
997
+ parsedMessageCount: Array.isArray(parsedStatus?.messages) ? parsedStatus.messages.length : 0,
998
+ });
999
+ return true;
1000
+ }
1001
+
959
1002
  private hasMeaningfulResponseBuffer(promptSnippet: string): boolean {
960
1003
  const raw = String(this.responseBuffer || '').trim();
961
1004
  if (!raw) return false;
@@ -1489,6 +1532,7 @@ export class ProviderCliAdapter implements CliAdapter {
1489
1532
  accumulatedRawBuffer: this.accumulatedRawBuffer,
1490
1533
  recentOutputBuffer: this.recentOutputBuffer,
1491
1534
  terminalScreenText: parseScreenText,
1535
+ workingDir: this.workingDir,
1492
1536
  baseMessages: [],
1493
1537
  partialResponse: this.responseBuffer,
1494
1538
  isWaitingForResponse: this.isWaitingForResponse,
@@ -1552,6 +1596,15 @@ export class ProviderCliAdapter implements CliAdapter {
1552
1596
  return !!(startupModal || this.activeModal);
1553
1597
  }
1554
1598
 
1599
+ private parsedStatusHasFinalAssistantMessage(parsed: any): boolean {
1600
+ const messages = Array.isArray(parsed?.messages) ? parsed.messages : [];
1601
+ const lastAssistant = [...messages].reverse().find((message: any) => {
1602
+ if (!message || message.role !== 'assistant') return false;
1603
+ return typeof message.content === 'string' && message.content.trim().length > 0;
1604
+ });
1605
+ return !!lastAssistant;
1606
+ }
1607
+
1555
1608
  private projectEffectiveStatus(startupModal: { message: string; buttons: string[] } | null = null): CliSessionStatus['status'] {
1556
1609
  if (this.parseErrorMessage) return 'error';
1557
1610
  if (this.hasActionableApproval(startupModal)) return 'waiting_approval';
@@ -1564,8 +1617,14 @@ export class ProviderCliAdapter implements CliAdapter {
1564
1617
  getStatus(options: { allowParse?: boolean } = {}): CliSessionStatus {
1565
1618
  const allowParse = options.allowParse !== false;
1566
1619
  const startupModal = allowParse && this.startupParseGate ? this.runParseApproval(this.recentOutputBuffer) : null;
1620
+ const startupDetectedStatus = allowParse && this.startupParseGate && !startupModal
1621
+ ? this.runDetectStatus(this.recentOutputBuffer || this.terminalScreen.getText())
1622
+ : null;
1567
1623
  let effectiveStatus = this.projectEffectiveStatus(startupModal);
1568
1624
  let effectiveModal = startupModal || this.activeModal;
1625
+ if (startupDetectedStatus === 'waiting_approval') {
1626
+ effectiveStatus = 'waiting_approval';
1627
+ }
1569
1628
  if (allowParse && !startupModal && !effectiveModal) {
1570
1629
  const parsed = this.getFreshParsedStatusCache();
1571
1630
  const parsedModal = parsed?.activeModal && Array.isArray(parsed.activeModal.buttons)
@@ -1575,6 +1634,18 @@ export class ProviderCliAdapter implements CliAdapter {
1575
1634
  if (parsed?.status === 'waiting_approval' && parsedModal) {
1576
1635
  effectiveStatus = 'waiting_approval';
1577
1636
  effectiveModal = parsedModal;
1637
+ } else if (
1638
+ effectiveStatus === 'idle'
1639
+ && parsed?.status === 'generating'
1640
+ && !this.parsedStatusHasFinalAssistantMessage(parsed)
1641
+ ) {
1642
+ effectiveStatus = 'generating';
1643
+ } else if (
1644
+ effectiveStatus === 'generating'
1645
+ && parsed?.status === 'idle'
1646
+ && this.parsedStatusHasFinalAssistantMessage(parsed)
1647
+ ) {
1648
+ effectiveStatus = 'idle';
1578
1649
  }
1579
1650
  }
1580
1651
  const bufferState = this.getBufferState();
@@ -1665,6 +1736,7 @@ export class ProviderCliAdapter implements CliAdapter {
1665
1736
  accumulatedRawBuffer: this.accumulatedRawBuffer,
1666
1737
  recentOutputBuffer: this.recentOutputBuffer,
1667
1738
  terminalScreenText: this.getParseScreenText(this.terminalScreen.getText()),
1739
+ workingDir: this.workingDir,
1668
1740
  baseMessages: [],
1669
1741
  partialResponse: this.responseBuffer,
1670
1742
  isWaitingForResponse: this.isWaitingForResponse,
@@ -1979,7 +2051,10 @@ export class ProviderCliAdapter implements CliAdapter {
1979
2051
  }
1980
2052
  }
1981
2053
  if (this.isWaitingForResponse && !allowInputDuringGeneration) {
1982
- if (!this.clearStaleIdleResponseGuard('send_message_guard')) {
2054
+ if (
2055
+ !this.clearStaleIdleResponseGuard('send_message_guard')
2056
+ && !this.clearParsedIdleResponseGuard('send_message_parsed_idle_guard', parsedStatusBeforeSend)
2057
+ ) {
1983
2058
  throw new Error(`${this.cliName} is still processing the previous prompt`);
1984
2059
  }
1985
2060
  }
@@ -2369,10 +2444,23 @@ export class ProviderCliAdapter implements CliAdapter {
2369
2444
  getDebugState(): Record<string, any> {
2370
2445
  const screenText = sanitizeTerminalText(this.terminalScreen.getText());
2371
2446
  const startupModal = this.startupParseGate ? this.runParseApproval(this.recentOutputBuffer) : null;
2372
- const effectiveStatus = this.projectEffectiveStatus(startupModal);
2373
- const effectiveReady = this.ready || !!startupModal;
2447
+ const startupDetectedStatus = this.startupParseGate && !startupModal
2448
+ ? this.runDetectStatus(this.recentOutputBuffer || screenText)
2449
+ : null;
2450
+ const effectiveReady = this.ready || !!startupModal || startupDetectedStatus === 'waiting_approval';
2374
2451
  const parsedDebugState = this.getParsedDebugState();
2375
2452
  const parsedMessages = Array.isArray(parsedDebugState?.messages) ? parsedDebugState.messages : [];
2453
+ let effectiveStatus = this.projectEffectiveStatus(startupModal);
2454
+ if (startupDetectedStatus === 'waiting_approval') {
2455
+ effectiveStatus = 'waiting_approval';
2456
+ }
2457
+ if (
2458
+ effectiveStatus === 'idle'
2459
+ && parsedDebugState?.status === 'generating'
2460
+ && !this.parsedStatusHasFinalAssistantMessage(parsedDebugState)
2461
+ ) {
2462
+ effectiveStatus = 'generating';
2463
+ }
2376
2464
  return {
2377
2465
  type: this.cliType,
2378
2466
  name: this.cliName,
@@ -15,6 +15,7 @@ export declare function buildCliParseInput(options: {
15
15
  accumulatedRawBuffer: string;
16
16
  recentOutputBuffer: string;
17
17
  terminalScreenText: string;
18
+ workingDir?: string;
18
19
  baseMessages: CliChatMessage[];
19
20
  partialResponse: string;
20
21
  isWaitingForResponse?: boolean;
@@ -35,6 +35,7 @@ export function buildCliParseInput(options: {
35
35
  accumulatedRawBuffer: string;
36
36
  recentOutputBuffer: string;
37
37
  terminalScreenText: string;
38
+ workingDir?: string;
38
39
  baseMessages: CliChatMessage[];
39
40
  partialResponse: string;
40
41
  isWaitingForResponse?: boolean;
@@ -46,6 +47,7 @@ export function buildCliParseInput(options: {
46
47
  accumulatedRawBuffer,
47
48
  recentOutputBuffer,
48
49
  terminalScreenText,
50
+ workingDir,
49
51
  baseMessages,
50
52
  partialResponse,
51
53
  isWaitingForResponse,
@@ -66,6 +68,8 @@ export function buildCliParseInput(options: {
66
68
  rawBuffer,
67
69
  recentBuffer,
68
70
  screenText,
71
+ workspace: workingDir,
72
+ workingDir,
69
73
  screen: buildCliScreenSnapshot(screenText),
70
74
  bufferScreen: buildCliScreenSnapshot(buffer),
71
75
  recentScreen: buildCliScreenSnapshot(recentBuffer),
@@ -36,7 +36,9 @@ export function resolveCliSpawnPlan(options: {
36
36
  : spawnConfig.command;
37
37
  const binaryPath = findBinary(configuredCommand);
38
38
  const isWin = os.platform() === 'win32';
39
- const allArgs = [...spawnConfig.args, ...extraArgs];
39
+ const allArgs = [...spawnConfig.args, ...extraArgs].map((arg) =>
40
+ typeof arg === 'string' ? arg.replace(/\{\{workingDir\}\}/g, workingDir) : arg,
41
+ );
40
42
 
41
43
  let shellCmd: string;
42
44
  let shellArgs: string[];
@@ -55,6 +55,8 @@ export interface CliScriptInput {
55
55
  rawBuffer: string;
56
56
  recentBuffer: string;
57
57
  screenText: string;
58
+ workspace?: string;
59
+ workingDir?: string;
58
60
  screen: CliScreenSnapshot;
59
61
  bufferScreen: CliScreenSnapshot;
60
62
  recentScreen: CliScreenSnapshot;
@@ -94,6 +94,8 @@ export interface CliScriptInput {
94
94
  rawBuffer: string;
95
95
  recentBuffer: string;
96
96
  screenText: string;
97
+ workspace?: string;
98
+ workingDir?: string;
97
99
  screen: CliScreenSnapshot;
98
100
  bufferScreen: CliScreenSnapshot;
99
101
  recentScreen: CliScreenSnapshot;
@@ -484,17 +486,25 @@ export function findBinary(name: string): string {
484
486
  return path.isAbsolute(expanded) ? expanded : path.resolve(expanded);
485
487
  }
486
488
  const isWin = os.platform() === 'win32';
487
- try {
488
- const cmd = isWin ? `where ${trimmed}` : `which ${trimmed}`;
489
- return execSync(cmd, {
490
- encoding: 'utf-8',
491
- timeout: 5000,
492
- stdio: ['pipe', 'pipe', 'pipe'],
493
- ...(isWin ? { windowsHide: true } : {}),
494
- }).trim().split('\n')[0].trim();
495
- } catch {
496
- return isWin ? `${trimmed}.cmd` : trimmed;
489
+ const paths = (process.env.PATH || '').split(path.delimiter);
490
+ const exes = isWin ? ['.exe', '.cmd', '.bat', ''] : [''];
491
+
492
+ for (const p of paths) {
493
+ if (!p) continue;
494
+ for (const ext of exes) {
495
+ const fullPath = path.join(p, trimmed + ext);
496
+ try {
497
+ const fs = require('fs');
498
+ if (fs.existsSync(fullPath)) {
499
+ const stat = fs.statSync(fullPath);
500
+ if (stat.isFile() && (isWin || (stat.mode & 0o111))) {
501
+ return fullPath;
502
+ }
503
+ }
504
+ } catch { }
505
+ }
497
506
  }
507
+ return isWin ? `${trimmed}.cmd` : trimmed;
498
508
  }
499
509
 
500
510
  export function isScriptBinary(binaryPath: string): boolean {
@@ -24,6 +24,7 @@ import { filterUserFacingChatMessages, normalizeChatMessages } from '../provider
24
24
  const RECENT_SEND_WINDOW_MS = 1200;
25
25
  export const READ_CHAT_PROVIDER_EVAL_TIMEOUT_MS = 25_000;
26
26
  const HERMES_CLI_STARTING_SEND_SETTLE_MS = 2_000;
27
+ const CODEX_NATIVE_HISTORY_FRESH_MS = 5 * 60_000;
27
28
  const recentSendByTarget = new Map<string, number>();
28
29
 
29
30
  interface ApprovalSelectableInstance extends ProviderInstance {
@@ -221,6 +222,114 @@ function normalizeReadChatMessages(payload: Record<string, any>): ChatMessage[]
221
222
  return normalizeChatMessages(messages);
222
223
  }
223
224
 
225
+ function getMessageNewestReceivedAt(messages: Array<{ receivedAt?: unknown; timestamp?: unknown }>): number {
226
+ let newest = 0;
227
+ for (const message of messages) {
228
+ const receivedAt = Number(message?.receivedAt ?? message?.timestamp ?? 0);
229
+ if (Number.isFinite(receivedAt) && receivedAt > newest) newest = receivedAt;
230
+ }
231
+ return newest;
232
+ }
233
+
234
+ function buildCliMessageSourceProvenance(args: {
235
+ selected: 'native-history' | 'pty-parser';
236
+ provider: string;
237
+ nativeHandle?: string;
238
+ fallbackReason?: string;
239
+ nativeSource?: string;
240
+ sourcePath?: string;
241
+ sourceMtimeMs?: number;
242
+ nativeMessages?: ChatMessage[];
243
+ ptyMessages?: ChatMessage[];
244
+ returnedMessages?: ChatMessage[];
245
+ safeMapping?: boolean;
246
+ freshEnough?: boolean;
247
+ ptyStatusApprovalOnly?: boolean;
248
+ }): Record<string, unknown> {
249
+ const sourceMtimeMs = Number(args.sourceMtimeMs || 0);
250
+ const sourceMtimeAgeMs = sourceMtimeMs > 0 ? Math.max(0, Date.now() - sourceMtimeMs) : undefined;
251
+ const nativeMessages = args.nativeMessages || [];
252
+ const ptyMessages = args.ptyMessages || [];
253
+ const returnedMessages = args.returnedMessages || [];
254
+ return {
255
+ selected: args.selected,
256
+ provider: args.provider,
257
+ ...(args.nativeHandle ? { nativeHandle: args.nativeHandle } : {}),
258
+ ...(args.fallbackReason ? { fallbackReason: args.fallbackReason } : {}),
259
+ ...(args.nativeSource ? { nativeSource: args.nativeSource } : {}),
260
+ ...(args.sourcePath ? { sourcePath: args.sourcePath } : {}),
261
+ ptyStatusApprovalOnly: args.ptyStatusApprovalOnly === true,
262
+ staleness: {
263
+ sourceMtimeMs: sourceMtimeMs || undefined,
264
+ sourceMtimeAgeMs,
265
+ nativeNewestMessageAt: getMessageNewestReceivedAt(nativeMessages),
266
+ ptyNewestMessageAt: getMessageNewestReceivedAt(ptyMessages),
267
+ freshEnough: args.freshEnough === true,
268
+ },
269
+ coverage: {
270
+ nativeMessageCount: nativeMessages.length,
271
+ ptyMessageCount: ptyMessages.length,
272
+ returnedMessageCount: returnedMessages.length,
273
+ safeMapping: args.safeMapping === true,
274
+ },
275
+ };
276
+ }
277
+
278
+ function buildNativeHistoryFallbackReason(args: {
279
+ providerType: string;
280
+ nativeSource?: string;
281
+ nativeMessageCount: number;
282
+ safeMapping: boolean;
283
+ freshEnough: boolean;
284
+ }): string {
285
+ if (args.providerType !== 'codex-cli') return 'provider_not_codex_cli';
286
+ if (args.nativeSource === 'native-unavailable') return 'native_history_unavailable';
287
+ if (args.nativeSource && args.nativeSource !== 'provider-native') return `native_history_source_${args.nativeSource}`;
288
+ if (args.nativeMessageCount <= 0) return 'native_history_empty';
289
+ if (!args.safeMapping) return 'native_history_not_safely_mapped';
290
+ if (!args.freshEnough) return 'native_history_stale';
291
+ return 'native_history_not_selected';
292
+ }
293
+
294
+ function isCodexCliProvider(providerType: string): boolean {
295
+ return providerType === 'codex-cli';
296
+ }
297
+
298
+ function hasSafeNativeHistoryMapping(args: {
299
+ historySessionId?: string;
300
+ providerSessionId?: string;
301
+ workspace?: string;
302
+ nativeMessages: ChatMessage[];
303
+ }): boolean {
304
+ const explicitSessionId = String(args.historySessionId || args.providerSessionId || '').trim();
305
+ if (explicitSessionId) {
306
+ const messageSessionIds = args.nativeMessages
307
+ .map((message: any) => typeof message?.historySessionId === 'string' ? message.historySessionId.trim() : '')
308
+ .filter(Boolean);
309
+ if (messageSessionIds.length === 0) return true;
310
+ return messageSessionIds.some((id) => id === explicitSessionId);
311
+ }
312
+ const workspace = String(args.workspace || '').trim();
313
+ if (!workspace) return false;
314
+ return args.nativeMessages.some((message: any) => String(message?.workspace || '').trim() === workspace);
315
+ }
316
+
317
+ function isNativeHistoryFreshEnough(args: {
318
+ sourceMtimeMs?: number;
319
+ nativeMessages: ChatMessage[];
320
+ ptyMessages: ChatMessage[];
321
+ }): boolean {
322
+ const nativeNewest = getMessageNewestReceivedAt(args.nativeMessages);
323
+ const ptyNewest = getMessageNewestReceivedAt(args.ptyMessages);
324
+ if (nativeNewest > 0 && nativeNewest >= ptyNewest) return true;
325
+ const sourceMtimeMs = Number(args.sourceMtimeMs || 0);
326
+ if (sourceMtimeMs > 0 && Date.now() - sourceMtimeMs <= CODEX_NATIVE_HISTORY_FRESH_MS) return true;
327
+ return ptyNewest === 0 && nativeNewest > 0;
328
+ }
329
+
330
+ function shouldPreserveReadChatPayloadField(key: string): boolean {
331
+ return key === 'messageSource' || key === 'transcriptProvenance';
332
+ }
224
333
 
225
334
  function deriveHistoryDedupKey(message: ChatMessage & { _unitKey?: string; _turnKey?: string }): string | undefined {
226
335
  const unitKey = typeof message._unitKey === 'string' ? message._unitKey.trim() : '';
@@ -356,6 +465,7 @@ function buildReadChatCommandResult(payload: Record<string, any>, args: any): Co
356
465
  return {
357
466
  success: true,
358
467
  ...validatedPayload,
468
+ ...Object.fromEntries(Object.entries(payload).filter(([key]) => shouldPreserveReadChatPayloadField(key))),
359
469
  messages: sync.messages,
360
470
  totalMessages: sync.totalMessages,
361
471
  ...(returnedDebugReadChat ? { debugReadChat: returnedDebugReadChat } : {}),
@@ -584,6 +694,8 @@ function buildChatDebugBundleSummary(bundle: Record<string, unknown>): Record<st
584
694
  adapterStatus: debugReadChat.adapterStatus,
585
695
  parsedStatus: debugReadChat.parsedStatus,
586
696
  returnedStatus: debugReadChat.returnedStatus,
697
+ selectedMessageSource: debugReadChat.selectedMessageSource,
698
+ messageSource: debugReadChat.messageSource,
587
699
  parsedMsgCount: debugReadChat.parsedMsgCount,
588
700
  returnedMsgCount: debugReadChat.returnedMsgCount,
589
701
  shouldPreferAdapterMessages: debugReadChat.shouldPreferAdapterMessages,
@@ -646,6 +758,8 @@ export async function handleGetChatDebugBundle(h: CommandHelpers, args: any): Pr
646
758
  providerSessionId: readResult.providerSessionId,
647
759
  transcriptAuthority: readResult.transcriptAuthority,
648
760
  coverage: readResult.coverage,
761
+ messageSource: readResult.messageSource,
762
+ transcriptProvenance: readResult.transcriptProvenance,
649
763
  activeModal: readResult.activeModal,
650
764
  messagesTail: Array.isArray(readResult.messages) ? readResult.messages.slice(-20) : [],
651
765
  debugReadChat: readResult.debugReadChat,
@@ -882,25 +996,146 @@ export async function handleReadChat(h: CommandHelpers, args: any): Promise<Comm
882
996
  && typeof runtimeMessageMerger.mergeRuntimeChatMessages === 'function'
883
997
  ? runtimeMessageMerger.mergeRuntimeChatMessages(parsedMessages)
884
998
  : parsedMessages;
999
+ const providerType = provider?.type || adapter.cliType;
1000
+ let selectedMessages = returnedMessages;
1001
+ let selectedTitle = title;
1002
+ let selectedProviderSessionId = providerSessionId;
1003
+ let selectedTranscriptAuthority = transcriptAuthority;
1004
+ let selectedCoverage = coverage;
1005
+ let messageSource = buildCliMessageSourceProvenance({
1006
+ selected: 'pty-parser',
1007
+ provider: adapter.cliType,
1008
+ fallbackReason: isCodexCliProvider(providerType) ? 'native_history_not_checked' : 'provider_not_codex_cli',
1009
+ ptyMessages: returnedMessages,
1010
+ returnedMessages,
1011
+ ptyStatusApprovalOnly: false,
1012
+ });
1013
+
1014
+ if (isCodexCliProvider(providerType)) {
1015
+ const agentStr = provider?.type || args?.agentType || getCurrentProviderType(h, adapter.cliType);
1016
+ const workspace = typeof args?.workspace === 'string'
1017
+ ? args.workspace
1018
+ : typeof (h.currentSession as any)?.workspace === 'string'
1019
+ ? (h.currentSession as any).workspace
1020
+ : typeof adapter.workingDir === 'string'
1021
+ ? adapter.workingDir
1022
+ : undefined;
1023
+ const nativeHistoryLimit = Math.max(
1024
+ normalizeReadChatTailLimit(args) || 0,
1025
+ returnedMessages.length,
1026
+ 200,
1027
+ );
1028
+ let nativeHistory: ReturnType<typeof readProviderChatHistory> | null = null;
1029
+ try {
1030
+ nativeHistory = readProviderChatHistory(agentStr, {
1031
+ canonicalHistory: provider?.canonicalHistory,
1032
+ historySessionId,
1033
+ workspace,
1034
+ offset: 0,
1035
+ limit: nativeHistoryLimit,
1036
+ excludeRecentCount: 0,
1037
+ historyBehavior: provider?.historyBehavior,
1038
+ scripts: provider?.scripts as any,
1039
+ });
1040
+ } catch (error: any) {
1041
+ const fallbackReason = `native_history_error:${error?.message || String(error)}`;
1042
+ messageSource = buildCliMessageSourceProvenance({
1043
+ selected: 'pty-parser',
1044
+ provider: adapter.cliType,
1045
+ fallbackReason,
1046
+ ptyMessages: returnedMessages,
1047
+ returnedMessages,
1048
+ ptyStatusApprovalOnly: false,
1049
+ });
1050
+ nativeHistory = null;
1051
+ }
1052
+
1053
+ if (nativeHistory) {
1054
+ const nativeMessages = Array.isArray((nativeHistory as any).messages)
1055
+ ? normalizeChatMessages((nativeHistory as any).messages as ChatMessage[])
1056
+ : [];
1057
+ const historyProviderSessionId = typeof (nativeHistory as any)?.providerSessionId === 'string'
1058
+ ? (nativeHistory as any).providerSessionId
1059
+ : historySessionId;
1060
+ const safeMapping = hasSafeNativeHistoryMapping({
1061
+ historySessionId,
1062
+ providerSessionId,
1063
+ workspace,
1064
+ nativeMessages,
1065
+ });
1066
+ const freshEnough = isNativeHistoryFreshEnough({
1067
+ sourceMtimeMs: (nativeHistory as any).sourceMtimeMs,
1068
+ nativeMessages,
1069
+ ptyMessages: returnedMessages,
1070
+ });
1071
+ if ((nativeHistory as any).source === 'provider-native' && nativeMessages.length > 0 && safeMapping && freshEnough) {
1072
+ selectedMessages = finalizeStreamingMessagesWhenIdle(nativeMessages, returnedStatus);
1073
+ selectedProviderSessionId = historyProviderSessionId || providerSessionId;
1074
+ selectedTranscriptAuthority = 'provider';
1075
+ selectedCoverage = (nativeHistory as any).hasMore ? 'tail' : 'full';
1076
+ messageSource = buildCliMessageSourceProvenance({
1077
+ selected: 'native-history',
1078
+ provider: adapter.cliType,
1079
+ nativeHandle: selectedProviderSessionId || historySessionId,
1080
+ nativeSource: (nativeHistory as any).source,
1081
+ sourcePath: (nativeHistory as any).sourcePath,
1082
+ sourceMtimeMs: (nativeHistory as any).sourceMtimeMs,
1083
+ nativeMessages,
1084
+ ptyMessages: returnedMessages,
1085
+ returnedMessages: selectedMessages,
1086
+ safeMapping,
1087
+ freshEnough,
1088
+ ptyStatusApprovalOnly: true,
1089
+ });
1090
+ } else {
1091
+ const fallbackReason = buildNativeHistoryFallbackReason({
1092
+ providerType,
1093
+ nativeSource: (nativeHistory as any).source,
1094
+ nativeMessageCount: nativeMessages.length,
1095
+ safeMapping,
1096
+ freshEnough,
1097
+ });
1098
+ messageSource = buildCliMessageSourceProvenance({
1099
+ selected: 'pty-parser',
1100
+ provider: adapter.cliType,
1101
+ nativeHandle: historyProviderSessionId || historySessionId,
1102
+ fallbackReason,
1103
+ nativeSource: (nativeHistory as any).source,
1104
+ sourcePath: (nativeHistory as any).sourcePath,
1105
+ sourceMtimeMs: (nativeHistory as any).sourceMtimeMs,
1106
+ nativeMessages,
1107
+ ptyMessages: returnedMessages,
1108
+ returnedMessages,
1109
+ safeMapping,
1110
+ freshEnough,
1111
+ ptyStatusApprovalOnly: false,
1112
+ });
1113
+ }
1114
+ }
1115
+ }
885
1116
  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
1117
  return buildReadChatCommandResult({
887
- messages: returnedMessages,
1118
+ messages: selectedMessages,
888
1119
  status: returnedStatus,
889
1120
  activeModal,
1121
+ messageSource,
1122
+ transcriptProvenance: messageSource,
890
1123
  debugReadChat: {
891
1124
  provider: adapter.cliType,
892
1125
  targetSessionId: String(args?.targetSessionId || ''),
893
1126
  adapterStatus: String(adapterStatus.status || ''),
894
1127
  parsedStatus: String(parsedRecord.status || ''),
895
1128
  returnedStatus: String(returnedStatus || ''),
896
- shouldPreferAdapterMessages: false,
1129
+ selectedMessageSource: (messageSource as any).selected,
1130
+ messageSource,
1131
+ shouldPreferAdapterMessages: (messageSource as any).selected !== 'native-history',
897
1132
  parsedMsgCount: parsedRecord.messages.length,
898
- returnedMsgCount: returnedMessages.length,
1133
+ returnedMsgCount: selectedMessages.length,
899
1134
  },
900
- ...(title ? { title } : {}),
901
- ...(providerSessionId ? { providerSessionId } : {}),
902
- ...(transcriptAuthority ? { transcriptAuthority } : {}),
903
- ...(coverage ? { coverage } : {}),
1135
+ ...(selectedTitle ? { title: selectedTitle } : {}),
1136
+ ...(selectedProviderSessionId ? { providerSessionId: selectedProviderSessionId } : {}),
1137
+ ...(selectedTranscriptAuthority ? { transcriptAuthority: selectedTranscriptAuthority } : {}),
1138
+ ...(selectedCoverage ? { coverage: selectedCoverage } : {}),
904
1139
  }, args);
905
1140
  }
906
1141
  const historyLimit = normalizeReadChatTailLimit(args);
@@ -80,6 +80,56 @@ export interface CliManagerDeps {
80
80
 
81
81
  type CommandResult = { success: boolean;[key: string]: unknown };
82
82
 
83
+ const BUSY_AGENT_STATUSES = new Set(['generating', 'running', 'streaming', 'starting', 'busy', 'waiting', 'waiting_approval', 'long_generating']);
84
+
85
+ function normalizeAgentStatus(value: unknown): string {
86
+ return typeof value === 'string' ? value.trim().toLowerCase() : '';
87
+ }
88
+
89
+ function hasNonEmptyModalButtons(activeModal: unknown): boolean {
90
+ const buttons = (activeModal as any)?.buttons;
91
+ return Array.isArray(buttons) && buttons.some((button) => String(button || '').trim().length > 0);
92
+ }
93
+
94
+ function hasAdapterPendingResponse(adapter: any): boolean {
95
+ if (adapter?.isWaitingForResponse === true) return true;
96
+ if (adapter?.currentTurnScope) return true;
97
+ try {
98
+ if (typeof adapter?.isProcessing === 'function' && adapter.isProcessing()) return true;
99
+ } catch { /* defensive: send guard should not fail on diagnostics */ }
100
+ try {
101
+ const partial = typeof adapter?.getPartialResponse === 'function' ? adapter.getPartialResponse() : '';
102
+ if (typeof partial === 'string' && partial.trim()) return true;
103
+ } catch { /* defensive: missing partial means no pending evidence */ }
104
+ return false;
105
+ }
106
+
107
+ function shouldSuppressStaleParsedBusyStatus(adapterStatus: string, parsedStatus: any, adapter: any): boolean {
108
+ const parsedRawStatus = normalizeAgentStatus(parsedStatus?.status);
109
+ if (!BUSY_AGENT_STATUSES.has(parsedRawStatus)) return false;
110
+ if (adapterStatus !== 'idle') return false;
111
+ if (hasNonEmptyModalButtons(parsedStatus?.activeModal ?? parsedStatus?.modal)) return false;
112
+ return !hasAdapterPendingResponse(adapter);
113
+ }
114
+
115
+ function getEffectiveAgentSendStatus(adapter: any): string {
116
+ const adapterStatus = normalizeAgentStatus(adapter?.getStatus?.({ allowParse: false })?.status ?? adapter?.getStatus?.()?.status);
117
+ if (adapterStatus && adapterStatus !== 'idle') return adapterStatus;
118
+ if (adapterStatus !== 'idle') return adapterStatus;
119
+
120
+ if (typeof adapter?.getScriptParsedStatus !== 'function') return adapterStatus;
121
+ try {
122
+ const parsedStatus = adapter.getScriptParsedStatus();
123
+ const parsedRawStatus = normalizeAgentStatus(parsedStatus?.status);
124
+ if (BUSY_AGENT_STATUSES.has(parsedRawStatus) && !shouldSuppressStaleParsedBusyStatus(adapterStatus, parsedStatus, adapter)) {
125
+ return parsedRawStatus;
126
+ }
127
+ } catch {
128
+ return adapterStatus;
129
+ }
130
+ return adapterStatus;
131
+ }
132
+
83
133
  export interface CliTransportFactoryParams {
84
134
  runtimeId: string;
85
135
  providerType: string;
@@ -1073,6 +1123,19 @@ export class DaemonCliManager {
1073
1123
  const { adapter, key } = found;
1074
1124
 
1075
1125
  if (action === 'send_chat') {
1126
+ const currentStatus = getEffectiveAgentSendStatus(adapter);
1127
+ if (BUSY_AGENT_STATUSES.has(currentStatus)) {
1128
+ return {
1129
+ success: false,
1130
+ code: 'agent_runtime_busy',
1131
+ reason: 'agent_runtime_busy',
1132
+ retryable: true,
1133
+ retryRecommended: true,
1134
+ status: currentStatus,
1135
+ targetSessionId: args?.targetSessionId,
1136
+ error: `CLI agent '${agentType}' is currently ${currentStatus}; retry after the current turn finishes.`,
1137
+ };
1138
+ }
1076
1139
  const input = normalizeInputEnvelope(args?.input ? { input: args.input } : args);
1077
1140
  const provider = this.providerLoader.resolve(agentType) || this.providerLoader.getMeta(agentType);
1078
1141
  if (provider?.category === 'acp') {
@@ -408,12 +408,19 @@ export class DaemonCommandHandler implements CommandHelpers {
408
408
  'invoke_provider_script',
409
409
  ]);
410
410
 
411
+ // read_chat and get_chat_debug_bundle can serve historical transcript data even
412
+ // when the live session record is gone (stopped/destroyed). Allow the fallback
413
+ // when the provider type is known and any session identity hint is present:
414
+ // an explicit providerSessionId/historySessionId, or the targetSessionId itself
415
+ // (which getHistorySessionId already uses as a fallback history key).
416
+ const isReadOrDebugCmd = cmd === 'read_chat' || cmd === 'get_chat_debug_bundle';
411
417
  const allowsInactiveReadChatFallback =
412
- cmd === 'read_chat'
418
+ isReadOrDebugCmd
413
419
  && !!this._currentRoute.providerType
414
420
  && (
415
421
  (typeof args?.providerSessionId === 'string' && args.providerSessionId.trim().length > 0)
416
422
  || (typeof args?.historySessionId === 'string' && args.historySessionId.trim().length > 0)
423
+ || (typeof args?.targetSessionId === 'string' && args.targetSessionId.trim().length > 0)
417
424
  );
418
425
 
419
426
  if (this._currentRoute.sessionLookupFailed && sessionScopedCommands.has(cmd) && !allowsInactiveReadChatFallback) {