@adhdev/daemon-core 0.9.82-rc.44 → 0.9.82-rc.441

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 (425) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +9 -0
  2. package/dist/boot/process-hardening.d.ts +50 -0
  3. package/dist/build-info.d.ts +37 -0
  4. package/dist/chat/source-machine.d.ts +166 -0
  5. package/dist/chat/source-resolver.d.ts +104 -0
  6. package/dist/chat/subscription-updates.d.ts +1 -0
  7. package/dist/cli-adapter-types.d.ts +68 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +200 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +126 -64
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +5 -0
  12. package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
  13. package/dist/cli-adapters/provider-cli-shared.d.ts +74 -0
  14. package/dist/cli-adapters/pty-write-chunking.d.ts +34 -0
  15. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  16. package/dist/cli-adapters/resolve-executable.d.ts +69 -0
  17. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  18. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  19. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  20. package/dist/commands/chat-commands-debug-bundle.d.ts +14 -0
  21. package/dist/commands/chat-commands-read.d.ts +7 -0
  22. package/dist/commands/chat-commands-scope.d.ts +39 -0
  23. package/dist/commands/chat-commands-shared.d.ts +33 -0
  24. package/dist/commands/chat-commands-write.d.ts +14 -0
  25. package/dist/commands/chat-commands.d.ts +10 -23
  26. package/dist/commands/cli-manager.d.ts +15 -1
  27. package/dist/commands/handler.d.ts +125 -0
  28. package/dist/commands/high-family/index.d.ts +3 -0
  29. package/dist/commands/high-family/mesh-coordinator-launch.d.ts +2 -0
  30. package/dist/commands/high-family/mesh-events.d.ts +2 -0
  31. package/dist/commands/high-family/mesh-status.d.ts +2 -0
  32. package/dist/commands/high-family/types.d.ts +60 -0
  33. package/dist/commands/low-family/coordinator-prompt.d.ts +9 -0
  34. package/dist/commands/low-family/daemon-lifecycle.d.ts +2 -0
  35. package/dist/commands/low-family/diagnostics.d.ts +2 -0
  36. package/dist/commands/low-family/index.d.ts +3 -0
  37. package/dist/commands/low-family/mesh-ledger.d.ts +10 -0
  38. package/dist/commands/low-family/mesh-node-logs.d.ts +2 -0
  39. package/dist/commands/low-family/notification.d.ts +2 -0
  40. package/dist/commands/low-family/refine-config.d.ts +2 -0
  41. package/dist/commands/low-family/session-host.d.ts +2 -0
  42. package/dist/commands/low-family/spec-providerdev.d.ts +11 -0
  43. package/dist/commands/low-family/status-meta.d.ts +2 -0
  44. package/dist/commands/low-family/types.d.ts +33 -0
  45. package/dist/commands/med-family/cli-agent.d.ts +2 -0
  46. package/dist/commands/med-family/fast-forward.d.ts +2 -0
  47. package/dist/commands/med-family/ide.d.ts +10 -0
  48. package/dist/commands/med-family/index.d.ts +3 -0
  49. package/dist/commands/med-family/mesh-crud.d.ts +29 -0
  50. package/dist/commands/med-family/mesh-host-pairing.d.ts +2 -0
  51. package/dist/commands/med-family/mesh-queue.d.ts +2 -0
  52. package/dist/commands/med-family/mesh-restart.d.ts +2 -0
  53. package/dist/commands/med-family/types.d.ts +142 -0
  54. package/dist/commands/mesh-coordinator.d.ts +85 -1
  55. package/dist/commands/router.d.ts +276 -2
  56. package/dist/commands/upgrade-helper.d.ts +41 -1
  57. package/dist/config/chat-history.d.ts +9 -0
  58. package/dist/config/config.d.ts +5 -0
  59. package/dist/config/mesh-config.d.ts +120 -1
  60. package/dist/config/mesh-json-config.d.ts +199 -0
  61. package/dist/config/repo-settings.d.ts +77 -0
  62. package/dist/daemon/dev-server.d.ts +0 -2
  63. package/dist/detection/ide-detector.d.ts +13 -0
  64. package/dist/detection/win32-ide-version.d.ts +37 -0
  65. package/dist/git/change-impact-config.d.ts +159 -0
  66. package/dist/git/git-commands.d.ts +11 -1
  67. package/dist/git/git-diff.d.ts +6 -0
  68. package/dist/git/git-executor.d.ts +11 -0
  69. package/dist/git/git-status.d.ts +57 -0
  70. package/dist/git/git-types.d.ts +2 -50
  71. package/dist/git/git-worktree.d.ts +71 -1
  72. package/dist/git/index.d.ts +3 -1
  73. package/dist/index.d.ts +64 -14
  74. package/dist/index.js +50719 -20120
  75. package/dist/index.js.map +1 -1
  76. package/dist/index.mjs +50317 -19882
  77. package/dist/index.mjs.map +1 -1
  78. package/dist/installer.d.ts +1 -4
  79. package/dist/ipc/local-ipc-server.d.ts +91 -0
  80. package/dist/launch.d.ts +1 -1
  81. package/dist/logging/async-batch-writer.d.ts +10 -0
  82. package/dist/logging/log-redactor.d.ts +24 -0
  83. package/dist/logging/log-tail-reader.d.ts +81 -0
  84. package/dist/logging/logger.d.ts +1 -1
  85. package/dist/mesh/contracts.d.ts +164 -0
  86. package/dist/mesh/coordinator-prompt.d.ts +89 -0
  87. package/dist/mesh/coordinator-registry.d.ts +59 -0
  88. package/dist/mesh/mesh-active-work.d.ts +174 -0
  89. package/dist/mesh/mesh-clone-grace.d.ts +8 -0
  90. package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
  91. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  92. package/dist/mesh/mesh-event-classify.d.ts +5 -0
  93. package/dist/mesh/mesh-event-forwarding.d.ts +41 -0
  94. package/dist/mesh/mesh-event-trace.d.ts +21 -0
  95. package/dist/mesh/mesh-events-coordinator.d.ts +4 -0
  96. package/dist/mesh/mesh-events-pending.d.ts +69 -0
  97. package/dist/mesh/mesh-events-stale.d.ts +61 -0
  98. package/dist/mesh/mesh-events-utils.d.ts +75 -0
  99. package/dist/mesh/mesh-events.d.ts +6 -49
  100. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  101. package/dist/mesh/mesh-host-ownership.d.ts +29 -0
  102. package/dist/mesh/mesh-init.d.ts +128 -0
  103. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -4
  104. package/dist/mesh/mesh-ledger.d.ts +77 -1
  105. package/dist/mesh/mesh-magi-status.d.ts +63 -0
  106. package/dist/mesh/mesh-missions.d.ts +189 -0
  107. package/dist/mesh/mesh-node-identity.d.ts +289 -0
  108. package/dist/mesh/mesh-queue-assignment.d.ts +113 -0
  109. package/dist/mesh/mesh-reconcile-loop.d.ts +65 -0
  110. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  111. package/dist/mesh/mesh-refine-gates.d.ts +428 -0
  112. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  113. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  114. package/dist/mesh/mesh-routing.d.ts +70 -0
  115. package/dist/mesh/mesh-runtime-store.d.ts +450 -0
  116. package/dist/mesh/mesh-scheduling-runtime.d.ts +78 -0
  117. package/dist/mesh/mesh-task-inflight.d.ts +46 -0
  118. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  119. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  120. package/dist/mesh/mesh-warmup-deadline.d.ts +68 -0
  121. package/dist/mesh/mesh-work-queue.d.ts +300 -5
  122. package/dist/mesh/preview-freshness.d.ts +18 -0
  123. package/dist/mesh/refine-config.d.ts +216 -0
  124. package/dist/mesh/worktree-bootstrap-config.d.ts +145 -0
  125. package/dist/providers/acp-provider-instance.d.ts +5 -0
  126. package/dist/providers/approval-utils.d.ts +20 -0
  127. package/dist/providers/chat-message-normalization.d.ts +31 -1
  128. package/dist/providers/cli-provider-instance.d.ts +252 -3
  129. package/dist/providers/contracts.d.ts +149 -6
  130. package/dist/providers/external-sources.d.ts +71 -0
  131. package/dist/providers/manual-attendance.d.ts +63 -0
  132. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  133. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  134. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  135. package/dist/providers/native-history/constants.d.ts +12 -0
  136. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  137. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  138. package/dist/providers/native-history/index.d.ts +13 -0
  139. package/dist/providers/provider-instance-manager.d.ts +29 -0
  140. package/dist/providers/provider-instance.d.ts +23 -1
  141. package/dist/providers/provider-loader.d.ts +26 -4
  142. package/dist/providers/provider-trust.d.ts +31 -0
  143. package/dist/providers/read-chat-contract.d.ts +29 -0
  144. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  145. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
  146. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  147. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  148. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  149. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  150. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  151. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  152. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  153. package/dist/providers/sdk/v1/index.d.ts +30 -0
  154. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  155. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  156. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  157. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  158. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  159. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  160. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  161. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  162. package/dist/providers/spec/adapter.d.ts +91 -0
  163. package/dist/providers/spec/cli-adapter.d.ts +223 -0
  164. package/dist/providers/spec/evaluator.d.ts +45 -0
  165. package/dist/providers/spec/fsm-driver.d.ts +422 -0
  166. package/dist/providers/spec/fsm-evaluator.d.ts +76 -0
  167. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  168. package/dist/providers/spec/fsm-types.d.ts +174 -0
  169. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  170. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  171. package/dist/providers/spec/route.d.ts +4 -0
  172. package/dist/providers/spec/types.d.ts +222 -0
  173. package/dist/providers/status-monitor.d.ts +7 -7
  174. package/dist/providers/transcript-v2.d.ts +176 -0
  175. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  176. package/dist/providers/working-dir.d.ts +17 -0
  177. package/dist/repo-mesh-types.d.ts +509 -13
  178. package/dist/runtime-defaults.d.ts +2 -0
  179. package/dist/sessions/registry.d.ts +6 -0
  180. package/dist/shared-types-extra.d.ts +2 -4
  181. package/dist/shared-types.d.ts +59 -2
  182. package/dist/status/normalize.d.ts +1 -1
  183. package/dist/status/normalize.js +1 -0
  184. package/dist/status/normalize.js.map +1 -1
  185. package/dist/status/normalize.mjs +1 -0
  186. package/dist/status/normalize.mjs.map +1 -1
  187. package/dist/status/reporter.d.ts +2 -0
  188. package/dist/status/snapshot.d.ts +26 -0
  189. package/dist/system/hash.d.ts +8 -0
  190. package/dist/system/load-better-sqlite3.d.ts +21 -0
  191. package/dist/types.d.ts +5 -0
  192. package/package.json +7 -3
  193. package/src/agent-stream/poller.ts +2 -3
  194. package/src/agent-stream/provider-adapter.ts +1 -1
  195. package/src/boot/daemon-lifecycle.ts +63 -12
  196. package/src/boot/process-hardening.ts +89 -0
  197. package/src/build-info.ts +73 -0
  198. package/src/chat/source-machine.ts +534 -0
  199. package/src/chat/source-resolver.ts +0 -0
  200. package/src/chat/subscription-updates.ts +20 -1
  201. package/src/cli-adapter-types.d.ts +3 -1
  202. package/src/cli-adapter-types.ts +68 -2
  203. package/src/cli-adapters/cli-script-runner.ts +421 -0
  204. package/src/cli-adapters/cli-state-engine.ts +1246 -0
  205. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  206. package/src/cli-adapters/provider-cli-adapter.ts +914 -1144
  207. package/src/cli-adapters/provider-cli-parse.d.ts +2 -0
  208. package/src/cli-adapters/provider-cli-parse.ts +19 -0
  209. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  210. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  211. package/src/cli-adapters/provider-cli-shared.ts +121 -11
  212. package/src/cli-adapters/pty-transport.ts +2 -1
  213. package/src/cli-adapters/pty-write-chunking.ts +106 -0
  214. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  215. package/src/cli-adapters/resolve-executable.ts +204 -0
  216. package/src/cli-adapters/session-host-transport.ts +2 -1
  217. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +63 -29
  218. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  219. package/src/cli-adapters/terminal-screen.ts +16 -81
  220. package/src/commands/WINDOWS-UPGRADE-LOCK-FAILURE.md +198 -0
  221. package/src/commands/chat-commands-debug-bundle.ts +398 -0
  222. package/src/commands/chat-commands-read.ts +2447 -0
  223. package/src/commands/chat-commands-scope.ts +54 -0
  224. package/src/commands/chat-commands-shared.ts +114 -0
  225. package/src/commands/chat-commands-write.ts +891 -0
  226. package/src/commands/chat-commands.ts +19 -1841
  227. package/src/commands/cli-manager.ts +572 -27
  228. package/src/commands/handler.ts +841 -2
  229. package/src/commands/high-family/index.ts +28 -0
  230. package/src/commands/high-family/mesh-coordinator-launch.ts +678 -0
  231. package/src/commands/high-family/mesh-events.ts +80 -0
  232. package/src/commands/high-family/mesh-status.ts +714 -0
  233. package/src/commands/high-family/types.ts +76 -0
  234. package/src/commands/low-family/coordinator-prompt.ts +72 -0
  235. package/src/commands/low-family/daemon-lifecycle.ts +107 -0
  236. package/src/commands/low-family/diagnostics.ts +57 -0
  237. package/src/commands/low-family/index.ts +37 -0
  238. package/src/commands/low-family/mesh-ledger.ts +62 -0
  239. package/src/commands/low-family/mesh-node-logs.ts +87 -0
  240. package/src/commands/low-family/notification.ts +116 -0
  241. package/src/commands/low-family/refine-config.ts +106 -0
  242. package/src/commands/low-family/session-host.ts +274 -0
  243. package/src/commands/low-family/spec-providerdev.ts +217 -0
  244. package/src/commands/low-family/status-meta.ts +112 -0
  245. package/src/commands/low-family/types.ts +39 -0
  246. package/src/commands/med-family/cli-agent.ts +238 -0
  247. package/src/commands/med-family/fast-forward.ts +230 -0
  248. package/src/commands/med-family/ide.ts +163 -0
  249. package/src/commands/med-family/index.ts +37 -0
  250. package/src/commands/med-family/mesh-crud.ts +1242 -0
  251. package/src/commands/med-family/mesh-host-pairing.ts +234 -0
  252. package/src/commands/med-family/mesh-queue.ts +167 -0
  253. package/src/commands/med-family/mesh-restart.ts +92 -0
  254. package/src/commands/med-family/types.ts +143 -0
  255. package/src/commands/mesh-coordinator.ts +334 -124
  256. package/src/commands/router.ts +2846 -3484
  257. package/src/commands/stream-commands.ts +8 -0
  258. package/src/commands/upgrade-helper.ts +310 -45
  259. package/src/config/chat-history.ts +493 -24
  260. package/src/config/config.ts +12 -0
  261. package/src/config/mesh-config.ts +593 -22
  262. package/src/config/mesh-json-config.ts +376 -0
  263. package/src/config/recent-activity.ts +8 -2
  264. package/src/config/repo-settings.ts +111 -0
  265. package/src/daemon/dev-auto-implement.ts +3 -2
  266. package/src/daemon/dev-cli-debug.ts +10 -1
  267. package/src/daemon/dev-server.ts +0 -541
  268. package/src/detection/cli-detector.ts +28 -9
  269. package/src/detection/ide-detector.ts +55 -16
  270. package/src/detection/win32-ide-version.ts +106 -0
  271. package/src/git/change-impact-config.ts +354 -0
  272. package/src/git/git-commands.ts +59 -15
  273. package/src/git/git-diff.ts +81 -11
  274. package/src/git/git-executor.ts +12 -0
  275. package/src/git/git-status.ts +767 -48
  276. package/src/git/git-types.ts +14 -62
  277. package/src/git/git-worktree.ts +261 -4
  278. package/src/git/index.ts +17 -0
  279. package/src/index.ts +196 -12
  280. package/src/installer.d.ts +1 -1
  281. package/src/installer.ts +8 -6
  282. package/src/ipc/local-ipc-server.ts +278 -0
  283. package/src/launch.d.ts +1 -1
  284. package/src/launch.ts +37 -28
  285. package/src/logging/async-batch-writer.ts +55 -0
  286. package/src/logging/command-log.ts +7 -5
  287. package/src/logging/log-redactor.ts +100 -0
  288. package/src/logging/log-tail-reader.ts +341 -0
  289. package/src/logging/logger.ts +14 -7
  290. package/src/mesh/contracts.ts +338 -0
  291. package/src/mesh/coordinator-prompt.ts +415 -34
  292. package/src/mesh/coordinator-registry.ts +121 -0
  293. package/src/mesh/mesh-active-work.ts +645 -0
  294. package/src/mesh/mesh-clone-grace.ts +68 -0
  295. package/src/mesh/mesh-coordinator-config.ts +97 -0
  296. package/src/mesh/mesh-delivery-policy.ts +315 -0
  297. package/src/mesh/mesh-event-classify.ts +51 -0
  298. package/src/mesh/mesh-event-forwarding.ts +1897 -0
  299. package/src/mesh/mesh-event-trace.ts +67 -0
  300. package/src/mesh/mesh-events-coordinator.ts +32 -0
  301. package/src/mesh/mesh-events-pending.ts +656 -0
  302. package/src/mesh/mesh-events-stale.ts +389 -0
  303. package/src/mesh/mesh-events-utils.ts +443 -0
  304. package/src/mesh/mesh-events.ts +33 -1035
  305. package/src/mesh/mesh-fast-forward.ts +843 -0
  306. package/src/mesh/mesh-host-ownership.ts +111 -0
  307. package/src/mesh/mesh-init.ts +350 -0
  308. package/src/mesh/mesh-ledger-reconciliation.ts +12 -7
  309. package/src/mesh/mesh-ledger.ts +656 -102
  310. package/src/mesh/mesh-magi-status.ts +223 -0
  311. package/src/mesh/mesh-missions.ts +449 -0
  312. package/src/mesh/mesh-node-identity.ts +1887 -0
  313. package/src/mesh/mesh-queue-assignment.ts +1924 -0
  314. package/src/mesh/mesh-reconcile-loop.ts +1997 -0
  315. package/src/mesh/mesh-refine-batch.ts +205 -0
  316. package/src/mesh/mesh-refine-gates.ts +1673 -0
  317. package/src/mesh/mesh-refine-status.ts +231 -0
  318. package/src/mesh/mesh-review-inbox.ts +307 -0
  319. package/src/mesh/mesh-routing.ts +291 -0
  320. package/src/mesh/mesh-runtime-store.ts +1853 -0
  321. package/src/mesh/mesh-scheduling-runtime.ts +198 -0
  322. package/src/mesh/mesh-task-inflight.ts +70 -0
  323. package/src/mesh/mesh-task-stats.ts +161 -0
  324. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  325. package/src/mesh/mesh-warmup-deadline.ts +152 -0
  326. package/src/mesh/mesh-work-queue.ts +1254 -141
  327. package/src/mesh/preview-freshness.ts +118 -0
  328. package/src/mesh/refine-config.ts +423 -0
  329. package/src/mesh/worktree-bootstrap-config.ts +450 -0
  330. package/src/providers/acp-provider-instance.ts +43 -10
  331. package/src/providers/approval-utils.d.ts +5 -0
  332. package/src/providers/approval-utils.ts +57 -5
  333. package/src/providers/chat-message-normalization.ts +92 -4
  334. package/src/providers/cli-provider-instance.ts +2001 -106
  335. package/src/providers/contracts.d.ts +55 -0
  336. package/src/providers/contracts.ts +160 -6
  337. package/src/providers/extension-provider-instance.ts +12 -7
  338. package/src/providers/external-sources.ts +218 -0
  339. package/src/providers/ide-provider-instance.ts +35 -12
  340. package/src/providers/manual-attendance.ts +85 -0
  341. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  342. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  343. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  344. package/src/providers/native-history/constants.ts +19 -0
  345. package/src/providers/native-history/dispatcher.ts +345 -0
  346. package/src/providers/native-history/hermes-cli-transcript.ts +260 -0
  347. package/src/providers/native-history/index.ts +30 -0
  348. package/src/providers/provider-instance-manager.ts +71 -0
  349. package/src/providers/provider-instance.ts +19 -1
  350. package/src/providers/provider-loader.ts +668 -50
  351. package/src/providers/provider-schema.ts +87 -14
  352. package/src/providers/provider-trust.ts +114 -0
  353. package/src/providers/read-chat-contract.ts +76 -16
  354. package/src/providers/sdk/README.md +49 -0
  355. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  356. package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
  357. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  358. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  359. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  360. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  361. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  362. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  363. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  364. package/src/providers/sdk/v1/index.ts +152 -0
  365. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  366. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  367. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  368. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +509 -0
  369. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  370. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  371. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  372. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  373. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  374. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  375. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  376. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  377. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  378. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  379. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  380. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  381. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  382. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  383. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  384. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  385. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  386. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  387. package/src/providers/sdk/v1/validators/index.ts +19 -0
  388. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  389. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  390. package/src/providers/spec/adapter.ts +235 -0
  391. package/src/providers/spec/cli-adapter.ts +1056 -0
  392. package/src/providers/spec/evaluator.ts +407 -0
  393. package/src/providers/spec/fsm-driver.ts +1410 -0
  394. package/src/providers/spec/fsm-evaluator.ts +272 -0
  395. package/src/providers/spec/fsm-loader.ts +120 -0
  396. package/src/providers/spec/fsm-types.ts +273 -0
  397. package/src/providers/spec/native-history-executor.ts +1143 -0
  398. package/src/providers/spec/pre-launch-trust.ts +104 -0
  399. package/src/providers/spec/route.ts +51 -0
  400. package/src/providers/spec/types.ts +262 -0
  401. package/src/providers/status-monitor.d.ts +7 -7
  402. package/src/providers/status-monitor.ts +37 -22
  403. package/src/providers/transcript-v2.ts +567 -0
  404. package/src/providers/types/interactive-prompt.ts +536 -0
  405. package/src/providers/version-archive.ts +64 -24
  406. package/src/providers/working-dir.ts +23 -0
  407. package/src/repo-mesh-types.ts +748 -14
  408. package/src/runtime-defaults.ts +39 -0
  409. package/src/sessions/registry.ts +6 -0
  410. package/src/shared-types-extra.ts +2 -4
  411. package/src/shared-types.d.ts +8 -0
  412. package/src/shared-types.ts +64 -1
  413. package/src/status/builders.ts +26 -6
  414. package/src/status/normalize.ts +2 -0
  415. package/src/status/reporter.ts +19 -1
  416. package/src/status/snapshot.ts +95 -26
  417. package/src/system/hash.ts +23 -0
  418. package/src/system/host-memory.ts +29 -12
  419. package/src/system/load-better-sqlite3.ts +68 -0
  420. package/src/types.ts +5 -0
  421. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  422. package/dist/mesh/mesh-sync.d.ts +0 -53
  423. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  424. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  425. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,1246 @@
1
+ /**
2
+ * CliStateEngine — CLI provider status state machine
3
+ *
4
+ * Owns all status-transition logic, timer management, and script-driven
5
+ * evaluation. Reads buffer state from the transport and writes to PTY via
6
+ * the transport interface — adapter stays as pure I/O layer.
7
+ */
8
+
9
+ import { LOG } from '../logging/logger.js';
10
+ import {
11
+ buildCliParseInput,
12
+ normalizeCliParsedMessages,
13
+ type TurnParseScope,
14
+ } from './provider-cli-parse.js';
15
+ import {
16
+ buildCliScreenSnapshot,
17
+ compactPromptText,
18
+ normalizePromptText,
19
+ promptLikelyVisible,
20
+ type CliChatMessage,
21
+ type CliProviderModule,
22
+ type CliSessionStatus,
23
+ type CliTraceEntry,
24
+ type ParsedSession,
25
+ } from './provider-cli-shared.js';
26
+ import type { CliScriptRunner } from './cli-script-runner.js';
27
+
28
+ // ─── Types ─────────────────────────────────────────────────────────────────
29
+
30
+ export interface CliBufferSnapshot {
31
+ accumulatedBuffer: string;
32
+ accumulatedRawBuffer: string;
33
+ recentOutputBuffer: string;
34
+ responseBuffer: string;
35
+ screenText: string;
36
+ parseScreenText: string;
37
+ workingDir: string;
38
+ providerSessionId: string | null;
39
+ runtimeSettings: Record<string, any>;
40
+ isWaitingForResponse: boolean;
41
+ currentTurnScope: TurnParseScope | null;
42
+ lastOutputAt: number;
43
+ lastNonEmptyOutputAt: number;
44
+ lastScreenChangeAt: number;
45
+ lastScreenSnapshot: string;
46
+ }
47
+
48
+ /** What the engine needs from the transport layer */
49
+ export interface CliTransportAccess {
50
+ getSnapshot(): CliBufferSnapshot;
51
+ writeRaw(data: string | Buffer): void;
52
+ getApprovalKeyForIndex(buttonIndex: number): string | undefined;
53
+ flushOutboundQueue(): void;
54
+ isAlive(): boolean;
55
+ /** Optional: override script dispatch (used by tests to mock detection) */
56
+ runDetectStatus?(text: string): string | null;
57
+ /** Optional: override script dispatch (used by tests to mock approval) */
58
+ runParseApproval?(tail: string): { message: string; buttons: string[] } | null;
59
+ /** Optional: override full session parse (used by tests to mock parsing) */
60
+ runParseSession?(): ParsedSession | null;
61
+ /** Optional: provider type override — used when tests patch the adapter's cliType */
62
+ cliType?: string;
63
+ }
64
+
65
+ export interface CliStateEngineCallbacks {
66
+ onStatusChange(): void;
67
+ onApplyParsedSession(session: ParsedSession): void;
68
+ onTurnCompleted(): void;
69
+ }
70
+
71
+ interface IdleFinishCandidate {
72
+ armedAt: number;
73
+ lastOutputAt: number;
74
+ lastScreenChangeAt: number;
75
+ responseEpoch: number;
76
+ assistantLength: number;
77
+ }
78
+
79
+ interface SettledEvalContext {
80
+ now: number;
81
+ modal: { message: string; buttons: string[] } | null;
82
+ status: string;
83
+ parsedMessages: CliChatMessage[];
84
+ lastParsedAssistant: CliChatMessage | undefined;
85
+ parsedStatus: string | null;
86
+ prevStatus: string;
87
+ }
88
+
89
+ // ─── Constants ─────────────────────────────────────────────────────────────
90
+
91
+ const SCRIPT_STATUS_DEBOUNCE_MS = 3000;
92
+ const MAX_FINISH_RETRIES = 2;
93
+ const FINISH_RETRY_DELAY_MS = 300;
94
+ const MAX_TRACE_ENTRIES = 250;
95
+ const APPROVAL_EXIT_TIMEOUT_MS = 60_000;
96
+ const IDLE_CONFIRMATION_GRACE_MS = 2_000;
97
+
98
+ // ─── Engine ────────────────────────────────────────────────────────────────
99
+
100
+ export class CliStateEngine {
101
+ // ── Status ───────────────────────────────────────
102
+ currentStatus: CliSessionStatus['status'] = 'starting';
103
+ isWaitingForResponse = false;
104
+ currentTurnScope: TurnParseScope | null = null;
105
+ // ARCH-REFACTOR R1 (per-turn task identity): the mesh taskId bound to the most
106
+ // recently STARTED turn. Unlike currentTurnScope (nulled the moment the turn
107
+ // settles, before the completion event is even built), this persists past
108
+ // completion and is only overwritten when the NEXT turn starts. That window is
109
+ // exactly what the completion path needs: when a turn settles to idle, this still
110
+ // holds THAT turn's taskId (the next task's turn cannot have started yet — it is
111
+ // queued in pendingOutbound and only flushed asynchronously after idle), so the
112
+ // completion event carries the correct id instead of the racy session scalar.
113
+ currentTurnTaskId: string | null = null;
114
+ // GENERATING-BOUNDARY (R4d): wall-clock when the most recently STARTED turn began
115
+ // (set by onTurnStarted, persists past completion until the next turn starts).
116
+ // The startup-grace idle-stayed synthesis anchors its window on when the FIRST turn
117
+ // STARTED — not on when it finished — so a turn dispatched a few seconds after the
118
+ // grace collapse and then running for a non-trivial duration is still attributed to
119
+ // the startup collapse even though its COMPLETION lands past a now-anchored window.
120
+ currentTurnStartedAt = 0;
121
+ activeModal: { message: string; buttons: string[] } | null = null;
122
+
123
+ // ── Approval ─────────────────────────────────────
124
+ lastApprovalResolvedAt = 0;
125
+ lastResolvedModalMessage = '';
126
+ /**
127
+ * Monotonic counter bumped every time the FSM *enters* waiting_approval
128
+ * with a freshly captured modal (see `applyWaitingApproval`). It is the
129
+ * single discriminator between "the same approval re-observed across TUI
130
+ * paint flaps" and "a genuinely new, distinct approval".
131
+ *
132
+ * The message-equality cooldown below (`lastResolvedModalMessage`) cannot
133
+ * tell these apart on its own: claude-cli routinely presents consecutive
134
+ * approvals whose modal message text is identical (e.g. two back-to-back
135
+ * Bash-command prompts). When that second approval arrived inside
136
+ * `approvalCooldown`, the message-equality guard silently swallowed the
137
+ * key write and the approval stuck forever — fatal under auto-approval.
138
+ *
139
+ * `approvalEntrySeq` increments on every fresh entry; `lastResolvedEntrySeq`
140
+ * records which entry the cooldown belongs to. We only short-circuit the
141
+ * write when we are still resolving *that same* entry — a new entry (new
142
+ * seq) is always a real, distinct approval and must be written.
143
+ */
144
+ approvalEntrySeq = 0;
145
+ // Records which approval entry the last resolveModal() handled. Set unconditionally on
146
+ // every resolveModal (auto-approve fire, dashboard/mesh_approve, dev-cli-debug), so
147
+ // `lastResolvedEntrySeq >= approvalEntrySeq` is positive, ADHDev-side proof that the
148
+ // current/latest approval entry was actually resolved. Exposed via getStatus so the
149
+ // completion finalization gate (FALSEIDLE-a) can require resolution evidence before
150
+ // confirming a waiting_approval→idle transition. Public (read-only by convention).
151
+ lastResolvedEntrySeq = -1;
152
+ /**
153
+ * When the engine previously held a modal but the latest parse failed
154
+ * to extract one, we record the timestamp here and only drop the modal
155
+ * after the configured `approvalCooldown` to avoid flapping between
156
+ * waiting_approval and generating on every Claude TUI redraw — that
157
+ * flapping is what fed auto-approve a fresh modal signature on each
158
+ * paint and made the engine type "1" repeatedly into the prompt.
159
+ */
160
+ modalLostAt = 0;
161
+ private approvalExitTimeout: NodeJS.Timeout | null = null;
162
+
163
+ // ── Response tracking ────────────────────────────
164
+ responseEpoch = 0;
165
+ submitPendingUntil = 0;
166
+ responseSettleIgnoreUntil = 0;
167
+ submitRetryUsed = false;
168
+ submitRetryPromptSnippet = '';
169
+ finishRetryCount = 0;
170
+ providerErrorMessage: string | null = null;
171
+ providerErrorReason: string | null = null;
172
+
173
+ // ── Timers ───────────────────────────────────────
174
+ private settleTimer: NodeJS.Timeout | null = null;
175
+ private idleTimeout: NodeJS.Timeout | null = null;
176
+ private finishRetryTimer: NodeJS.Timeout | null = null;
177
+ private providerErrorRetryTimer: NodeJS.Timeout | null = null;
178
+ private providerErrorRetryKey = '';
179
+
180
+ // ── Debounce ─────────────────────────────────────
181
+ pendingScriptStatus: 'generating' | 'waiting_approval' | null = null;
182
+ pendingScriptStatusSince = 0;
183
+ private pendingScriptStatusTimer: NodeJS.Timeout | null = null;
184
+
185
+ // ── Idle candidate ───────────────────────────────
186
+ private idleFinishCandidate: IdleFinishCandidate | null = null;
187
+
188
+ // ── Idle confirmation grace ──────────────────────
189
+ /**
190
+ * `finishResponse` produces the `generating → idle` transition that
191
+ * coordinators interpret as "task complete". Some providers (antigravity-
192
+ * cli observed in the wild) briefly paint a screen that looks like an
193
+ * idle prompt between tool result frames while still actively running,
194
+ * which fired `response_finished` and broke completion semantics.
195
+ * We defer the actual idle transition by IDLE_CONFIRMATION_GRACE_MS and
196
+ * cancel it if the scripted detection re-detects generating during that
197
+ * window — a true completion stays idle for many seconds, so a 2-second
198
+ * grace is sufficient to filter the paint blip.
199
+ */
200
+ private pendingIdleFinishTimer: NodeJS.Timeout | null = null;
201
+ private pendingIdleFinishAt = 0;
202
+
203
+ // ── Status history (debug) ───────────────────────
204
+ private statusHistory: { status: string; at: number; trigger?: string }[] = [];
205
+ private traceEntries: CliTraceEntry[] = [];
206
+ private traceSeq = 0;
207
+ private traceSessionId = '';
208
+
209
+ constructor(
210
+ private readonly provider: CliProviderModule,
211
+ private readonly runner: CliScriptRunner,
212
+ private readonly transport: CliTransportAccess,
213
+ private readonly callbacks: CliStateEngineCallbacks,
214
+ private readonly timeouts: Required<NonNullable<CliProviderModule['timeouts']>>,
215
+ ) {}
216
+
217
+ // ─── Public API ────────────────────────────────────────────────────────
218
+
219
+ setStatus(status: CliSessionStatus['status'], trigger?: string): void {
220
+ const prev = this.currentStatus;
221
+ if (prev === status) return;
222
+ this.currentStatus = status;
223
+ this.statusHistory.push({ status, at: Date.now(), trigger });
224
+ if (this.statusHistory.length > 50) this.statusHistory.shift();
225
+ this.recordTrace('status', { previousStatus: prev, trigger: trigger || null });
226
+ LOG.info('CLI', `[${this.provider.type}] status: ${prev} → ${status}${trigger ? ` (${trigger})` : ''}`);
227
+ }
228
+
229
+ scheduleSettle(): void {
230
+ if (this.settleTimer) clearTimeout(this.settleTimer);
231
+ const epoch = this.responseEpoch;
232
+ const delay = Math.max(
233
+ this.timeouts.outputSettle,
234
+ this.submitPendingUntil > Date.now()
235
+ ? (this.submitPendingUntil - Date.now()) + this.timeouts.outputSettle
236
+ : 0,
237
+ );
238
+ this.settleTimer = setTimeout(() => {
239
+ this.settleTimer = null;
240
+ if (epoch !== this.responseEpoch) return;
241
+ this.evaluateSettled(this.transport.getSnapshot());
242
+ }, delay);
243
+ }
244
+
245
+ /** Called from sendMessage in transport once a turn scope is established. */
246
+ onTurnStarted(turnScope: TurnParseScope): void {
247
+ this.isWaitingForResponse = true;
248
+ this.finishRetryCount = 0;
249
+ this.clearIdleFinishCandidate('send_message');
250
+ this.currentTurnScope = turnScope;
251
+ // ARCH-REFACTOR R1: bind this turn's mesh taskId. A task-less (ad-hoc dashboard)
252
+ // turn carries no taskId → null here, which correctly clears any prior task's id
253
+ // so an ad-hoc turn's completion is never stamped with a stale taskId.
254
+ this.currentTurnTaskId = typeof turnScope.taskId === 'string' && turnScope.taskId.trim()
255
+ ? turnScope.taskId
256
+ : null;
257
+ // R4d: stamp the turn-start moment so the startup-grace idle-stayed synthesis can
258
+ // anchor its window on dispatch time rather than completion time.
259
+ this.currentTurnStartedAt = Date.now();
260
+ this.responseEpoch += 1;
261
+ }
262
+
263
+ /** Called when PTY exits */
264
+ onPtyExit(): void {
265
+ this.clearAllTimers();
266
+ this.setStatus('stopped', 'pty_exit');
267
+ }
268
+
269
+ /** Called when adapter starts up successfully */
270
+ onSpawnReady(): void {
271
+ this.setStatus('starting', 'pty_ready');
272
+ this.traceEntries = [];
273
+ this.traceSeq = 0;
274
+ this.traceSessionId = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
275
+ this.recordTrace('session_start', { providerType: this.provider.type });
276
+ }
277
+
278
+ resolveModal(buttonIndex: number): void {
279
+ const snap = this.transport.getSnapshot();
280
+ const parseApproval = typeof this.transport.runParseApproval === 'function'
281
+ ? (s: CliBufferSnapshot) => this.transport.runParseApproval!(s.recentOutputBuffer.slice(-500))
282
+ : (s: CliBufferSnapshot) => this.runParseApproval(s);
283
+ let modal = this.activeModal ?? parseApproval(snap);
284
+
285
+ if (!modal && this.runner.hasParseSession()) {
286
+ try {
287
+ const parsed = this.runParseSession(snap) as any;
288
+ const parsedModal = parsed?.activeModal && Array.isArray(parsed.activeModal.buttons)
289
+ && parsed.activeModal.buttons.some((b: any) => typeof b === 'string' && b.trim())
290
+ ? parsed.activeModal : null;
291
+ if (parsed?.status === 'waiting_approval' && parsedModal) {
292
+ modal = parsedModal;
293
+ // No modal was held (`this.activeModal` was null above), so a
294
+ // freshly parsed approval here is a new entry by definition.
295
+ this.activeModal = parsedModal;
296
+ this.approvalEntrySeq++;
297
+ if (this.currentStatus !== 'waiting_approval') {
298
+ this.setStatus('waiting_approval', 'resolve_modal_parse');
299
+ this.callbacks.onStatusChange();
300
+ }
301
+ }
302
+ } catch { /* ignore parse failures */ }
303
+ }
304
+
305
+ if (!this.transport.isAlive()) return;
306
+ // (fix) Hard fail-safe: never write an approval key without a concrete
307
+ // modal that has buttons. The previous gate `currentStatus !== 'WA' &&
308
+ // !modal` let resolveModal proceed whenever status was still pinned to
309
+ // waiting_approval, even if parseApproval had returned null. Combined
310
+ // with auto-approve and Claude's modal flapping (status==WA but modal
311
+ // briefly null between paints) this typed "1" into the prompt over and
312
+ // over. Require a real modal with at least one button.
313
+ const buttonsValid = Array.isArray(modal?.buttons)
314
+ && modal.buttons.some((b: any) => typeof b === 'string' && b.trim());
315
+ if (!modal || !buttonsValid) return;
316
+
317
+ const currentModalMessage = typeof modal?.message === 'string' ? modal.message.trim() : '';
318
+ const inCooldown = !!this.lastApprovalResolvedAt
319
+ && (Date.now() - this.lastApprovalResolvedAt) < this.timeouts.approvalCooldown;
320
+ // (fix) Suppress the duplicate key-write ONLY when this is the *same*
321
+ // approval entry re-observed across TUI paint flaps — i.e. the FSM has
322
+ // not entered waiting_approval afresh since the last resolve
323
+ // (approvalEntrySeq unchanged). A new entry (bumped seq) is always a
324
+ // distinct approval and must be written, even within the cooldown
325
+ // window and even when its message text matches the previous one.
326
+ //
327
+ // Previously this gated on message equality alone, so consecutive
328
+ // claude-cli approvals that share message text (very common) had the
329
+ // second write swallowed — the approval stuck unresolved despite
330
+ // auto-approval being on.
331
+ const sameEntryReResolve = this.approvalEntrySeq === this.lastResolvedEntrySeq;
332
+ if (inCooldown && sameEntryReResolve && currentModalMessage === this.lastResolvedModalMessage) return;
333
+
334
+ this.clearIdleFinishCandidate('resolve_modal');
335
+ this.recordTrace('resolve_modal', { buttonIndex, activeModal: modal, approvalEntrySeq: this.approvalEntrySeq });
336
+ this.activeModal = null;
337
+ this.lastApprovalResolvedAt = Date.now();
338
+ this.lastResolvedModalMessage = currentModalMessage;
339
+ this.lastResolvedEntrySeq = this.approvalEntrySeq;
340
+ this.responseSettleIgnoreUntil = Date.now() + this.timeouts.outputSettle + 400;
341
+ if (this.approvalExitTimeout) { clearTimeout(this.approvalExitTimeout); this.approvalExitTimeout = null; }
342
+ this.setStatus('generating', 'approval_resolved');
343
+ this.callbacks.onStatusChange();
344
+
345
+ const approvalKey = this.transport.getApprovalKeyForIndex(buttonIndex);
346
+ if (approvalKey !== undefined) {
347
+ this.transport.writeRaw(approvalKey);
348
+ } else {
349
+ const DOWN = '\x1B[B';
350
+ const buttonCount = Array.isArray(modal?.buttons) ? modal.buttons.length : 0;
351
+ const clamped = buttonCount > 0
352
+ ? Math.min(Math.max(0, buttonIndex), buttonCount - 1)
353
+ : Math.max(0, buttonIndex);
354
+ this.transport.writeRaw(DOWN.repeat(clamped) + '\r');
355
+ }
356
+ }
357
+
358
+ isApprovalRecentlyResolved(): boolean {
359
+ return !!(this.lastApprovalResolvedAt
360
+ && (Date.now() - this.lastApprovalResolvedAt) < this.timeouts.approvalCooldown);
361
+ }
362
+
363
+ /**
364
+ * Called from sendMessage before starting a new turn.
365
+ * Clears stale idle response state when the terminal looks idle and no modal is active.
366
+ */
367
+ clearStaleIdleResponseGuard(reason: string, snap: CliBufferSnapshot): boolean {
368
+ const blockingModal = this.activeModal
369
+ ?? (typeof this.transport.runParseApproval === 'function'
370
+ ? this.transport.runParseApproval(snap.recentOutputBuffer.slice(-500))
371
+ : this.runParseApproval(snap));
372
+ const isIdle = (typeof this.transport.runDetectStatus === 'function'
373
+ ? this.transport.runDetectStatus(snap.recentOutputBuffer)
374
+ : this.runDetectStatus(snap)) === 'idle';
375
+ if (!this.isWaitingForResponse || this.currentStatus !== 'idle' || !isIdle || !!blockingModal) {
376
+ return false;
377
+ }
378
+ this.clearAllTimers();
379
+ this.clearIdleFinishCandidate(reason);
380
+ this.isWaitingForResponse = false;
381
+ this.responseSettleIgnoreUntil = 0;
382
+ this.submitRetryUsed = false;
383
+ this.submitRetryPromptSnippet = '';
384
+ this.finishRetryCount = 0;
385
+ this.currentTurnScope = null;
386
+ this.activeModal = null;
387
+ this.recordTrace('stale_idle_response_cleared', { reason });
388
+ this.callbacks.onTurnCompleted();
389
+ return true;
390
+ }
391
+
392
+ /**
393
+ * Called from sendMessage before starting a new turn.
394
+ * Clears stale idle response state when the parsed session confirms idle with a final assistant message.
395
+ */
396
+ clearParsedIdleResponseGuard(reason: string, parsedStatus: any, snap: CliBufferSnapshot): boolean {
397
+ const parsedRawStatus = typeof parsedStatus?.status === 'string' ? parsedStatus.status.trim() : '';
398
+ const parsedModal = parsedStatus?.activeModal ?? parsedStatus?.modal ?? null;
399
+ const blockingModal = this.activeModal
400
+ ?? (typeof this.transport.runParseApproval === 'function'
401
+ ? this.transport.runParseApproval(snap.recentOutputBuffer.slice(-500))
402
+ : this.runParseApproval(snap));
403
+ if (
404
+ !this.isWaitingForResponse
405
+ || parsedRawStatus !== 'idle'
406
+ || !!parsedModal
407
+ || !!blockingModal
408
+ || !this.parsedStatusHasFinalAssistantMessage(parsedStatus)
409
+ ) {
410
+ return false;
411
+ }
412
+ this.clearAllTimers();
413
+ this.clearIdleFinishCandidate(reason);
414
+ this.isWaitingForResponse = false;
415
+ this.responseSettleIgnoreUntil = 0;
416
+ this.submitRetryUsed = false;
417
+ this.submitRetryPromptSnippet = '';
418
+ this.finishRetryCount = 0;
419
+ this.currentTurnScope = null;
420
+ this.activeModal = null;
421
+ this.setStatus('idle', reason);
422
+ this.recordTrace('parsed_idle_response_cleared', {
423
+ reason,
424
+ parsedStatus: parsedRawStatus,
425
+ parsedMessageCount: Array.isArray(parsedStatus?.messages) ? parsedStatus.messages.length : 0,
426
+ });
427
+ this.callbacks.onTurnCompleted();
428
+ return true;
429
+ }
430
+
431
+ clearAllTimers(): void {
432
+ if (this.settleTimer) { clearTimeout(this.settleTimer); this.settleTimer = null; }
433
+ if (this.idleTimeout) { clearTimeout(this.idleTimeout); this.idleTimeout = null; }
434
+ if (this.approvalExitTimeout) { clearTimeout(this.approvalExitTimeout); this.approvalExitTimeout = null; }
435
+ if (this.finishRetryTimer) { clearTimeout(this.finishRetryTimer); this.finishRetryTimer = null; }
436
+ if (this.pendingScriptStatusTimer) { clearTimeout(this.pendingScriptStatusTimer); this.pendingScriptStatusTimer = null; }
437
+ if (this.providerErrorRetryTimer) { clearTimeout(this.providerErrorRetryTimer); this.providerErrorRetryTimer = null; }
438
+ if (this.pendingIdleFinishTimer) { clearTimeout(this.pendingIdleFinishTimer); this.pendingIdleFinishTimer = null; this.pendingIdleFinishAt = 0; }
439
+ this.providerErrorRetryKey = '';
440
+ }
441
+
442
+ resetActiveTurnState(): void {
443
+ this.clearAllTimers();
444
+ this.isWaitingForResponse = false;
445
+ this.responseSettleIgnoreUntil = 0;
446
+ this.submitRetryUsed = false;
447
+ this.submitRetryPromptSnippet = '';
448
+ this.finishRetryCount = 0;
449
+ this.currentTurnScope = null;
450
+ this.activeModal = null;
451
+ this.pendingScriptStatus = null;
452
+ this.pendingScriptStatusSince = 0;
453
+ }
454
+
455
+ clearIdleFinishCandidate(reason: string): void {
456
+ if (!this.idleFinishCandidate) return;
457
+ this.recordTrace('idle_candidate_reset', { reason, candidate: this.idleFinishCandidate });
458
+ this.idleFinishCandidate = null;
459
+ }
460
+
461
+ hasActionableApproval(startupModal?: { message: string; buttons: string[] } | null): boolean {
462
+ return !!(startupModal ?? this.activeModal);
463
+ }
464
+
465
+ getTraceEntries(): CliTraceEntry[] { return this.traceEntries; }
466
+ getStatusHistory(): { status: string; at: number; trigger?: string }[] { return this.statusHistory; }
467
+ getTraceSessionId(): string { return this.traceSessionId; }
468
+
469
+ /** Record a trace entry from the transport layer (e.g. output events in debug mode). */
470
+ recordExternalTrace(type: string, payload: Record<string, any> = {}): void {
471
+ this.recordTrace(type, payload);
472
+ }
473
+
474
+ // ─── Script dispatch (builds inputs from snapshot) ──────────────────────
475
+
476
+ runDetectStatus(snap: CliBufferSnapshot): string | null {
477
+ const tail = snap.recentOutputBuffer.slice(-500);
478
+ return this.runner.detectStatus({
479
+ tail,
480
+ screenText: snap.screenText,
481
+ rawBuffer: snap.accumulatedRawBuffer,
482
+ isWaitingForResponse: snap.isWaitingForResponse,
483
+ screen: buildCliScreenSnapshot(snap.screenText),
484
+ tailScreen: buildCliScreenSnapshot(tail),
485
+ });
486
+ }
487
+
488
+ runParseApproval(snap: CliBufferSnapshot): { message: string; buttons: string[] } | null {
489
+ const tail = snap.recentOutputBuffer.slice(-500);
490
+ const buffer = snap.screenText || snap.accumulatedBuffer;
491
+ return this.runner.parseApproval({
492
+ buffer,
493
+ screenText: snap.screenText,
494
+ rawBuffer: snap.accumulatedRawBuffer,
495
+ tail,
496
+ screen: buildCliScreenSnapshot(snap.screenText),
497
+ bufferScreen: buildCliScreenSnapshot(buffer),
498
+ tailScreen: buildCliScreenSnapshot(tail),
499
+ });
500
+ }
501
+
502
+ runParseSession(snap: CliBufferSnapshot): ParsedSession | null {
503
+ // Allow transport to override session parsing (enables test mocking)
504
+ if (typeof this.transport.runParseSession === 'function') {
505
+ const session = this.transport.runParseSession();
506
+ if (session && typeof session === 'object') {
507
+ this.callbacks.onApplyParsedSession(session);
508
+ }
509
+ return session;
510
+ }
511
+ const tail = snap.recentOutputBuffer.slice(-500);
512
+ const input = buildCliParseInput({
513
+ accumulatedBuffer: snap.accumulatedBuffer,
514
+ accumulatedRawBuffer: snap.accumulatedRawBuffer,
515
+ recentOutputBuffer: snap.recentOutputBuffer,
516
+ terminalScreenText: snap.parseScreenText,
517
+ workingDir: snap.workingDir,
518
+ providerSessionId: snap.providerSessionId || undefined,
519
+ historySessionId: snap.providerSessionId || undefined,
520
+ baseMessages: [],
521
+ partialResponse: snap.responseBuffer,
522
+ isWaitingForResponse: snap.isWaitingForResponse,
523
+ scope: snap.currentTurnScope,
524
+ runtimeSettings: snap.runtimeSettings,
525
+ });
526
+ const session = this.runner.parseSession({
527
+ ...input,
528
+ tail,
529
+ tailScreen: buildCliScreenSnapshot(tail),
530
+ });
531
+ if (session && typeof session === 'object') {
532
+ this.callbacks.onApplyParsedSession(session);
533
+ }
534
+ return session;
535
+ }
536
+
537
+ // ─── Core evaluation loop ───────────────────────────────────────────────
538
+
539
+ evaluateSettled(snap: CliBufferSnapshot): void {
540
+ const now = Date.now();
541
+ if (this.submitPendingUntil > now || this.responseSettleIgnoreUntil > now) {
542
+ const delayTime = Math.max(this.submitPendingUntil - now, this.responseSettleIgnoreUntil - now) + 50;
543
+ if (this.settleTimer) clearTimeout(this.settleTimer);
544
+ this.settleTimer = setTimeout(() => {
545
+ this.settleTimer = null;
546
+ this.evaluateSettled(this.transport.getSnapshot());
547
+ }, delayTime);
548
+ return;
549
+ }
550
+
551
+ if (!this.isWaitingForResponse && !this.currentTurnScope && !this.activeModal && !this.runner.parseErrorMessage) {
552
+ const tail = snap.recentOutputBuffer;
553
+ const modal = this.runParseApproval(snap);
554
+ const lightweightStatus = this.runner.hasDetectStatus() ? this.runDetectStatus(snap) : null;
555
+ if (!modal && lightweightStatus === 'idle' && this.currentStatus === 'idle') return;
556
+ }
557
+
558
+ const session = this.runParseSession(snap);
559
+ if (!session) return;
560
+
561
+ const { status, messages } = session;
562
+ const modal = (session as any).activeModal ?? session.modal ?? null;
563
+ const parsedStatus = (session as any).parsedStatus ?? null;
564
+ const parsedMessages = normalizeCliParsedMessages(messages, {
565
+ scope: null,
566
+ lastOutputAt: snap.lastOutputAt,
567
+ });
568
+
569
+ if (this.maybeCommitVisibleIdleTranscript(session, parsedMessages, snap)) return;
570
+
571
+ const lastParsedAssistant = [...parsedMessages].reverse().find((m) => m.role === 'assistant');
572
+
573
+ if (
574
+ this.currentTurnScope
575
+ && !lastParsedAssistant
576
+ && !this.submitRetryUsed
577
+ && this.transport.isAlive()
578
+ && !this.hasActionableApproval()
579
+ && promptLikelyVisible(snap.screenText, normalizePromptText(this.submitRetryPromptSnippet || this.currentTurnScope?.prompt || ''))
580
+ && !this.hasMeaningfulResponseBuffer(snap, normalizePromptText(this.submitRetryPromptSnippet || this.currentTurnScope?.prompt || ''))
581
+ ) {
582
+ this.submitRetryUsed = true;
583
+ this.responseSettleIgnoreUntil = Date.now() + this.timeouts.outputSettle + 400;
584
+ LOG.info('CLI', `[${this.provider.type}] Retrying submit key from settled parser (no assistant yet)`);
585
+ this.transport.writeRaw('\r');
586
+ if (this.settleTimer) clearTimeout(this.settleTimer);
587
+ this.settleTimer = setTimeout(() => {
588
+ this.settleTimer = null;
589
+ this.evaluateSettled(this.transport.getSnapshot());
590
+ }, this.timeouts.outputSettle + 150);
591
+ return;
592
+ }
593
+
594
+ if (!status) return;
595
+
596
+ const prevStatus = this.currentStatus;
597
+ const ctx: SettledEvalContext = { now, modal, status, parsedMessages, lastParsedAssistant, parsedStatus: parsedStatus || null, prevStatus };
598
+
599
+ if (!this.applyPendingScriptStatusDebounce(ctx)) return;
600
+
601
+ const recentInteractiveActivity = this.hasRecentInteractiveActivity(snap, now);
602
+ LOG.debug(
603
+ 'CLI',
604
+ `[${this.provider.type}] settled diagnostics prompt=${JSON.stringify(this.currentTurnScope?.prompt || '').slice(0, 140)} status=${String(status || '')} parsedStatus=${String(parsedStatus || '')} parsedMsgCount=${parsedMessages.length} lastParsedAssistant=${JSON.stringify((lastParsedAssistant?.content || '').slice(0, 120)).slice(0, 160)} responseBuffer=${JSON.stringify((snap.responseBuffer || '').slice(0, 160)).slice(0, 220)} recentActivity=${recentInteractiveActivity}`
605
+ );
606
+
607
+ // recent_activity_hold protects an in-flight user turn from a false
608
+ // idle blip. It must NOT fire during startup — when the adapter has
609
+ // no currentTurnScope, there is no user turn to protect; the recent
610
+ // activity is just the CLI painting its welcome screen. Firing here
611
+ // produced the startup status flip the user reported
612
+ // (generating → idle → generating → idle within the first few seconds
613
+ // of claude-cli launch).
614
+ //
615
+ // When isWaitingForResponse=true and a currentTurnScope is alive, a
616
+ // PTY quiet period (>statusActivityHold ms without output) does NOT
617
+ // mean the response is done — claude-cli regularly pauses 2s+ between
618
+ // chunks during parsing/generation. recentInteractiveActivity going
619
+ // false during such a pause was the root cause of false-idle
620
+ // regressions. We hold generating whenever an active response turn is
621
+ // in flight (unconditionally, not just when there was recent output).
622
+ // The real completion gate is applyIdle's idleFinishCandidate +
623
+ // idleFinish timeout, which requires stable quiet AND a parsed
624
+ // assistant message.
625
+ //
626
+ // Fast-path exception: only release the hold if the parser shows a
627
+ // *current-turn* final standard assistant after the last user message,
628
+ // and it is not still streaming. Using !!lastParsedAssistant was too
629
+ // broad — it matched previous-turn assistant messages and caused
630
+ // false-idle between the first assistant text chunk and the first
631
+ // tool call (the agent outputs text, then immediately begins tool use;
632
+ // the gap between them hit this fast path and committed idle).
633
+ const hasFinalCurrentTurnAssistant = (() => {
634
+ if (parsedStatus !== 'idle') return false;
635
+ const msgs: any[] = Array.isArray(parsedMessages) ? parsedMessages : [];
636
+ let lastUserIdx = -1;
637
+ for (let i = msgs.length - 1; i >= 0; i--) {
638
+ if (msgs[i]?.role === 'user') { lastUserIdx = i; break; }
639
+ }
640
+ // No user message visible: fall back to any non-streaming standard assistant.
641
+ const searchSlice = lastUserIdx >= 0 ? msgs.slice(lastUserIdx + 1) : msgs;
642
+ return searchSlice.some((m: any) => {
643
+ if (!m || m.role !== 'assistant') return false;
644
+ if (typeof m.content !== 'string' || !m.content.trim()) return false;
645
+ const kind = typeof m.kind === 'string' && m.kind.trim() ? m.kind.trim() : 'standard';
646
+ return kind === 'standard' && m.meta?.streaming !== true;
647
+ });
648
+ })();
649
+ const shouldHoldGenerating = status === 'idle'
650
+ && this.isWaitingForResponse
651
+ && !!this.currentTurnScope
652
+ && !modal
653
+ && !hasFinalCurrentTurnAssistant;
654
+
655
+ if (shouldHoldGenerating) { this.applyHoldGenerating(ctx); return; }
656
+ if (status === 'error') {
657
+ if (this.maybeScheduleProviderErrorRetry(ctx, session, snap)) return;
658
+ this.applyError(ctx, session);
659
+ return;
660
+ }
661
+ if (status === 'waiting_approval') { this.applyWaitingApproval(ctx); return; }
662
+ if (status === 'generating') { this.applyGenerating(ctx); return; }
663
+ if (status === 'idle') { this.applyIdle(ctx, snap, now); }
664
+ }
665
+
666
+ // ─── State transitions ──────────────────────────────────────────────────
667
+
668
+ private applyPendingScriptStatusDebounce(ctx: SettledEvalContext): boolean {
669
+ const { now, status, prevStatus } = ctx;
670
+ const shouldDebounce = prevStatus === 'idle' && !this.isWaitingForResponse
671
+ && !this.currentTurnScope && (status === 'generating' || status === 'waiting_approval');
672
+
673
+ if (!shouldDebounce) {
674
+ this.pendingScriptStatus = null;
675
+ this.pendingScriptStatusSince = 0;
676
+ if (this.pendingScriptStatusTimer) { clearTimeout(this.pendingScriptStatusTimer); this.pendingScriptStatusTimer = null; }
677
+ return true;
678
+ }
679
+
680
+ const armPending = (delayMs: number) => {
681
+ if (this.pendingScriptStatusTimer) clearTimeout(this.pendingScriptStatusTimer);
682
+ this.pendingScriptStatusTimer = setTimeout(() => {
683
+ this.pendingScriptStatusTimer = null;
684
+ this.evaluateSettled(this.transport.getSnapshot());
685
+ }, delayMs);
686
+ };
687
+
688
+ if (this.pendingScriptStatus !== status) {
689
+ this.pendingScriptStatus = status as 'generating' | 'waiting_approval';
690
+ this.pendingScriptStatusSince = now;
691
+ armPending(SCRIPT_STATUS_DEBOUNCE_MS);
692
+ return false;
693
+ }
694
+ const elapsed = now - this.pendingScriptStatusSince;
695
+ if (elapsed < SCRIPT_STATUS_DEBOUNCE_MS) { armPending(SCRIPT_STATUS_DEBOUNCE_MS - elapsed); return false; }
696
+ return true;
697
+ }
698
+
699
+ private applyHoldGenerating(ctx: SettledEvalContext): void {
700
+ this.clearIdleFinishCandidate('hold_generating_recent_activity');
701
+ this.setStatus('generating', 'recent_activity_hold');
702
+ if (this.idleTimeout) clearTimeout(this.idleTimeout);
703
+ this.idleTimeout = setTimeout(() => {
704
+ if (this.isWaitingForResponse && !this.hasActionableApproval()) {
705
+ if (this.shouldDeferIdleTimeoutFinish()) return;
706
+ this.finishResponse();
707
+ }
708
+ }, this.timeouts.generatingIdle);
709
+ this.callbacks.onStatusChange();
710
+ }
711
+
712
+ private applyWaitingApproval(ctx: SettledEvalContext): void {
713
+ const { modal } = ctx;
714
+ this.clearIdleFinishCandidate('waiting_approval');
715
+ const inCooldown = this.lastApprovalResolvedAt
716
+ && (Date.now() - this.lastApprovalResolvedAt) < this.timeouts.approvalCooldown;
717
+ if (inCooldown && !modal) {
718
+ if (this.approvalExitTimeout) { clearTimeout(this.approvalExitTimeout); this.approvalExitTimeout = null; }
719
+ this.activeModal = null;
720
+ const reason = inCooldown ? 'approval_cooldown_non_actionable' : 'approval_prompt_gone_non_actionable';
721
+ if (this.isWaitingForResponse) {
722
+ this.setStatus('idle', reason);
723
+ if (this.idleTimeout) clearTimeout(this.idleTimeout);
724
+ this.idleTimeout = setTimeout(() => {
725
+ if (this.isWaitingForResponse && !this.hasActionableApproval()) {
726
+ if (this.shouldDeferIdleTimeoutFinish()) return;
727
+ this.finishResponse();
728
+ }
729
+ }, this.timeouts.generatingIdle);
730
+ } else {
731
+ this.setStatus('idle', reason);
732
+ }
733
+ this.callbacks.onStatusChange();
734
+ return;
735
+ }
736
+ // (fix) A *real* modal with valid buttons surfacing during the cooldown
737
+ // window is a genuinely new approval, not a trailing repaint of the one
738
+ // we just resolved — resolveModal cleared activeModal and flipped status
739
+ // to generating, so detectStatus only re-reports waiting_approval with a
740
+ // concrete modal when the CLI actually presents the next prompt.
741
+ // Previously this case fell through BOTH the `inCooldown && !modal`
742
+ // branch above and the `!inCooldown` branch below, so the FSM silently
743
+ // ignored the second approval — leaving it stuck unresolved under
744
+ // auto-approval. Capture it like any fresh entry (the modal-message
745
+ // cooldown still de-dupes the same approval inside resolveModal, now
746
+ // keyed on approvalEntrySeq). The `!modal` flap case stays gated by
747
+ // cooldown above; only an actionable new modal breaks through here.
748
+ if (!inCooldown || modal) {
749
+ if (!modal) {
750
+ LOG.warn('CLI', `[${this.provider.type}] detectStatus=waiting_approval but parseApproval returned null; ignoring`);
751
+ // (fix) If we previously surfaced waiting_approval but the
752
+ // modal extraction is now failing, eventually drop the modal
753
+ // and fall back to generating so the dashboard doesn't show
754
+ // a "waiting" badge with no buttons. BUT defer the transition
755
+ // for a hysteresis window — Claude TUI re-renders parts of
756
+ // the approval frame multiple times per second and the
757
+ // intermediate parses occasionally lose buttons for a single
758
+ // pass. Flapping the engine status WA → generating → WA →
759
+ // generating between paints fed auto-approve a fresh modal
760
+ // signature each time, which typed the approval key
761
+ // ("1") into the prompt repeatedly. Wait for the modal to
762
+ // stay gone for `approvalCooldown` before clearing.
763
+ if (this.currentStatus === 'waiting_approval' && this.activeModal) {
764
+ const lostAt = this.modalLostAt || Date.now();
765
+ if (!this.modalLostAt) this.modalLostAt = lostAt;
766
+ if (Date.now() - lostAt >= this.timeouts.approvalCooldown) {
767
+ this.activeModal = null;
768
+ this.modalLostAt = 0;
769
+ this.setStatus('generating', 'approval_lost_modal');
770
+ this.callbacks.onStatusChange();
771
+ }
772
+ }
773
+ return;
774
+ }
775
+ this.modalLostAt = 0;
776
+ this.isWaitingForResponse = true;
777
+ this.setStatus('waiting_approval', 'script_detect');
778
+ // (fix) Don't overwrite an already-captured modal with a fresh
779
+ // re-parse on every evaluate — Claude TUI redraws option labels
780
+ // partially between paints (e.g. "Yes, and don't ask again for ..."
781
+ // is wider than the row and ships with a different trailing
782
+ // string each paint), which made the dashboard flap the modal
783
+ // signature continuously. Keep the first stable modal whose
784
+ // button count matches the latest parse; only swap when the
785
+ // shape clearly changed (different number of buttons → different
786
+ // approval).
787
+ const prev = this.activeModal;
788
+ const prevBtnCount = Array.isArray(prev?.buttons) ? prev!.buttons.length : 0;
789
+ const nextBtnCount = Array.isArray(modal.buttons) ? modal.buttons.length : 0;
790
+ if (!prev || prevBtnCount !== nextBtnCount) {
791
+ this.activeModal = modal;
792
+ // A fresh modal was captured (none held, or the button shape
793
+ // changed). This is a distinct approval entry — bump the seq so
794
+ // resolveModal's message-equality cooldown does not mistake it
795
+ // for a flap-repaint of the previously resolved approval.
796
+ this.approvalEntrySeq++;
797
+ this.callbacks.onStatusChange();
798
+ }
799
+ if (this.idleTimeout) clearTimeout(this.idleTimeout);
800
+ this.armApprovalExitTimeout();
801
+ }
802
+ }
803
+
804
+ private applyGenerating(ctx: SettledEvalContext): void {
805
+ const { modal, parsedMessages, lastParsedAssistant, parsedStatus, prevStatus } = ctx;
806
+ const noActiveTurn = !this.currentTurnScope;
807
+ // If the turn is already complete (isWaitingForResponse=false, no scope,
808
+ // no modal), PTY generating blips are just the CLI repainting its prompt.
809
+ // Check BEFORE cancelling the pending idle-finish timer — we don't want
810
+ // to cancel a scheduled idle transition just because the CLI blinked.
811
+ if (!this.isWaitingForResponse && noActiveTurn && !modal) return;
812
+ this.clearIdleFinishCandidate('generating');
813
+ // Cancel any pending grace-window idle transition. We have fresh
814
+ // evidence the provider is still generating; the previous
815
+ // finishResponse() was a paint blip, not a real completion.
816
+ this.cancelPendingIdleFinish('generating_signal_returned');
817
+ const snap = this.transport.getSnapshot();
818
+ const effectiveScreenText = snap.screenText || snap.accumulatedBuffer;
819
+ const looksIdleChrome = /(^|\n)\s*[❯›>]\s*(?:\n|$)/m.test(effectiveScreenText);
820
+ const parsedShowsLiveProgress = parsedStatus === 'generating' && !!lastParsedAssistant;
821
+ if (prevStatus === 'idle' && !this.isWaitingForResponse && noActiveTurn && !modal && looksIdleChrome && !parsedShowsLiveProgress) return;
822
+ if (prevStatus === 'waiting_approval') {
823
+ if (this.approvalExitTimeout) { clearTimeout(this.approvalExitTimeout); this.approvalExitTimeout = null; }
824
+ this.activeModal = null;
825
+ this.lastApprovalResolvedAt = Date.now();
826
+ }
827
+ if (!this.isWaitingForResponse) { this.isWaitingForResponse = true; }
828
+ this.setStatus('generating', 'script_detect');
829
+ if (this.idleTimeout) clearTimeout(this.idleTimeout);
830
+ this.idleTimeout = setTimeout(() => {
831
+ if (this.isWaitingForResponse) {
832
+ if (this.shouldDeferIdleTimeoutFinish()) return;
833
+ this.finishResponse();
834
+ }
835
+ }, this.timeouts.generatingIdle);
836
+ this.callbacks.onStatusChange();
837
+ }
838
+
839
+ private applyError(ctx: SettledEvalContext, session: ParsedSession): void {
840
+ this.clearIdleFinishCandidate('provider_error');
841
+ this.clearAllTimers();
842
+ this.isWaitingForResponse = false;
843
+ this.responseSettleIgnoreUntil = 0;
844
+ this.submitRetryUsed = false;
845
+ this.submitRetryPromptSnippet = '';
846
+ this.finishRetryCount = 0;
847
+ this.currentTurnScope = null;
848
+ this.activeModal = null;
849
+ this.providerErrorMessage = typeof session.errorMessage === 'string' && session.errorMessage.trim()
850
+ ? session.errorMessage.trim() : 'Provider reported an error';
851
+ this.providerErrorReason = typeof session.errorReason === 'string' && session.errorReason.trim()
852
+ ? session.errorReason.trim() : 'provider_error';
853
+ this.setStatus('error', this.providerErrorReason);
854
+ this.callbacks.onStatusChange();
855
+ }
856
+
857
+ private maybeScheduleProviderErrorRetry(ctx: SettledEvalContext, session: ParsedSession, snap: CliBufferSnapshot): boolean {
858
+ const retryPrompt = typeof (session as any).retryPrompt === 'string' ? String((session as any).retryPrompt).trim() : '';
859
+ const retryDelayMs = typeof (session as any).retryDelayMs === 'number' ? Number((session as any).retryDelayMs) : NaN;
860
+ if (!retryPrompt || !Number.isFinite(retryDelayMs) || retryDelayMs < 0 || !this.transport.isAlive()) return false;
861
+
862
+ const retryAttempt = typeof (session as any).retryAttempt === 'number' ? Number((session as any).retryAttempt) : 0;
863
+ const errorReason = typeof session.errorReason === 'string' && session.errorReason.trim() ? session.errorReason.trim() : 'provider_error';
864
+ const retryKey = `${errorReason}:${retryAttempt}:${retryPrompt}`;
865
+ if (this.providerErrorRetryTimer && this.providerErrorRetryKey === retryKey) return true;
866
+
867
+ if (this.providerErrorRetryTimer) clearTimeout(this.providerErrorRetryTimer);
868
+ this.providerErrorRetryKey = retryKey;
869
+ this.clearIdleFinishCandidate('provider_error_retry');
870
+ if (this.idleTimeout) { clearTimeout(this.idleTimeout); this.idleTimeout = null; }
871
+ if (this.approvalExitTimeout) { clearTimeout(this.approvalExitTimeout); this.approvalExitTimeout = null; }
872
+ this.providerErrorMessage = typeof session.errorMessage === 'string' && session.errorMessage.trim()
873
+ ? session.errorMessage.trim() : 'Provider reported an error';
874
+ this.providerErrorReason = errorReason;
875
+ this.activeModal = null;
876
+ this.responseSettleIgnoreUntil = Date.now() + retryDelayMs + this.timeouts.outputSettle + 400;
877
+ this.setStatus('generating', 'provider_error_retry_scheduled');
878
+ this.callbacks.onStatusChange();
879
+
880
+ this.providerErrorRetryTimer = setTimeout(() => {
881
+ this.providerErrorRetryTimer = null;
882
+ this.providerErrorRetryKey = '';
883
+ if (!this.transport.isAlive()) return;
884
+ this.responseSettleIgnoreUntil = Date.now() + this.timeouts.outputSettle + 400;
885
+ this.submitRetryUsed = false;
886
+ this.transport.writeRaw(`${retryPrompt}\r`);
887
+ if (this.settleTimer) clearTimeout(this.settleTimer);
888
+ this.settleTimer = setTimeout(() => {
889
+ this.settleTimer = null;
890
+ this.evaluateSettled(this.transport.getSnapshot());
891
+ }, this.timeouts.outputSettle + 150);
892
+ }, retryDelayMs);
893
+ return true;
894
+ }
895
+
896
+ private applyIdle(ctx: SettledEvalContext, snap: CliBufferSnapshot, now: number): void {
897
+ const { modal, lastParsedAssistant, prevStatus } = ctx;
898
+ if (prevStatus === 'waiting_approval') {
899
+ if (this.approvalExitTimeout) { clearTimeout(this.approvalExitTimeout); this.approvalExitTimeout = null; }
900
+ this.activeModal = null;
901
+ this.lastApprovalResolvedAt = Date.now();
902
+ this.setStatus('idle', 'approval_prompt_gone_script_idle');
903
+ }
904
+ if (!this.isWaitingForResponse) {
905
+ if (prevStatus !== 'idle') {
906
+ this.clearIdleFinishCandidate('idle_without_response');
907
+ this.setStatus('idle', 'script_detect');
908
+ this.callbacks.onStatusChange();
909
+ }
910
+ return;
911
+ }
912
+ const quietForMs = snap.lastNonEmptyOutputAt ? (now - snap.lastNonEmptyOutputAt) : Number.MAX_SAFE_INTEGER;
913
+ const screenStableMs = snap.lastScreenChangeAt ? (now - snap.lastScreenChangeAt) : 0;
914
+ const hasAssistantTurn = !!lastParsedAssistant;
915
+ const assistantLength = (lastParsedAssistant as any)?.content?.length || 0;
916
+ const idleFinishConfirmMs = this.timeouts.idleFinishConfirm;
917
+ const idleQuietThresholdMs = Math.max(idleFinishConfirmMs, this.timeouts.outputSettle);
918
+ const idleReady = !modal && hasAssistantTurn && quietForMs >= idleQuietThresholdMs && screenStableMs >= idleFinishConfirmMs;
919
+ const candidate = this.idleFinishCandidate;
920
+ const candidateQuiet = !!candidate && candidate.responseEpoch === this.responseEpoch
921
+ && candidate.lastOutputAt === snap.lastOutputAt
922
+ && candidate.lastScreenChangeAt === snap.lastScreenChangeAt
923
+ && assistantLength >= candidate.assistantLength
924
+ && (now - candidate.armedAt) >= idleFinishConfirmMs;
925
+
926
+ if (idleReady && candidateQuiet) {
927
+ this.clearIdleFinishCandidate('finish_response');
928
+ if (this.idleTimeout) clearTimeout(this.idleTimeout);
929
+ this.finishResponse();
930
+ return;
931
+ }
932
+
933
+ if (idleReady) {
934
+ if (!candidate) { this.armIdleFinishCandidate(snap, assistantLength); return; }
935
+ } else {
936
+ this.clearIdleFinishCandidate('idle_not_ready');
937
+ }
938
+
939
+ if (this.idleTimeout) clearTimeout(this.idleTimeout);
940
+ this.idleTimeout = setTimeout(() => {
941
+ if (this.isWaitingForResponse && !this.hasActionableApproval()) {
942
+ if (this.shouldDeferIdleTimeoutFinish()) return;
943
+ const parsed = this.runParseSession(this.transport.getSnapshot());
944
+ if (this.shouldDeferFinishForTranscript(parsed)) {
945
+ this.rescheduleTranscriptFinishCheck('transcript_idle_timeout_not_final');
946
+ return;
947
+ }
948
+ this.clearIdleFinishCandidate('idle_timeout_finish');
949
+ this.finishResponse();
950
+ }
951
+ }, this.timeouts.idleFinish);
952
+ }
953
+
954
+ finishResponse(): void {
955
+ if (this.submitPendingUntil > Date.now()) return;
956
+ if (this.responseSettleIgnoreUntil > Date.now()) return;
957
+ const snap = this.transport.getSnapshot();
958
+ const parsedBeforeFinish = this.runParseSession(snap);
959
+ if (this.shouldDeferFinishForTranscript(parsedBeforeFinish)) {
960
+ this.rescheduleTranscriptFinishCheck('transcript_finish_not_final');
961
+ return;
962
+ }
963
+ this.clearIdleFinishCandidate('finish_response_enter');
964
+ const commitResult = this.commitCurrentTranscript(snap);
965
+ if (this.shouldRetryFinishResponse(snap, commitResult)) {
966
+ this.finishRetryCount += 1;
967
+ if (this.finishRetryTimer) clearTimeout(this.finishRetryTimer);
968
+ this.finishRetryTimer = setTimeout(() => {
969
+ this.finishRetryTimer = null;
970
+ if (this.isWaitingForResponse && !this.hasActionableApproval()) this.finishResponse();
971
+ }, FINISH_RETRY_DELAY_MS);
972
+ return;
973
+ }
974
+ this.resetActiveTurnState();
975
+ this.callbacks.onTurnCompleted();
976
+ // Defer the actual `generating → idle` transition by a short grace
977
+ // window. If applyGenerating fires again before the grace expires —
978
+ // antigravity's tool-result paint blips do this — cancelPendingIdle
979
+ // Finish() drops the pending transition and we stay generating.
980
+ this.scheduleIdleFinish('response_finished');
981
+ this.transport.flushOutboundQueue();
982
+ }
983
+
984
+ private scheduleIdleFinish(reason: string): void {
985
+ // If we are already deferring, replace the schedule so the most
986
+ // recent finishResponse "wins". Reasons accumulate via the trigger.
987
+ if (this.pendingIdleFinishTimer) clearTimeout(this.pendingIdleFinishTimer);
988
+ this.pendingIdleFinishAt = Date.now() + IDLE_CONFIRMATION_GRACE_MS;
989
+ this.pendingIdleFinishTimer = setTimeout(() => {
990
+ this.pendingIdleFinishTimer = null;
991
+ this.pendingIdleFinishAt = 0;
992
+ // If a new user turn started during the grace window, we owe
993
+ // generating semantics to that turn — do not retroactively idle.
994
+ if (this.isWaitingForResponse) return;
995
+ // The timer firing without a cancelPendingIdleFinish call means
996
+ // no fresh applyGenerating happened during the grace window;
997
+ // the previous fake-blip is over. Commit the idle.
998
+ //
999
+ // Note: the previous "currentStatus === 'generating' → return"
1000
+ // guard caused stuck-generating sessions — finishResponse leaves
1001
+ // currentStatus='generating' on purpose (so the dashboard keeps
1002
+ // the spinner during the 2s grace), and then the timer fired
1003
+ // without cancellation but refused to commit because the very
1004
+ // status we are about to transition out of was still set.
1005
+ // Re-checking currentStatus there meant idle was unreachable.
1006
+ this.setStatus('idle', reason);
1007
+ this.callbacks.onStatusChange();
1008
+ }, IDLE_CONFIRMATION_GRACE_MS);
1009
+ }
1010
+
1011
+ private cancelPendingIdleFinish(reason: string): void {
1012
+ if (!this.pendingIdleFinishTimer) return;
1013
+ clearTimeout(this.pendingIdleFinishTimer);
1014
+ this.pendingIdleFinishTimer = null;
1015
+ this.pendingIdleFinishAt = 0;
1016
+ this.recordTrace('idle_finish_cancelled', { trigger: reason });
1017
+ }
1018
+
1019
+ // ─── Helpers ────────────────────────────────────────────────────────────
1020
+
1021
+ private armApprovalExitTimeout(): void {
1022
+ if (this.approvalExitTimeout) clearTimeout(this.approvalExitTimeout);
1023
+ this.approvalExitTimeout = setTimeout(() => {
1024
+ if (!this.hasActionableApproval()) return;
1025
+ const snap = this.transport.getSnapshot();
1026
+ const modal = typeof this.transport.runParseApproval === 'function'
1027
+ ? this.transport.runParseApproval(snap.recentOutputBuffer.slice(-500))
1028
+ : this.runParseApproval(snap);
1029
+ const detectStatus = typeof this.transport.runDetectStatus === 'function'
1030
+ ? this.transport.runDetectStatus(snap.recentOutputBuffer)
1031
+ : this.runDetectStatus(snap);
1032
+ const stillWaiting = detectStatus === 'waiting_approval' || !!modal;
1033
+ if (stillWaiting) {
1034
+ if (!modal) {
1035
+ LOG.warn('CLI', `[${this.provider.type}] approval timeout: no actionable modal; keeping fail-closed`);
1036
+ this.activeModal = null;
1037
+ this.callbacks.onStatusChange();
1038
+ this.armApprovalExitTimeout();
1039
+ return;
1040
+ }
1041
+ this.activeModal = modal;
1042
+ this.callbacks.onStatusChange();
1043
+ this.armApprovalExitTimeout();
1044
+ return;
1045
+ }
1046
+ LOG.warn('CLI', `[${this.provider.type}] Approval timeout — auto-clearing`);
1047
+ this.activeModal = null;
1048
+ this.lastApprovalResolvedAt = Date.now();
1049
+ this.setStatus('idle', 'approval_timeout');
1050
+ this.callbacks.onStatusChange();
1051
+ }, APPROVAL_EXIT_TIMEOUT_MS);
1052
+ }
1053
+
1054
+ private armIdleFinishCandidate(snap: CliBufferSnapshot, assistantLength: number): void {
1055
+ const now = Date.now();
1056
+ this.idleFinishCandidate = {
1057
+ armedAt: now,
1058
+ lastOutputAt: snap.lastOutputAt,
1059
+ lastScreenChangeAt: snap.lastScreenChangeAt,
1060
+ responseEpoch: this.responseEpoch,
1061
+ assistantLength,
1062
+ };
1063
+ if (this.settleTimer) clearTimeout(this.settleTimer);
1064
+ this.settleTimer = setTimeout(() => {
1065
+ this.settleTimer = null;
1066
+ this.evaluateSettled(this.transport.getSnapshot());
1067
+ }, this.timeouts.idleFinishConfirm);
1068
+ }
1069
+
1070
+ private shouldDeferIdleTimeoutFinish(): boolean {
1071
+ if (!this.isWaitingForResponse || this.hasActionableApproval()) return false;
1072
+ const snap = this.transport.getSnapshot();
1073
+ const detectFn = typeof this.transport.runDetectStatus === 'function'
1074
+ ? () => this.transport.runDetectStatus!(snap.recentOutputBuffer)
1075
+ : () => this.runDetectStatus(snap);
1076
+ const latestStatus = detectFn() || this.currentStatus;
1077
+ if (latestStatus === 'generating') {
1078
+ this.evaluateSettled(snap);
1079
+ return true;
1080
+ }
1081
+ return false;
1082
+ }
1083
+
1084
+ private hasRecentInteractiveActivity(snap: CliBufferSnapshot, now: number): boolean {
1085
+ const quietForMs = snap.lastNonEmptyOutputAt ? (now - snap.lastNonEmptyOutputAt) : Number.MAX_SAFE_INTEGER;
1086
+ const screenStableMs = snap.lastScreenChangeAt ? (now - snap.lastScreenChangeAt) : Number.MAX_SAFE_INTEGER;
1087
+ return quietForMs < this.timeouts.statusActivityHold || screenStableMs < this.timeouts.statusActivityHold;
1088
+ }
1089
+
1090
+ private hasMeaningfulResponseBuffer(snap: CliBufferSnapshot, normalizedPromptSnippet: string): boolean {
1091
+ const raw = String(snap.responseBuffer || '').trim();
1092
+ if (!raw) return false;
1093
+ const normalizedPrompt = compactPromptText(normalizedPromptSnippet);
1094
+ if (!normalizedPrompt) return true;
1095
+ const normalizedBuffer = compactPromptText(raw);
1096
+ if (!normalizedBuffer) return false;
1097
+ if (normalizedBuffer === normalizedPrompt) return false;
1098
+ if (normalizedBuffer.startsWith(normalizedPrompt)) {
1099
+ const remainder = normalizedBuffer.slice(normalizedPrompt.length)
1100
+ .replace(/[─═\-]+/g, '')
1101
+ .replace(/⏵⏵accepteditson\([^)]*\)/gi, '')
1102
+ .replace(/esctointerrupt/gi, '')
1103
+ .replace(/❯/g, '')
1104
+ .replace(/^[\s\-–—:;,.!/?]+/, '')
1105
+ .trim();
1106
+ return remainder.length > 0;
1107
+ }
1108
+ return true;
1109
+ }
1110
+
1111
+ private shouldDeferFinishForTranscript(parsed: any): boolean {
1112
+ // Honor only the explicit manifest opt-in. We used to also hard-code
1113
+ // codex-cli here, but that left codex sessions wedged in `generating`
1114
+ // whenever the PTY parser or native transcript missed the final
1115
+ // assistant line — a much more common failure mode than the original
1116
+ // background-tool race this was meant to guard against. If a provider
1117
+ // really needs the gate, the manifest can set
1118
+ // `requiresFinalAssistantBeforeIdle: true`.
1119
+ const requiresFinalAssistant = !!this.provider.requiresFinalAssistantBeforeIdle;
1120
+ if (!requiresFinalAssistant) return false;
1121
+ if (!this.isWaitingForResponse || !this.currentTurnScope || this.hasActionableApproval()) return false;
1122
+ const parsedStatus = typeof parsed?.status === 'string' ? parsed.status.trim() : '';
1123
+ if (parsedStatus !== 'idle') return true;
1124
+ if (parsed?.activeModal || parsed?.modal) return true;
1125
+ // For providers that own their history externally (e.g. SpecCliAdapter
1126
+ // reading native JSONL), parsed.messages only reflects PTY-visible
1127
+ // content which may include previous-turn assistant messages. Gate on
1128
+ // whether the *current turn* has a final assistant: find the last user
1129
+ // in parsed.messages, and check there is an assistant after it.
1130
+ // If no user found at all (e.g. PTY hid it), defer — the native-history
1131
+ // completion gate in cli-provider-instance will confirm via JSONL read.
1132
+ // For providers that own their history externally (e.g. SpecCliAdapter
1133
+ // reading native JSONL), parsed.messages may include previous-turn
1134
+ // assistant messages. Only an assistant that appears *after* the last
1135
+ // user message counts as evidence the current turn finished.
1136
+ const messages: any[] = Array.isArray(parsed?.messages) ? parsed.messages : [];
1137
+ let lastUserIdx = -1;
1138
+ for (let i = messages.length - 1; i >= 0; i--) {
1139
+ if (messages[i]?.role === 'user') { lastUserIdx = i; break; }
1140
+ }
1141
+ if (lastUserIdx < 0) {
1142
+ // No user message visible in PTY parser. Two sub-cases:
1143
+ // (a) messages is non-empty — some content was parsed but no user
1144
+ // line was found. Use the any-assistant fallback.
1145
+ // (b) messages is empty — the provider owns history externally
1146
+ // (e.g. SpecCliAdapter always returns []) and PTY gives us
1147
+ // nothing to judge. Do NOT defer here: deferring with empty
1148
+ // messages causes an infinite reschedule loop because
1149
+ // parsedStatusHasFinalStandardAssistantMessage also returns
1150
+ // false on empty input. Let cli-provider-instance's native-
1151
+ // history gate handle this case.
1152
+ if (messages.length === 0) return false;
1153
+ return !this.parsedStatusHasFinalStandardAssistantMessage(parsed);
1154
+ }
1155
+ // Check for a final standard assistant after the last user
1156
+ const hasCurrentTurnAssistant = messages.slice(lastUserIdx + 1).some((m: any) => {
1157
+ if (!m || m.role !== 'assistant') return false;
1158
+ if (typeof m.content !== 'string' || !m.content.trim()) return false;
1159
+ const kind = typeof m.kind === 'string' && m.kind.trim() ? m.kind.trim() : 'standard';
1160
+ return kind === 'standard' && m.meta?.streaming !== true;
1161
+ });
1162
+ return !hasCurrentTurnAssistant;
1163
+ }
1164
+
1165
+ private rescheduleTranscriptFinishCheck(reason: string): void {
1166
+ this.clearIdleFinishCandidate(reason);
1167
+ this.setStatus('generating', reason);
1168
+ if (this.idleTimeout) clearTimeout(this.idleTimeout);
1169
+ this.idleTimeout = setTimeout(() => {
1170
+ if (!this.isWaitingForResponse || this.hasActionableApproval()) return;
1171
+ this.evaluateSettled(this.transport.getSnapshot());
1172
+ }, this.timeouts.idleFinishConfirm);
1173
+ this.recordTrace('transcript_finish_deferred', { reason });
1174
+ }
1175
+
1176
+ private shouldRetryFinishResponse(snap: CliBufferSnapshot, commitResult: { hasAssistant: boolean; assistantContent: string }): boolean {
1177
+ if (!this.currentTurnScope) return false;
1178
+ if (this.hasActionableApproval()) return false;
1179
+ if (this.finishRetryCount >= MAX_FINISH_RETRIES) return false;
1180
+ if (commitResult.hasAssistant && commitResult.assistantContent.trim()) return false;
1181
+ if (this.runDetectStatus(snap) !== 'idle') return false;
1182
+ const now = Date.now();
1183
+ const quietForMs = snap.lastNonEmptyOutputAt ? (now - snap.lastNonEmptyOutputAt) : Number.MAX_SAFE_INTEGER;
1184
+ const screenStableMs = snap.lastScreenChangeAt ? (now - snap.lastScreenChangeAt) : 0;
1185
+ return quietForMs < 1200 || screenStableMs < 1200 || !commitResult.hasAssistant;
1186
+ }
1187
+
1188
+ private commitCurrentTranscript(snap: CliBufferSnapshot): { hasAssistant: boolean; assistantContent: string } {
1189
+ const parsed = this.runParseSession(snap);
1190
+ if (parsed && Array.isArray(parsed.messages)) {
1191
+ const parsedMessages = normalizeCliParsedMessages(parsed.messages, { scope: null, lastOutputAt: snap.lastOutputAt });
1192
+ const lastAssistant = [...parsedMessages].reverse().find((m) => m.role === 'assistant');
1193
+ if (lastAssistant) return { hasAssistant: true, assistantContent: lastAssistant.content || '' };
1194
+ }
1195
+ return { hasAssistant: false, assistantContent: '' };
1196
+ }
1197
+
1198
+ private maybeCommitVisibleIdleTranscript(session: ParsedSession, parsedMessages: CliChatMessage[], snap: CliBufferSnapshot): boolean {
1199
+ if (!this.provider.allowInputDuringGeneration) return false;
1200
+ if (!session || session.status !== 'idle' || !this.isWaitingForResponse || !this.currentTurnScope || this.activeModal || session.modal) return false;
1201
+ const visibleAssistant = [...parsedMessages].reverse().find((m) => m.role === 'assistant' && String(m.content || '').trim());
1202
+ if (!visibleAssistant) return false;
1203
+ this.resetActiveTurnState();
1204
+ this.callbacks.onTurnCompleted();
1205
+ this.setStatus('idle', 'script_idle_commit');
1206
+ this.callbacks.onStatusChange();
1207
+ this.transport.flushOutboundQueue();
1208
+ return true;
1209
+ }
1210
+
1211
+ private parsedStatusHasFinalAssistantMessage(parsed: any): boolean {
1212
+ const messages = Array.isArray(parsed?.messages) ? parsed.messages : [];
1213
+ const last = [...messages].reverse().find((m: any) => {
1214
+ if (!m || m.role !== 'assistant') return false;
1215
+ return typeof m.content === 'string' && m.content.trim().length > 0;
1216
+ });
1217
+ return !!last;
1218
+ }
1219
+
1220
+ private parsedStatusHasFinalStandardAssistantMessage(parsed: any): boolean {
1221
+ const messages = Array.isArray(parsed?.messages) ? parsed.messages : [];
1222
+ const last = [...messages].reverse().find((m: any) => {
1223
+ if (!m || m.role !== 'assistant') return false;
1224
+ if (typeof m.content !== 'string' || !m.content.trim()) return false;
1225
+ const kind = typeof m.kind === 'string' && m.kind.trim() ? m.kind.trim() : 'standard';
1226
+ return kind === 'standard' && m.meta?.streaming !== true;
1227
+ });
1228
+ return !!last;
1229
+ }
1230
+
1231
+ private recordTrace(type: string, payload: Record<string, any> = {}): void {
1232
+ const entry: CliTraceEntry = {
1233
+ id: ++this.traceSeq,
1234
+ at: Date.now(),
1235
+ type,
1236
+ status: this.currentStatus,
1237
+ isWaitingForResponse: this.isWaitingForResponse,
1238
+ activeModal: this.activeModal ? { message: this.activeModal.message, buttons: [...this.activeModal.buttons] } : null,
1239
+ payload,
1240
+ };
1241
+ this.traceEntries.push(entry);
1242
+ if (this.traceEntries.length > MAX_TRACE_ENTRIES) {
1243
+ this.traceEntries.splice(0, this.traceEntries.length - MAX_TRACE_ENTRIES);
1244
+ }
1245
+ }
1246
+ }