@adhdev/daemon-core 0.9.82-rc.40 → 0.9.82-rc.401

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