@0xmaxma/claude-gateway 2.0.6 → 2.0.8

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 (429) hide show
  1. package/README.md +15 -1
  2. package/config.template.json +5 -3
  3. package/dist/agent/builtin-commands.js +5 -5
  4. package/dist/agent/builtin-commands.js.map +1 -1
  5. package/dist/agent/command-help.d.ts +9 -0
  6. package/dist/agent/command-help.d.ts.map +1 -0
  7. package/dist/agent/command-help.js +50 -0
  8. package/dist/agent/command-help.js.map +1 -0
  9. package/dist/agent/dreaming/index.d.ts +6 -3
  10. package/dist/agent/dreaming/index.d.ts.map +1 -1
  11. package/dist/agent/dreaming/index.js +21 -1
  12. package/dist/agent/dreaming/index.js.map +1 -1
  13. package/dist/agent/knowledge/reflection.d.ts +7 -4
  14. package/dist/agent/knowledge/reflection.d.ts.map +1 -1
  15. package/dist/agent/knowledge/reflection.js +19 -1
  16. package/dist/agent/knowledge/reflection.js.map +1 -1
  17. package/dist/agent/runner.d.ts +51 -3
  18. package/dist/agent/runner.d.ts.map +1 -1
  19. package/dist/agent/runner.js +244 -66
  20. package/dist/agent/runner.js.map +1 -1
  21. package/dist/agent/session-confirmations.d.ts +12 -0
  22. package/dist/agent/session-confirmations.d.ts.map +1 -0
  23. package/dist/agent/session-confirmations.js +43 -0
  24. package/dist/agent/session-confirmations.js.map +1 -0
  25. package/dist/agent/session-status.d.ts +7 -0
  26. package/dist/agent/session-status.d.ts.map +1 -0
  27. package/dist/agent/session-status.js +16 -0
  28. package/dist/agent/session-status.js.map +1 -0
  29. package/dist/agent/skill-learning/index.d.ts +5 -1
  30. package/dist/agent/skill-learning/index.d.ts.map +1 -1
  31. package/dist/agent/skill-learning/index.js +23 -1
  32. package/dist/agent/skill-learning/index.js.map +1 -1
  33. package/dist/agent/skill-learning/notifier.d.ts +2 -1
  34. package/dist/agent/skill-learning/notifier.d.ts.map +1 -1
  35. package/dist/agent/skill-learning/notifier.js +1 -0
  36. package/dist/agent/skill-learning/notifier.js.map +1 -1
  37. package/dist/api/apps-router.d.ts.map +1 -1
  38. package/dist/api/apps-router.js +1 -3
  39. package/dist/api/apps-router.js.map +1 -1
  40. package/dist/api/cron-router.d.ts +1 -1
  41. package/dist/api/cron-router.d.ts.map +1 -1
  42. package/dist/api/cron-router.js +4 -4
  43. package/dist/api/cron-router.js.map +1 -1
  44. package/dist/api/dashboard-processes.d.ts +86 -0
  45. package/dist/api/dashboard-processes.d.ts.map +1 -0
  46. package/dist/api/dashboard-processes.js +155 -0
  47. package/dist/api/dashboard-processes.js.map +1 -0
  48. package/dist/api/dashboard-sessions.d.ts +15 -0
  49. package/dist/api/dashboard-sessions.d.ts.map +1 -0
  50. package/dist/api/dashboard-sessions.js +66 -0
  51. package/dist/api/dashboard-sessions.js.map +1 -0
  52. package/dist/api/gateway-router.d.ts +3 -4
  53. package/dist/api/gateway-router.d.ts.map +1 -1
  54. package/dist/api/gateway-router.js +77 -56
  55. package/dist/api/gateway-router.js.map +1 -1
  56. package/dist/api/oauth-connectors-router.d.ts +1 -1
  57. package/dist/api/oauth-connectors-router.d.ts.map +1 -1
  58. package/dist/api/oauth-connectors-router.js +11 -21
  59. package/dist/api/oauth-connectors-router.js.map +1 -1
  60. package/dist/api/router.d.ts +1 -1
  61. package/dist/api/router.d.ts.map +1 -1
  62. package/dist/api/router.js +119 -14
  63. package/dist/api/router.js.map +1 -1
  64. package/dist/api/share-router.d.ts +1 -1
  65. package/dist/api/share-router.d.ts.map +1 -1
  66. package/dist/api/share-router.js +1 -1
  67. package/dist/api/share-router.js.map +1 -1
  68. package/dist/api/slack-webhook-router.js +1 -1
  69. package/dist/api/slack-webhook-router.js.map +1 -1
  70. package/dist/api/voice-router.d.ts +1 -0
  71. package/dist/api/voice-router.d.ts.map +1 -1
  72. package/dist/api/voice-router.js +7 -0
  73. package/dist/api/voice-router.js.map +1 -1
  74. package/dist/api/voice-settings-router.d.ts.map +1 -1
  75. package/dist/api/voice-settings-router.js +2 -1
  76. package/dist/api/voice-settings-router.js.map +1 -1
  77. package/dist/apps/agent-container-migration.d.ts +2 -0
  78. package/dist/apps/agent-container-migration.d.ts.map +1 -1
  79. package/dist/apps/agent-container-migration.js +59 -2
  80. package/dist/apps/agent-container-migration.js.map +1 -1
  81. package/dist/apps/agent-manager.d.ts +4 -2
  82. package/dist/apps/agent-manager.d.ts.map +1 -1
  83. package/dist/apps/agent-manager.js +39 -3
  84. package/dist/apps/agent-manager.js.map +1 -1
  85. package/dist/apps/installer.d.ts +4 -3
  86. package/dist/apps/installer.d.ts.map +1 -1
  87. package/dist/apps/installer.js +8 -4
  88. package/dist/apps/installer.js.map +1 -1
  89. package/dist/build-provenance.json +8 -0
  90. package/dist/cli/args.js +1 -1
  91. package/dist/cli/args.js.map +1 -1
  92. package/dist/cli/commands/app.d.ts.map +1 -1
  93. package/dist/cli/commands/app.js +39 -3
  94. package/dist/cli/commands/app.js.map +1 -1
  95. package/dist/cli/commands/doctor.d.ts.map +1 -1
  96. package/dist/cli/commands/doctor.js +6 -2
  97. package/dist/cli/commands/doctor.js.map +1 -1
  98. package/dist/cli/commands/safemode.d.ts +2 -0
  99. package/dist/cli/commands/safemode.d.ts.map +1 -0
  100. package/dist/cli/commands/safemode.js +279 -0
  101. package/dist/cli/commands/safemode.js.map +1 -0
  102. package/dist/cli/dependencies.d.ts +2 -0
  103. package/dist/cli/dependencies.d.ts.map +1 -1
  104. package/dist/cli/dependencies.js +81 -0
  105. package/dist/cli/dependencies.js.map +1 -1
  106. package/dist/cli/index.d.ts.map +1 -1
  107. package/dist/cli/index.js +11 -1
  108. package/dist/cli/index.js.map +1 -1
  109. package/dist/cli/manager.d.ts.map +1 -1
  110. package/dist/cli/manager.js +4 -1
  111. package/dist/cli/manager.js.map +1 -1
  112. package/dist/config/agent-lifecycle.d.ts +26 -0
  113. package/dist/config/agent-lifecycle.d.ts.map +1 -0
  114. package/dist/config/agent-lifecycle.js +63 -0
  115. package/dist/config/agent-lifecycle.js.map +1 -0
  116. package/dist/config/loader.d.ts.map +1 -1
  117. package/dist/config/loader.js +11 -0
  118. package/dist/config/loader.js.map +1 -1
  119. package/dist/config/reload-policy.d.ts +9 -0
  120. package/dist/config/reload-policy.d.ts.map +1 -0
  121. package/dist/config/reload-policy.js +62 -0
  122. package/dist/config/reload-policy.js.map +1 -0
  123. package/dist/config/watcher.d.ts +3 -2
  124. package/dist/config/watcher.d.ts.map +1 -1
  125. package/dist/config/watcher.js +34 -51
  126. package/dist/config/watcher.js.map +1 -1
  127. package/dist/cron/tool-schemas.d.ts +296 -0
  128. package/dist/cron/tool-schemas.d.ts.map +1 -0
  129. package/dist/cron/tool-schemas.js +122 -0
  130. package/dist/cron/tool-schemas.js.map +1 -0
  131. package/dist/history/db.d.ts +4 -0
  132. package/dist/history/db.d.ts.map +1 -1
  133. package/dist/history/db.js +33 -5
  134. package/dist/history/db.js.map +1 -1
  135. package/dist/history/types.d.ts +1 -0
  136. package/dist/history/types.d.ts.map +1 -1
  137. package/dist/index.js +141 -158
  138. package/dist/index.js.map +1 -1
  139. package/dist/orchestration/agent-tool-schemas.js +4 -4
  140. package/dist/orchestration/agent-tool-schemas.js.map +1 -1
  141. package/dist/orchestration/background-work.d.ts +9 -0
  142. package/dist/orchestration/background-work.d.ts.map +1 -0
  143. package/dist/orchestration/background-work.js +49 -0
  144. package/dist/orchestration/background-work.js.map +1 -0
  145. package/dist/orchestration/bridge.d.ts +6 -15
  146. package/dist/orchestration/bridge.d.ts.map +1 -1
  147. package/dist/orchestration/bridge.js +67 -32
  148. package/dist/orchestration/bridge.js.map +1 -1
  149. package/dist/orchestration/capabilities.d.ts.map +1 -1
  150. package/dist/orchestration/capabilities.js +18 -10
  151. package/dist/orchestration/capabilities.js.map +1 -1
  152. package/dist/orchestration/capacity.d.ts +3 -2
  153. package/dist/orchestration/capacity.d.ts.map +1 -1
  154. package/dist/orchestration/capacity.js +7 -0
  155. package/dist/orchestration/capacity.js.map +1 -1
  156. package/dist/orchestration/channel-controls.d.ts.map +1 -1
  157. package/dist/orchestration/channel-controls.js +3 -2
  158. package/dist/orchestration/channel-controls.js.map +1 -1
  159. package/dist/orchestration/channel-speech.d.ts +1 -1
  160. package/dist/orchestration/channel-speech.d.ts.map +1 -1
  161. package/dist/orchestration/channel-speech.js +2 -2
  162. package/dist/orchestration/channel-speech.js.map +1 -1
  163. package/dist/orchestration/cli-skills.d.ts +5 -0
  164. package/dist/orchestration/cli-skills.d.ts.map +1 -1
  165. package/dist/orchestration/config.d.ts +13 -0
  166. package/dist/orchestration/config.d.ts.map +1 -1
  167. package/dist/orchestration/config.js +6 -0
  168. package/dist/orchestration/config.js.map +1 -1
  169. package/dist/orchestration/container-tool-schemas.d.ts +37 -0
  170. package/dist/orchestration/container-tool-schemas.d.ts.map +1 -0
  171. package/dist/orchestration/container-tool-schemas.js +27 -0
  172. package/dist/orchestration/container-tool-schemas.js.map +1 -0
  173. package/dist/orchestration/container.d.ts.map +1 -1
  174. package/dist/orchestration/container.js +7 -0
  175. package/dist/orchestration/container.js.map +1 -1
  176. package/dist/orchestration/dashboard-provider-wait.d.ts +9 -0
  177. package/dist/orchestration/dashboard-provider-wait.d.ts.map +1 -0
  178. package/dist/orchestration/dashboard-provider-wait.js +26 -0
  179. package/dist/orchestration/dashboard-provider-wait.js.map +1 -0
  180. package/dist/orchestration/dashboard-reader-worker.js +18 -11
  181. package/dist/orchestration/dashboard-reader-worker.js.map +1 -1
  182. package/dist/orchestration/decision-context.js +1 -1
  183. package/dist/orchestration/decision-context.js.map +1 -1
  184. package/dist/orchestration/delivery.d.ts +2 -1
  185. package/dist/orchestration/delivery.d.ts.map +1 -1
  186. package/dist/orchestration/delivery.js +39 -5
  187. package/dist/orchestration/delivery.js.map +1 -1
  188. package/dist/orchestration/file-delivery.d.ts +1 -1
  189. package/dist/orchestration/file-delivery.d.ts.map +1 -1
  190. package/dist/orchestration/file-delivery.js +8 -1
  191. package/dist/orchestration/file-delivery.js.map +1 -1
  192. package/dist/orchestration/gateway-config.js +1 -1
  193. package/dist/orchestration/gateway-config.js.map +1 -1
  194. package/dist/orchestration/gateway-tasks/controller.d.ts +29 -0
  195. package/dist/orchestration/gateway-tasks/controller.d.ts.map +1 -0
  196. package/dist/orchestration/gateway-tasks/controller.js +139 -0
  197. package/dist/orchestration/gateway-tasks/controller.js.map +1 -0
  198. package/dist/orchestration/gateway-tasks/safemode.d.ts +19 -0
  199. package/dist/orchestration/gateway-tasks/safemode.d.ts.map +1 -0
  200. package/dist/orchestration/gateway-tasks/safemode.js +128 -0
  201. package/dist/orchestration/gateway-tasks/safemode.js.map +1 -0
  202. package/dist/orchestration/line-quota.d.ts +57 -0
  203. package/dist/orchestration/line-quota.d.ts.map +1 -0
  204. package/dist/orchestration/line-quota.js +191 -0
  205. package/dist/orchestration/line-quota.js.map +1 -0
  206. package/dist/orchestration/process-turn.d.ts +12 -2
  207. package/dist/orchestration/process-turn.d.ts.map +1 -1
  208. package/dist/orchestration/process-turn.js +72 -12
  209. package/dist/orchestration/process-turn.js.map +1 -1
  210. package/dist/orchestration/provider-admission.d.ts +63 -0
  211. package/dist/orchestration/provider-admission.d.ts.map +1 -0
  212. package/dist/orchestration/provider-admission.js +175 -0
  213. package/dist/orchestration/provider-admission.js.map +1 -0
  214. package/dist/orchestration/provider-error-metadata.d.ts +9 -0
  215. package/dist/orchestration/provider-error-metadata.d.ts.map +1 -0
  216. package/dist/orchestration/provider-error-metadata.js +28 -0
  217. package/dist/orchestration/provider-error-metadata.js.map +1 -0
  218. package/dist/orchestration/provider-scope.d.ts +28 -0
  219. package/dist/orchestration/provider-scope.d.ts.map +1 -0
  220. package/dist/orchestration/provider-scope.js +137 -0
  221. package/dist/orchestration/provider-scope.js.map +1 -0
  222. package/dist/orchestration/recovery.d.ts.map +1 -1
  223. package/dist/orchestration/recovery.js +4 -2
  224. package/dist/orchestration/recovery.js.map +1 -1
  225. package/dist/orchestration/runtime.d.ts +23 -0
  226. package/dist/orchestration/runtime.d.ts.map +1 -1
  227. package/dist/orchestration/runtime.js +248 -28
  228. package/dist/orchestration/runtime.js.map +1 -1
  229. package/dist/orchestration/skills.d.ts +2 -0
  230. package/dist/orchestration/skills.d.ts.map +1 -1
  231. package/dist/orchestration/skills.js +4 -3
  232. package/dist/orchestration/skills.js.map +1 -1
  233. package/dist/orchestration/store.d.ts +6 -0
  234. package/dist/orchestration/store.d.ts.map +1 -1
  235. package/dist/orchestration/store.js +51 -10
  236. package/dist/orchestration/store.js.map +1 -1
  237. package/dist/orchestration/task-controls.d.ts +12 -0
  238. package/dist/orchestration/task-controls.d.ts.map +1 -1
  239. package/dist/orchestration/task-controls.js +3 -1
  240. package/dist/orchestration/task-controls.js.map +1 -1
  241. package/dist/orchestration/tasks/driver.d.ts +5 -2
  242. package/dist/orchestration/tasks/driver.d.ts.map +1 -1
  243. package/dist/orchestration/tasks/driver.js +116 -15
  244. package/dist/orchestration/tasks/driver.js.map +1 -1
  245. package/dist/orchestration/tasks/pool.d.ts +2 -0
  246. package/dist/orchestration/tasks/pool.d.ts.map +1 -1
  247. package/dist/orchestration/tasks/pool.js +4 -0
  248. package/dist/orchestration/tasks/pool.js.map +1 -1
  249. package/dist/orchestration/tasks/scheduler.d.ts +12 -2
  250. package/dist/orchestration/tasks/scheduler.d.ts.map +1 -1
  251. package/dist/orchestration/tasks/scheduler.js +81 -7
  252. package/dist/orchestration/tasks/scheduler.js.map +1 -1
  253. package/dist/orchestration/tasks/service.d.ts +5 -1
  254. package/dist/orchestration/tasks/service.d.ts.map +1 -1
  255. package/dist/orchestration/tasks/service.js +49 -10
  256. package/dist/orchestration/tasks/service.js.map +1 -1
  257. package/dist/orchestration/token-ledger.d.ts +1 -0
  258. package/dist/orchestration/token-ledger.d.ts.map +1 -1
  259. package/dist/orchestration/token-ledger.js +6 -2
  260. package/dist/orchestration/token-ledger.js.map +1 -1
  261. package/dist/orchestration/token-usage.d.ts +3 -0
  262. package/dist/orchestration/token-usage.d.ts.map +1 -1
  263. package/dist/orchestration/token-usage.js +12 -3
  264. package/dist/orchestration/token-usage.js.map +1 -1
  265. package/dist/orchestration/types.d.ts +22 -1
  266. package/dist/orchestration/types.d.ts.map +1 -1
  267. package/dist/orchestration/types.js.map +1 -1
  268. package/dist/orchestration/worker-crons.d.ts +5 -0
  269. package/dist/orchestration/worker-crons.d.ts.map +1 -0
  270. package/dist/orchestration/worker-crons.js +84 -0
  271. package/dist/orchestration/worker-crons.js.map +1 -0
  272. package/dist/orchestration/worker-harness.d.ts +15 -0
  273. package/dist/orchestration/worker-harness.d.ts.map +1 -0
  274. package/dist/orchestration/worker-harness.js +72 -0
  275. package/dist/orchestration/worker-harness.js.map +1 -0
  276. package/dist/safemode/config.d.ts +7 -0
  277. package/dist/safemode/config.d.ts.map +1 -0
  278. package/dist/safemode/config.js +67 -0
  279. package/dist/safemode/config.js.map +1 -0
  280. package/dist/safemode/context.d.ts +7 -0
  281. package/dist/safemode/context.d.ts.map +1 -0
  282. package/dist/safemode/context.js +397 -0
  283. package/dist/safemode/context.js.map +1 -0
  284. package/dist/safemode/external-owners.d.ts +19 -0
  285. package/dist/safemode/external-owners.d.ts.map +1 -0
  286. package/dist/safemode/external-owners.js +229 -0
  287. package/dist/safemode/external-owners.js.map +1 -0
  288. package/dist/safemode/native.d.ts +38 -0
  289. package/dist/safemode/native.d.ts.map +1 -0
  290. package/dist/safemode/native.js +220 -0
  291. package/dist/safemode/native.js.map +1 -0
  292. package/dist/safemode/params.d.ts +10 -0
  293. package/dist/safemode/params.d.ts.map +1 -0
  294. package/dist/safemode/params.js +86 -0
  295. package/dist/safemode/params.js.map +1 -0
  296. package/dist/safemode/provenance.d.ts +45 -0
  297. package/dist/safemode/provenance.d.ts.map +1 -0
  298. package/dist/safemode/provenance.js +153 -0
  299. package/dist/safemode/provenance.js.map +1 -0
  300. package/dist/safemode/runner.d.ts +17 -0
  301. package/dist/safemode/runner.d.ts.map +1 -0
  302. package/dist/safemode/runner.js +398 -0
  303. package/dist/safemode/runner.js.map +1 -0
  304. package/dist/safemode/store.d.ts +56 -0
  305. package/dist/safemode/store.d.ts.map +1 -0
  306. package/dist/safemode/store.js +451 -0
  307. package/dist/safemode/store.js.map +1 -0
  308. package/dist/session/codex-auth.d.ts +37 -0
  309. package/dist/session/codex-auth.d.ts.map +1 -0
  310. package/dist/session/codex-auth.js +266 -0
  311. package/dist/session/codex-auth.js.map +1 -0
  312. package/dist/session/codex-container-runtime.d.ts +15 -0
  313. package/dist/session/codex-container-runtime.d.ts.map +1 -0
  314. package/dist/session/codex-container-runtime.js +85 -0
  315. package/dist/session/codex-container-runtime.js.map +1 -0
  316. package/dist/session/codex-context-defaults.json +5 -0
  317. package/dist/session/codex-context.d.ts +13 -0
  318. package/dist/session/codex-context.d.ts.map +1 -0
  319. package/dist/session/codex-context.js +27 -0
  320. package/dist/session/codex-context.js.map +1 -0
  321. package/dist/session/codex-extension-discovery.d.ts +21 -0
  322. package/dist/session/codex-extension-discovery.d.ts.map +1 -0
  323. package/dist/session/codex-extension-discovery.js +132 -0
  324. package/dist/session/codex-extension-discovery.js.map +1 -0
  325. package/dist/session/codex-native-mcp-client.d.ts +37 -0
  326. package/dist/session/codex-native-mcp-client.d.ts.map +1 -0
  327. package/dist/session/codex-native-mcp-client.js +164 -0
  328. package/dist/session/codex-native-mcp-client.js.map +1 -0
  329. package/dist/session/codex-policy.d.ts +6 -0
  330. package/dist/session/codex-policy.d.ts.map +1 -0
  331. package/dist/session/codex-policy.js +17 -0
  332. package/dist/session/codex-policy.js.map +1 -0
  333. package/dist/session/codex-process.d.ts +120 -0
  334. package/dist/session/codex-process.d.ts.map +1 -0
  335. package/dist/session/codex-process.js +817 -0
  336. package/dist/session/codex-process.js.map +1 -0
  337. package/dist/session/codex-runtime.d.ts +20 -0
  338. package/dist/session/codex-runtime.d.ts.map +1 -0
  339. package/dist/session/codex-runtime.js +190 -0
  340. package/dist/session/codex-runtime.js.map +1 -0
  341. package/dist/session/codex-tool-capture.d.ts +35 -0
  342. package/dist/session/codex-tool-capture.d.ts.map +1 -0
  343. package/dist/session/codex-tool-capture.js +178 -0
  344. package/dist/session/codex-tool-capture.js.map +1 -0
  345. package/dist/session/container-connectors.d.ts +10 -0
  346. package/dist/session/container-connectors.d.ts.map +1 -0
  347. package/dist/session/container-connectors.js +41 -0
  348. package/dist/session/container-connectors.js.map +1 -0
  349. package/dist/session/container-extensions.d.ts +4 -0
  350. package/dist/session/container-extensions.d.ts.map +1 -0
  351. package/dist/session/container-extensions.js +45 -0
  352. package/dist/session/container-extensions.js.map +1 -0
  353. package/dist/session/managed-connectors.d.ts +16 -0
  354. package/dist/session/managed-connectors.d.ts.map +1 -0
  355. package/dist/session/managed-connectors.js +25 -0
  356. package/dist/session/managed-connectors.js.map +1 -0
  357. package/dist/session/process-diagnostics.d.ts +14 -0
  358. package/dist/session/process-diagnostics.d.ts.map +1 -0
  359. package/dist/session/process-diagnostics.js +39 -0
  360. package/dist/session/process-diagnostics.js.map +1 -0
  361. package/dist/session/process.d.ts +4 -0
  362. package/dist/session/process.d.ts.map +1 -1
  363. package/dist/session/process.js +21 -16
  364. package/dist/session/process.js.map +1 -1
  365. package/dist/session/request-tool-capture.d.ts +1 -1
  366. package/dist/session/request-tool-capture.d.ts.map +1 -1
  367. package/dist/session/runtime-profile.d.ts +8 -0
  368. package/dist/session/runtime-profile.d.ts.map +1 -1
  369. package/dist/session/runtime-profile.js +3 -2
  370. package/dist/session/runtime-profile.js.map +1 -1
  371. package/dist/session/worker-environment.d.ts +5 -0
  372. package/dist/session/worker-environment.d.ts.map +1 -0
  373. package/dist/session/worker-environment.js +27 -0
  374. package/dist/session/worker-environment.js.map +1 -0
  375. package/dist/session/worker-extensions.d.ts +20 -0
  376. package/dist/session/worker-extensions.d.ts.map +1 -0
  377. package/dist/session/worker-extensions.js +322 -0
  378. package/dist/session/worker-extensions.js.map +1 -0
  379. package/dist/share/share-store.d.ts +5 -11
  380. package/dist/share/share-store.d.ts.map +1 -1
  381. package/dist/share/share-store.js +33 -5
  382. package/dist/share/share-store.js.map +1 -1
  383. package/dist/skills/loader.d.ts +2 -0
  384. package/dist/skills/loader.d.ts.map +1 -1
  385. package/dist/skills/loader.js.map +1 -1
  386. package/dist/types.d.ts +30 -0
  387. package/dist/types.d.ts.map +1 -1
  388. package/dist/ui/codex-context.d.ts +4 -0
  389. package/dist/ui/codex-context.d.ts.map +1 -0
  390. package/dist/ui/codex-context.js +15 -0
  391. package/dist/ui/codex-context.js.map +1 -0
  392. package/dist/ui/dashboard-client.d.ts.map +1 -1
  393. package/dist/ui/dashboard-client.js +17 -13
  394. package/dist/ui/dashboard-client.js.map +1 -1
  395. package/dist/ui/dashboard-presentation.d.ts +3 -1
  396. package/dist/ui/dashboard-presentation.d.ts.map +1 -1
  397. package/dist/ui/dashboard-presentation.js +17 -3
  398. package/dist/ui/dashboard-presentation.js.map +1 -1
  399. package/dist/ui/token-report.d.ts +9 -0
  400. package/dist/ui/token-report.d.ts.map +1 -1
  401. package/dist/ui/token-report.js +23 -11
  402. package/dist/ui/token-report.js.map +1 -1
  403. package/dist/ui/web-ui.d.ts.map +1 -1
  404. package/dist/ui/web-ui.js +53 -132
  405. package/dist/ui/web-ui.js.map +1 -1
  406. package/dist/voice/providers/paxalabs-live-stt.d.ts +29 -0
  407. package/dist/voice/providers/paxalabs-live-stt.d.ts.map +1 -0
  408. package/dist/voice/providers/paxalabs-live-stt.js +137 -0
  409. package/dist/voice/providers/paxalabs-live-stt.js.map +1 -0
  410. package/dist/voice/providers/registry.d.ts.map +1 -1
  411. package/dist/voice/providers/registry.js +2 -1
  412. package/dist/voice/providers/registry.js.map +1 -1
  413. package/mcp/capability-catalog.ts +2 -0
  414. package/mcp/extension-catalog.ts +18 -0
  415. package/mcp/lazy-connector.ts +4 -2
  416. package/mcp/lazy-tools.test.ts +29 -0
  417. package/mcp/modules.ts +1 -0
  418. package/mcp/server.ts +2 -2
  419. package/mcp/tools/cron/module.ts +8 -114
  420. package/mcp/tools/discord/commands.ts +4 -1
  421. package/mcp/tools/safemode/module.test.ts +29 -0
  422. package/mcp/tools/telegram/receiver-server.ts +6 -24
  423. package/mcp/tools/telegram/task-detail.ts +2 -1
  424. package/package.json +3 -2
  425. package/scripts/orchestration/audit-codex-context.cjs +83 -0
  426. package/scripts/orchestration/benchmark-worker-harnesses.cjs +112 -0
  427. package/scripts/orchestration/smoke-codex-extensions.ts +29 -0
  428. package/scripts/orchestration/smoke-codex-worker.cjs +166 -0
  429. package/scripts/orchestration/smoke-safemode-codex.cjs +66 -0
@@ -1,6 +1,9 @@
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");
4
7
  const compact_measurements_1 = require("./compact-measurements");
5
8
  const session_compaction_1 = require("./session-compaction");
6
9
  const context_delivery_1 = require("./context-delivery");
@@ -70,8 +73,11 @@ const capacity_1 = require("./capacity");
70
73
  const cleanup_1 = require("./tasks/cleanup");
71
74
  const task_files_1 = require("./task-files");
72
75
  const worker_shares_1 = require("./worker-shares");
76
+ const provider_admission_1 = require("./provider-admission");
77
+ const provider_scope_1 = require("./provider-scope");
73
78
  /** Stable instructions are carried in the system prefix, not appended to every
74
79
  * resumed user turn. Per-turn authorization flags remain explicit below it. */
80
+ 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.';
75
81
  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.';
76
82
  class AgentOrchestrationRuntime {
77
83
  setBrowserVoice(sessionId, principalId, enabled) {
@@ -122,7 +128,10 @@ class AgentOrchestrationRuntime {
122
128
  this.taskControls = new task_controls_1.TaskControls(store, tasks);
123
129
  this.stopControls = new stop_controls_1.StopControls(store, tasks, id => this.stopResponse(id));
124
130
  this.channelControls = new channel_controls_1.ChannelControls(store, this.taskControls, this.stopControls, new telegram_voices_1.TelegramVoices(store, () => this.config.voice.tts, voice_catalog_1.voiceChoices, 8), () => (this.config.voice.enabled && this.config.voice.notes.replyWithVoice));
125
- this.delivery = new delivery_1.DeliveryOutbox(store, (0, delivery_1.channelSender)(() => this.agent, fetch, (binding, speech) => Boolean(this.config.enabled && this.config.channels.includes(String(binding.channel)) && (this.config.voice.enabled && this.config.voice.notes.replyWithVoice) && (0, voice_reply_policy_1.voiceReplyAllowed)(store.channelVoiceMode(String(binding.channel), String(binding.chat_id), String(binding.thread_key ?? '')), speech.voiceOrigin === true) && (0, model_ref_1.canonicalVoiceProvider)(this.config.voice.tts.provider) === (0, model_ref_1.canonicalVoiceProvider)(speech.provider)), host.sendLinkedChannel));
131
+ this.delivery = new delivery_1.DeliveryOutbox(store, (0, delivery_1.channelSender)(() => this.agent, fetch, (binding, speech) => Boolean(this.config.enabled && this.config.channels.includes(String(binding.channel)) && (this.config.voice.enabled && this.config.voice.notes.replyWithVoice) && (0, voice_reply_policy_1.voiceReplyAllowed)(store.channelVoiceMode(String(binding.channel), String(binding.chat_id), String(binding.thread_key ?? '')), speech.voiceOrigin === true) && (0, model_ref_1.canonicalVoiceProvider)(this.config.voice.tts.provider) === (0, model_ref_1.canonicalVoiceProvider)(speech.provider)), host.sendLinkedChannel,
132
+ // Includes 'processing' so the delivery that just 429'd (already claimed,
133
+ // no longer 'pending') still counts itself as part of the group needing quota.
134
+ () => Number(store.get(`SELECT COUNT(*) n FROM outbox o JOIN deliveries d ON d.id=json_extract(o.payload_json,'$.deliveryId') JOIN conversation_bindings b ON b.id=d.binding_id WHERE o.kind='delivery' AND o.state IN ('pending','processing') AND b.channel='line'`).n)));
126
135
  this.decisions = new decisions_1.DecisionService(store, (response, binding, text) => {
127
136
  this.delivery.enqueue(response, binding, text);
128
137
  const spoken = store.get('SELECT text FROM response_speech WHERE response_id=?', response);
@@ -184,10 +193,13 @@ class AgentOrchestrationRuntime {
184
193
  }
185
194
  const tasks = new service_1.TaskService(store, agent.orchestration, agent.workspace);
186
195
  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);
187
- 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);
196
+ const safemodeAllowed = () => agent.type !== 'app-agent' && Boolean(gateway.safemode?.allowedAgentIds?.includes(agent.id));
197
+ const gatewayAdapters = new Map(agent.type === 'app-agent' ? [] : [['safemode', new safemode_1.SafemodeTaskAdapter(agent.id, safemodeAllowed)]]);
198
+ 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);
188
199
  const personalRetention = (0, config_1.resolveDreamingConfig)(agent.dreaming, gateway.gateway.dreaming, gateway.gateway.timezone).staleness;
189
200
  const sharedRetention = (0, knowledge_1.resolveSharedConfig)(agent.knowledge?.shared, gateway.gateway.knowledge?.shared).staleness;
190
201
  bridge.recordRetrievals = (personalRetention.enabled && personalRetention.recordRetrievals) || (sharedRetention.enabled && sharedRetention.recordRetrievals);
202
+ let admissionStore;
191
203
  try {
192
204
  (0, recovery_1.recoverOrchestration)(store);
193
205
  (0, session_compaction_1.recoverSessionCompaction)(store);
@@ -195,6 +207,8 @@ class AgentOrchestrationRuntime {
195
207
  // their global capacity conservatively as well as the per-agent slots.
196
208
  const recoveredReservations = new Map();
197
209
  for (const row of store.all("SELECT id FROM tasks WHERE state='needs_reconciliation' AND active_attempt_id IS NOT NULL")) {
210
+ if (store.task(String(row.id))?.gatewayTarget)
211
+ continue;
198
212
  recoveredReservations.set(String(row.id), (0, capacity_1.gatewayCapacity)(gateway).acquireWorker(agent.id, String(row.id), false));
199
213
  }
200
214
  if (agent.orchestration?.enabled)
@@ -209,11 +223,49 @@ class AgentOrchestrationRuntime {
209
223
  const workspaces = new workspace_1.TaskWorkspaces(store, project, (0, path_1.join)(root, 'task-worktrees'), agent.orchestration?.tasks?.workspaceMode);
210
224
  for (const row of store.all("SELECT id FROM tasks WHERE state IN ('completed','failed','cancelled')"))
211
225
  await workspaces.release(String(row.id));
212
- const driver = workerDriver ?? new driver_1.ClaudeWorkerDriver(agent, gateway, tasks, bridge, workspaces, (0, path_1.join)(root, 'task-attempts'), host.onManagedTurn);
213
- const scheduler = new scheduler_1.WorkerScheduler(tasks, driver, undefined, recoveredReservations);
226
+ const providerAdmission = admissionStore = new provider_admission_1.ProviderAdmissionStore((0, path_1.join)(sessions.getAgentsBaseDir(), 'provider-admission.db'));
227
+ const providerPolicy = () => runtime.config.providerAdmission;
228
+ const driver = workerDriver ?? new driver_1.ClaudeWorkerDriver(agent, gateway, tasks, bridge, workspaces, (0, path_1.join)(root, 'task-attempts'), host.onManagedTurn, (task, permit, harness, model, resolvedIdentity) => {
229
+ const actualAgent = { ...agent, workers: { ...agent.workers, harness } };
230
+ const scope = resolvedIdentity
231
+ ? (0, provider_scope_1.resolvedCodexProviderScope)(resolvedIdentity, providerPolicy().recoveryGeneration)
232
+ : (0, provider_scope_1.resolveProviderScope)(actualAgent, gateway, model, 'worker', task.resourceProfile?.projectRoot);
233
+ const configured = (0, provider_scope_1.resolveProviderScope)(agent, gateway, task.model, 'worker', task.resourceProfile?.projectRoot);
234
+ store.run('INSERT INTO provider_task_routes VALUES(?,?,?) ON CONFLICT(task_id) DO UPDATE SET configured_scope=excluded.configured_scope,actual_scope=excluded.actual_scope', task.taskId, configured, scope);
235
+ if (scope === permit.scope)
236
+ return;
237
+ providerAdmission.release(permit);
238
+ const next = providerAdmission.acquire(scope, providerPolicy());
239
+ if (next.waiting) {
240
+ runtime.waitForProvider(task.taskId, task.conversationId, scope, next.waiting);
241
+ throw new types_2.OrchestrationError('PROVIDER_WAITING');
242
+ }
243
+ delete permit.probe;
244
+ Object.assign(permit, next.permit);
245
+ });
246
+ const scheduler = new scheduler_1.WorkerScheduler(tasks, driver, undefined, recoveredReservations, {
247
+ acquire: task => {
248
+ const configured = (0, provider_scope_1.resolveProviderScope)(agent, gateway, task.model, 'worker', task.resourceProfile?.projectRoot);
249
+ const previous = store.get('SELECT configured_scope,actual_scope FROM provider_task_routes WHERE task_id=?', task.taskId);
250
+ const scope = previous?.configured_scope === configured ? String(previous.actual_scope) : configured;
251
+ const result = providerAdmission.acquire(scope, providerPolicy());
252
+ if (result.waiting)
253
+ runtime.waitForProvider(task.taskId, task.conversationId, scope, result.waiting);
254
+ else
255
+ store.run('DELETE FROM provider_waits WHERE entity_id=?', task.taskId);
256
+ return result;
257
+ },
258
+ renew: permit => providerAdmission.renew(permit, providerPolicy()),
259
+ settle: (permit, result) => {
260
+ if (providerAdmission.settle(permit, result, providerPolicy()))
261
+ runtime.providerRecovered(permit.scope);
262
+ },
263
+ release: permit => providerAdmission.release(permit),
264
+ });
214
265
  const cleanup = new cleanup_1.ResourceCleanup(store, (0, path_1.join)(root, 'task-worktrees'), (0, path_1.join)(root, 'task-artifacts'), (0, config_2.resolveOrchestrationConfig)(agent.orchestration).tasks.resourceRetentionDays);
215
266
  const runtime = new AgentOrchestrationRuntime(agent, root, host, store, new history_1.OrchestrationHistoryWriter(store, sessions, historyDb), scheduler, bridge, tasks);
216
267
  runtime.gateway = gateway;
268
+ runtime.providerAdmission = providerAdmission;
217
269
  runtime.releaseLock = releaseLock;
218
270
  runtime.settleResources = async () => { cleanup.stop(); await workspaces.settle(); await cleanup.settle(); };
219
271
  const shared = (0, knowledge_1.resolveSharedConfig)(agent.knowledge?.shared, gateway.gateway.knowledge?.shared);
@@ -222,6 +274,8 @@ class AgentOrchestrationRuntime {
222
274
  runtime.drain();
223
275
  await runtime.flushHistory();
224
276
  scheduler.start();
277
+ runtime.gatewayTasks = new controller_1.GatewayTaskController(tasks, gatewayAdapters);
278
+ runtime.gatewayTasks.start();
225
279
  runtime.mailboxTimer = setInterval(() => {
226
280
  try {
227
281
  runtime.pumpMailbox();
@@ -252,6 +306,7 @@ class AgentOrchestrationRuntime {
252
306
  return runtime;
253
307
  }
254
308
  catch (error) {
309
+ admissionStore?.close();
255
310
  await bridge.close();
256
311
  store.close();
257
312
  releaseLock();
@@ -267,14 +322,60 @@ class AgentOrchestrationRuntime {
267
322
  if (!Number.isSafeInteger(after) || after < 0 || after > Number(conversation.last_event_seq))
268
323
  throw new types_2.OrchestrationError('INVALID_CURSOR');
269
324
  const tasks = this.tasks.status(id, principalId).map(t => {
270
- return { taskId: t.taskId, title: t.title, state: t.state, stateVersion: t.stateVersion, progress: t.latestProgress, execution: t.execution, result: t.result?.summary, updatedAt: Math.max(t.updatedAt, t.execution?.lastActivityAt ?? 0) };
325
+ return { taskId: t.taskId, title: t.title, state: t.state, stateVersion: t.stateVersion, providerWaiting: t.providerWaiting, progress: t.latestProgress, execution: t.execution, result: t.result?.summary, updatedAt: Math.max(t.updatedAt, t.execution?.lastActivityAt ?? 0) };
271
326
  });
272
327
  const responses = this.store.all('SELECT id,request_id,state,generated_text,COALESCE(completed_at,created_at) AS message_at FROM assistant_responses WHERE conversation_id=? ORDER BY message_at DESC,rowid DESC LIMIT 100', id).reverse().map(r => ({
273
328
  id: r.id, requestId: r.request_id, state: r.state, text: r.generated_text, createdAt: r.message_at,
274
329
  files: this.store.all('SELECT path FROM task_files WHERE response_id=? ORDER BY created_at,id', r.id).map(f => f.path),
275
330
  }));
276
331
  const tools = this.store.all("SELECT seq,payload_json FROM conversation_events WHERE conversation_id=? AND seq>? AND type='tool.activity' ORDER BY seq LIMIT 500", id, after).map(r => ({ seq: r.seq, ...JSON.parse(String(r.payload_json)).payload }));
277
- return { cursor: tools.length === 500 ? tools[tools.length - 1].seq : Number(conversation.last_event_seq), tasks, responses, tools, busy: this.isBusy(sessionId) };
332
+ const waiting = this.store.get('SELECT waiting_json FROM provider_waits WHERE entity_id=?', `session:${sessionId}`);
333
+ return { cursor: tools.length === 500 ? tools[tools.length - 1].seq : Number(conversation.last_event_seq), tasks, responses, tools, busy: this.isBusy(sessionId), providerWaiting: waiting ? JSON.parse(String(waiting.waiting_json)) : undefined };
334
+ }
335
+ waitForProvider(entity, conversationId, scope, waiting) {
336
+ const previous = this.store.get('SELECT waiting_json FROM provider_waits WHERE entity_id=?', entity);
337
+ const data = JSON.stringify(waiting);
338
+ let text = '';
339
+ let changed = false;
340
+ this.store.compose(() => {
341
+ if (previous?.waiting_json !== data) {
342
+ changed = true;
343
+ this.store.run('INSERT INTO provider_waits VALUES(?,?,?,?,?) ON CONFLICT(entity_id) DO UPDATE SET scope=excluded.scope,waiting_json=excluded.waiting_json,updated_at=excluded.updated_at', entity, conversationId, scope, data, Date.now());
344
+ this.store.appendEvent(conversationId, 'provider.waiting', { entity, ...waiting });
345
+ }
346
+ const notice = this.store.get('SELECT episode FROM provider_notices WHERE conversation_id=? AND scope=?', conversationId, scope);
347
+ if (notice?.episode !== waiting.episode) {
348
+ text = waiting.requiresConfigurationChange
349
+ ? 'Waiting for provider. Check the provider credentials, model or quota. Your pending messages and task results are saved.'
350
+ : 'Waiting for provider. Your pending messages and task results are saved. I will retry automatically after the cooldown.';
351
+ const response = this.decisions.notice(conversationId, text, true);
352
+ this.store.run('INSERT INTO provider_notices VALUES(?,?,?,0) ON CONFLICT(conversation_id,scope) DO UPDATE SET episode=excluded.episode,recovered=0', conversationId, scope, waiting.episode);
353
+ const session = this.store.get('SELECT agent_session_id FROM conversations WHERE id=?', conversationId);
354
+ if (session)
355
+ this.publishText(String(session.agent_session_id), response, text, true);
356
+ }
357
+ });
358
+ if (changed || text) {
359
+ void this.flushHistory().catch(() => { });
360
+ void this.delivery.tick().catch(() => { });
361
+ }
362
+ return text;
363
+ }
364
+ providerRecovered(scope) {
365
+ this.store.compose(() => {
366
+ this.store.run('DELETE FROM provider_waits WHERE scope=?', scope);
367
+ for (const conversation of this.store.all(`SELECT n.conversation_id,c.agent_session_id FROM provider_notices n
368
+ JOIN conversations c ON c.id=n.conversation_id WHERE n.scope=? AND n.recovered=0 AND c.status='active'`, scope)) {
369
+ const conversationId = String(conversation.conversation_id), sessionId = String(conversation.agent_session_id);
370
+ this.store.run('UPDATE provider_notices SET recovered=1 WHERE conversation_id=? AND scope=?', conversationId, scope);
371
+ this.store.appendEvent(conversationId, 'provider.recovered', {});
372
+ const text = 'The provider is responding again. Pending messages and task reports can continue.';
373
+ const response = this.decisions.notice(conversationId, text, true);
374
+ this.publishText(sessionId, response, text, true);
375
+ }
376
+ });
377
+ void this.flushHistory().catch(() => { });
378
+ void this.delivery.tick().catch(() => { });
278
379
  }
279
380
  isBusy(sessionId) { return this.active.has(sessionId); }
280
381
  isCompacting(sessionId) { return this.active.get(sessionId)?.maintenance === 'compact'; }
@@ -330,6 +431,7 @@ class AgentOrchestrationRuntime {
330
431
  if (this.agent.type !== 'app-agent' && config?.tasks?.workspaceMode === 'container')
331
432
  throw new types_2.OrchestrationError('CONTAINER_REQUIRED');
332
433
  this.config = (0, config_2.resolveOrchestrationConfig)(config, backendAgent.voice ?? { enabled: false });
434
+ this.agent.orchestration = config;
333
435
  this.tasks.configure(config);
334
436
  if (!this.config.enabled)
335
437
  this.drain();
@@ -423,6 +525,18 @@ class AgentOrchestrationRuntime {
423
525
  void operation.finally(() => this.pending.delete(operation)).catch(() => { });
424
526
  return operation;
425
527
  }
528
+ /** Lightweight live ownership only: no transcript or token-ledger scans. */
529
+ processOwners() {
530
+ return this.store.all(`SELECT t.snapshot_json,a.payload_json FROM tasks t JOIN task_attempts a
531
+ ON a.id=t.active_attempt_id WHERE t.active_attempt_id IS NOT NULL`).flatMap(row => {
532
+ const task = JSON.parse(String(row.snapshot_json)), attempt = JSON.parse(String(row.payload_json));
533
+ const pid = attempt.processIdentity?.pid;
534
+ return Number.isInteger(pid) ? [{ pid, startTicks: attempt.processIdentity?.startTicks, group: 'worker', agentId: this.agent.id,
535
+ sessionId: task.agentSessionId, taskId: task.taskId, title: task.title,
536
+ harness: attempt.harness ?? 'claude', model: attempt.harnessModel ?? task.model,
537
+ container: this.agent.type === 'app-agent' ? this.agent.container : undefined }] : [];
538
+ });
539
+ }
426
540
  sessionContextWindow(sessionId) {
427
541
  if (!this.store.get("SELECT name FROM sqlite_master WHERE name='token_turns'"))
428
542
  return null;
@@ -447,8 +561,8 @@ class AgentOrchestrationRuntime {
447
561
  const tool = event ? JSON.parse(String(event.payload_json)).payload : undefined;
448
562
  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));
449
563
  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,
450
- execution: snapshot.execution, workerId: attempt?.workerId, workstreamId: snapshot.workstreamId, continueTaskId: snapshot.continueTaskId, resumed: attempt?.resumeSession,
451
- attemptId: attempt?.attemptId, workerSessionId: attempt?.sessionId, hostProcessId: row.active_attempt_id ? attempt?.processIdentity?.pid : undefined,
564
+ executionType: snapshot.gatewayTarget ? 'gateway-managed' : 'worker', gatewayTarget: snapshot.gatewayTarget, execution: snapshot.execution, workerId: attempt?.workerId, workstreamId: snapshot.workstreamId, continueTaskId: snapshot.continueTaskId, resumed: attempt?.resumeSession,
565
+ attemptId: attempt?.attemptId, workerSessionId: snapshot.gatewayTarget ? undefined : attempt?.sessionId, targetSessionId: snapshot.gatewayTarget?.sessionId, hostProcessId: row.active_attempt_id ? attempt?.processIdentity?.pid : undefined,
452
566
  container: this.agent.type === 'app-agent' ? this.agent.container : undefined,
453
567
  lastTool: tool ? { name: tool.name, type: tool.type, is_error: tool.is_error } : undefined };
454
568
  });
@@ -673,6 +787,7 @@ class AgentOrchestrationRuntime {
673
787
  }
674
788
  return receipt;
675
789
  });
790
+ void this.flushHistory().catch(() => { });
676
791
  if (this.config.conversation.semanticIntake)
677
792
  this.intake.touch(receipt.inputId);
678
793
  const previous = this.inputResponses.get(receipt.inputId);
@@ -719,6 +834,12 @@ class AgentOrchestrationRuntime {
719
834
  if (Date.now() >= this.nextQuestionCheck) {
720
835
  this.questionControls.tick();
721
836
  this.nextQuestionCheck = Date.now() + 1000;
837
+ // A sibling agent or a worker can recover the shared circuit without a
838
+ // conversation turn here. Deliver its notices through the same outbox.
839
+ for (const row of this.store.all('SELECT DISTINCT scope FROM provider_notices WHERE recovered=0 LIMIT 100')) {
840
+ if (this.providerAdmission.recovered(String(row.scope)))
841
+ this.providerRecovered(String(row.scope));
842
+ }
722
843
  }
723
844
  for (const conversation of this.questionControls.initialReviews([...this.active.keys()])) {
724
845
  this.store.compose(() => {
@@ -741,25 +862,46 @@ class AgentOrchestrationRuntime {
741
862
  ingressKey: `notification:${row.notification_id}${row.previous_input_id ? `:retry:${row.previous_seq}` : ''}`, capabilities: { execute: false, writeMemory: false } }, this.config.conversation.maxPendingInputs);
742
863
  }
743
864
  }
744
- for (const row of this.store.all("SELECT i.* FROM conversation_inputs i JOIN conversations c ON c.id=i.conversation_id WHERE i.status='accepted' AND c.agent_session_id NOT IN (SELECT value FROM json_each(?)) ORDER BY i.created_at,i.input_seq LIMIT 100", JSON.stringify([...this.active.keys()]))) {
745
- if (this.active.size >= this.config.conversation.maxActiveSessions)
865
+ let mailboxCursor = 0;
866
+ const visitedSessions = new Set();
867
+ mailbox: while (this.active.size < this.config.conversation.maxActiveSessions) {
868
+ const rows = this.store.all("SELECT i.*,i.rowid AS mailbox_row FROM conversation_inputs i JOIN conversations c ON c.id=i.conversation_id WHERE i.status='accepted' AND i.rowid>? AND c.agent_session_id NOT IN (SELECT value FROM json_each(?)) ORDER BY i.rowid LIMIT 100", mailboxCursor, JSON.stringify([...this.active.keys()]));
869
+ if (!rows.length)
746
870
  break;
747
- const input = JSON.parse(String(row.ingress_json));
748
- if (!input.scope || !input.capabilities || this.active.has(input.scope.agentSessionId))
749
- continue;
750
- // A persisted input retains the authenticated scope and model from ingress.
751
- // Recovery can repeat inference, but committed tool receipts remain fenced.
752
- const result = this.send({ ...input, acceptedInputId: String(row.id) }, input.capabilities, { timeoutMs: this.config.conversation.maxDecisionDurationMs, model: input.model, onTool: event => this.inputTools.get(String(row.id))?.(event), onText: text => {
753
- const responseId = this.responseIdForInput(String(row.id));
754
- if (input.modality !== 'live_voice' && responseId) {
755
- try {
756
- this.inputStreams.get(String(row.id))?.push({ responseId, text });
871
+ for (const row of rows) {
872
+ mailboxCursor = Number(row.mailbox_row);
873
+ if (this.active.size >= this.config.conversation.maxActiveSessions)
874
+ break;
875
+ const input = JSON.parse(String(row.ingress_json));
876
+ if (!input.scope || !input.capabilities || this.active.has(input.scope.agentSessionId))
877
+ continue;
878
+ if (visitedSessions.has(input.scope.agentSessionId))
879
+ continue;
880
+ visitedSessions.add(input.scope.agentSessionId);
881
+ const scope = (0, provider_scope_1.resolveProviderScope)(this.agent, this.gateway, input.model, 'agent');
882
+ const waiting = this.providerAdmission.inspect(scope, this.config.providerAdmission);
883
+ if (waiting) {
884
+ const text = this.waitForProvider(`session:${input.scope.agentSessionId}`, String(row.conversation_id), scope, waiting);
885
+ if (text)
886
+ this.deferred.get(String(row.id))?.resolve(text);
887
+ continue;
888
+ }
889
+ // A persisted input retains the authenticated scope and model from ingress.
890
+ // Recovery can repeat inference, but committed tool receipts remain fenced.
891
+ const result = this.send({ ...input, acceptedInputId: String(row.id) }, input.capabilities, { timeoutMs: this.config.conversation.maxDecisionDurationMs, model: input.model, onTool: event => this.inputTools.get(String(row.id))?.(event), onText: text => {
892
+ const responseId = this.responseIdForInput(String(row.id));
893
+ if (input.modality !== 'live_voice' && responseId) {
894
+ try {
895
+ this.inputStreams.get(String(row.id))?.push({ responseId, text });
896
+ }
897
+ catch { /* slow audio cannot stall inference */ }
757
898
  }
758
- catch { /* slow audio cannot stall inference */ }
759
- }
760
- } });
761
- void result.then(text => this.deferred.get(String(row.id))?.resolve(text), error => this.deferred.get(String(row.id))?.reject(error))
762
- .finally(() => this.deferred.delete(String(row.id)));
899
+ } });
900
+ void result.then(text => this.deferred.get(String(row.id))?.resolve(text), error => this.deferred.get(String(row.id))?.reject(error))
901
+ .finally(() => this.deferred.delete(String(row.id)));
902
+ }
903
+ if (this.active.size >= this.config.conversation.maxActiveSessions)
904
+ break mailbox;
763
905
  }
764
906
  }
765
907
  async run(input, capabilities, options) {
@@ -779,13 +921,29 @@ class AgentOrchestrationRuntime {
779
921
  const questionReview = Boolean(input.ingressKey?.startsWith('question-review:'));
780
922
  let internalReview = false;
781
923
  let streamedDisplay = '';
924
+ let providerPermit;
925
+ let providerRenewal;
782
926
  try {
783
927
  const receipt = this.store.acceptInput(input, this.config.conversation.maxPendingInputs);
928
+ await this.flushHistory();
784
929
  if (this.config.conversation.semanticIntake)
785
930
  this.intake.touch(receipt.inputId);
786
931
  const admitted = this.store.get('SELECT ingress_json,binding_id FROM conversation_inputs WHERE id=?', receipt.inputId);
787
932
  const admittedModel = admitted ? JSON.parse(String(admitted.ingress_json)).model : undefined;
788
- options = { ...options, model: options.model ?? admittedModel ?? input.model };
933
+ options = { ...options, model: options.model ?? admittedModel ?? input.model ?? this.agent.claude.model };
934
+ const providerScope = (0, provider_scope_1.resolveProviderScope)(this.agent, this.gateway, options.model, 'agent');
935
+ const provider = this.providerAdmission.acquire(providerScope, this.config.providerAdmission);
936
+ if (provider.waiting)
937
+ return this.waitForProvider(`session:${sessionId}`, receipt.conversationId, providerScope, provider.waiting);
938
+ providerPermit = provider.permit;
939
+ this.store.run('DELETE FROM provider_waits WHERE entity_id=?', `session:${sessionId}`);
940
+ if (providerPermit.probe) {
941
+ providerRenewal = setInterval(() => { try {
942
+ this.providerAdmission.renew(providerPermit, this.config.providerAdmission);
943
+ }
944
+ catch { /* durable lease expires conservatively */ } }, Math.max(250, Math.floor(this.config.providerAdmission.probeLeaseMs / 3)));
945
+ providerRenewal.unref();
946
+ }
789
947
  if (this.draining)
790
948
  this.store.run("UPDATE conversations SET status='draining' WHERE id=?", receipt.conversationId);
791
949
  this.seenSessions.add(sessionId);
@@ -1106,7 +1264,7 @@ class AgentOrchestrationRuntime {
1106
1264
  // produced, while speech and review turns fill the optional fields their per-turn overlay
1107
1265
  // asks for. This restores the structured-output guarantee without a per-turn tools diff.
1108
1266
  ticket.profile.responseSchema = response_schema_1.ORCHESTRATION_RESPONSE_SCHEMA;
1109
- ticket.profile.overlay += `\n\n${CONTEXT_DELIVERY_INSTRUCTIONS}\n\nOnly when the current turn explicitly enables semantic intake, apply these rules:\n${conversation_intake_1.INTAKE_OVERLAY}`;
1267
+ 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}`;
1110
1268
  // Continue the CLI session this agent session already has a transcript for. Each decision
1111
1269
  // turn is still its own process; resuming is what lets the next one reuse the previous
1112
1270
  // turn's cached prefix instead of paying a full cache write, and it replaces the flattened
@@ -1129,6 +1287,7 @@ class AgentOrchestrationRuntime {
1129
1287
  ticket.profile.excludedHistoryOperationIds = this.store.all(`SELECT r.id FROM assistant_responses r
1130
1288
  JOIN conversation_decisions d ON d.id=r.decision_id WHERE d.session_id=? AND r.state='failed'`, sessionId)
1131
1289
  .map(row => `response:${row.id}`);
1290
+ ticket.profile.responseId = decision.responseId;
1132
1291
  agentSession = await this.host.createAgentSession(sessionId, ticket.profile, options.model, input.scope);
1133
1292
  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)));
1134
1293
  const taskCandidates = this.tasks.context(receipt.conversationId, input.scope.principalId, decision.decisionId)
@@ -1210,7 +1369,23 @@ class AgentOrchestrationRuntime {
1210
1369
  displayChunk(chunk);
1211
1370
  });
1212
1371
  active.turn = turn;
1372
+ let providerResponded = false;
1373
+ void turn.providerReady.then(() => {
1374
+ providerResponded = true;
1375
+ try {
1376
+ if (!active.stopping && this.providerAdmission.settle(providerPermit, 'success', this.config.providerAdmission))
1377
+ this.providerRecovered(providerPermit.scope);
1378
+ }
1379
+ catch { /* Never turn a successful inference into a failed task receipt. */ }
1380
+ }).catch(() => { });
1213
1381
  const response = await turn.result;
1382
+ if (!response.interrupted && !providerResponded) {
1383
+ try {
1384
+ if (this.providerAdmission.settle(providerPermit, 'success', this.config.providerAdmission))
1385
+ this.providerRecovered(providerPermit.scope);
1386
+ }
1387
+ catch { /* Provider bookkeeping cannot invalidate a completed inference. */ }
1388
+ }
1214
1389
  if (!response.interrupted) {
1215
1390
  // A completed CLI turn has consumed its tool results. Failed/interrupted
1216
1391
  // turns never advance this checkpoint, so committed receipts can recover.
@@ -1284,6 +1459,13 @@ class AgentOrchestrationRuntime {
1284
1459
  ? (speechEnabled || active.stopReason === 'barge-in' || parsed.outcome !== 'structured' ? stoppedDisplay : surfaces.display || 'Response stopped.')
1285
1460
  : surfaces.display || '';
1286
1461
  this.decisions.finish(decision, display, response.interrupted ? 'interrupted' : 'completed', channelSpeech && !silent ? taskSpeech || surfaces.spoken : undefined, !active.stopping && !silent);
1462
+ if (active.notification && !response.interrupted) {
1463
+ const batch = this.store.get('SELECT COUNT(*)-COUNT(DISTINCT task_id) n FROM notifications WHERE decision_id=?', decision.decisionId);
1464
+ try {
1465
+ this.providerAdmission.coalesced(Number(batch?.n ?? 0));
1466
+ }
1467
+ catch { /* telemetry cannot invalidate a report */ }
1468
+ }
1287
1469
  if (!silent && speechEnabled && !response.interrupted && !taskSpeech) {
1288
1470
  if (!channelSpeech)
1289
1471
  this.store.run('INSERT INTO response_speech VALUES(?,?)', decision.responseId, surfaces.spoken);
@@ -1328,6 +1510,15 @@ class AgentOrchestrationRuntime {
1328
1510
  return silent ? acknowledgement : display || acknowledgement;
1329
1511
  }
1330
1512
  catch (error) {
1513
+ if (providerPermit && active.turn && !active.stopping) {
1514
+ const failure = (0, provider_admission_1.providerFailure)(error);
1515
+ if (failure) {
1516
+ try {
1517
+ this.providerAdmission.settle(providerPermit, failure, this.config.providerAdmission);
1518
+ }
1519
+ catch { /* Preserve original error and cleanup even when shared storage is busy. */ }
1520
+ }
1521
+ }
1331
1522
  // Retain a safe diagnostic code; never log prompts, credentials or provider bodies.
1332
1523
  failedTurn = true;
1333
1524
  const failure = error;
@@ -1381,6 +1572,14 @@ class AgentOrchestrationRuntime {
1381
1572
  throw error;
1382
1573
  }
1383
1574
  finally {
1575
+ if (providerRenewal)
1576
+ clearInterval(providerRenewal);
1577
+ if (providerPermit) {
1578
+ try {
1579
+ this.providerAdmission.release(providerPermit);
1580
+ }
1581
+ catch { /* lease expires; process cleanup must still run */ }
1582
+ }
1384
1583
  removeContextObserver?.();
1385
1584
  revoke?.();
1386
1585
  if (agentSession)
@@ -1396,7 +1595,23 @@ class AgentOrchestrationRuntime {
1396
1595
  }
1397
1596
  stopResponse(sessionId, reason = 'user') {
1398
1597
  const active = this.active.get(sessionId);
1399
- if (!active || active.stopping)
1598
+ if (!active) {
1599
+ if (reason !== 'user' || !this.store.get('SELECT entity_id FROM provider_waits WHERE entity_id=?', `session:${sessionId}`))
1600
+ return false;
1601
+ let stopped = false;
1602
+ for (const row of this.store.all("SELECT i.* FROM conversation_inputs i JOIN conversations c ON c.id=i.conversation_id WHERE c.agent_session_id=? AND i.status='accepted' ORDER BY i.input_seq", sessionId)) {
1603
+ const decision = this.decisions.begin(String(row.conversation_id), String(row.principal_id), [String(row.id)], row.request_id ? String(row.request_id) : undefined);
1604
+ this.decisions.interrupt(decision);
1605
+ this.decisions.finish(decision, '', 'interrupted', undefined, false);
1606
+ this.deferred.get(String(row.id))?.resolve('Response stopped.');
1607
+ this.deferred.delete(String(row.id));
1608
+ stopped = true;
1609
+ }
1610
+ this.store.run('DELETE FROM provider_waits WHERE entity_id=?', `session:${sessionId}`);
1611
+ void this.flushHistory().catch(() => { });
1612
+ return stopped;
1613
+ }
1614
+ if (active.stopping)
1400
1615
  return false;
1401
1616
  active.stopping = true;
1402
1617
  active.stopReason = reason;
@@ -1410,6 +1625,9 @@ class AgentOrchestrationRuntime {
1410
1625
  for (const row of this.store.all("SELECT operation_id FROM history_operations WHERE state='pending' ORDER BY updated_at LIMIT 200"))
1411
1626
  await this.history.write(String(row.operation_id));
1412
1627
  }
1628
+ hasPendingWork() {
1629
+ 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"));
1630
+ }
1413
1631
  drain() {
1414
1632
  this.draining = true;
1415
1633
  this.store.run("UPDATE conversations SET status='draining' WHERE status='active'");
@@ -1437,6 +1655,7 @@ class AgentOrchestrationRuntime {
1437
1655
  this.drain();
1438
1656
  for (const sessionId of this.active.keys())
1439
1657
  this.stopResponse(sessionId);
1658
+ await this.gatewayTasks?.close();
1440
1659
  await this.scheduler.close();
1441
1660
  await this.settleResources();
1442
1661
  await Promise.allSettled([...this.pending]);
@@ -1445,6 +1664,7 @@ class AgentOrchestrationRuntime {
1445
1664
  // Caller waits for pending conversational responses before releasing store.
1446
1665
  if (this.active.size)
1447
1666
  throw new types_2.OrchestrationError('ACTIVE_DECISIONS_DURING_SHUTDOWN');
1667
+ this.providerAdmission.close();
1448
1668
  this.store.close();
1449
1669
  this.releaseLock();
1450
1670
  }