@ashx-j/lunr-dev 0.2.13-dev.8.1 → 0.2.19-dev.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (484) hide show
  1. package/CHANGELOG.md +60 -1
  2. package/README.md +7 -1
  3. package/dist/builtin-extensions/ashxj-thinking.d.ts +1 -0
  4. package/dist/builtin-extensions/ashxj-thinking.d.ts.map +1 -1
  5. package/dist/builtin-extensions/ashxj-thinking.js +44 -19
  6. package/dist/builtin-extensions/ashxj-thinking.js.map +1 -1
  7. package/dist/builtin-extensions/ashxj-tui.d.ts +14 -0
  8. package/dist/builtin-extensions/ashxj-tui.d.ts.map +1 -1
  9. package/dist/builtin-extensions/ashxj-tui.js +37 -3
  10. package/dist/builtin-extensions/ashxj-tui.js.map +1 -1
  11. package/dist/builtin-extensions/index.d.ts +1 -15
  12. package/dist/builtin-extensions/index.d.ts.map +1 -1
  13. package/dist/builtin-extensions/index.js +8 -21
  14. package/dist/builtin-extensions/index.js.map +1 -1
  15. package/dist/builtin-extensions/lunr-computer-use.d.ts +3 -0
  16. package/dist/builtin-extensions/lunr-computer-use.d.ts.map +1 -0
  17. package/dist/builtin-extensions/lunr-computer-use.js +157 -0
  18. package/dist/builtin-extensions/lunr-computer-use.js.map +1 -0
  19. package/dist/builtin-extensions/narumiruna-pi-goal/src/goal.d.ts.map +1 -1
  20. package/dist/builtin-extensions/narumiruna-pi-goal/src/goal.js +6 -2
  21. package/dist/builtin-extensions/narumiruna-pi-goal/src/goal.js.map +1 -1
  22. package/dist/builtin-extensions/pi-lsp-extension/src/index.d.ts +4 -0
  23. package/dist/builtin-extensions/pi-lsp-extension/src/index.d.ts.map +1 -1
  24. package/dist/builtin-extensions/pi-lsp-extension/src/index.js +172 -171
  25. package/dist/builtin-extensions/pi-lsp-extension/src/index.js.map +1 -1
  26. package/dist/builtin-extensions/pi-lsp-extension/src/runtime.d.ts +50 -0
  27. package/dist/builtin-extensions/pi-lsp-extension/src/runtime.d.ts.map +1 -0
  28. package/dist/builtin-extensions/pi-lsp-extension/src/runtime.js +131 -0
  29. package/dist/builtin-extensions/pi-lsp-extension/src/runtime.js.map +1 -0
  30. package/dist/builtin-extensions/pi-mcp-adapter/direct-tool-executor.d.ts +7 -0
  31. package/dist/builtin-extensions/pi-mcp-adapter/direct-tool-executor.d.ts.map +1 -0
  32. package/dist/builtin-extensions/pi-mcp-adapter/direct-tool-executor.js +211 -0
  33. package/dist/builtin-extensions/pi-mcp-adapter/direct-tool-executor.js.map +1 -0
  34. package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.d.ts +0 -5
  35. package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.d.ts.map +1 -1
  36. package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.js +0 -202
  37. package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.js.map +1 -1
  38. package/dist/builtin-extensions/pi-mcp-adapter/index.d.ts.map +1 -1
  39. package/dist/builtin-extensions/pi-mcp-adapter/index.js +276 -109
  40. package/dist/builtin-extensions/pi-mcp-adapter/index.js.map +1 -1
  41. package/dist/builtin-extensions/pi-mcp-adapter/init.d.ts +4 -1
  42. package/dist/builtin-extensions/pi-mcp-adapter/init.d.ts.map +1 -1
  43. package/dist/builtin-extensions/pi-mcp-adapter/init.js +10 -3
  44. package/dist/builtin-extensions/pi-mcp-adapter/init.js.map +1 -1
  45. package/dist/builtin-extensions/pi-mcp-adapter/metadata-cache.d.ts.map +1 -1
  46. package/dist/builtin-extensions/pi-mcp-adapter/metadata-cache.js +6 -1
  47. package/dist/builtin-extensions/pi-mcp-adapter/metadata-cache.js.map +1 -1
  48. package/dist/builtin-extensions/pi-mcp-adapter/server-manager.d.ts +6 -1
  49. package/dist/builtin-extensions/pi-mcp-adapter/server-manager.d.ts.map +1 -1
  50. package/dist/builtin-extensions/pi-mcp-adapter/server-manager.js +33 -8
  51. package/dist/builtin-extensions/pi-mcp-adapter/server-manager.js.map +1 -1
  52. package/dist/builtin-extensions/pi-prompt-template-model/prompt-loader.d.ts.map +1 -1
  53. package/dist/builtin-extensions/pi-prompt-template-model/prompt-loader.js +2 -1
  54. package/dist/builtin-extensions/pi-prompt-template-model/prompt-loader.js.map +1 -1
  55. package/dist/builtin-extensions/pi-prompt-template-model/tool-manager.d.ts +1 -1
  56. package/dist/builtin-extensions/pi-prompt-template-model/tool-manager.d.ts.map +1 -1
  57. package/dist/builtin-extensions/pi-prompt-template-model/tool-manager.js +1 -1
  58. package/dist/builtin-extensions/pi-prompt-template-model/tool-manager.js.map +1 -1
  59. package/dist/builtin-extensions/pi-subagents/src/extension/index.d.ts +1 -1
  60. package/dist/builtin-extensions/pi-subagents/src/extension/index.d.ts.map +1 -1
  61. package/dist/builtin-extensions/pi-subagents/src/extension/index.js +68 -15
  62. package/dist/builtin-extensions/pi-subagents/src/extension/index.js.map +1 -1
  63. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.d.ts.map +1 -1
  64. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js +6 -2
  65. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js.map +1 -1
  66. package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.d.ts +1 -1
  67. package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.d.ts.map +1 -1
  68. package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.js +5 -2
  69. package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.js.map +1 -1
  70. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/request-params.d.ts +10 -0
  71. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/request-params.d.ts.map +1 -0
  72. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/request-params.js +38 -0
  73. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/request-params.js.map +1 -0
  74. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts.map +1 -1
  75. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js +3 -16
  76. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js.map +1 -1
  77. package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.d.ts +1 -1
  78. package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.d.ts.map +1 -1
  79. package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.js +2 -0
  80. package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.js.map +1 -1
  81. package/dist/builtin-extensions/pi-subagents/src/shared/fork-context.d.ts.map +1 -1
  82. package/dist/builtin-extensions/pi-subagents/src/shared/fork-context.js +1 -1
  83. package/dist/builtin-extensions/pi-subagents/src/shared/fork-context.js.map +1 -1
  84. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.d.ts +1 -1
  85. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.d.ts.map +1 -1
  86. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js +1 -1
  87. package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js.map +1 -1
  88. package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts +2 -1
  89. package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts.map +1 -1
  90. package/dist/builtin-extensions/pi-subagents/src/tui/render.js +72 -31
  91. package/dist/builtin-extensions/pi-subagents/src/tui/render.js.map +1 -1
  92. package/dist/builtin-extensions/pi-subagents/src/watchdog/review.d.ts +1 -1
  93. package/dist/builtin-extensions/pi-subagents/src/watchdog/review.d.ts.map +1 -1
  94. package/dist/builtin-extensions/pi-subagents/src/watchdog/review.js +2 -1
  95. package/dist/builtin-extensions/pi-subagents/src/watchdog/review.js.map +1 -1
  96. package/dist/builtin-extensions/pi-web-access/extract.d.ts.map +1 -1
  97. package/dist/builtin-extensions/pi-web-access/extract.js +105 -54
  98. package/dist/builtin-extensions/pi-web-access/extract.js.map +1 -1
  99. package/dist/builtin-extensions/pi-web-access/gemini-search.d.ts +1 -1
  100. package/dist/builtin-extensions/pi-web-access/gemini-search.d.ts.map +1 -1
  101. package/dist/builtin-extensions/pi-web-access/gemini-search.js +82 -65
  102. package/dist/builtin-extensions/pi-web-access/gemini-search.js.map +1 -1
  103. package/dist/builtin-extensions/pi-web-access/github-extract.d.ts.map +1 -1
  104. package/dist/builtin-extensions/pi-web-access/github-extract.js +2 -0
  105. package/dist/builtin-extensions/pi-web-access/github-extract.js.map +1 -1
  106. package/dist/builtin-extensions/pi-web-access/index.d.ts.map +1 -1
  107. package/dist/builtin-extensions/pi-web-access/index.js +259 -168
  108. package/dist/builtin-extensions/pi-web-access/index.js.map +1 -1
  109. package/dist/builtin-extensions/pi-web-access/lazy.d.ts +18 -0
  110. package/dist/builtin-extensions/pi-web-access/lazy.d.ts.map +1 -0
  111. package/dist/builtin-extensions/pi-web-access/lazy.js +19 -0
  112. package/dist/builtin-extensions/pi-web-access/lazy.js.map +1 -0
  113. package/dist/builtin-extensions/pi-web-access/session-cleanup.d.ts +6 -0
  114. package/dist/builtin-extensions/pi-web-access/session-cleanup.d.ts.map +1 -0
  115. package/dist/builtin-extensions/pi-web-access/session-cleanup.js +17 -0
  116. package/dist/builtin-extensions/pi-web-access/session-cleanup.js.map +1 -0
  117. package/dist/catalog/publication.json +12 -12
  118. package/dist/cli-runtime.d.ts +3 -0
  119. package/dist/cli-runtime.d.ts.map +1 -0
  120. package/dist/cli-runtime.js +73 -0
  121. package/dist/cli-runtime.js.map +1 -0
  122. package/dist/cli.d.ts.map +1 -1
  123. package/dist/cli.js +14 -53
  124. package/dist/cli.js.map +1 -1
  125. package/dist/config.d.ts +1 -0
  126. package/dist/config.d.ts.map +1 -1
  127. package/dist/config.js +1 -0
  128. package/dist/config.js.map +1 -1
  129. package/dist/core/agent-session-services.d.ts.map +1 -1
  130. package/dist/core/agent-session-services.js +1 -1
  131. package/dist/core/agent-session-services.js.map +1 -1
  132. package/dist/core/agent-session.d.ts +3 -0
  133. package/dist/core/agent-session.d.ts.map +1 -1
  134. package/dist/core/agent-session.js +56 -12
  135. package/dist/core/agent-session.js.map +1 -1
  136. package/dist/core/compaction/compaction.d.ts.map +1 -1
  137. package/dist/core/compaction/compaction.js +10 -5
  138. package/dist/core/compaction/compaction.js.map +1 -1
  139. package/dist/core/computer-use/adapter.d.ts +23 -0
  140. package/dist/core/computer-use/adapter.d.ts.map +1 -0
  141. package/dist/core/computer-use/adapter.js +116 -0
  142. package/dist/core/computer-use/adapter.js.map +1 -0
  143. package/dist/core/computer-use/lease.d.ts +18 -0
  144. package/dist/core/computer-use/lease.d.ts.map +1 -0
  145. package/dist/core/computer-use/lease.js +129 -0
  146. package/dist/core/computer-use/lease.js.map +1 -0
  147. package/dist/core/computer-use/macos-runtime.d.ts +14 -0
  148. package/dist/core/computer-use/macos-runtime.d.ts.map +1 -0
  149. package/dist/core/computer-use/macos-runtime.js +148 -0
  150. package/dist/core/computer-use/macos-runtime.js.map +1 -0
  151. package/dist/core/computer-use/policy.d.ts +19 -0
  152. package/dist/core/computer-use/policy.d.ts.map +1 -0
  153. package/dist/core/computer-use/policy.js +66 -0
  154. package/dist/core/computer-use/policy.js.map +1 -0
  155. package/dist/core/computer-use/release.generated.d.ts +31 -0
  156. package/dist/core/computer-use/release.generated.d.ts.map +1 -0
  157. package/dist/core/computer-use/release.generated.js +36 -0
  158. package/dist/core/computer-use/release.generated.js.map +1 -0
  159. package/dist/core/computer-use/runtime.d.ts +13 -0
  160. package/dist/core/computer-use/runtime.d.ts.map +1 -0
  161. package/dist/core/computer-use/runtime.js +158 -0
  162. package/dist/core/computer-use/runtime.js.map +1 -0
  163. package/dist/core/computer-use/schemas.d.ts +88 -0
  164. package/dist/core/computer-use/schemas.d.ts.map +1 -0
  165. package/dist/core/computer-use/schemas.js +80 -0
  166. package/dist/core/computer-use/schemas.js.map +1 -0
  167. package/dist/core/computer-use/windows-desktop.d.ts +3 -0
  168. package/dist/core/computer-use/windows-desktop.d.ts.map +1 -0
  169. package/dist/core/computer-use/windows-desktop.js +48 -0
  170. package/dist/core/computer-use/windows-desktop.js.map +1 -0
  171. package/dist/core/computer-use/workflow.d.ts +24 -0
  172. package/dist/core/computer-use/workflow.d.ts.map +1 -0
  173. package/dist/core/computer-use/workflow.js +330 -0
  174. package/dist/core/computer-use/workflow.js.map +1 -0
  175. package/dist/core/extensions/host-static.d.ts.map +1 -1
  176. package/dist/core/extensions/host-static.js +34 -12
  177. package/dist/core/extensions/host-static.js.map +1 -1
  178. package/dist/core/extensions/loader.d.ts +1 -2
  179. package/dist/core/extensions/loader.d.ts.map +1 -1
  180. package/dist/core/extensions/loader.js +10 -64
  181. package/dist/core/extensions/loader.js.map +1 -1
  182. package/dist/core/extensions/types.d.ts +2 -2
  183. package/dist/core/extensions/types.d.ts.map +1 -1
  184. package/dist/core/extensions/types.js.map +1 -1
  185. package/dist/core/footer-data-provider.d.ts.map +1 -1
  186. package/dist/core/footer-data-provider.js +2 -0
  187. package/dist/core/footer-data-provider.js.map +1 -1
  188. package/dist/core/keybindings.d.ts +2 -2
  189. package/dist/core/keybindings.d.ts.map +1 -1
  190. package/dist/core/keybindings.js +2 -2
  191. package/dist/core/keybindings.js.map +1 -1
  192. package/dist/core/model-runtime.d.ts +0 -3
  193. package/dist/core/model-runtime.d.ts.map +1 -1
  194. package/dist/core/model-runtime.js +1 -10
  195. package/dist/core/model-runtime.js.map +1 -1
  196. package/dist/core/package-manager.d.ts.map +1 -1
  197. package/dist/core/package-manager.js +1 -1
  198. package/dist/core/package-manager.js.map +1 -1
  199. package/dist/core/permissions.d.ts +1 -3
  200. package/dist/core/permissions.d.ts.map +1 -1
  201. package/dist/core/permissions.js +33 -25
  202. package/dist/core/permissions.js.map +1 -1
  203. package/dist/core/plan-mode.d.ts.map +1 -1
  204. package/dist/core/plan-mode.js +9 -0
  205. package/dist/core/plan-mode.js.map +1 -1
  206. package/dist/core/rollback.d.ts.map +1 -1
  207. package/dist/core/rollback.js +13 -90
  208. package/dist/core/rollback.js.map +1 -1
  209. package/dist/core/sdk.d.ts +1 -1
  210. package/dist/core/sdk.d.ts.map +1 -1
  211. package/dist/core/sdk.js +1 -1
  212. package/dist/core/sdk.js.map +1 -1
  213. package/dist/core/session-manager.d.ts +0 -1
  214. package/dist/core/session-manager.d.ts.map +1 -1
  215. package/dist/core/session-manager.js +21 -79
  216. package/dist/core/session-manager.js.map +1 -1
  217. package/dist/core/settings-manager.d.ts +6 -0
  218. package/dist/core/settings-manager.d.ts.map +1 -1
  219. package/dist/core/settings-manager.js +19 -0
  220. package/dist/core/settings-manager.js.map +1 -1
  221. package/dist/core/slash-commands.d.ts.map +1 -1
  222. package/dist/core/slash-commands.js +0 -1
  223. package/dist/core/slash-commands.js.map +1 -1
  224. package/dist/core/timings.d.ts +2 -1
  225. package/dist/core/timings.d.ts.map +1 -1
  226. package/dist/core/timings.js +17 -2
  227. package/dist/core/timings.js.map +1 -1
  228. package/dist/dev-cli.js +0 -0
  229. package/dist/gateway/agent-bridge.d.ts +6 -1
  230. package/dist/gateway/agent-bridge.d.ts.map +1 -1
  231. package/dist/gateway/agent-bridge.js +23 -6
  232. package/dist/gateway/agent-bridge.js.map +1 -1
  233. package/dist/gateway/commands.d.ts +1 -1
  234. package/dist/gateway/commands.d.ts.map +1 -1
  235. package/dist/gateway/commands.js +1 -18
  236. package/dist/gateway/commands.js.map +1 -1
  237. package/dist/gateway/cron.d.ts +1 -1
  238. package/dist/gateway/cron.d.ts.map +1 -1
  239. package/dist/gateway/cron.js +23 -7
  240. package/dist/gateway/cron.js.map +1 -1
  241. package/dist/main.d.ts +2 -2
  242. package/dist/main.d.ts.map +1 -1
  243. package/dist/main.js +57 -48
  244. package/dist/main.js.map +1 -1
  245. package/dist/modes/interactive/components/footer.d.ts +4 -2
  246. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  247. package/dist/modes/interactive/components/footer.js +23 -32
  248. package/dist/modes/interactive/components/footer.js.map +1 -1
  249. package/dist/modes/interactive/components/processes-selector.d.ts +2 -3
  250. package/dist/modes/interactive/components/processes-selector.d.ts.map +1 -1
  251. package/dist/modes/interactive/components/processes-selector.js +5 -10
  252. package/dist/modes/interactive/components/processes-selector.js.map +1 -1
  253. package/dist/modes/interactive/components/settings-selector.d.ts +4 -0
  254. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  255. package/dist/modes/interactive/components/settings-selector.js +20 -0
  256. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  257. package/dist/modes/interactive/interactive-mode.d.ts +12 -21
  258. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  259. package/dist/modes/interactive/interactive-mode.js +138 -152
  260. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  261. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  262. package/dist/modes/interactive/theme/theme.js +95 -84
  263. package/dist/modes/interactive/theme/theme.js.map +1 -1
  264. package/dist/modes/interactive/thinking-level-slash.d.ts +4 -0
  265. package/dist/modes/interactive/thinking-level-slash.d.ts.map +1 -0
  266. package/dist/modes/interactive/thinking-level-slash.js +23 -0
  267. package/dist/modes/interactive/thinking-level-slash.js.map +1 -0
  268. package/dist/node-runtime/adapter-AZMY335J.js +279 -0
  269. package/dist/node-runtime/agent-session-services-RSGP5GDN.js +39 -0
  270. package/dist/node-runtime/benchmark-request-UC7PD3V3.js +57 -0
  271. package/dist/node-runtime/brave-UWDA3I22.js +143 -0
  272. package/dist/node-runtime/builtin-extensions-7STLFW3A.js +29 -0
  273. package/dist/node-runtime/chunk-2IDTZAG5.js +1415 -0
  274. package/dist/node-runtime/chunk-3GHXVUAK.js +21 -0
  275. package/dist/node-runtime/chunk-3RCWXWAY.js +466 -0
  276. package/dist/node-runtime/chunk-3WFAEVKS.js +115 -0
  277. package/dist/node-runtime/chunk-3X3KZKMI.js +49 -0
  278. package/dist/node-runtime/chunk-4HXHDDCF.js +16 -0
  279. package/dist/node-runtime/chunk-4SJWFTUP.js +24 -0
  280. package/dist/node-runtime/chunk-4ZWGEEAS.js +69 -0
  281. package/dist/node-runtime/chunk-53YJI7JU.js +137 -0
  282. package/dist/node-runtime/chunk-5NWQCSKR.js +19218 -0
  283. package/dist/node-runtime/chunk-5OLJGVCB.js +68 -0
  284. package/dist/node-runtime/chunk-5Q45AVQG.js +108 -0
  285. package/dist/node-runtime/chunk-5SQDLSZJ.js +949 -0
  286. package/dist/node-runtime/chunk-6SPPH4FY.js +1269 -0
  287. package/dist/node-runtime/chunk-6UB6NKA3.js +860 -0
  288. package/dist/node-runtime/chunk-7AFOFSDY.js +105 -0
  289. package/dist/node-runtime/chunk-7N3YHTYF.js +26 -0
  290. package/dist/node-runtime/chunk-ARC4KOTI.js +11178 -0
  291. package/dist/node-runtime/chunk-AUXVGBO4.js +19 -0
  292. package/dist/node-runtime/chunk-AY6CAJSL.js +30 -0
  293. package/dist/node-runtime/chunk-BHO7O6E5.js +296 -0
  294. package/dist/node-runtime/chunk-BI3DHYCN.js +8845 -0
  295. package/dist/node-runtime/chunk-BKAZ6BKX.js +2185 -0
  296. package/dist/node-runtime/chunk-BR7YDUKA.js +109 -0
  297. package/dist/node-runtime/chunk-BRJX2PRC.js +53 -0
  298. package/dist/node-runtime/chunk-C4O2RSQQ.js +37 -0
  299. package/dist/node-runtime/chunk-CCZJ3PYY.js +17 -0
  300. package/dist/node-runtime/chunk-CGBXPL3E.js +1171 -0
  301. package/dist/node-runtime/chunk-CH6OL6P2.js +295 -0
  302. package/dist/node-runtime/chunk-CJECDQKP.js +19 -0
  303. package/dist/node-runtime/chunk-DAPBPCBP.js +53 -0
  304. package/dist/node-runtime/chunk-DDGMHUOW.js +305 -0
  305. package/dist/node-runtime/chunk-DMMTJQMQ.js +43 -0
  306. package/dist/node-runtime/chunk-DVGWF6A2.js +1180 -0
  307. package/dist/node-runtime/chunk-EH2LJQPM.js +64 -0
  308. package/dist/node-runtime/chunk-EHMBW7FA.js +772 -0
  309. package/dist/node-runtime/chunk-FLYMHKCS.js +966 -0
  310. package/dist/node-runtime/chunk-FVDOXRUD.js +96 -0
  311. package/dist/node-runtime/chunk-GZQHMEWL.js +126 -0
  312. package/dist/node-runtime/chunk-H2EOZYMP.js +57 -0
  313. package/dist/node-runtime/chunk-HQCKFM2O.js +56 -0
  314. package/dist/node-runtime/chunk-HRS4HMDX.js +610 -0
  315. package/dist/node-runtime/chunk-HYHJIRDW.js +19 -0
  316. package/dist/node-runtime/chunk-I6R76AG7.js +22 -0
  317. package/dist/node-runtime/chunk-ISQDQIZN.js +296 -0
  318. package/dist/node-runtime/chunk-J7QGQD45.js +24921 -0
  319. package/dist/node-runtime/chunk-JHYKXIMM.js +378 -0
  320. package/dist/node-runtime/chunk-JT6YCS5B.js +5648 -0
  321. package/dist/node-runtime/chunk-JZHEUQRL.js +180 -0
  322. package/dist/node-runtime/chunk-K72NVGUB.js +2834 -0
  323. package/dist/node-runtime/chunk-KKSIVROT.js +88 -0
  324. package/dist/node-runtime/chunk-LCACDWHJ.js +1743 -0
  325. package/dist/node-runtime/chunk-LTXUQJI4.js +173 -0
  326. package/dist/node-runtime/chunk-LWJXTA6Z.js +6814 -0
  327. package/dist/node-runtime/chunk-M3LZLQW2.js +98 -0
  328. package/dist/node-runtime/chunk-MGSB2C3M.js +46 -0
  329. package/dist/node-runtime/chunk-MGWCVY6Y.js +47 -0
  330. package/dist/node-runtime/chunk-MJQDX3BA.js +72 -0
  331. package/dist/node-runtime/chunk-MUMMMTW4.js +8392 -0
  332. package/dist/node-runtime/chunk-MX3GJNXJ.js +986 -0
  333. package/dist/node-runtime/chunk-NUIFPZWX.js +209 -0
  334. package/dist/node-runtime/chunk-OBMWP3I5.js +68 -0
  335. package/dist/node-runtime/chunk-OR4L3IB2.js +42 -0
  336. package/dist/node-runtime/chunk-OTT6JMPU.js +807 -0
  337. package/dist/node-runtime/chunk-PCIGF2XK.js +250 -0
  338. package/dist/node-runtime/chunk-PL6JKXWI.js +3622 -0
  339. package/dist/node-runtime/chunk-PVCDKGR6.js +55 -0
  340. package/dist/node-runtime/chunk-Q4Q6D4IY.js +364 -0
  341. package/dist/node-runtime/chunk-Q5ZU2VRT.js +83 -0
  342. package/dist/node-runtime/chunk-QFWG2RVL.js +5477 -0
  343. package/dist/node-runtime/chunk-RQ2Q5IYR.js +72 -0
  344. package/dist/node-runtime/chunk-RQ5DNUNG.js +429 -0
  345. package/dist/node-runtime/chunk-RRIZE6QQ.js +17 -0
  346. package/dist/node-runtime/chunk-SN6G4OU6.js +4753 -0
  347. package/dist/node-runtime/chunk-SWSN6HAB.js +53 -0
  348. package/dist/node-runtime/chunk-T5GM5BFH.js +7558 -0
  349. package/dist/node-runtime/chunk-TAP7QTUT.js +1346 -0
  350. package/dist/node-runtime/chunk-U6C7VTR5.js +2033 -0
  351. package/dist/node-runtime/chunk-URD2SLIT.js +1019 -0
  352. package/dist/node-runtime/chunk-VRB2IYGG.js +53 -0
  353. package/dist/node-runtime/chunk-W3CVH5RX.js +62 -0
  354. package/dist/node-runtime/chunk-W7S2REEG.js +9478 -0
  355. package/dist/node-runtime/chunk-XBWPBZBN.js +125 -0
  356. package/dist/node-runtime/chunk-XTHQ7XR7.js +509 -0
  357. package/dist/node-runtime/chunk-ZCHMJ34K.js +130 -0
  358. package/dist/node-runtime/chunk-ZRDIMBEQ.js +651 -0
  359. package/dist/node-runtime/chunk-ZSEZY3II.js +247 -0
  360. package/dist/node-runtime/cli-runtime.js +81 -0
  361. package/dist/node-runtime/clipboard-OZ63BBC6.js +12 -0
  362. package/dist/node-runtime/clipboard-image-7QR6GXVA.js +13 -0
  363. package/dist/node-runtime/command-6UXQ6XZN.js +13 -0
  364. package/dist/node-runtime/commands-LGR5VT5X.js +293 -0
  365. package/dist/node-runtime/config-FMEOZSWE.js +77 -0
  366. package/dist/node-runtime/curator-server-XCM43VEF.js +3816 -0
  367. package/dist/node-runtime/customize-XEXL2DGQ.js +12 -0
  368. package/dist/node-runtime/direct-tool-executor-TDJS7TBD.js +191 -0
  369. package/dist/node-runtime/exa-LL64QZR2.js +329 -0
  370. package/dist/node-runtime/export-html-E4DT6ZJQ.js +150 -0
  371. package/dist/node-runtime/extension-input-RV5N6APL.js +14 -0
  372. package/dist/node-runtime/extension-selector-CPD5LWDD.js +14 -0
  373. package/dist/node-runtime/extract-IUCVZCWC.js +17 -0
  374. package/dist/node-runtime/file-sync-HCOP2QVF.js +117 -0
  375. package/dist/node-runtime/gateway-3OLC4GQN.js +2139 -0
  376. package/dist/node-runtime/gemini-api-QE7ANVDZ.js +29 -0
  377. package/dist/node-runtime/gemini-search-NCIDF7NE.js +330 -0
  378. package/dist/node-runtime/gemini-url-context-OKIN7AIP.js +103 -0
  379. package/dist/node-runtime/gemini-web-MM446SEH.js +14 -0
  380. package/dist/node-runtime/github-extract-F64RZOEA.js +619 -0
  381. package/dist/node-runtime/goal-CZQ7FFQJ.js +1831 -0
  382. package/dist/node-runtime/image-resize-6ZPBFMWW.js +11 -0
  383. package/dist/node-runtime/index.js +863 -0
  384. package/dist/node-runtime/init-EKE277AG.js +30 -0
  385. package/dist/node-runtime/install-cli-TH7IJJQQ.js +308 -0
  386. package/dist/node-runtime/interactive-mode-S5M26CQ7.js +59 -0
  387. package/dist/node-runtime/interactive-view-N6F4KUIT.js +247 -0
  388. package/dist/node-runtime/lsp-manager-3ASUSO4T.js +1104 -0
  389. package/dist/node-runtime/lunr-computer-use-4X3KUNF4.js +206 -0
  390. package/dist/node-runtime/lunr-cron-KKBOGAEF.js +274 -0
  391. package/dist/node-runtime/main.js +57 -0
  392. package/dist/node-runtime/mcp-auth-flow-YL6RWPYG.js +33 -0
  393. package/dist/node-runtime/mcp-panel-IIGMXQGP.js +501 -0
  394. package/dist/node-runtime/mcp-setup-panel-FEK7663I.js +355 -0
  395. package/dist/node-runtime/memory-cap-3S4XRLNP.js +20 -0
  396. package/dist/node-runtime/model-tiers-NJLHUEGK.js +20 -0
  397. package/dist/node-runtime/openai-search-B3MSNCQA.js +288 -0
  398. package/dist/node-runtime/package-manager-cli-C4EJOO5Q.js +751 -0
  399. package/dist/node-runtime/parallel-AI2MNSCU.js +265 -0
  400. package/dist/node-runtime/parser-manager-TQHWYDH7.js +152 -0
  401. package/dist/node-runtime/pdf-extract-IPE6H4HP.js +57 -0
  402. package/dist/node-runtime/perplexity-QVJW3I35.js +12 -0
  403. package/dist/node-runtime/pi-intercom-EEMBGQID.js +2215 -0
  404. package/dist/node-runtime/pi-mcp-adapter-DPTJGAAL.js +428 -0
  405. package/dist/node-runtime/pi-ollama-cloud-4VZRMULP.js +1440 -0
  406. package/dist/node-runtime/pi-prompt-template-model-4QT4LLXF.js +3946 -0
  407. package/dist/node-runtime/pi-subagents-VKCLYIBY.js +6050 -0
  408. package/dist/node-runtime/pi-web-access-BV6DSZOP.js +1867 -0
  409. package/dist/node-runtime/print-mode-VWIRFDAC.js +12 -0
  410. package/dist/node-runtime/proxy-modes-R64LU6WZ.js +688 -0
  411. package/dist/node-runtime/rpc-entry.js +65 -0
  412. package/dist/node-runtime/rpc-mode-SJNSOA4G.js +13 -0
  413. package/dist/node-runtime/runtime-3SB5ATHQ.js +21 -0
  414. package/dist/node-runtime/runtime-bridges-UJ5WJJLN.js +14 -0
  415. package/dist/node-runtime/session-manager-QEMZBMTM.js +33 -0
  416. package/dist/node-runtime/session-selector-URVJLOTK.js +14 -0
  417. package/dist/node-runtime/settings-manager-K6IPIQTI.js +23 -0
  418. package/dist/node-runtime/src-GPFAU3N6.js +2427 -0
  419. package/dist/node-runtime/subagent-executor-EFLTO32A.js +8501 -0
  420. package/dist/node-runtime/summary-review-YSMXKITO.js +228 -0
  421. package/dist/node-runtime/tavily-WEZFVFP7.js +154 -0
  422. package/dist/node-runtime/timings-UAD5BEAS.js +16 -0
  423. package/dist/node-runtime/tool-renderer-MV5O452K.js +204 -0
  424. package/dist/node-runtime/update-cli-I6OVDRPL.js +75 -0
  425. package/dist/node-runtime/v4-5MNC3H7G.js +424 -0
  426. package/dist/node-runtime/video-extract-ETA5RA7U.js +304 -0
  427. package/dist/node-runtime/workflow-SA34S4VX.js +325 -0
  428. package/dist/node-runtime/workspace-index-6DBXSTJ6.js +163 -0
  429. package/dist/node-runtime/youtube-extract-SRVGNN26.js +264 -0
  430. package/dist/rpc.d.ts +3 -0
  431. package/dist/rpc.d.ts.map +1 -0
  432. package/dist/rpc.js +18 -0
  433. package/dist/rpc.js.map +1 -0
  434. package/dist/startup/benchmark-request.d.ts +3 -0
  435. package/dist/startup/benchmark-request.d.ts.map +1 -0
  436. package/dist/startup/benchmark-request.js +65 -0
  437. package/dist/startup/benchmark-request.js.map +1 -0
  438. package/dist/startup/{interactive-shell.d.ts → interactive-view.d.ts} +18 -18
  439. package/dist/startup/interactive-view.d.ts.map +1 -0
  440. package/dist/startup/{interactive-shell.js → interactive-view.js} +119 -52
  441. package/dist/startup/interactive-view.js.map +1 -0
  442. package/dist/startup/launch-routing.d.ts.map +1 -1
  443. package/dist/startup/launch-routing.js +9 -10
  444. package/dist/startup/launch-routing.js.map +1 -1
  445. package/dist/startup/startup-milestones.d.ts +1 -1
  446. package/dist/startup/startup-milestones.d.ts.map +1 -1
  447. package/dist/startup/startup-milestones.js +3 -2
  448. package/dist/startup/startup-milestones.js.map +1 -1
  449. package/dist/utils/await-with-abort.d.ts +2 -0
  450. package/dist/utils/await-with-abort.d.ts.map +1 -0
  451. package/dist/utils/await-with-abort.js +19 -0
  452. package/dist/utils/await-with-abort.js.map +1 -0
  453. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  454. package/dist/utils/syntax-highlight.js +10 -4
  455. package/dist/utils/syntax-highlight.js.map +1 -1
  456. package/docs/compaction.md +5 -3
  457. package/docs/computer-use.md +277 -0
  458. package/docs/development.md +5 -33
  459. package/docs/features.md +2 -3
  460. package/docs/interactive-startup.md +105 -0
  461. package/docs/keybindings.md +2 -2
  462. package/docs/terminal-setup.md +1 -1
  463. package/docs/usage.md +1 -2
  464. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  465. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  466. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  467. package/examples/extensions/gondolin/package-lock.json +2 -2
  468. package/examples/extensions/gondolin/package.json +1 -1
  469. package/examples/extensions/hidden-thinking-label.ts +1 -1
  470. package/examples/extensions/sandbox/package-lock.json +2 -2
  471. package/examples/extensions/sandbox/package.json +1 -1
  472. package/examples/extensions/with-deps/package-lock.json +2 -2
  473. package/examples/extensions/with-deps/package.json +1 -1
  474. package/install-lock/package-lock.json +3827 -0
  475. package/install-lock/package.json +18 -0
  476. package/native/computer-use/LICENSE.md +21 -0
  477. package/npm-shrinkwrap.json +3808 -0
  478. package/package.json +30 -24
  479. package/dist/core/swarm.d.ts +0 -23
  480. package/dist/core/swarm.d.ts.map +0 -1
  481. package/dist/core/swarm.js +0 -45
  482. package/dist/core/swarm.js.map +0 -1
  483. package/dist/startup/interactive-shell.d.ts.map +0 -1
  484. package/dist/startup/interactive-shell.js.map +0 -1
@@ -0,0 +1,1743 @@
1
+ import { createRequire as __lunrRequire } from "node:module"; const require = __lunrRequire(import.meta.url);
2
+ import {
3
+ chatPlatformDeliverBlockedMessage,
4
+ deliverMentionsChatPlatform,
5
+ isFeatureEnabled,
6
+ platformConfigFor
7
+ } from "./chunk-RQ5DNUNG.js";
8
+ import {
9
+ beginCronFire,
10
+ endCronFire
11
+ } from "./chunk-CJECDQKP.js";
12
+ import {
13
+ processImage
14
+ } from "./chunk-5Q45AVQG.js";
15
+ import {
16
+ createPermissionContext,
17
+ deletePermissionContext
18
+ } from "./chunk-ZRDIMBEQ.js";
19
+ import {
20
+ getAgentDir
21
+ } from "./chunk-PCIGF2XK.js";
22
+
23
+ // packages/coding-agent/dist/core/cron/jobs.js
24
+ import { randomUUID } from "node:crypto";
25
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
26
+ import { homedir } from "node:os";
27
+ import { isAbsolute, join, normalize, resolve } from "node:path";
28
+
29
+ // node_modules/croner/dist/croner.js
30
+ function T(s2) {
31
+ return Date.UTC(s2.y, s2.m - 1, s2.d, s2.h, s2.i, s2.s);
32
+ }
33
+ function D(s2, e) {
34
+ return s2.y === e.y && s2.m === e.m && s2.d === e.d && s2.h === e.h && s2.i === e.i && s2.s === e.s;
35
+ }
36
+ function A(s2, e) {
37
+ let t = new Date(Date.parse(s2));
38
+ if (isNaN(t)) throw new Error("Invalid ISO8601 passed to timezone parser.");
39
+ let r = s2.substring(9);
40
+ return r.includes("Z") || r.includes("+") || r.includes("-") ? b(t.getUTCFullYear(), t.getUTCMonth() + 1, t.getUTCDate(), t.getUTCHours(), t.getUTCMinutes(), t.getUTCSeconds(), "Etc/UTC") : b(t.getFullYear(), t.getMonth() + 1, t.getDate(), t.getHours(), t.getMinutes(), t.getSeconds(), e);
41
+ }
42
+ function v(s2, e, t) {
43
+ return k(A(s2, e), t);
44
+ }
45
+ function k(s2, e) {
46
+ let t = new Date(T(s2)), r = g(t, s2.tz), n = T(s2), i = T(r), a = n - i, o = new Date(t.getTime() + a), h = g(o, s2.tz);
47
+ if (D(h, s2)) {
48
+ let u = new Date(o.getTime() - 36e5), d = g(u, s2.tz);
49
+ return D(d, s2) ? u : o;
50
+ }
51
+ let l = new Date(o.getTime() + T(s2) - T(h)), y = g(l, s2.tz);
52
+ if (D(y, s2)) return l;
53
+ if (e) throw new Error("Invalid date passed to fromTZ()");
54
+ return o.getTime() > l.getTime() ? o : l;
55
+ }
56
+ function g(s2, e) {
57
+ let t, r;
58
+ try {
59
+ t = new Intl.DateTimeFormat("en-US", { timeZone: e, year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric", hour12: !1 }), r = t.formatToParts(s2);
60
+ } catch (i) {
61
+ let a = i instanceof Error ? i.message : String(i);
62
+ throw new RangeError(`toTZ: Invalid timezone '${e}' or date. Please provide a valid IANA timezone (e.g., 'America/New_York', 'Europe/Stockholm'). Original error: ${a}`);
63
+ }
64
+ let n = { year: 0, month: 0, day: 0, hour: 0, minute: 0, second: 0 };
65
+ for (let i of r) (i.type === "year" || i.type === "month" || i.type === "day" || i.type === "hour" || i.type === "minute" || i.type === "second") && (n[i.type] = parseInt(i.value, 10));
66
+ if (isNaN(n.year) || isNaN(n.month) || isNaN(n.day) || isNaN(n.hour) || isNaN(n.minute) || isNaN(n.second)) throw new Error(`toTZ: Failed to parse all date components from timezone '${e}'. This may indicate an invalid date or timezone configuration. Parsed components: ${JSON.stringify(n)}`);
67
+ return n.hour === 24 && (n.hour = 0), { y: n.year, m: n.month, d: n.day, h: n.hour, i: n.minute, s: n.second, tz: e };
68
+ }
69
+ function b(s2, e, t, r, n, i, a) {
70
+ return { y: s2, m: e, d: t, h: r, i: n, s: i, tz: a };
71
+ }
72
+ var O = [1, 2, 4, 8, 16], C = class {
73
+ pattern;
74
+ timezone;
75
+ mode;
76
+ alternativeWeekdays;
77
+ sloppyRanges;
78
+ second;
79
+ minute;
80
+ hour;
81
+ day;
82
+ month;
83
+ dayOfWeek;
84
+ year;
85
+ lastDayOfMonth;
86
+ lastWeekday;
87
+ nearestWeekdays;
88
+ starDOM;
89
+ starDOW;
90
+ starYear;
91
+ useAndLogic;
92
+ constructor(e, t, r) {
93
+ this.pattern = e, this.timezone = t, this.mode = r?.mode ?? "auto", this.alternativeWeekdays = r?.alternativeWeekdays ?? !1, this.sloppyRanges = r?.sloppyRanges ?? !1, this.second = Array(60).fill(0), this.minute = Array(60).fill(0), this.hour = Array(24).fill(0), this.day = Array(31).fill(0), this.month = Array(12).fill(0), this.dayOfWeek = Array(7).fill(0), this.year = Array(1e4).fill(0), this.lastDayOfMonth = !1, this.lastWeekday = !1, this.nearestWeekdays = Array(31).fill(0), this.starDOM = !1, this.starDOW = !1, this.starYear = !1, this.useAndLogic = !1, this.parse();
94
+ }
95
+ parse() {
96
+ if (!(typeof this.pattern == "string" || this.pattern instanceof String)) throw new TypeError("CronPattern: Pattern has to be of type string.");
97
+ this.pattern.indexOf("@") >= 0 && (this.pattern = this.handleNicknames(this.pattern).trim());
98
+ let e = this.pattern.match(/\S+/g) || [""], t = e.length;
99
+ if (e.length < 5 || e.length > 7) throw new TypeError("CronPattern: invalid configuration format ('" + this.pattern + "'), exactly five, six, or seven space separated parts are required.");
100
+ if (this.mode !== "auto") {
101
+ let n;
102
+ switch (this.mode) {
103
+ case "5-part":
104
+ n = 5;
105
+ break;
106
+ case "6-part":
107
+ n = 6;
108
+ break;
109
+ case "7-part":
110
+ n = 7;
111
+ break;
112
+ case "5-or-6-parts":
113
+ n = [5, 6];
114
+ break;
115
+ case "6-or-7-parts":
116
+ n = [6, 7];
117
+ break;
118
+ default:
119
+ n = 0;
120
+ }
121
+ if (!(Array.isArray(n) ? n.includes(t) : t === n)) {
122
+ let a = Array.isArray(n) ? n.join(" or ") : n.toString();
123
+ throw new TypeError(`CronPattern: mode '${this.mode}' requires exactly ${a} parts, but pattern '${this.pattern}' has ${t} parts.`);
124
+ }
125
+ }
126
+ if (e.length === 5 && e.unshift("0"), e.length === 6 && e.push("*"), e[3].toUpperCase() === "LW" ? (this.lastWeekday = !0, e[3] = "") : e[3].toUpperCase().indexOf("L") >= 0 && (e[3] = e[3].replace(/L/gi, ""), this.lastDayOfMonth = !0), e[3] == "*" && (this.starDOM = !0), e[6] == "*" && (this.starYear = !0), e[4].length >= 3 && (e[4] = this.replaceAlphaMonths(e[4])), e[5].length >= 3 && (e[5] = this.alternativeWeekdays ? this.replaceAlphaDaysQuartz(e[5]) : this.replaceAlphaDays(e[5])), e[5].startsWith("+") && (this.useAndLogic = !0, e[5] = e[5].substring(1), e[5] === "")) throw new TypeError("CronPattern: Day-of-week field cannot be empty after '+' modifier.");
127
+ switch (e[5] == "*" && (this.starDOW = !0), this.pattern.indexOf("?") >= 0 && (e[0] = e[0].replace(/\?/g, "*"), e[1] = e[1].replace(/\?/g, "*"), e[2] = e[2].replace(/\?/g, "*"), e[3] = e[3].replace(/\?/g, "*"), e[4] = e[4].replace(/\?/g, "*"), e[5] = e[5].replace(/\?/g, "*"), e[6] && (e[6] = e[6].replace(/\?/g, "*"))), this.mode) {
128
+ case "5-part":
129
+ e[0] = "0", e[6] = "*";
130
+ break;
131
+ case "6-part":
132
+ e[6] = "*";
133
+ break;
134
+ case "5-or-6-parts":
135
+ e[6] = "*";
136
+ break;
137
+ case "6-or-7-parts":
138
+ break;
139
+ case "7-part":
140
+ case "auto":
141
+ break;
142
+ }
143
+ this.throwAtIllegalCharacters(e), this.partToArray("second", e[0], 0, 1), this.partToArray("minute", e[1], 0, 1), this.partToArray("hour", e[2], 0, 1), this.partToArray("day", e[3], -1, 1), this.partToArray("month", e[4], -1, 1);
144
+ let r = this.alternativeWeekdays ? -1 : 0;
145
+ this.partToArray("dayOfWeek", e[5], r, 63), this.partToArray("year", e[6], 0, 1), !this.alternativeWeekdays && this.dayOfWeek[7] && (this.dayOfWeek[0] = this.dayOfWeek[7]);
146
+ }
147
+ partToArray(e, t, r, n) {
148
+ let i = this[e], a = e === "day" && this.lastDayOfMonth, o = e === "day" && this.lastWeekday;
149
+ if (t === "" && !a && !o) throw new TypeError("CronPattern: configuration entry " + e + " (" + t + ") is empty, check for trailing spaces.");
150
+ if (t === "*") return i.fill(n);
151
+ let h = t.split(",");
152
+ if (h.length > 1) for (let l = 0; l < h.length; l++) this.partToArray(e, h[l], r, n);
153
+ else t.indexOf("-") !== -1 && t.indexOf("/") !== -1 ? this.handleRangeWithStepping(t, e, r, n) : t.indexOf("-") !== -1 ? this.handleRange(t, e, r, n) : t.indexOf("/") !== -1 ? this.handleStepping(t, e, r, n) : t !== "" && this.handleNumber(t, e, r, n);
154
+ }
155
+ throwAtIllegalCharacters(e) {
156
+ for (let t = 0; t < e.length; t++) if ((t === 3 ? /[^/*0-9,\-WwLl]+/ : t === 5 ? /[^/*0-9,\-#Ll]+/ : /[^/*0-9,\-]+/).test(e[t])) throw new TypeError("CronPattern: configuration entry " + t + " (" + e[t] + ") contains illegal characters.");
157
+ }
158
+ handleNumber(e, t, r, n) {
159
+ let i = this.extractNth(e, t), a = e.toUpperCase().includes("W");
160
+ if (t !== "day" && a) throw new TypeError("CronPattern: Nearest weekday modifier (W) only allowed in day-of-month.");
161
+ a && (t = "nearestWeekdays");
162
+ let o = parseInt(i[0], 10) + r;
163
+ if (isNaN(o)) throw new TypeError("CronPattern: " + t + " is not a number: '" + e + "'");
164
+ this.setPart(t, o, i[1] || n);
165
+ }
166
+ setPart(e, t, r) {
167
+ if (!Object.prototype.hasOwnProperty.call(this, e)) throw new TypeError("CronPattern: Invalid part specified: " + e);
168
+ if (e === "dayOfWeek") {
169
+ if (t === 7 && (t = 0), t < 0 || t > 6) throw new RangeError("CronPattern: Invalid value for dayOfWeek: " + t);
170
+ this.setNthWeekdayOfMonth(t, r);
171
+ return;
172
+ }
173
+ if (e === "second" || e === "minute") {
174
+ if (t < 0 || t >= 60) throw new RangeError("CronPattern: Invalid value for " + e + ": " + t);
175
+ } else if (e === "hour") {
176
+ if (t < 0 || t >= 24) throw new RangeError("CronPattern: Invalid value for " + e + ": " + t);
177
+ } else if (e === "day" || e === "nearestWeekdays") {
178
+ if (t < 0 || t >= 31) throw new RangeError("CronPattern: Invalid value for " + e + ": " + t);
179
+ } else if (e === "month") {
180
+ if (t < 0 || t >= 12) throw new RangeError("CronPattern: Invalid value for " + e + ": " + t);
181
+ } else if (e === "year" && (t < 1 || t >= 1e4)) throw new RangeError("CronPattern: Invalid value for " + e + ": " + t + " (supported range: 1-9999)");
182
+ this[e][t] = r;
183
+ }
184
+ validateNotNaN(e, t) {
185
+ if (isNaN(e)) throw new TypeError(t);
186
+ }
187
+ validateRange(e, t, r, n, i) {
188
+ if (e > t) throw new TypeError("CronPattern: From value is larger than to value: '" + i + "'");
189
+ if (r !== void 0) {
190
+ if (r === 0) throw new TypeError("CronPattern: Syntax error, illegal stepping: 0");
191
+ if (r > this[n].length) throw new TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part (" + this[n].length + ")");
192
+ }
193
+ }
194
+ handleRangeWithStepping(e, t, r, n) {
195
+ if (e.toUpperCase().includes("W")) throw new TypeError("CronPattern: Syntax error, W is not allowed in ranges with stepping.");
196
+ let i = this.extractNth(e, t), a = i[0].match(/^(\d+)-(\d+)\/(\d+)$/);
197
+ if (a === null) throw new TypeError("CronPattern: Syntax error, illegal range with stepping: '" + e + "'");
198
+ let [, o, h, l] = a, y = parseInt(o, 10) + r, u = parseInt(h, 10) + r, d = parseInt(l, 10);
199
+ this.validateNotNaN(y, "CronPattern: Syntax error, illegal lower range (NaN)"), this.validateNotNaN(u, "CronPattern: Syntax error, illegal upper range (NaN)"), this.validateNotNaN(d, "CronPattern: Syntax error, illegal stepping: (NaN)"), this.validateRange(y, u, d, t, e);
200
+ for (let c = y; c <= u; c += d) this.setPart(t, c, i[1] || n);
201
+ }
202
+ extractNth(e, t) {
203
+ let r = e, n;
204
+ if (r.includes("#")) {
205
+ if (t !== "dayOfWeek") throw new Error("CronPattern: nth (#) only allowed in day-of-week field");
206
+ n = r.split("#")[1], r = r.split("#")[0];
207
+ } else if (r.toUpperCase().endsWith("L")) {
208
+ if (t !== "dayOfWeek") throw new Error("CronPattern: L modifier only allowed in day-of-week field (use L alone for day-of-month)");
209
+ n = "L", r = r.slice(0, -1);
210
+ }
211
+ return [r, n];
212
+ }
213
+ handleRange(e, t, r, n) {
214
+ if (e.toUpperCase().includes("W")) throw new TypeError("CronPattern: Syntax error, W is not allowed in a range.");
215
+ let i = this.extractNth(e, t), a = i[0].split("-");
216
+ if (a.length !== 2) throw new TypeError("CronPattern: Syntax error, illegal range: '" + e + "'");
217
+ let o = parseInt(a[0], 10) + r, h = parseInt(a[1], 10) + r;
218
+ this.validateNotNaN(o, "CronPattern: Syntax error, illegal lower range (NaN)"), this.validateNotNaN(h, "CronPattern: Syntax error, illegal upper range (NaN)"), this.validateRange(o, h, void 0, t, e);
219
+ for (let l = o; l <= h; l++) this.setPart(t, l, i[1] || n);
220
+ }
221
+ handleStepping(e, t, r, n) {
222
+ if (e.toUpperCase().includes("W")) throw new TypeError("CronPattern: Syntax error, W is not allowed in parts with stepping.");
223
+ let i = this.extractNth(e, t), a = i[0].split("/");
224
+ if (a.length !== 2) throw new TypeError("CronPattern: Syntax error, illegal stepping: '" + e + "'");
225
+ if (this.sloppyRanges) a[0] === "" && (a[0] = "*");
226
+ else {
227
+ if (a[0] === "") throw new TypeError("CronPattern: Syntax error, stepping with missing prefix ('" + e + "') is not allowed. Use wildcard (*/step) or range (min-max/step) instead.");
228
+ if (a[0] !== "*") throw new TypeError("CronPattern: Syntax error, stepping with numeric prefix ('" + e + "') is not allowed. Use wildcard (*/step) or range (min-max/step) instead.");
229
+ }
230
+ let o = 0;
231
+ a[0] !== "*" && (o = parseInt(a[0], 10) + r);
232
+ let h = parseInt(a[1], 10);
233
+ this.validateNotNaN(h, "CronPattern: Syntax error, illegal stepping: (NaN)"), this.validateRange(0, this[t].length - 1, h, t, e);
234
+ for (let l = o; l < this[t].length; l += h) this.setPart(t, l, i[1] || n);
235
+ }
236
+ replaceAlphaDays(e) {
237
+ return e.replace(/-sun/gi, "-7").replace(/sun/gi, "0").replace(/mon/gi, "1").replace(/tue/gi, "2").replace(/wed/gi, "3").replace(/thu/gi, "4").replace(/fri/gi, "5").replace(/sat/gi, "6");
238
+ }
239
+ replaceAlphaDaysQuartz(e) {
240
+ return e.replace(/sun/gi, "1").replace(/mon/gi, "2").replace(/tue/gi, "3").replace(/wed/gi, "4").replace(/thu/gi, "5").replace(/fri/gi, "6").replace(/sat/gi, "7");
241
+ }
242
+ replaceAlphaMonths(e) {
243
+ return e.replace(/jan/gi, "1").replace(/feb/gi, "2").replace(/mar/gi, "3").replace(/apr/gi, "4").replace(/may/gi, "5").replace(/jun/gi, "6").replace(/jul/gi, "7").replace(/aug/gi, "8").replace(/sep/gi, "9").replace(/oct/gi, "10").replace(/nov/gi, "11").replace(/dec/gi, "12");
244
+ }
245
+ handleNicknames(e) {
246
+ let t = e.trim().toLowerCase();
247
+ if (t === "@yearly" || t === "@annually") return "0 0 1 1 *";
248
+ if (t === "@monthly") return "0 0 1 * *";
249
+ if (t === "@weekly") return "0 0 * * 0";
250
+ if (t === "@daily" || t === "@midnight") return "0 0 * * *";
251
+ if (t === "@hourly") return "0 * * * *";
252
+ if (t === "@reboot") throw new TypeError("CronPattern: @reboot is not supported in this environment. This is an event-based trigger that requires system startup detection.");
253
+ return e;
254
+ }
255
+ setNthWeekdayOfMonth(e, t) {
256
+ if (typeof t != "number" && t.toUpperCase() === "L") this.dayOfWeek[e] = this.dayOfWeek[e] | 32;
257
+ else if (t === 63) this.dayOfWeek[e] = 63;
258
+ else if (t < 6 && t > 0) this.dayOfWeek[e] = this.dayOfWeek[e] | O[t - 1];
259
+ else throw new TypeError(`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${t}, Type: ${typeof t}`);
260
+ }
261
+ }, P = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], f = [["month", "year", 0], ["day", "month", -1], ["hour", "day", 0], ["minute", "hour", 0], ["second", "minute", 0]], m = class s {
262
+ tz;
263
+ ms;
264
+ second;
265
+ minute;
266
+ hour;
267
+ day;
268
+ month;
269
+ year;
270
+ constructor(e, t) {
271
+ if (this.tz = t, e && e instanceof Date) if (!isNaN(e)) this.fromDate(e);
272
+ else throw new TypeError("CronDate: Invalid date passed to CronDate constructor");
273
+ else if (e == null) this.fromDate(/* @__PURE__ */ new Date());
274
+ else if (e && typeof e == "string") this.fromString(e);
275
+ else if (e instanceof s) this.fromCronDate(e);
276
+ else throw new TypeError("CronDate: Invalid type (" + typeof e + ") passed to CronDate constructor");
277
+ }
278
+ getLastDayOfMonth(e, t) {
279
+ return t !== 1 ? P[t] : new Date(Date.UTC(e, t + 1, 0)).getUTCDate();
280
+ }
281
+ getLastWeekday(e, t) {
282
+ let r = this.getLastDayOfMonth(e, t), i = new Date(Date.UTC(e, t, r)).getUTCDay();
283
+ return i === 0 ? r - 2 : i === 6 ? r - 1 : r;
284
+ }
285
+ getNearestWeekday(e, t, r) {
286
+ let n = this.getLastDayOfMonth(e, t);
287
+ if (r > n) return -1;
288
+ let a = new Date(Date.UTC(e, t, r)).getUTCDay();
289
+ return a === 0 ? r === n ? r - 2 : r + 1 : a === 6 ? r === 1 ? r + 2 : r - 1 : r;
290
+ }
291
+ isNthWeekdayOfMonth(e, t, r, n) {
292
+ let a = new Date(Date.UTC(e, t, r)).getUTCDay(), o = 0;
293
+ for (let h = 1; h <= r; h++) new Date(Date.UTC(e, t, h)).getUTCDay() === a && o++;
294
+ if (n & 63 && O[o - 1] & n) return !0;
295
+ if (n & 32) {
296
+ let h = this.getLastDayOfMonth(e, t);
297
+ for (let l = r + 1; l <= h; l++) if (new Date(Date.UTC(e, t, l)).getUTCDay() === a) return !1;
298
+ return !0;
299
+ }
300
+ return !1;
301
+ }
302
+ fromDate(e) {
303
+ if (this.tz !== void 0) if (typeof this.tz == "number") this.ms = e.getUTCMilliseconds(), this.second = e.getUTCSeconds(), this.minute = e.getUTCMinutes() + this.tz, this.hour = e.getUTCHours(), this.day = e.getUTCDate(), this.month = e.getUTCMonth(), this.year = e.getUTCFullYear(), this.apply();
304
+ else try {
305
+ let t = g(e, this.tz);
306
+ this.ms = e.getMilliseconds(), this.second = t.s, this.minute = t.i, this.hour = t.h, this.day = t.d, this.month = t.m - 1, this.year = t.y;
307
+ } catch (t) {
308
+ let r = t instanceof Error ? t.message : String(t);
309
+ throw new TypeError(`CronDate: Failed to convert date to timezone '${this.tz}'. This may happen with invalid timezone names or dates. Original error: ${r}`);
310
+ }
311
+ else this.ms = e.getMilliseconds(), this.second = e.getSeconds(), this.minute = e.getMinutes(), this.hour = e.getHours(), this.day = e.getDate(), this.month = e.getMonth(), this.year = e.getFullYear();
312
+ }
313
+ fromCronDate(e) {
314
+ this.tz = e.tz, this.year = e.year, this.month = e.month, this.day = e.day, this.hour = e.hour, this.minute = e.minute, this.second = e.second, this.ms = e.ms;
315
+ }
316
+ apply() {
317
+ if (this.month > 11 || this.month < 0 || this.day > P[this.month] || this.day < 1 || this.hour > 59 || this.minute > 59 || this.second > 59 || this.hour < 0 || this.minute < 0 || this.second < 0) {
318
+ let e = new Date(Date.UTC(this.year, this.month, this.day, this.hour, this.minute, this.second, this.ms));
319
+ return this.ms = e.getUTCMilliseconds(), this.second = e.getUTCSeconds(), this.minute = e.getUTCMinutes(), this.hour = e.getUTCHours(), this.day = e.getUTCDate(), this.month = e.getUTCMonth(), this.year = e.getUTCFullYear(), !0;
320
+ } else return !1;
321
+ }
322
+ fromString(e) {
323
+ if (typeof this.tz == "number") {
324
+ let t = v(e);
325
+ this.ms = t.getUTCMilliseconds(), this.second = t.getUTCSeconds(), this.minute = t.getUTCMinutes(), this.hour = t.getUTCHours(), this.day = t.getUTCDate(), this.month = t.getUTCMonth(), this.year = t.getUTCFullYear(), this.apply();
326
+ } else return this.fromDate(v(e, this.tz));
327
+ }
328
+ findNext(e, t, r, n) {
329
+ return this._findMatch(e, t, r, n, 1);
330
+ }
331
+ _findMatch(e, t, r, n, i) {
332
+ let a = this[t], o;
333
+ r.lastDayOfMonth && (o = this.getLastDayOfMonth(this.year, this.month));
334
+ let h = !r.starDOW && t == "day" ? new Date(Date.UTC(this.year, this.month, 1, 0, 0, 0, 0)).getUTCDay() : void 0, l = this[t] + n, y = i === 1 ? (u) => u < r[t].length : (u) => u >= 0;
335
+ for (let u = l; y(u); u += i) {
336
+ let d = r[t][u];
337
+ if (t === "day" && !d) {
338
+ for (let c = 0; c < r.nearestWeekdays.length; c++) if (r.nearestWeekdays[c]) {
339
+ let M = this.getNearestWeekday(this.year, this.month, c - n);
340
+ if (M === -1) continue;
341
+ if (M === u - n) {
342
+ d = 1;
343
+ break;
344
+ }
345
+ }
346
+ }
347
+ if (t === "day" && r.lastWeekday) {
348
+ let c = this.getLastWeekday(this.year, this.month);
349
+ u - n === c && (d = 1);
350
+ }
351
+ if (t === "day" && r.lastDayOfMonth && u - n == o && (d = 1), t === "day" && !r.starDOW) {
352
+ let c = r.dayOfWeek[(h + (u - n - 1)) % 7];
353
+ if (c && c & 63) c = this.isNthWeekdayOfMonth(this.year, this.month, u - n, c) ? 1 : 0;
354
+ else if (c) throw new Error(`CronDate: Invalid value for dayOfWeek encountered. ${c}`);
355
+ r.useAndLogic ? d = d && c : !e.domAndDow && !r.starDOM ? d = d || c : d = d && c;
356
+ }
357
+ if (d) return this[t] = u - n, a !== this[t] ? 2 : 1;
358
+ }
359
+ return 3;
360
+ }
361
+ recurse(e, t, r) {
362
+ if (r === 0 && !e.starYear) {
363
+ if (this.year >= 0 && this.year < e.year.length && e.year[this.year] === 0) {
364
+ let i = -1;
365
+ for (let a = this.year + 1; a < e.year.length && a < 1e4; a++) if (e.year[a] === 1) {
366
+ i = a;
367
+ break;
368
+ }
369
+ if (i === -1) return null;
370
+ this.year = i, this.month = 0, this.day = 1, this.hour = 0, this.minute = 0, this.second = 0, this.ms = 0;
371
+ }
372
+ if (this.year >= 1e4) return null;
373
+ }
374
+ let n = this.findNext(t, f[r][0], e, f[r][2]);
375
+ if (n > 1) {
376
+ let i = r + 1;
377
+ for (; i < f.length; ) this[f[i][0]] = -f[i][2], i++;
378
+ if (n === 3) {
379
+ if (this[f[r][1]]++, this[f[r][0]] = -f[r][2], this.apply(), r === 0 && !e.starYear) {
380
+ for (; this.year >= 0 && this.year < e.year.length && e.year[this.year] === 0 && this.year < 1e4; ) this.year++;
381
+ if (this.year >= 1e4 || this.year >= e.year.length) return null;
382
+ }
383
+ return this.recurse(e, t, 0);
384
+ } else if (this.apply()) return this.recurse(e, t, r - 1);
385
+ }
386
+ return r += 1, r >= f.length ? this : (e.starYear ? this.year >= 3e3 : this.year >= 1e4) ? null : this.recurse(e, t, r);
387
+ }
388
+ increment(e, t, r) {
389
+ return this.second += t.interval !== void 0 && t.interval > 1 && r ? t.interval : 1, this.ms = 0, this.apply(), this.recurse(e, t, 0);
390
+ }
391
+ decrement(e, t) {
392
+ return this.second -= t.interval !== void 0 && t.interval > 1 ? t.interval : 1, this.ms = 0, this.apply(), this.recurseBackward(e, t, 0, 0);
393
+ }
394
+ recurseBackward(e, t, r, n = 0) {
395
+ if (n > 1e4) return null;
396
+ if (r === 0 && !e.starYear) {
397
+ if (this.year >= 0 && this.year < e.year.length && e.year[this.year] === 0) {
398
+ let a = -1;
399
+ for (let o = this.year - 1; o >= 0; o--) if (e.year[o] === 1) {
400
+ a = o;
401
+ break;
402
+ }
403
+ if (a === -1) return null;
404
+ this.year = a, this.month = 11, this.day = 31, this.hour = 23, this.minute = 59, this.second = 59, this.ms = 0;
405
+ }
406
+ if (this.year < 0) return null;
407
+ }
408
+ let i = this.findPrevious(t, f[r][0], e, f[r][2]);
409
+ if (i > 1) {
410
+ let a = r + 1;
411
+ for (; a < f.length; ) {
412
+ let o = f[a][0], h = f[a][2], l = this.getMaxPatternValue(o, e, h);
413
+ this[o] = l, a++;
414
+ }
415
+ if (i === 3) {
416
+ if (this[f[r][1]]--, r === 0) {
417
+ let y = this.getLastDayOfMonth(this.year, this.month);
418
+ this.day > y && (this.day = y);
419
+ }
420
+ if (r === 1) if (this.day <= 0) this.day = 1;
421
+ else {
422
+ let y = this.year, u = this.month;
423
+ for (; u < 0; ) u += 12, y--;
424
+ for (; u > 11; ) u -= 12, y++;
425
+ let d = u !== 1 ? P[u] : new Date(Date.UTC(y, u + 1, 0)).getUTCDate();
426
+ this.day > d && (this.day = d);
427
+ }
428
+ this.apply();
429
+ let o = f[r][0], h = f[r][2], l = this.getMaxPatternValue(o, e, h);
430
+ if (o === "day") {
431
+ let y = this.getLastDayOfMonth(this.year, this.month);
432
+ this[o] = Math.min(l, y);
433
+ } else this[o] = l;
434
+ if (this.apply(), r === 0) {
435
+ let y = f[1][2], u = this.getMaxPatternValue("day", e, y), d = this.getLastDayOfMonth(this.year, this.month), c = Math.min(u, d);
436
+ c !== this.day && (this.day = c, this.hour = this.getMaxPatternValue("hour", e, f[2][2]), this.minute = this.getMaxPatternValue("minute", e, f[3][2]), this.second = this.getMaxPatternValue("second", e, f[4][2]));
437
+ }
438
+ if (r === 0 && !e.starYear) {
439
+ for (; this.year >= 0 && this.year < e.year.length && e.year[this.year] === 0; ) this.year--;
440
+ if (this.year < 0) return null;
441
+ }
442
+ return this.recurseBackward(e, t, 0, n + 1);
443
+ } else if (this.apply()) return this.recurseBackward(e, t, r - 1, n + 1);
444
+ }
445
+ return r += 1, r >= f.length ? this : this.year < 0 ? null : this.recurseBackward(e, t, r, n + 1);
446
+ }
447
+ getMaxPatternValue(e, t, r) {
448
+ if (e === "day" && t.lastDayOfMonth) return this.getLastDayOfMonth(this.year, this.month);
449
+ if (e === "day" && !t.starDOW) return this.getLastDayOfMonth(this.year, this.month);
450
+ for (let n = t[e].length - 1; n >= 0; n--) if (t[e][n]) return n - r;
451
+ return t[e].length - 1 - r;
452
+ }
453
+ findPrevious(e, t, r, n) {
454
+ return this._findMatch(e, t, r, n, -1);
455
+ }
456
+ getDate(e) {
457
+ return e || this.tz === void 0 ? new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.ms) : typeof this.tz == "number" ? new Date(Date.UTC(this.year, this.month, this.day, this.hour, this.minute - this.tz, this.second, this.ms)) : k(b(this.year, this.month + 1, this.day, this.hour, this.minute, this.second, this.tz), !1);
458
+ }
459
+ getTime() {
460
+ return this.getDate(!1).getTime();
461
+ }
462
+ match(e, t) {
463
+ if (!e.starYear && (this.year < 0 || this.year >= e.year.length || e.year[this.year] === 0)) return !1;
464
+ for (let r = 0; r < f.length; r++) {
465
+ let n = f[r][0], i = f[r][2], a = this[n];
466
+ if (a + i < 0 || a + i >= e[n].length) return !1;
467
+ let o = e[n][a + i];
468
+ if (n === "day") {
469
+ if (!o) {
470
+ for (let h = 0; h < e.nearestWeekdays.length; h++) if (e.nearestWeekdays[h]) {
471
+ let l = this.getNearestWeekday(this.year, this.month, h - i);
472
+ if (l !== -1 && l === a) {
473
+ o = 1;
474
+ break;
475
+ }
476
+ }
477
+ }
478
+ if (e.lastWeekday) {
479
+ let h = this.getLastWeekday(this.year, this.month);
480
+ a === h && (o = 1);
481
+ }
482
+ if (e.lastDayOfMonth) {
483
+ let h = this.getLastDayOfMonth(this.year, this.month);
484
+ a === h && (o = 1);
485
+ }
486
+ if (!e.starDOW) {
487
+ let h = new Date(Date.UTC(this.year, this.month, 1, 0, 0, 0, 0)).getUTCDay(), l = e.dayOfWeek[(h + (a - 1)) % 7];
488
+ l && l & 63 && (l = this.isNthWeekdayOfMonth(this.year, this.month, a, l) ? 1 : 0), e.useAndLogic ? o = o && l : !t.domAndDow && !e.starDOM ? o = o || l : o = o && l;
489
+ }
490
+ }
491
+ if (!o) return !1;
492
+ }
493
+ return !0;
494
+ }
495
+ };
496
+ function R(s2) {
497
+ if (s2 === void 0 && (s2 = {}), delete s2.name, s2.legacyMode !== void 0 && s2.domAndDow === void 0 ? s2.domAndDow = !s2.legacyMode : s2.domAndDow === void 0 && (s2.domAndDow = !1), s2.legacyMode = !s2.domAndDow, s2.paused = s2.paused === void 0 ? !1 : s2.paused, s2.maxRuns = s2.maxRuns === void 0 ? 1 / 0 : s2.maxRuns, s2.catch = s2.catch === void 0 ? !1 : s2.catch, s2.interval = s2.interval === void 0 ? 0 : parseInt(s2.interval.toString(), 10), s2.utcOffset = s2.utcOffset === void 0 ? void 0 : parseInt(s2.utcOffset.toString(), 10), s2.dayOffset = s2.dayOffset === void 0 ? 0 : parseInt(s2.dayOffset.toString(), 10), s2.unref = s2.unref === void 0 ? !1 : s2.unref, s2.mode = s2.mode === void 0 ? "auto" : s2.mode, s2.alternativeWeekdays = s2.alternativeWeekdays === void 0 ? !1 : s2.alternativeWeekdays, s2.sloppyRanges = s2.sloppyRanges === void 0 ? !1 : s2.sloppyRanges, !["auto", "5-part", "6-part", "7-part", "5-or-6-parts", "6-or-7-parts"].includes(s2.mode)) throw new Error("CronOptions: mode must be one of 'auto', '5-part', '6-part', '7-part', '5-or-6-parts', or '6-or-7-parts'.");
498
+ if (s2.startAt && (s2.startAt = new m(s2.startAt, s2.timezone)), s2.stopAt && (s2.stopAt = new m(s2.stopAt, s2.timezone)), s2.interval !== null) {
499
+ if (isNaN(s2.interval)) throw new Error("CronOptions: Supplied value for interval is not a number");
500
+ if (s2.interval < 0) throw new Error("CronOptions: Supplied value for interval can not be negative");
501
+ }
502
+ if (s2.utcOffset !== void 0) {
503
+ if (isNaN(s2.utcOffset)) throw new Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.");
504
+ if (s2.utcOffset < -870 || s2.utcOffset > 870) throw new Error("CronOptions: utcOffset out of bounds.");
505
+ if (s2.utcOffset !== void 0 && s2.timezone) throw new Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.");
506
+ }
507
+ if (s2.unref !== !0 && s2.unref !== !1) throw new Error("CronOptions: Unref should be either true, false or undefined(false).");
508
+ if (s2.dayOffset !== void 0 && s2.dayOffset !== 0 && isNaN(s2.dayOffset)) throw new Error("CronOptions: Invalid value passed for dayOffset, should be a number representing days to offset.");
509
+ return s2;
510
+ }
511
+ function p(s2) {
512
+ return Object.prototype.toString.call(s2) === "[object Function]" || typeof s2 == "function" || s2 instanceof Function;
513
+ }
514
+ function _(s2) {
515
+ return p(s2);
516
+ }
517
+ function x(s2) {
518
+ typeof Deno < "u" && typeof Deno.unrefTimer < "u" ? Deno.unrefTimer(s2) : s2 && typeof s2.unref < "u" && s2.unref();
519
+ }
520
+ var W = 30 * 1e3, w = [], E = class {
521
+ name;
522
+ options;
523
+ _states;
524
+ fn;
525
+ getTz() {
526
+ return this.options.timezone || this.options.utcOffset;
527
+ }
528
+ applyDayOffset(e) {
529
+ if (this.options.dayOffset !== void 0 && this.options.dayOffset !== 0) {
530
+ let t = this.options.dayOffset * 24 * 60 * 60 * 1e3;
531
+ return new Date(e.getTime() + t);
532
+ }
533
+ return e;
534
+ }
535
+ constructor(e, t, r) {
536
+ let n, i;
537
+ if (p(t)) i = t;
538
+ else if (typeof t == "object") n = t;
539
+ else if (t !== void 0) throw new Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).");
540
+ if (p(r)) i = r;
541
+ else if (typeof r == "object") n = r;
542
+ else if (r !== void 0) throw new Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).");
543
+ if (this.name = n?.name, this.options = R(n), this._states = { kill: !1, blocking: !1, previousRun: void 0, currentRun: void 0, once: void 0, currentTimeout: void 0, maxRuns: n ? n.maxRuns : void 0, paused: n ? n.paused : !1, pattern: new C("* * * * *", void 0, { mode: "auto" }) }, e && (e instanceof Date || typeof e == "string" && e.indexOf(":") > 0) ? this._states.once = new m(e, this.getTz()) : this._states.pattern = new C(e, this.options.timezone, { mode: this.options.mode, alternativeWeekdays: this.options.alternativeWeekdays, sloppyRanges: this.options.sloppyRanges }), this.name) {
544
+ if (w.find((o) => o.name === this.name)) throw new Error("Cron: Tried to initialize new named job '" + this.name + "', but name already taken.");
545
+ w.push(this);
546
+ }
547
+ return i !== void 0 && _(i) && (this.fn = i, this.schedule()), this;
548
+ }
549
+ nextRun(e) {
550
+ let t = this._next(e);
551
+ return t ? this.applyDayOffset(t.getDate(!1)) : null;
552
+ }
553
+ nextRuns(e, t) {
554
+ this._states.maxRuns !== void 0 && e > this._states.maxRuns && (e = this._states.maxRuns);
555
+ let r = t || this._states.currentRun || void 0;
556
+ return this._enumerateRuns(e, r, "next");
557
+ }
558
+ previousRuns(e, t) {
559
+ return this._enumerateRuns(e, t || void 0, "previous");
560
+ }
561
+ _enumerateRuns(e, t, r) {
562
+ let n = [], i = t ? new m(t, this.getTz()) : null, a = r === "next" ? this._next : this._previous;
563
+ for (; e--; ) {
564
+ let o = a.call(this, i);
565
+ if (!o) break;
566
+ let h = o.getDate(!1);
567
+ n.push(this.applyDayOffset(h)), i = o;
568
+ }
569
+ return n;
570
+ }
571
+ match(e) {
572
+ if (this._states.once) {
573
+ let r = new m(e, this.getTz());
574
+ r.ms = 0;
575
+ let n = new m(this._states.once, this.getTz());
576
+ return n.ms = 0, r.getTime() === n.getTime();
577
+ }
578
+ let t = new m(e, this.getTz());
579
+ return t.ms = 0, t.match(this._states.pattern, this.options);
580
+ }
581
+ getPattern() {
582
+ if (!this._states.once) return this._states.pattern ? this._states.pattern.pattern : void 0;
583
+ }
584
+ getOnce() {
585
+ return this._states.once ? this._states.once.getDate() : null;
586
+ }
587
+ isRunning() {
588
+ let e = this.nextRun(this._states.currentRun), t = !this._states.paused, r = this.fn !== void 0, n = !this._states.kill;
589
+ return t && r && n && e !== null;
590
+ }
591
+ isStopped() {
592
+ return this._states.kill;
593
+ }
594
+ isBusy() {
595
+ return this._states.blocking;
596
+ }
597
+ currentRun() {
598
+ return this._states.currentRun ? this._states.currentRun.getDate() : null;
599
+ }
600
+ previousRun() {
601
+ return this._states.previousRun ? this._states.previousRun.getDate() : null;
602
+ }
603
+ msToNext(e) {
604
+ let t = this._next(e);
605
+ return t ? e instanceof m || e instanceof Date ? t.getTime() - e.getTime() : t.getTime() - new m(e).getTime() : null;
606
+ }
607
+ stop() {
608
+ this._states.kill = !0, this._states.currentTimeout && clearTimeout(this._states.currentTimeout);
609
+ let e = w.indexOf(this);
610
+ e >= 0 && w.splice(e, 1);
611
+ }
612
+ pause() {
613
+ return this._states.paused = !0, !this._states.kill;
614
+ }
615
+ resume() {
616
+ return this._states.paused = !1, !this._states.kill;
617
+ }
618
+ schedule(e) {
619
+ if (e && this.fn) throw new Error("Cron: It is not allowed to schedule two functions using the same Croner instance.");
620
+ e && (this.fn = e);
621
+ let t = this.msToNext(), r = this.nextRun(this._states.currentRun);
622
+ return t == null || isNaN(t) || r === null ? this : (t > W && (t = W), this._states.currentTimeout = setTimeout(() => this._checkTrigger(r), t), this._states.currentTimeout && this.options.unref && x(this._states.currentTimeout), this);
623
+ }
624
+ async _trigger(e) {
625
+ this._states.blocking = !0, this._states.currentRun = new m(void 0, this.getTz());
626
+ try {
627
+ if (this.options.catch) try {
628
+ this.fn !== void 0 && await this.fn(this, this.options.context);
629
+ } catch (t) {
630
+ if (p(this.options.catch)) try {
631
+ this.options.catch(t, this);
632
+ } catch {
633
+ }
634
+ }
635
+ else this.fn !== void 0 && await this.fn(this, this.options.context);
636
+ } finally {
637
+ this._states.previousRun = new m(e, this.getTz()), this._states.blocking = !1;
638
+ }
639
+ }
640
+ async trigger() {
641
+ await this._trigger();
642
+ }
643
+ runsLeft() {
644
+ return this._states.maxRuns;
645
+ }
646
+ _checkTrigger(e) {
647
+ let t = /* @__PURE__ */ new Date(), r = !this._states.paused && t.getTime() >= e.getTime(), n = this._states.blocking && this.options.protect;
648
+ r && !n ? (this._states.maxRuns !== void 0 && this._states.maxRuns--, this._trigger()) : r && n && p(this.options.protect) && setTimeout(() => this.options.protect(this), 0), this.schedule();
649
+ }
650
+ _next(e) {
651
+ let t = !!(e || this._states.currentRun), r = !1;
652
+ !e && this.options.startAt && this.options.interval && ([e, t] = this._calculatePreviousRun(e, t), r = !e), e = new m(e, this.getTz()), this.options.startAt && e && e.getTime() < this.options.startAt.getTime() && (e = this.options.startAt);
653
+ let n = this._states.once || new m(e, this.getTz());
654
+ return !r && n !== this._states.once && (n = n.increment(this._states.pattern, this.options, t)), this._states.once && this._states.once.getTime() <= e.getTime() || n === null || this._states.maxRuns !== void 0 && this._states.maxRuns <= 0 || this._states.kill || this.options.stopAt && n.getTime() >= this.options.stopAt.getTime() ? null : n;
655
+ }
656
+ _previous(e) {
657
+ let t = new m(e, this.getTz());
658
+ this.options.stopAt && t.getTime() > this.options.stopAt.getTime() && (t = this.options.stopAt);
659
+ let r = new m(t, this.getTz());
660
+ return this._states.once ? this._states.once.getTime() < t.getTime() ? this._states.once : null : (r = r.decrement(this._states.pattern, this.options), r === null || this.options.startAt && r.getTime() < this.options.startAt.getTime() ? null : r);
661
+ }
662
+ _calculatePreviousRun(e, t) {
663
+ let r = new m(void 0, this.getTz()), n = e;
664
+ if (this.options.startAt.getTime() <= r.getTime()) {
665
+ n = this.options.startAt;
666
+ let i = n.getTime() + this.options.interval * 1e3;
667
+ for (; i <= r.getTime(); ) n = new m(n, this.getTz()).increment(this._states.pattern, this.options, !0), i = n.getTime() + this.options.interval * 1e3;
668
+ t = !0;
669
+ }
670
+ return n === null && (n = void 0), [n, t];
671
+ }
672
+ };
673
+
674
+ // packages/coding-agent/dist/core/cron/jobs.js
675
+ var ONE_SHOT_GRACE_MS = 12e4, MIN_GRACE_MS = 12e4, MAX_GRACE_MS = 72e5, OUTPUT_RETENTION = 50, CONTEXT_OUTPUT_CAP = 8e3, MAX_NAME_LEN = 50, baseDirOverride, cache, writeQueue = Promise.resolve();
676
+ function cronDir() {
677
+ return join(baseDirOverride ?? getAgentDir(), "cron");
678
+ }
679
+ function jobsFile() {
680
+ return join(cronDir(), "jobs.json");
681
+ }
682
+ function outputDir(jobId) {
683
+ return join(cronDir(), "output", jobId);
684
+ }
685
+ function loadJobs() {
686
+ if (cache)
687
+ return cache;
688
+ let file = jobsFile();
689
+ if (!existsSync(file))
690
+ return cache = [], cache;
691
+ try {
692
+ let parsed = JSON.parse(readFileSync(file, "utf-8"));
693
+ cache = Array.isArray(parsed?.jobs) ? parsed.jobs : [];
694
+ } catch {
695
+ cache = [];
696
+ }
697
+ return cache;
698
+ }
699
+ function persist() {
700
+ let snapshot = JSON.stringify({ jobs: cache ?? [], updated_at: (/* @__PURE__ */ new Date()).toISOString() }, null, 2), p2 = writeQueue.then(() => {
701
+ mkdirSync(cronDir(), { recursive: !0 });
702
+ let tmp = join(cronDir(), `.jobs.json.${process.pid}.${Date.now()}.tmp`);
703
+ writeFileSync(tmp, snapshot, "utf-8"), renameSync(tmp, jobsFile());
704
+ });
705
+ return writeQueue = p2.then(() => {
706
+ }, () => {
707
+ }), p2;
708
+ }
709
+ var INTERVAL_RE = /^every\s+(\d+)\s*([mhd])$/i, DURATION_RE = /^(\d+)\s*([mhd])$/i;
710
+ function toMinutes(value, unit) {
711
+ let u = unit.toLowerCase();
712
+ return value * (u === "d" ? 1440 : u === "h" ? 60 : 1);
713
+ }
714
+ function parseSchedule(input, now = /* @__PURE__ */ new Date()) {
715
+ let text = input.trim().replace(/\s+/g, " ");
716
+ if (!text)
717
+ throw new Error("schedule is empty");
718
+ let interval = INTERVAL_RE.exec(text);
719
+ if (interval) {
720
+ let minutes = toMinutes(Number(interval[1]), interval[2]);
721
+ if (minutes <= 0)
722
+ throw new Error(`invalid interval: "${text}"`);
723
+ return {
724
+ schedule: { kind: "interval", minutes },
725
+ scheduleDisplay: `every ${Number(interval[1])}${interval[2].toLowerCase()}`
726
+ };
727
+ }
728
+ let duration = DURATION_RE.exec(text);
729
+ if (duration) {
730
+ let minutes = toMinutes(Number(duration[1]), duration[2]);
731
+ if (minutes <= 0)
732
+ throw new Error(`invalid duration: "${text}"`);
733
+ return { schedule: { kind: "once", runAt: new Date(now.getTime() + minutes * 6e4).toISOString() }, scheduleDisplay: text };
734
+ }
735
+ if (/^\d{4}-\d{2}-\d{2}/.test(text)) {
736
+ let ts = Date.parse(text);
737
+ if (!Number.isNaN(ts)) {
738
+ let runAt = new Date(ts).toISOString();
739
+ return { schedule: { kind: "once", runAt }, scheduleDisplay: runAt };
740
+ }
741
+ }
742
+ if (text.split(" ").length === 5) {
743
+ try {
744
+ new E(text);
745
+ } catch (err) {
746
+ throw new Error(`invalid cron expression "${text}": ${err instanceof Error ? err.message : String(err)}`);
747
+ }
748
+ return { schedule: { kind: "cron", expr: text }, scheduleDisplay: text };
749
+ }
750
+ throw new Error(`unrecognized schedule: "${input}" (expected "every 30m", "2h", an ISO timestamp, or a 5-field cron expression)`);
751
+ }
752
+ function computeNextRun(job, now = /* @__PURE__ */ new Date()) {
753
+ let s2 = job.schedule;
754
+ if (s2.kind === "once") {
755
+ if (job.repeat.completed > 0 || !s2.runAt)
756
+ return null;
757
+ let runAt = new Date(s2.runAt);
758
+ return Number.isNaN(runAt.getTime()) ? null : now.getTime() - runAt.getTime() <= ONE_SHOT_GRACE_MS ? runAt : null;
759
+ }
760
+ if (s2.kind === "interval") {
761
+ let base = job.lastRunAt ? new Date(job.lastRunAt) : new Date(job.createdAt);
762
+ return new Date(base.getTime() + (s2.minutes ?? 0) * 6e4);
763
+ }
764
+ return new E(s2.expr).nextRun(job.lastRunAt ? new Date(job.lastRunAt) : now);
765
+ }
766
+ function periodMs(job, now) {
767
+ if (job.schedule.kind === "interval")
768
+ return (job.schedule.minutes ?? 0) * 6e4;
769
+ if (job.schedule.kind === "cron") {
770
+ let cron = new E(job.schedule.expr), a = cron.nextRun(now);
771
+ if (!a)
772
+ return MAX_GRACE_MS;
773
+ let b2 = cron.nextRun(a);
774
+ return b2 ? Math.max(b2.getTime() - a.getTime(), 1) : MAX_GRACE_MS;
775
+ }
776
+ return 0;
777
+ }
778
+ function nextSlotAfter(job, after) {
779
+ if (job.schedule.kind === "interval") {
780
+ let period = (job.schedule.minutes ?? 0) * 6e4;
781
+ if (period <= 0)
782
+ return null;
783
+ let slot = job.nextRunAt ? new Date(job.nextRunAt).getTime() : new Date(job.createdAt).getTime() + period;
784
+ for (; slot <= after.getTime(); )
785
+ slot += period;
786
+ return new Date(slot);
787
+ }
788
+ return job.schedule.kind === "cron" ? new E(job.schedule.expr).nextRun(after) : null;
789
+ }
790
+ var workdirRoots = [process.cwd(), homedir()], deliverValidator;
791
+ function setCronDeliverValidator(fn) {
792
+ deliverValidator = fn;
793
+ }
794
+ function isPathUnderRoot(absPath, root) {
795
+ let normRoot = normalize(root).replace(/\\$/g, ""), normPath = normalize(absPath).replace(/\\$/g, "");
796
+ return normPath === normRoot || normPath.startsWith(`${normRoot}/`) || normPath.startsWith(`${normRoot}\\`);
797
+ }
798
+ function validateWorkdir(workdir) {
799
+ let candidate = resolve(workdir);
800
+ if (isAbsolute(workdir) && !workdirRoots.some((root) => isPathUnderRoot(candidate, root)))
801
+ return `workdir ${workdir} is outside allowed roots`;
802
+ if (!workdirRoots.some((root) => isPathUnderRoot(candidate, root)))
803
+ return `workdir ${workdir} resolves outside allowed roots`;
804
+ }
805
+ function runDeliverValidation(deliver, origin) {
806
+ return deliverMentionsChatPlatform(deliver) && !isFeatureEnabled("chat-platforms") ? chatPlatformDeliverBlockedMessage() : deliverValidator?.(deliver, origin);
807
+ }
808
+ function deriveName(prompt) {
809
+ return (prompt.split(`
810
+ `)[0].replace(/\s+/g, " ").trim() || "cron job").slice(0, MAX_NAME_LEN);
811
+ }
812
+ async function createJob(input) {
813
+ let prompt = input.prompt.trim();
814
+ if (!prompt)
815
+ throw new Error("createJob: prompt is empty");
816
+ if (input.workdir) {
817
+ let err = validateWorkdir(input.workdir);
818
+ if (err)
819
+ throw new Error(`createJob: ${err}`);
820
+ }
821
+ if (input.deliver) {
822
+ let err = runDeliverValidation(input.deliver, input.origin);
823
+ if (err)
824
+ throw new Error(`createJob: ${err}`);
825
+ }
826
+ let now = /* @__PURE__ */ new Date(), parsed = parseSchedule(input.schedule, now), times = parsed.schedule.kind === "once" ? 1 : input.times ?? null;
827
+ if (times !== null && (!Number.isInteger(times) || times < 1))
828
+ throw new Error(`createJob: times must be a positive integer or null, got ${times}`);
829
+ let job = {
830
+ id: randomUUID().replaceAll("-", "").slice(0, 12),
831
+ name: (input.name?.trim() || deriveName(prompt)).slice(0, MAX_NAME_LEN),
832
+ prompt,
833
+ schedule: parsed.schedule,
834
+ scheduleDisplay: parsed.scheduleDisplay,
835
+ repeat: { times, completed: 0 },
836
+ enabled: !0,
837
+ state: "scheduled",
838
+ createdAt: now.toISOString(),
839
+ nextRunAt: null,
840
+ lastRunAt: null,
841
+ lastStatus: null,
842
+ lastError: null,
843
+ lastDeliveryError: null,
844
+ deliver: input.deliver?.trim() || "local",
845
+ origin: input.origin ?? null,
846
+ contextFrom: input.contextFrom,
847
+ workdir: input.workdir
848
+ };
849
+ return job.nextRunAt = computeNextRun(job, now)?.toISOString() ?? null, loadJobs().push(job), await persist(), job;
850
+ }
851
+ function getJob(idOrName) {
852
+ let jobs = loadJobs(), byId = jobs.find((j) => j.id === idOrName);
853
+ if (byId)
854
+ return byId;
855
+ let byName = jobs.filter((j) => j.name === idOrName);
856
+ if (byName.length === 1)
857
+ return byName[0];
858
+ throw byName.length > 1 ? new Error(`cron job name "${idOrName}" is ambiguous (${byName.length} matches: ${byName.map((j) => j.id).join(", ")})`) : new Error(`no cron job matches "${idOrName}"`);
859
+ }
860
+ function listJobs() {
861
+ return [...loadJobs()];
862
+ }
863
+ async function updateJob(idOrName, patch) {
864
+ let job = getJob(idOrName);
865
+ if (patch.name !== void 0 && (job.name = patch.name.trim().slice(0, MAX_NAME_LEN) || job.name), patch.workdir !== void 0) {
866
+ if (patch.workdir) {
867
+ let err = validateWorkdir(patch.workdir);
868
+ if (err)
869
+ throw new Error(`updateJob: ${err}`);
870
+ }
871
+ job.workdir = patch.workdir;
872
+ }
873
+ if (patch.deliver !== void 0) {
874
+ let err = runDeliverValidation(patch.deliver, patch.origin ?? job.origin);
875
+ if (err)
876
+ throw new Error(`updateJob: ${err}`);
877
+ job.deliver = patch.deliver.trim() || "local";
878
+ }
879
+ if (patch.prompt !== void 0) {
880
+ let prompt = patch.prompt.trim();
881
+ if (!prompt)
882
+ throw new Error("updateJob: prompt is empty");
883
+ job.prompt = prompt;
884
+ }
885
+ if (patch.schedule !== void 0) {
886
+ let parsed = parseSchedule(patch.schedule);
887
+ job.schedule = parsed.schedule, job.scheduleDisplay = parsed.scheduleDisplay, parsed.schedule.kind === "once" && (job.repeat.times = 1), job.nextRunAt = computeNextRun(job)?.toISOString() ?? null;
888
+ }
889
+ if (patch.enabled !== void 0 && (job.enabled = patch.enabled), patch.times !== void 0) {
890
+ if (patch.times !== null && (!Number.isInteger(patch.times) || patch.times < 1))
891
+ throw new Error(`updateJob: times must be a positive integer or null, got ${patch.times}`);
892
+ job.schedule.kind !== "once" && (job.repeat.times = patch.times);
893
+ }
894
+ return patch.contextFrom !== void 0 && (job.contextFrom = patch.contextFrom), patch.origin !== void 0 && (job.origin = patch.origin), patch.nextRunAt !== void 0 && (job.nextRunAt = patch.nextRunAt), patch.lastDeliveryError !== void 0 && (job.lastDeliveryError = patch.lastDeliveryError), await persist(), job;
895
+ }
896
+ async function pauseJob(idOrName) {
897
+ let job = getJob(idOrName);
898
+ return job.state !== "completed" && (job.state = "paused"), await persist(), job;
899
+ }
900
+ async function resumeJob(idOrName) {
901
+ let job = getJob(idOrName);
902
+ return job.state === "paused" && (job.state = "scheduled", job.nextRunAt = computeNextRun(job)?.toISOString() ?? null), await persist(), job;
903
+ }
904
+ async function removeJob(idOrName) {
905
+ let job = getJob(idOrName), jobs = loadJobs();
906
+ return jobs.splice(jobs.indexOf(job), 1), await persist(), job;
907
+ }
908
+ async function getDueJobs(now = /* @__PURE__ */ new Date()) {
909
+ let due = [], changed = !1;
910
+ for (let job of loadJobs()) {
911
+ if (!job.enabled || job.state === "paused" || job.state === "completed" || !job.nextRunAt)
912
+ continue;
913
+ let next = new Date(job.nextRunAt).getTime();
914
+ if (Number.isNaN(next) || now.getTime() < next)
915
+ continue;
916
+ if (job.schedule.kind === "once") {
917
+ now.getTime() - next <= ONE_SHOT_GRACE_MS ? due.push(job) : (job.state = "error", job.lastStatus = "error", job.lastError = "missed one-shot schedule beyond the 120s recovery grace", job.nextRunAt = null, changed = !0);
918
+ continue;
919
+ }
920
+ let grace = Math.min(Math.max(periodMs(job, now) / 2, MIN_GRACE_MS), MAX_GRACE_MS);
921
+ now.getTime() - next > grace && (job.nextRunAt = nextSlotAfter(job, now)?.toISOString() ?? null, changed = !0), due.push(job);
922
+ }
923
+ return changed && await persist(), due;
924
+ }
925
+ async function advanceNextRun(jobId) {
926
+ let job = getJob(jobId);
927
+ return job.schedule.kind !== "once" && (job.nextRunAt = nextSlotAfter(job, /* @__PURE__ */ new Date())?.toISOString() ?? computeNextRun(job)?.toISOString() ?? null, await persist()), job;
928
+ }
929
+ async function markJobRun(jobId, result) {
930
+ let job = getJob(jobId), now = /* @__PURE__ */ new Date();
931
+ if (job.lastRunAt = now.toISOString(), job.lastStatus = result.status, job.lastError = result.error ?? null, job.repeat.completed += 1, job.repeat.times !== null && job.repeat.completed >= job.repeat.times)
932
+ job.state = "completed", job.nextRunAt = null;
933
+ else if (job.schedule.kind === "interval") {
934
+ let current = job.nextRunAt ? new Date(job.nextRunAt) : now;
935
+ current.getTime() > now.getTime() ? job.nextRunAt = current.toISOString() : job.nextRunAt = nextSlotAfter(job, now)?.toISOString() ?? null;
936
+ } else job.schedule.kind === "cron" && (job.nextRunAt = new E(job.schedule.expr).nextRun(now)?.toISOString() ?? null);
937
+ return await persist(), job;
938
+ }
939
+ function formatStamp(d) {
940
+ let p2 = (n) => String(n).padStart(2, "0");
941
+ return `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())}_${p2(d.getHours())}-${p2(d.getMinutes())}-${p2(d.getSeconds())}`;
942
+ }
943
+ function parseStamp(stamp) {
944
+ let m2 = /^(\d{4})-(\d{2})-(\d{2})_(\d{2})-(\d{2})-(\d{2})/.exec(stamp);
945
+ return m2 ? new Date(Number(m2[1]), Number(m2[2]) - 1, Number(m2[3]), Number(m2[4]), Number(m2[5]), Number(m2[6])) : /* @__PURE__ */ new Date();
946
+ }
947
+ var lastOutputStamp = "";
948
+ function nextOutputStamp() {
949
+ let d = /* @__PURE__ */ new Date(), stamp = formatStamp(d);
950
+ return stamp <= lastOutputStamp && (d = new Date(parseStamp(lastOutputStamp).getTime() + 1e3), stamp = formatStamp(d)), lastOutputStamp = stamp, stamp;
951
+ }
952
+ function listOutputFiles(jobId) {
953
+ let dir = outputDir(jobId);
954
+ return existsSync(dir) ? readdirSync(dir).filter((f2) => f2.endsWith(".md")).sort() : [];
955
+ }
956
+ async function saveJobOutput(jobId, content) {
957
+ let dir = outputDir(jobId);
958
+ mkdirSync(dir, { recursive: !0 });
959
+ let file = join(dir, `${nextOutputStamp()}.md`);
960
+ writeFileSync(file, content, "utf-8");
961
+ let files = listOutputFiles(jobId);
962
+ for (; files.length > OUTPUT_RETENTION; ) {
963
+ let oldest = files.shift();
964
+ oldest && rmSync(join(dir, oldest), { force: !0 });
965
+ }
966
+ return file;
967
+ }
968
+ function getLatestJobOutput(jobId) {
969
+ let files = listOutputFiles(jobId), latest = files[files.length - 1];
970
+ if (!latest)
971
+ return null;
972
+ try {
973
+ return readFileSync(join(outputDir(jobId), latest), "utf-8");
974
+ } catch {
975
+ return null;
976
+ }
977
+ }
978
+
979
+ // packages/coding-agent/dist/core/cron/origin-context.js
980
+ import { AsyncLocalStorage } from "node:async_hooks";
981
+ var storage = new AsyncLocalStorage();
982
+ function runWithOrigin(origin, fn) {
983
+ return storage.run(origin, fn);
984
+ }
985
+ function currentOrigin() {
986
+ return storage.getStore();
987
+ }
988
+
989
+ // packages/coding-agent/dist/core/cron/scheduler.js
990
+ var SILENT_TAG = "[SILENT]";
991
+ function cronPromptPrefix(job) {
992
+ return `You are running as a scheduled cron job '${job.name}'. Delivery of your final response is automatic; respond with ${SILENT_TAG} to suppress delivery.`;
993
+ }
994
+ function isSilent(text) {
995
+ let trimmed = text.trim();
996
+ if (trimmed === SILENT_TAG)
997
+ return !0;
998
+ let lines = trimmed.split(`
999
+ `);
1000
+ return lines[0].trim() === SILENT_TAG || lines[lines.length - 1].trim() === SILENT_TAG;
1001
+ }
1002
+ function buildJobPrompt(job) {
1003
+ let parts = [cronPromptPrefix(job)];
1004
+ for (let upstreamId of job.contextFrom ?? []) {
1005
+ let output = getLatestJobOutput(upstreamId);
1006
+ output && parts.push(`Latest output from cron job '${upstreamId}':
1007
+ ${output.slice(0, CONTEXT_OUTPUT_CAP)}`);
1008
+ }
1009
+ return parts.push(job.prompt), parts.join(`
1010
+
1011
+ `);
1012
+ }
1013
+ function errorMessage(err) {
1014
+ return err instanceof Error ? err.message : String(err);
1015
+ }
1016
+ function oneLine(text) {
1017
+ return text.replace(/\s+/g, " ").trim().slice(0, 200);
1018
+ }
1019
+ async function recordDeliveryError(jobId, error, previous) {
1020
+ error === null && previous === null || await updateJob(jobId, { lastDeliveryError: error });
1021
+ }
1022
+ async function deliverFailure(job, deps, message) {
1023
+ try {
1024
+ await deps.deliverResult(job, `Cron job '${job.name}' failed: ${oneLine(message)}`), await recordDeliveryError(job.id, null, job.lastDeliveryError);
1025
+ } catch (err) {
1026
+ await recordDeliveryError(job.id, errorMessage(err), job.lastDeliveryError);
1027
+ }
1028
+ }
1029
+ async function executeJob(job, deps) {
1030
+ let text;
1031
+ try {
1032
+ text = await deps.runJob(buildJobPrompt(job), job);
1033
+ } catch (err) {
1034
+ let message = errorMessage(err);
1035
+ await markJobRun(job.id, { status: "error", error: message }), await deliverFailure(job, deps, message);
1036
+ return;
1037
+ }
1038
+ if (!text.trim()) {
1039
+ await markJobRun(job.id, { status: "error", error: "empty response" }), await deliverFailure(job, deps, "empty response");
1040
+ return;
1041
+ }
1042
+ if (await saveJobOutput(job.id, text), isSilent(text)) {
1043
+ await markJobRun(job.id, { status: "ok" });
1044
+ return;
1045
+ }
1046
+ let deliveryError = null;
1047
+ try {
1048
+ await deps.deliverResult(job, text);
1049
+ } catch (err) {
1050
+ deliveryError = errorMessage(err);
1051
+ }
1052
+ await markJobRun(job.id, { status: "ok" }), await recordDeliveryError(job.id, deliveryError, job.lastDeliveryError);
1053
+ }
1054
+ async function runSchedulerTick(deps, now = /* @__PURE__ */ new Date()) {
1055
+ let due = await getDueJobs(now), jobTimeoutMs = deps.jobTimeoutMs ?? 300 * 1e3;
1056
+ for (let dueJob of due) {
1057
+ dueJob.schedule.kind !== "once" && await advanceNextRun(dueJob.id);
1058
+ let job = getJob(dueJob.id), timedOut = !1, executePromise = executeJob(job, deps), timeoutPromise = new Promise((_2, reject) => {
1059
+ setTimeout(() => {
1060
+ timedOut = !0, reject(new Error(`timed out after ${jobTimeoutMs}ms`));
1061
+ }, jobTimeoutMs).unref?.();
1062
+ });
1063
+ try {
1064
+ await Promise.race([executePromise, timeoutPromise]);
1065
+ } catch (err) {
1066
+ if (!timedOut)
1067
+ throw err;
1068
+ let message = err instanceof Error ? err.message : String(err);
1069
+ await markJobRun(job.id, { status: "error", error: message }), await deliverFailure(job, deps, message);
1070
+ }
1071
+ }
1072
+ }
1073
+ function startScheduler(deps) {
1074
+ let intervalMs = deps.intervalMs ?? 6e4, stopped = !1, timer, loop = async () => {
1075
+ if (!stopped) {
1076
+ try {
1077
+ await runSchedulerTick(deps);
1078
+ } catch {
1079
+ }
1080
+ stopped || (timer = setTimeout(loop, intervalMs), timer.unref?.());
1081
+ }
1082
+ };
1083
+ return timer = setTimeout(loop, intervalMs), timer.unref?.(), {
1084
+ stop() {
1085
+ stopped = !0, timer && clearTimeout(timer);
1086
+ }
1087
+ };
1088
+ }
1089
+
1090
+ // packages/coding-agent/dist/gateway/store.js
1091
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
1092
+ import { dirname, join as join2 } from "node:path";
1093
+ var storePathOverride;
1094
+ function storePath() {
1095
+ return storePathOverride ?? join2(getAgentDir(), "gateway-sessions.json");
1096
+ }
1097
+ function readStore() {
1098
+ let path = storePath();
1099
+ if (!existsSync2(path))
1100
+ return {};
1101
+ try {
1102
+ let parsed = JSON.parse(readFileSync2(path, "utf-8"));
1103
+ if (parsed == null || typeof parsed != "object" || Array.isArray(parsed))
1104
+ return {};
1105
+ let out = {};
1106
+ for (let [key, value] of Object.entries(parsed)) {
1107
+ if (value == null || typeof value != "object")
1108
+ continue;
1109
+ let v2 = value;
1110
+ typeof v2.sessionId != "string" || typeof v2.sessionFile != "string" || (out[key] = {
1111
+ sessionId: v2.sessionId,
1112
+ sessionFile: v2.sessionFile,
1113
+ createdAt: typeof v2.createdAt == "string" ? v2.createdAt : (/* @__PURE__ */ new Date(0)).toISOString(),
1114
+ lastActiveAt: typeof v2.lastActiveAt == "string" ? v2.lastActiveAt : (/* @__PURE__ */ new Date(0)).toISOString()
1115
+ });
1116
+ }
1117
+ return out;
1118
+ } catch {
1119
+ return {};
1120
+ }
1121
+ }
1122
+ function writeStore(data) {
1123
+ let path = storePath(), dir = dirname(path);
1124
+ existsSync2(dir) || mkdirSync2(dir, { recursive: !0 });
1125
+ let tmp = `${path}.tmp-${process.pid}`;
1126
+ writeFileSync2(tmp, `${JSON.stringify(data, null, 2)}
1127
+ `, "utf-8"), renameSync2(tmp, path);
1128
+ }
1129
+ function getSession(key) {
1130
+ return readStore()[key];
1131
+ }
1132
+ function putSession(key, entry) {
1133
+ let data = readStore(), existing = data[key], stored = {
1134
+ sessionId: entry.sessionId,
1135
+ sessionFile: entry.sessionFile,
1136
+ createdAt: existing?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1137
+ lastActiveAt: (/* @__PURE__ */ new Date()).toISOString()
1138
+ };
1139
+ return data[key] = stored, writeStore(data), stored;
1140
+ }
1141
+ function touchSession(key) {
1142
+ let data = readStore(), existing = data[key];
1143
+ existing && (existing.lastActiveAt = (/* @__PURE__ */ new Date()).toISOString(), writeStore(data));
1144
+ }
1145
+ function removeSession(key) {
1146
+ let data = readStore();
1147
+ return key in data ? (delete data[key], writeStore(data), !0) : !1;
1148
+ }
1149
+ function listSessions() {
1150
+ return readStore();
1151
+ }
1152
+
1153
+ // packages/coding-agent/dist/gateway/agent-bridge.js
1154
+ import { existsSync as existsSync3 } from "node:fs";
1155
+ function isUserMessageEntry(entry) {
1156
+ return entry.type === "message";
1157
+ }
1158
+ var QUEUED = "__lunr_gateway_queued__", CACHE_CAP = 20, QUEUE_CAP = 5, runDepth = 0;
1159
+ async function shutdownBridgeSession(session, reason, targetSessionFile) {
1160
+ try {
1161
+ session.extensionRunner?.hasHandlers("session_shutdown") && await session.extensionRunner.emit({
1162
+ type: "session_shutdown",
1163
+ reason,
1164
+ ...targetSessionFile ? { targetSessionFile } : {}
1165
+ });
1166
+ } catch (error) {
1167
+ console.error("[gateway] session shutdown handler failed", error);
1168
+ } finally {
1169
+ session.dispose?.();
1170
+ }
1171
+ }
1172
+ async function defaultSessionFactory(key, reopen) {
1173
+ let [{ loadAllBuiltinExtensions }, { getAgentDir: getAgentDir2 }, { registerCustomizeBridge }, { registerMemoryCapBridge }, { registerModelTierBridge }, { createAgentSessionFromServices, createAgentSessionServices }, { SessionManager }, { SettingsManager }, { bindRuntimeBridges }] = await Promise.all([
1174
+ import("./builtin-extensions-7STLFW3A.js"),
1175
+ import("./config-FMEOZSWE.js"),
1176
+ import("./customize-XEXL2DGQ.js"),
1177
+ import("./memory-cap-3S4XRLNP.js"),
1178
+ import("./model-tiers-NJLHUEGK.js"),
1179
+ import("./agent-session-services-RSGP5GDN.js"),
1180
+ import("./session-manager-QEMZBMTM.js"),
1181
+ import("./settings-manager-K6IPIQTI.js"),
1182
+ import("./runtime-bridges-UJ5WJJLN.js")
1183
+ ]), cwd = process.cwd(), agentDir = getAgentDir2(), settingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted: !1 });
1184
+ registerModelTierBridge(settingsManager), registerMemoryCapBridge(settingsManager), registerCustomizeBridge(settingsManager);
1185
+ let sessionManager;
1186
+ reopen && existsSync3(reopen.sessionFile) ? sessionManager = SessionManager.open(reopen.sessionFile) : (reopen && console.warn(`[gateway] stored session file missing for ${key}; starting a fresh session`), sessionManager = SessionManager.create(cwd));
1187
+ let services = await createAgentSessionServices({
1188
+ cwd,
1189
+ agentDir,
1190
+ settingsManager,
1191
+ resourceLoaderOptions: { extensionFactories: await loadAllBuiltinExtensions() }
1192
+ }), { session } = await createAgentSessionFromServices({ services, sessionManager });
1193
+ return bindRuntimeBridges({ session, services }), await session.bindExtensions({
1194
+ mode: "print",
1195
+ onError: (err) => console.error(`[gateway] extension error (${err.extensionPath}): ${err.error}`)
1196
+ }), session;
1197
+ }
1198
+ function extractFinalText(session) {
1199
+ let messages = session.state.messages, last = messages[messages.length - 1];
1200
+ if (last?.role !== "assistant")
1201
+ return "";
1202
+ let assistant = last;
1203
+ if (assistant.stopReason === "error" || assistant.stopReason === "aborted")
1204
+ throw new Error(assistant.errorMessage || `Request ${assistant.stopReason}`);
1205
+ let text = "";
1206
+ for (let content of assistant.content)
1207
+ content.type === "text" && (text += content.text);
1208
+ return text;
1209
+ }
1210
+ var AgentBridge = class {
1211
+ cap;
1212
+ sessionFactory;
1213
+ cache = /* @__PURE__ */ new Map();
1214
+ redoStack = /* @__PURE__ */ new Map();
1215
+ creating = /* @__PURE__ */ new Map();
1216
+ constructor(options = {}) {
1217
+ this.cap = options.cacheCap ?? CACHE_CAP, this.sessionFactory = options.sessionFactory ?? defaultSessionFactory;
1218
+ }
1219
+ /**
1220
+ * Run one conversational turn. Resolves with the final assistant text, or
1221
+ * the QUEUED sentinel when the session was busy (router must not reply).
1222
+ */
1223
+ async runTurn(key, event, callbacks = {}) {
1224
+ let entry = await this.getOrCreate(key);
1225
+ if (entry.busy)
1226
+ return entry.queue.length >= QUEUE_CAP && (entry.queue.shift(), entry.dropped++), entry.queue.push(event), QUEUED;
1227
+ entry.busy = !0;
1228
+ let result;
1229
+ try {
1230
+ result = await this.runPrompt(entry, event.text, callbacks, event.source, event.attachments);
1231
+ } catch (err) {
1232
+ throw entry.busy = !1, err;
1233
+ }
1234
+ return touchSession(key), this.drainQueue(entry, callbacks).finally(() => {
1235
+ entry.busy = !1;
1236
+ }), result;
1237
+ }
1238
+ async abort(key) {
1239
+ await this.cache.get(key)?.session.abort();
1240
+ }
1241
+ /** Return the live session for a key, or null when none exists yet. */
1242
+ async getSession(key) {
1243
+ let cached = this.cache.get(key);
1244
+ return cached ? cached.session : getSession(key) ? (await this.getOrCreate(key)).session : null;
1245
+ }
1246
+ /** Switch the chat to a different persisted session file. */
1247
+ async switchSession(key, sessionFile) {
1248
+ let entry = this.cache.get(key);
1249
+ if (entry?.busy)
1250
+ throw new Error("Session is busy \u2014 /stop first or wait");
1251
+ if (entry) {
1252
+ let oldSessionId = entry.session.sessionManager?.getSessionId();
1253
+ entry.unsubscribe?.(), this.cache.delete(key), await shutdownBridgeSession(entry.session, "resume", sessionFile), oldSessionId && deletePermissionContext(oldSessionId);
1254
+ }
1255
+ removeSession(key), this.redoStack.delete(key);
1256
+ let session = await this.sessionFactory(key, { sessionFile }), newFile = session.sessionManager?.getSessionFile(), newSessionId = session.sessionManager?.getSessionId();
1257
+ newFile && putSession(key, { sessionId: newSessionId ?? key, sessionFile: newFile }), newSessionId && createPermissionContext(newSessionId);
1258
+ let newEntry = { session, busy: !1, queue: [], dropped: 0 };
1259
+ this.cache.set(key, newEntry), newEntry.unsubscribe = this._subscribeToSession(key, newEntry), await this._enforceCacheCap(key);
1260
+ }
1261
+ /** Undo the last user turn and push the previous leaf onto the redo stack. */
1262
+ async undo(key) {
1263
+ let session = await this.getSession(key);
1264
+ if (!session)
1265
+ throw new Error("No session");
1266
+ if (session.isStreaming)
1267
+ throw new Error("Wait for the current response to finish");
1268
+ let branch = session.sessionManager?.getBranch() ?? [], lastUserIndex = -1;
1269
+ for (let i = branch.length - 1; i >= 0; i--) {
1270
+ let entry = branch[i];
1271
+ if (isUserMessageEntry(entry) && entry.message.role === "user") {
1272
+ lastUserIndex = i;
1273
+ break;
1274
+ }
1275
+ }
1276
+ if (lastUserIndex === -1)
1277
+ throw new Error("Nothing to undo");
1278
+ let lastUser = branch[lastUserIndex];
1279
+ if (!isUserMessageEntry(lastUser))
1280
+ throw new Error("Nothing to undo");
1281
+ let leafId = session.sessionManager?.getLeafId() ?? null, targetId;
1282
+ if (lastUser.id === leafId) {
1283
+ if (!lastUser.parentId)
1284
+ throw new Error("Nothing to undo");
1285
+ targetId = lastUser.parentId;
1286
+ } else
1287
+ targetId = lastUser.id;
1288
+ if ((await session.navigateTree(targetId, {})).cancelled)
1289
+ throw new Error("Navigation cancelled");
1290
+ if (leafId) {
1291
+ let stack = this.redoStack.get(key) ?? [];
1292
+ stack.push(leafId), this.redoStack.set(key, stack);
1293
+ }
1294
+ return { userText: extractUserText(lastUser.message) };
1295
+ }
1296
+ /** Redo to the leaf saved by the most recent undo. */
1297
+ async redo(key) {
1298
+ let session = await this.getSession(key);
1299
+ if (!session)
1300
+ throw new Error("No session");
1301
+ if (session.isStreaming)
1302
+ throw new Error("Wait for the current response to finish");
1303
+ let stack = this.redoStack.get(key) ?? [], targetId = stack.pop();
1304
+ if (!targetId)
1305
+ throw new Error("Nothing to redo");
1306
+ if (this.redoStack.set(key, stack), (await session.navigateTree(targetId, {})).cancelled)
1307
+ throw stack.push(targetId), this.redoStack.set(key, stack), new Error("Navigation cancelled");
1308
+ }
1309
+ /** Test/debug hook: how many redo targets are saved for a key. */
1310
+ getRedoStackLength(key) {
1311
+ return this.redoStack.get(key)?.length ?? 0;
1312
+ }
1313
+ /** Drop the cached session (disposing it) and forget the store entry (/new, /reset). */
1314
+ async reset(key) {
1315
+ let entry = this.cache.get(key);
1316
+ if (entry) {
1317
+ entry.queue.length = 0, entry.dropped = 0;
1318
+ try {
1319
+ await entry.session.abort();
1320
+ } catch {
1321
+ }
1322
+ entry.unsubscribe?.(), this.cache.delete(key), await shutdownBridgeSession(entry.session, "new");
1323
+ }
1324
+ removeSession(key), this.redoStack.delete(key);
1325
+ }
1326
+ getStatus(key) {
1327
+ let entry = this.cache.get(key);
1328
+ return {
1329
+ busy: entry?.busy ?? !1,
1330
+ queueDepth: entry?.queue.length ?? 0,
1331
+ createdAt: getSession(key)?.createdAt
1332
+ };
1333
+ }
1334
+ /** One prompt → final text. Increments runDepth; streams deltas when asked. */
1335
+ async runPrompt(entry, text, callbacks, source, attachments) {
1336
+ let { session } = entry, unsubscribe;
1337
+ if (callbacks.onDelta) {
1338
+ let onDelta = callbacks.onDelta, streamedLen = 0;
1339
+ unsubscribe = session.subscribe((event) => {
1340
+ if (event.type !== "message_update")
1341
+ return;
1342
+ let assistantEvent = event.assistantMessageEvent;
1343
+ if (assistantEvent.type !== "text_delta")
1344
+ return;
1345
+ let full = "";
1346
+ for (let content of assistantEvent.partial.content)
1347
+ content.type === "text" && (full += content.text);
1348
+ full.length < streamedLen && (streamedLen = 0), full.length > streamedLen && (onDelta(full.slice(streamedLen)), streamedLen = full.length);
1349
+ });
1350
+ }
1351
+ runDepth++;
1352
+ try {
1353
+ let images = [], notes = [];
1354
+ for (let attachment of attachments ?? []) {
1355
+ let bytes = Buffer.from(attachment.data, "base64"), processed = await processImage(new Uint8Array(bytes), attachment.mimeType);
1356
+ if (processed.ok) {
1357
+ images.push({ type: "image", data: processed.data, mimeType: processed.mimeType });
1358
+ for (let hint of processed.hints)
1359
+ notes.push(hint);
1360
+ } else
1361
+ notes.push(processed.message);
1362
+ }
1363
+ let promptText = notes.length > 0 ? `${text}
1364
+
1365
+ ${notes.join(" ")}` : text;
1366
+ await runWithOrigin({
1367
+ platform: source.platform,
1368
+ chatId: source.chatId,
1369
+ threadId: source.threadId,
1370
+ chatType: source.chatType
1371
+ }, () => session.prompt(promptText, { source: "extension", ...images.length ? { images } : {} }));
1372
+ } finally {
1373
+ runDepth--, unsubscribe?.();
1374
+ }
1375
+ return extractFinalText(session);
1376
+ }
1377
+ /** Drain the queue FIFO: all queued messages become one concatenated turn. */
1378
+ async drainQueue(entry, callbacks) {
1379
+ for (; entry.queue.length > 0; ) {
1380
+ let items = entry.queue.splice(0), parts = items.map((item) => item.text), attachments = items.flatMap((item) => item.attachments ?? []);
1381
+ entry.dropped > 0 && (parts.unshift(`[gateway: ${entry.dropped} earlier message(s) were dropped \u2014 the queue was full]`), entry.dropped = 0);
1382
+ try {
1383
+ let text = await this.runPrompt(entry, parts.join(`
1384
+
1385
+ `), {}, items[items.length - 1].source, attachments);
1386
+ callbacks.onFollowUpResult?.(text);
1387
+ } catch (err) {
1388
+ callbacks.onError?.(err instanceof Error ? err.message : String(err));
1389
+ return;
1390
+ }
1391
+ }
1392
+ }
1393
+ async getOrCreate(key) {
1394
+ let cached = this.cache.get(key);
1395
+ if (cached)
1396
+ return this.cache.delete(key), this.cache.set(key, cached), cached;
1397
+ let pending = this.creating.get(key);
1398
+ if (!pending) {
1399
+ pending = this.createEntry(key), this.creating.set(key, pending);
1400
+ try {
1401
+ await pending;
1402
+ } finally {
1403
+ this.creating.delete(key);
1404
+ }
1405
+ }
1406
+ return pending;
1407
+ }
1408
+ async createEntry(key) {
1409
+ let stored = getSession(key), session = await this.sessionFactory(key, stored ? { sessionFile: stored.sessionFile } : void 0), sessionFile = session.sessionManager?.getSessionFile(), sessionId = session.sessionManager?.getSessionId();
1410
+ sessionFile && putSession(key, { sessionId: sessionId ?? key, sessionFile }), sessionId && createPermissionContext(sessionId);
1411
+ let entry = { session, busy: !1, queue: [], dropped: 0, unsubscribe: void 0 };
1412
+ return this.cache.set(key, entry), entry.unsubscribe = this._subscribeToSession(key, entry), await this._enforceCacheCap(key), entry;
1413
+ }
1414
+ async _enforceCacheCap(protectedKey) {
1415
+ for (; this.cache.size > this.cap; ) {
1416
+ let oldestKey, oldest;
1417
+ for (let [key, entry] of this.cache)
1418
+ if (key !== protectedKey && !entry.busy) {
1419
+ oldestKey = key, oldest = entry;
1420
+ break;
1421
+ }
1422
+ if (!oldest || !oldestKey) {
1423
+ this.cap = this.cache.size;
1424
+ break;
1425
+ }
1426
+ oldest.unsubscribe?.(), this.cache.delete(oldestKey), await shutdownBridgeSession(oldest.session, "quit");
1427
+ let evictedSessionId = oldest.session.sessionManager?.getSessionId();
1428
+ evictedSessionId && deletePermissionContext(evictedSessionId);
1429
+ }
1430
+ }
1431
+ _subscribeToSession(key, entry) {
1432
+ return entry.session.subscribe((event) => this._handleSessionEvent(key, event));
1433
+ }
1434
+ _handleSessionEvent(key, event) {
1435
+ event.type === "message_start" && event.message?.role === "user" && this.redoStack.delete(key);
1436
+ }
1437
+ };
1438
+ function extractUserText(message) {
1439
+ let text = "";
1440
+ if ("content" in message && Array.isArray(message.content))
1441
+ for (let block of message.content)
1442
+ block && typeof block == "object" && "type" in block && block.type === "text" && "text" in block && typeof block.text == "string" && (text += block.text);
1443
+ return text;
1444
+ }
1445
+
1446
+ // packages/coding-agent/dist/gateway/text.js
1447
+ function utf16Len(s2) {
1448
+ return s2.length;
1449
+ }
1450
+ var graphemeSegmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
1451
+ function surrogateSafeCut(s2, cut) {
1452
+ if (cut > 0) {
1453
+ let code = s2.charCodeAt(cut - 1);
1454
+ if (code >= 55296 && code <= 56319)
1455
+ return cut - 1;
1456
+ }
1457
+ return cut;
1458
+ }
1459
+ function graphemeSafeCut(s2, maxIndex) {
1460
+ if (maxIndex <= 0)
1461
+ return 0;
1462
+ let end = 0;
1463
+ for (let segment of graphemeSegmenter.segment(s2)) {
1464
+ let nextEnd = segment.index + segment.segment.length;
1465
+ if (nextEnd > maxIndex)
1466
+ break;
1467
+ end = nextEnd;
1468
+ }
1469
+ return surrogateSafeCut(s2, end);
1470
+ }
1471
+ function findSplitPoint(window, limit) {
1472
+ let blank = window.lastIndexOf(`
1473
+
1474
+ `);
1475
+ if (blank > 0)
1476
+ return blank + 1;
1477
+ let newline = window.lastIndexOf(`
1478
+ `);
1479
+ if (newline > 0)
1480
+ return newline + 1;
1481
+ let space = window.lastIndexOf(" ");
1482
+ return space > 0 ? space + 1 : graphemeSafeCut(window, limit);
1483
+ }
1484
+ var FENCE_RE = /^\s*```/;
1485
+ function openFenceAtEnd(chunk) {
1486
+ let opener;
1487
+ for (let line of chunk.split(`
1488
+ `))
1489
+ FENCE_RE.test(line) && (opener = opener === void 0 ? line.trim() : void 0);
1490
+ return opener;
1491
+ }
1492
+ var FENCE_CLOSE = "\n```";
1493
+ function splitRaw(text, limit) {
1494
+ let chunks = [], rest = text;
1495
+ for (; utf16Len(rest) > limit; ) {
1496
+ let cut = findSplitPoint(rest.slice(0, limit), limit), chunk = rest.slice(0, cut).replace(/\s+$/, ""), opener = openFenceAtEnd(chunk);
1497
+ for (; opener !== void 0 && chunk.length + FENCE_CLOSE.length > limit; )
1498
+ cut = findSplitPoint(rest.slice(0, limit - FENCE_CLOSE.length), limit - FENCE_CLOSE.length), chunk = rest.slice(0, cut).replace(/\s+$/, ""), opener = openFenceAtEnd(chunk);
1499
+ opener !== void 0 && chunk === opener && (cut = graphemeSafeCut(rest, Math.max(1, limit - FENCE_CLOSE.length)), chunk = rest.slice(0, cut), opener = openFenceAtEnd(chunk), opener !== void 0 && chunk === opener && (cut = graphemeSafeCut(rest, limit), chunk = rest.slice(0, cut), opener = void 0)), rest = rest.slice(cut).replace(/^\n+/, ""), opener !== void 0 && (chunk += FENCE_CLOSE, rest = `${opener}
1500
+ ${rest}`), chunk.length > 0 && chunks.push(chunk);
1501
+ }
1502
+ return rest.length > 0 && chunks.push(rest), chunks;
1503
+ }
1504
+ function indicatorReserve(m2) {
1505
+ return 4 + 2 * String(m2).length;
1506
+ }
1507
+ function splitMessage(text, max) {
1508
+ if (max < 1)
1509
+ throw new RangeError("max must be >= 1");
1510
+ if (utf16Len(text) <= max)
1511
+ return [text];
1512
+ let chunks = splitRaw(text, max);
1513
+ if (chunks.length > 1 && max - indicatorReserve(chunks.length) >= 1) {
1514
+ let reserve = indicatorReserve(chunks.length), adjusted = splitRaw(text, max - reserve);
1515
+ chunks = indicatorReserve(adjusted.length) === reserve ? adjusted : splitRaw(text, max - indicatorReserve(adjusted.length));
1516
+ }
1517
+ return chunks.length <= 1 ? chunks : chunks.map((chunk, i) => `${chunk} (${i + 1}/${chunks.length})`);
1518
+ }
1519
+
1520
+ // packages/coding-agent/dist/gateway/cron.js
1521
+ var DELIVERY_BRIDGE_SYMBOL = /* @__PURE__ */ Symbol.for("@lunr/cron-delivery"), KNOWN_PLATFORMS = ["telegram", "discord"];
1522
+ async function defaultCronSessionFactory(job, modelOverride) {
1523
+ let [{ loadAllBuiltinExtensions }, { getAgentDir: getAgentDir2 }, { registerCustomizeBridge }, { registerMemoryCapBridge }, { registerModelTierBridge }, { createAgentSessionFromServices, createAgentSessionServices }, { SessionManager }, { SettingsManager }, { bindRuntimeBridges }] = await Promise.all([
1524
+ import("./builtin-extensions-7STLFW3A.js"),
1525
+ import("./config-FMEOZSWE.js"),
1526
+ import("./customize-XEXL2DGQ.js"),
1527
+ import("./memory-cap-3S4XRLNP.js"),
1528
+ import("./model-tiers-NJLHUEGK.js"),
1529
+ import("./agent-session-services-RSGP5GDN.js"),
1530
+ import("./session-manager-QEMZBMTM.js"),
1531
+ import("./settings-manager-K6IPIQTI.js"),
1532
+ import("./runtime-bridges-UJ5WJJLN.js")
1533
+ ]), cwd = job.workdir ?? process.cwd(), agentDir = getAgentDir2(), settingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted: !1 });
1534
+ registerModelTierBridge(settingsManager), registerMemoryCapBridge(settingsManager), registerCustomizeBridge(settingsManager);
1535
+ let sessionManager = SessionManager.inMemory(cwd), services = await createAgentSessionServices({
1536
+ cwd,
1537
+ agentDir,
1538
+ settingsManager,
1539
+ resourceLoaderOptions: { extensionFactories: await loadAllBuiltinExtensions() }
1540
+ }), model;
1541
+ if (modelOverride) {
1542
+ let resolved = services.modelRuntime.getModel(modelOverride.provider, modelOverride.modelId);
1543
+ if (!resolved)
1544
+ throw new Error(`model not found: ${modelOverride.provider}/${modelOverride.modelId}`);
1545
+ if (!services.modelRuntime.hasConfiguredAuth(resolved.provider))
1546
+ throw new Error(`no configured auth for provider: ${modelOverride.provider}`);
1547
+ model = resolved;
1548
+ }
1549
+ let { session } = await createAgentSessionFromServices({ services, sessionManager, model }), permissionId = sessionManager.getSessionId();
1550
+ createPermissionContext(permissionId, settingsManager.getDefaultPermissionMode(), !1);
1551
+ let dispose = session.dispose.bind(session);
1552
+ session.dispose = () => {
1553
+ deletePermissionContext(permissionId), dispose();
1554
+ };
1555
+ try {
1556
+ return bindRuntimeBridges({ session, services }), await session.bindExtensions({
1557
+ mode: "print",
1558
+ onError: (err) => console.error(`[gateway cron] extension error (${err.extensionPath}): ${err.error}`)
1559
+ }), session;
1560
+ } catch (error) {
1561
+ throw await shutdownBridgeSession(session, "quit"), error;
1562
+ }
1563
+ }
1564
+ function extractFinalText2(session) {
1565
+ let messages = session.state.messages, last = messages[messages.length - 1];
1566
+ if (last?.role !== "assistant")
1567
+ return "";
1568
+ let assistant = last;
1569
+ if (assistant.stopReason === "error" || assistant.stopReason === "aborted")
1570
+ throw new Error(assistant.errorMessage || `Request ${assistant.stopReason}`);
1571
+ let text = "";
1572
+ for (let content of assistant.content ?? [])
1573
+ content.type === "text" && (text += content.text ?? "");
1574
+ return text;
1575
+ }
1576
+ var EXPLICIT_TARGET_RE = /^([a-z0-9_-]+):([^:]+)(?::([^:]+))?$/i;
1577
+ function resolveTarget(target, job, cfg) {
1578
+ if (target === "origin") {
1579
+ let origin = job.origin;
1580
+ if (origin?.platform && origin.chatId)
1581
+ return { platform: origin.platform, chatId: origin.chatId, threadId: origin.threadId };
1582
+ let platforms = origin?.platform ? [origin.platform] : KNOWN_PLATFORMS;
1583
+ for (let platform2 of platforms) {
1584
+ let home2 = platformConfigFor(cfg, platform2)?.homeChannel;
1585
+ if (home2)
1586
+ return { platform: platform2, chatId: home2 };
1587
+ }
1588
+ return 'deliver target "origin": job has no origin and no homeChannel is configured';
1589
+ }
1590
+ let explicit = EXPLICIT_TARGET_RE.exec(target), platform = explicit ? explicit[1].toLowerCase() : target.toLowerCase();
1591
+ if (platformConfigFor(cfg, platform) === void 0)
1592
+ return `unknown platform "${explicit ? explicit[1] : target}"`;
1593
+ if (explicit)
1594
+ return { platform, chatId: explicit[2], threadId: explicit[3] };
1595
+ let home = platformConfigFor(cfg, platform)?.homeChannel;
1596
+ return home ? { platform, chatId: home } : `no homeChannel configured for ${platform}`;
1597
+ }
1598
+ function isAllowedDeliverChat(cfg, platform, chatId, origin) {
1599
+ let platformCfg = platformConfigFor(cfg, platform);
1600
+ return platformCfg ? platformCfg.homeChannel && platformCfg.homeChannel === chatId || platformCfg.allowedChats?.includes(chatId) ? !0 : origin?.platform === platform && origin.chatId === chatId : !1;
1601
+ }
1602
+ function createDeliverValidator(cfg) {
1603
+ return (deliver, origin) => {
1604
+ let targets = deliver.split(",").map((t) => t.trim()).filter(Boolean);
1605
+ for (let target of targets) {
1606
+ if (target === "local" || target === "origin")
1607
+ continue;
1608
+ let explicit = EXPLICIT_TARGET_RE.exec(target), platform = explicit ? explicit[1].toLowerCase() : target.toLowerCase(), platformCfg = platformConfigFor(cfg, platform);
1609
+ if (!platformCfg)
1610
+ return `unknown platform "${explicit ? explicit[1] : target}"`;
1611
+ if (explicit) {
1612
+ if (!isAllowedDeliverChat(cfg, platform, explicit[2], origin))
1613
+ return `deliver target "${target}" is not an allowed chat for ${platform}`;
1614
+ } else if (!platformCfg.homeChannel)
1615
+ return `no homeChannel configured for ${platform}`;
1616
+ }
1617
+ };
1618
+ }
1619
+ function wrapCronContent(job, content) {
1620
+ return `\u263E Cron: ${job.name}
1621
+ \u2014\u2014\u2014
1622
+ ${content}`;
1623
+ }
1624
+ function createPlatformDeliverer(adapters, cfg) {
1625
+ return async (job, content) => {
1626
+ let targets = job.deliver.split(",").map((t) => t.trim()).filter(Boolean), firstError = null;
1627
+ for (let target of targets) {
1628
+ if (target === "local")
1629
+ continue;
1630
+ let resolved = resolveTarget(target, job, cfg);
1631
+ if (typeof resolved == "string") {
1632
+ firstError ??= resolved;
1633
+ continue;
1634
+ }
1635
+ if (!isAllowedDeliverChat(cfg, resolved.platform, resolved.chatId, job.origin)) {
1636
+ firstError ??= `deliver target "${target}" is not an allowed chat for ${resolved.platform}`;
1637
+ continue;
1638
+ }
1639
+ let adapter = adapters.get(resolved.platform);
1640
+ if (!adapter) {
1641
+ firstError ??= `no adapter connected for ${resolved.platform}`;
1642
+ continue;
1643
+ }
1644
+ let wrapped = wrapCronContent(job, content);
1645
+ for (let chunk of splitMessage(wrapped, adapter.maxMessageLength))
1646
+ try {
1647
+ let result = await adapter.send(resolved.chatId, chunk, {
1648
+ threadId: resolved.threadId
1649
+ });
1650
+ if (!result.success) {
1651
+ firstError ??= `${resolved.platform} send failed: ${result.error ?? "unknown error"}`;
1652
+ break;
1653
+ }
1654
+ } catch (err) {
1655
+ firstError ??= `${resolved.platform} send failed: ${err instanceof Error ? err.message : String(err)}`;
1656
+ break;
1657
+ }
1658
+ }
1659
+ return firstError;
1660
+ };
1661
+ }
1662
+ function withAttemptTimeout(promise, ms) {
1663
+ return Promise.race([
1664
+ promise,
1665
+ new Promise((_2, reject) => {
1666
+ setTimeout(() => reject(new Error(`attempt timed out after ${ms}ms`)), ms).unref?.();
1667
+ })
1668
+ ]);
1669
+ }
1670
+ async function readCronFallbackModels() {
1671
+ try {
1672
+ let [{ getAgentDir: getAgentDir2 }, { SettingsManager }] = await Promise.all([
1673
+ import("./config-FMEOZSWE.js"),
1674
+ import("./settings-manager-K6IPIQTI.js")
1675
+ ]), settingsManager = SettingsManager.create(process.cwd(), getAgentDir2(), { projectTrusted: !1 }), out = [];
1676
+ for (let entry of settingsManager.getCronFallbackModels()) {
1677
+ let idx = entry.indexOf("/");
1678
+ if (idx <= 0 || idx === entry.length - 1) {
1679
+ console.error(`[gateway cron] ignoring invalid cronFallbackModels entry "${entry}" (want "provider/modelId")`);
1680
+ continue;
1681
+ }
1682
+ out.push({ provider: entry.slice(0, idx), modelId: entry.slice(idx + 1) });
1683
+ }
1684
+ return out;
1685
+ } catch (err) {
1686
+ return console.error(`[gateway cron] failed to read cronFallbackModels: ${err instanceof Error ? err.message : String(err)}`), [];
1687
+ }
1688
+ }
1689
+ function startGatewayCron(options) {
1690
+ let { adapters, cfg } = options, sessionFactory = options.sessionFactory ?? defaultCronSessionFactory, platformDeliverer = createPlatformDeliverer(adapters, cfg), jobTimeoutMs = 300 * 1e3;
1691
+ setCronDeliverValidator(createDeliverValidator(cfg)), globalThis[DELIVERY_BRIDGE_SYMBOL] = platformDeliverer;
1692
+ let scheduler = startScheduler({ runJob: async (prompt, job) => {
1693
+ let candidates = [void 0, ...options.fallbackModels ?? await readCronFallbackModels()], attemptTimeoutMs = Math.floor(jobTimeoutMs / candidates.length), errors = [];
1694
+ beginCronFire();
1695
+ try {
1696
+ for (let candidate of candidates) {
1697
+ let label = candidate ? `${candidate.provider}/${candidate.modelId}` : "default model", session;
1698
+ try {
1699
+ session = await sessionFactory(job, candidate), globalThis[DELIVERY_BRIDGE_SYMBOL] = platformDeliverer, await withAttemptTimeout(session.prompt(prompt, { source: "extension" }), attemptTimeoutMs);
1700
+ let text = extractFinalText2(session);
1701
+ return candidate ? `[fell back to ${label}]
1702
+ ${text}` : text;
1703
+ } catch (err) {
1704
+ errors.push(`${label}: ${err instanceof Error ? err.message : String(err)}`);
1705
+ } finally {
1706
+ session && await shutdownBridgeSession(session, "quit");
1707
+ }
1708
+ }
1709
+ throw new Error(errors.join(" | ") || "no model candidates");
1710
+ } finally {
1711
+ endCronFire();
1712
+ }
1713
+ }, deliverResult: async (job, content) => {
1714
+ let bridge = globalThis[DELIVERY_BRIDGE_SYMBOL];
1715
+ if (!bridge)
1716
+ throw new Error("no cron delivery bridge registered");
1717
+ let err = await bridge(job, content);
1718
+ if (err)
1719
+ throw new Error(err);
1720
+ }, intervalMs: options.intervalMs, jobTimeoutMs });
1721
+ return { stop: () => scheduler.stop(), intervalMs: options.intervalMs ?? 6e4 };
1722
+ }
1723
+
1724
+ export {
1725
+ parseSchedule,
1726
+ setCronDeliverValidator,
1727
+ createJob,
1728
+ getJob,
1729
+ listJobs,
1730
+ updateJob,
1731
+ pauseJob,
1732
+ resumeJob,
1733
+ removeJob,
1734
+ currentOrigin,
1735
+ executeJob,
1736
+ startScheduler,
1737
+ listSessions,
1738
+ QUEUED,
1739
+ AgentBridge,
1740
+ splitMessage,
1741
+ createDeliverValidator,
1742
+ startGatewayCron
1743
+ };