charness 4.2.0 → 4.3.1

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 (553) hide show
  1. package/CHANGELOG.md +168 -2
  2. package/DEVELOPMENT.md +58 -10
  3. package/LICENSE +331 -151
  4. package/MIGRATION_3_TO_4.md +8 -5
  5. package/README.md +21 -9
  6. package/SETUP.md +54 -10
  7. package/agent-plugin/README.md +10 -3
  8. package/agent-plugin/skills/charness-delegate-claude/SKILL.md +18 -27
  9. package/agent-plugin/skills/charness-delegate-opencode/SKILL.md +5 -3
  10. package/agent-plugin/skills/charness-orchestration/SKILL.md +62 -16
  11. package/dist/adapters/claudeCliAdapter.d.ts +4 -0
  12. package/dist/adapters/claudeCliAdapter.d.ts.map +1 -1
  13. package/dist/adapters/claudeCliAdapter.js +13 -0
  14. package/dist/adapters/claudeCliAdapter.js.map +1 -1
  15. package/dist/adapters/claudeJsonStreamAdapter.d.ts +136 -10
  16. package/dist/adapters/claudeJsonStreamAdapter.d.ts.map +1 -1
  17. package/dist/adapters/claudeJsonStreamAdapter.js +365 -77
  18. package/dist/adapters/claudeJsonStreamAdapter.js.map +1 -1
  19. package/dist/adapters/createAdapter.d.ts +12 -3
  20. package/dist/adapters/createAdapter.d.ts.map +1 -1
  21. package/dist/adapters/createAdapter.js +39 -13
  22. package/dist/adapters/createAdapter.js.map +1 -1
  23. package/dist/adapters/openCodeAdapter.d.ts +34 -0
  24. package/dist/adapters/openCodeAdapter.d.ts.map +1 -1
  25. package/dist/adapters/openCodeAdapter.js +118 -11
  26. package/dist/adapters/openCodeAdapter.js.map +1 -1
  27. package/dist/apiErrorRetry.d.ts +11 -3
  28. package/dist/apiErrorRetry.d.ts.map +1 -1
  29. package/dist/apiErrorRetry.js +33 -3
  30. package/dist/apiErrorRetry.js.map +1 -1
  31. package/dist/apiRetryKick.d.ts +18 -7
  32. package/dist/apiRetryKick.d.ts.map +1 -1
  33. package/dist/apiRetryKick.js +26 -13
  34. package/dist/apiRetryKick.js.map +1 -1
  35. package/dist/bot.d.ts +2 -6
  36. package/dist/bot.d.ts.map +1 -1
  37. package/dist/bot.js +2055 -653
  38. package/dist/bot.js.map +1 -1
  39. package/dist/cli/claudeProfiles.d.ts +28 -6
  40. package/dist/cli/claudeProfiles.d.ts.map +1 -1
  41. package/dist/cli/claudeProfiles.js +89 -22
  42. package/dist/cli/claudeProfiles.js.map +1 -1
  43. package/dist/cli.d.ts.map +1 -1
  44. package/dist/cli.js +2 -1
  45. package/dist/cli.js.map +1 -1
  46. package/dist/connectors/jira/answerSink.d.ts +102 -7
  47. package/dist/connectors/jira/answerSink.d.ts.map +1 -1
  48. package/dist/connectors/jira/answerSink.js +366 -60
  49. package/dist/connectors/jira/answerSink.js.map +1 -1
  50. package/dist/connectors/jira/answerThreads.d.ts +44 -0
  51. package/dist/connectors/jira/answerThreads.d.ts.map +1 -0
  52. package/dist/connectors/jira/answerThreads.js +85 -0
  53. package/dist/connectors/jira/answerThreads.js.map +1 -0
  54. package/dist/connectors/jira/client.d.ts +67 -2
  55. package/dist/connectors/jira/client.d.ts.map +1 -1
  56. package/dist/connectors/jira/client.js +176 -4
  57. package/dist/connectors/jira/client.js.map +1 -1
  58. package/dist/connectors/jira/config.d.ts +6 -0
  59. package/dist/connectors/jira/config.d.ts.map +1 -1
  60. package/dist/connectors/jira/config.js +14 -1
  61. package/dist/connectors/jira/config.js.map +1 -1
  62. package/dist/connectors/jira/connector.d.ts +19 -0
  63. package/dist/connectors/jira/connector.d.ts.map +1 -1
  64. package/dist/connectors/jira/connector.js +68 -6
  65. package/dist/connectors/jira/connector.js.map +1 -1
  66. package/dist/connectors/jira/contextPreamble.d.ts.map +1 -1
  67. package/dist/connectors/jira/contextPreamble.js +6 -1
  68. package/dist/connectors/jira/contextPreamble.js.map +1 -1
  69. package/dist/connectors/jira/inbound.d.ts +21 -6
  70. package/dist/connectors/jira/inbound.d.ts.map +1 -1
  71. package/dist/connectors/jira/inbound.js +22 -16
  72. package/dist/connectors/jira/inbound.js.map +1 -1
  73. package/dist/connectors/jira/issueBlocks.d.ts +8 -1
  74. package/dist/connectors/jira/issueBlocks.d.ts.map +1 -1
  75. package/dist/connectors/jira/issueBlocks.js +38 -2
  76. package/dist/connectors/jira/issueBlocks.js.map +1 -1
  77. package/dist/connectors/jira/operatorIssue.d.ts +28 -0
  78. package/dist/connectors/jira/operatorIssue.d.ts.map +1 -0
  79. package/dist/connectors/jira/operatorIssue.js +81 -0
  80. package/dist/connectors/jira/operatorIssue.js.map +1 -0
  81. package/dist/connectors/jira/outbound.d.ts +8 -4
  82. package/dist/connectors/jira/outbound.d.ts.map +1 -1
  83. package/dist/connectors/jira/outbound.js +16 -8
  84. package/dist/connectors/jira/outbound.js.map +1 -1
  85. package/dist/connectors/jira/outgoingFileCheck.d.ts +37 -0
  86. package/dist/connectors/jira/outgoingFileCheck.d.ts.map +1 -0
  87. package/dist/connectors/jira/outgoingFileCheck.js +279 -0
  88. package/dist/connectors/jira/outgoingFileCheck.js.map +1 -0
  89. package/dist/connectors/jira/outgoingFiles.d.ts +81 -0
  90. package/dist/connectors/jira/outgoingFiles.d.ts.map +1 -0
  91. package/dist/connectors/jira/outgoingFiles.js +268 -0
  92. package/dist/connectors/jira/outgoingFiles.js.map +1 -0
  93. package/dist/connectors/jira/progressComments.d.ts +69 -0
  94. package/dist/connectors/jira/progressComments.d.ts.map +1 -0
  95. package/dist/connectors/jira/progressComments.js +136 -0
  96. package/dist/connectors/jira/progressComments.js.map +1 -0
  97. package/dist/connectors/jira/prompt.d.ts +5 -1
  98. package/dist/connectors/jira/prompt.d.ts.map +1 -1
  99. package/dist/connectors/jira/prompt.js +23 -3
  100. package/dist/connectors/jira/prompt.js.map +1 -1
  101. package/dist/connectors/jira/promptSpill.js +1 -1
  102. package/dist/connectors/jira/promptSpill.js.map +1 -1
  103. package/dist/connectors/jira/trigger.d.ts +13 -5
  104. package/dist/connectors/jira/trigger.d.ts.map +1 -1
  105. package/dist/connectors/jira/trigger.js +13 -7
  106. package/dist/connectors/jira/trigger.js.map +1 -1
  107. package/dist/connectors/jira/uploadedFiles.d.ts +48 -0
  108. package/dist/connectors/jira/uploadedFiles.d.ts.map +1 -0
  109. package/dist/connectors/jira/uploadedFiles.js +123 -0
  110. package/dist/connectors/jira/uploadedFiles.js.map +1 -0
  111. package/dist/connectors/telegram/commands/backendSwitch.d.ts +9 -1
  112. package/dist/connectors/telegram/commands/backendSwitch.d.ts.map +1 -1
  113. package/dist/connectors/telegram/commands/backendSwitch.js +17 -8
  114. package/dist/connectors/telegram/commands/backendSwitch.js.map +1 -1
  115. package/dist/connectors/telegram/commands/botSkills.d.ts +2 -0
  116. package/dist/connectors/telegram/commands/botSkills.d.ts.map +1 -1
  117. package/dist/connectors/telegram/commands/botSkills.js +17 -2
  118. package/dist/connectors/telegram/commands/botSkills.js.map +1 -1
  119. package/dist/connectors/telegram/commands/claudeAccounts.d.ts +6 -0
  120. package/dist/connectors/telegram/commands/claudeAccounts.d.ts.map +1 -1
  121. package/dist/connectors/telegram/commands/claudeAccounts.js +22 -4
  122. package/dist/connectors/telegram/commands/claudeAccounts.js.map +1 -1
  123. package/dist/connectors/telegram/commands/compaction.d.ts +14 -3
  124. package/dist/connectors/telegram/commands/compaction.d.ts.map +1 -1
  125. package/dist/connectors/telegram/commands/compaction.js +261 -96
  126. package/dist/connectors/telegram/commands/compaction.js.map +1 -1
  127. package/dist/connectors/telegram/commands/limitReminders.d.ts +21 -0
  128. package/dist/connectors/telegram/commands/limitReminders.d.ts.map +1 -0
  129. package/dist/connectors/telegram/commands/limitReminders.js +95 -0
  130. package/dist/connectors/telegram/commands/limitReminders.js.map +1 -0
  131. package/dist/connectors/telegram/commands/limitsBoard.d.ts +4 -0
  132. package/dist/connectors/telegram/commands/limitsBoard.d.ts.map +1 -1
  133. package/dist/connectors/telegram/commands/limitsBoard.js +27 -6
  134. package/dist/connectors/telegram/commands/limitsBoard.js.map +1 -1
  135. package/dist/connectors/telegram/commands/modelProviders.d.ts +2 -2
  136. package/dist/connectors/telegram/commands/modelProviders.d.ts.map +1 -1
  137. package/dist/connectors/telegram/commands/modelProviders.js +27 -16
  138. package/dist/connectors/telegram/commands/modelProviders.js.map +1 -1
  139. package/dist/connectors/telegram/commands/topicCommand.d.ts.map +1 -1
  140. package/dist/connectors/telegram/commands/topicCommand.js +7 -2
  141. package/dist/connectors/telegram/commands/topicCommand.js.map +1 -1
  142. package/dist/connectors/telegram/commands/workerRoles.d.ts +25 -0
  143. package/dist/connectors/telegram/commands/workerRoles.d.ts.map +1 -0
  144. package/dist/connectors/telegram/commands/workerRoles.js +259 -0
  145. package/dist/connectors/telegram/commands/workerRoles.js.map +1 -0
  146. package/dist/connectors/telegram/groupWelcome.d.ts +12 -0
  147. package/dist/connectors/telegram/groupWelcome.d.ts.map +1 -0
  148. package/dist/connectors/telegram/groupWelcome.js +12 -0
  149. package/dist/connectors/telegram/groupWelcome.js.map +1 -0
  150. package/dist/connectors/telegram/inbound.d.ts +7 -0
  151. package/dist/connectors/telegram/inbound.d.ts.map +1 -1
  152. package/dist/connectors/telegram/inbound.js +10 -0
  153. package/dist/connectors/telegram/inbound.js.map +1 -1
  154. package/dist/connectors/telegram/outputFlushPlan.d.ts +12 -0
  155. package/dist/connectors/telegram/outputFlushPlan.d.ts.map +1 -1
  156. package/dist/connectors/telegram/outputFlushPlan.js +12 -0
  157. package/dist/connectors/telegram/outputFlushPlan.js.map +1 -1
  158. package/dist/connectors/telegram/runnerPairingMessages.d.ts +1 -1
  159. package/dist/connectors/telegram/topicIndicator.d.ts +1 -1
  160. package/dist/connectors/telegram/topicIndicator.d.ts.map +1 -1
  161. package/dist/connectors/telegram/topicIndicator.js +103 -5
  162. package/dist/connectors/telegram/topicIndicator.js.map +1 -1
  163. package/dist/effortLevels.d.ts +6 -0
  164. package/dist/effortLevels.d.ts.map +1 -1
  165. package/dist/effortLevels.js +6 -1
  166. package/dist/effortLevels.js.map +1 -1
  167. package/dist/i18n/de.d.ts.map +1 -1
  168. package/dist/i18n/de.js +95 -14
  169. package/dist/i18n/de.js.map +1 -1
  170. package/dist/i18n/en.d.ts.map +1 -1
  171. package/dist/i18n/en.js +95 -14
  172. package/dist/i18n/en.js.map +1 -1
  173. package/dist/i18n/es.d.ts.map +1 -1
  174. package/dist/i18n/es.js +95 -14
  175. package/dist/i18n/es.js.map +1 -1
  176. package/dist/i18n/fr.d.ts.map +1 -1
  177. package/dist/i18n/fr.js +95 -14
  178. package/dist/i18n/fr.js.map +1 -1
  179. package/dist/i18n/hi.d.ts.map +1 -1
  180. package/dist/i18n/hi.js +95 -14
  181. package/dist/i18n/hi.js.map +1 -1
  182. package/dist/i18n/ja.d.ts.map +1 -1
  183. package/dist/i18n/ja.js +95 -14
  184. package/dist/i18n/ja.js.map +1 -1
  185. package/dist/i18n/ka.d.ts.map +1 -1
  186. package/dist/i18n/ka.js +95 -14
  187. package/dist/i18n/ka.js.map +1 -1
  188. package/dist/i18n/pt.d.ts.map +1 -1
  189. package/dist/i18n/pt.js +95 -14
  190. package/dist/i18n/pt.js.map +1 -1
  191. package/dist/i18n/ru.d.ts.map +1 -1
  192. package/dist/i18n/ru.js +95 -14
  193. package/dist/i18n/ru.js.map +1 -1
  194. package/dist/i18n/uk.d.ts.map +1 -1
  195. package/dist/i18n/uk.js +95 -14
  196. package/dist/i18n/uk.js.map +1 -1
  197. package/dist/i18n/uz.d.ts.map +1 -1
  198. package/dist/i18n/uz.js +95 -14
  199. package/dist/i18n/uz.js.map +1 -1
  200. package/dist/i18n/zh.d.ts.map +1 -1
  201. package/dist/i18n/zh.js +95 -14
  202. package/dist/i18n/zh.js.map +1 -1
  203. package/dist/instanceSettings.d.ts +24 -2
  204. package/dist/instanceSettings.d.ts.map +1 -1
  205. package/dist/instanceSettings.js +75 -3
  206. package/dist/instanceSettings.js.map +1 -1
  207. package/dist/limitNotes/engine.d.ts +47 -0
  208. package/dist/limitNotes/engine.d.ts.map +1 -0
  209. package/dist/limitNotes/engine.js +98 -0
  210. package/dist/limitNotes/engine.js.map +1 -0
  211. package/dist/limitNotes/noteText.d.ts +33 -0
  212. package/dist/limitNotes/noteText.d.ts.map +1 -0
  213. package/dist/limitNotes/noteText.js +55 -0
  214. package/dist/limitNotes/noteText.js.map +1 -0
  215. package/dist/limitNotes/plan.d.ts +147 -0
  216. package/dist/limitNotes/plan.d.ts.map +1 -0
  217. package/dist/limitNotes/plan.js +323 -0
  218. package/dist/limitNotes/plan.js.map +1 -0
  219. package/dist/limitNotes/reminderChoices.d.ts +30 -0
  220. package/dist/limitNotes/reminderChoices.d.ts.map +1 -0
  221. package/dist/limitNotes/reminderChoices.js +48 -0
  222. package/dist/limitNotes/reminderChoices.js.map +1 -0
  223. package/dist/limitNotes/service.d.ts +106 -0
  224. package/dist/limitNotes/service.d.ts.map +1 -0
  225. package/dist/limitNotes/service.js +169 -0
  226. package/dist/limitNotes/service.js.map +1 -0
  227. package/dist/openCodeSessionTitle.js +1 -1
  228. package/dist/openCodeSessionTitle.js.map +1 -1
  229. package/dist/outputTrace.d.ts +19 -0
  230. package/dist/outputTrace.d.ts.map +1 -1
  231. package/dist/outputTrace.js +23 -2
  232. package/dist/outputTrace.js.map +1 -1
  233. package/dist/platform/answerSink.d.ts +23 -0
  234. package/dist/platform/answerSink.d.ts.map +1 -1
  235. package/dist/platform/answerSink.js.map +1 -1
  236. package/dist/platform/operatorAlert.d.ts +24 -0
  237. package/dist/platform/operatorAlert.d.ts.map +1 -0
  238. package/dist/platform/operatorAlert.js +9 -0
  239. package/dist/platform/operatorAlert.js.map +1 -0
  240. package/dist/postToSession.d.ts +34 -2
  241. package/dist/postToSession.d.ts.map +1 -1
  242. package/dist/postToSession.js +31 -2
  243. package/dist/postToSession.js.map +1 -1
  244. package/dist/remoteRun/exitCodes.d.ts +2 -2
  245. package/dist/remoteRun/exitCodes.d.ts.map +1 -1
  246. package/dist/remoteRun/exitCodes.js +2 -2
  247. package/dist/remoteRun/exitCodes.js.map +1 -1
  248. package/dist/remoteRun/foreground.d.ts.map +1 -1
  249. package/dist/remoteRun/foreground.js +5 -1
  250. package/dist/remoteRun/foreground.js.map +1 -1
  251. package/dist/remoteRun/runnerClient.d.ts +1 -1
  252. package/dist/remoteRun/runnerClient.d.ts.map +1 -1
  253. package/dist/remoteRun/runnerClient.js +3 -3
  254. package/dist/remoteRun/runnerClient.js.map +1 -1
  255. package/dist/requests/answerRequest.d.ts +3 -0
  256. package/dist/requests/answerRequest.d.ts.map +1 -1
  257. package/dist/requests/answerRequest.js +9 -2
  258. package/dist/requests/answerRequest.js.map +1 -1
  259. package/dist/requests/limitWaitAnswer.d.ts +14 -0
  260. package/dist/requests/limitWaitAnswer.d.ts.map +1 -1
  261. package/dist/requests/limitWaitAnswer.js +26 -4
  262. package/dist/requests/limitWaitAnswer.js.map +1 -1
  263. package/dist/requests/requestHeader.d.ts +37 -5
  264. package/dist/requests/requestHeader.d.ts.map +1 -1
  265. package/dist/requests/requestHeader.js +70 -17
  266. package/dist/requests/requestHeader.js.map +1 -1
  267. package/dist/requests/scheduleWait.d.ts +79 -0
  268. package/dist/requests/scheduleWait.d.ts.map +1 -0
  269. package/dist/requests/scheduleWait.js +101 -0
  270. package/dist/requests/scheduleWait.js.map +1 -0
  271. package/dist/requests/sessionTurnProbe.d.ts +26 -3
  272. package/dist/requests/sessionTurnProbe.d.ts.map +1 -1
  273. package/dist/requests/sessionTurnProbe.js +22 -3
  274. package/dist/requests/sessionTurnProbe.js.map +1 -1
  275. package/dist/requests/topicRequestSettle.d.ts +13 -7
  276. package/dist/requests/topicRequestSettle.d.ts.map +1 -1
  277. package/dist/requests/topicRequestSettle.js +2 -2
  278. package/dist/requests/topicRequestSettle.js.map +1 -1
  279. package/dist/requests/trackerTurnPoster.d.ts +30 -0
  280. package/dist/requests/trackerTurnPoster.d.ts.map +1 -0
  281. package/dist/requests/trackerTurnPoster.js +36 -0
  282. package/dist/requests/trackerTurnPoster.js.map +1 -0
  283. package/dist/requests/types.d.ts +26 -5
  284. package/dist/requests/types.d.ts.map +1 -1
  285. package/dist/requests/wakeUpEngine.d.ts +201 -12
  286. package/dist/requests/wakeUpEngine.d.ts.map +1 -1
  287. package/dist/requests/wakeUpEngine.js +514 -44
  288. package/dist/requests/wakeUpEngine.js.map +1 -1
  289. package/dist/requests/wakeUpRules.d.ts +185 -14
  290. package/dist/requests/wakeUpRules.d.ts.map +1 -1
  291. package/dist/requests/wakeUpRules.js +169 -36
  292. package/dist/requests/wakeUpRules.js.map +1 -1
  293. package/dist/resumeContext.d.ts +2 -2
  294. package/dist/resumeContext.js +3 -3
  295. package/dist/resumeContext.js.map +1 -1
  296. package/dist/runnerUtility/adminService.js +1 -1
  297. package/dist/runnerUtility/adminService.js.map +1 -1
  298. package/dist/runnerUtility/guiAgent.d.ts +1 -1
  299. package/dist/runnerUtility/guiAgent.d.ts.map +1 -1
  300. package/dist/runnerUtility/guiAgent.js +1 -1
  301. package/dist/runnerUtility/guiAgent.js.map +1 -1
  302. package/dist/runnerUtility/managedNode.d.ts +3 -3
  303. package/dist/runnerUtility/managedNode.d.ts.map +1 -1
  304. package/dist/runnerUtility/managedNode.js +2 -2
  305. package/dist/runnerUtility/managedNode.js.map +1 -1
  306. package/dist/runnerUtility/runnerConfig.d.ts +1 -1
  307. package/dist/runnerUtility/runnerHome.d.ts +1 -1
  308. package/dist/runnerUtility/runnerHome.js +1 -1
  309. package/dist/runnerUtility/serviceCommon.d.ts +1 -1
  310. package/dist/runnerUtility/serviceCommon.d.ts.map +1 -1
  311. package/dist/runnerUtility/serviceCommon.js +1 -1
  312. package/dist/runnerUtility/serviceCommon.js.map +1 -1
  313. package/dist/runners/bootstrapLine.js +1 -1
  314. package/dist/runners/hubPackage.d.ts +1 -1
  315. package/dist/runners/hubPackage.js +3 -3
  316. package/dist/runners/hubPackage.js.map +1 -1
  317. package/dist/runners/hubPaths.d.ts +1 -1
  318. package/dist/runners/hubPaths.d.ts.map +1 -1
  319. package/dist/runners/runnerLock.d.ts +2 -2
  320. package/dist/runners/runnerLock.d.ts.map +1 -1
  321. package/dist/runners/runnerLock.js +2 -2
  322. package/dist/runners/runnerLock.js.map +1 -1
  323. package/dist/scheduler/checkRun.d.ts +2 -0
  324. package/dist/scheduler/checkRun.d.ts.map +1 -1
  325. package/dist/scheduler/checkRun.js +5 -1
  326. package/dist/scheduler/checkRun.js.map +1 -1
  327. package/dist/scheduler/delivery.d.ts +57 -0
  328. package/dist/scheduler/delivery.d.ts.map +1 -1
  329. package/dist/scheduler/delivery.js +152 -14
  330. package/dist/scheduler/delivery.js.map +1 -1
  331. package/dist/scheduler/injection.d.ts +6 -0
  332. package/dist/scheduler/injection.d.ts.map +1 -1
  333. package/dist/scheduler/injection.js +10 -0
  334. package/dist/scheduler/injection.js.map +1 -1
  335. package/dist/scheduler/mcpSurface.d.ts +68 -4
  336. package/dist/scheduler/mcpSurface.d.ts.map +1 -1
  337. package/dist/scheduler/mcpSurface.js +363 -189
  338. package/dist/scheduler/mcpSurface.js.map +1 -1
  339. package/dist/scheduler/rebindResume.d.ts +24 -0
  340. package/dist/scheduler/rebindResume.d.ts.map +1 -1
  341. package/dist/scheduler/rebindResume.js +32 -0
  342. package/dist/scheduler/rebindResume.js.map +1 -1
  343. package/dist/scheduler/scheduleToolWording.d.ts +29 -0
  344. package/dist/scheduler/scheduleToolWording.d.ts.map +1 -0
  345. package/dist/scheduler/scheduleToolWording.js +117 -0
  346. package/dist/scheduler/scheduleToolWording.js.map +1 -0
  347. package/dist/scheduler/scheduledRunTarget.d.ts +90 -0
  348. package/dist/scheduler/scheduledRunTarget.d.ts.map +1 -0
  349. package/dist/scheduler/scheduledRunTarget.js +92 -0
  350. package/dist/scheduler/scheduledRunTarget.js.map +1 -0
  351. package/dist/scheduler/store.d.ts +2 -0
  352. package/dist/scheduler/store.d.ts.map +1 -1
  353. package/dist/scheduler/store.js +2 -0
  354. package/dist/scheduler/store.js.map +1 -1
  355. package/dist/scheduler/types.d.ts +10 -0
  356. package/dist/scheduler/types.d.ts.map +1 -1
  357. package/dist/scheduler/workerWatch.d.ts +2 -0
  358. package/dist/scheduler/workerWatch.d.ts.map +1 -1
  359. package/dist/scheduler/workerWatch.js +3 -3
  360. package/dist/scheduler/workerWatch.js.map +1 -1
  361. package/dist/selfUpdate/constants.d.ts +2 -0
  362. package/dist/selfUpdate/constants.d.ts.map +1 -1
  363. package/dist/selfUpdate/constants.js +3 -1
  364. package/dist/selfUpdate/constants.js.map +1 -1
  365. package/dist/selfUpdate/emittedSource.d.ts.map +1 -1
  366. package/dist/selfUpdate/emittedSource.js +1 -1
  367. package/dist/selfUpdate/emittedSource.js.map +1 -1
  368. package/dist/selfUpdate/updateRuntime.js +1 -1
  369. package/dist/selfUpdate/updateRuntime.js.map +1 -1
  370. package/dist/sessionPick.d.ts +1 -1
  371. package/dist/sessionPick.js +1 -1
  372. package/dist/shutdown.d.ts +12 -0
  373. package/dist/shutdown.d.ts.map +1 -1
  374. package/dist/shutdown.js +11 -0
  375. package/dist/shutdown.js.map +1 -1
  376. package/dist/startupPromptBuffer.d.ts +35 -6
  377. package/dist/startupPromptBuffer.d.ts.map +1 -1
  378. package/dist/startupPromptBuffer.js +70 -21
  379. package/dist/startupPromptBuffer.js.map +1 -1
  380. package/dist/state.d.ts +173 -25
  381. package/dist/state.d.ts.map +1 -1
  382. package/dist/state.js +282 -58
  383. package/dist/state.js.map +1 -1
  384. package/dist/testTimings.d.ts +8 -3
  385. package/dist/testTimings.d.ts.map +1 -1
  386. package/dist/testTimings.js +15 -2
  387. package/dist/testTimings.js.map +1 -1
  388. package/dist/threadContextPreamble.d.ts +7 -0
  389. package/dist/threadContextPreamble.d.ts.map +1 -1
  390. package/dist/threadContextPreamble.js +11 -0
  391. package/dist/threadContextPreamble.js.map +1 -1
  392. package/dist/threadRouting.d.ts +12 -0
  393. package/dist/threadRouting.d.ts.map +1 -1
  394. package/dist/threadRouting.js +15 -0
  395. package/dist/threadRouting.js.map +1 -1
  396. package/dist/todos/midTurn.d.ts +15 -41
  397. package/dist/todos/midTurn.d.ts.map +1 -1
  398. package/dist/todos/midTurn.js +27 -171
  399. package/dist/todos/midTurn.js.map +1 -1
  400. package/dist/types.d.ts +147 -23
  401. package/dist/types.d.ts.map +1 -1
  402. package/dist/types.js +10 -0
  403. package/dist/types.js.map +1 -1
  404. package/dist/utils/backendSwitchPlan.d.ts +3 -3
  405. package/dist/utils/backendSwitchPlan.js +3 -3
  406. package/dist/utils/claudeAccountAlert.d.ts +104 -0
  407. package/dist/utils/claudeAccountAlert.d.ts.map +1 -0
  408. package/dist/utils/claudeAccountAlert.js +130 -0
  409. package/dist/utils/claudeAccountAlert.js.map +1 -0
  410. package/dist/utils/claudeAccountPickerPlan.d.ts +7 -0
  411. package/dist/utils/claudeAccountPickerPlan.d.ts.map +1 -1
  412. package/dist/utils/claudeAccountPickerPlan.js +13 -2
  413. package/dist/utils/claudeAccountPickerPlan.js.map +1 -1
  414. package/dist/utils/claudeAuthRefusal.d.ts +122 -0
  415. package/dist/utils/claudeAuthRefusal.d.ts.map +1 -0
  416. package/dist/utils/claudeAuthRefusal.js +228 -0
  417. package/dist/utils/claudeAuthRefusal.js.map +1 -0
  418. package/dist/utils/claudeCompactHook.d.ts +6 -6
  419. package/dist/utils/claudeCompactHook.js +8 -8
  420. package/dist/utils/claudeCompactHook.js.map +1 -1
  421. package/dist/utils/claudeProfileUsageViews.d.ts +54 -2
  422. package/dist/utils/claudeProfileUsageViews.d.ts.map +1 -1
  423. package/dist/utils/claudeProfileUsageViews.js +44 -1
  424. package/dist/utils/claudeProfileUsageViews.js.map +1 -1
  425. package/dist/utils/claudeProfiles.d.ts.map +1 -1
  426. package/dist/utils/claudeProfiles.js +10 -1
  427. package/dist/utils/claudeProfiles.js.map +1 -1
  428. package/dist/utils/claudeRuntimeInfo.d.ts +24 -0
  429. package/dist/utils/claudeRuntimeInfo.d.ts.map +1 -1
  430. package/dist/utils/claudeRuntimeInfo.js +128 -3
  431. package/dist/utils/claudeRuntimeInfo.js.map +1 -1
  432. package/dist/utils/claudeScheduledJobs.d.ts +6 -2
  433. package/dist/utils/claudeScheduledJobs.d.ts.map +1 -1
  434. package/dist/utils/claudeScheduledJobs.js +10 -2
  435. package/dist/utils/claudeScheduledJobs.js.map +1 -1
  436. package/dist/utils/claudeSessionTitle.js +1 -1
  437. package/dist/utils/claudeSessionTitle.js.map +1 -1
  438. package/dist/utils/claudeStreamJson.d.ts +28 -2
  439. package/dist/utils/claudeStreamJson.d.ts.map +1 -1
  440. package/dist/utils/claudeStreamJson.js +33 -3
  441. package/dist/utils/claudeStreamJson.js.map +1 -1
  442. package/dist/utils/claudeTranscriptEpoch.d.ts +14 -0
  443. package/dist/utils/claudeTranscriptEpoch.d.ts.map +1 -1
  444. package/dist/utils/claudeTranscriptEpoch.js +79 -19
  445. package/dist/utils/claudeTranscriptEpoch.js.map +1 -1
  446. package/dist/utils/claudeUsage.d.ts +103 -7
  447. package/dist/utils/claudeUsage.d.ts.map +1 -1
  448. package/dist/utils/claudeUsage.js +108 -15
  449. package/dist/utils/claudeUsage.js.map +1 -1
  450. package/dist/utils/compactOnIdle.d.ts +139 -29
  451. package/dist/utils/compactOnIdle.d.ts.map +1 -1
  452. package/dist/utils/compactOnIdle.js +163 -36
  453. package/dist/utils/compactOnIdle.js.map +1 -1
  454. package/dist/utils/conversationEnding.d.ts +76 -0
  455. package/dist/utils/conversationEnding.d.ts.map +1 -0
  456. package/dist/utils/conversationEnding.js +117 -0
  457. package/dist/utils/conversationEnding.js.map +1 -0
  458. package/dist/utils/doctorLine.d.ts +10 -0
  459. package/dist/utils/doctorLine.d.ts.map +1 -1
  460. package/dist/utils/doctorLine.js +16 -0
  461. package/dist/utils/doctorLine.js.map +1 -1
  462. package/dist/utils/fallbackBridge.d.ts.map +1 -1
  463. package/dist/utils/fallbackBridge.js +2 -1
  464. package/dist/utils/fallbackBridge.js.map +1 -1
  465. package/dist/utils/fallbackChain.d.ts +2 -0
  466. package/dist/utils/fallbackChain.d.ts.map +1 -1
  467. package/dist/utils/fallbackChain.js +4 -3
  468. package/dist/utils/fallbackChain.js.map +1 -1
  469. package/dist/utils/fallbackSwitchNotice.d.ts +11 -4
  470. package/dist/utils/fallbackSwitchNotice.d.ts.map +1 -1
  471. package/dist/utils/fallbackSwitchNotice.js +9 -5
  472. package/dist/utils/fallbackSwitchNotice.js.map +1 -1
  473. package/dist/utils/fileSendService.d.ts +31 -0
  474. package/dist/utils/fileSendService.d.ts.map +1 -1
  475. package/dist/utils/fileSendService.js +45 -2
  476. package/dist/utils/fileSendService.js.map +1 -1
  477. package/dist/utils/jsonStreamHost.d.ts +2 -0
  478. package/dist/utils/jsonStreamHost.d.ts.map +1 -1
  479. package/dist/utils/jsonStreamHost.js +4 -1
  480. package/dist/utils/jsonStreamHost.js.map +1 -1
  481. package/dist/utils/jsonStreamPendingWork.d.ts +14 -2
  482. package/dist/utils/jsonStreamPendingWork.d.ts.map +1 -1
  483. package/dist/utils/jsonStreamPendingWork.js +25 -5
  484. package/dist/utils/jsonStreamPendingWork.js.map +1 -1
  485. package/dist/utils/jsonStreamUnconsumedInput.d.ts +80 -0
  486. package/dist/utils/jsonStreamUnconsumedInput.d.ts.map +1 -0
  487. package/dist/utils/jsonStreamUnconsumedInput.js +99 -0
  488. package/dist/utils/jsonStreamUnconsumedInput.js.map +1 -0
  489. package/dist/utils/limitEpisodeRecovery.d.ts +43 -4
  490. package/dist/utils/limitEpisodeRecovery.d.ts.map +1 -1
  491. package/dist/utils/limitEpisodeRecovery.js +107 -20
  492. package/dist/utils/limitEpisodeRecovery.js.map +1 -1
  493. package/dist/utils/limitHeldPrompts.d.ts +21 -11
  494. package/dist/utils/limitHeldPrompts.d.ts.map +1 -1
  495. package/dist/utils/limitHeldPrompts.js +12 -9
  496. package/dist/utils/limitHeldPrompts.js.map +1 -1
  497. package/dist/utils/limitRemindersScreenPlan.d.ts +63 -0
  498. package/dist/utils/limitRemindersScreenPlan.d.ts.map +1 -0
  499. package/dist/utils/limitRemindersScreenPlan.js +121 -0
  500. package/dist/utils/limitRemindersScreenPlan.js.map +1 -0
  501. package/dist/utils/limitSwitchPlan.d.ts +51 -14
  502. package/dist/utils/limitSwitchPlan.d.ts.map +1 -1
  503. package/dist/utils/limitSwitchPlan.js +33 -15
  504. package/dist/utils/limitSwitchPlan.js.map +1 -1
  505. package/dist/utils/limitsBoardPlan.d.ts +16 -7
  506. package/dist/utils/limitsBoardPlan.d.ts.map +1 -1
  507. package/dist/utils/limitsBoardPlan.js +41 -9
  508. package/dist/utils/limitsBoardPlan.js.map +1 -1
  509. package/dist/utils/lostWork.d.ts +16 -2
  510. package/dist/utils/lostWork.d.ts.map +1 -1
  511. package/dist/utils/lostWork.js +16 -3
  512. package/dist/utils/lostWork.js.map +1 -1
  513. package/dist/utils/messageContext.d.ts +2 -2
  514. package/dist/utils/messageContext.js +2 -2
  515. package/dist/utils/midTurnInbox.d.ts +79 -0
  516. package/dist/utils/midTurnInbox.d.ts.map +1 -0
  517. package/dist/utils/midTurnInbox.js +265 -0
  518. package/dist/utils/midTurnInbox.js.map +1 -0
  519. package/dist/utils/promptDelivery.d.ts +70 -22
  520. package/dist/utils/promptDelivery.d.ts.map +1 -1
  521. package/dist/utils/promptDelivery.js +100 -42
  522. package/dist/utils/promptDelivery.js.map +1 -1
  523. package/dist/utils/topicIndicatorPlan.d.ts +13 -3
  524. package/dist/utils/topicIndicatorPlan.d.ts.map +1 -1
  525. package/dist/utils/topicIndicatorPlan.js +26 -4
  526. package/dist/utils/topicIndicatorPlan.js.map +1 -1
  527. package/dist/utils/topicRequest.d.ts +3 -0
  528. package/dist/utils/topicRequest.d.ts.map +1 -1
  529. package/dist/utils/topicRequest.js +4 -0
  530. package/dist/utils/topicRequest.js.map +1 -1
  531. package/dist/utils/workerRoles.d.ts +122 -0
  532. package/dist/utils/workerRoles.d.ts.map +1 -0
  533. package/dist/utils/workerRoles.js +160 -0
  534. package/dist/utils/workerRoles.js.map +1 -0
  535. package/dist/utils/workerRolesScreenPlan.d.ts +118 -0
  536. package/dist/utils/workerRolesScreenPlan.d.ts.map +1 -0
  537. package/dist/utils/workerRolesScreenPlan.js +232 -0
  538. package/dist/utils/workerRolesScreenPlan.js.map +1 -0
  539. package/dist/utils/workingSignals.d.ts +59 -0
  540. package/dist/utils/workingSignals.d.ts.map +1 -0
  541. package/dist/utils/workingSignals.js +60 -0
  542. package/dist/utils/workingSignals.js.map +1 -0
  543. package/licensing.json +88 -0
  544. package/npm-shrinkwrap.json +2 -2
  545. package/package.json +7 -7
  546. package/{remoteRun → runner-scripts}/runner.sh +6 -3
  547. package/LICENSE-COMMERCIAL.md +0 -142
  548. package/dist/agentTrigger.d.ts +0 -28
  549. package/dist/agentTrigger.d.ts.map +0 -1
  550. package/dist/agentTrigger.js +0 -53
  551. package/dist/agentTrigger.js.map +0 -1
  552. /package/{remoteRun → runner-scripts}/ensureNode.sh +0 -0
  553. /package/{remoteRun → runner-scripts}/runner-package-lock.json +0 -0
@@ -33,10 +33,11 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.ClaudeJsonStreamAdapter = exports.claudeJsonStreamUsageLogPrefix = void 0;
36
+ exports.ClaudeJsonStreamAdapter = exports.claudeJsonStreamUsageLogPrefix = exports.streamOutputBatchMs = void 0;
37
37
  const crypto_1 = require("crypto");
38
38
  const events_1 = require("events");
39
39
  const fs = __importStar(require("fs"));
40
+ const types_1 = require("../types");
40
41
  const sessionKey_1 = require("../sessionKey");
41
42
  const apiErrorRetry_1 = require("../apiErrorRetry");
42
43
  const transcriptErrorTime_1 = require("../utils/transcriptErrorTime");
@@ -68,6 +69,7 @@ const adapterNames_1 = require("./adapterNames");
68
69
  const claudeCodeVersion_1 = require("../utils/claudeCodeVersion");
69
70
  const sessionLaunchDefaults_1 = require("./sessionLaunchDefaults");
70
71
  const jsonStreamPendingWork_1 = require("../utils/jsonStreamPendingWork");
72
+ const jsonStreamUnconsumedInput_1 = require("../utils/jsonStreamUnconsumedInput");
71
73
  const lostWork_1 = require("../utils/lostWork");
72
74
  const claudeScheduledJobs_1 = require("../utils/claudeScheduledJobs");
73
75
  /**
@@ -79,12 +81,39 @@ const claudeScheduledJobs_1 = require("../utils/claudeScheduledJobs");
79
81
  * stops the process on one instance while the other spawns the next.
80
82
  */
81
83
  const stopsInFlightByKey = new Map();
84
+ /**
85
+ * The number the next spawned, re-spawned or adopted process gets ({@link StreamSession.processGeneration}). MODULE-level for the same
86
+ * reason as {@link stopsInFlightByKey}: a `/claude_mode` switch between the idle and the per-turn instance keeps the conversation's request
87
+ * watches, and a number both instances handed out would read the new process as the one a prompt was written to — a message that died
88
+ * unread with the old process would read as taken in (review 21 #1 a). It starts above `unnumberedProcessGeneration`, the name the
89
+ * wake-up probe gives a live session of a backend that cannot number its processes.
90
+ */
91
+ let nextProcessGeneration = types_1.unnumberedProcessGeneration + 1;
92
+ /**
93
+ * The re-spawns of each conversation that are under way or about to start ({@link ClaudeJsonStreamAdapter.waitForRespawn}): a model,
94
+ * effort or account change replaces the process outside the bot's session queue, with the process down for seconds. MODULE-level, like
95
+ * {@link stopsInFlightByKey}: the bot asks whichever instance the topic runs now. Each entry settles (never rejects) once its re-spawn
96
+ * is over, whatever its end.
97
+ */
98
+ const respawnsInFlightByKey = new Map();
99
+ /** Record `respawn` as under way for `conversationKey` until it settles. */
100
+ function noteRespawnInFlight(conversationKey, respawn) {
101
+ const settled = respawn.then(() => undefined, () => undefined);
102
+ const inFlight = respawnsInFlightByKey.get(conversationKey) ?? new Set();
103
+ inFlight.add(settled);
104
+ respawnsInFlightByKey.set(conversationKey, inFlight);
105
+ void settled.then(() => {
106
+ inFlight.delete(settled);
107
+ if (inFlight.size === 0 && respawnsInFlightByKey.get(conversationKey) === inFlight)
108
+ respawnsInFlightByKey.delete(conversationKey);
109
+ });
110
+ }
82
111
  /**
83
112
  * @description Coalesce window for streamed answer/thinking deltas before an
84
113
  * `output`/`thinking` emit — the CLI streams per-token, so raw per-delta emits
85
114
  * would flood Telegram with edits. Mirrors OpenCode's `sseOutputBatchMs` (500).
86
115
  */
87
- const streamOutputBatchMs = 350;
116
+ exports.streamOutputBatchMs = 350;
88
117
  /** Prefix of the per-turn token accounting line (L-D11); the process-level e2e
89
118
  * and the live cache check read it. */
90
119
  exports.claudeJsonStreamUsageLogPrefix = '[ClaudeJson] usage ';
@@ -172,6 +201,13 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
172
201
  /** No TUI banner → keep the bot's `agent.ready` cue + one-shot boot ping (L2). */
173
202
  selfGreetsOnStart = false;
174
203
  sessions = new Map();
204
+ /**
205
+ * The compactions the bot did NOT issue that completed in each conversation (the CLI's own overflow compaction), by conversation key:
206
+ * `AgentAdapter.getOwnCompactionCount`. Kept here, not on the process's session — every spawn and every adopt would start it at 0, and
207
+ * two processes in a row that each compacted by themselves would both read 1, no change between them. Dropped when the conversation is
208
+ * released (`finalizeExternalExit`), never by a suspend or a re-spawn.
209
+ */
210
+ ownCompactionCounts = new Map();
175
211
  claudePath = (0, resolveBinary_1.resolveClaudeBinary)();
176
212
  writeFifo;
177
213
  /** How long a user turn waits for a CLI that reads nothing, and a write for a reader that takes nothing (tests shorten it). */
@@ -377,19 +413,19 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
377
413
  pollTimer: null, pollDelayMs: pollBackoff_1.basePollIntervalMs, unchangedStreak: 0,
378
414
  isOversizeWarned: false, lastPersistedTailOffset: 0,
379
415
  reader: new claudeStreamJson_1.ClaudeStreamLineReader(),
380
- isActive: true, isStopping: false, isSuspending: false, isRespawning: false, isBusy: false, unconsumedInputCount: 0,
416
+ isActive: true, isStopping: false, isSuspending: false, isRespawning: false, processGeneration: this.createProcessGeneration(), isBusy: false, unconsumedInputs: [],
381
417
  lastStdoutActivityAt: Date.now(), outstandingToolUseIds: new Set(),
382
418
  model: opts.model, reportedModel: null, effort: opts.effort,
383
- configDir: opts.configDir, isConfigDirSwitchPending: false, startCostUsd,
384
- currentResponseText: '', emittedLength: 0, outputTimer: null,
419
+ configDir: opts.configDir, isConfigDirSwitchPending: false, isConfigDirSwitchReleased: false, startCostUsd,
420
+ currentResponseText: '', emittedLength: 0, isAnswerCursorUnknown: false, isAnswerEmittedInTurn: false, outputTimer: null,
385
421
  reasoningText: '', reasoningStartedAt: null, reasoningTimer: null, reasoningActive: false,
386
422
  toolNamesById: new Map(), questionToolUseIds: new Set(),
387
423
  subagentActive: false, childResponseText: '', childEmittedLength: 0, childOutputTimer: null,
388
424
  pendingInitResolve: null, startExitDetail: null, initRequestId: null, pendingControlRequests: new Map(),
389
425
  compactionInProgress: false, pendingCompaction: null,
390
- pendingQuestion: null, apiErrorFired: false, rejectedResetAtMs: null, swallowNextAbortError: false,
426
+ pendingQuestion: null, apiErrorFired: false, rejectedResetAtMs: null, turnApiErrorCode: null, swallowNextAbortError: false,
391
427
  lastWatermarkOffset: -1,
392
- backgroundTasks: new Map(), notificationTurnPendingSince: null, lastTurnEndedAt: Date.now(), isCompactionResultPending: false, scheduledJobs: new Map(),
428
+ backgroundTasks: new Map(), notificationTurnPendingSince: null, isCliOwnTurn: false, lastTurnEndedAt: Date.now(), isCompactionResultPending: false, scheduledJobs: new Map(),
393
429
  claudeCodeVersion: null, applyingChunk: null,
394
430
  adoptCatchUpOffset: null, adoptCatchUpResolvers: [], isTailHeld: false,
395
431
  };
@@ -496,6 +532,8 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
496
532
  return;
497
533
  console.warn(`[ClaudeJson] busy-idle watchdog: ${(0, sessionKey_1.keyToString)(session.key)} idle ${jsonStreamBusyWatchdog_1.busyIdleWatchdogMs}ms with nothing in flight — clearing stuck busy (missed terminal result?)`);
498
534
  session.isBusy = false;
535
+ // A turn that never reported its `result` leaves no marks behind.
536
+ session.unconsumedInputs = (0, jsonStreamUnconsumedInput_1.getInputsWithoutEchoMarks)(session.unconsumedInputs);
499
537
  this.finishReasoning(session);
500
538
  // The record must not keep saying "turn in flight": an adopt would restore the cleared flag.
501
539
  this.jsonStreamTailWriter?.(session.key, buildTailRecord(session, session.lastPersistedTailOffset));
@@ -581,6 +619,10 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
581
619
  this.clearTimers(session);
582
620
  session.isActive = false;
583
621
  this.sessions.delete((0, sessionKey_1.keyToString)(key));
622
+ // The conversation is released (an explicit stop, or a process that died): what was counted of its compactions goes with it. An idle
623
+ // stop (suspend) and a re-spawn keep it — the conversation lives on, and the next process counts on from here.
624
+ if (!session.isSuspending)
625
+ this.ownCompactionCounts.delete((0, sessionKey_1.keyToString)(key));
584
626
  this.settleAdoptCatchUp(session, true);
585
627
  this.closeFifo(session);
586
628
  const stderrTail = session.isStopping ? '' : (0, jsonStreamHost_1.readStderrTail)(session.paths.stderrFile);
@@ -718,7 +760,7 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
718
760
  // tool call leaves no frame after the tail offset to rebuild it from. The
719
761
  // replayed/live events then keep it right (deltas/toolUse set it, `result`
720
762
  // clears it) — see `applyAction`.
721
- isActive: true, isStopping: false, isSuspending: false, isRespawning: false, isBusy: isTurnInFlight, unconsumedInputCount: 0,
763
+ isActive: true, isStopping: false, isSuspending: false, isRespawning: false, processGeneration: this.createProcessGeneration(), isBusy: isTurnInFlight, unconsumedInputs: [],
722
764
  // The outstanding tools come from the record too: they veto the busy-idle watchdog, which would
723
765
  // otherwise clear the restored turn after its silence window and let the stale-tool stop kill it.
724
766
  lastStdoutActivityAt: Date.now(), outstandingToolUseIds: new Set(outstandingToolUseIds),
@@ -727,21 +769,23 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
727
769
  model: launchFlags.model, reportedModel: null, effort: launchFlags.effort,
728
770
  // The account the surviving process runs on is in its own wrapper; the bot compares it with the topic's pick.
729
771
  // A switch the user picked while the process worked survives the reload: it still applies at the turn's end.
730
- configDir: (0, jsonStreamHost_1.readWrapperScriptConfigDir)(paths.wrapperFile), isConfigDirSwitchPending: adoptedTail.isConfigDirSwitchPending, startCostUsd: null,
731
- currentResponseText: '', emittedLength: 0, outputTimer: null,
772
+ configDir: (0, jsonStreamHost_1.readWrapperScriptConfigDir)(paths.wrapperFile), isConfigDirSwitchPending: adoptedTail.isConfigDirSwitchPending, isConfigDirSwitchReleased: false, startCostUsd: null,
773
+ currentResponseText: '', emittedLength: 0, isAnswerCursorUnknown: adoptedTail.isAnswerEmittedInTurn, isAnswerEmittedInTurn: adoptedTail.isAnswerEmittedInTurn, outputTimer: null,
732
774
  reasoningText: '', reasoningStartedAt: null, reasoningTimer: null, reasoningActive: false,
733
775
  toolNamesById: new Map(), questionToolUseIds: new Set(),
734
776
  subagentActive: false, childResponseText: '', childEmittedLength: 0, childOutputTimer: null,
735
777
  pendingInitResolve: null, startExitDetail: null, initRequestId: null, pendingControlRequests: new Map(),
736
778
  compactionInProgress: false, pendingCompaction: null,
737
779
  pendingQuestion: this.readQuestionSidecar(paths),
738
- apiErrorFired: false, rejectedResetAtMs: null, swallowNextAbortError: false,
780
+ apiErrorFired: false, rejectedResetAtMs: null, turnApiErrorCode: null, swallowNextAbortError: false,
739
781
  lastWatermarkOffset: -1,
740
782
  // The frames that built the list and reported the version lie before the
741
783
  // tail offset (not replayed): both come from the persisted record, with the
742
784
  // rest of the pending work (a turn announced, the hold's start, scheduled jobs).
743
785
  backgroundTasks: new Map(adoptedTail.backgroundTasks.map((task) => [task.taskId, task.description])),
744
786
  notificationTurnPendingSince: adoptedTail.notificationTurnPendingSinceMs,
787
+ // A turn in flight at the adopt is taken for the bot's own: nothing tells otherwise from the record.
788
+ isCliOwnTurn: false,
745
789
  lastTurnEndedAt: adoptedTail.lastTurnEndedAtMs ?? Date.now(),
746
790
  isCompactionResultPending: false,
747
791
  scheduledJobs: new Map(adoptedTail.scheduledJobs.map((job) => [job.jobId, job])),
@@ -815,6 +859,7 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
815
859
  session.adoptCatchUpOffset = null;
816
860
  resolveAdoptReplayWaiters(session);
817
861
  // A switch the user picked before the reload, whose turn ended meanwhile, applies now that the state is current.
862
+ this.releasePendingConfigDirSwitch(session);
818
863
  this.applyPendingConfigDirSwitch(session);
819
864
  }
820
865
  /** Restore a pending question persisted by a previous bot life (see
@@ -932,16 +977,21 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
932
977
  const session = this.sessions.get((0, sessionKey_1.keyToString)(key));
933
978
  return session?.isActive === true;
934
979
  }
980
+ /** A process being stopped stays active until its exit, but takes no more input (`writeStdin` abandons a write on `isStopping`). */
981
+ checkIsAcceptingInput(key) {
982
+ const session = this.sessions.get((0, sessionKey_1.keyToString)(key));
983
+ return session !== undefined && this.checkIsLiveForRespawn(session);
984
+ }
935
985
  flushPendingOutput(key) {
936
986
  const session = this.sessions.get((0, sessionKey_1.keyToString)(key));
937
987
  if (!session?.isActive)
938
988
  return;
939
989
  // The text the process wrote an instant before its tool call may not have been polled yet (the poll lags by its backoff):
940
- // read it first, or the batch flushed below would miss it and the answer would still overtake it. Not from inside the
941
- // handling of a chunk (a question event asks for it): that read is going on right now, and a second one would handle the
942
- // lines behind the chunk ahead of the rest of it. Nor from an adopted tail the boot still holds: its replay is read only
943
- // from the boot's release on (`releaseAdoptedTails`), and what it holds lands after the answer — nothing to warn of.
944
- if (!session.applyingChunk && !session.isTailHeld)
990
+ // read it first, or the batch flushed below would miss it and the answer would still overtake it. `refreshWorkingState` reads
991
+ // nothing from inside the handling of a chunk (a question event asks for it here). Not from an adopted tail the boot still holds
992
+ // either: its replay is read only from the boot's release on (`releaseAdoptedTails`), and what it holds lands after the answer —
993
+ // nothing to warn of, so it is not asked at all.
994
+ if (!session.isTailHeld)
945
995
  this.refreshWorkingState(key);
946
996
  this.flushAnswer(session, false);
947
997
  }
@@ -949,7 +999,17 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
949
999
  return this.sessions.get((0, sessionKey_1.keyToString)(key))?.isBusy === true;
950
1000
  }
951
1001
  checkHasUnconsumedInput(key) {
952
- return (this.sessions.get((0, sessionKey_1.keyToString)(key))?.unconsumedInputCount ?? 0) > 0;
1002
+ const session = this.sessions.get((0, sessionKey_1.keyToString)(key));
1003
+ return session !== undefined && this.getUnconsumedInputsOnTheirWay(session).length > 0;
1004
+ }
1005
+ /**
1006
+ * The written messages that may still be on their way to the CLI's turn — a bounded judgement, see {@link getInputsOnTheirWay}.
1007
+ * Every read drops what is no longer on its way from the list too, so a stale entry never waits for the next write to go.
1008
+ */
1009
+ getUnconsumedInputsOnTheirWay(session) {
1010
+ const inputsOnTheirWay = (0, jsonStreamUnconsumedInput_1.getInputsOnTheirWay)({ inputs: session.unconsumedInputs, isBusy: session.isBusy, now: Date.now() });
1011
+ session.unconsumedInputs = inputsOnTheirWay;
1012
+ return inputsOnTheirWay;
953
1013
  }
954
1014
  /**
955
1015
  * @description Whether the process is WORKING and must not be stopped (L-D2):
@@ -962,19 +1022,28 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
962
1022
  const session = this.sessions.get((0, sessionKey_1.keyToString)(key));
963
1023
  if (!session?.isActive)
964
1024
  return false;
965
- return session.isBusy || this.checkHasBackgroundWork(key);
1025
+ return session.isBusy || this.getBackgroundWorkSignals(key).length > 0;
966
1026
  }
967
1027
  /**
968
- * The agent's own pending work (background tasks and scheduled jobs within the hold, a finished task's turn on its
969
- * way), input not yet taken in, a compaction in flight — "working" minus the turn (L-D2).
1028
+ * @description What keeps the process working apart from its running turn (L-D2), by name: the agent's own pending work
1029
+ * (background tasks and scheduled jobs within the hold, a finished task's turn on its way), input not yet taken in, a
1030
+ * compaction in flight. Empty for an unknown / inactive session. Each signal is BOUNDED, so none holds a turn-less process
1031
+ * for good: pending work by the hold, input by the grace the CLI has to start the turn that takes it in
1032
+ * (`unconsumedInputGraceMs`), a compaction by the longest the bot itself waits for one (`compactionAbsoluteTimeoutMs`).
970
1033
  */
971
- checkHasBackgroundWork(key) {
1034
+ getBackgroundWorkSignals(key) {
972
1035
  const session = this.sessions.get((0, sessionKey_1.keyToString)(key));
973
1036
  if (!session?.isActive)
974
- return false;
975
- return (0, jsonStreamPendingWork_1.checkHasPendingWork)(this.getPendingWorkInput(session))
976
- || session.unconsumedInputCount > 0
977
- || session.compactionInProgress;
1037
+ return [];
1038
+ const signals = (0, jsonStreamPendingWork_1.getPendingWorkSignals)(this.getPendingWorkInput(session));
1039
+ const inputsOnTheirWay = this.getUnconsumedInputsOnTheirWay(session);
1040
+ if (inputsOnTheirWay.length > 0)
1041
+ signals.push({ kind: 'unconsumedInput', count: inputsOnTheirWay.length });
1042
+ // The flag alone is not enough: a compaction nobody awaits any more, or one older than the bot's own timeout, is stale.
1043
+ if (session.compactionInProgress && session.pendingCompaction !== null && Date.now() - session.pendingCompaction.startedAt < jsonStreamBusyWatchdog_1.compactionAbsoluteTimeoutMs) {
1044
+ signals.push({ kind: 'compaction' });
1045
+ }
1046
+ return signals;
978
1047
  }
979
1048
  /**
980
1049
  * @description The hold left for the session's background tasks / scheduled jobs (`utils/jsonStreamPendingWork.ts`):
@@ -992,6 +1061,10 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
992
1061
  const session = this.sessions.get((0, sessionKey_1.keyToString)(key));
993
1062
  if (!session?.isActive)
994
1063
  return;
1064
+ // Not from inside the handling of a chunk: that read is going on right now, and a second one would handle the lines behind the
1065
+ // chunk ahead of the rest of it.
1066
+ if (session.applyingChunk)
1067
+ return;
995
1068
  // A held tail is read only from the boot's release on; a caller that decides on the state waits for `whenAdoptReplayed`.
996
1069
  if (session.isTailHeld) {
997
1070
  console.warn(`[ClaudeJson] ${(0, sessionKey_1.keyToString)(key)}: the working state was asked for before the boot released the adopted session; its output is not read yet`);
@@ -1089,6 +1162,22 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1089
1162
  return { version: null, model: null, contextWindowTokens: null, contextUsedTokens: null };
1090
1163
  }
1091
1164
  }
1165
+ /** The transcript of the live session of `key`, `null` when it has none or is not active — read in the caller's tick (see `AgentAdapter.getContextUsedTokens`). */
1166
+ getActiveTranscriptPath(key) {
1167
+ const session = this.sessions.get((0, sessionKey_1.keyToString)(key));
1168
+ return session?.isActive ? (0, claudeCliAdapter_1.getClaudeTranscriptPath)(session.workDir, session.sessionId) : null;
1169
+ }
1170
+ getOwnCompactionCount(key) {
1171
+ return this.ownCompactionCounts.get((0, sessionKey_1.keyToString)(key)) ?? 0;
1172
+ }
1173
+ async getContextUsedTokens(key) {
1174
+ const filePath = this.getActiveTranscriptPath(key);
1175
+ return filePath === null ? null : (0, claudeRuntimeInfo_1.readClaudeContextUsedTokens)(filePath);
1176
+ }
1177
+ async getFirstCallContextTokens(key) {
1178
+ const filePath = this.getActiveTranscriptPath(key);
1179
+ return filePath === null ? null : (0, claudeRuntimeInfo_1.readClaudeFirstCallContextTokens)(filePath);
1180
+ }
1092
1181
  getClaudeSessionId(key) {
1093
1182
  return this.sessions.get((0, sessionKey_1.keyToString)(key))?.sessionId ?? null;
1094
1183
  }
@@ -1150,7 +1239,7 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1150
1239
  });
1151
1240
  }, jsonStreamBusyWatchdog_1.compactionWaitPollMs);
1152
1241
  timer.unref?.();
1153
- session.pendingCompaction = { resolve, timer, sawSuccess: false };
1242
+ session.pendingCompaction = { resolve, timer, sawSuccess: false, startedAt };
1154
1243
  session.compactionInProgress = true;
1155
1244
  session.isCompactionResultPending = true;
1156
1245
  // Fresh turn: reset the answer cursor + idle-watchdog clock, mark busy.
@@ -1194,7 +1283,7 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1194
1283
  * @description {@link sendInput} that resolves once the user turn is written WHOLE into the CLI's stdin, and rejects
1195
1284
  * when it could not be (`EAGAIN` past the stall budget, a dead reader, a broken stream): the prompt never reached the
1196
1285
  * agent, and its caller is told so instead of believing it delivered. The state a turn start sets is set before the
1197
- * first await, as `sendInput` always did; a write that failed takes back its unconsumed-input count, and the busy flag
1286
+ * first await, as `sendInput` always did; a write that failed takes its message back off the unconsumed-input list, and the busy flag
1198
1287
  * when nothing of the CLI was seen since. A session that is not active drops the input, as before (logged).
1199
1288
  */
1200
1289
  sendInputAndWait(key, input) {
@@ -1205,9 +1294,13 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1205
1294
  }
1206
1295
  const wasBusy = session.isBusy;
1207
1296
  // A fresh user turn begins → reset the answer cursor so its first tail is a
1208
- // new message (the bot also flips `needsNewMessage` for delta adapters).
1209
- session.currentResponseText = '';
1210
- session.emittedLength = 0;
1297
+ // new message (the bot also flips `needsNewMessage` for delta adapters). Only
1298
+ // when no turn is running: the tail is polled, so the `result` of a turn that
1299
+ // has just ended may still be unread, and it settles against THIS cursor —
1300
+ // reset here, its text would be emitted as the start of the new turn's, glued
1301
+ // to it. The running turn's own end resets it (`handleTurnEnd`).
1302
+ if (!wasBusy)
1303
+ this.resetAnswerCursor(session);
1211
1304
  session.apiErrorFired = false;
1212
1305
  session.isBusy = true;
1213
1306
  // A fresh turn resets the idle-watchdog clock: without this a session that
@@ -1218,14 +1311,21 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1218
1311
  // The turn in flight is persisted at once (same offset, flipped flag): a restart
1219
1312
  // during a long, silent tool call finds no frame after the offset to rebuild it.
1220
1313
  this.jsonStreamTailWriter?.(key, buildTailRecord(session, session.lastPersistedTailOffset));
1221
- return this.writeUserMessage(session, input).catch((error) => {
1222
- // Nothing of this turn reached the CLI: it is not owed an echo, and — unless the CLI showed life since — it is as busy as it was.
1223
- session.unconsumedInputCount = Math.max(0, session.unconsumedInputCount - 1);
1314
+ return this.writeUserMessage(session, input, wasBusy).catch((error) => {
1315
+ // Nothing of this turn reached the CLI: it is not owed an echo (the write took its message back off the list), and — unless
1316
+ // the CLI showed life since — it is as busy as it was.
1224
1317
  if (session.lastStdoutActivityAt === turnStartedAt)
1225
1318
  session.isBusy = wasBusy;
1226
1319
  throw error;
1227
1320
  });
1228
1321
  }
1322
+ /** Forget the answer text of the turn in progress: what was streamed so far was emitted (or dropped) and belongs to a turn that is over. */
1323
+ resetAnswerCursor(session) {
1324
+ session.currentResponseText = '';
1325
+ session.emittedLength = 0;
1326
+ session.isAnswerCursorUnknown = false;
1327
+ session.isAnswerEmittedInTurn = false;
1328
+ }
1229
1329
  sendSignal(key, _signal) {
1230
1330
  this.sendInterrupt(key);
1231
1331
  }
@@ -1247,6 +1347,9 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1247
1347
  // the typing indicator drops immediately. If output resumes, a delta re-arms
1248
1348
  // busy; if a `result` does arrive, `handleTurnEnd` is a harmless no-op.
1249
1349
  session.isBusy = false;
1350
+ // The aborted turn's marks are void. (The marker the CLI writes AFTER the interrupt request is no echo of anything queued either, but
1351
+ // it arrives after this and may still mark an entry: the next turn's `init` forgets that mark.)
1352
+ session.unconsumedInputs = (0, jsonStreamUnconsumedInput_1.getInputsWithoutEchoMarks)(session.unconsumedInputs);
1250
1353
  session.outstandingToolUseIds.clear();
1251
1354
  // When the CLI DOES emit a terminal `result{is_error}` for this abort, it
1252
1355
  // carries no text → `claudeStreamJson` labels it the literal `'API error'`.
@@ -1255,10 +1358,18 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1255
1358
  // and any bare `/esc` mid-turn). Consumed by the next `handleTurnEnd`.
1256
1359
  session.swallowNextAbortError = true;
1257
1360
  }
1258
- /** Write one user turn, counting it until Claude echoes it back (it has read it); settles as its write does. */
1259
- writeUserMessage(session, content) {
1260
- session.unconsumedInputCount += 1;
1261
- return this.writeStdin(session, { type: 'user', message: { role: 'user', content } }, { userText: content });
1361
+ /**
1362
+ * Write one user turn, keeping it on the unconsumed list until Claude echoes it back (it has read it); settles as its write
1363
+ * does, and a write that failed takes its message back off the list — no echo is owed for it. What went stale before this
1364
+ * write is dropped first: it must not come back to life beside the new message.
1365
+ */
1366
+ writeUserMessage(session, content, wasBusy) {
1367
+ const pending = { text: content, since: Date.now(), hasUnmatchedEcho: false };
1368
+ session.unconsumedInputs = [...(0, jsonStreamUnconsumedInput_1.getInputsOnTheirWay)({ inputs: session.unconsumedInputs, isBusy: wasBusy, now: pending.since }), pending];
1369
+ return this.writeStdin(session, { type: 'user', message: { role: 'user', content } }, { userText: content }).catch((error) => {
1370
+ session.unconsumedInputs = session.unconsumedInputs.filter((unconsumed) => unconsumed !== pending);
1371
+ throw error;
1372
+ });
1262
1373
  }
1263
1374
  /**
1264
1375
  * Enqueue one stream-json frame onto the stdin FIFO. The per-session chain keeps wire order and waits out a full
@@ -1521,11 +1632,14 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1521
1632
  // it `/status` and the pinned banner showed no model at all on a default
1522
1633
  // start / resume / adopt (nothing ever set the `--model` pick).
1523
1634
  this.handleInit(session, action);
1524
- // `init` opens every turn: the turn runs from here, not from its first output.
1525
- this.markTurnStarted(session);
1635
+ // `init` opens every turn: the turn runs from here, not from its first output. Always a new turn — also after an interrupt, when
1636
+ // the CLI's marker line has set the busy flag again: the marker's mark must not outlive the turn that opens here.
1637
+ this.markTurnStarted(session, { isNewTurn: true });
1526
1638
  return;
1527
1639
  case 'turnStarted':
1528
- this.markTurnStarted(session);
1640
+ // `session_state_changed` `running` also comes back in the MIDDLE of a turn (after a permission or a question: `requires_action` →
1641
+ // `running`): it opens a turn only when none was running. A job's firing always opens one.
1642
+ this.markTurnStarted(session, { isNewTurn: action.wakeupSource !== null || !session.isBusy, isJobFiring: action.wakeupSource !== null });
1529
1643
  if (action.wakeupSource !== null)
1530
1644
  session.scheduledJobs = (0, claudeScheduledJobs_1.getScheduledJobsAfterFiring)(session.scheduledJobs, action.wakeupSource);
1531
1645
  return;
@@ -1581,11 +1695,21 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1581
1695
  case 'rateLimit':
1582
1696
  this.handleRateLimit(session, action);
1583
1697
  return;
1698
+ case 'apiErrorCode':
1699
+ session.turnApiErrorCode = action.code;
1700
+ return;
1584
1701
  case 'userEcho':
1585
- // Claude has read one of our user messages. A message written mid-turn
1586
- // is taken into the RUNNING turn, so the session is busy from here until
1587
- // the turn's `result`, even if an earlier `result` already cleared it.
1588
- session.unconsumedInputCount = Math.max(0, session.unconsumedInputCount - 1);
1702
+ // Claude has read one or SEVERAL of our user messages (those it takes in together are one echo). A message written
1703
+ // mid-turn is taken into the RUNNING turn, so the session is busy from here until the turn's `result`, even if an
1704
+ // earlier `result` already cleared it.
1705
+ // With anything of ours listed, the echo is one of ours (matched, or tied to the oldest entry below): the turn is the bot's.
1706
+ if (session.unconsumedInputs.length > 0)
1707
+ session.isCliOwnTurn = false;
1708
+ const inputsAfterEcho = (0, jsonStreamUnconsumedInput_1.getInputsAfterEcho)(session.unconsumedInputs, action.text);
1709
+ // An echo that took nothing off the list is a message the turn took in in a shape nothing here matches: it is tied to the
1710
+ // oldest entry not yet marked, which the turn's end drops. With nothing listed it marks nothing — a user line of the CLI's
1711
+ // own takes no message written after it with it.
1712
+ session.unconsumedInputs = inputsAfterEcho.length === session.unconsumedInputs.length ? (0, jsonStreamUnconsumedInput_1.getInputsWithOldestEchoMarked)(inputsAfterEcho) : inputsAfterEcho;
1589
1713
  session.isBusy = true;
1590
1714
  return;
1591
1715
  }
@@ -1607,8 +1731,23 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1607
1731
  if (session.backgroundTasks.has(action.taskId))
1608
1732
  session.notificationTurnPendingSince = Date.now();
1609
1733
  }
1610
- /** A turn began (its `init`, the CLI's running state, a scheduled job firing): busy from here; an announced turn has shown. */
1611
- markTurnStarted(session) {
1734
+ /**
1735
+ * A turn began (its `init`, the CLI's running state, a scheduled job firing): busy from here; an announced turn has shown.
1736
+ * `isNewTurn`: a turn really OPENS here, so the marks of the turn before are forgotten — one that never reported a result must not
1737
+ * leave marks for a later turn's end to act on. A `running` inside a running turn (after a permission or a question) is no new turn.
1738
+ */
1739
+ markTurnStarted(session, options) {
1740
+ // A turn the bot never wrote to (a task's notification, a scheduled job) starting while nothing ran: a running turn counts every
1741
+ // listed message as queued behind it, so what went stale before it must not be revived by it.
1742
+ if (!session.isBusy)
1743
+ this.getUnconsumedInputsOnTheirWay(session);
1744
+ if (options.isNewTurn) {
1745
+ session.unconsumedInputs = (0, jsonStreamUnconsumedInput_1.getInputsWithoutEchoMarks)(session.unconsumedInputs);
1746
+ // Whose turn opens: the CLI's own when a finished task or a job starts it, or when nothing of ours waits to be taken in; an
1747
+ // echo of ours later in the turn makes it ours (`userEcho`). A bot-issued `/compact` is the bot's.
1748
+ const isStartedByCli = options.isJobFiring === true || session.notificationTurnPendingSince !== null || session.unconsumedInputs.length === 0;
1749
+ session.isCliOwnTurn = !session.compactionInProgress && isStartedByCli;
1750
+ }
1612
1751
  session.isBusy = true;
1613
1752
  session.notificationTurnPendingSince = null;
1614
1753
  }
@@ -1632,6 +1771,8 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1632
1771
  if (!session.pendingCompaction) {
1633
1772
  // The CLI's own compaction (a context overflow mid-turn, or one met while replaying the downtime tail):
1634
1773
  // nobody waits for it, but the conversation's context was replaced all the same.
1774
+ const conversationKey = (0, sessionKey_1.keyToString)(session.key);
1775
+ this.ownCompactionCounts.set(conversationKey, (this.ownCompactionCounts.get(conversationKey) ?? 0) + 1);
1635
1776
  this.emit('contextCompacted', session.key, action.trigger);
1636
1777
  return;
1637
1778
  }
@@ -1665,7 +1806,7 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1665
1806
  session.outputTimer = setTimeout(() => {
1666
1807
  session.outputTimer = null;
1667
1808
  this.flushAnswer(session, false);
1668
- }, streamOutputBatchMs);
1809
+ }, exports.streamOutputBatchMs);
1669
1810
  }
1670
1811
  flushAnswer(session, isFinal) {
1671
1812
  if (session.outputTimer) {
@@ -1675,6 +1816,7 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1675
1816
  const tail = session.currentResponseText.slice(session.emittedLength);
1676
1817
  if (tail) {
1677
1818
  session.emittedLength = session.currentResponseText.length;
1819
+ session.isAnswerEmittedInTurn = true;
1678
1820
  const meta = isFinal ? { isFinal: true } : {};
1679
1821
  // NO isContinuation: `outputsDeltas` adapters let the transports synthesise it.
1680
1822
  this.emit('output', session.key, tail, meta);
@@ -1697,7 +1839,7 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1697
1839
  session.reasoningTimer = setTimeout(() => {
1698
1840
  session.reasoningTimer = null;
1699
1841
  this.emit('thinking', session.key, { phase: 'live', text: session.reasoningText });
1700
- }, streamOutputBatchMs);
1842
+ }, exports.streamOutputBatchMs);
1701
1843
  }
1702
1844
  finishReasoning(session) {
1703
1845
  if (!session.reasoningActive)
@@ -1745,7 +1887,10 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1745
1887
  }
1746
1888
  /** A `CronCreate` / `CronDelete` / `ScheduleWakeup` result changes the session-only jobs the process holds. */
1747
1889
  trackScheduledJob(session, tool, output) {
1748
- if (tool === claudeScheduledJobs_1.cronCreateToolName || tool === claudeScheduledJobs_1.loopWakeupToolName) {
1890
+ if (tool === claudeScheduledJobs_1.loopWakeupToolName && (0, claudeScheduledJobs_1.checkIsLoopStoppedResult)(output)) {
1891
+ session.scheduledJobs.delete(claudeScheduledJobs_1.loopWakeupJobId);
1892
+ }
1893
+ else if (tool === claudeScheduledJobs_1.cronCreateToolName || tool === claudeScheduledJobs_1.loopWakeupToolName) {
1749
1894
  const job = tool === claudeScheduledJobs_1.cronCreateToolName ? (0, claudeScheduledJobs_1.getScheduledJobFromCronCreateResult)(output) : (0, claudeScheduledJobs_1.getScheduledJobFromLoopWakeupResult)(output);
1750
1895
  if (job)
1751
1896
  session.scheduledJobs.set(job.jobId, job);
@@ -1777,7 +1922,7 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1777
1922
  // `drainStdoutTail`).
1778
1923
  if (checkIsEmitCaughtUp(session))
1779
1924
  this.persistTailOffset(session);
1780
- }, streamOutputBatchMs);
1925
+ }, exports.streamOutputBatchMs);
1781
1926
  }
1782
1927
  else {
1783
1928
  this.markSubagentActive(session);
@@ -1805,9 +1950,16 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1805
1950
  });
1806
1951
  session.startCostUsd = null;
1807
1952
  }
1953
+ // What was queued behind the turn is the next turn's, an error `result`'s included (`applyTurnEnd` keeps that queue): read as the
1954
+ // turn end leaves it — the entries this turn took in, in a shape nothing matches, dropped.
1955
+ const hasInputOnItsWay = (0, jsonStreamUnconsumedInput_1.getInputsAfterTurnEnd)(session.unconsumedInputs, Date.now()).length > 0;
1808
1956
  this.applyTurnEnd(session, action);
1957
+ // The turn's text has been emitted (or dropped) by now: the next turn starts from an empty cursor, whenever its prompt was written.
1958
+ this.resetAnswerCursor(session);
1959
+ // Released before the bot hears of this end, applied after its handlers: its turn probe reads the re-spawn as coming from here.
1960
+ this.releasePendingConfigDirSwitch(session);
1809
1961
  // After the handlers above: the bot's per-turn stop (L5) reads the session's state as settled here.
1810
- this.emit('turnEnded', session.key);
1962
+ this.emit('turnEnded', session.key, { hasInputOnItsWay });
1811
1963
  this.applyPendingConfigDirSwitch(session);
1812
1964
  }
1813
1965
  applyTurnEnd(session, action) {
@@ -1826,12 +1978,16 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1826
1978
  if (!session.isCompactionResultPending)
1827
1979
  session.lastTurnEndedAt = Date.now();
1828
1980
  session.isCompactionResultPending = false;
1829
- // Self-healing accounting: a FAILED turn (usage limit, API error) may never echo the messages that were
1830
- // queued behind it, and a count left above zero would make the session look "working" forever — a pending
1831
- // account switch would never fire. A message still genuinely queued is echoed later (the decrement clamps
1832
- // at zero and the echo marks the session busy again), so zeroing here can only under-count briefly.
1833
- if (action.isError)
1834
- session.unconsumedInputCount = 0;
1981
+ // The queue is taken in by the turn that starts next, its wait starting over from this end — less what this turn took in in a shape
1982
+ // nothing matches (the marked entries). A FAILED turn (usage limit, API error) keeps its queue too: measured on 2.1.330 (an unknown
1983
+ // `--model`; an HTTP 400, and an HTTP 429 after its ten retries, from a loopback API — `utils/jsonStreamUnconsumedInput.ts`
1984
+ // `getInputsAfterTurnEnd` has the command), the CLI writes a new `init` 0.02–0.2 s after the error `result` and runs the queued
1985
+ // message as its own turn; in a turn that fails, the echo comes at its end, right before its `result`. Emptied, the list read that message as taken
1986
+ // in before its turn began: the per-turn stop killed the process ahead of it, and the bot decided its request's turn ended. The grace
1987
+ // (`unconsumedInputGraceMs`) still bounds each entry, so one the CLI never echoes holds nothing for good — a deferred account switch
1988
+ // included: it waits for that turn's end like any work (`checkIsConfigDirSwitchDue`), and fires at it.
1989
+ session.unconsumedInputs = (0, jsonStreamUnconsumedInput_1.getInputsAfterTurnEnd)(session.unconsumedInputs, Date.now());
1990
+ session.isCliOwnTurn = false;
1835
1991
  session.outstandingToolUseIds.clear();
1836
1992
  this.finishReasoning(session);
1837
1993
  this.clearSubagent(session);
@@ -1856,6 +2012,9 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1856
2012
  // (read-and-clear so it can never leak onto a later, unrelated turn).
1857
2013
  const swallowAbortError = session.swallowNextAbortError;
1858
2014
  session.swallowNextAbortError = false;
2015
+ // The error code belongs to THIS turn only, read-and-clear like the flag above.
2016
+ const apiErrorCode = session.turnApiErrorCode;
2017
+ session.turnApiErrorCode = null;
1859
2018
  if (action.isError && action.errorText) {
1860
2019
  // The turn is over, whatever it ended on: the text it streamed goes out FIRST and at once (a debounced flush would
1861
2020
  // let the notice overtake it), and the saved offset moves past the turn. A text left in the 350 ms batch held the
@@ -1868,14 +2027,16 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1868
2027
  console.log(`[ClaudeJson] swallowed interrupt-aborted turn error for ${(0, sessionKey_1.keyToString)(session.key)}: ${action.errorText}`);
1869
2028
  return;
1870
2029
  }
1871
- const emitted = this.maybeEmitApiError(session, action.errorText);
2030
+ const emitted = this.maybeEmitApiError(session, action.errorText, apiErrorCode);
1872
2031
  if (!emitted)
1873
2032
  this.emit('output', session.key, `Claude error: ${action.errorText}`, { isFinal: true });
1874
2033
  return;
1875
2034
  }
1876
2035
  // Reconciliation backstop: if the delta stream under-delivered vs the final
1877
- // `result` text, append the gap so the answer is never short.
1878
- if (action.resultText && action.resultText.length > session.currentResponseText.length
2036
+ // `result` text, append the gap so the answer is never short. Not for a turn
2037
+ // adopted in flight: what its old process emitted is not in the cursor, so the
2038
+ // whole final message would read as the gap and go out a second time.
2039
+ if (action.resultText && !session.isAnswerCursorUnknown && action.resultText.length > session.currentResponseText.length
1879
2040
  && action.resultText.startsWith(session.currentResponseText)) {
1880
2041
  session.currentResponseText = action.resultText;
1881
2042
  }
@@ -1940,18 +2101,28 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
1940
2101
  /**
1941
2102
  * Classify + emit an `apiError` once per episode; returns whether it fired. A usage limit takes the reset of the window
1942
2103
  * that rejected the request when one is still ahead — exact, where the text's is a parse of whatever this release
1943
- * prints. (The same rejection marks the profile limited, which is what confirms an `isUnconfirmed` wording.)
2104
+ * prints. (The same rejection marks the profile limited, which is what confirms an `isUnconfirmed` wording.) An account
2105
+ * refusal is `auth` by the CLI's own code (`apiErrorCode`: signed out, or the organization turned its use off) whatever the
2106
+ * text says, by the text otherwise, and says why (`authReason`) — the bot moves the conversation to another account on it.
1944
2107
  */
1945
- maybeEmitApiError(session, text) {
2108
+ maybeEmitApiError(session, text, apiErrorCode = null) {
1946
2109
  if (session.apiErrorFired)
1947
2110
  return false;
1948
2111
  const now = Date.now();
1949
2112
  const isReplayed = session.adoptCatchUpOffset !== null;
2113
+ const codeAuthReason = (0, claudeStreamJson_1.getClaudeAuthErrorCodeReason)(apiErrorCode);
1950
2114
  // An error read from the downtime tail ended a turn when it was WRITTEN: a reset named by its clock ("resets 10:20am") is
1951
2115
  // the next occurrence after that moment, not after the replay's — read against the replay it became tomorrow's.
1952
- const classified = (0, apiErrorRetry_1.classifyAgentApiError)(text, isReplayed ? this.getReplayedErrorWrittenAtMs(session, text) ?? now : now);
2116
+ const classified = codeAuthReason !== null
2117
+ ? { kind: 'auth', authReason: codeAuthReason }
2118
+ : (0, apiErrorRetry_1.classifyAgentApiError)(text, isReplayed ? this.getReplayedErrorWrittenAtMs(session, text) ?? now : now);
1953
2119
  if (!classified)
1954
2120
  return false;
2121
+ if (classified.kind === 'auth') {
2122
+ if (classified.authReason === undefined)
2123
+ classified.authReason = (0, apiErrorRetry_1.getAuthErrorReason)(text);
2124
+ classified.authDetail = text;
2125
+ }
1955
2126
  const rejectedResetAtMs = session.rejectedResetAtMs;
1956
2127
  const apiError = {
1957
2128
  ...(classified.kind === 'usageLimit' && rejectedResetAtMs !== null && rejectedResetAtMs > now
@@ -2147,7 +2318,7 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
2147
2318
  // ─────────────────────────────────────────────────────────────────────────
2148
2319
  async setModel(key, modelId) {
2149
2320
  const session = this.sessions.get((0, sessionKey_1.keyToString)(key));
2150
- if (!session?.isActive)
2321
+ if (!session || !this.checkIsLiveForRespawn(session))
2151
2322
  return (0, i18n_1.t)('model.start_agent_first');
2152
2323
  await this.respawnWithChange(session, { model: modelId, effort: session.effort });
2153
2324
  return null;
@@ -2174,7 +2345,7 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
2174
2345
  }
2175
2346
  (0, claudeCliAdapter_1.saveEffortPref)(key, level);
2176
2347
  const session = this.sessions.get((0, sessionKey_1.keyToString)(key));
2177
- if (!session?.isActive)
2348
+ if (!session || !this.checkIsLiveForRespawn(session))
2178
2349
  return { status: 'stored', notice: (0, i18n_1.t)('effort.start_agent_first') };
2179
2350
  await this.respawnWithChange(session, { model: session.model, effort: level });
2180
2351
  return { status: 'applied' };
@@ -2199,7 +2370,7 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
2199
2370
  async clearEffort(key) {
2200
2371
  (0, claudeCliAdapter_1.clearEffortPref)(key);
2201
2372
  const session = this.sessions.get((0, sessionKey_1.keyToString)(key));
2202
- if (!session?.isActive)
2373
+ if (!session || !this.checkIsLiveForRespawn(session))
2203
2374
  return;
2204
2375
  const { effort } = this.getLaunchOptions(key);
2205
2376
  if (session.effort !== effort)
@@ -2215,10 +2386,28 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
2215
2386
  * intermediate exit is suppressed (`isRespawning`) so the bot sees no
2216
2387
  * closed/stopped churn.
2217
2388
  */
2218
- async respawnWithChange(session, change) {
2389
+ respawnWithChange(session, change) {
2390
+ const respawn = this.runRespawnWithChange(session, change);
2391
+ noteRespawnInFlight((0, sessionKey_1.keyToString)(session.key), respawn);
2392
+ return respawn;
2393
+ }
2394
+ /** {@link respawnWithChange}'s work, recorded as under way for {@link waitForRespawn} while it runs. */
2395
+ async runRespawnWithChange(session, change) {
2396
+ session.isRespawning = true;
2397
+ try {
2398
+ await this.replaceSessionProcess(session, change);
2399
+ }
2400
+ catch (e) {
2401
+ // The re-spawn is over: the old session stays as a stopped one (the next prompt's ensure starts the conversation again), not
2402
+ // as a re-spawn still under way, which holds every watch of the conversation (`checkIsRespawnPending`).
2403
+ session.isRespawning = false;
2404
+ throw e;
2405
+ }
2406
+ }
2407
+ /** {@link respawnWithChange}'s steps: the old process ended, the new one spawned with `--resume` and `change`. */
2408
+ async replaceSessionProcess(session, change) {
2219
2409
  const { key, workDir, sessionId } = session;
2220
2410
  const configDir = change.configDir === undefined ? session.configDir : change.configDir;
2221
- session.isRespawning = true;
2222
2411
  // The re-spawned process starts with none of the old one's background tasks or jobs, and the turn it cuts off is
2223
2412
  // re-prompted by nothing else.
2224
2413
  this.storeLostWork(key, this.describePendingWork(session, { isTurnCutOff: true }));
@@ -2249,17 +2438,20 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
2249
2438
  * wait). The turn is dead and the model cannot act on the limited account, so the re-spawn happens NOW even
2250
2439
  * when the session looks working (busy flag, unconsumed input). Live background tasks (background Bash,
2251
2440
  * sub-agents) are stopped by it too — a deliberate choice: the user chose to move, and a process on a limited
2252
- * account cannot make progress; the caller says so when `checkHasBackgroundWork` was true.
2441
+ * account cannot make progress; the caller says so when `getBackgroundWorkSignals` listed any.
2253
2442
  */
2254
2443
  async applyClaudeConfigDir(key, options = {}) {
2255
2444
  const session = this.sessions.get((0, sessionKey_1.keyToString)(key));
2256
- if (!session?.isActive)
2445
+ // A process being stopped is as good as gone: its next resume reads the account the conversation resolves to then.
2446
+ if (!session || !this.checkIsLiveForRespawn(session))
2257
2447
  return 'inactive';
2258
2448
  const wanted = this.resolveConfigDir(key);
2259
2449
  if ((0, claudeProfiles_1.checkIsSameClaudeConfigDir)(wanted, session.configDir)) {
2260
2450
  session.isConfigDirSwitchPending = false;
2261
2451
  return 'unchanged';
2262
2452
  }
2453
+ // A message queued behind the turn defers it like any work — one behind a turn that ended in an error result too: the CLI runs it as
2454
+ // its next turn within a fraction of a second (measured, `applyTurnEnd`), and a re-spawn now would kill it unread.
2263
2455
  if (!options.isAfterLimit && this.checkIsWorking(key)) {
2264
2456
  session.isConfigDirSwitchPending = true;
2265
2457
  // Recorded now: a reload before the turn ends must not drop the user's pick.
@@ -2271,16 +2463,110 @@ class ClaudeJsonStreamAdapter extends events_1.EventEmitter {
2271
2463
  await this.respawnWithChange(session, { model: session.model, effort: session.effort, configDir: wanted });
2272
2464
  return 'respawned';
2273
2465
  }
2466
+ /**
2467
+ * A deferred account switch that the process's idle releases now: pending, on a live process that no longer works — a message queued
2468
+ * behind the turn, one behind a turn that ended in an error result included, holds it until its own turn's end (the grace bounds it).
2469
+ */
2470
+ checkIsConfigDirSwitchDue(session) {
2471
+ // On the per-turn lifecycle the bot stops this very process at the same turn end (L5): a re-spawn there would race that stop, and
2472
+ // the resume after it spawns on the account the conversation resolves to then anyway (review 22 #1 a). A CLI too old for the
2473
+ // auto-stop is never stopped by the bot, so its switch still re-spawns.
2474
+ if (this.lifecycle === 'perTurn' && this.checkIsAutoStopSupported(session.key))
2475
+ return false;
2476
+ return session.isConfigDirSwitchPending && session.isActive && !this.checkIsWorking(session.key);
2477
+ }
2478
+ /**
2479
+ * @description Whether a change may re-spawn `session`'s process now: it is live and not being stopped. A re-spawn that met a stop
2480
+ * would terminate the same process twice and bring one back the stop's caller believes gone (review 22 #1 a): a process being
2481
+ * stopped takes the change at its next start instead (an effort or account pick is read then; a model pick is refused).
2482
+ */
2483
+ checkIsLiveForRespawn(session) {
2484
+ return session.isActive && !session.isStopping;
2485
+ }
2486
+ /**
2487
+ * @description Which process of this conversation is live (`AgentAdapter.getProcessGeneration`): a new number for each spawn, re-spawn
2488
+ * and adopt; `undefined` with none live (stopped, or down for a re-spawn).
2489
+ */
2490
+ getProcessGeneration(key) {
2491
+ const session = this.sessions.get((0, sessionKey_1.keyToString)(key));
2492
+ return session?.isActive ? session.processGeneration : undefined;
2493
+ }
2494
+ /** A number no other process of any instance of this adapter got ({@link nextProcessGeneration}). */
2495
+ createProcessGeneration() {
2496
+ const generation = nextProcessGeneration;
2497
+ nextProcessGeneration += 1;
2498
+ return generation;
2499
+ }
2500
+ /**
2501
+ * @description Whether this conversation's process is being re-spawned, or is about to be (`AgentAdapter.checkIsRespawnPending`):
2502
+ * a re-spawn under way (`isRespawning`, also while the process is down for it), or a deferred account switch a turn's end released
2503
+ * (`isConfigDirSwitchReleased`: set before that `turnEnded`, one timer tick ahead of the re-spawn, {@link applyPendingConfigDirSwitch}).
2504
+ */
2505
+ checkIsRespawnPending(key) {
2506
+ const session = this.sessions.get((0, sessionKey_1.keyToString)(key));
2507
+ if (!session)
2508
+ return false;
2509
+ return session.isRespawning || session.isConfigDirSwitchReleased;
2510
+ }
2511
+ /**
2512
+ * @description Resolves once no re-spawn of this conversation's process is under way or about to start
2513
+ * (`AgentAdapter.waitForRespawn`): at once with none; else when the last one is over, whatever its end — re-spawned, a no-op, deferred
2514
+ * again, failed. The bot's ensure and command transitions wait here, so none resumes a second process beside a re-spawn whose process
2515
+ * is down for it (review 21 nit 6).
2516
+ */
2517
+ async waitForRespawn(key) {
2518
+ const conversationKey = (0, sessionKey_1.keyToString)(key);
2519
+ for (let inFlight = respawnsInFlightByKey.get(conversationKey); inFlight !== undefined; inFlight = respawnsInFlightByKey.get(conversationKey)) {
2520
+ await Promise.all(inFlight);
2521
+ }
2522
+ }
2523
+ /**
2524
+ * @description Whether a finished background task's own turn is on its way: its `task_notification` came, the turn has not opened
2525
+ * yet, within the grace (`AgentAdapter.checkIsTurnOnItsWay`). The CLI starts it ~0.1 s after the `result` of the turn it ended in.
2526
+ */
2527
+ checkIsTurnOnItsWay(key) {
2528
+ const session = this.sessions.get((0, sessionKey_1.keyToString)(key));
2529
+ if (session?.isActive !== true || session.isBusy)
2530
+ return false;
2531
+ return (0, jsonStreamPendingWork_1.checkIsNotificationTurnPending)({ now: Date.now(), notificationTurnPendingSince: session.notificationTurnPendingSince });
2532
+ }
2533
+ /**
2534
+ * @description Whether the turn that runs, or is on its way, is one the CLI started by itself (`AgentAdapter.checkIsCliOwnTurn`): a
2535
+ * finished task's, a session job's, one with nothing of ours behind it — `isCliOwnTurn` while busy, a task's turn on its way between.
2536
+ */
2537
+ checkIsCliOwnTurn(key) {
2538
+ const session = this.sessions.get((0, sessionKey_1.keyToString)(key));
2539
+ if (session?.isActive !== true)
2540
+ return false;
2541
+ return session.isBusy ? session.isCliOwnTurn : this.checkIsTurnOnItsWay(key);
2542
+ }
2543
+ /** At a turn's end: a deferred switch that is due now is released (`isConfigDirSwitchReleased`), before the bot hears of the end. */
2544
+ releasePendingConfigDirSwitch(session) {
2545
+ session.isConfigDirSwitchReleased = this.checkIsConfigDirSwitchDue(session);
2546
+ }
2274
2547
  /** A deferred profile switch runs once the turn that held it off has ended (and nothing else works). */
2275
2548
  applyPendingConfigDirSwitch(session) {
2276
- if (!session.isConfigDirSwitchPending || !session.isActive)
2549
+ if (!session.isConfigDirSwitchReleased)
2277
2550
  return;
2278
- if (this.checkIsWorking(session.key))
2279
- return; // a background task still runs: the next turn end looks again
2280
- // Detached from the tail poll that delivered the `result`: the re-spawn tears this very session down.
2281
- setTimeout(() => {
2282
- void this.applyClaudeConfigDir(session.key).catch((e) => console.warn(`[ClaudeJson] ${(0, sessionKey_1.keyToString)(session.key)}: the deferred profile switch failed:`, e instanceof Error ? e.message : e));
2283
- }, 0).unref?.();
2551
+ // A write in the turn end's handlers (the todo reminder) made the process work again: the next turn end looks again.
2552
+ if (!this.checkIsConfigDirSwitchDue(session)) {
2553
+ session.isConfigDirSwitchReleased = false;
2554
+ return;
2555
+ }
2556
+ // Detached from the tail poll that delivered the `result`: the re-spawn tears this very session down. Recorded as under way from
2557
+ // now, the turn end's own tick, so an ensure that comes before the re-spawn starts already waits for it (`waitForRespawn`).
2558
+ const applied = new Promise((resolve) => {
2559
+ setTimeout(() => {
2560
+ void this.applyClaudeConfigDir(session.key)
2561
+ .catch((e) => console.warn(`[ClaudeJson] ${(0, sessionKey_1.keyToString)(session.key)}: the deferred profile switch failed:`, e instanceof Error ? e.message : e))
2562
+ // Over: re-spawned (this session is replaced, `isRespawning` covered the way), a no-op, or deferred again.
2563
+ .finally(() => {
2564
+ session.isConfigDirSwitchReleased = false;
2565
+ resolve();
2566
+ });
2567
+ }, 0).unref?.();
2568
+ });
2569
+ noteRespawnInFlight((0, sessionKey_1.keyToString)(session.key), applied);
2284
2570
  }
2285
2571
  clearTimers(session) {
2286
2572
  if (session.pollTimer) {
@@ -2337,6 +2623,8 @@ function buildTailRecord(session, offsetBytes) {
2337
2623
  ...(session.scheduledJobs.size > 0 ? { scheduledJobs: [...session.scheduledJobs.values()] } : {}),
2338
2624
  ...(session.notificationTurnPendingSince !== null ? { notificationTurnPendingSinceMs: session.notificationTurnPendingSince } : {}),
2339
2625
  ...(session.isConfigDirSwitchPending ? { isConfigDirSwitchPending: true } : {}),
2626
+ // Only while a turn is in flight (an idle record stays as it was): written both ways, since an absent flag reads as "emitted".
2627
+ ...(session.isBusy ? { isAnswerEmittedInTurn: session.isAnswerEmittedInTurn } : {}),
2340
2628
  };
2341
2629
  }
2342
2630
  /**