@cortex-agent/server 2026.5.19-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 (503) hide show
  1. package/defaults/.claude/settings.json +13 -0
  2. package/defaults/CORTEX.md +15 -0
  3. package/defaults/config/budget.json +4 -0
  4. package/defaults/config/session-hooks.json +7 -0
  5. package/defaults/config/thread-templates.json +528 -0
  6. package/defaults/context/CORTEX.md +40 -0
  7. package/defaults/context/decisions/DR-0012.md +54 -0
  8. package/defaults/context/ideas/CORTEX.md +10 -0
  9. package/defaults/context/projects/CORTEX.md +25 -0
  10. package/defaults/context/scans/CORTEX.md +13 -0
  11. package/defaults/context/user/CORTEX.md +21 -0
  12. package/defaults/data/schedules.json +52 -0
  13. package/defaults/gitignore +44 -0
  14. package/defaults/hooks/ask-user-question-hook.mjs +66 -0
  15. package/defaults/hooks/cortex-md-injector.mjs +237 -0
  16. package/defaults/hooks/exit-plan-mode-hook.mjs +84 -0
  17. package/defaults/hooks/memory-ref-tracker.mjs +154 -0
  18. package/defaults/hooks/new-session-hook.mjs +83 -0
  19. package/defaults/hooks/post-task-hook.mjs +63 -0
  20. package/defaults/hooks/rules-loader.mjs +212 -0
  21. package/defaults/hooks/sensitive-file-edit.mjs +84 -0
  22. package/defaults/hooks/session-activity-tracker.mjs +254 -0
  23. package/defaults/hooks/task-status-check.mjs +218 -0
  24. package/defaults/hooks/tasks-yaml-guard.mjs +230 -0
  25. package/defaults/plugins/cortex-coder/.claude-plugin/plugin.json +5 -0
  26. package/defaults/plugins/cortex-coder/skills/cli-standards/SKILL.md +208 -0
  27. package/defaults/plugins/cortex-coder/skills/code-standards/SKILL.md +146 -0
  28. package/defaults/plugins/cortex-coder/skills/develop/SKILL.md +164 -0
  29. package/defaults/plugins/cortex-common/.claude-plugin/plugin.json +5 -0
  30. package/defaults/plugins/cortex-common/skills/compound/SKILL.md +349 -0
  31. package/defaults/plugins/cortex-common/skills/compound-simple/SKILL.md +104 -0
  32. package/defaults/plugins/cortex-common/skills/critique/SKILL.md +88 -0
  33. package/defaults/plugins/cortex-common/skills/debug-campaign/SKILL.md +508 -0
  34. package/defaults/plugins/cortex-common/skills/diagnose/SKILL.md +169 -0
  35. package/defaults/plugins/cortex-common/skills/postmortem/SKILL.md +135 -0
  36. package/defaults/plugins/cortex-common/skills/solution-design/SKILL.md +183 -0
  37. package/defaults/plugins/cortex-common/skills/synthesize/SKILL.md +120 -0
  38. package/defaults/plugins/cortex-stage-gate/.claude-plugin/plugin.json +5 -0
  39. package/defaults/plugins/cortex-stage-gate/skills/need-approval/SKILL.md +89 -0
  40. package/defaults/plugins/cortex-stage-gate/skills/reorient/SKILL.md +163 -0
  41. package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +425 -0
  42. package/defaults/plugins/cortex-system/.claude-plugin/plugin.json +5 -0
  43. package/defaults/plugins/cortex-system/skills/approval/SKILL.md +84 -0
  44. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +199 -0
  45. package/defaults/plugins/cortex-system/skills/deep-retrospective/CORTEX.md +8 -0
  46. package/defaults/plugins/cortex-system/skills/deep-retrospective/SKILL.md +201 -0
  47. package/defaults/plugins/cortex-system/skills/deep-retrospective/scripts/CORTEX.md +8 -0
  48. package/defaults/plugins/cortex-system/skills/deep-retrospective/scripts/extract_session.py +165 -0
  49. package/defaults/plugins/cortex-system/skills/deep-retrospective/scripts/scan_logs.py +402 -0
  50. package/defaults/plugins/cortex-system/skills/evolve/SKILL.md +115 -0
  51. package/defaults/plugins/cortex-system/skills/feedback/SKILL.md +262 -0
  52. package/defaults/plugins/cortex-system/skills/gravity/SKILL.md +125 -0
  53. package/defaults/plugins/cortex-system/skills/orient/SKILL.md +310 -0
  54. package/defaults/plugins/cortex-system/skills/orient-project/SKILL.md +85 -0
  55. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +167 -0
  56. package/defaults/plugins/cortex-system/skills/refresh-skills/SKILL.md +153 -0
  57. package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +209 -0
  58. package/defaults/plugins/cortex-system/skills/thread/SKILL.md +478 -0
  59. package/defaults/plugins/cortex-system/skills/user-learn/SKILL.md +95 -0
  60. package/defaults/prompts/directives/coder-reviewer.md +106 -0
  61. package/defaults/prompts/directives/coder.md +90 -0
  62. package/defaults/prompts/directives/director.md +97 -0
  63. package/defaults/prompts/directives/doc-reviewer.md +93 -0
  64. package/defaults/prompts/directives/doc-writer.md +85 -0
  65. package/defaults/prompts/directives/executor-reviewer.md +96 -0
  66. package/defaults/prompts/directives/executor.md +85 -0
  67. package/defaults/prompts/directives/milestone-executor.md +119 -0
  68. package/defaults/prompts/directives/milestone-reviewer.md +108 -0
  69. package/defaults/prompts/directives/plan-executor.md +121 -0
  70. package/defaults/prompts/directives/plan-reviewer.md +99 -0
  71. package/defaults/prompts/systemPrompts/coder.md +64 -0
  72. package/defaults/prompts/systemPrompts/direct.md +92 -0
  73. package/defaults/prompts/systemPrompts/web-opus-4-6.md +68 -0
  74. package/defaults/prompts/systemPrompts/web-sonnet-4-6.md +76 -0
  75. package/defaults/prompts/systemPrompts/web.md +50 -0
  76. package/defaults/prompts/systemPrompts/worker.md +67 -0
  77. package/defaults/rules/correction-propagation.md +31 -0
  78. package/defaults/rules/decision-records.md +49 -0
  79. package/defaults/rules/experiment-format.md +165 -0
  80. package/defaults/rules/issues-md.md +37 -0
  81. package/defaults/rules/meta-conventions.md +45 -0
  82. package/defaults/rules/mission-md.md +47 -0
  83. package/defaults/rules/overview-md.md +41 -0
  84. package/defaults/rules/roadmap-md.md +55 -0
  85. package/defaults/rules/status-md.md +49 -0
  86. package/defaults/rules/task-system.md +53 -0
  87. package/dist/agent-adapter/capabilities.d.ts +12 -0
  88. package/dist/agent-adapter/capabilities.js +52 -0
  89. package/dist/agent-adapter/claude/adapter-tui.d.ts +140 -0
  90. package/dist/agent-adapter/claude/adapter-tui.js +422 -0
  91. package/dist/agent-adapter/claude/adapter.d.ts +85 -0
  92. package/dist/agent-adapter/claude/adapter.js +771 -0
  93. package/dist/agent-adapter/claude/cost-from-usage.d.ts +62 -0
  94. package/dist/agent-adapter/claude/cost-from-usage.js +97 -0
  95. package/dist/agent-adapter/claude/defaults.d.ts +30 -0
  96. package/dist/agent-adapter/claude/defaults.js +49 -0
  97. package/dist/agent-adapter/claude/event-parser.d.ts +28 -0
  98. package/dist/agent-adapter/claude/event-parser.js +173 -0
  99. package/dist/agent-adapter/claude/hooks-builder.d.ts +36 -0
  100. package/dist/agent-adapter/claude/hooks-builder.js +57 -0
  101. package/dist/agent-adapter/claude/jsonl-tail.d.ts +68 -0
  102. package/dist/agent-adapter/claude/jsonl-tail.js +344 -0
  103. package/dist/agent-adapter/claude/spawn-args.d.ts +38 -0
  104. package/dist/agent-adapter/claude/spawn-args.js +83 -0
  105. package/dist/agent-adapter/claude/tmux-control.d.ts +69 -0
  106. package/dist/agent-adapter/claude/tmux-control.js +127 -0
  107. package/dist/agent-adapter/claude/tool-summarizers.d.ts +2 -0
  108. package/dist/agent-adapter/claude/tool-summarizers.js +24 -0
  109. package/dist/agent-adapter/codex/adapter.d.ts +42 -0
  110. package/dist/agent-adapter/codex/adapter.js +916 -0
  111. package/dist/agent-adapter/codex/event-parser.d.ts +17 -0
  112. package/dist/agent-adapter/codex/event-parser.js +41 -0
  113. package/dist/agent-adapter/codex/spawn-args.d.ts +6 -0
  114. package/dist/agent-adapter/codex/spawn-args.js +30 -0
  115. package/dist/agent-adapter/index.d.ts +8 -0
  116. package/dist/agent-adapter/index.js +33 -0
  117. package/dist/agent-adapter/normalize/event-stream.d.ts +6 -0
  118. package/dist/agent-adapter/normalize/event-stream.js +47 -0
  119. package/dist/agent-adapter/normalize/event-types.d.ts +58 -0
  120. package/dist/agent-adapter/normalize/event-types.js +5 -0
  121. package/dist/agent-adapter/normalize/hooks.d.ts +26 -0
  122. package/dist/agent-adapter/normalize/hooks.js +5 -0
  123. package/dist/agent-adapter/normalize/prompt-builder.d.ts +6 -0
  124. package/dist/agent-adapter/normalize/prompt-builder.js +23 -0
  125. package/dist/agent-adapter/normalize/tool-names.d.ts +6 -0
  126. package/dist/agent-adapter/normalize/tool-names.js +73 -0
  127. package/dist/agent-adapter/pi/adapter.d.ts +60 -0
  128. package/dist/agent-adapter/pi/adapter.js +626 -0
  129. package/dist/agent-adapter/pi/agent-dir.d.ts +11 -0
  130. package/dist/agent-adapter/pi/agent-dir.js +34 -0
  131. package/dist/agent-adapter/pi/event-parser.d.ts +26 -0
  132. package/dist/agent-adapter/pi/event-parser.js +313 -0
  133. package/dist/agent-adapter/pi/framing.d.ts +6 -0
  134. package/dist/agent-adapter/pi/framing.js +35 -0
  135. package/dist/agent-adapter/pi/hook-bridge.d.ts +59 -0
  136. package/dist/agent-adapter/pi/hook-bridge.js +233 -0
  137. package/dist/agent-adapter/pi/mcp-bridge.d.ts +26 -0
  138. package/dist/agent-adapter/pi/mcp-bridge.js +140 -0
  139. package/dist/agent-adapter/pi/pi-ext-types.d.ts +90 -0
  140. package/dist/agent-adapter/pi/pi-ext-types.js +5 -0
  141. package/dist/agent-adapter/pi/spawn-args.d.ts +20 -0
  142. package/dist/agent-adapter/pi/spawn-args.js +54 -0
  143. package/dist/agent-adapter/pi/tool-shims.d.ts +2 -0
  144. package/dist/agent-adapter/pi/tool-shims.js +181 -0
  145. package/dist/agent-adapter/types.d.ts +94 -0
  146. package/dist/agent-adapter/types.js +5 -0
  147. package/dist/core/async-mutex.d.ts +6 -0
  148. package/dist/core/async-mutex.js +36 -0
  149. package/dist/core/cli-utils.d.ts +37 -0
  150. package/dist/core/cli-utils.js +69 -0
  151. package/dist/core/config-generator.d.ts +9 -0
  152. package/dist/core/config-generator.js +58 -0
  153. package/dist/core/gateway-generator.d.ts +46 -0
  154. package/dist/core/gateway-generator.js +336 -0
  155. package/dist/core/log.d.ts +7 -0
  156. package/dist/core/log.js +103 -0
  157. package/dist/core/paths.d.ts +32 -0
  158. package/dist/core/paths.js +49 -0
  159. package/dist/core/profile-generator.d.ts +65 -0
  160. package/dist/core/profile-generator.js +310 -0
  161. package/dist/core/running-executions.d.ts +88 -0
  162. package/dist/core/running-executions.js +186 -0
  163. package/dist/core/status-format.d.ts +18 -0
  164. package/dist/core/status-format.js +31 -0
  165. package/dist/core/task-parser.d.ts +69 -0
  166. package/dist/core/task-parser.js +423 -0
  167. package/dist/core/types/agent-types.d.ts +31 -0
  168. package/dist/core/types/agent-types.js +5 -0
  169. package/dist/core/types/thread-types.d.ts +261 -0
  170. package/dist/core/types/thread-types.js +5 -0
  171. package/dist/core/utils.d.ts +29 -0
  172. package/dist/core/utils.js +98 -0
  173. package/dist/core/version.d.ts +3 -0
  174. package/dist/core/version.js +12 -0
  175. package/dist/domain/agents/config.d.ts +58 -0
  176. package/dist/domain/agents/config.js +313 -0
  177. package/dist/domain/agents/facade.d.ts +52 -0
  178. package/dist/domain/agents/facade.js +264 -0
  179. package/dist/domain/agents/index.d.ts +2 -0
  180. package/dist/domain/agents/index.js +4 -0
  181. package/dist/domain/agents/profile-manager.d.ts +54 -0
  182. package/dist/domain/agents/profile-manager.js +161 -0
  183. package/dist/domain/costs/codex-event-format.d.ts +4 -0
  184. package/dist/domain/costs/codex-event-format.js +66 -0
  185. package/dist/domain/costs/codex-usage-monitor.d.ts +7 -0
  186. package/dist/domain/costs/codex-usage-monitor.js +72 -0
  187. package/dist/domain/costs/cost-tracker.d.ts +115 -0
  188. package/dist/domain/costs/cost-tracker.js +327 -0
  189. package/dist/domain/costs/gateway-manager.d.ts +6 -0
  190. package/dist/domain/costs/gateway-manager.js +228 -0
  191. package/dist/domain/costs/rate-limit-parser.d.ts +11 -0
  192. package/dist/domain/costs/rate-limit-parser.js +87 -0
  193. package/dist/domain/costs/rate-limit-throttle.d.ts +32 -0
  194. package/dist/domain/costs/rate-limit-throttle.js +129 -0
  195. package/dist/domain/executions/registry.d.ts +20 -0
  196. package/dist/domain/executions/registry.js +124 -0
  197. package/dist/domain/mcp/core-server.d.ts +2 -0
  198. package/dist/domain/mcp/core-server.js +34 -0
  199. package/dist/domain/mcp/server.d.ts +3 -0
  200. package/dist/domain/mcp/server.js +78 -0
  201. package/dist/domain/mcp/tools/context.d.ts +23 -0
  202. package/dist/domain/mcp/tools/context.js +51 -0
  203. package/dist/domain/mcp/tools/cortex-md.d.ts +17 -0
  204. package/dist/domain/mcp/tools/cortex-md.js +36 -0
  205. package/dist/domain/mcp/tools/cost.d.ts +2 -0
  206. package/dist/domain/mcp/tools/cost.js +54 -0
  207. package/dist/domain/mcp/tools/executions.d.ts +2 -0
  208. package/dist/domain/mcp/tools/executions.js +94 -0
  209. package/dist/domain/mcp/tools/schedule.d.ts +23 -0
  210. package/dist/domain/mcp/tools/schedule.js +245 -0
  211. package/dist/domain/mcp/tools/slack.d.ts +21 -0
  212. package/dist/domain/mcp/tools/slack.js +124 -0
  213. package/dist/domain/mcp/tools/task-ops.d.ts +2 -0
  214. package/dist/domain/mcp/tools/task-ops.js +509 -0
  215. package/dist/domain/mcp/tools/tui-ask.d.ts +31 -0
  216. package/dist/domain/mcp/tools/tui-ask.js +108 -0
  217. package/dist/domain/mcp/tools/tui-plan.d.ts +28 -0
  218. package/dist/domain/mcp/tools/tui-plan.js +118 -0
  219. package/dist/domain/mcp/tui-server.d.ts +2 -0
  220. package/dist/domain/mcp/tui-server.js +69 -0
  221. package/dist/domain/memory/consolidate.d.ts +55 -0
  222. package/dist/domain/memory/consolidate.js +471 -0
  223. package/dist/domain/memory/cortex-md-injector.d.ts +30 -0
  224. package/dist/domain/memory/cortex-md-injector.js +123 -0
  225. package/dist/domain/memory/cortex-md-scanner.d.ts +9 -0
  226. package/dist/domain/memory/cortex-md-scanner.js +67 -0
  227. package/dist/domain/memory/index-regen.d.ts +19 -0
  228. package/dist/domain/memory/index-regen.js +398 -0
  229. package/dist/domain/memory/rules-loader.d.ts +27 -0
  230. package/dist/domain/memory/rules-loader.js +97 -0
  231. package/dist/domain/memory/skill-scanner.d.ts +5 -0
  232. package/dist/domain/memory/skill-scanner.js +132 -0
  233. package/dist/domain/memory/user-context.d.ts +5 -0
  234. package/dist/domain/memory/user-context.js +34 -0
  235. package/dist/domain/memory/watcher.d.ts +2 -0
  236. package/dist/domain/memory/watcher.js +81 -0
  237. package/dist/domain/monitor/disk-monitor.d.ts +20 -0
  238. package/dist/domain/monitor/disk-monitor.js +97 -0
  239. package/dist/domain/monitor/gpu-monitor.d.ts +26 -0
  240. package/dist/domain/monitor/gpu-monitor.js +135 -0
  241. package/dist/domain/remote/client-bootstrap.d.ts +1 -0
  242. package/dist/domain/remote/client-bootstrap.js +139 -0
  243. package/dist/domain/remote/client-hot-reload.d.ts +18 -0
  244. package/dist/domain/remote/client-hot-reload.js +142 -0
  245. package/dist/domain/remote/client-manager.d.ts +50 -0
  246. package/dist/domain/remote/client-manager.js +452 -0
  247. package/dist/domain/remote/cortex-client.d.ts +1 -0
  248. package/dist/domain/remote/cortex-client.js +704 -0
  249. package/dist/domain/scheduling/job-registry.d.ts +31 -0
  250. package/dist/domain/scheduling/job-registry.js +34 -0
  251. package/dist/domain/scheduling/jobs/_shared.d.ts +14 -0
  252. package/dist/domain/scheduling/jobs/_shared.js +45 -0
  253. package/dist/domain/scheduling/jobs/memory-index-regen.d.ts +1 -0
  254. package/dist/domain/scheduling/jobs/memory-index-regen.js +16 -0
  255. package/dist/domain/scheduling/jobs/scheduled-task.d.ts +11 -0
  256. package/dist/domain/scheduling/jobs/scheduled-task.js +186 -0
  257. package/dist/domain/scheduling/jobs/target-dispatch.d.ts +41 -0
  258. package/dist/domain/scheduling/jobs/target-dispatch.js +48 -0
  259. package/dist/domain/scheduling/jobs/task-archive.d.ts +1 -0
  260. package/dist/domain/scheduling/jobs/task-archive.js +19 -0
  261. package/dist/domain/scheduling/jobs/task-dispatch.d.ts +12 -0
  262. package/dist/domain/scheduling/jobs/task-dispatch.js +214 -0
  263. package/dist/domain/scheduling/runner.d.ts +13 -0
  264. package/dist/domain/scheduling/runner.js +24 -0
  265. package/dist/domain/scheduling/schedule-cli.d.ts +16 -0
  266. package/dist/domain/scheduling/schedule-cli.js +268 -0
  267. package/dist/domain/scheduling/schedule-command.d.ts +4 -0
  268. package/dist/domain/scheduling/schedule-command.js +274 -0
  269. package/dist/domain/scheduling/scheduler.d.ts +86 -0
  270. package/dist/domain/scheduling/scheduler.js +544 -0
  271. package/dist/domain/sessions/session-backup.d.ts +49 -0
  272. package/dist/domain/sessions/session-backup.js +217 -0
  273. package/dist/domain/sessions/session-hooks.d.ts +103 -0
  274. package/dist/domain/sessions/session-hooks.js +311 -0
  275. package/dist/domain/sessions/session-registry.d.ts +21 -0
  276. package/dist/domain/sessions/session-registry.js +31 -0
  277. package/dist/domain/sessions/session.d.ts +3 -0
  278. package/dist/domain/sessions/session.js +14 -0
  279. package/dist/domain/tasks/archiver.d.ts +9 -0
  280. package/dist/domain/tasks/archiver.js +123 -0
  281. package/dist/domain/tasks/dispatch-utils.d.ts +37 -0
  282. package/dist/domain/tasks/dispatch-utils.js +143 -0
  283. package/dist/domain/tasks/dispatcher.d.ts +48 -0
  284. package/dist/domain/tasks/dispatcher.js +285 -0
  285. package/dist/domain/tasks/lint.d.ts +12 -0
  286. package/dist/domain/tasks/lint.js +102 -0
  287. package/dist/domain/tasks/mutator.d.ts +21 -0
  288. package/dist/domain/tasks/mutator.js +208 -0
  289. package/dist/domain/tasks/parser.d.ts +1 -0
  290. package/dist/domain/tasks/parser.js +6 -0
  291. package/dist/domain/tasks/pending-tracker.d.ts +67 -0
  292. package/dist/domain/tasks/pending-tracker.js +163 -0
  293. package/dist/domain/tasks/recommendation/extractor.d.ts +12 -0
  294. package/dist/domain/tasks/recommendation/extractor.js +563 -0
  295. package/dist/domain/tasks/recommendation/patterns.d.ts +11 -0
  296. package/dist/domain/tasks/recommendation/patterns.js +99 -0
  297. package/dist/domain/tasks/recommendation/types.d.ts +67 -0
  298. package/dist/domain/tasks/recommendation/types.js +5 -0
  299. package/dist/domain/tasks/store.d.ts +1 -0
  300. package/dist/domain/tasks/store.js +3 -0
  301. package/dist/domain/tasks/system/cortex-run.d.ts +24 -0
  302. package/dist/domain/tasks/system/cortex-run.js +342 -0
  303. package/dist/domain/tasks/system/task-cli.d.ts +49 -0
  304. package/dist/domain/tasks/system/task-cli.js +664 -0
  305. package/dist/domain/tasks/system/task-completion.d.ts +22 -0
  306. package/dist/domain/tasks/system/task-completion.js +89 -0
  307. package/dist/domain/tasks/system/task-id-utils.d.ts +24 -0
  308. package/dist/domain/tasks/system/task-id-utils.js +84 -0
  309. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +34 -0
  310. package/dist/domain/tasks/system/task-lifecycle-edit.js +208 -0
  311. package/dist/domain/tasks/system/task-lock.d.ts +25 -0
  312. package/dist/domain/tasks/system/task-lock.js +139 -0
  313. package/dist/domain/tasks/system/task-mutations.d.ts +31 -0
  314. package/dist/domain/tasks/system/task-mutations.js +110 -0
  315. package/dist/domain/tasks/system/task-process.d.ts +37 -0
  316. package/dist/domain/tasks/system/task-process.js +119 -0
  317. package/dist/domain/tasks/system/task-state.d.ts +70 -0
  318. package/dist/domain/tasks/system/task-state.js +176 -0
  319. package/dist/domain/threads/artifact-io.d.ts +18 -0
  320. package/dist/domain/threads/artifact-io.js +182 -0
  321. package/dist/domain/threads/auto-thread.d.ts +3 -0
  322. package/dist/domain/threads/auto-thread.js +19 -0
  323. package/dist/domain/threads/hook-runner.d.ts +4 -0
  324. package/dist/domain/threads/hook-runner.js +250 -0
  325. package/dist/domain/threads/index.d.ts +5 -0
  326. package/dist/domain/threads/index.js +7 -0
  327. package/dist/domain/threads/prompt-builder.d.ts +25 -0
  328. package/dist/domain/threads/prompt-builder.js +176 -0
  329. package/dist/domain/threads/runner.d.ts +83 -0
  330. package/dist/domain/threads/runner.js +434 -0
  331. package/dist/domain/threads/state-machine.d.ts +61 -0
  332. package/dist/domain/threads/state-machine.js +440 -0
  333. package/dist/domain/threads/template-loader.d.ts +20 -0
  334. package/dist/domain/threads/template-loader.js +189 -0
  335. package/dist/domain/threads/template-resolver.d.ts +1 -0
  336. package/dist/domain/threads/template-resolver.js +95 -0
  337. package/dist/domain/threads/utils.d.ts +19 -0
  338. package/dist/domain/threads/utils.js +49 -0
  339. package/dist/entry/app.d.ts +1 -0
  340. package/dist/entry/app.js +234 -0
  341. package/dist/entry/cli.d.ts +12 -0
  342. package/dist/entry/cli.js +254 -0
  343. package/dist/entry/daemon.d.ts +11 -0
  344. package/dist/entry/daemon.js +521 -0
  345. package/dist/entry/init.d.ts +93 -0
  346. package/dist/entry/init.js +1299 -0
  347. package/dist/entry/startup-helpers.d.ts +2 -0
  348. package/dist/entry/startup-helpers.js +56 -0
  349. package/dist/entry/startup-notify.d.ts +10 -0
  350. package/dist/entry/startup-notify.js +20 -0
  351. package/dist/events/event-bus.d.ts +42 -0
  352. package/dist/events/event-bus.js +84 -0
  353. package/dist/events/event-logger.d.ts +12 -0
  354. package/dist/events/event-logger.js +135 -0
  355. package/dist/events/event-replay.d.ts +1 -0
  356. package/dist/events/event-replay.js +51 -0
  357. package/dist/events/event-types.d.ts +145 -0
  358. package/dist/events/event-types.js +5 -0
  359. package/dist/events/index.d.ts +5 -0
  360. package/dist/events/index.js +6 -0
  361. package/dist/hooks/ask-user-question-hook.mjs +66 -0
  362. package/dist/hooks/cortex-md-injector.mjs +237 -0
  363. package/dist/hooks/exit-plan-mode-hook.mjs +84 -0
  364. package/dist/hooks/memory-ref-tracker.mjs +154 -0
  365. package/dist/hooks/new-session-hook.mjs +83 -0
  366. package/dist/hooks/post-task-hook.mjs +63 -0
  367. package/dist/hooks/rules-loader.mjs +212 -0
  368. package/dist/hooks/sensitive-file-edit.mjs +84 -0
  369. package/dist/hooks/session-activity-tracker.mjs +254 -0
  370. package/dist/hooks/task-status-check.mjs +218 -0
  371. package/dist/hooks/tasks-yaml-guard.mjs +230 -0
  372. package/dist/orchestration/agent-runner.d.ts +72 -0
  373. package/dist/orchestration/agent-runner.js +289 -0
  374. package/dist/orchestration/busy-tracker.d.ts +12 -0
  375. package/dist/orchestration/busy-tracker.js +35 -0
  376. package/dist/orchestration/channel-queue.d.ts +18 -0
  377. package/dist/orchestration/channel-queue.js +32 -0
  378. package/dist/orchestration/dispatch-reconciler.d.ts +1 -0
  379. package/dist/orchestration/dispatch-reconciler.js +16 -0
  380. package/dist/orchestration/durable-helpers.d.ts +4 -0
  381. package/dist/orchestration/durable-helpers.js +42 -0
  382. package/dist/orchestration/interactions/ask-user-question.d.ts +32 -0
  383. package/dist/orchestration/interactions/ask-user-question.js +182 -0
  384. package/dist/orchestration/interactions/command-action-router.d.ts +47 -0
  385. package/dist/orchestration/interactions/command-action-router.js +91 -0
  386. package/dist/orchestration/interactions/interaction-handlers.d.ts +5 -0
  387. package/dist/orchestration/interactions/interaction-handlers.js +279 -0
  388. package/dist/orchestration/interactions/plan-approvals.d.ts +47 -0
  389. package/dist/orchestration/interactions/plan-approvals.js +77 -0
  390. package/dist/orchestration/interactions/plan-handler.d.ts +6 -0
  391. package/dist/orchestration/interactions/plan-handler.js +12 -0
  392. package/dist/orchestration/lifecycle.d.ts +50 -0
  393. package/dist/orchestration/lifecycle.js +308 -0
  394. package/dist/orchestration/orchestrator.d.ts +29 -0
  395. package/dist/orchestration/orchestrator.js +25 -0
  396. package/dist/orchestration/routing/commands/cancel.d.ts +10 -0
  397. package/dist/orchestration/routing/commands/cancel.js +136 -0
  398. package/dist/orchestration/routing/commands/channel.d.ts +11 -0
  399. package/dist/orchestration/routing/commands/channel.js +219 -0
  400. package/dist/orchestration/routing/commands/command-context.d.ts +29 -0
  401. package/dist/orchestration/routing/commands/command-context.js +4 -0
  402. package/dist/orchestration/routing/commands/cost.d.ts +3 -0
  403. package/dist/orchestration/routing/commands/cost.js +22 -0
  404. package/dist/orchestration/routing/commands/device.d.ts +6 -0
  405. package/dist/orchestration/routing/commands/device.js +83 -0
  406. package/dist/orchestration/routing/commands/dispatch.d.ts +2 -0
  407. package/dist/orchestration/routing/commands/dispatch.js +49 -0
  408. package/dist/orchestration/routing/commands/index.d.ts +15 -0
  409. package/dist/orchestration/routing/commands/index.js +130 -0
  410. package/dist/orchestration/routing/commands/mode.d.ts +13 -0
  411. package/dist/orchestration/routing/commands/mode.js +290 -0
  412. package/dist/orchestration/routing/commands/nvtop.d.ts +3 -0
  413. package/dist/orchestration/routing/commands/nvtop.js +103 -0
  414. package/dist/orchestration/routing/commands/orient.d.ts +2 -0
  415. package/dist/orchestration/routing/commands/orient.js +3 -0
  416. package/dist/orchestration/routing/commands/schedule.d.ts +4 -0
  417. package/dist/orchestration/routing/commands/schedule.js +132 -0
  418. package/dist/orchestration/routing/commands/sendfile.d.ts +2 -0
  419. package/dist/orchestration/routing/commands/sendfile.js +92 -0
  420. package/dist/orchestration/routing/commands/session.d.ts +9 -0
  421. package/dist/orchestration/routing/commands/session.js +153 -0
  422. package/dist/orchestration/routing/commands/status.d.ts +7 -0
  423. package/dist/orchestration/routing/commands/status.js +180 -0
  424. package/dist/orchestration/routing/commands/tail.d.ts +2 -0
  425. package/dist/orchestration/routing/commands/tail.js +73 -0
  426. package/dist/orchestration/routing/commands/task.d.ts +6 -0
  427. package/dist/orchestration/routing/commands/task.js +142 -0
  428. package/dist/orchestration/routing/commands/thread-handlers.d.ts +2 -0
  429. package/dist/orchestration/routing/commands/thread-handlers.js +138 -0
  430. package/dist/orchestration/routing/commands/thread.d.ts +2 -0
  431. package/dist/orchestration/routing/commands/thread.js +2 -0
  432. package/dist/orchestration/routing/edit-handler.d.ts +24 -0
  433. package/dist/orchestration/routing/edit-handler.js +161 -0
  434. package/dist/orchestration/routing/file-handler.d.ts +6 -0
  435. package/dist/orchestration/routing/file-handler.js +23 -0
  436. package/dist/orchestration/routing/hook-bridge-subscribers.d.ts +4 -0
  437. package/dist/orchestration/routing/hook-bridge-subscribers.js +79 -0
  438. package/dist/orchestration/routing/hook-bridge.d.ts +30 -0
  439. package/dist/orchestration/routing/hook-bridge.js +112 -0
  440. package/dist/orchestration/routing/message-router.d.ts +6 -0
  441. package/dist/orchestration/routing/message-router.js +70 -0
  442. package/dist/orchestration/routing/webhook.d.ts +10 -0
  443. package/dist/orchestration/routing/webhook.js +239 -0
  444. package/dist/orchestration/status-helpers.d.ts +66 -0
  445. package/dist/orchestration/status-helpers.js +222 -0
  446. package/dist/orchestration/superseded-edits.d.ts +22 -0
  447. package/dist/orchestration/superseded-edits.js +31 -0
  448. package/dist/orchestration/thread-executor.d.ts +31 -0
  449. package/dist/orchestration/thread-executor.js +234 -0
  450. package/dist/platform/adapter.d.ts +28 -0
  451. package/dist/platform/adapter.js +5 -0
  452. package/dist/platform/adapters/feishu.d.ts +66 -0
  453. package/dist/platform/adapters/feishu.js +558 -0
  454. package/dist/platform/adapters/index.d.ts +16 -0
  455. package/dist/platform/adapters/index.js +65 -0
  456. package/dist/platform/adapters/slack.d.ts +90 -0
  457. package/dist/platform/adapters/slack.js +630 -0
  458. package/dist/platform/index.d.ts +12 -0
  459. package/dist/platform/index.js +10 -0
  460. package/dist/platform/interactive-builder.d.ts +27 -0
  461. package/dist/platform/interactive-builder.js +120 -0
  462. package/dist/platform/testing.d.ts +100 -0
  463. package/dist/platform/testing.js +190 -0
  464. package/dist/platform/tool-trace.d.ts +33 -0
  465. package/dist/platform/tool-trace.js +165 -0
  466. package/dist/platform/types.d.ts +176 -0
  467. package/dist/platform/types.js +5 -0
  468. package/dist/platform/utils/rate-limiter.d.ts +92 -0
  469. package/dist/platform/utils/rate-limiter.js +213 -0
  470. package/dist/platform/virtual-message.d.ts +68 -0
  471. package/dist/platform/virtual-message.js +464 -0
  472. package/dist/store/atomic-write.d.ts +6 -0
  473. package/dist/store/atomic-write.js +18 -0
  474. package/dist/store/channel-repo.d.ts +21 -0
  475. package/dist/store/channel-repo.js +55 -0
  476. package/dist/store/conversation-ledger-repo.d.ts +86 -0
  477. package/dist/store/conversation-ledger-repo.js +220 -0
  478. package/dist/store/cost-repo.d.ts +57 -0
  479. package/dist/store/cost-repo.js +135 -0
  480. package/dist/store/execution-repo.d.ts +172 -0
  481. package/dist/store/execution-repo.js +343 -0
  482. package/dist/store/in-memory-repository.d.ts +14 -0
  483. package/dist/store/in-memory-repository.js +31 -0
  484. package/dist/store/json-repository.d.ts +51 -0
  485. package/dist/store/json-repository.js +118 -0
  486. package/dist/store/outbound-queue.d.ts +65 -0
  487. package/dist/store/outbound-queue.js +269 -0
  488. package/dist/store/profile-repo.d.ts +36 -0
  489. package/dist/store/profile-repo.js +144 -0
  490. package/dist/store/project-dir-repo.d.ts +22 -0
  491. package/dist/store/project-dir-repo.js +60 -0
  492. package/dist/store/schedule-repo.d.ts +92 -0
  493. package/dist/store/schedule-repo.js +88 -0
  494. package/dist/store/session-registry-repo.d.ts +38 -0
  495. package/dist/store/session-registry-repo.js +96 -0
  496. package/dist/store/session-repo.d.ts +14 -0
  497. package/dist/store/session-repo.js +56 -0
  498. package/dist/store/task-repo.d.ts +41 -0
  499. package/dist/store/task-repo.js +137 -0
  500. package/dist/store/thread-repo.d.ts +50 -0
  501. package/dist/store/thread-repo.js +190 -0
  502. package/package.json +58 -0
  503. package/scripts/postinstall-restart-trigger.mjs +39 -0
@@ -0,0 +1,544 @@
1
+ // input: ScheduleRepo, runner callback
2
+ // output: Scheduler class + duration helpers
3
+ // pos: scheduled task scheduler (hot-reload + preCheck skip). Persistence delegated to store/schedule-repo.ts.
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { watch } from 'fs';
6
+ import { execSync } from 'child_process';
7
+ import { randomBytes } from 'crypto';
8
+ import { DATA_DIR } from '../../core/utils.js';
9
+ import { createLogger } from '../../core/log.js';
10
+ import { getDefaultProfileName } from '../agents/profile-manager.js';
11
+ import { ScheduleRepo, scheduleRepo, SCHEDULES_FILE } from '../../store/schedule-repo.js';
12
+ const log = createLogger('scheduler');
13
+ // Parse duration strings like "30s", "5m", "2h", "1d" → milliseconds
14
+ function parseDuration(str) {
15
+ const match = str?.match(/^(\d+(?:\.\d+)?)(s|m|h|d)$/i);
16
+ if (!match)
17
+ return null;
18
+ const value = parseFloat(match[1]);
19
+ const unit = match[2].toLowerCase();
20
+ const ms = { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
21
+ return Math.round(value * ms[unit]);
22
+ }
23
+ // Format milliseconds as a human-readable duration string
24
+ function formatDuration(ms) {
25
+ if (ms < 60_000)
26
+ return `${Math.round(ms / 1000)}s`;
27
+ if (ms < 3_600_000)
28
+ return `${Math.round(ms / 60_000)}m`;
29
+ if (ms < 86_400_000) {
30
+ const h = ms / 3_600_000;
31
+ return Number.isInteger(h) ? `${h}h` : `${h.toFixed(1)}h`;
32
+ }
33
+ const d = ms / 86_400_000;
34
+ return Number.isInteger(d) ? `${d}d` : `${d.toFixed(1)}d`;
35
+ }
36
+ // Format ms until an event as "in 5m", "in 2.5h", "overdue"
37
+ function formatTimeUntil(ms) {
38
+ if (ms <= 0)
39
+ return 'overdue';
40
+ if (ms < 60_000)
41
+ return `in ${Math.round(ms / 1000)}s`;
42
+ if (ms < 3_600_000)
43
+ return `in ${Math.round(ms / 60_000)}m`;
44
+ if (ms < 86_400_000)
45
+ return `in ${(ms / 3_600_000).toFixed(1)}h`;
46
+ return `in ${(ms / 86_400_000).toFixed(1)}d`;
47
+ }
48
+ // Returns ms until the next occurrence of HH:MM today or tomorrow
49
+ function nextDailyMs(timeStr) {
50
+ const [hours, minutes] = timeStr.split(':').map(Number);
51
+ const now = new Date();
52
+ const next = new Date();
53
+ next.setHours(hours, minutes, 0, 0);
54
+ if (next <= now)
55
+ next.setDate(next.getDate() + 1);
56
+ return next.getTime() - now.getTime();
57
+ }
58
+ // Returns ms until the next occurrence of dayOfWeek at HH:MM
59
+ // dayOfWeek: 0=Sun, 1=Mon, ..., 6=Sat
60
+ function nextWeeklyMs(dayOfWeek, timeStr) {
61
+ const [hours, minutes] = timeStr.split(':').map(Number);
62
+ const now = new Date();
63
+ const next = new Date();
64
+ next.setHours(hours, minutes, 0, 0);
65
+ let daysAhead = (dayOfWeek - next.getDay() + 7) % 7;
66
+ if (daysAhead === 0 && next <= now)
67
+ daysAhead = 7;
68
+ next.setDate(next.getDate() + daysAhead);
69
+ return next.getTime() - now.getTime();
70
+ }
71
+ // Hash task config fields that affect scheduling (not timestamps)
72
+ function taskConfigHash(task) {
73
+ const keys = { interval: 'intervalMs', daily: 'time', once: 'runAt', weekly: 'dayOfWeek' };
74
+ const key = keys[task.type];
75
+ const extra = task.type === 'weekly' ? `${task.dayOfWeek}:${task.time}` : (String(task[key] || ''));
76
+ return `${task.type}:${extra}:${task.message}:${task.channel}:${task.profile || ''}:${task.dispatchType || ''}:${task.preCheck || ''}`;
77
+ }
78
+ function validateTime(time) {
79
+ if (!/^\d{2}:\d{2}$/.test(time))
80
+ throw new Error('time must be HH:MM');
81
+ const [hours, minutes] = time.split(':').map(Number);
82
+ if (hours > 23 || minutes > 59)
83
+ throw new Error('time must be HH:MM');
84
+ }
85
+ function computeTaskTiming(type, task) {
86
+ const now = Date.now();
87
+ if (task.isPaused) {
88
+ return { nextRun: null };
89
+ }
90
+ if (type === 'interval') {
91
+ return { nextRun: now + (task.intervalMs || 0) };
92
+ }
93
+ if (type === 'daily') {
94
+ return { nextRun: now + nextDailyMs(task.time) };
95
+ }
96
+ if (type === 'weekly') {
97
+ return { nextRun: now + nextWeeklyMs(task.dayOfWeek, task.time) };
98
+ }
99
+ if (type === 'once') {
100
+ return { runAt: task.runAt };
101
+ }
102
+ return {};
103
+ }
104
+ function validateTaskPatch(task, patch) {
105
+ const commonFields = new Set(['message', 'channel', 'profile', 'dispatchType', 'preCheck']);
106
+ const typeFields = {
107
+ interval: new Set(['intervalMs']),
108
+ daily: new Set(['time']),
109
+ weekly: new Set(['dayOfWeek', 'time']),
110
+ once: new Set(['runAt']),
111
+ };
112
+ const allowed = new Set([...commonFields, ...typeFields[task.type]]);
113
+ const invalid = Object.keys(patch).filter(key => !allowed.has(key));
114
+ if (invalid.length)
115
+ throw new Error(`invalid fields for ${task.type}: ${invalid.join(', ')}`);
116
+ if ('intervalMs' in patch && (!Number.isFinite(patch.intervalMs) || patch.intervalMs <= 0)) {
117
+ throw new Error('intervalMs must be a positive number');
118
+ }
119
+ if ('time' in patch)
120
+ validateTime(patch.time);
121
+ if ('dayOfWeek' in patch && (!Number.isInteger(patch.dayOfWeek) || patch.dayOfWeek < 0 || patch.dayOfWeek > 6)) {
122
+ throw new Error('dayOfWeek must be an integer from 0 to 6');
123
+ }
124
+ if ('runAt' in patch && (!Number.isFinite(patch.runAt) || patch.runAt <= 0)) {
125
+ throw new Error('runAt must be a positive epoch ms');
126
+ }
127
+ }
128
+ function resolveTaskProfile(profile) {
129
+ return profile || getDefaultProfileName();
130
+ }
131
+ function buildTask(type, id, now, options) {
132
+ const { message, channel, profile = null, preCheck = null } = options;
133
+ const resolvedProfile = resolveTaskProfile(profile);
134
+ const base = { preCheck: preCheck || undefined };
135
+ if (type === 'interval') {
136
+ const { intervalMs } = options;
137
+ if (!intervalMs)
138
+ throw new Error('intervalMs required');
139
+ return { id, type: 'interval', intervalMs, message, channel, profile: resolvedProfile, ...base, lastRun: null, nextRun: now + intervalMs, createdAt: now };
140
+ }
141
+ if (type === 'daily') {
142
+ const { time } = options;
143
+ if (!time)
144
+ throw new Error('time required (HH:MM)');
145
+ return { id, type: 'daily', time, message, channel, profile: resolvedProfile, ...base, lastRun: null, nextRun: now + nextDailyMs(time), createdAt: now };
146
+ }
147
+ if (type === 'weekly') {
148
+ const { dayOfWeek, time } = options;
149
+ if (dayOfWeek == null || dayOfWeek < 0 || dayOfWeek > 6)
150
+ throw new Error('dayOfWeek required (0=Sun..6=Sat)');
151
+ if (!time)
152
+ throw new Error('time required (HH:MM)');
153
+ return { id, type: 'weekly', dayOfWeek, time, message, channel, profile: resolvedProfile, ...base, lastRun: null, nextRun: now + nextWeeklyMs(dayOfWeek, time), createdAt: now };
154
+ }
155
+ if (type === 'once') {
156
+ const { delay } = options;
157
+ if (!delay)
158
+ throw new Error('delay required');
159
+ return { id, type: 'once', runAt: now + delay, message, channel, profile: resolvedProfile, ...base, createdAt: now };
160
+ }
161
+ throw new Error(`Unknown type: ${type}. Use: interval, daily, weekly, once`);
162
+ }
163
+ class Scheduler {
164
+ runner;
165
+ taskDispatchRunner;
166
+ programmaticHandlers;
167
+ schedulesFile;
168
+ watchFile;
169
+ timers;
170
+ _repo;
171
+ _inFlight;
172
+ _taskConfigs;
173
+ _watcher;
174
+ _reloadTimer;
175
+ _selfWriting;
176
+ _beforeRunGuard;
177
+ /** Async callback invoked after _beforeRunGuard blocks a task. Used for async bookkeeping (e.g. persisting pause). */
178
+ _onGuardBlocked;
179
+ /** Admin notification callback for hot-reload → Slack messages. Set by app.ts after adapter creation. */
180
+ _adminNotifier;
181
+ /** Set _selfWriting=true before a disk write, clear after 100ms to avoid triggering fs.watch hot-reload. */
182
+ async _withWriteGuard(fn) {
183
+ this._selfWriting = true;
184
+ try {
185
+ return await fn();
186
+ }
187
+ finally {
188
+ setTimeout(() => { this._selfWriting = false; }, 100);
189
+ }
190
+ }
191
+ constructor(runner, taskDispatchRunner, programmaticHandlers = {}, options = {}) {
192
+ this.runner = runner;
193
+ this.taskDispatchRunner = taskDispatchRunner || null;
194
+ this.programmaticHandlers = programmaticHandlers;
195
+ this.schedulesFile = options.schedulesFile || SCHEDULES_FILE;
196
+ this.watchFile = options.watchFile !== false;
197
+ this._repo = options.repo || (this.schedulesFile !== SCHEDULES_FILE
198
+ ? new ScheduleRepo(this.schedulesFile)
199
+ : scheduleRepo);
200
+ this.timers = new Map();
201
+ this._inFlight = new Set();
202
+ this._taskConfigs = new Map();
203
+ this._watcher = null;
204
+ this._reloadTimer = null;
205
+ this._selfWriting = false;
206
+ this._beforeRunGuard = null;
207
+ this._onGuardBlocked = null;
208
+ this._adminNotifier = null;
209
+ }
210
+ /** Set a callback for admin notifications (hot-reload → Slack). Called by app.ts after adapter creation. */
211
+ setAdminNotifier(fn) { this._adminNotifier = fn; }
212
+ // Load persisted tasks and arm timers. Call once after app is ready.
213
+ async start() {
214
+ const now = Date.now();
215
+ // Drop once tasks that are more than 1 minute overdue
216
+ const data = await this._withWriteGuard(() => this._repo.mutate((data) => {
217
+ data.tasks = data.tasks.filter(task => {
218
+ if (task.type === 'once' && task.runAt < now - 60_000) {
219
+ log.info(`Dropping overdue once task ${task.id}: "${task.message}"`);
220
+ return false;
221
+ }
222
+ return true;
223
+ });
224
+ return { next: data, result: data };
225
+ }));
226
+ for (const task of data.tasks) {
227
+ this._scheduleTask(task);
228
+ }
229
+ if (this.watchFile)
230
+ this._startWatching();
231
+ log.info(`Started with ${data.tasks.length} task(s)`);
232
+ }
233
+ // Stop all timers and file watcher (used on shutdown)
234
+ stop() {
235
+ if (this._watcher) {
236
+ this._watcher.close();
237
+ this._watcher = null;
238
+ }
239
+ if (this._reloadTimer) {
240
+ clearTimeout(this._reloadTimer);
241
+ this._reloadTimer = null;
242
+ }
243
+ for (const timer of this.timers.values())
244
+ clearTimeout(timer);
245
+ this.timers.clear();
246
+ log.info('Stopped');
247
+ }
248
+ // Watch schedules.json for external changes and hot-reload.
249
+ _startWatching() {
250
+ const setup = () => {
251
+ try {
252
+ if (this._watcher)
253
+ this._watcher.close();
254
+ this._watcher = watch(this.schedulesFile, (eventType) => {
255
+ if (eventType === 'rename') {
256
+ setTimeout(() => setup(), 100);
257
+ }
258
+ if (this._selfWriting)
259
+ return;
260
+ if (this._reloadTimer)
261
+ clearTimeout(this._reloadTimer);
262
+ this._reloadTimer = setTimeout(() => {
263
+ this._reloadTimer = null;
264
+ this._hotReload().catch(e => log.error('Hot-reload error:', e));
265
+ }, 300);
266
+ });
267
+ }
268
+ catch (e) {
269
+ log.error('Failed to watch schedules.json:', e.message);
270
+ }
271
+ };
272
+ setup();
273
+ }
274
+ // Hot-reload: diff file vs in-memory timers — add, remove, or update as needed
275
+ async _hotReload() {
276
+ // Must invalidate cache before reading so we see the actual on-disk state,
277
+ // not the stale in-memory cache from before the external write.
278
+ this._repo.invalidate();
279
+ const data = await this._repo.read();
280
+ const fileIds = new Set(data.tasks.map(t => t.id));
281
+ const memIds = new Set(this.timers.keys());
282
+ let added = 0, removed = 0, updated = 0;
283
+ // Remove timers for tasks no longer in file
284
+ for (const id of memIds) {
285
+ if (!fileIds.has(id)) {
286
+ clearTimeout(this.timers.get(id));
287
+ this.timers.delete(id);
288
+ this._taskConfigs.delete(id);
289
+ removed++;
290
+ }
291
+ }
292
+ for (const task of data.tasks) {
293
+ if (!memIds.has(task.id)) {
294
+ this._scheduleTask(task);
295
+ added++;
296
+ }
297
+ else {
298
+ const oldHash = this._taskConfigs.get(task.id);
299
+ const newHash = taskConfigHash(task);
300
+ if (oldHash && oldHash !== newHash) {
301
+ clearTimeout(this.timers.get(task.id));
302
+ this.timers.delete(task.id);
303
+ this._scheduleTask(task);
304
+ updated++;
305
+ }
306
+ }
307
+ }
308
+ if (added || removed || updated) {
309
+ log.info(`Hot-reload: +${added} -${removed} ~${updated} task(s), total ${this.timers.size}`);
310
+ this._adminNotifier?.(`:arrows_counterclockwise: \`schedules.json\` hot-reloaded: +${added} -${removed} ~${updated} task(s), ${this.timers.size} total`);
311
+ }
312
+ }
313
+ // Add a new scheduled task and return it
314
+ async add(type, options) {
315
+ const id = randomBytes(4).toString('hex');
316
+ const now = Date.now();
317
+ const task = buildTask(type, id, now, options);
318
+ await this._withWriteGuard(() => this._repo.addTask(task));
319
+ this._scheduleTask(task);
320
+ return task;
321
+ }
322
+ // Remove a task by id. Returns true if found and removed.
323
+ async remove(id) {
324
+ const removed = await this._withWriteGuard(() => this._repo.removeTask(id));
325
+ if (removed) {
326
+ const timer = this.timers.get(id);
327
+ if (timer) {
328
+ clearTimeout(timer);
329
+ this.timers.delete(id);
330
+ }
331
+ }
332
+ return removed;
333
+ }
334
+ async list() {
335
+ return (await this._repo.read()).tasks;
336
+ }
337
+ async get(id) {
338
+ return this._repo.findTask(id);
339
+ }
340
+ async update(id, patch) {
341
+ const task = await this._repo.findTask(id);
342
+ if (!task)
343
+ return null;
344
+ validateTaskPatch(task, patch);
345
+ const updated = await this._withWriteGuard(() => this._repo.updateTask(id, (t) => {
346
+ Object.assign(t, patch);
347
+ Object.assign(t, computeTaskTiming(t.type, t));
348
+ }));
349
+ if (updated)
350
+ this._rescheduleTask(updated);
351
+ return updated;
352
+ }
353
+ async pause(id, pausedBy = 'user') {
354
+ const task = await this._repo.findTask(id);
355
+ if (!task)
356
+ return null;
357
+ if (task.type === 'once')
358
+ throw new Error(`cannot pause once schedule ${id}`);
359
+ if (task.isPaused)
360
+ return task;
361
+ const now = Date.now();
362
+ const updated = await this._withWriteGuard(() => this._repo.updateTask(id, (t) => {
363
+ t.isPaused = true;
364
+ t.pausedAt = now;
365
+ t.pausedBy = pausedBy;
366
+ t.nextRun = null;
367
+ }));
368
+ if (updated)
369
+ this._rescheduleTask(updated);
370
+ return updated;
371
+ }
372
+ async resume(id) {
373
+ const task = await this._repo.findTask(id);
374
+ if (!task)
375
+ return null;
376
+ if (task.type === 'once')
377
+ throw new Error(`cannot resume once schedule ${id}`);
378
+ if (!task.isPaused)
379
+ return task;
380
+ const updated = await this._withWriteGuard(() => this._repo.updateTask(id, (t) => {
381
+ t.isPaused = false;
382
+ t.pausedAt = null;
383
+ t.pausedBy = null;
384
+ Object.assign(t, computeTaskTiming(t.type, t));
385
+ }));
386
+ if (updated)
387
+ this._rescheduleTask(updated);
388
+ return updated;
389
+ }
390
+ setBeforeRunGuard(fn) {
391
+ this._beforeRunGuard = fn;
392
+ }
393
+ setOnGuardBlocked(fn) {
394
+ this._onGuardBlocked = fn;
395
+ }
396
+ async getRateLimitThrottle() {
397
+ return this._repo.getRateLimitThrottle();
398
+ }
399
+ async setRateLimitThrottle(meta) {
400
+ await this._withWriteGuard(() => this._repo.setRateLimitThrottle(meta));
401
+ }
402
+ async setInterval(id, intervalMs) {
403
+ const task = await this.get(id);
404
+ if (!task)
405
+ return null;
406
+ if (task.type !== 'interval')
407
+ throw new Error(`task ${id} is not an interval schedule`);
408
+ return this.update(id, { intervalMs });
409
+ }
410
+ _rescheduleTask(task) {
411
+ const timer = this.timers.get(task.id);
412
+ if (timer) {
413
+ clearTimeout(timer);
414
+ this.timers.delete(task.id);
415
+ }
416
+ this._scheduleTask(task);
417
+ }
418
+ // Internal: set up the timer(s) for a task
419
+ _scheduleTask(task) {
420
+ this._taskConfigs.set(task.id, taskConfigHash(task));
421
+ if (task.isPaused) {
422
+ return;
423
+ }
424
+ if (task.type === 'once') {
425
+ const delay = Math.max(0, (task.runAt || 0) - Date.now());
426
+ const timer = setTimeout(async () => {
427
+ await this._runTask(task);
428
+ await this.remove(task.id);
429
+ }, delay);
430
+ this.timers.set(task.id, timer);
431
+ return;
432
+ }
433
+ const getNextDelay = (t) => {
434
+ if (t.type === 'interval')
435
+ return t.intervalMs || 60000;
436
+ if (t.type === 'daily')
437
+ return nextDailyMs(t.time);
438
+ if (t.type === 'weekly')
439
+ return nextWeeklyMs(t.dayOfWeek, t.time);
440
+ return 60000;
441
+ };
442
+ let initialDelay;
443
+ if (task.type === 'daily') {
444
+ initialDelay = nextDailyMs(task.time);
445
+ }
446
+ else if (task.type === 'weekly') {
447
+ initialDelay = nextWeeklyMs(task.dayOfWeek, task.time);
448
+ }
449
+ else {
450
+ initialDelay = Math.max(0, (task.nextRun || 0) - Date.now());
451
+ }
452
+ const fire = async () => {
453
+ try {
454
+ // Pre-check gate
455
+ if (task.preCheck) {
456
+ const freshTask = await this._repo.findTask(task.id);
457
+ if (freshTask?.preCheck) {
458
+ try {
459
+ execSync(freshTask.preCheck, {
460
+ timeout: 15000,
461
+ env: { ...process.env, PRECHECK_LAST_RUN: String(freshTask.lastRun || 0) },
462
+ stdio: 'pipe',
463
+ cwd: DATA_DIR,
464
+ });
465
+ }
466
+ catch (e) {
467
+ const output = (e.stdout || e.stderr || '').toString().trim();
468
+ log.info(`Pre-check skip for ${task.id}: ${output || 'exit ' + e.status}`);
469
+ await this._withWriteGuard(() => this._repo.updateTask(task.id, (t) => {
470
+ const nextDelayMs = getNextDelay(t);
471
+ t.nextRun = Date.now() + nextDelayMs;
472
+ t.lastSkipped = Date.now();
473
+ }));
474
+ this.timers.set(task.id, setTimeout(fire, getNextDelay(freshTask)));
475
+ return;
476
+ }
477
+ }
478
+ }
479
+ // Before-run guard
480
+ if (this._beforeRunGuard && this._beforeRunGuard(task)) {
481
+ if (this._onGuardBlocked) {
482
+ this._onGuardBlocked(task).catch(e => log.error(`Guard-blocked handler error for ${task.id}:`, e));
483
+ }
484
+ return;
485
+ }
486
+ if (this._inFlight.has(task.id)) {
487
+ log.info(`Task ${task.id} still in-flight, skipping this cycle`);
488
+ }
489
+ else {
490
+ this._inFlight.add(task.id);
491
+ await this._runTask(task).finally(() => this._inFlight.delete(task.id));
492
+ }
493
+ // Update lastRun and reschedule
494
+ const t = await this._repo.findTask(task.id);
495
+ if (!t || t.isPaused)
496
+ return;
497
+ const nextDelayMs = getNextDelay(t);
498
+ await this._withWriteGuard(() => this._repo.updateTask(task.id, (tt) => {
499
+ tt.lastRun = Date.now();
500
+ tt.nextRun = Date.now() + nextDelayMs;
501
+ }));
502
+ this.timers.set(task.id, setTimeout(fire, nextDelayMs));
503
+ }
504
+ catch (e) {
505
+ log.error(`Fire error for ${task.id}:`, e.message);
506
+ }
507
+ };
508
+ this.timers.set(task.id, setTimeout(fire, initialDelay));
509
+ }
510
+ // Internal: invoke the runner for a task
511
+ async _runTask(task) {
512
+ const profileName = resolveTaskProfile(task.profile);
513
+ log.info(`Firing task ${task.id} (${task.type}, dispatch=${task.dispatchType || 'llm'}, profile=${profileName}): "${task.message}"`);
514
+ try {
515
+ if (task.dispatchType === 'task-dispatch' && this.taskDispatchRunner) {
516
+ await this.taskDispatchRunner({
517
+ channel: task.channel,
518
+ scheduleTaskId: task.id,
519
+ profileName,
520
+ });
521
+ }
522
+ else if (task.dispatchType && this.programmaticHandlers[task.dispatchType]) {
523
+ await this.programmaticHandlers[task.dispatchType]({
524
+ channel: task.channel,
525
+ scheduleTaskId: task.id,
526
+ });
527
+ }
528
+ else {
529
+ await this.runner({
530
+ message: `[Scheduled Task] ${task.message}`,
531
+ channel: task.channel,
532
+ scheduleTaskId: task.id,
533
+ profileName,
534
+ target: task.target,
535
+ fallback: task.fallback,
536
+ });
537
+ }
538
+ }
539
+ catch (e) {
540
+ log.error(`Task ${task.id} runner error:`, e.message);
541
+ }
542
+ }
543
+ }
544
+ export { Scheduler, parseDuration, formatDuration, formatTimeUntil, SCHEDULES_FILE };
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Derive the Claude Code project directory hash from DATA_DIR.
3
+ * Claude Code encodes project directories by replacing '/' and '.' with '-'.
4
+ * e.g. /home/user/.cortex → -home-user--cortex
5
+ */
6
+ declare function getProjectHash(): string;
7
+ /**
8
+ * Get the path to a Claude Code session JSONL file.
9
+ */
10
+ declare function getSessionFilePath(sessionId: string): string;
11
+ /**
12
+ * Find a PI session file by session ID.
13
+ * Scans the PI session directory for .jsonl files and matches by the header's `id` field.
14
+ * Returns the full file path, or null if not found.
15
+ */
16
+ declare function findPISessionFile(sessionId: string): string | null;
17
+ /**
18
+ * Create a session file backup at an explicit file path.
19
+ * The backup is stored as `<filePath>.turn-<turnIndex>.bak`.
20
+ * Returns the backup path, or null if the file doesn't exist.
21
+ */
22
+ declare function backupSessionFile(filePath: string, turnIndex: number): string | null;
23
+ /**
24
+ * Restore a session file from a turn backup.
25
+ * Returns true if the backup was found and restored.
26
+ */
27
+ declare function restoreSessionFile(filePath: string, turnIndex: number): boolean;
28
+ /**
29
+ * Delete backups for turns strictly after the given index for a specific session file.
30
+ * Backups are named `<basename>.turn-<N>.bak`.
31
+ */
32
+ declare function cleanupBackupsForFile(filePath: string, afterTurnIndex: number): void;
33
+ /**
34
+ * Create a backup of the session file before processing a turn.
35
+ * Returns the backup path, or null if the session file doesn't exist yet.
36
+ */
37
+ declare function createBackup(sessionId: string, turnIndex: number): string | null;
38
+ declare function restoreBackup(sessionId: string, turnIndex: number): boolean;
39
+ /**
40
+ * Delete all backup files for a session.
41
+ * Called on !new to clean up.
42
+ */
43
+ declare function cleanupAllBackups(sessionId: string): void;
44
+ /**
45
+ * Delete backups for turns strictly after the given index.
46
+ * Called after rollback to remove invalidated backups.
47
+ */
48
+ declare function cleanupBackupsAfter(sessionId: string, afterTurnIndex: number): void;
49
+ export { getSessionFilePath, createBackup, restoreBackup, cleanupAllBackups, cleanupBackupsAfter, getProjectHash, findPISessionFile, backupSessionFile, restoreSessionFile, cleanupBackupsForFile, };