openryoko 2026.10.8 → 2026.10.13

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 (691) hide show
  1. package/dist/bin/jimmy.js +51 -1
  2. package/dist/bin/jimmy.js.map +1 -1
  3. package/dist/package.json +2 -1
  4. package/dist/src/backup/archive.d.ts +65 -0
  5. package/dist/src/backup/archive.d.ts.map +1 -0
  6. package/dist/src/backup/archive.js +214 -0
  7. package/dist/src/backup/archive.js.map +1 -0
  8. package/dist/src/backup/catalog.d.ts +64 -0
  9. package/dist/src/backup/catalog.d.ts.map +1 -0
  10. package/dist/src/backup/catalog.js +252 -0
  11. package/dist/src/backup/catalog.js.map +1 -0
  12. package/dist/src/backup/database-restore.d.ts +63 -0
  13. package/dist/src/backup/database-restore.d.ts.map +1 -0
  14. package/dist/src/backup/database-restore.js +236 -0
  15. package/dist/src/backup/database-restore.js.map +1 -0
  16. package/dist/src/backup/database-source.d.ts +70 -0
  17. package/dist/src/backup/database-source.d.ts.map +1 -0
  18. package/dist/src/backup/database-source.js +70 -0
  19. package/dist/src/backup/database-source.js.map +1 -0
  20. package/dist/src/backup/format.d.ts +4 -0
  21. package/dist/src/backup/format.d.ts.map +1 -0
  22. package/dist/src/backup/format.js +15 -0
  23. package/dist/src/backup/format.js.map +1 -0
  24. package/dist/src/backup/gateway-liveness.d.ts +44 -0
  25. package/dist/src/backup/gateway-liveness.d.ts.map +1 -0
  26. package/dist/src/backup/gateway-liveness.js +120 -0
  27. package/dist/src/backup/gateway-liveness.js.map +1 -0
  28. package/dist/src/backup/inspect.d.ts +45 -0
  29. package/dist/src/backup/inspect.d.ts.map +1 -0
  30. package/dist/src/backup/inspect.js +291 -0
  31. package/dist/src/backup/inspect.js.map +1 -0
  32. package/dist/src/backup/layout.d.ts +11 -0
  33. package/dist/src/backup/layout.d.ts.map +1 -0
  34. package/dist/src/backup/layout.js +16 -0
  35. package/dist/src/backup/layout.js.map +1 -0
  36. package/dist/src/backup/limits.d.ts +54 -0
  37. package/dist/src/backup/limits.d.ts.map +1 -0
  38. package/dist/src/backup/limits.js +59 -0
  39. package/dist/src/backup/limits.js.map +1 -0
  40. package/dist/src/backup/manifest.d.ts +45 -0
  41. package/dist/src/backup/manifest.d.ts.map +1 -0
  42. package/dist/src/backup/manifest.js +77 -0
  43. package/dist/src/backup/manifest.js.map +1 -0
  44. package/dist/src/backup/restore.d.ts +73 -0
  45. package/dist/src/backup/restore.d.ts.map +1 -0
  46. package/dist/src/backup/restore.js +685 -0
  47. package/dist/src/backup/restore.js.map +1 -0
  48. package/dist/src/backup/run.d.ts +76 -0
  49. package/dist/src/backup/run.d.ts.map +1 -0
  50. package/dist/src/backup/run.js +181 -0
  51. package/dist/src/backup/run.js.map +1 -0
  52. package/dist/src/backup/scheduler.d.ts +51 -0
  53. package/dist/src/backup/scheduler.d.ts.map +1 -0
  54. package/dist/src/backup/scheduler.js +198 -0
  55. package/dist/src/backup/scheduler.js.map +1 -0
  56. package/dist/src/backup/settings.d.ts +44 -0
  57. package/dist/src/backup/settings.d.ts.map +1 -0
  58. package/dist/src/backup/settings.js +91 -0
  59. package/dist/src/backup/settings.js.map +1 -0
  60. package/dist/src/backup/space.d.ts +22 -0
  61. package/dist/src/backup/space.d.ts.map +1 -0
  62. package/dist/src/backup/space.js +47 -0
  63. package/dist/src/backup/space.js.map +1 -0
  64. package/dist/src/backup/state.d.ts +46 -0
  65. package/dist/src/backup/state.d.ts.map +1 -0
  66. package/dist/src/backup/state.js +137 -0
  67. package/dist/src/backup/state.js.map +1 -0
  68. package/dist/src/backup/tar.d.ts +64 -0
  69. package/dist/src/backup/tar.d.ts.map +1 -0
  70. package/dist/src/backup/tar.js +274 -0
  71. package/dist/src/backup/tar.js.map +1 -0
  72. package/dist/src/backup/targets.d.ts +85 -0
  73. package/dist/src/backup/targets.d.ts.map +1 -0
  74. package/dist/src/backup/targets.js +104 -0
  75. package/dist/src/backup/targets.js.map +1 -0
  76. package/dist/src/backup/walk.d.ts +42 -0
  77. package/dist/src/backup/walk.d.ts.map +1 -0
  78. package/dist/src/backup/walk.js +324 -0
  79. package/dist/src/backup/walk.js.map +1 -0
  80. package/dist/src/cli/backup.d.ts +45 -0
  81. package/dist/src/cli/backup.d.ts.map +1 -0
  82. package/dist/src/cli/backup.js +344 -0
  83. package/dist/src/cli/backup.js.map +1 -0
  84. package/dist/src/cli/bundled-skills.d.ts +7 -1
  85. package/dist/src/cli/bundled-skills.d.ts.map +1 -1
  86. package/dist/src/cli/bundled-skills.js +12 -2
  87. package/dist/src/cli/bundled-skills.js.map +1 -1
  88. package/dist/src/cli/config-failure.d.ts +18 -0
  89. package/dist/src/cli/config-failure.d.ts.map +1 -0
  90. package/dist/src/cli/config-failure.js +39 -0
  91. package/dist/src/cli/config-failure.js.map +1 -0
  92. package/dist/src/cli/gateway-audit.d.ts +3 -0
  93. package/dist/src/cli/gateway-audit.d.ts.map +1 -1
  94. package/dist/src/cli/gateway-audit.js +61 -14
  95. package/dist/src/cli/gateway-audit.js.map +1 -1
  96. package/dist/src/cli/gateway-url-backup.d.ts +21 -0
  97. package/dist/src/cli/gateway-url-backup.d.ts.map +1 -0
  98. package/dist/src/cli/gateway-url-backup.js +87 -0
  99. package/dist/src/cli/gateway-url-backup.js.map +1 -0
  100. package/dist/src/cli/home-copy.d.ts +37 -0
  101. package/dist/src/cli/home-copy.d.ts.map +1 -0
  102. package/dist/src/cli/home-copy.js +155 -0
  103. package/dist/src/cli/home-copy.js.map +1 -0
  104. package/dist/src/cli/interactive-config.d.ts +5 -0
  105. package/dist/src/cli/interactive-config.d.ts.map +1 -1
  106. package/dist/src/cli/interactive-config.js +16 -7
  107. package/dist/src/cli/interactive-config.js.map +1 -1
  108. package/dist/src/cli/migrate.d.ts +20 -0
  109. package/dist/src/cli/migrate.d.ts.map +1 -1
  110. package/dist/src/cli/migrate.js +365 -68
  111. package/dist/src/cli/migrate.js.map +1 -1
  112. package/dist/src/cli/migration-declarations.d.ts +24 -0
  113. package/dist/src/cli/migration-declarations.d.ts.map +1 -0
  114. package/dist/src/cli/migration-declarations.js +54 -0
  115. package/dist/src/cli/migration-declarations.js.map +1 -0
  116. package/dist/src/cli/start.d.ts.map +1 -1
  117. package/dist/src/cli/start.js +40 -1
  118. package/dist/src/cli/start.js.map +1 -1
  119. package/dist/src/connectors/chunked-send.d.ts +27 -0
  120. package/dist/src/connectors/chunked-send.d.ts.map +1 -0
  121. package/dist/src/connectors/chunked-send.js +40 -0
  122. package/dist/src/connectors/chunked-send.js.map +1 -0
  123. package/dist/src/connectors/cron/index.d.ts +10 -0
  124. package/dist/src/connectors/cron/index.d.ts.map +1 -1
  125. package/dist/src/connectors/cron/index.js +26 -3
  126. package/dist/src/connectors/cron/index.js.map +1 -1
  127. package/dist/src/connectors/discord/attachments.d.ts +25 -0
  128. package/dist/src/connectors/discord/attachments.d.ts.map +1 -0
  129. package/dist/src/connectors/discord/attachments.js +33 -0
  130. package/dist/src/connectors/discord/attachments.js.map +1 -0
  131. package/dist/src/connectors/discord/format.d.ts +17 -1
  132. package/dist/src/connectors/discord/format.d.ts.map +1 -1
  133. package/dist/src/connectors/discord/format.js +36 -6
  134. package/dist/src/connectors/discord/format.js.map +1 -1
  135. package/dist/src/connectors/discord/index.d.ts +12 -0
  136. package/dist/src/connectors/discord/index.d.ts.map +1 -1
  137. package/dist/src/connectors/discord/index.js +47 -40
  138. package/dist/src/connectors/discord/index.js.map +1 -1
  139. package/dist/src/connectors/discord/remote.d.ts +45 -1
  140. package/dist/src/connectors/discord/remote.d.ts.map +1 -1
  141. package/dist/src/connectors/discord/remote.js +147 -22
  142. package/dist/src/connectors/discord/remote.js.map +1 -1
  143. package/dist/src/connectors/slack/attachments.d.ts +25 -0
  144. package/dist/src/connectors/slack/attachments.d.ts.map +1 -0
  145. package/dist/src/connectors/slack/attachments.js +32 -0
  146. package/dist/src/connectors/slack/attachments.js.map +1 -0
  147. package/dist/src/connectors/slack/auth-test-cache.d.ts +22 -0
  148. package/dist/src/connectors/slack/auth-test-cache.d.ts.map +1 -0
  149. package/dist/src/connectors/slack/auth-test-cache.js +34 -0
  150. package/dist/src/connectors/slack/auth-test-cache.js.map +1 -0
  151. package/dist/src/connectors/slack/format.d.ts +6 -1
  152. package/dist/src/connectors/slack/format.d.ts.map +1 -1
  153. package/dist/src/connectors/slack/format.js +65 -13
  154. package/dist/src/connectors/slack/format.js.map +1 -1
  155. package/dist/src/connectors/slack/index.d.ts +4 -0
  156. package/dist/src/connectors/slack/index.d.ts.map +1 -1
  157. package/dist/src/connectors/slack/index.js +64 -52
  158. package/dist/src/connectors/slack/index.js.map +1 -1
  159. package/dist/src/connectors/slack/provider-auth-blocks.d.ts +62 -0
  160. package/dist/src/connectors/slack/provider-auth-blocks.d.ts.map +1 -0
  161. package/dist/src/connectors/slack/provider-auth-blocks.js +204 -0
  162. package/dist/src/connectors/slack/provider-auth-blocks.js.map +1 -0
  163. package/dist/src/connectors/slack/provider-auth.d.ts +126 -0
  164. package/dist/src/connectors/slack/provider-auth.d.ts.map +1 -0
  165. package/dist/src/connectors/slack/provider-auth.js +357 -0
  166. package/dist/src/connectors/slack/provider-auth.js.map +1 -0
  167. package/dist/src/connectors/telegram/index.d.ts +5 -0
  168. package/dist/src/connectors/telegram/index.d.ts.map +1 -1
  169. package/dist/src/connectors/telegram/index.js +14 -22
  170. package/dist/src/connectors/telegram/index.js.map +1 -1
  171. package/dist/src/connectors/whatsapp/index.d.ts +3 -0
  172. package/dist/src/connectors/whatsapp/index.d.ts.map +1 -1
  173. package/dist/src/connectors/whatsapp/index.js +33 -14
  174. package/dist/src/connectors/whatsapp/index.js.map +1 -1
  175. package/dist/src/cron/alert-throttle.d.ts +28 -0
  176. package/dist/src/cron/alert-throttle.d.ts.map +1 -0
  177. package/dist/src/cron/alert-throttle.js +106 -0
  178. package/dist/src/cron/alert-throttle.js.map +1 -0
  179. package/dist/src/cron/jobs.d.ts +8 -0
  180. package/dist/src/cron/jobs.d.ts.map +1 -1
  181. package/dist/src/cron/jobs.js +27 -1
  182. package/dist/src/cron/jobs.js.map +1 -1
  183. package/dist/src/cron/run-outcome.d.ts +28 -0
  184. package/dist/src/cron/run-outcome.d.ts.map +1 -0
  185. package/dist/src/cron/run-outcome.js +66 -0
  186. package/dist/src/cron/run-outcome.js.map +1 -0
  187. package/dist/src/cron/runner.d.ts.map +1 -1
  188. package/dist/src/cron/runner.js +68 -5
  189. package/dist/src/cron/runner.js.map +1 -1
  190. package/dist/src/cron/scheduler.d.ts +8 -1
  191. package/dist/src/cron/scheduler.d.ts.map +1 -1
  192. package/dist/src/cron/scheduler.js +11 -4
  193. package/dist/src/cron/scheduler.js.map +1 -1
  194. package/dist/src/cron/waiting-fires.d.ts +18 -0
  195. package/dist/src/cron/waiting-fires.d.ts.map +1 -0
  196. package/dist/src/cron/waiting-fires.js +49 -0
  197. package/dist/src/cron/waiting-fires.js.map +1 -0
  198. package/dist/src/engines/claude-interactive.d.ts +19 -3
  199. package/dist/src/engines/claude-interactive.d.ts.map +1 -1
  200. package/dist/src/engines/claude-interactive.js +42 -17
  201. package/dist/src/engines/claude-interactive.js.map +1 -1
  202. package/dist/src/engines/claude.d.ts.map +1 -1
  203. package/dist/src/engines/claude.js +38 -5
  204. package/dist/src/engines/claude.js.map +1 -1
  205. package/dist/src/engines/codex.d.ts.map +1 -1
  206. package/dist/src/engines/codex.js +1 -0
  207. package/dist/src/engines/codex.js.map +1 -1
  208. package/dist/src/engines/gemini.d.ts.map +1 -1
  209. package/dist/src/engines/gemini.js +1 -0
  210. package/dist/src/engines/gemini.js.map +1 -1
  211. package/dist/src/gateway/api.d.ts.map +1 -1
  212. package/dist/src/gateway/api.js +184 -160
  213. package/dist/src/gateway/api.js.map +1 -1
  214. package/dist/src/gateway/config-redaction.d.ts +32 -0
  215. package/dist/src/gateway/config-redaction.d.ts.map +1 -0
  216. package/dist/src/gateway/config-redaction.js +139 -0
  217. package/dist/src/gateway/config-redaction.js.map +1 -0
  218. package/dist/src/gateway/config-revision.d.ts +46 -0
  219. package/dist/src/gateway/config-revision.d.ts.map +1 -0
  220. package/dist/src/gateway/config-revision.js +63 -0
  221. package/dist/src/gateway/config-revision.js.map +1 -0
  222. package/dist/src/gateway/connector-config.d.ts +21 -0
  223. package/dist/src/gateway/connector-config.d.ts.map +1 -0
  224. package/dist/src/gateway/connector-config.js +24 -0
  225. package/dist/src/gateway/connector-config.js.map +1 -0
  226. package/dist/src/gateway/daemon-entry.js +5 -0
  227. package/dist/src/gateway/daemon-entry.js.map +1 -1
  228. package/dist/src/gateway/engine-health-monitor.d.ts +67 -0
  229. package/dist/src/gateway/engine-health-monitor.d.ts.map +1 -0
  230. package/dist/src/gateway/engine-health-monitor.js +221 -0
  231. package/dist/src/gateway/engine-health-monitor.js.map +1 -0
  232. package/dist/src/gateway/files.d.ts +7 -1
  233. package/dist/src/gateway/files.d.ts.map +1 -1
  234. package/dist/src/gateway/files.js +110 -217
  235. package/dist/src/gateway/files.js.map +1 -1
  236. package/dist/src/gateway/onboarding-personalize.d.ts +2 -0
  237. package/dist/src/gateway/onboarding-personalize.d.ts.map +1 -1
  238. package/dist/src/gateway/onboarding-personalize.js +17 -1
  239. package/dist/src/gateway/onboarding-personalize.js.map +1 -1
  240. package/dist/src/gateway/portal-config.d.ts +17 -3
  241. package/dist/src/gateway/portal-config.d.ts.map +1 -1
  242. package/dist/src/gateway/portal-config.js +52 -3
  243. package/dist/src/gateway/portal-config.js.map +1 -1
  244. package/dist/src/gateway/request-origin.d.ts +9 -0
  245. package/dist/src/gateway/request-origin.d.ts.map +1 -1
  246. package/dist/src/gateway/request-origin.js +10 -0
  247. package/dist/src/gateway/request-origin.js.map +1 -1
  248. package/dist/src/gateway/server.d.ts.map +1 -1
  249. package/dist/src/gateway/server.js +82 -59
  250. package/dist/src/gateway/server.js.map +1 -1
  251. package/dist/src/gateway/slack-connect-rollback.d.ts +23 -0
  252. package/dist/src/gateway/slack-connect-rollback.d.ts.map +1 -0
  253. package/dist/src/gateway/slack-connect-rollback.js +53 -0
  254. package/dist/src/gateway/slack-connect-rollback.js.map +1 -0
  255. package/dist/src/gateway/status-reconciler.d.ts +25 -7
  256. package/dist/src/gateway/status-reconciler.d.ts.map +1 -1
  257. package/dist/src/gateway/status-reconciler.js +86 -43
  258. package/dist/src/gateway/status-reconciler.js.map +1 -1
  259. package/dist/src/gateway/watcher.d.ts.map +1 -1
  260. package/dist/src/gateway/watcher.js +44 -3
  261. package/dist/src/gateway/watcher.js.map +1 -1
  262. package/dist/src/mcp/gateway-server.js +21 -3
  263. package/dist/src/mcp/gateway-server.js.map +1 -1
  264. package/dist/src/mcp/resolver.d.ts.map +1 -1
  265. package/dist/src/mcp/resolver.js +51 -1
  266. package/dist/src/mcp/resolver.js.map +1 -1
  267. package/dist/src/models/service.d.ts.map +1 -1
  268. package/dist/src/models/service.js +14 -8
  269. package/dist/src/models/service.js.map +1 -1
  270. package/dist/src/provider-auth/discovery.d.ts +16 -0
  271. package/dist/src/provider-auth/discovery.d.ts.map +1 -0
  272. package/dist/src/provider-auth/discovery.js +66 -0
  273. package/dist/src/provider-auth/discovery.js.map +1 -0
  274. package/dist/src/provider-auth/failure-notices.d.ts +29 -0
  275. package/dist/src/provider-auth/failure-notices.d.ts.map +1 -0
  276. package/dist/src/provider-auth/failure-notices.js +48 -0
  277. package/dist/src/provider-auth/failure-notices.js.map +1 -0
  278. package/dist/src/provider-auth/failure-signal.d.ts +22 -0
  279. package/dist/src/provider-auth/failure-signal.d.ts.map +1 -0
  280. package/dist/src/provider-auth/failure-signal.js +79 -0
  281. package/dist/src/provider-auth/failure-signal.js.map +1 -0
  282. package/dist/src/provider-auth/index.d.ts +26 -0
  283. package/dist/src/provider-auth/index.d.ts.map +1 -0
  284. package/dist/src/provider-auth/index.js +51 -0
  285. package/dist/src/provider-auth/index.js.map +1 -0
  286. package/dist/src/provider-auth/input.d.ts +44 -0
  287. package/dist/src/provider-auth/input.d.ts.map +1 -0
  288. package/dist/src/provider-auth/input.js +86 -0
  289. package/dist/src/provider-auth/input.js.map +1 -0
  290. package/dist/src/provider-auth/providers.d.ts +26 -0
  291. package/dist/src/provider-auth/providers.d.ts.map +1 -0
  292. package/dist/src/provider-auth/providers.js +86 -0
  293. package/dist/src/provider-auth/providers.js.map +1 -0
  294. package/dist/src/provider-auth/runtime.d.ts +21 -0
  295. package/dist/src/provider-auth/runtime.d.ts.map +1 -0
  296. package/dist/src/provider-auth/runtime.js +104 -0
  297. package/dist/src/provider-auth/runtime.js.map +1 -0
  298. package/dist/src/provider-auth/service.d.ts +70 -0
  299. package/dist/src/provider-auth/service.d.ts.map +1 -0
  300. package/dist/src/provider-auth/service.js +349 -0
  301. package/dist/src/provider-auth/service.js.map +1 -0
  302. package/dist/src/provider-auth/terminal.d.ts +21 -0
  303. package/dist/src/provider-auth/terminal.d.ts.map +1 -0
  304. package/dist/src/provider-auth/terminal.js +46 -0
  305. package/dist/src/provider-auth/terminal.js.map +1 -0
  306. package/dist/src/provider-auth/types.d.ts +123 -0
  307. package/dist/src/provider-auth/types.d.ts.map +1 -0
  308. package/dist/src/provider-auth/types.js +10 -0
  309. package/dist/src/provider-auth/types.js.map +1 -0
  310. package/dist/src/sessions/accounting.d.ts +3 -0
  311. package/dist/src/sessions/accounting.d.ts.map +1 -1
  312. package/dist/src/sessions/accounting.js +5 -0
  313. package/dist/src/sessions/accounting.js.map +1 -1
  314. package/dist/src/sessions/backup-integrity.d.ts +45 -0
  315. package/dist/src/sessions/backup-integrity.d.ts.map +1 -0
  316. package/dist/src/sessions/backup-integrity.js +122 -0
  317. package/dist/src/sessions/backup-integrity.js.map +1 -0
  318. package/dist/src/sessions/backup.d.ts +40 -2
  319. package/dist/src/sessions/backup.d.ts.map +1 -1
  320. package/dist/src/sessions/backup.js +88 -12
  321. package/dist/src/sessions/backup.js.map +1 -1
  322. package/dist/src/sessions/callbacks.d.ts +9 -0
  323. package/dist/src/sessions/callbacks.d.ts.map +1 -1
  324. package/dist/src/sessions/callbacks.js +55 -10
  325. package/dist/src/sessions/callbacks.js.map +1 -1
  326. package/dist/src/sessions/completion-batching.d.ts +82 -0
  327. package/dist/src/sessions/completion-batching.d.ts.map +1 -0
  328. package/dist/src/sessions/completion-batching.js +126 -0
  329. package/dist/src/sessions/completion-batching.js.map +1 -0
  330. package/dist/src/sessions/connector-command-guard.d.ts +66 -0
  331. package/dist/src/sessions/connector-command-guard.d.ts.map +1 -0
  332. package/dist/src/sessions/connector-command-guard.js +145 -0
  333. package/dist/src/sessions/connector-command-guard.js.map +1 -0
  334. package/dist/src/sessions/context.d.ts.map +1 -1
  335. package/dist/src/sessions/context.js +3 -4
  336. package/dist/src/sessions/context.js.map +1 -1
  337. package/dist/src/sessions/engine-fallback.d.ts +43 -1
  338. package/dist/src/sessions/engine-fallback.d.ts.map +1 -1
  339. package/dist/src/sessions/engine-fallback.js +266 -15
  340. package/dist/src/sessions/engine-fallback.js.map +1 -1
  341. package/dist/src/sessions/engine-health-gate.d.ts +83 -0
  342. package/dist/src/sessions/engine-health-gate.d.ts.map +1 -0
  343. package/dist/src/sessions/engine-health-gate.js +186 -0
  344. package/dist/src/sessions/engine-health-gate.js.map +1 -0
  345. package/dist/src/sessions/engine-login.d.ts +58 -0
  346. package/dist/src/sessions/engine-login.d.ts.map +1 -0
  347. package/dist/src/sessions/engine-login.js +107 -0
  348. package/dist/src/sessions/engine-login.js.map +1 -0
  349. package/dist/src/sessions/fork.d.ts.map +1 -1
  350. package/dist/src/sessions/fork.js +3 -1
  351. package/dist/src/sessions/fork.js.map +1 -1
  352. package/dist/src/sessions/goal-execution.d.ts.map +1 -1
  353. package/dist/src/sessions/goal-execution.js +8 -1
  354. package/dist/src/sessions/goal-execution.js.map +1 -1
  355. package/dist/src/sessions/limit-failure-notice.d.ts +41 -0
  356. package/dist/src/sessions/limit-failure-notice.d.ts.map +1 -0
  357. package/dist/src/sessions/limit-failure-notice.js +87 -0
  358. package/dist/src/sessions/limit-failure-notice.js.map +1 -0
  359. package/dist/src/sessions/lost-turn.d.ts +39 -0
  360. package/dist/src/sessions/lost-turn.d.ts.map +1 -0
  361. package/dist/src/sessions/lost-turn.js +32 -0
  362. package/dist/src/sessions/lost-turn.js.map +1 -0
  363. package/dist/src/sessions/manager.d.ts.map +1 -1
  364. package/dist/src/sessions/manager.js +104 -47
  365. package/dist/src/sessions/manager.js.map +1 -1
  366. package/dist/src/sessions/new-session-engine.d.ts +42 -0
  367. package/dist/src/sessions/new-session-engine.d.ts.map +1 -0
  368. package/dist/src/sessions/new-session-engine.js +100 -0
  369. package/dist/src/sessions/new-session-engine.js.map +1 -0
  370. package/dist/src/sessions/origin-delivery.d.ts +50 -4
  371. package/dist/src/sessions/origin-delivery.d.ts.map +1 -1
  372. package/dist/src/sessions/origin-delivery.js +108 -9
  373. package/dist/src/sessions/origin-delivery.js.map +1 -1
  374. package/dist/src/sessions/queue.d.ts +14 -0
  375. package/dist/src/sessions/queue.d.ts.map +1 -1
  376. package/dist/src/sessions/queue.js +38 -2
  377. package/dist/src/sessions/queue.js.map +1 -1
  378. package/dist/src/sessions/registry.d.ts +4 -2
  379. package/dist/src/sessions/registry.d.ts.map +1 -1
  380. package/dist/src/sessions/registry.js +21 -4
  381. package/dist/src/sessions/registry.js.map +1 -1
  382. package/dist/src/sessions/reply-disposition.d.ts +8 -0
  383. package/dist/src/sessions/reply-disposition.d.ts.map +1 -1
  384. package/dist/src/sessions/reply-disposition.js +8 -0
  385. package/dist/src/sessions/reply-disposition.js.map +1 -1
  386. package/dist/src/sessions/restart-resume.d.ts +234 -0
  387. package/dist/src/sessions/restart-resume.d.ts.map +1 -0
  388. package/dist/src/sessions/restart-resume.js +596 -0
  389. package/dist/src/sessions/restart-resume.js.map +1 -0
  390. package/dist/src/sessions/speaker-prefix.d.ts.map +1 -1
  391. package/dist/src/sessions/speaker-prefix.js +3 -1
  392. package/dist/src/sessions/speaker-prefix.js.map +1 -1
  393. package/dist/src/sessions/turn-delivery.d.ts +26 -0
  394. package/dist/src/sessions/turn-delivery.d.ts.map +1 -0
  395. package/dist/src/sessions/turn-delivery.js +34 -0
  396. package/dist/src/sessions/turn-delivery.js.map +1 -0
  397. package/dist/src/sessions/unrequested-stop.d.ts +26 -0
  398. package/dist/src/sessions/unrequested-stop.d.ts.map +1 -0
  399. package/dist/src/sessions/unrequested-stop.js +19 -0
  400. package/dist/src/sessions/unrequested-stop.js.map +1 -0
  401. package/dist/src/sessions/usage-limit-wait.d.ts +14 -0
  402. package/dist/src/sessions/usage-limit-wait.d.ts.map +1 -0
  403. package/dist/src/sessions/usage-limit-wait.js +9 -0
  404. package/dist/src/sessions/usage-limit-wait.js.map +1 -0
  405. package/dist/src/shared/attachment-download.d.ts +41 -0
  406. package/dist/src/shared/attachment-download.d.ts.map +1 -0
  407. package/dist/src/shared/attachment-download.js +110 -0
  408. package/dist/src/shared/attachment-download.js.map +1 -0
  409. package/dist/src/shared/attachment-notice.d.ts +24 -0
  410. package/dist/src/shared/attachment-notice.d.ts.map +1 -0
  411. package/dist/src/shared/attachment-notice.js +37 -0
  412. package/dist/src/shared/attachment-notice.js.map +1 -0
  413. package/dist/src/shared/attachments.d.ts +65 -0
  414. package/dist/src/shared/attachments.d.ts.map +1 -0
  415. package/dist/src/shared/attachments.js +153 -0
  416. package/dist/src/shared/attachments.js.map +1 -0
  417. package/dist/src/shared/childEnv.d.ts +15 -0
  418. package/dist/src/shared/childEnv.d.ts.map +1 -1
  419. package/dist/src/shared/childEnv.js +15 -0
  420. package/dist/src/shared/childEnv.js.map +1 -1
  421. package/dist/src/shared/claude-auto-memory.d.ts +33 -0
  422. package/dist/src/shared/claude-auto-memory.d.ts.map +1 -0
  423. package/dist/src/shared/claude-auto-memory.js +156 -0
  424. package/dist/src/shared/claude-auto-memory.js.map +1 -0
  425. package/dist/src/shared/claude-limit-reset.d.ts +54 -0
  426. package/dist/src/shared/claude-limit-reset.d.ts.map +1 -0
  427. package/dist/src/shared/claude-limit-reset.js +99 -0
  428. package/dist/src/shared/claude-limit-reset.js.map +1 -0
  429. package/dist/src/shared/config-error.d.ts +21 -0
  430. package/dist/src/shared/config-error.d.ts.map +1 -0
  431. package/dist/src/shared/config-error.js +37 -0
  432. package/dist/src/shared/config-error.js.map +1 -0
  433. package/dist/src/shared/config-file.d.ts +57 -0
  434. package/dist/src/shared/config-file.d.ts.map +1 -0
  435. package/dist/src/shared/config-file.js +217 -0
  436. package/dist/src/shared/config-file.js.map +1 -0
  437. package/dist/src/shared/config-yaml-edit.d.ts +20 -0
  438. package/dist/src/shared/config-yaml-edit.d.ts.map +1 -0
  439. package/dist/src/shared/config-yaml-edit.js +468 -0
  440. package/dist/src/shared/config-yaml-edit.js.map +1 -0
  441. package/dist/src/shared/config.d.ts.map +1 -1
  442. package/dist/src/shared/config.js +12 -4
  443. package/dist/src/shared/config.js.map +1 -1
  444. package/dist/src/shared/engine-fallback.d.ts +22 -0
  445. package/dist/src/shared/engine-fallback.d.ts.map +1 -1
  446. package/dist/src/shared/engine-fallback.js +55 -4
  447. package/dist/src/shared/engine-fallback.js.map +1 -1
  448. package/dist/src/shared/engine-health.d.ts +16 -0
  449. package/dist/src/shared/engine-health.d.ts.map +1 -1
  450. package/dist/src/shared/engine-health.js +42 -0
  451. package/dist/src/shared/engine-health.js.map +1 -1
  452. package/dist/src/shared/list-alignment.d.ts +23 -0
  453. package/dist/src/shared/list-alignment.d.ts.map +1 -0
  454. package/dist/src/shared/list-alignment.js +61 -0
  455. package/dist/src/shared/list-alignment.js.map +1 -0
  456. package/dist/src/shared/logger.d.ts.map +1 -1
  457. package/dist/src/shared/logger.js +104 -33
  458. package/dist/src/shared/logger.js.map +1 -1
  459. package/dist/src/shared/map-limited.d.ts +11 -0
  460. package/dist/src/shared/map-limited.d.ts.map +1 -0
  461. package/dist/src/shared/map-limited.js +30 -0
  462. package/dist/src/shared/map-limited.js.map +1 -0
  463. package/dist/src/shared/oneShotCli.d.ts.map +1 -1
  464. package/dist/src/shared/oneShotCli.js +4 -2
  465. package/dist/src/shared/oneShotCli.js.map +1 -1
  466. package/dist/src/shared/partial-delivery.d.ts +24 -0
  467. package/dist/src/shared/partial-delivery.d.ts.map +1 -0
  468. package/dist/src/shared/partial-delivery.js +46 -0
  469. package/dist/src/shared/partial-delivery.js.map +1 -0
  470. package/dist/src/shared/process-safety-net.d.ts +44 -0
  471. package/dist/src/shared/process-safety-net.d.ts.map +1 -0
  472. package/dist/src/shared/process-safety-net.js +88 -0
  473. package/dist/src/shared/process-safety-net.js.map +1 -0
  474. package/dist/src/shared/rateLimit.d.ts +45 -2
  475. package/dist/src/shared/rateLimit.d.ts.map +1 -1
  476. package/dist/src/shared/rateLimit.js +64 -2
  477. package/dist/src/shared/rateLimit.js.map +1 -1
  478. package/dist/src/shared/redact.d.ts.map +1 -1
  479. package/dist/src/shared/redact.js +11 -1
  480. package/dist/src/shared/redact.js.map +1 -1
  481. package/dist/src/shared/safe-file-name.d.ts +9 -0
  482. package/dist/src/shared/safe-file-name.d.ts.map +1 -0
  483. package/dist/src/shared/safe-file-name.js +16 -0
  484. package/dist/src/shared/safe-file-name.js.map +1 -0
  485. package/dist/src/shared/terminal-safe-text.d.ts +2 -0
  486. package/dist/src/shared/terminal-safe-text.d.ts.map +1 -0
  487. package/dist/src/shared/terminal-safe-text.js +21 -0
  488. package/dist/src/shared/terminal-safe-text.js.map +1 -0
  489. package/dist/src/shared/types.d.ts +75 -4
  490. package/dist/src/shared/types.d.ts.map +1 -1
  491. package/dist/src/skills-sync/apply.d.ts +21 -0
  492. package/dist/src/skills-sync/apply.d.ts.map +1 -0
  493. package/dist/src/skills-sync/apply.js +209 -0
  494. package/dist/src/skills-sync/apply.js.map +1 -0
  495. package/dist/src/skills-sync/backup-run.d.ts +47 -0
  496. package/dist/src/skills-sync/backup-run.d.ts.map +1 -0
  497. package/dist/src/skills-sync/backup-run.js +150 -0
  498. package/dist/src/skills-sync/backup-run.js.map +1 -0
  499. package/dist/src/skills-sync/bounded-read.d.ts +32 -0
  500. package/dist/src/skills-sync/bounded-read.d.ts.map +1 -0
  501. package/dist/src/skills-sync/bounded-read.js +104 -0
  502. package/dist/src/skills-sync/bounded-read.js.map +1 -0
  503. package/dist/src/skills-sync/bundled.d.ts +28 -0
  504. package/dist/src/skills-sync/bundled.d.ts.map +1 -0
  505. package/dist/src/skills-sync/bundled.js +84 -0
  506. package/dist/src/skills-sync/bundled.js.map +1 -0
  507. package/dist/src/skills-sync/fingerprint.d.ts +32 -0
  508. package/dist/src/skills-sync/fingerprint.d.ts.map +1 -0
  509. package/dist/src/skills-sync/fingerprint.js +58 -0
  510. package/dist/src/skills-sync/fingerprint.js.map +1 -0
  511. package/dist/src/skills-sync/history.d.ts +44 -0
  512. package/dist/src/skills-sync/history.d.ts.map +1 -0
  513. package/dist/src/skills-sync/history.js +115 -0
  514. package/dist/src/skills-sync/history.js.map +1 -0
  515. package/dist/src/skills-sync/home-skill.d.ts +28 -0
  516. package/dist/src/skills-sync/home-skill.d.ts.map +1 -0
  517. package/dist/src/skills-sync/home-skill.js +67 -0
  518. package/dist/src/skills-sync/home-skill.js.map +1 -0
  519. package/dist/src/skills-sync/instance.d.ts +26 -0
  520. package/dist/src/skills-sync/instance.d.ts.map +1 -0
  521. package/dist/src/skills-sync/instance.js +128 -0
  522. package/dist/src/skills-sync/instance.js.map +1 -0
  523. package/dist/src/skills-sync/names.d.ts +25 -0
  524. package/dist/src/skills-sync/names.d.ts.map +1 -0
  525. package/dist/src/skills-sync/names.js +56 -0
  526. package/dist/src/skills-sync/names.js.map +1 -0
  527. package/dist/src/skills-sync/plan.d.ts +58 -0
  528. package/dist/src/skills-sync/plan.d.ts.map +1 -0
  529. package/dist/src/skills-sync/plan.js +132 -0
  530. package/dist/src/skills-sync/plan.js.map +1 -0
  531. package/dist/src/skills-sync/receipt.d.ts +61 -0
  532. package/dist/src/skills-sync/receipt.d.ts.map +1 -0
  533. package/dist/src/skills-sync/receipt.js +149 -0
  534. package/dist/src/skills-sync/receipt.js.map +1 -0
  535. package/dist/src/skills-sync/staging.d.ts +21 -0
  536. package/dist/src/skills-sync/staging.d.ts.map +1 -0
  537. package/dist/src/skills-sync/staging.js +81 -0
  538. package/dist/src/skills-sync/staging.js.map +1 -0
  539. package/dist/src/skills-sync/sync.d.ts +37 -0
  540. package/dist/src/skills-sync/sync.d.ts.map +1 -0
  541. package/dist/src/skills-sync/sync.js +201 -0
  542. package/dist/src/skills-sync/sync.js.map +1 -0
  543. package/dist/src/skills-sync/types.d.ts +66 -0
  544. package/dist/src/skills-sync/types.d.ts.map +1 -0
  545. package/dist/src/skills-sync/types.js +2 -0
  546. package/dist/src/skills-sync/types.js.map +1 -0
  547. package/dist/src/stt/config.d.ts +5 -0
  548. package/dist/src/stt/config.d.ts.map +1 -0
  549. package/dist/src/stt/config.js +18 -0
  550. package/dist/src/stt/config.js.map +1 -0
  551. package/dist/src/updates/maintenance.d.ts.map +1 -1
  552. package/dist/src/updates/maintenance.js +24 -4
  553. package/dist/src/updates/maintenance.js.map +1 -1
  554. package/dist/src/workflows/repository-mutex.d.ts +1 -1
  555. package/dist/web/404.html +1 -1
  556. package/dist/web/__next.__PAGE__.txt +11 -11
  557. package/dist/web/__next._full.txt +12 -12
  558. package/dist/web/__next._tree.txt +2 -2
  559. package/dist/web/_next/static/chunks/{0g5c5ppr8zmup.js → 20v6mri7epga5.js} +1 -1
  560. package/dist/web/_next/static/chunks/2u0328ngpt-ek.js +1 -0
  561. package/dist/web/_next/static/chunks/3f9i3f9q6v6_j.css +1 -0
  562. package/dist/web/_next/static/chunks/{08i7uo3uz6_fn.js → 3yy053rafgrzy.js} +1 -1
  563. package/dist/web/_not-found/__next._full.txt +10 -10
  564. package/dist/web/_not-found/__next._not-found.__PAGE__.txt +9 -9
  565. package/dist/web/_not-found/__next._tree.txt +2 -2
  566. package/dist/web/_not-found.html +1 -1
  567. package/dist/web/_not-found.txt +10 -10
  568. package/dist/web/chat/__next._full.txt +12 -12
  569. package/dist/web/chat/__next._tree.txt +2 -2
  570. package/dist/web/chat/__next.chat.__PAGE__.txt +11 -11
  571. package/dist/web/chat.html +1 -1
  572. package/dist/web/chat.txt +12 -12
  573. package/dist/web/cron/__next._full.txt +12 -12
  574. package/dist/web/cron/__next._tree.txt +2 -2
  575. package/dist/web/cron/__next.cron.__PAGE__.txt +11 -11
  576. package/dist/web/cron.html +1 -1
  577. package/dist/web/cron.txt +12 -12
  578. package/dist/web/index.html +1 -1
  579. package/dist/web/index.txt +12 -12
  580. package/dist/web/kanban/__next._full.txt +12 -12
  581. package/dist/web/kanban/__next._tree.txt +2 -2
  582. package/dist/web/kanban/__next.kanban.__PAGE__.txt +11 -11
  583. package/dist/web/kanban.html +1 -1
  584. package/dist/web/kanban.txt +12 -12
  585. package/dist/web/logs/__next._full.txt +12 -12
  586. package/dist/web/logs/__next._tree.txt +2 -2
  587. package/dist/web/logs/__next.logs.__PAGE__.txt +11 -11
  588. package/dist/web/logs.html +1 -1
  589. package/dist/web/logs.txt +12 -12
  590. package/dist/web/models/__next._full.txt +12 -12
  591. package/dist/web/models/__next._tree.txt +2 -2
  592. package/dist/web/models/__next.models.__PAGE__.txt +11 -11
  593. package/dist/web/models.html +1 -1
  594. package/dist/web/models.txt +12 -12
  595. package/dist/web/org/__next._full.txt +12 -12
  596. package/dist/web/org/__next._tree.txt +2 -2
  597. package/dist/web/org/__next.org.__PAGE__.txt +11 -11
  598. package/dist/web/org.html +1 -1
  599. package/dist/web/org.txt +12 -12
  600. package/dist/web/sessions/__next._full.txt +10 -10
  601. package/dist/web/sessions/__next._tree.txt +2 -2
  602. package/dist/web/sessions/__next.sessions.__PAGE__.txt +9 -9
  603. package/dist/web/sessions.html +1 -1
  604. package/dist/web/sessions.txt +10 -10
  605. package/dist/web/settings/__next._full.txt +12 -12
  606. package/dist/web/settings/__next._tree.txt +2 -2
  607. package/dist/web/settings/__next.settings.__PAGE__.txt +11 -11
  608. package/dist/web/settings.html +1 -1
  609. package/dist/web/settings.txt +12 -12
  610. package/dist/web/skills/__next._full.txt +12 -12
  611. package/dist/web/skills/__next._tree.txt +2 -2
  612. package/dist/web/skills/__next.skills.__PAGE__.txt +11 -11
  613. package/dist/web/skills.html +1 -1
  614. package/dist/web/skills.txt +12 -12
  615. package/package.json +2 -1
  616. package/template/AGENTS.md +48 -308
  617. package/template/CLAUDE.md +4 -349
  618. package/template/bundled-skill-history.json +377 -0
  619. package/template/config.default.yaml +52 -3
  620. package/template/docs/architecture.md +41 -3
  621. package/template/docs/backup.md +142 -0
  622. package/template/docs/connectors.md +192 -16
  623. package/template/docs/cron.md +30 -11
  624. package/template/docs/memory.md +47 -0
  625. package/template/docs/overview.md +6 -2
  626. package/template/docs/self-modification.md +11 -10
  627. package/template/docs/skills.md +77 -4
  628. package/template/migrations/0.3.0/MIGRATION.md +6 -0
  629. package/template/migrations/0.7.3/MIGRATION.md +6 -0
  630. package/template/migrations/0.7.5/MIGRATION.md +1 -1
  631. package/template/migrations/0.9.0/MIGRATION.md +6 -0
  632. package/template/migrations/2026.10.13/MIGRATION.md +76 -0
  633. package/template/migrations/2026.10.13/files/docs/architecture.md +112 -0
  634. package/template/migrations/2026.10.13/files/docs/automations.md +110 -0
  635. package/template/migrations/2026.10.13/files/docs/backup.md +142 -0
  636. package/template/migrations/2026.10.13/files/docs/connectors.md +370 -0
  637. package/template/migrations/2026.10.13/files/docs/cron-commands.md +52 -0
  638. package/template/migrations/2026.10.13/files/docs/cron.md +178 -0
  639. package/template/migrations/2026.10.13/files/docs/mcp.md +108 -0
  640. package/template/migrations/2026.10.13/files/docs/memory.md +47 -0
  641. package/template/migrations/2026.10.13/files/docs/org.md +111 -0
  642. package/template/migrations/2026.10.13/files/docs/overview.md +44 -0
  643. package/template/migrations/2026.10.13/files/docs/self-modification.md +71 -0
  644. package/template/migrations/2026.10.13/files/docs/skills.md +140 -0
  645. package/template/migrations/2026.10.13/files/skills/cron-manager/SKILL.md +107 -0
  646. package/template/migrations/2026.10.13/files/skills/management/SKILL.md +227 -0
  647. package/template/migrations/2026.10.13/files/skills/migrate/SKILL.md +194 -0
  648. package/template/migrations/2026.10.13/files/skills/onboarding/SKILL.md +153 -0
  649. package/template/migrations/2026.10.13/files/skills/openryoko-config/SKILL.md +35 -0
  650. package/template/migrations/2026.10.13/files/skills/openryoko-config/references/engine-fallback.md +98 -0
  651. package/template/migrations/2026.10.13/files/skills/openryoko-config/references/jev.md +89 -0
  652. package/template/migrations/2026.10.13/files/skills/openryoko-config/references/maintenance.md +49 -0
  653. package/template/migrations/2026.10.13/files/skills/openryoko-config/references/platform.md +100 -0
  654. package/template/migrations/2026.10.13/files/skills/self-heal/SKILL.md +187 -0
  655. package/template/migrations/2026.10.9/MIGRATION.md +44 -0
  656. package/template/migrations/2026.10.9/files/docs/memory.md +47 -0
  657. package/template/migrations/2026.10.9/files/skills/migrate/SKILL.md +194 -0
  658. package/template/migrations/2026.5.7/MIGRATION.md +6 -0
  659. package/template/migrations/2026.8.28/MIGRATION.md +6 -0
  660. package/template/migrations/2026.9.11/MIGRATION.md +6 -0
  661. package/template/skills/cron-manager/SKILL.md +10 -0
  662. package/template/skills/management/SKILL.md +5 -4
  663. package/template/skills/migrate/SKILL.md +47 -14
  664. package/template/skills/onboarding/SKILL.md +3 -3
  665. package/template/skills/openryoko-config/SKILL.md +1 -1
  666. package/template/skills/openryoko-config/references/engine-fallback.md +16 -5
  667. package/template/skills/openryoko-config/references/platform.md +23 -4
  668. package/template/skills/self-heal/SKILL.md +117 -44
  669. package/dist/src/engines/mock.d.ts +0 -16
  670. package/dist/src/engines/mock.d.ts.map +0 -1
  671. package/dist/src/engines/mock.js +0 -47
  672. package/dist/src/engines/mock.js.map +0 -1
  673. package/dist/src/shared/test-support/posix-mode.d.ts +0 -17
  674. package/dist/src/shared/test-support/posix-mode.d.ts.map +0 -1
  675. package/dist/src/shared/test-support/posix-mode.js +0 -23
  676. package/dist/src/shared/test-support/posix-mode.js.map +0 -1
  677. package/dist/web/_next/static/Oux0UBcCkbX5eOp9-vC4k/_buildManifest.js +0 -11
  678. package/dist/web/_next/static/Oux0UBcCkbX5eOp9-vC4k/_clientMiddlewareManifest.js +0 -1
  679. package/dist/web/_next/static/Oux0UBcCkbX5eOp9-vC4k/_ssgManifest.js +0 -1
  680. package/dist/web/_next/static/chunks/02h65sho8c14h.js +0 -1
  681. package/dist/web/_next/static/chunks/0ic18n-m7ixyw.css +0 -1
  682. package/dist/web/_next/static/chunks/19s8vn2kgy7q1.js +0 -1
  683. package/dist/web/_next/static/chunks/1_jm0szyu2the.js +0 -1
  684. package/dist/web/_next/static/chunks/1omdg4m5w9lgx.js +0 -1
  685. package/dist/web/_next/static/chunks/25nob1new8t4s.js +0 -79
  686. package/dist/web/_next/static/chunks/2iqxlc9wtxzm2.js +0 -1
  687. package/dist/web/_next/static/chunks/3_6klkygi417n.js +0 -1
  688. package/dist/web/_next/static/chunks/3alc-b00c58_3.css +0 -1
  689. /package/dist/web/_next/static/{70PNIyOj8-2kywAG6J41- → ov0mWzyHx0B5oEnTHE_pa}/_buildManifest.js +0 -0
  690. /package/dist/web/_next/static/{70PNIyOj8-2kywAG6J41- → ov0mWzyHx0B5oEnTHE_pa}/_clientMiddlewareManifest.js +0 -0
  691. /package/dist/web/_next/static/{70PNIyOj8-2kywAG6J41- → ov0mWzyHx0B5oEnTHE_pa}/_ssgManifest.js +0 -0
@@ -1,4 +1,7 @@
1
1
  import { withConfigLock } from "../shared/config-lock.js";
2
+ import { readConfigSnapshot, writeConfigDocument } from "../shared/config-file.js";
3
+ import { CONFIG_CONFLICT_BODY, CONFIG_REVISION_HEADER, configForApi, isStaleConfigRevision } from "./config-revision.js";
4
+ import { redactMcpSecrets, restoreCustomMcpSecrets, storedItemWithSameId, withoutPlaceholders } from "./config-redaction.js";
2
5
  import { validateCommandJob } from "../cron/command.js";
3
6
  import { validateCronSchedule } from "../cron/validation.js";
4
7
  import http from "node:http";
@@ -6,27 +9,29 @@ import crypto from "node:crypto";
6
9
  import fs from "node:fs";
7
10
  import os from "node:os";
8
11
  import path from "node:path";
9
- import yaml from "js-yaml";
10
12
  import cron from "node-cron";
11
13
  import { isInterruptibleEngine } from "../shared/types.js";
12
14
  import { runWithSessionGoal, sessionGoalOptions } from "../sessions/goal-execution.js";
13
- import { buildEngineSyncPrompt, clearEngineSyncMarker, engineSyncSince, maybeRevertEngineOverride, runEngineWithResponseTimeout, runFallbackAttempts, waitForEngineRetry } from "../sessions/engine-fallback.js";
15
+ import { buildEngineSyncPrompt, clearEngineSyncMarker, engineOverrideAfterReset, engineSyncSince, failLimitThatOutlastsTheWait, maybeRevertEngineOverride, runEngineWithResponseTimeout, runFallbackAttempts, stoppedByShutdown, waitForEngineRetry } from "../sessions/engine-fallback.js";
16
+ import { startOnHealthyEngine } from "../sessions/new-session-engine.js";
14
17
  import { cleanupMcpConfigFile, resolveMcpServers, writeMcpConfigFile } from "../mcp/resolver.js";
15
18
  import { buildContext } from "../sessions/context.js";
16
19
  import { initDb, listSessions, getSession, createSession, updateSession, deleteSession, deleteSessions, duplicateSession, insertMessage, getMessages, enqueueQueueItem, insertNotificationWithQueueItem, cancelQueueItem, getQueueItems, cancelAllPendingQueueItems, listAllPendingQueueItems, getFile, getMessagePage, getMessageWindow, isFtsBackfillPending, listSessionPage, searchMessages, } from "../sessions/registry.js";
17
20
  import { forkEngineSession } from "../sessions/fork.js";
18
21
  import { deliverToOriginConnector, isUndeliveredToOrigin, recordFailedOriginDelivery } from "../sessions/origin-delivery.js";
19
- import { CONFIG_PATH, CRON_RUNS, ORG_DIR, SKILLS_DIR, LOGS_DIR, TMP_DIR, FILES_DIR, } from "../shared/paths.js";
22
+ import { isCompletionBatchItem, queueChildCompletion, queuedPrompt } from "../sessions/completion-batching.js";
23
+ import { ORG_DIR, SKILLS_DIR, LOGS_DIR, TMP_DIR, FILES_DIR, } from "../shared/paths.js";
20
24
  import { logger } from "../shared/logger.js";
21
25
  import { getSttStatus, downloadModel, transcribe as sttTranscribe, resolveLanguages, WHISPER_LANGUAGES } from "../stt/stt.js";
26
+ import { markSttModelInstalled, saveSttLanguages } from "../stt/config.js";
22
27
  import { JINN_HOME } from "../shared/paths.js";
23
28
  import { handleHookPost, LOOPBACK as HOOK_LOOPBACK } from "./hook-endpoint.js";
24
29
  import { resolveEffort } from "../shared/effort.js";
25
30
  import { explicitThread } from "../shared/threading.js";
26
31
  import { effortLevelsForModel, invalidateModelRegistry } from "../shared/models.js";
27
- import { computeNextRetryDelayMs, computeRateLimitDeadlineMs, detectRateLimit } from "../shared/rateLimit.js";
32
+ import { computeNextRetryDelayMs, computeRateLimitDeadlineMs, detectRateLimit, MAX_USAGE_LIMIT_WAIT_MS } from "../shared/rateLimit.js";
28
33
  import { getClaudeExpectedResetAt, recordClaudeRateLimit } from "../shared/usageAwareness.js";
29
- import { CronJobsReadError, loadJobs, saveJobs } from "../cron/jobs.js";
34
+ import { CronJobsReadError, loadJobs, readRunLog, runLogPath, saveJobs } from "../cron/jobs.js";
30
35
  import { getCronJobScheduleStatus, getSchedulerSnapshot, reloadScheduler } from "../cron/scheduler.js";
31
36
  import { runCronJob } from "../cron/runner.js";
32
37
  import { checkForUpdates } from "../updates/checker.js";
@@ -43,14 +48,26 @@ import { handleWorkflowApi } from "./workflow-api.js";
43
48
  import { handleTypeSafeIntegrationApi } from "./integrations-typesafe-api.js";
44
49
  import { shouldRequireGatewayAuth as workflowAuthRequired, verifyGatewayAuth as workflowVerifyAuth } from "./auth.js";
45
50
  import { getDiskSpaceStatus } from "../shared/storage-health.js";
51
+ import { getBackupStatus } from "../backup/scheduler.js";
52
+ import { getProcessSafetyNetStats } from "../shared/process-safety-net.js";
46
53
  import { ptySnapshotStore } from "../engines/pty-snapshot.js";
47
54
  import { collectClaudeUsage } from "../shared/claude-usage.js";
48
55
  import { PairingAttemptLimiter, pairingAttemptKey } from "./pairing-rate-limit.js";
49
- import { personalizeInstructionMd, personalizeIdentityMd, resolveEffectiveName } from "./onboarding-personalize.js";
50
- import { patchPortalSection, writeFileAtomic } from "./portal-config.js";
56
+ import { applyLanguageSection, personalizeInstructionMd, personalizeIdentityMd, resolveEffectiveName } from "./onboarding-personalize.js";
57
+ import { savePortalBlock, writeFileAtomic } from "./portal-config.js";
58
+ import { restoreBeforeSlackConnect, slackBlockOf, snapshotStillHoldingSlackTokens } from "./slack-connect-rollback.js";
59
+ import { newAttachmentDir } from "../shared/attachments.js";
51
60
  /** Max bytes accepted on /api/internal/hook (loopback-only relay payloads are tiny). */
52
61
  const HOOK_BODY_MAX_BYTES = 64 * 1024;
53
62
  const PAIR_BODY_MAX_BYTES = 1024;
63
+ /** Max bytes accepted on PUT /api/config. The body is merged into config.yaml,
64
+ * and what a save costs grows with the size of that file: a megabyte is far
65
+ * more than a configuration needs (the shipped one is tens of kilobytes). */
66
+ const CONFIG_BODY_MAX_BYTES = 1024 * 1024;
67
+ /** Max bytes accepted on /api/connectors/:id/incoming. A forwarded Discord
68
+ * message is a few thousand characters, ten attachment URLs and some
69
+ * metadata: tens of kilobytes at the very most. */
70
+ const INCOMING_BODY_MAX_BYTES = 256 * 1024;
54
71
  const PAIR_ATTEMPT_WINDOW_MS = 5 * 60_000;
55
72
  const pairingAttempts = new PairingAttemptLimiter(10, PAIR_ATTEMPT_WINDOW_MS);
56
73
  const pairingGlobalAttempts = new PairingAttemptLimiter(1_000, PAIR_ATTEMPT_WINDOW_MS, 1);
@@ -75,7 +92,8 @@ export function resumePendingWebQueueItems(context) {
75
92
  if (session.source !== "web") {
76
93
  const messages = getMessages(session.id);
77
94
  const match = [...messages].reverse().find((m) => m.content === item.prompt);
78
- if (match?.role !== "notification")
95
+ // A completion batch is a wake-up too, but its prompt is several notifications folded together.
96
+ if (match?.role !== "notification" && !isCompletionBatchItem(item.id))
79
97
  continue;
80
98
  deliverToConnector = true;
81
99
  }
@@ -113,7 +131,8 @@ function dispatchWebSessionRun(session, prompt, engine, config, context, opts) {
113
131
  const run = async () => {
114
132
  await context.sessionManager.getQueue().enqueue(session.sessionKey || session.sourceRef, async () => {
115
133
  context.emit("session:started", { sessionId: session.id });
116
- await runWebSession(session, prompt, engine, config, context, opts?.attachments, opts?.deliverToConnector);
134
+ // Run what the row holds now: a completion batch can grow while it waits its turn.
135
+ await runWebSession(session, queuedPrompt(opts?.queueItemId, prompt), engine, config, context, opts?.attachments, opts?.deliverToConnector);
117
136
  }, opts?.queueItemId);
118
137
  };
119
138
  const launch = () => {
@@ -244,7 +263,7 @@ function badRequest(res, message) {
244
263
  function serverError(res, message) {
245
264
  json(res, { error: message }, 500);
246
265
  }
247
- const SANITIZED_KEYS = new Set(["token", "botToken", "signingSecret", "appToken", "proxyViaToken"]);
266
+ const SANITIZED_KEYS = new Set(["token", "botToken", "signingSecret", "appToken", "proxyViaToken", "apiKey"]);
248
267
  /** Mask the per-route bearer tokens inside connectors.*.channelRouting for
249
268
  * GET /api/config. deepMerge already restores "***" placeholders on PUT —
250
269
  * "token" is in SANITIZED_KEYS and the merge is recursive. */
@@ -271,33 +290,30 @@ export function deepMerge(target, source) {
271
290
  continue;
272
291
  // JSON cannot carry `undefined`. An explicit null removes an optional
273
292
  // override, allowing clients to restore inherited/default behavior.
293
+ // Unless null is what config.yaml already holds there: a section written
294
+ // as a heading with only comments under it (`cron:`) is null on disk and
295
+ // comes back from GET as null, and saving that back removes nothing —
296
+ // the heading stays, with the comments that belong under it.
274
297
  if (sv === null) {
275
- delete result[key];
298
+ if (tv !== null)
299
+ delete result[key];
276
300
  continue;
277
301
  }
278
302
  if (Array.isArray(sv)) {
279
- // For arrays (e.g. instances), preserve secrets from matching items
280
- if (Array.isArray(tv)) {
281
- result[key] = sv.map((item) => {
282
- if (item && typeof item === "object" && !Array.isArray(item)) {
283
- const srcItem = item;
284
- // Find matching target item by id
285
- const matchTarget = tv.find((t) => t && typeof t === "object" && t.id === srcItem.id);
286
- if (matchTarget)
287
- return deepMerge(matchTarget, srcItem);
288
- }
289
- return item;
290
- });
291
- }
292
- else {
293
- result[key] = sv;
294
- }
303
+ // For arrays (e.g. instances), preserve secrets from matching items:
304
+ // the stored item with the same id. Any other item is stored as sent,
305
+ // minus the placeholders — there is nothing stored they could stand for.
306
+ result[key] = sv.map((item) => {
307
+ const matchTarget = storedItemWithSameId(tv, item);
308
+ return matchTarget ? deepMerge(matchTarget, item) : withoutPlaceholders(item, SANITIZED_KEYS);
309
+ });
295
310
  }
296
311
  else if (sv && typeof sv === "object" && !Array.isArray(sv) && tv && typeof tv === "object" && !Array.isArray(tv)) {
297
312
  result[key] = deepMerge(tv, sv);
298
313
  }
299
314
  else {
300
- result[key] = sv;
315
+ // A block config.yaml does not have: same rule, no placeholder is written.
316
+ result[key] = withoutPlaceholders(sv, SANITIZED_KEYS);
301
317
  }
302
318
  }
303
319
  return result;
@@ -574,6 +590,10 @@ export async function handleApiRequest(req, res, context) {
574
590
  const running = sessions.filter((s) => s.status === "running").length;
575
591
  const connectors = Object.fromEntries(Array.from(context.connectors.values()).map((connector) => [connector.name, connector.getHealth()]));
576
592
  res.setHeader("Cache-Control", "no-store");
593
+ // `health` sits beside the fields below and changes none of them:
594
+ // `available` stays what it always was for whoever already reads it.
595
+ const { engineHealthForStatus } = await import("../sessions/engine-health-gate.js");
596
+ const health = engineHealthForStatus();
577
597
  return json(res, {
578
598
  status: "ok",
579
599
  uptime: Math.floor((Date.now() - context.startTime) / 1000),
@@ -583,13 +603,17 @@ export async function handleApiRequest(req, res, context) {
583
603
  // `interactive` tells the web UI the Claude engine runs as a live PTY
584
604
  // (cc_entrypoint=cli, Max-subsidized) — so the CLI view can attach the
585
605
  // live xterm (/ws/pty) instead of the poll-based transcript.
586
- claude: { model: config.engines.claude.model, available: true, interactive: config.engines.claude.interactive === true },
587
- codex: { model: config.engines.codex.model, available: true },
588
- ...(config.engines.gemini ? { gemini: { model: config.engines.gemini.model, available: true } } : {}),
606
+ claude: { model: config.engines.claude.model, available: true, interactive: config.engines.claude.interactive === true, health: health("claude") },
607
+ codex: { model: config.engines.codex.model, available: true, health: health("codex") },
608
+ ...(config.engines.gemini ? { gemini: { model: config.engines.gemini.model, available: true, health: health("gemini") } } : {}),
589
609
  },
590
610
  sessions: { total: sessions.length, running, active: running },
591
611
  connectors,
592
612
  storage: getDiskSpaceStatus(),
613
+ backup: getBackupStatus(),
614
+ // Faults the process safety net caught instead of dying on. Anything
615
+ // above zero means the gateway is running on after an error nothing handled.
616
+ process: getProcessSafetyNetStats(),
593
617
  });
594
618
  }
595
619
  if (pathname === "/api/models" || pathname === "/api/models/actions") {
@@ -908,7 +932,13 @@ export async function handleApiRequest(req, res, context) {
908
932
  context.sessionManager.getQueue().clearQueue(session.sessionKey || session.sourceRef || session.id);
909
933
  const meta = { ...(session.transportMeta || {}) };
910
934
  delete meta["engineSessions"];
911
- delete meta["engineOverride"];
935
+ // The override is kept: it is the session's way back to the engine it was
936
+ // moved off, and deleting it left the session on its fallback for good.
937
+ const override = engineOverrideAfterReset(meta["engineOverride"]);
938
+ if (override)
939
+ meta["engineOverride"] = override;
940
+ else
941
+ delete meta["engineOverride"];
912
942
  delete meta["engineSyncSince"];
913
943
  delete meta["claudeSyncSince"];
914
944
  updateSession(params.id, {
@@ -919,7 +949,7 @@ export async function handleApiRequest(req, res, context) {
919
949
  transportMeta: meta,
920
950
  });
921
951
  ptySnapshotStore.deleteSync(params.id);
922
- logger.info(`Session ${params.id} reset via API (cleared engineSessions, engineOverride, engineSessionId, lastError)`);
952
+ logger.info(`Session ${params.id} reset via API (cleared engineSessions, engineSessionId, lastError)`);
923
953
  context.emit("session:updated", { sessionId: params.id });
924
954
  return json(res, { status: "reset", sessionId: params.id });
925
955
  }
@@ -1113,7 +1143,7 @@ export async function handleApiRequest(req, res, context) {
1113
1143
  const requestedModel = typeof body.model === "string" && body.model.trim() ? body.model.trim() : undefined;
1114
1144
  const model = requestedModel ?? (employeeDef && employeeDef.engine === engineName ? employeeDef.model || undefined : undefined);
1115
1145
  const sessionKey = `web:${Date.now()}`;
1116
- const session = createSession({
1146
+ const created = createSession({
1117
1147
  engine: engineName,
1118
1148
  model,
1119
1149
  source: "web",
@@ -1127,10 +1157,18 @@ export async function handleApiRequest(req, res, context) {
1127
1157
  prompt,
1128
1158
  portalName: config.portal?.portalName,
1129
1159
  });
1160
+ // An engine already known to be out of allowance is not worth a failed
1161
+ // turn to rediscover: start on its fallback, as a routed session does.
1162
+ // An engine or model the request itself names is run as asked.
1163
+ const { session, notice } = startOnHealthyEngine(config, (name) => context.sessionManager.getEngine(name), created, { engine: body.engine || undefined, model: requestedModel, employee: employeeDef });
1130
1164
  logger.info(`Web session created: ${session.id}`);
1131
1165
  insertMessage(session.id, "user", prompt);
1166
+ if (notice) {
1167
+ insertMessage(session.id, "notification", notice);
1168
+ context.emit("session:notification", { sessionId: session.id, message: notice });
1169
+ }
1132
1170
  // Run engine asynchronously — respond immediately, push result via WebSocket
1133
- const engine = context.sessionManager.getEngine(engineName);
1171
+ const engine = context.sessionManager.getEngine(session.engine);
1134
1172
  if (!engine) {
1135
1173
  updateSession(session.id, {
1136
1174
  status: "error",
@@ -1248,20 +1286,27 @@ export async function handleApiRequest(req, res, context) {
1248
1286
  context.sessionManager.getQueue().clearCancelled(session.sessionKey || session.sourceRef || session.id);
1249
1287
  const attachmentPaths = resolveAttachmentPaths(body.attachments);
1250
1288
  const sessionKey = session.sessionKey || session.sourceRef || session.id;
1251
- const queueItemId = dedupedNotification
1289
+ // A child's completion joins the completion row already waiting behind a
1290
+ // busy parent, so N children finishing cost the parent one turn, not N.
1291
+ const completion = isNotification && !dedupedNotification
1292
+ ? queueChildCompletion(session, sessionKey, body, prompt, context.sessionManager.getQueue())
1293
+ : null;
1294
+ const queueItemId = completion?.queueItemId ?? (dedupedNotification
1252
1295
  ? insertNotificationWithQueueItem(session.id, sessionKey, prompt)
1253
- : enqueueQueueItem(session.id, sessionKey, prompt);
1296
+ : enqueueQueueItem(session.id, sessionKey, prompt));
1254
1297
  if (dedupedNotification)
1255
1298
  rememberDedupeKey(dedupeKey);
1256
1299
  context.emit("queue:updated", { sessionId: session.id, sessionKey });
1257
- dispatchWebSessionRun(session, prompt, engine, config, context, {
1258
- queueItemId,
1259
- attachments: attachmentPaths.length > 0 ? attachmentPaths : undefined,
1260
- // A notification wake-up (detached job finished, child callback) runs
1261
- // on this connector-less path; deliver the answer back to the origin
1262
- // conversation so e.g. a Slack thread is not left waiting silently.
1263
- deliverToConnector: isNotification,
1264
- });
1300
+ // A joined row already has its dispatcher — unless a restart orphaned it.
1301
+ if (completion?.needsDispatch !== false)
1302
+ dispatchWebSessionRun(session, prompt, engine, config, context, {
1303
+ queueItemId,
1304
+ attachments: attachmentPaths.length > 0 ? attachmentPaths : undefined,
1305
+ // A notification wake-up (detached job finished, child callback) runs
1306
+ // on this connector-less path; deliver the answer back to the origin
1307
+ // conversation so e.g. a Slack thread is not left waiting silently.
1308
+ deliverToConnector: isNotification,
1309
+ });
1265
1310
  return json(res, { status: "queued", sessionId: session.id });
1266
1311
  }
1267
1312
  // Runtime state must be queryable even when the file cannot be read.
@@ -1290,9 +1335,9 @@ export async function handleApiRequest(req, res, context) {
1290
1335
  const jobs = loadCronJobsForApi();
1291
1336
  // Enrich with last run status
1292
1337
  const enriched = jobs.map((job) => {
1293
- const runFile = path.join(CRON_RUNS, `${job.id}.jsonl`);
1338
+ const runFile = runLogPath(job.id);
1294
1339
  let lastRun = null;
1295
- if (fs.existsSync(runFile)) {
1340
+ if (runFile && fs.existsSync(runFile)) {
1296
1341
  const lines = fs.readFileSync(runFile, "utf-8").trim().split("\n").filter(Boolean);
1297
1342
  if (lines.length > 0) {
1298
1343
  try {
@@ -1305,19 +1350,11 @@ export async function handleApiRequest(req, res, context) {
1305
1350
  });
1306
1351
  return json(res, enriched);
1307
1352
  }
1308
- // GET /api/cron/:id/runs
1353
+ // GET /api/cron/:id/runs — every run, oldest first; ?limit=N keeps the newest N.
1309
1354
  params = matchRoute("/api/cron/:id/runs", pathname);
1310
1355
  if (method === "GET" && params) {
1311
- const runFile = path.join(CRON_RUNS, `${params.id}.jsonl`);
1312
- if (!fs.existsSync(runFile))
1313
- return json(res, []);
1314
- const lines = fs
1315
- .readFileSync(runFile, "utf-8")
1316
- .trim()
1317
- .split("\n")
1318
- .filter(Boolean)
1319
- .map((l) => JSON.parse(l));
1320
- return json(res, lines);
1356
+ const limit = Math.max(0, parseInt(url.searchParams.get("limit") || "0", 10) || 0);
1357
+ return json(res, readRunLog(params.id, limit));
1321
1358
  }
1322
1359
  // POST /api/cron — create new cron job
1323
1360
  if (method === "POST" && pathname === "/api/cron") {
@@ -1759,7 +1796,9 @@ Handle this as a priority request from a colleague.`;
1759
1796
  }
1760
1797
  // GET /api/config
1761
1798
  if (method === "GET" && pathname === "/api/config") {
1762
- const config = context.getConfig();
1799
+ // The document on disk plus the revision of those bytes — see configForApi.
1800
+ const { config, revision } = configForApi(context.getConfig());
1801
+ res.setHeader(CONFIG_REVISION_HEADER, revision);
1763
1802
  // Sanitize: remove any secrets/tokens from connectors
1764
1803
  const rawConnectors = config.connectors || {};
1765
1804
  const sanitizedConnectors = {};
@@ -1793,12 +1832,13 @@ Handle this as a priority request from a colleague.`;
1793
1832
  const sanitized = {
1794
1833
  ...config,
1795
1834
  connectors: sanitizedConnectors,
1835
+ ...(config.mcp ? { mcp: redactMcpSecrets(config.mcp) } : {}),
1796
1836
  };
1797
1837
  return json(res, sanitized);
1798
1838
  }
1799
1839
  // PUT /api/config
1800
1840
  if (method === "PUT" && pathname === "/api/config") {
1801
- const _parsed = await readJsonBody(req, res);
1841
+ const _parsed = await readJsonBody(req, res, CONFIG_BODY_MAX_BYTES);
1802
1842
  if (!_parsed.ok)
1803
1843
  return;
1804
1844
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -1809,6 +1849,8 @@ Handle this as a priority request from a colleague.`;
1809
1849
  }
1810
1850
  // Validate known top-level keys
1811
1851
  // Keep this aligned with `JinnConfig` in src/shared/types.ts
1852
+ // (`remotes` is legacy: nothing reads it since /api/files/transfer was
1853
+ // retired, but existing configs may still carry it.)
1812
1854
  const KNOWN_KEYS = [
1813
1855
  "jinn",
1814
1856
  "gateway",
@@ -1818,8 +1860,10 @@ Handle this as a priority request from a colleague.`;
1818
1860
  "connectors",
1819
1861
  "logging",
1820
1862
  "mcp",
1863
+ "budgets", // written by PUT /api/budgets — without it the Settings save 400s once a limit exists
1821
1864
  "sessions",
1822
1865
  "cron",
1866
+ "backup",
1823
1867
  "workflows",
1824
1868
  "notifications",
1825
1869
  "portal",
@@ -1847,16 +1891,24 @@ Handle this as a priority request from a colleague.`;
1847
1891
  // Every read→merge→write→reload of config.yaml runs under one lock, so a
1848
1892
  // concurrent writer (another PUT, the onboarding Slack connect and its
1849
1893
  // rollback) can never interleave with — or be overwritten by — this one.
1850
- return withConfigLock(async () => {
1894
+ // Awaited, so a refused or failed write reaches this handler's catch
1895
+ // instead of escaping as an unhandled rejection.
1896
+ return await withConfigLock(async () => {
1851
1897
  // Deep-merge incoming config with existing config to preserve
1852
- // fields not included in the update (e.g. connector tokens).
1853
- let existing = {};
1854
- try {
1855
- existing = yaml.load(fs.readFileSync(CONFIG_PATH, "utf-8")) || {};
1898
+ // fields not included in the update (e.g. connector tokens). A file
1899
+ // that exists but cannot be read throws here: merging into an empty
1900
+ // object would replace the whole config with this request body.
1901
+ const snapshot = readConfigSnapshot();
1902
+ // A caller that sends the revision it loaded (the Settings page saves
1903
+ // the whole document) must not write over a file it has not seen.
1904
+ // Checked here, under the lock, against the bytes the merge starts from.
1905
+ if (isStaleConfigRevision(req.headers, snapshot.revision)) {
1906
+ return json(res, CONFIG_CONFLICT_BODY, 409);
1856
1907
  }
1857
- catch { /* start fresh if unreadable */ }
1858
- const merged = deepMerge(existing, body);
1859
- const yamlStr = yaml.dump(merged);
1908
+ const existing = snapshot.document;
1909
+ // A custom MCP server's env and headers come back from GET hidden value by
1910
+ // value; the stored values are put back before the merge sees them.
1911
+ const merged = deepMerge(existing, restoreCustomMcpSecrets(body, existing));
1860
1912
  // Compare AGAINST THE MERGED config, not the request body — partial
1861
1913
  // updates (e.g. saving only "portal.portalName") leave body.connectors
1862
1914
  // undefined, which would falsely look like the connectors block was
@@ -1882,7 +1934,9 @@ Handle this as a priority request from a colleague.`;
1882
1934
  if (connectorsChanged) {
1883
1935
  context.suppressNextConnectorReload?.();
1884
1936
  }
1885
- fs.writeFileSync(CONFIG_PATH, yamlStr);
1937
+ // The new revision travels back so the page that just saved is not stale
1938
+ // against its own write.
1939
+ res.setHeader(CONFIG_REVISION_HEADER, writeConfigDocument(snapshot, merged));
1886
1940
  invalidateModelRegistry(); // models/engines may have changed — rebuild on next read
1887
1941
  _resetEngineProbeCache(); // engine bins may have changed — the onboarding probe must re-run
1888
1942
  logger.info("Config updated via API");
@@ -1974,26 +2028,19 @@ Handle this as a priority request from a colleague.`;
1974
2028
  if (!("deliverMessage" in connector)) {
1975
2029
  return json(res, { error: "Discord connector is not in remote mode" }, 400);
1976
2030
  }
1977
- const _parsed = await readJsonBody(req, res);
2031
+ const _parsed = await readJsonBody(req, res, INCOMING_BODY_MAX_BYTES);
1978
2032
  if (!_parsed.ok)
1979
2033
  return;
1980
2034
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1981
2035
  const body = _parsed.body;
1982
- // Download attachments from Discord CDN URLs to local temp
1983
- const { downloadAttachment } = await import("../connectors/discord/format.js");
1984
- const { sanitizeIncomingDiscordMeta } = await import("../connectors/discord/remote.js");
1985
- const attachments = await Promise.all((body.attachments || []).map(async (att) => {
1986
- if (att.url) {
1987
- try {
1988
- const localPath = await downloadAttachment(att.url, TMP_DIR, att.name);
1989
- return { name: att.name, url: att.url, mimeType: att.mimeType, localPath };
1990
- }
1991
- catch {
1992
- return { name: att.name, url: att.url, mimeType: att.mimeType };
1993
- }
1994
- }
1995
- return att;
1996
- }));
2036
+ // Download attachments from Discord CDN URLs to local temp. The names
2037
+ // and URLs are the caller's: only https Discord CDN URLs are fetched.
2038
+ const { downloadIncomingAttachments, routedMessageText, sanitizeIncomingDiscordMeta } = await import("../connectors/discord/remote.js");
2039
+ // Only for a message the connector is going to hand on: one it stays
2040
+ // silent on (respondTo, addressed to somebody else) is not fetched first.
2041
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2042
+ const wanted = connector.willDeliver?.(sanitizeIncomingDiscordMeta(body.transportMeta)) ?? true;
2043
+ const fetched = wanted ? await downloadIncomingAttachments(body.attachments, newAttachmentDir()) : { attachments: [], failed: [] };
1997
2044
  const incomingMsg = {
1998
2045
  connector: params.id,
1999
2046
  source: "discord",
@@ -2002,9 +2049,9 @@ Handle this as a priority request from a colleague.`;
2002
2049
  thread: body.thread,
2003
2050
  user: body.user,
2004
2051
  userId: body.userId,
2005
- text: body.text,
2052
+ text: routedMessageText(body.text, fetched.failed), // says which attachments were not fetched
2006
2053
  messageId: body.messageId,
2007
- attachments,
2054
+ attachments: fetched.attachments,
2008
2055
  replyContext: body.replyContext || {},
2009
2056
  // Boundary scrub: this endpoint carries Discord traffic — drop
2010
2057
  // cross-platform identity fields a forged payload might smuggle in.
@@ -2189,23 +2236,18 @@ Handle this as a priority request from a colleague.`;
2189
2236
  // the portal to its defaults.
2190
2237
  const config = context.getConfig();
2191
2238
  const provided = (v) => typeof v === "string" && v.trim() !== "";
2192
- const portalPatch = {
2193
- ...config.portal,
2239
+ // Patch only the portal block — a whole-file yaml.dump would strip
2240
+ // every comment the shipped config template carries. The block on disk
2241
+ // is what gets patched, not the in-memory one: see savePortalBlock.
2242
+ const portalPatch = savePortalBlock({
2194
2243
  onboarded: true,
2195
2244
  ...(provided(portalName) && { portalName }),
2196
2245
  ...(provided(operatorName) && { operatorName }),
2197
2246
  ...(provided(language) && { language }),
2198
- };
2247
+ }, config.portal);
2199
2248
  const updated = { ...config, portal: portalPatch };
2200
- // Patch only the portal block — a whole-file yaml.dump would strip
2201
- // every comment the shipped config template carries.
2202
- const rawConfig = fs.existsSync(CONFIG_PATH) ? fs.readFileSync(CONFIG_PATH, "utf-8") : "";
2203
- writeFileAtomic(CONFIG_PATH, patchPortalSection(rawConfig, portalPatch));
2204
2249
  logger.info(`Onboarding: portal name="${portalName}", operator="${operatorName}", language="${language}"`);
2205
2250
  const effectiveName = resolveEffectiveName(portalName, config.portal?.portalName);
2206
- const languageSection = language && language !== "English"
2207
- ? `\n\n## Language\nAlways respond in ${language}. All communication with the user must be in ${language}.`
2208
- : "";
2209
2251
  // Update CLAUDE.md / AGENTS.md: language section always; the name only
2210
2252
  // when this request actually carries one (a language-only update must
2211
2253
  // not rename a customized assistant back to the default).
@@ -2217,12 +2259,7 @@ Handle this as a priority request from a colleague.`;
2217
2259
  if (provided(portalName)) {
2218
2260
  md = personalizeInstructionMd(md, effectiveName);
2219
2261
  }
2220
- // Remove existing language section if present, then add new one if needed
2221
- md = md.replace(/\n\n## Language\nAlways respond in .+\. All communication with the user must be in .+\./m, "");
2222
- if (languageSection) {
2223
- md = md.trimEnd() + languageSection + "\n";
2224
- }
2225
- writeFileAtomic(mdPath, md);
2262
+ writeFileAtomic(mdPath, applyLanguageSection(md, language));
2226
2263
  }
2227
2264
  // Keep the persona file's Name section in sync
2228
2265
  const identityMdPath = path.join(JINN_HOME, "IDENTITY.md");
@@ -2247,16 +2284,7 @@ Handle this as a priority request from a colleague.`;
2247
2284
  }).then(() => {
2248
2285
  // Update config to mark STT as enabled
2249
2286
  try {
2250
- const raw = fs.readFileSync(CONFIG_PATH, "utf-8");
2251
- const cfg = yaml.load(raw);
2252
- if (!cfg.stt || typeof cfg.stt !== "object")
2253
- cfg.stt = {};
2254
- const sttCfg = cfg.stt;
2255
- sttCfg.enabled = true;
2256
- sttCfg.model = model;
2257
- if (!sttCfg.languages)
2258
- sttCfg.languages = ["en"];
2259
- fs.writeFileSync(CONFIG_PATH, yaml.dump(cfg, { lineWidth: -1 }));
2287
+ markSttModelInstalled(model);
2260
2288
  }
2261
2289
  catch (err) {
2262
2290
  logger.error(`Failed to update config after STT download: ${err}`);
@@ -2320,15 +2348,7 @@ Handle this as a priority request from a colleague.`;
2320
2348
  return badRequest(res, `Invalid language codes: ${invalid.join(", ")}`);
2321
2349
  }
2322
2350
  try {
2323
- const raw = fs.readFileSync(CONFIG_PATH, "utf-8");
2324
- const cfg = yaml.load(raw);
2325
- if (!cfg.stt || typeof cfg.stt !== "object")
2326
- cfg.stt = {};
2327
- const sttCfg = cfg.stt;
2328
- sttCfg.languages = langs;
2329
- // Remove deprecated language field if present
2330
- delete sttCfg.language;
2331
- fs.writeFileSync(CONFIG_PATH, yaml.dump(cfg, { lineWidth: -1 }));
2351
+ saveSttLanguages(langs);
2332
2352
  return json(res, { status: "ok", languages: langs });
2333
2353
  }
2334
2354
  catch (err) {
@@ -2430,13 +2450,9 @@ Handle this as a priority request from a colleague.`;
2430
2450
  if (!_parsed.ok)
2431
2451
  return;
2432
2452
  const body = _parsed.body;
2433
- let existing = {};
2434
- try {
2435
- existing = yaml.load(fs.readFileSync(CONFIG_PATH, "utf-8")) || {};
2436
- }
2437
- catch { /* start fresh if unreadable */ }
2438
- const merged = deepMerge(existing, { budgets: { employees: body } });
2439
- fs.writeFileSync(CONFIG_PATH, yaml.dump(merged));
2453
+ const snapshot = readConfigSnapshot();
2454
+ const merged = deepMerge(snapshot.document, { budgets: { employees: body } });
2455
+ writeConfigDocument(snapshot, merged);
2440
2456
  logger.info("Budget limits updated via API");
2441
2457
  return json(res, { status: "ok" });
2442
2458
  }
@@ -2791,7 +2807,7 @@ deliverToConnector) {
2791
2807
  });
2792
2808
  if (shouldStop())
2793
2809
  return;
2794
- const result = fallback.result;
2810
+ const result = failLimitThatOutlastsTheWait(fallback);
2795
2811
  const wasInterrupted = result.error?.startsWith("Interrupted");
2796
2812
  const rateLimit = !wasInterrupted ? detectRateLimit(result) : { limited: false };
2797
2813
  if (rateLimit.limited && fallback.engine.name === "claude")
@@ -2801,7 +2817,7 @@ deliverToConnector) {
2801
2817
  const engineLabel = fallback.engine.name;
2802
2818
  // Otherwise: wait until reset and retry automatically
2803
2819
  const { delayMs, resumeAt } = computeNextRetryDelayMs(rateLimit.resetsAt);
2804
- const deadlineMs = computeRateLimitDeadlineMs(rateLimit.resetsAt, rateLimit.resetsAt ? 30 * 60_000 : 6 * 60 * 60_000);
2820
+ const deadlineMs = computeRateLimitDeadlineMs(rateLimit.resetsAt, rateLimit.resetsAt ? 30 * 60_000 : MAX_USAGE_LIMIT_WAIT_MS);
2805
2821
  const resumeText = resumeAt
2806
2822
  ? resumeAt.toLocaleString("en-GB", { weekday: "short", day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit" })
2807
2823
  : null;
@@ -2848,11 +2864,18 @@ deliverToConnector) {
2848
2864
  return;
2849
2865
  }
2850
2866
  logger.info(`Web session ${currentSession.id} retrying after usage limit (attempt ${attempt})`);
2851
- const retryResult = await runTurn(engine, { ...initialOpts, prompt,
2867
+ const retried = await runTurn(engine, { ...initialOpts, prompt,
2852
2868
  resumeSessionId: current.engineSessionId ?? undefined,
2853
2869
  });
2854
2870
  if (shouldStop())
2855
2871
  return;
2872
+ // Told that the next reset is further off than a turn waits for, the
2873
+ // wait ends the way a turn that starts on such a limit does: failed
2874
+ // now, with the reset time for its error — not slept through.
2875
+ const retryResult = failLimitThatOutlastsTheWait({ result: retried, engine, attempted: false, session: currentSession });
2876
+ if (stoppedByShutdown(retryResult))
2877
+ return; // not an outcome of the turn: the next start resumes it
2878
+ const gaveUp = retryResult !== retried;
2856
2879
  const retryInterrupted = retryResult.error?.startsWith("Interrupted");
2857
2880
  const retryRateLimit = !retryInterrupted ? detectRateLimit(retryResult) : { limited: false };
2858
2881
  if (retryRateLimit.limited) {
@@ -2885,8 +2908,12 @@ deliverToConnector) {
2885
2908
  ...(typeof retryResult.contextTokens === "number" ? { lastContextTokens: retryResult.contextTokens } : {}),
2886
2909
  });
2887
2910
  if (completedAfterRetry) {
2888
- notifyRateLimitResumed(completedAfterRetry);
2889
- notifyDiscordChannel(`✅ ${engineLabel} usage limit cleared. Session ${currentSession.id}${currentSession.employee ? ` (${currentSession.employee})` : ""} resumed.`);
2911
+ // A wait that was given up did not end with the limit clearing.
2912
+ if (!gaveUp)
2913
+ notifyRateLimitResumed(completedAfterRetry);
2914
+ notifyDiscordChannel(gaveUp
2915
+ ? `❌ ${engineLabel} usage limit did not clear in time. Session ${currentSession.id}${currentSession.employee ? ` (${currentSession.employee})` : ""} has been stopped.`
2916
+ : `✅ ${engineLabel} usage limit cleared. Session ${currentSession.id}${currentSession.employee ? ` (${currentSession.employee})` : ""} resumed.`);
2890
2917
  notifyParentSession(completedAfterRetry, { result: retryResult.result, error: retryResult.error ?? null, cost: retryResult.cost, durationMs: retryResult.durationMs }, { alwaysNotify: employee?.alwaysNotify });
2891
2918
  if (deliverToConnector && retryResult.result && (!retryResult.error || retryResult.retryable === false)) {
2892
2919
  const delivery = await deliverToOriginConnector(completedAfterRetry, retryResult.result, context.connectors);
@@ -2903,7 +2930,7 @@ deliverToConnector) {
2903
2930
  cost: retryResult.cost,
2904
2931
  durationMs: retryResult.durationMs,
2905
2932
  });
2906
- logger.info(`Web session ${currentSession.id} resumed after usage reset`);
2933
+ logger.info(`Web session ${currentSession.id} ${gaveUp ? "stopped waiting: the next usage reset is too far off" : "resumed after usage reset"}`);
2907
2934
  return;
2908
2935
  }
2909
2936
  // Exhausted waiting window
@@ -3143,16 +3170,18 @@ async function verifySlackTokens(botToken, appToken) {
3143
3170
  }
3144
3171
  /** Merge a patch into config.yaml and reload connectors — the same steps
3145
3172
  * PUT /api/config performs, callable from a server-side flow that has to
3146
- * read the outcome and possibly undo the write. */
3173
+ * read the outcome and possibly undo the write. `revision` identifies the
3174
+ * file as this write left it. */
3147
3175
  async function writeConfigPatchAndReload(context, patch) {
3148
- let existing = {};
3149
- try {
3150
- existing = yaml.load(fs.readFileSync(CONFIG_PATH, "utf-8")) || {};
3151
- }
3152
- catch { /* first write */ }
3153
- const merged = deepMerge(existing, patch);
3176
+ const snapshot = readConfigSnapshot();
3177
+ const merged = deepMerge(snapshot.document, patch);
3154
3178
  context.suppressNextConnectorReload?.();
3155
- fs.writeFileSync(CONFIG_PATH, yaml.dump(merged));
3179
+ const revision = writeConfigDocument(snapshot, merged);
3180
+ return { ...(await reloadAfterConfigWrite(context)), revision };
3181
+ }
3182
+ /** config.yaml was just written (with the watcher's connector reload
3183
+ * suppressed): drop the caches built from it and reload the connectors. */
3184
+ async function reloadAfterConfigWrite(context) {
3156
3185
  invalidateModelRegistry();
3157
3186
  _resetEngineProbeCache();
3158
3187
  if (!context.reloadAllConnectors)
@@ -3181,15 +3210,6 @@ function slackFailure(outcome) {
3181
3210
  return errors.join(" | ");
3182
3211
  return null;
3183
3212
  }
3184
- function readSlackBlock() {
3185
- try {
3186
- const current = yaml.load(fs.readFileSync(CONFIG_PATH, "utf-8")) || {};
3187
- return current.connectors?.slack ?? null;
3188
- }
3189
- catch {
3190
- return null;
3191
- }
3192
- }
3193
3213
  async function connectSlack(context, botToken, appToken) {
3194
3214
  const verified = await verifySlackTokens(botToken, appToken);
3195
3215
  if (!verified.ok)
@@ -3198,18 +3218,19 @@ async function connectSlack(context, botToken, appToken) {
3198
3218
  // /api/config or a second connect waits for it, so the snapshot we would
3199
3219
  // restore can never be older than what a concurrent writer put down.
3200
3220
  return withConfigLock(async () => {
3201
- const previousSlack = readSlackBlock();
3202
- const previous = previousSlack ? "config" : "none";
3221
+ // The file exactly as it is before this attempt: what a rollback puts back.
3222
+ const before = readConfigSnapshot();
3223
+ const previous = slackBlockOf(before.document) ? "config" : "none";
3203
3224
  const outcome = await writeConfigPatchAndReload(context, { connectors: { slack: { botToken, appToken } } });
3204
3225
  const failure = slackFailure(outcome);
3205
3226
  if (!failure)
3206
3227
  return { ok: true, team: verified.bot.team, user: verified.bot.user };
3207
3228
  // The connector did not come up on tokens Slack itself accepted. Put the
3208
- // previous configuration back (or remove the block if there was none) —
3209
- // but only if the block on disk is still OURS: an out-of-band editor may
3210
- // have written something else meanwhile, and that is theirs to keep.
3211
- const onDisk = readSlackBlock();
3212
- if (onDisk?.botToken !== botToken || onDisk?.appToken !== appToken) {
3229
+ // file back as it was before the attempt — but only if the block on disk
3230
+ // is still OURS: an out-of-band editor may have written something else
3231
+ // meanwhile, and that is theirs to keep.
3232
+ const current = snapshotStillHoldingSlackTokens(botToken, appToken);
3233
+ if (!current) {
3213
3234
  logger.warn(`[onboarding] Slack connect failed (${failure}) but the Slack config changed concurrently — leaving it as is`);
3214
3235
  return { ok: false, stage: "reload", error: failure, previous, rolledBack: false,
3215
3236
  restored: { disk: false, running: false }, rollbackSkipped: "config changed concurrently" };
@@ -3217,9 +3238,12 @@ async function connectSlack(context, botToken, appToken) {
3217
3238
  logger.warn(`[onboarding] Slack connect failed after save (${failure}) — ${previous === "config" ? "restoring previous Slack config" : "removing the Slack block again"}`);
3218
3239
  let rollback;
3219
3240
  try {
3220
- rollback = await writeConfigPatchAndReload(context, { connectors: { slack: previousSlack ?? null } });
3241
+ context.suppressNextConnectorReload?.();
3242
+ restoreBeforeSlackConnect(before, current, outcome.revision);
3243
+ rollback = await reloadAfterConfigWrite(context);
3221
3244
  }
3222
3245
  catch (err) {
3246
+ context.clearSuppressNextConnectorReload?.(); // nothing was written for the watcher to skip
3223
3247
  const rollbackError = err instanceof Error ? err.message : String(err);
3224
3248
  logger.error(`[onboarding] Slack rollback write failed: ${rollbackError}`);
3225
3249
  return { ok: false, stage: "reload", error: failure, previous, rolledBack: false,