@adhdev/daemon-core 0.9.82-rc.38 → 0.9.82-rc.381

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