@0xmaxma/claude-gateway 2.0.5 → 2.0.7

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 (435) hide show
  1. package/README.md +14 -1
  2. package/dist/agent/builtin-commands.js +5 -5
  3. package/dist/agent/builtin-commands.js.map +1 -1
  4. package/dist/agent/command-help.d.ts +9 -0
  5. package/dist/agent/command-help.d.ts.map +1 -0
  6. package/dist/agent/command-help.js +50 -0
  7. package/dist/agent/command-help.js.map +1 -0
  8. package/dist/agent/dreaming/index.d.ts +6 -3
  9. package/dist/agent/dreaming/index.d.ts.map +1 -1
  10. package/dist/agent/dreaming/index.js +21 -1
  11. package/dist/agent/dreaming/index.js.map +1 -1
  12. package/dist/agent/knowledge/reflection.d.ts +7 -4
  13. package/dist/agent/knowledge/reflection.d.ts.map +1 -1
  14. package/dist/agent/knowledge/reflection.js +19 -1
  15. package/dist/agent/knowledge/reflection.js.map +1 -1
  16. package/dist/agent/runner.d.ts +51 -3
  17. package/dist/agent/runner.d.ts.map +1 -1
  18. package/dist/agent/runner.js +228 -107
  19. package/dist/agent/runner.js.map +1 -1
  20. package/dist/agent/session-compaction-scheduler.d.ts +22 -0
  21. package/dist/agent/session-compaction-scheduler.d.ts.map +1 -0
  22. package/dist/agent/session-compaction-scheduler.js +40 -0
  23. package/dist/agent/session-compaction-scheduler.js.map +1 -0
  24. package/dist/agent/session-confirmations.d.ts +12 -0
  25. package/dist/agent/session-confirmations.d.ts.map +1 -0
  26. package/dist/agent/session-confirmations.js +43 -0
  27. package/dist/agent/session-confirmations.js.map +1 -0
  28. package/dist/agent/session-status.d.ts +7 -0
  29. package/dist/agent/session-status.d.ts.map +1 -0
  30. package/dist/agent/session-status.js +16 -0
  31. package/dist/agent/session-status.js.map +1 -0
  32. package/dist/agent/skill-learning/index.d.ts +5 -1
  33. package/dist/agent/skill-learning/index.d.ts.map +1 -1
  34. package/dist/agent/skill-learning/index.js +23 -1
  35. package/dist/agent/skill-learning/index.js.map +1 -1
  36. package/dist/agent/skill-learning/notifier.d.ts +2 -1
  37. package/dist/agent/skill-learning/notifier.d.ts.map +1 -1
  38. package/dist/agent/skill-learning/notifier.js +1 -0
  39. package/dist/agent/skill-learning/notifier.js.map +1 -1
  40. package/dist/api/apps-router.d.ts.map +1 -1
  41. package/dist/api/apps-router.js +1 -3
  42. package/dist/api/apps-router.js.map +1 -1
  43. package/dist/api/cron-router.d.ts +1 -1
  44. package/dist/api/cron-router.d.ts.map +1 -1
  45. package/dist/api/cron-router.js +4 -4
  46. package/dist/api/cron-router.js.map +1 -1
  47. package/dist/api/dashboard-processes.d.ts +86 -0
  48. package/dist/api/dashboard-processes.d.ts.map +1 -0
  49. package/dist/api/dashboard-processes.js +155 -0
  50. package/dist/api/dashboard-processes.js.map +1 -0
  51. package/dist/api/dashboard-sessions.d.ts +15 -0
  52. package/dist/api/dashboard-sessions.d.ts.map +1 -0
  53. package/dist/api/dashboard-sessions.js +66 -0
  54. package/dist/api/dashboard-sessions.js.map +1 -0
  55. package/dist/api/gateway-router.d.ts +3 -4
  56. package/dist/api/gateway-router.d.ts.map +1 -1
  57. package/dist/api/gateway-router.js +177 -66
  58. package/dist/api/gateway-router.js.map +1 -1
  59. package/dist/api/memory-activity.d.ts +18 -0
  60. package/dist/api/memory-activity.d.ts.map +1 -0
  61. package/dist/api/memory-activity.js +97 -0
  62. package/dist/api/memory-activity.js.map +1 -0
  63. package/dist/api/oauth-connectors-router.d.ts +1 -1
  64. package/dist/api/oauth-connectors-router.d.ts.map +1 -1
  65. package/dist/api/oauth-connectors-router.js +11 -21
  66. package/dist/api/oauth-connectors-router.js.map +1 -1
  67. package/dist/api/router.d.ts +1 -1
  68. package/dist/api/router.d.ts.map +1 -1
  69. package/dist/api/router.js +3 -9
  70. package/dist/api/router.js.map +1 -1
  71. package/dist/api/share-router.d.ts +1 -1
  72. package/dist/api/share-router.d.ts.map +1 -1
  73. package/dist/api/share-router.js +1 -1
  74. package/dist/api/share-router.js.map +1 -1
  75. package/dist/api/slack-webhook-router.js +1 -1
  76. package/dist/api/slack-webhook-router.js.map +1 -1
  77. package/dist/api/voice-router.d.ts +1 -0
  78. package/dist/api/voice-router.d.ts.map +1 -1
  79. package/dist/api/voice-router.js +7 -0
  80. package/dist/api/voice-router.js.map +1 -1
  81. package/dist/apps/agent-container-migration.d.ts +2 -0
  82. package/dist/apps/agent-container-migration.d.ts.map +1 -1
  83. package/dist/apps/agent-container-migration.js +59 -2
  84. package/dist/apps/agent-container-migration.js.map +1 -1
  85. package/dist/apps/agent-manager.d.ts +4 -2
  86. package/dist/apps/agent-manager.d.ts.map +1 -1
  87. package/dist/apps/agent-manager.js +39 -3
  88. package/dist/apps/agent-manager.js.map +1 -1
  89. package/dist/apps/installer.d.ts +4 -3
  90. package/dist/apps/installer.d.ts.map +1 -1
  91. package/dist/apps/installer.js +8 -4
  92. package/dist/apps/installer.js.map +1 -1
  93. package/dist/build-provenance.json +8 -0
  94. package/dist/cli/args.js +1 -1
  95. package/dist/cli/args.js.map +1 -1
  96. package/dist/cli/commands/app.d.ts.map +1 -1
  97. package/dist/cli/commands/app.js +39 -3
  98. package/dist/cli/commands/app.js.map +1 -1
  99. package/dist/cli/commands/doctor.d.ts.map +1 -1
  100. package/dist/cli/commands/doctor.js +6 -2
  101. package/dist/cli/commands/doctor.js.map +1 -1
  102. package/dist/cli/commands/safemode.d.ts +2 -0
  103. package/dist/cli/commands/safemode.d.ts.map +1 -0
  104. package/dist/cli/commands/safemode.js +279 -0
  105. package/dist/cli/commands/safemode.js.map +1 -0
  106. package/dist/cli/dependencies.d.ts +2 -0
  107. package/dist/cli/dependencies.d.ts.map +1 -1
  108. package/dist/cli/dependencies.js +81 -0
  109. package/dist/cli/dependencies.js.map +1 -1
  110. package/dist/cli/index.d.ts.map +1 -1
  111. package/dist/cli/index.js +11 -1
  112. package/dist/cli/index.js.map +1 -1
  113. package/dist/cli/manager.d.ts.map +1 -1
  114. package/dist/cli/manager.js +4 -1
  115. package/dist/cli/manager.js.map +1 -1
  116. package/dist/config/agent-lifecycle.d.ts +26 -0
  117. package/dist/config/agent-lifecycle.d.ts.map +1 -0
  118. package/dist/config/agent-lifecycle.js +63 -0
  119. package/dist/config/agent-lifecycle.js.map +1 -0
  120. package/dist/config/loader.d.ts.map +1 -1
  121. package/dist/config/loader.js +11 -0
  122. package/dist/config/loader.js.map +1 -1
  123. package/dist/config/reload-policy.d.ts +9 -0
  124. package/dist/config/reload-policy.d.ts.map +1 -0
  125. package/dist/config/reload-policy.js +62 -0
  126. package/dist/config/reload-policy.js.map +1 -0
  127. package/dist/config/watcher.d.ts +3 -2
  128. package/dist/config/watcher.d.ts.map +1 -1
  129. package/dist/config/watcher.js +34 -51
  130. package/dist/config/watcher.js.map +1 -1
  131. package/dist/cron/tool-schemas.d.ts +296 -0
  132. package/dist/cron/tool-schemas.d.ts.map +1 -0
  133. package/dist/cron/tool-schemas.js +122 -0
  134. package/dist/cron/tool-schemas.js.map +1 -0
  135. package/dist/index.js +141 -158
  136. package/dist/index.js.map +1 -1
  137. package/dist/orchestration/agent-tool-schemas.js +5 -5
  138. package/dist/orchestration/agent-tool-schemas.js.map +1 -1
  139. package/dist/orchestration/background-work.d.ts +9 -0
  140. package/dist/orchestration/background-work.d.ts.map +1 -0
  141. package/dist/orchestration/background-work.js +49 -0
  142. package/dist/orchestration/background-work.js.map +1 -0
  143. package/dist/orchestration/bridge.d.ts +6 -15
  144. package/dist/orchestration/bridge.d.ts.map +1 -1
  145. package/dist/orchestration/bridge.js +67 -32
  146. package/dist/orchestration/bridge.js.map +1 -1
  147. package/dist/orchestration/capabilities.d.ts.map +1 -1
  148. package/dist/orchestration/capabilities.js +18 -10
  149. package/dist/orchestration/capabilities.js.map +1 -1
  150. package/dist/orchestration/capacity.d.ts +3 -2
  151. package/dist/orchestration/capacity.d.ts.map +1 -1
  152. package/dist/orchestration/capacity.js +7 -0
  153. package/dist/orchestration/capacity.js.map +1 -1
  154. package/dist/orchestration/channel-controls.d.ts.map +1 -1
  155. package/dist/orchestration/channel-controls.js +3 -2
  156. package/dist/orchestration/channel-controls.js.map +1 -1
  157. package/dist/orchestration/cli-skills.d.ts +5 -0
  158. package/dist/orchestration/cli-skills.d.ts.map +1 -1
  159. package/dist/orchestration/compact-measurements.d.ts +21 -0
  160. package/dist/orchestration/compact-measurements.d.ts.map +1 -0
  161. package/dist/orchestration/compact-measurements.js +62 -0
  162. package/dist/orchestration/compact-measurements.js.map +1 -0
  163. package/dist/orchestration/config.d.ts +4 -0
  164. package/dist/orchestration/config.d.ts.map +1 -1
  165. package/dist/orchestration/config.js +1 -1
  166. package/dist/orchestration/config.js.map +1 -1
  167. package/dist/orchestration/container-tool-schemas.d.ts +37 -0
  168. package/dist/orchestration/container-tool-schemas.d.ts.map +1 -0
  169. package/dist/orchestration/container-tool-schemas.js +27 -0
  170. package/dist/orchestration/container-tool-schemas.js.map +1 -0
  171. package/dist/orchestration/container.d.ts.map +1 -1
  172. package/dist/orchestration/container.js +7 -0
  173. package/dist/orchestration/container.js.map +1 -1
  174. package/dist/orchestration/context-delivery.d.ts +32 -0
  175. package/dist/orchestration/context-delivery.d.ts.map +1 -0
  176. package/dist/orchestration/context-delivery.js +101 -0
  177. package/dist/orchestration/context-delivery.js.map +1 -0
  178. package/dist/orchestration/conversation-intake.d.ts +10 -6
  179. package/dist/orchestration/conversation-intake.d.ts.map +1 -1
  180. package/dist/orchestration/conversation-intake.js +22 -8
  181. package/dist/orchestration/conversation-intake.js.map +1 -1
  182. package/dist/orchestration/dashboard-charts.d.ts +32 -0
  183. package/dist/orchestration/dashboard-charts.d.ts.map +1 -0
  184. package/dist/orchestration/dashboard-charts.js +77 -0
  185. package/dist/orchestration/dashboard-charts.js.map +1 -0
  186. package/dist/orchestration/dashboard-reader-worker.js +28 -10
  187. package/dist/orchestration/dashboard-reader-worker.js.map +1 -1
  188. package/dist/orchestration/dashboard-reader.d.ts +1 -1
  189. package/dist/orchestration/dashboard-reader.d.ts.map +1 -1
  190. package/dist/orchestration/dashboard-reader.js +2 -2
  191. package/dist/orchestration/dashboard-reader.js.map +1 -1
  192. package/dist/orchestration/decision-context.d.ts +1 -1
  193. package/dist/orchestration/decision-context.d.ts.map +1 -1
  194. package/dist/orchestration/decision-context.js +3 -3
  195. package/dist/orchestration/decision-context.js.map +1 -1
  196. package/dist/orchestration/gateway-tasks/controller.d.ts +29 -0
  197. package/dist/orchestration/gateway-tasks/controller.d.ts.map +1 -0
  198. package/dist/orchestration/gateway-tasks/controller.js +139 -0
  199. package/dist/orchestration/gateway-tasks/controller.js.map +1 -0
  200. package/dist/orchestration/gateway-tasks/safemode.d.ts +19 -0
  201. package/dist/orchestration/gateway-tasks/safemode.d.ts.map +1 -0
  202. package/dist/orchestration/gateway-tasks/safemode.js +128 -0
  203. package/dist/orchestration/gateway-tasks/safemode.js.map +1 -0
  204. package/dist/orchestration/mutation-recovery.d.ts +3 -2
  205. package/dist/orchestration/mutation-recovery.d.ts.map +1 -1
  206. package/dist/orchestration/mutation-recovery.js +8 -0
  207. package/dist/orchestration/mutation-recovery.js.map +1 -1
  208. package/dist/orchestration/native-compact.d.ts +4 -1
  209. package/dist/orchestration/native-compact.d.ts.map +1 -1
  210. package/dist/orchestration/native-compact.js +6 -2
  211. package/dist/orchestration/native-compact.js.map +1 -1
  212. package/dist/orchestration/process-turn.d.ts +12 -2
  213. package/dist/orchestration/process-turn.d.ts.map +1 -1
  214. package/dist/orchestration/process-turn.js +48 -8
  215. package/dist/orchestration/process-turn.js.map +1 -1
  216. package/dist/orchestration/recovery.d.ts.map +1 -1
  217. package/dist/orchestration/recovery.js +4 -2
  218. package/dist/orchestration/recovery.js.map +1 -1
  219. package/dist/orchestration/runtime.d.ts +23 -1
  220. package/dist/orchestration/runtime.d.ts.map +1 -1
  221. package/dist/orchestration/runtime.js +191 -21
  222. package/dist/orchestration/runtime.js.map +1 -1
  223. package/dist/orchestration/session-compaction.d.ts +59 -0
  224. package/dist/orchestration/session-compaction.d.ts.map +1 -0
  225. package/dist/orchestration/session-compaction.js +212 -0
  226. package/dist/orchestration/session-compaction.js.map +1 -0
  227. package/dist/orchestration/skills.d.ts +2 -0
  228. package/dist/orchestration/skills.d.ts.map +1 -1
  229. package/dist/orchestration/skills.js +4 -3
  230. package/dist/orchestration/skills.js.map +1 -1
  231. package/dist/orchestration/task-controls.d.ts +12 -0
  232. package/dist/orchestration/task-controls.d.ts.map +1 -1
  233. package/dist/orchestration/task-controls.js +3 -1
  234. package/dist/orchestration/task-controls.js.map +1 -1
  235. package/dist/orchestration/tasks/driver.d.ts.map +1 -1
  236. package/dist/orchestration/tasks/driver.js +100 -13
  237. package/dist/orchestration/tasks/driver.js.map +1 -1
  238. package/dist/orchestration/tasks/pool.d.ts +2 -0
  239. package/dist/orchestration/tasks/pool.d.ts.map +1 -1
  240. package/dist/orchestration/tasks/pool.js +4 -0
  241. package/dist/orchestration/tasks/pool.js.map +1 -1
  242. package/dist/orchestration/tasks/scheduler.d.ts.map +1 -1
  243. package/dist/orchestration/tasks/scheduler.js +4 -0
  244. package/dist/orchestration/tasks/scheduler.js.map +1 -1
  245. package/dist/orchestration/tasks/service.d.ts +4 -0
  246. package/dist/orchestration/tasks/service.d.ts.map +1 -1
  247. package/dist/orchestration/tasks/service.js +38 -8
  248. package/dist/orchestration/tasks/service.js.map +1 -1
  249. package/dist/orchestration/token-ledger.d.ts +8 -0
  250. package/dist/orchestration/token-ledger.d.ts.map +1 -1
  251. package/dist/orchestration/token-ledger.js +7 -2
  252. package/dist/orchestration/token-ledger.js.map +1 -1
  253. package/dist/orchestration/token-usage.d.ts +3 -0
  254. package/dist/orchestration/token-usage.d.ts.map +1 -1
  255. package/dist/orchestration/token-usage.js +12 -3
  256. package/dist/orchestration/token-usage.js.map +1 -1
  257. package/dist/orchestration/types.d.ts +19 -1
  258. package/dist/orchestration/types.d.ts.map +1 -1
  259. package/dist/orchestration/types.js.map +1 -1
  260. package/dist/orchestration/worker-crons.d.ts +5 -0
  261. package/dist/orchestration/worker-crons.d.ts.map +1 -0
  262. package/dist/orchestration/worker-crons.js +84 -0
  263. package/dist/orchestration/worker-crons.js.map +1 -0
  264. package/dist/orchestration/worker-harness.d.ts +15 -0
  265. package/dist/orchestration/worker-harness.d.ts.map +1 -0
  266. package/dist/orchestration/worker-harness.js +72 -0
  267. package/dist/orchestration/worker-harness.js.map +1 -0
  268. package/dist/safemode/config.d.ts +7 -0
  269. package/dist/safemode/config.d.ts.map +1 -0
  270. package/dist/safemode/config.js +67 -0
  271. package/dist/safemode/config.js.map +1 -0
  272. package/dist/safemode/context.d.ts +7 -0
  273. package/dist/safemode/context.d.ts.map +1 -0
  274. package/dist/safemode/context.js +397 -0
  275. package/dist/safemode/context.js.map +1 -0
  276. package/dist/safemode/external-owners.d.ts +19 -0
  277. package/dist/safemode/external-owners.d.ts.map +1 -0
  278. package/dist/safemode/external-owners.js +229 -0
  279. package/dist/safemode/external-owners.js.map +1 -0
  280. package/dist/safemode/native.d.ts +38 -0
  281. package/dist/safemode/native.d.ts.map +1 -0
  282. package/dist/safemode/native.js +220 -0
  283. package/dist/safemode/native.js.map +1 -0
  284. package/dist/safemode/params.d.ts +10 -0
  285. package/dist/safemode/params.d.ts.map +1 -0
  286. package/dist/safemode/params.js +86 -0
  287. package/dist/safemode/params.js.map +1 -0
  288. package/dist/safemode/provenance.d.ts +45 -0
  289. package/dist/safemode/provenance.d.ts.map +1 -0
  290. package/dist/safemode/provenance.js +153 -0
  291. package/dist/safemode/provenance.js.map +1 -0
  292. package/dist/safemode/runner.d.ts +17 -0
  293. package/dist/safemode/runner.d.ts.map +1 -0
  294. package/dist/safemode/runner.js +398 -0
  295. package/dist/safemode/runner.js.map +1 -0
  296. package/dist/safemode/store.d.ts +56 -0
  297. package/dist/safemode/store.d.ts.map +1 -0
  298. package/dist/safemode/store.js +451 -0
  299. package/dist/safemode/store.js.map +1 -0
  300. package/dist/session/codex-auth.d.ts +37 -0
  301. package/dist/session/codex-auth.d.ts.map +1 -0
  302. package/dist/session/codex-auth.js +266 -0
  303. package/dist/session/codex-auth.js.map +1 -0
  304. package/dist/session/codex-container-runtime.d.ts +15 -0
  305. package/dist/session/codex-container-runtime.d.ts.map +1 -0
  306. package/dist/session/codex-container-runtime.js +85 -0
  307. package/dist/session/codex-container-runtime.js.map +1 -0
  308. package/dist/session/codex-context-defaults.json +5 -0
  309. package/dist/session/codex-context.d.ts +13 -0
  310. package/dist/session/codex-context.d.ts.map +1 -0
  311. package/dist/session/codex-context.js +27 -0
  312. package/dist/session/codex-context.js.map +1 -0
  313. package/dist/session/codex-extension-discovery.d.ts +21 -0
  314. package/dist/session/codex-extension-discovery.d.ts.map +1 -0
  315. package/dist/session/codex-extension-discovery.js +132 -0
  316. package/dist/session/codex-extension-discovery.js.map +1 -0
  317. package/dist/session/codex-native-mcp-client.d.ts +37 -0
  318. package/dist/session/codex-native-mcp-client.d.ts.map +1 -0
  319. package/dist/session/codex-native-mcp-client.js +164 -0
  320. package/dist/session/codex-native-mcp-client.js.map +1 -0
  321. package/dist/session/codex-policy.d.ts +6 -0
  322. package/dist/session/codex-policy.d.ts.map +1 -0
  323. package/dist/session/codex-policy.js +17 -0
  324. package/dist/session/codex-policy.js.map +1 -0
  325. package/dist/session/codex-process.d.ts +114 -0
  326. package/dist/session/codex-process.d.ts.map +1 -0
  327. package/dist/session/codex-process.js +759 -0
  328. package/dist/session/codex-process.js.map +1 -0
  329. package/dist/session/codex-runtime.d.ts +20 -0
  330. package/dist/session/codex-runtime.d.ts.map +1 -0
  331. package/dist/session/codex-runtime.js +182 -0
  332. package/dist/session/codex-runtime.js.map +1 -0
  333. package/dist/session/codex-tool-capture.d.ts +35 -0
  334. package/dist/session/codex-tool-capture.d.ts.map +1 -0
  335. package/dist/session/codex-tool-capture.js +178 -0
  336. package/dist/session/codex-tool-capture.js.map +1 -0
  337. package/dist/session/container-connectors.d.ts +10 -0
  338. package/dist/session/container-connectors.d.ts.map +1 -0
  339. package/dist/session/container-connectors.js +41 -0
  340. package/dist/session/container-connectors.js.map +1 -0
  341. package/dist/session/container-extensions.d.ts +4 -0
  342. package/dist/session/container-extensions.d.ts.map +1 -0
  343. package/dist/session/container-extensions.js +45 -0
  344. package/dist/session/container-extensions.js.map +1 -0
  345. package/dist/session/managed-connectors.d.ts +16 -0
  346. package/dist/session/managed-connectors.d.ts.map +1 -0
  347. package/dist/session/managed-connectors.js +25 -0
  348. package/dist/session/managed-connectors.js.map +1 -0
  349. package/dist/session/process-diagnostics.d.ts +14 -0
  350. package/dist/session/process-diagnostics.d.ts.map +1 -0
  351. package/dist/session/process-diagnostics.js +39 -0
  352. package/dist/session/process-diagnostics.js.map +1 -0
  353. package/dist/session/process.d.ts +4 -0
  354. package/dist/session/process.d.ts.map +1 -1
  355. package/dist/session/process.js +21 -16
  356. package/dist/session/process.js.map +1 -1
  357. package/dist/session/request-tool-capture.d.ts +1 -1
  358. package/dist/session/request-tool-capture.d.ts.map +1 -1
  359. package/dist/session/runtime-profile.d.ts +8 -0
  360. package/dist/session/runtime-profile.d.ts.map +1 -1
  361. package/dist/session/runtime-profile.js +3 -2
  362. package/dist/session/runtime-profile.js.map +1 -1
  363. package/dist/session/worker-environment.d.ts +5 -0
  364. package/dist/session/worker-environment.d.ts.map +1 -0
  365. package/dist/session/worker-environment.js +27 -0
  366. package/dist/session/worker-environment.js.map +1 -0
  367. package/dist/session/worker-extensions.d.ts +20 -0
  368. package/dist/session/worker-extensions.d.ts.map +1 -0
  369. package/dist/session/worker-extensions.js +322 -0
  370. package/dist/session/worker-extensions.js.map +1 -0
  371. package/dist/skills/loader.d.ts +2 -0
  372. package/dist/skills/loader.d.ts.map +1 -1
  373. package/dist/skills/loader.js.map +1 -1
  374. package/dist/types.d.ts +33 -0
  375. package/dist/types.d.ts.map +1 -1
  376. package/dist/ui/codex-context.d.ts +4 -0
  377. package/dist/ui/codex-context.d.ts.map +1 -0
  378. package/dist/ui/codex-context.js +15 -0
  379. package/dist/ui/codex-context.js.map +1 -0
  380. package/dist/ui/dashboard-charts.d.ts +3 -0
  381. package/dist/ui/dashboard-charts.d.ts.map +1 -0
  382. package/dist/ui/dashboard-charts.js +130 -0
  383. package/dist/ui/dashboard-charts.js.map +1 -0
  384. package/dist/ui/dashboard-client.d.ts.map +1 -1
  385. package/dist/ui/dashboard-client.js +20 -21
  386. package/dist/ui/dashboard-client.js.map +1 -1
  387. package/dist/ui/dashboard-controls.d.ts +4 -0
  388. package/dist/ui/dashboard-controls.d.ts.map +1 -0
  389. package/dist/ui/dashboard-controls.js +27 -0
  390. package/dist/ui/dashboard-controls.js.map +1 -0
  391. package/dist/ui/dashboard-presentation.d.ts +4 -1
  392. package/dist/ui/dashboard-presentation.d.ts.map +1 -1
  393. package/dist/ui/dashboard-presentation.js +13 -7
  394. package/dist/ui/dashboard-presentation.js.map +1 -1
  395. package/dist/ui/dashboard-range.d.ts +3 -3
  396. package/dist/ui/dashboard-range.d.ts.map +1 -1
  397. package/dist/ui/dashboard-range.js +21 -5
  398. package/dist/ui/dashboard-range.js.map +1 -1
  399. package/dist/ui/dashboard-theme.d.ts +3 -1
  400. package/dist/ui/dashboard-theme.d.ts.map +1 -1
  401. package/dist/ui/dashboard-theme.js +80 -3
  402. package/dist/ui/dashboard-theme.js.map +1 -1
  403. package/dist/ui/memory-activity.d.ts +4 -0
  404. package/dist/ui/memory-activity.d.ts.map +1 -0
  405. package/dist/ui/memory-activity.js +115 -0
  406. package/dist/ui/memory-activity.js.map +1 -0
  407. package/dist/ui/token-report-client.d.ts +1 -1
  408. package/dist/ui/token-report-client.d.ts.map +1 -1
  409. package/dist/ui/token-report-client.js +1 -1
  410. package/dist/ui/token-report.d.ts +4 -0
  411. package/dist/ui/token-report.d.ts.map +1 -1
  412. package/dist/ui/token-report.js +38 -23
  413. package/dist/ui/token-report.js.map +1 -1
  414. package/dist/ui/web-ui.d.ts +1 -1
  415. package/dist/ui/web-ui.d.ts.map +1 -1
  416. package/dist/ui/web-ui.js +68 -370
  417. package/dist/ui/web-ui.js.map +1 -1
  418. package/mcp/capability-catalog.ts +2 -0
  419. package/mcp/extension-catalog.ts +18 -0
  420. package/mcp/lazy-connector.ts +4 -2
  421. package/mcp/lazy-tools.test.ts +29 -0
  422. package/mcp/modules.ts +1 -0
  423. package/mcp/server.ts +2 -2
  424. package/mcp/tools/cron/module.ts +8 -114
  425. package/mcp/tools/discord/commands.ts +4 -1
  426. package/mcp/tools/safemode/module.test.ts +29 -0
  427. package/mcp/tools/telegram/receiver-server.ts +33 -39
  428. package/mcp/tools/telegram/session-browser.ts +10 -0
  429. package/mcp/tools/telegram/task-detail.ts +2 -1
  430. package/package.json +3 -2
  431. package/scripts/orchestration/audit-codex-context.cjs +83 -0
  432. package/scripts/orchestration/benchmark-worker-harnesses.cjs +112 -0
  433. package/scripts/orchestration/smoke-codex-extensions.ts +29 -0
  434. package/scripts/orchestration/smoke-codex-worker.cjs +166 -0
  435. package/scripts/orchestration/smoke-safemode-codex.cjs +66 -0
@@ -1,6 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.AgentOrchestrationRuntime = void 0;
4
+ const controller_1 = require("./gateway-tasks/controller");
5
+ const safemode_1 = require("./gateway-tasks/safemode");
6
+ const worker_crons_1 = require("./worker-crons");
7
+ const compact_measurements_1 = require("./compact-measurements");
8
+ const session_compaction_1 = require("./session-compaction");
9
+ const context_delivery_1 = require("./context-delivery");
4
10
  const native_compact_1 = require("./native-compact");
5
11
  const browser_voice_1 = require("./browser-voice");
6
12
  const mutation_recovery_1 = require("./mutation-recovery");
@@ -67,6 +73,10 @@ const capacity_1 = require("./capacity");
67
73
  const cleanup_1 = require("./tasks/cleanup");
68
74
  const task_files_1 = require("./task-files");
69
75
  const worker_shares_1 = require("./worker-shares");
76
+ /** Stable instructions are carried in the system prefix, not appended to every
77
+ * resumed user turn. Per-turn authorization flags remain explicit below it. */
78
+ const GATEWAY_TASK_INSTRUCTIONS = 'For safemode discovery use capabilities_list(scope=safemode); this creates no task. For authorized work on a discovered session use task_spawn(target_profile=gateway-managed, gateway_target={adapter:safemode,session_id:...}). Gateway-managed tasks are followed by the gateway and report results automatically; never spawn a polling worker.';
79
+ const CONTEXT_DELIVERY_INSTRUCTIONS = 'Worker profiles: default-worker is the general-purpose worker for research, files, browser/API operations, services, calculations and code. In host mode it uses the Agent working environment; no Git or projectRoot is required. In container mode it stays inside the app container. Only explicitly configured isolated-worktree mode requires Git for default-worker; media-worker remains available for standalone scratch work in isolated modes. State the authorized working directory in task instructions; workers may change directories only within their execution boundary. Serialize conflicting edits to the same shared files; continue related work with continue_task_id. Task context is incremental within a resumed CLI conversation. Omission means unchanged, not deleted. On a fresh context only active/waiting tasks and current reports are bootstrapped; use task_status for other past work or full results. Receipt recovery is evidence, not authorization to replay a command. Previously supplied materials remain in the resumed context; preserve their references when assigning workers. Never infer that missing image bytes mean a missing attachment if its ref was already supplied.';
70
80
  class AgentOrchestrationRuntime {
71
81
  setBrowserVoice(sessionId, principalId, enabled) {
72
82
  this.authorizeSession(sessionId, principalId);
@@ -105,6 +115,7 @@ class AgentOrchestrationRuntime {
105
115
  this.sessionResponses = new Map();
106
116
  this.textListeners = new Map();
107
117
  this.intake = new conversation_intake_1.ConversationIntake(store);
118
+ this.contextDelivery = new context_delivery_1.ContextDelivery(store);
108
119
  this.cliSessions = new agent_cli_session_1.AgentCliSessions(store);
109
120
  this.store = store;
110
121
  this.history = history;
@@ -177,16 +188,21 @@ class AgentOrchestrationRuntime {
177
188
  }
178
189
  const tasks = new service_1.TaskService(store, agent.orchestration, agent.workspace);
179
190
  const files = new task_files_1.TaskFiles(store, (0, path_1.join)(agent.workspace, '../..'), agent.type === 'app-agent' ? (0, path_1.join)(root, 'container-files') : undefined, agent.workspace);
180
- const bridge = new bridge_1.TaskBridge(tasks, files, (0, worker_shares_1.workerShares)(files, agent, gateway), host.skills ? () => host.skills() : undefined, agent.type === 'app-agent' ? { agent, spool: (0, path_1.join)(root, 'container-files') } : undefined);
191
+ const safemodeAllowed = () => agent.type !== 'app-agent' && Boolean(gateway.safemode?.allowedAgentIds?.includes(agent.id));
192
+ const gatewayAdapters = new Map(agent.type === 'app-agent' ? [] : [['safemode', new safemode_1.SafemodeTaskAdapter(agent.id, safemodeAllowed)]]);
193
+ const bridge = new bridge_1.TaskBridge(tasks, files, (0, worker_shares_1.workerShares)(files, agent, gateway), host.skills ? () => host.skills() : undefined, agent.type === 'app-agent' ? { agent, spool: (0, path_1.join)(root, 'container-files') } : undefined, (0, worker_crons_1.workerCrons)(files, agent, gateway), gatewayAdapters);
181
194
  const personalRetention = (0, config_1.resolveDreamingConfig)(agent.dreaming, gateway.gateway.dreaming, gateway.gateway.timezone).staleness;
182
195
  const sharedRetention = (0, knowledge_1.resolveSharedConfig)(agent.knowledge?.shared, gateway.gateway.knowledge?.shared).staleness;
183
196
  bridge.recordRetrievals = (personalRetention.enabled && personalRetention.recordRetrievals) || (sharedRetention.enabled && sharedRetention.recordRetrievals);
184
197
  try {
185
198
  (0, recovery_1.recoverOrchestration)(store);
199
+ (0, session_compaction_1.recoverSessionCompaction)(store);
186
200
  // A prior gateway cannot prove that these processes stopped. Reserve
187
201
  // their global capacity conservatively as well as the per-agent slots.
188
202
  const recoveredReservations = new Map();
189
203
  for (const row of store.all("SELECT id FROM tasks WHERE state='needs_reconciliation' AND active_attempt_id IS NOT NULL")) {
204
+ if (store.task(String(row.id))?.gatewayTarget)
205
+ continue;
190
206
  recoveredReservations.set(String(row.id), (0, capacity_1.gatewayCapacity)(gateway).acquireWorker(agent.id, String(row.id), false));
191
207
  }
192
208
  if (agent.orchestration?.enabled)
@@ -214,6 +230,8 @@ class AgentOrchestrationRuntime {
214
230
  runtime.drain();
215
231
  await runtime.flushHistory();
216
232
  scheduler.start();
233
+ runtime.gatewayTasks = new controller_1.GatewayTaskController(tasks, gatewayAdapters);
234
+ runtime.gatewayTasks.start();
217
235
  runtime.mailboxTimer = setInterval(() => {
218
236
  try {
219
237
  runtime.pumpMailbox();
@@ -375,9 +393,18 @@ class AgentOrchestrationRuntime {
375
393
  process = await this.host.createAgentSession(sessionId, ticket.profile, model, { agentId: this.agent.id, agentSessionId: sessionId, source: conversation.source, accountId: String(conversation.account_id), chatId: String(conversation.chat_id), threadKey: String(conversation.thread_key), principalId: String(conversation.owner_principal_id) });
376
394
  if (active.stopping || this.closing)
377
395
  throw new types_2.OrchestrationError('INTERRUPTED');
378
- active.turn = (0, native_compact_1.startNativeCompact)(process);
379
- await active.turn.result;
396
+ this.contextDelivery.invalidateConversation(String(conversation.id));
397
+ const startedAt = Date.now(), compact = (0, native_compact_1.startNativeCompact)(process);
398
+ active.turn = compact;
399
+ await compact.result;
400
+ let measured = compact.measurements();
401
+ if (this.agent.type !== 'app-agent' && measured?.afterTokens == null) {
402
+ const storedMetrics = await (0, compact_measurements_1.readCompactMeasurements)((0, claude_settings_1.transcriptPath)(this.agent.workspace, cli.id), startedAt, Date.now());
403
+ if (storedMetrics)
404
+ measured = storedMetrics;
405
+ }
380
406
  this.store.transaction(() => this.store.appendEvent(String(conversation.id), 'session.context_compacted', { sessionId, cliSessionId: cli.id }));
407
+ return measured;
381
408
  }
382
409
  finally {
383
410
  revoke?.();
@@ -394,6 +421,39 @@ class AgentOrchestrationRuntime {
394
421
  void operation.finally(() => this.pending.delete(operation)).catch(() => { });
395
422
  return operation;
396
423
  }
424
+ compactionMaintenance(window) {
425
+ return this.sessionCompaction ?? (this.sessionCompaction = new session_compaction_1.SessionCompaction(this.store, this.agent.id, {
426
+ busy: id => this.active.has(id), stopping: () => this.closing || this.draining,
427
+ model: () => this.agent.claude.model, window, compact: (id, model) => this.compactSession(id, model),
428
+ }));
429
+ }
430
+ runSessionCompaction(config, window) {
431
+ const operation = this.compactionMaintenance(window).run(config);
432
+ this.pending.add(operation);
433
+ void operation.finally(() => this.pending.delete(operation)).catch(() => { });
434
+ return operation;
435
+ }
436
+ /** Lightweight live ownership only: no transcript or token-ledger scans. */
437
+ processOwners() {
438
+ return this.store.all(`SELECT t.snapshot_json,a.payload_json FROM tasks t JOIN task_attempts a
439
+ ON a.id=t.active_attempt_id WHERE t.active_attempt_id IS NOT NULL`).flatMap(row => {
440
+ const task = JSON.parse(String(row.snapshot_json)), attempt = JSON.parse(String(row.payload_json));
441
+ const pid = attempt.processIdentity?.pid;
442
+ return Number.isInteger(pid) ? [{ pid, startTicks: attempt.processIdentity?.startTicks, group: 'worker', agentId: this.agent.id,
443
+ sessionId: task.agentSessionId, taskId: task.taskId, title: task.title,
444
+ harness: attempt.harness ?? 'claude', model: attempt.harnessModel ?? task.model,
445
+ container: this.agent.type === 'app-agent' ? this.agent.container : undefined }] : [];
446
+ });
447
+ }
448
+ sessionContextWindow(sessionId) {
449
+ if (!this.store.get("SELECT name FROM sqlite_master WHERE name='token_turns'"))
450
+ return null;
451
+ const last = this.store.get(`SELECT MAX(COALESCE(d.ended_at,d.started_at)) at FROM conversation_decisions d
452
+ JOIN conversations c ON c.id=d.conversation_id WHERE c.agent_session_id=?`, sessionId)?.at;
453
+ if (last == null || Date.now() - Number(last) > 3600000)
454
+ return null;
455
+ return (0, token_ledger_1.latestAgentContextWindow)(this.store, sessionId);
456
+ }
397
457
  tokenReport(sessionId) {
398
458
  if (!this.ownsSession(sessionId))
399
459
  return undefined;
@@ -409,8 +469,8 @@ class AgentOrchestrationRuntime {
409
469
  const tool = event ? JSON.parse(String(event.payload_json)).payload : undefined;
410
470
  const measured = (0, token_ledger_1.summarizeTokenTurns)((0, token_ledger_1.measuredTurns)(this.store, String(row.agent_session_id)).filter(turn => turn.id === attempt?.attemptId));
411
471
  return { tokenSummary: { totalTokens: measured.totalTokens }, contextTools: measured.contextTools, loadedTools: measured.loadedTools, usedTools: measured.usedTools, taskId: row.id, sessionId: row.agent_session_id, state: row.state, title: snapshot.title,
412
- execution: snapshot.execution, workerId: attempt?.workerId, workstreamId: snapshot.workstreamId, continueTaskId: snapshot.continueTaskId, resumed: attempt?.resumeSession,
413
- attemptId: attempt?.attemptId, workerSessionId: attempt?.sessionId, hostProcessId: row.active_attempt_id ? attempt?.processIdentity?.pid : undefined,
472
+ executionType: snapshot.gatewayTarget ? 'gateway-managed' : 'worker', gatewayTarget: snapshot.gatewayTarget, execution: snapshot.execution, workerId: attempt?.workerId, workstreamId: snapshot.workstreamId, continueTaskId: snapshot.continueTaskId, resumed: attempt?.resumeSession,
473
+ attemptId: attempt?.attemptId, workerSessionId: snapshot.gatewayTarget ? undefined : attempt?.sessionId, targetSessionId: snapshot.gatewayTarget?.sessionId, hostProcessId: row.active_attempt_id ? attempt?.processIdentity?.pid : undefined,
414
474
  container: this.agent.type === 'app-agent' ? this.agent.container : undefined,
415
475
  lastTool: tool ? { name: tool.name, type: tool.type, is_error: tool.is_error } : undefined };
416
476
  });
@@ -737,6 +797,7 @@ class AgentOrchestrationRuntime {
737
797
  let transcriptCheckpoint;
738
798
  let restoreContainerTranscript;
739
799
  let failedTurn = false;
800
+ let removeContextObserver;
740
801
  const questionReview = Boolean(input.ingressKey?.startsWith('question-review:'));
741
802
  let internalReview = false;
742
803
  let streamedDisplay = '';
@@ -816,12 +877,52 @@ class AgentOrchestrationRuntime {
816
877
  input = { ...input, metadata: replyMetadata, attachmentIds: [...new Set([...(input.attachmentIds ?? []), ...(replyMetadata?.repliedAttachmentIds ?? [])])] };
817
878
  const semantic = this.config.conversation.semanticIntake && !active.notification;
818
879
  const prepared = semantic ? this.intake.context(receipt.conversationId, input.scope.principalId, String(admitted.binding_id)) : undefined;
819
- const preparedInputs = prepared?.inputIds?.length ? this.store.all(`SELECT id,text,attachment_refs_json,ingress_json FROM conversation_inputs
820
- WHERE conversation_id=? AND principal_id=? AND id IN (SELECT value FROM json_each(?))`, receipt.conversationId, input.scope.principalId, JSON.stringify(prepared.inputIds)) : [];
880
+ const recoveryInputId = input.ingressKey?.startsWith('intake-recovery:') ? input.ingressKey.slice('intake-recovery:'.length) : undefined;
881
+ const preparedInputIds = [...new Set([...(prepared?.inputIds ?? []), ...(recoveryInputId ? [recoveryInputId] : [])])];
882
+ const preparedInputs = preparedInputIds.length ? this.store.all(`SELECT id,text,attachment_refs_json,ingress_json FROM conversation_inputs
883
+ WHERE conversation_id=? AND principal_id=? AND binding_id=? AND id IN (SELECT value FROM json_each(?))`, receipt.conversationId, input.scope.principalId, admitted.binding_id, JSON.stringify(preparedInputIds)) : [];
821
884
  const preparedRefs = preparedInputs.flatMap(row => JSON.parse(String(row.attachment_refs_json)));
822
885
  if (preparedRefs.length)
823
886
  input = { ...input, attachmentIds: [...new Set([...(input.attachmentIds ?? []), ...preparedRefs])] };
824
- const visualInput = await (0, input_images_1.loadInputImages)((0, path_1.join)(this.agent.workspace, '../..'), this.agent.id, input.attachmentIds);
887
+ const cliSession = this.agent.type === 'app-agent'
888
+ ? await this.cliSessions.resolveContainer(sessionId, this.agent)
889
+ : this.cliSessions.resolve(sessionId, this.agent.workspace);
890
+ const contextPlan = this.contextDelivery.begin({ conversationId: receipt.conversationId,
891
+ principalId: input.scope.principalId, bindingId: String(admitted.binding_id),
892
+ cliSessionId: cliSession.id, resume: cliSession.resume });
893
+ const reusedImages = [];
894
+ const unreadImageRefs = input.attachmentIds?.filter(ref => {
895
+ const originalRef = contextPlan.imageReference(ref);
896
+ if (!originalRef)
897
+ return true;
898
+ reusedImages.push({ ref, originalRef });
899
+ return false;
900
+ });
901
+ const visualInput = await (0, input_images_1.loadInputImages)((0, path_1.join)(this.agent.workspace, '../..'), this.agent.id, unreadImageRefs);
902
+ // References are immutable ingress files. Also avoid sending identical image
903
+ // content twice when it arrived under different references.
904
+ const deliveredImages = visualInput.images.map((image, index) => ({ image, ref: visualInput.refs[index] }));
905
+ visualInput.images = [];
906
+ visualInput.refs = [];
907
+ for (const { image, ref } of deliveredImages) {
908
+ const originalRef = contextPlan.rememberImage(ref, (0, store_1.payloadHash)(image.source));
909
+ if (originalRef) {
910
+ reusedImages.push({ ref, originalRef });
911
+ continue;
912
+ }
913
+ visualInput.images.push(image);
914
+ visualInput.refs.push(ref);
915
+ }
916
+ // Immutable source IDs remain available to workers. Only the model delivery
917
+ // is incremental; full canonical text and attachment references are retained.
918
+ const freshPreparedInputs = preparedInputs.filter(row => row.id !== receipt.inputId && !contextPlan.includes('materials', String(row.id)));
919
+ for (const row of freshPreparedInputs)
920
+ contextPlan.mark('materials', String(row.id), true);
921
+ contextPlan.mark('materials', receipt.inputId, true);
922
+ const intakeValue = (value) => value ? { mode: value.mode, deferredDispatch: value.deferredDispatch,
923
+ preparation: value.preparation, inputIds: value.inputIds, task_id: value.task_id, resolution: value.resolution } : null;
924
+ const pendingState = intakeValue(prepared);
925
+ const pendingChanges = contextPlan.select('intake', [{ id: 'pending', value: pendingState }], row => row.id);
825
926
  if (!semantic && input.skill && input.modality !== 'live_voice' && !channelSpeech && !visualInput.images.length && !visualInput.unavailable.length) {
826
927
  const task = this.tasks.spawn({ ...capabilities, ...receipt, ...decision, principalId: input.scope.principalId,
827
928
  model: options.model ?? this.agent.claude.model, actionId: `skill:${receipt.inputId}` }, {
@@ -846,6 +947,15 @@ class AgentOrchestrationRuntime {
846
947
  const newerInputPending = () => !!this.store.get("SELECT id FROM conversation_inputs WHERE conversation_id=? AND principal_id=? AND binding_id=(SELECT binding_id FROM conversation_inputs WHERE id=?) AND status='accepted' AND input_seq>(SELECT input_seq FROM conversation_inputs WHERE id=?)", receipt.conversationId, input.scope.principalId, receipt.inputId, receipt.inputId);
847
948
  const intakeContext = { ...capabilities, ...receipt, ...decision, model: options.model ?? this.agent.claude.model, principalId: input.scope.principalId, actionId: `intake:${receipt.inputId}` };
848
949
  const deliverAcknowledgement = async (choice) => {
950
+ if (choice.mode === 'resolve') {
951
+ if (newerInputPending()) {
952
+ intakeDeferred = true;
953
+ return { deferred: true, reason: 'NEW_INPUT_PENDING' };
954
+ }
955
+ this.intake.choose(intakeContext, choice);
956
+ this.intake.consume(receipt.inputId, true);
957
+ return { resolved: true };
958
+ }
849
959
  if (acknowledgementId && (choice.mode !== intakeChoice?.mode || choice.task_id !== intakeChoice?.task_id))
850
960
  throw new types_2.OrchestrationError('INTAKE_ALREADY_ACKNOWLEDGED');
851
961
  if (acknowledgementReady)
@@ -853,6 +963,7 @@ class AgentOrchestrationRuntime {
853
963
  if (!acknowledgementId)
854
964
  intakeChoice = this.intake.choose(intakeContext, choice);
855
965
  if (choice.mode !== 'wait' && newerInputPending()) {
966
+ this.intake.deferDispatch(receipt.inputId);
856
967
  intakeDeferred = true;
857
968
  return { deferred: true, reason: 'NEW_INPUT_PENDING', instruction: 'New user input is already queued. End without another reply or task mutation; the next turn will receive these materials and the new instruction.' };
858
969
  }
@@ -926,8 +1037,8 @@ class AgentOrchestrationRuntime {
926
1037
  return (0, capabilities_1.readCapabilityPage)(await this.capabilityCatalog.snapshot(), this.host.skills?.(), args);
927
1038
  },
928
1039
  onIntake: semantic ? acknowledge : undefined,
929
- onMutationResult: semantic ? (actionId, committed, errorCode) => { taskActionResults.set(actionId, committed); const attempt = attemptedTaskActions.get(actionId); if (attempt)
930
- Object.assign(attempt, { committed, errorCode }); } : undefined,
1040
+ onMutationResult: (actionId, committed, errorCode) => { taskActionResults.set(actionId, committed); const attempt = attemptedTaskActions.get(actionId); if (attempt)
1041
+ Object.assign(attempt, { committed, errorCode }); },
931
1042
  beforeMutation: semantic ? async (tool, args, actionId) => {
932
1043
  if (actionId && !attemptedTaskActions.has(actionId))
933
1044
  attemptedTaskActions.set(actionId, { actionId, tool, args: JSON.parse(JSON.stringify(args)) });
@@ -938,17 +1049,23 @@ class AgentOrchestrationRuntime {
938
1049
  if (tool !== 'task_answer' && acknowledgementInFlight)
939
1050
  await acknowledgementInFlight;
940
1051
  if (intakeDeferred || newerInputPending()) {
1052
+ if (tool === 'task_spawn' || tool === 'task_update')
1053
+ this.intake.deferDispatch(receipt.inputId);
941
1054
  intakeDeferred = true;
942
1055
  throw new types_2.OrchestrationError('NEW_INPUT_PENDING');
943
1056
  }
944
1057
  if (tool === 'task_answer')
945
1058
  return;
946
- if (!intakeChoice || intakeChoice.mode === 'wait' || !acknowledgementReady)
1059
+ if (!intakeChoice || intakeChoice.mode === 'wait' || intakeChoice.mode === 'resolve' || !acknowledgementReady)
947
1060
  throw new types_2.OrchestrationError('ACKNOWLEDGEMENT_REQUIRED');
948
1061
  if (tool === 'task_spawn' && preparedInputs.length)
949
1062
  args.context_refs = [...new Set([...(Array.isArray(args.context_refs) ? args.context_refs : []), ...preparedRefs, ...preparedInputs.map(row => String(row.id))])];
950
- if (intakeChoice.mode === 'update' && (tool === 'task_spawn' || args.task_id !== intakeChoice.task_id))
1063
+ if (intakeChoice.mode === 'update' && (tool === 'task_spawn' || args.task_id !== intakeChoice.task_id)) {
1064
+ const attempt = attemptedTaskActions.get(actionId);
1065
+ if (attempt)
1066
+ attempt.intendedUpdateTaskId = intakeChoice.task_id;
951
1067
  throw new types_2.OrchestrationError('INTAKE_TASK_MISMATCH');
1068
+ }
952
1069
  } : undefined,
953
1070
  onTaskQueued: !semantic && speechEnabled && !active.notification ? spoken => {
954
1071
  if (taskSpeech)
@@ -997,8 +1114,9 @@ class AgentOrchestrationRuntime {
997
1114
  // those turns' byte-prefix diverge from every other turn in the same session, forcing a
998
1115
  // full cache-write every time such a turn interleaves with a differently shaped one.
999
1116
  // INTAKE_OVERLAY, the review directive and the speech directive below all live in the
1000
- // per-turn prompt instead that is new message content every turn regardless, so it was
1001
- // never part of the cached prefix and appending it there costs nothing extra.
1117
+ // per-turn prompt instead when their content changes. Stable intake/worker
1118
+ // instructions now live in the invariant system prefix below, rather than
1119
+ // accumulating another complete copy in each resumed user message.
1002
1120
  // The schema is resolved the other way round: ONE invariant union schema on every turn
1003
1121
  // shape, which is Anthropic's own remedy for mode switching (keep the tool set fixed,
1004
1122
  // convey the mode in message content). Verified against claude-code 2.1.274: --json-schema
@@ -1010,14 +1128,12 @@ class AgentOrchestrationRuntime {
1010
1128
  // produced, while speech and review turns fill the optional fields their per-turn overlay
1011
1129
  // asks for. This restores the structured-output guarantee without a per-turn tools diff.
1012
1130
  ticket.profile.responseSchema = response_schema_1.ORCHESTRATION_RESPONSE_SCHEMA;
1131
+ ticket.profile.overlay += `\n\n${CONTEXT_DELIVERY_INSTRUCTIONS}${this.agent.type !== 'app-agent' && this.gateway.safemode?.allowedAgentIds?.includes(this.agent.id) ? '\n' + GATEWAY_TASK_INSTRUCTIONS : ''}\n\nOnly when the current turn explicitly enables semantic intake, apply these rules:\n${conversation_intake_1.INTAKE_OVERLAY}`;
1013
1132
  // Continue the CLI session this agent session already has a transcript for. Each decision
1014
1133
  // turn is still its own process; resuming is what lets the next one reuse the previous
1015
1134
  // turn's cached prefix instead of paying a full cache write, and it replaces the flattened
1016
1135
  // history copy SessionProcess used to seed (see buildInitialPrompt). Container agents probe their transcript inside the validated container, never on the host.
1017
1136
  {
1018
- const cliSession = this.agent.type === 'app-agent'
1019
- ? await this.cliSessions.resolveContainer(sessionId, this.agent)
1020
- : this.cliSessions.resolve(sessionId, this.agent.workspace);
1021
1137
  ticket.profile.cliSession = { id: cliSession.id, resume: cliSession.resume };
1022
1138
  if (cliSession.resume && this.agent.type !== 'app-agent')
1023
1139
  transcriptCheckpoint = await (0, transcript_checkpoint_1.checkpointTranscript)((0, claude_settings_1.transcriptPath)(this.agent.workspace, cliSession.id));
@@ -1035,9 +1151,24 @@ class AgentOrchestrationRuntime {
1035
1151
  ticket.profile.excludedHistoryOperationIds = this.store.all(`SELECT r.id FROM assistant_responses r
1036
1152
  JOIN conversation_decisions d ON d.id=r.decision_id WHERE d.session_id=? AND r.state='failed'`, sessionId)
1037
1153
  .map(row => `response:${row.id}`);
1154
+ ticket.profile.responseId = decision.responseId;
1038
1155
  agentSession = await this.host.createAgentSession(sessionId, ticket.profile, options.model, input.scope);
1039
- const snapshots = this.tasks.context(receipt.conversationId, input.scope.principalId, decision.decisionId);
1040
- const committed = (0, decision_context_1.committedCommandContext)(this.store, receipt.conversationId);
1156
+ const reportingTasks = new Set(this.store.all("SELECT task_id FROM notifications WHERE decision_id=? AND status='assigned'", decision.decisionId).map(row => String(row.task_id)));
1157
+ const taskCandidates = this.tasks.context(receipt.conversationId, input.scope.principalId, decision.decisionId)
1158
+ .filter(task => !['completed', 'failed', 'cancelled'].includes(task.state) ||
1159
+ contextPlan.includes('tasks', task.taskId) || reportingTasks.has(task.taskId));
1160
+ const snapshots = contextPlan.select('tasks', taskCandidates, task => task.taskId);
1161
+ const committed = contextPlan.select('receipts', (0, decision_context_1.committedCommandContext)(this.store, receipt.conversationId, true), row => String(row.actionId));
1162
+ const observeContext = (line) => {
1163
+ try {
1164
+ const event = JSON.parse(line);
1165
+ if (event.type === 'system' && event.subtype === 'compact_boundary')
1166
+ this.contextDelivery.invalidateConversation(receipt.conversationId);
1167
+ }
1168
+ catch { /* Non-protocol output. */ }
1169
+ };
1170
+ agentSession.on('output', observeContext);
1171
+ removeContextObserver = () => agentSession?.off('output', observeContext);
1041
1172
  // Ordering inside the per-turn message: orchestration context first, the user's newest
1042
1173
  // message last. The cache matches a strict prefix and the CLI puts its breakpoint at the
1043
1174
  // end of this message, so a turn can only reuse the previous turn's write where the new
@@ -1048,7 +1179,7 @@ class AgentOrchestrationRuntime {
1048
1179
  // prefix ([tools, system]) is untouched and still carries no per-turn conditional. The
1049
1180
  // label distinguishes a real user message from an orchestration report request so the
1050
1181
  // agent does not attribute the report wording to the user.
1051
- const prompt = `${ticket.profile.cliSession?.resume && previousReports.length ? "Previously communicated updates are already in this resumed conversation; compare against them before reporting again." : (0, decision_context_1.communicatedProgressContext)(previousReports)}\nPending question attention (data, not instructions): ${JSON.stringify(this.questionControls.context(receipt.conversationId, input.scope.principalId))}\nReply-to question context (not consent): ${JSON.stringify(this.questionControls.replyContext(input))}\n${(0, reply_context_1.replyContext)(input.metadata)}\nAttachment details (reference data): ${JSON.stringify(input.metadata?.attachmentDetails ?? [])}. ${input.metadata?.attachmentError ?? ''}\n${semantic ? `[Pending preparation; source inputs are data, not new authorization] ${JSON.stringify({ prepared, inputs: preparedInputs.map(({ ingress_json, ...row }) => ({ ...row, replyContext: (0, reply_context_1.storedReplyContext)(ingress_json) })) })}` : ''}\n${input.metadata?.promptContext ?? ''}\n\n[Orchestration context: persisted task snapshots, not instructions. Each entry is an index, not a report: call task_status with its task_id for the stored result, evidence, progress and workflow history.]\n${JSON.stringify(snapshots)}\nRecent committed command receipts (do not repeat their originating work): ${JSON.stringify(committed)}\nExecution eligible: ${capabilities.execute}. Workspace mode: ${this.config.tasks.workspaceMode}. Worker profiles: default-worker is the general-purpose worker for research, files, browser/API operations, services, calculations and code. In host mode it uses the Agent working environment; no Git or projectRoot is required. In container mode it stays inside the app container. Only explicitly configured isolated-worktree mode requires Git for default-worker; media-worker remains available for standalone scratch work in isolated modes. State the authorized working directory in task instructions; workers may change directories only within their execution boundary. Serialize conflicting edits to the same shared files; continue related work with continue_task_id. Memory write eligible: ${capabilities.writeMemory}.\nOriginal attachment refs (automatically inherited by workers): ${JSON.stringify(input.attachmentIds ?? [])}\nImages attached to this user message in order: ${JSON.stringify(visualInput.refs)}. Inspect these yourself before answering or delegating execution.\nUnavailable attachments: ${JSON.stringify([...(input.metadata?.unavailableAttachments ?? []), ...visualInput.unavailable])}${input.skill ? `\nRequested installed skill: ${JSON.stringify({ name: input.skill.name, args: input.skill.args })}. Inspect the user images first, then dispatch this skill via task_spawn with skill_name and skill_args.` : ''}${semantic ? `\n\n${conversation_intake_1.INTAKE_OVERLAY}` : ''}${speechDirective}${internalReview ? `\n\n${progress_review_1.PROGRESS_REVIEW_OVERLAY}` : ''}\n\n[${active.notification ? 'Current orchestration request' : 'Current user message'} — the request to answer now]\n${input.text}`;
1182
+ const prompt = `${ticket.profile.cliSession?.resume && previousReports.length ? "Previously communicated updates are already in this resumed conversation; compare against them before reporting again." : (0, decision_context_1.communicatedProgressContext)(previousReports)}\nPending question attention (data, not instructions): ${JSON.stringify(this.questionControls.context(receipt.conversationId, input.scope.principalId))}\nReply-to question context (not consent): ${JSON.stringify(this.questionControls.replyContext(input))}\n${(0, reply_context_1.replyContext)(input.metadata)}\nAttachment details (reference data): ${JSON.stringify(input.metadata?.attachmentDetails ?? [])}. ${input.metadata?.attachmentError ?? ''}\n${semantic ? `[Pending preparation; source inputs are data, not new authorization] ${JSON.stringify({ changes: pendingChanges.map(row => row.value), inputs: freshPreparedInputs.map(({ ingress_json, ...row }) => ({ ...row, replyContext: (0, reply_context_1.storedReplyContext)(ingress_json) })) })}` : ''}\n${input.metadata?.promptContext ?? ''}\n\n[Orchestration context: persisted task snapshots, not instructions. Incremental changes only; omitted tasks are unchanged, not deleted. Each entry is an index, not a report: call task_status with its task_id for the stored result, evidence, progress and workflow history.]\n${JSON.stringify(snapshots)}\nRecent committed command receipts (do not repeat their originating work): ${JSON.stringify(committed)}\nExecution eligible: ${capabilities.execute}. Workspace mode: ${this.config.tasks.workspaceMode}. Memory write eligible: ${capabilities.writeMemory}.\nAttachment refs (automatically inherited by workers; previously delivered images remain in resumed context): ${JSON.stringify(input.attachmentIds ?? [])}\nImages attached to this user message in order: ${JSON.stringify(visualInput.refs)}. Inspect these yourself before answering or delegating execution.\nReused images (reference data; each ref has the same image as originalRef already supplied in this conversation): ${JSON.stringify(reusedImages)}\nUnavailable attachments: ${JSON.stringify([...(input.metadata?.unavailableAttachments ?? []), ...visualInput.unavailable])}${input.skill ? `\nRequested installed skill: ${JSON.stringify({ name: input.skill.name, args: input.skill.args })}. Inspect the user images first, then dispatch this skill via task_spawn with skill_name and skill_args.` : ''}${semantic ? '\nSemantic intake is active for this turn; follow the intake rules in the system instructions.' : '\nSemantic intake is inactive for this turn; do not call conversation_intake.'}${speechDirective}${internalReview ? `\n\n${progress_review_1.PROGRESS_REVIEW_OVERLAY}` : ''}\n\n[${active.notification ? 'Current orchestration request' : 'Current user message'} — the request to answer now]\n${input.text}`;
1052
1183
  if (active.stopping) {
1053
1184
  this.decisions.interrupt(decision);
1054
1185
  const display = active.stopReason === 'barge-in' ? '' : 'Response stopped.';
@@ -1091,7 +1222,7 @@ class AgentOrchestrationRuntime {
1091
1222
  }, visualInput.images, {
1092
1223
  onUsage: metrics => (0, token_ledger_1.recordTokenTurn)(this.store, { id: decision.decisionId, sessionId, role: 'agent', category: active.notification ? 'report' : 'input', ...metrics }),
1093
1224
  startupTimeoutMs: this.config.conversation.startupTimeoutMs,
1094
- firstResponseTimeoutMs: this.config.conversation.firstResponseTimeoutMs,
1225
+ firstResponseTimeoutMs: this.config.conversation.firstResponseTimeoutMs, compactionTimeoutMs: this.config.conversation.compactionTimeoutMs,
1095
1226
  idleTimeoutMs: this.config.conversation.idleTimeoutMs,
1096
1227
  }, chunk => {
1097
1228
  // StructuredOutput tool arguments are a separate JSON stream from commentary.
@@ -1103,6 +1234,22 @@ class AgentOrchestrationRuntime {
1103
1234
  });
1104
1235
  active.turn = turn;
1105
1236
  const response = await turn.result;
1237
+ if (!response.interrupted) {
1238
+ // A completed CLI turn has consumed its tool results. Failed/interrupted
1239
+ // turns never advance this checkpoint, so committed receipts can recover.
1240
+ for (const row of this.store.all("SELECT action_id,receipt_json FROM task_commands WHERE decision_id=?", decision.decisionId)) {
1241
+ if (!taskActionResults.get(String(row.action_id)))
1242
+ continue;
1243
+ const task = JSON.parse(String(row.receipt_json));
1244
+ // The worker may already have progressed beyond the returned receipt.
1245
+ // Only acknowledge the version actually returned to this tool call.
1246
+ if (typeof task?.taskId === 'string' && typeof task.stateVersion === 'number')
1247
+ contextPlan.mark('tasks', task.taskId, (0, service_1.taskIndexEntry)(task));
1248
+ }
1249
+ if (intakeChoice)
1250
+ contextPlan.mark('intake', 'pending', { id: 'pending', value: intakeValue(intakeChoice) });
1251
+ contextPlan.commit();
1252
+ }
1106
1253
  // Single conversion point from the raw turn text to the user-facing surfaces; every
1107
1254
  // downstream consumer (channels, web, dashboard, history, token accounting) reads the
1108
1255
  // result of this boundary, so the union schema stays invisible to them. Every turn is
@@ -1183,6 +1330,24 @@ class AgentOrchestrationRuntime {
1183
1330
  }
1184
1331
  if (semantic && intakeChoice?.mode !== 'wait' && (intakeChoice || display.trim()) && !intakeDeferred && !newerInputPending() && !response.interrupted)
1185
1332
  this.intake.consume(receipt.inputId);
1333
+ const pendingDispatch = semantic && this.intake.context(receipt.conversationId, input.scope.principalId, String(admitted.binding_id));
1334
+ if (pendingDispatch?.deferredDispatch && pendingDispatch.mode !== 'wait' && capabilities.execute &&
1335
+ !input.ingressKey?.startsWith('intake-recovery:') && !intakeDeferred && !newerInputPending() &&
1336
+ !response.interrupted && !active.stopping) {
1337
+ // One bounded reconciliation turn after a direct reply, never an automatic
1338
+ // replay of the rejected command. It sees current instructions and uses
1339
+ // the same principal, binding and execution permissions as this turn.
1340
+ try {
1341
+ this.store.acceptInput({ scope: input.scope, storeUserMessage: false,
1342
+ ingressKey: `intake-recovery:${receipt.inputId}`, capabilities, model: options.model,
1343
+ text: 'Reconcile the pending deferred dispatch with the latest user instructions. Earlier NEW_INPUT_PENDING was temporary. If still authorized, acknowledge and commit the appropriate task command now. If cancelled, replaced, or already satisfied, use conversation_intake mode=resolve with a concrete resolution. Do not merely repeat a promise or the earlier rejection. If a new decision is necessary, ask a specific question and preserve the pending work.' + '\nLatest user input ID: ' + receipt.inputId }, this.config.conversation.maxPendingInputs);
1344
+ }
1345
+ catch (error) {
1346
+ if (!(error instanceof types_2.OrchestrationError) || error.code !== 'QUEUE_FULL')
1347
+ throw error;
1348
+ // Keep the durable pending dispatch for the next input when admission is full.
1349
+ }
1350
+ }
1186
1351
  return silent ? acknowledgement : display || acknowledgement;
1187
1352
  }
1188
1353
  catch (error) {
@@ -1239,6 +1404,7 @@ class AgentOrchestrationRuntime {
1239
1404
  throw error;
1240
1405
  }
1241
1406
  finally {
1407
+ removeContextObserver?.();
1242
1408
  revoke?.();
1243
1409
  if (agentSession)
1244
1410
  await this.host.releaseAgentSession(sessionId, agentSession);
@@ -1267,6 +1433,9 @@ class AgentOrchestrationRuntime {
1267
1433
  for (const row of this.store.all("SELECT operation_id FROM history_operations WHERE state='pending' ORDER BY updated_at LIMIT 200"))
1268
1434
  await this.history.write(String(row.operation_id));
1269
1435
  }
1436
+ hasPendingWork() {
1437
+ return !!(this.active.size || this.pending.size || this.store.get("SELECT id FROM conversation_inputs WHERE status IN ('accepted','assigned') LIMIT 1") || this.store.get("SELECT id FROM tasks WHERE state NOT IN ('completed','failed','cancelled') LIMIT 1"));
1438
+ }
1270
1439
  drain() {
1271
1440
  this.draining = true;
1272
1441
  this.store.run("UPDATE conversations SET status='draining' WHERE status='active'");
@@ -1294,6 +1463,7 @@ class AgentOrchestrationRuntime {
1294
1463
  this.drain();
1295
1464
  for (const sessionId of this.active.keys())
1296
1465
  this.stopResponse(sessionId);
1466
+ await this.gatewayTasks?.close();
1297
1467
  await this.scheduler.close();
1298
1468
  await this.settleResources();
1299
1469
  await Promise.allSettled([...this.pending]);