@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,103 @@
1
+ // input: nothing (leaf module)
2
+ // output: createLogger() factory
3
+ // pos: centralized logging — console + daily-rotating file sink
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { LOGS_DIR } from './paths.js';
8
+ // ── Config ──────────────────────────────────────────────
9
+ const RETENTION_DAYS = 14;
10
+ // ── File sink (daily rotation) ──────────────────────────
11
+ let currentDate = '';
12
+ let stream = null;
13
+ let lastCleanup = '';
14
+ function dateTag() {
15
+ const d = new Date();
16
+ return [
17
+ d.getFullYear(),
18
+ String(d.getMonth() + 1).padStart(2, '0'),
19
+ String(d.getDate()).padStart(2, '0'),
20
+ ].join('');
21
+ }
22
+ function getStream() {
23
+ const tag = dateTag();
24
+ if (tag !== currentDate || !stream) {
25
+ stream?.end();
26
+ fs.mkdirSync(LOGS_DIR, { recursive: true });
27
+ currentDate = tag;
28
+ stream = fs.createWriteStream(path.join(LOGS_DIR, `server-${tag}.log`), { flags: 'a' });
29
+ // attempt cleanup at most once per calendar day
30
+ if (lastCleanup !== tag) {
31
+ lastCleanup = tag;
32
+ cleanOldLogs();
33
+ }
34
+ }
35
+ return stream;
36
+ }
37
+ function cleanOldLogs() {
38
+ try {
39
+ const cutoff = Date.now() - RETENTION_DAYS * 86_400_000;
40
+ for (const f of fs.readdirSync(LOGS_DIR)) {
41
+ const m = f.match(/^server-(\d{4})(\d{2})(\d{2})\.log$/);
42
+ if (!m)
43
+ continue;
44
+ const fileDate = new Date(+m[1], +m[2] - 1, +m[3]).getTime();
45
+ if (fileDate < cutoff) {
46
+ fs.unlinkSync(path.join(LOGS_DIR, f));
47
+ }
48
+ }
49
+ }
50
+ catch {
51
+ // best-effort cleanup — don't crash on permission errors etc.
52
+ }
53
+ }
54
+ // ── Formatting ──────────────────────────────────────────
55
+ function formatArg(a) {
56
+ if (a instanceof Error)
57
+ return a.stack || a.message;
58
+ if (typeof a === 'object' && a !== null) {
59
+ try {
60
+ return JSON.stringify(a);
61
+ }
62
+ catch {
63
+ return String(a);
64
+ }
65
+ }
66
+ return String(a);
67
+ }
68
+ // ── Core write ──────────────────────────────────────────
69
+ function write(level, mod, args) {
70
+ const ts = new Date().toLocaleTimeString('en-GB', { hour12: false });
71
+ const prefix = `[${mod} ${ts}]`;
72
+ // Console output
73
+ switch (level) {
74
+ case 'ERROR':
75
+ console.error(prefix, ...args);
76
+ break;
77
+ case 'WARN':
78
+ console.warn(prefix, ...args);
79
+ break;
80
+ case 'DEBUG':
81
+ console.debug(prefix, ...args);
82
+ break;
83
+ default: console.log(prefix, ...args);
84
+ }
85
+ // File output
86
+ const line = `${prefix} ${level} ${args.map(formatArg).join(' ')}\n`;
87
+ try {
88
+ getStream().write(line);
89
+ }
90
+ catch { /* don't crash on write failure */ }
91
+ }
92
+ // ── Factory ─────────────────────────────────────────────
93
+ export function createLogger(mod) {
94
+ return {
95
+ info: (...args) => write('INFO', mod, args),
96
+ warn: (...args) => write('WARN', mod, args),
97
+ error: (...args) => write('ERROR', mod, args),
98
+ debug: (...args) => { if (process.env.DEBUG)
99
+ write('DEBUG', mod, args); },
100
+ };
101
+ }
102
+ // Flush on process exit
103
+ process.on('exit', () => { stream?.end(); });
@@ -0,0 +1,32 @@
1
+ /** Installed package root — where `dist/` and `defaults/` live. Immutable code/assets,
2
+ * never write here. For user-mutable state use DATA_DIR. */
3
+ export declare const INSTALL_ROOT: string;
4
+ /** Default scaffold assets shipped with the package. Read-only at runtime;
5
+ * `cortex init` copies what users need from here into DATA_DIR. */
6
+ export declare const DEFAULTS_DIR: string;
7
+ /** @deprecated Use INSTALL_ROOT. Kept as alias during refactor. */
8
+ export declare const PACKAGE_ROOT: string;
9
+ /** @deprecated Use INSTALL_ROOT. Kept as alias during refactor. */
10
+ export declare const SERVER_ROOT: string;
11
+ /** @deprecated Use INSTALL_ROOT or DATA_DIR depending on intent. Alias during refactor. */
12
+ export declare const REPO_ROOT: string;
13
+ /** User data directory. Reads $CORTEX_HOME, falls back to ~/.cortex/. */
14
+ export declare const DATA_DIR: string;
15
+ /** Configuration files — .env, budget, mode, profiles, templates, etc. (DATA_DIR/config/). */
16
+ export declare const CONFIG_DIR: string;
17
+ /** Persistent store for runtime JSON state files (DATA_DIR/data/). */
18
+ export declare const STORE_DIR: string;
19
+ /** Research context root — OVERVIEW, decisions, projects, scans, user profile (DATA_DIR/context/). */
20
+ export declare const CONTEXT_DIR: string;
21
+ /** User project directory. Reads $CORTEX_PROJECTS_DIR, falls back to CONTEXT_DIR/projects/. */
22
+ export declare const PROJECTS_DIR: string;
23
+ /** Temporary workspace directory for thread artifacts, tool results, etc. */
24
+ export declare const WORKSPACE_DIR: string;
25
+ /** Plugin packages directory (DATA_DIR/plugins/). */
26
+ export declare const PLUGINS_DIR: string;
27
+ /** Prompt files directory — directives, systemPrompts, promptTemplates (DATA_DIR/prompts/). */
28
+ export declare const PROMPTS_DIR: string;
29
+ /** Claude Code hook scripts directory (DATA_DIR/hooks/). */
30
+ export declare const HOOKS_DIR: string;
31
+ /** Log files directory — server daily logs, event logs, session logs (DATA_DIR/logs/). */
32
+ export declare const LOGS_DIR: string;
@@ -0,0 +1,49 @@
1
+ // input: nothing (leaf module)
2
+ // output: INSTALL_ROOT / DEFAULTS_DIR / DATA_DIR / CONFIG_DIR / STORE_DIR / CONTEXT_DIR / PROJECTS_DIR / WORKSPACE_DIR / PLUGINS_DIR / PROMPTS_DIR / HOOKS_DIR / LOGS_DIR
3
+ // (deprecated aliases: PACKAGE_ROOT, SERVER_ROOT, REPO_ROOT — all map to INSTALL_ROOT for migration period)
4
+ // pos: canonical path constants — install root (immutable code/assets) + user data/config/store/context/tmp
5
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
6
+ import * as path from 'path';
7
+ import * as os from 'os';
8
+ import { fileURLToPath } from 'url';
9
+ // This file lives at dist/core/paths.js when installed (or running from repo via tsx).
10
+ // Two levels up resolves to the install/package root, which contains `dist/` and `defaults/`.
11
+ // Install layout: <prefix>/lib/node_modules/cortex-agent-server/{dist,defaults}/
12
+ // Repo layout: <repo>/agent-server/{dist,defaults}/ (Node resolves symlinks via realpath)
13
+ const CORE_DIR = path.dirname(fileURLToPath(import.meta.url));
14
+ /** Installed package root — where `dist/` and `defaults/` live. Immutable code/assets,
15
+ * never write here. For user-mutable state use DATA_DIR. */
16
+ export const INSTALL_ROOT = path.resolve(CORE_DIR, '..', '..');
17
+ /** Default scaffold assets shipped with the package. Read-only at runtime;
18
+ * `cortex init` copies what users need from here into DATA_DIR. */
19
+ export const DEFAULTS_DIR = path.join(INSTALL_ROOT, 'defaults');
20
+ /** @deprecated Use INSTALL_ROOT. Kept as alias during refactor. */
21
+ export const PACKAGE_ROOT = INSTALL_ROOT;
22
+ /** @deprecated Use INSTALL_ROOT. Kept as alias during refactor. */
23
+ export const SERVER_ROOT = INSTALL_ROOT;
24
+ /** @deprecated Use INSTALL_ROOT or DATA_DIR depending on intent. Alias during refactor. */
25
+ export const REPO_ROOT = INSTALL_ROOT;
26
+ /** User data directory. Reads $CORTEX_HOME, falls back to ~/.cortex/. */
27
+ export const DATA_DIR = process.env.CORTEX_HOME
28
+ ? path.resolve(process.env.CORTEX_HOME)
29
+ : path.join(os.homedir(), '.cortex');
30
+ /** Configuration files — .env, budget, mode, profiles, templates, etc. (DATA_DIR/config/). */
31
+ export const CONFIG_DIR = path.join(DATA_DIR, 'config');
32
+ /** Persistent store for runtime JSON state files (DATA_DIR/data/). */
33
+ export const STORE_DIR = path.join(DATA_DIR, 'data');
34
+ /** Research context root — OVERVIEW, decisions, projects, scans, user profile (DATA_DIR/context/). */
35
+ export const CONTEXT_DIR = path.join(DATA_DIR, 'context');
36
+ /** User project directory. Reads $CORTEX_PROJECTS_DIR, falls back to CONTEXT_DIR/projects/. */
37
+ export const PROJECTS_DIR = process.env.CORTEX_PROJECTS_DIR
38
+ ? path.resolve(process.env.CORTEX_PROJECTS_DIR)
39
+ : path.join(CONTEXT_DIR, 'projects');
40
+ /** Temporary workspace directory for thread artifacts, tool results, etc. */
41
+ export const WORKSPACE_DIR = path.join(DATA_DIR, 'tmp');
42
+ /** Plugin packages directory (DATA_DIR/plugins/). */
43
+ export const PLUGINS_DIR = path.join(DATA_DIR, 'plugins');
44
+ /** Prompt files directory — directives, systemPrompts, promptTemplates (DATA_DIR/prompts/). */
45
+ export const PROMPTS_DIR = path.join(DATA_DIR, 'prompts');
46
+ /** Claude Code hook scripts directory (DATA_DIR/hooks/). */
47
+ export const HOOKS_DIR = path.join(DATA_DIR, 'hooks');
48
+ /** Log files directory — server daily logs, event logs, session logs (DATA_DIR/logs/). */
49
+ export const LOGS_DIR = path.join(DATA_DIR, 'logs');
@@ -0,0 +1,65 @@
1
+ import type { DiscoveredEndpoint } from './gateway-generator.js';
2
+ interface ProfileEntry {
3
+ model: string;
4
+ backend: string;
5
+ mode: string;
6
+ fallback?: ProfileEntry[];
7
+ extraEnv?: Record<string, string>;
8
+ extraOption?: Record<string, string>;
9
+ }
10
+ interface ProfilesFile {
11
+ defaultProfile: string;
12
+ profiles: Record<string, ProfileEntry>;
13
+ }
14
+ /** A (mode, model) pair the user can pick as the source for plan/execute. */
15
+ export interface ModelChoice {
16
+ mode: string;
17
+ model: string;
18
+ }
19
+ export interface GenerateOpts {
20
+ /** Explicit (mode, model) to use as the `plan` profile. Otherwise auto-inferred from anthropic max-tier. */
21
+ planChoice?: ModelChoice;
22
+ /** Explicit (mode, model) to use as the `execute` profile. Otherwise auto-inferred (non-Claude-Code mid-tier preferred). */
23
+ executeChoice?: ModelChoice;
24
+ }
25
+ /**
26
+ * Flatten endpoints to a list of (mode, model) choices the user can pick from.
27
+ * Ordered so Anthropic plan/api modes come first (recommended for `plan` profile).
28
+ */
29
+ export declare function listChoices(endpoints: DiscoveredEndpoint[]): ModelChoice[];
30
+ /**
31
+ * Generate a profiles.json object from discovered endpoints.
32
+ *
33
+ * Naming: outputs unsuffixed `plan` and `execute` (no provider suffix).
34
+ *
35
+ * Selection rules:
36
+ * - plan: explicit `opts.planChoice` if provided, else max-tier Anthropic.
37
+ * - execute: explicit `opts.executeChoice` if provided, else prefer non-Claude-Code
38
+ * mid-tier (cost), fall back to Anthropic mid-tier, then max.
39
+ *
40
+ * Provider-specific profiles always layered on top:
41
+ * - deepseek-flash / deepseek-pro: if DeepSeek models discovered. `--thinking xhigh`
42
+ * only on PI backend non-flash (the only PI + DeepSeek combo that should get it).
43
+ * - codex: if OpenAI models discovered.
44
+ */
45
+ export declare function generateProfiles(endpoints: DiscoveredEndpoint[], opts?: GenerateOpts): ProfilesFile;
46
+ /**
47
+ * Merge generated profiles into existing profiles.json.
48
+ * - Non-(plan/execute) existing profiles are always preserved.
49
+ * - For `plan` and `execute`: `overwrite=true` replaces them with generated;
50
+ * `overwrite=false` (default) preserves existing user customization.
51
+ * - defaultProfile is only updated if the current default doesn't exist in merged.
52
+ */
53
+ export declare function mergeProfilesJson(generated: ProfilesFile, outputDir?: string, overwrite?: boolean): ProfilesFile;
54
+ export interface WriteProfilesOpts extends GenerateOpts {
55
+ /** Output directory. Defaults to ~/.cortex/config. */
56
+ outputDir?: string;
57
+ /** Force overwrite of existing `plan` / `execute` profiles. Default false. */
58
+ overwrite?: boolean;
59
+ }
60
+ /**
61
+ * Write profiles.json to ~/.cortex/config/profiles.json (or outputDir/profiles.json).
62
+ * Merges with existing file to preserve user customizations unless overwrite=true.
63
+ */
64
+ export declare function writeProfilesJson(endpoints: DiscoveredEndpoint[], optsOrOutputDir?: WriteProfilesOpts | string): string;
65
+ export {};
@@ -0,0 +1,310 @@
1
+ // input: DiscoveredEndpoint[], profile-manager types, fs, path
2
+ // output: generateProfiles / mergeProfilesJson / writeProfilesJson / listChoices
3
+ // — produce profiles.json content from discovered models
4
+ // pos: init-time profiles.json auto-generation. Names are unsuffixed (`plan`, `execute`);
5
+ // users can override via explicit (mode, model) choices from `cortex init`.
6
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
7
+ import * as path from 'path';
8
+ import * as os from 'os';
9
+ import { createLogger } from './log.js';
10
+ const log = createLogger('profile-generator');
11
+ // ─── Model tier classification ────────────────────────────────────
12
+ /** Determine model tier: "max", "mid", or "budget". */
13
+ function classifyTier(model) {
14
+ const lower = model.toLowerCase();
15
+ if (lower.includes('opus') || lower.includes('pro') || lower.includes('gpt-5'))
16
+ return 'max';
17
+ if (lower.includes('sonnet') || lower.includes('flash') || lower.includes('mini'))
18
+ return 'mid';
19
+ if (lower.includes('haiku') || lower.includes('lite'))
20
+ return 'budget';
21
+ return 'mid'; // default
22
+ }
23
+ // ─── Endpoint → backend mapping ────────────────────────────────────
24
+ /**
25
+ * Determine the Cortex backend from endpoint and mode.
26
+ * - anthropic endpoint with plan/api mode → claude
27
+ * - openai endpoint → codex
28
+ * - everything else → pi (or claude if anthropic endpoint)
29
+ */
30
+ function resolveBackend(endpoint, mode) {
31
+ if (endpoint === 'anthropic' && (mode === 'plan' || mode === 'api')) {
32
+ return 'claude';
33
+ }
34
+ if (endpoint === 'openai') {
35
+ return 'codex';
36
+ }
37
+ if (endpoint === 'anthropic') {
38
+ // Non-standard Anthropic mode (e.g., deepseek-anthropic) — can use claude or pi
39
+ // PI handles anthropic-compatible APIs better for custom providers
40
+ return 'pi';
41
+ }
42
+ return 'pi';
43
+ }
44
+ /** Flatten all discovered endpoints into a list of (model, backend, mode) entries. */
45
+ function flattenModels(endpoints) {
46
+ const entries = [];
47
+ for (const ep of endpoints) {
48
+ const backend = resolveBackend(ep.endpoint, ep.mode);
49
+ for (const model of ep.models) {
50
+ entries.push({
51
+ model,
52
+ backend,
53
+ mode: ep.mode,
54
+ tier: classifyTier(model),
55
+ endpoint: ep.endpoint,
56
+ });
57
+ }
58
+ }
59
+ return entries;
60
+ }
61
+ /** Pick the best model for a given tier and preferred endpoint. */
62
+ function pickModel(models, tier, preferEndpoint) {
63
+ // Prefer specific endpoint
64
+ if (preferEndpoint) {
65
+ const match = models.filter(m => m.tier === tier && m.endpoint === preferEndpoint);
66
+ if (match.length > 0)
67
+ return match[0];
68
+ }
69
+ // Fallback to any endpoint
70
+ const any = models.filter(m => m.tier === tier);
71
+ if (any.length > 0)
72
+ return any[0];
73
+ // Downgrade tier
74
+ if (tier === 'max')
75
+ return pickModel(models, 'mid', preferEndpoint);
76
+ if (tier === 'mid')
77
+ return pickModel(models, 'budget', preferEndpoint);
78
+ return null;
79
+ }
80
+ /** Build a fallback chain for a given model.
81
+ * Only includes models that are strictly lower-tier or from other endpoints. */
82
+ function buildFallbackChain(primary, models) {
83
+ const fallbacks = [];
84
+ const tierOrder = { max: 0, mid: 1, budget: 2 };
85
+ const primaryRank = tierOrder[primary.tier] ?? 1;
86
+ // Same endpoint, strictly lower tier (not same or higher)
87
+ const sameEndpoint = models.filter(m => m.endpoint === primary.endpoint
88
+ && m.model !== primary.model
89
+ && (tierOrder[m.tier] ?? 1) > primaryRank);
90
+ sameEndpoint.sort((a, b) => (tierOrder[a.tier] ?? 1) - (tierOrder[b.tier] ?? 1));
91
+ for (const m of sameEndpoint.slice(0, 2)) {
92
+ fallbacks.push({ model: m.model, backend: m.backend, mode: m.mode });
93
+ }
94
+ // Cross-endpoint fallback (e.g., Claude → DeepSeek)
95
+ const otherEndpoint = models.filter(m => m.endpoint !== primary.endpoint);
96
+ otherEndpoint.sort((a, b) => (tierOrder[a.tier] ?? 1) - (tierOrder[b.tier] ?? 1));
97
+ for (const m of otherEndpoint.slice(0, 2)) {
98
+ fallbacks.push({ model: m.model, backend: m.backend, mode: m.mode });
99
+ }
100
+ return fallbacks;
101
+ }
102
+ /** Build profile entry from a ModelEntry, with optional extra config. */
103
+ function makeProfileEntry(m, models, extraEnv, extraOption) {
104
+ return {
105
+ model: m.model,
106
+ backend: m.backend,
107
+ mode: m.mode,
108
+ fallback: buildFallbackChain(m, models),
109
+ ...(extraEnv ? { extraEnv } : {}),
110
+ ...(extraOption ? { extraOption } : {}),
111
+ };
112
+ }
113
+ /** Locate a ModelEntry by explicit (mode, model). Throws if not found. */
114
+ function findModelEntry(models, choice, label) {
115
+ const match = models.find(m => m.mode === choice.mode && m.model === choice.model);
116
+ if (!match) {
117
+ throw new Error(`${label}: (mode="${choice.mode}", model="${choice.model}") not found among discovered models`);
118
+ }
119
+ return match;
120
+ }
121
+ /** Generate profiles for DeepSeek models (if available in discovered endpoints). */
122
+ function generateDeepSeekProfiles(models) {
123
+ const result = {};
124
+ const deepseekModels = models.filter(m => m.model.toLowerCase().includes('deepseek'));
125
+ for (const dm of deepseekModels) {
126
+ const isFlash = dm.model.toLowerCase().includes('flash');
127
+ const profileName = isFlash ? 'deepseek-flash' : 'deepseek-pro';
128
+ const extraEnv = {};
129
+ const extraOption = {};
130
+ if (dm.backend === 'claude') {
131
+ // Claude Code requires these for non-Anthropic providers
132
+ extraEnv.CLAUDE_CODE_ATTRIBUTION_HEADER = '0';
133
+ extraEnv.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = '1';
134
+ extraEnv.CLAUDE_CODE_DISABLE_SESSION_METADATA = '1';
135
+ }
136
+ else if (dm.backend === 'pi' && !isFlash) {
137
+ // DeepSeek pro with extended thinking via PI (only PI + DeepSeek non-flash)
138
+ extraOption['--thinking'] = 'xhigh';
139
+ }
140
+ result[profileName] = {
141
+ model: dm.model,
142
+ backend: dm.backend,
143
+ mode: dm.mode,
144
+ ...(Object.keys(extraEnv).length > 0 ? { extraEnv } : {}),
145
+ ...(Object.keys(extraOption).length > 0 ? { extraOption } : {}),
146
+ };
147
+ }
148
+ return result;
149
+ }
150
+ /** Generate Codex profile if OpenAI models are available. */
151
+ function generateCodexProfile(models) {
152
+ const openaiModels = models.filter(m => m.endpoint === 'openai');
153
+ if (openaiModels.length === 0)
154
+ return {};
155
+ const best = openaiModels.find(m => m.tier === 'max') || openaiModels[0];
156
+ const fallbacks = [];
157
+ // Fallback: Anthropic sonnet
158
+ const claudeMid = models.find(m => m.endpoint === 'anthropic' && m.tier === 'mid');
159
+ if (claudeMid) {
160
+ fallbacks.push({ model: claudeMid.model, backend: claudeMid.backend, mode: 'plan' });
161
+ }
162
+ return {
163
+ codex: {
164
+ model: best.model,
165
+ backend: 'codex',
166
+ mode: 'plan',
167
+ fallback: fallbacks.length > 0 ? fallbacks : undefined,
168
+ },
169
+ };
170
+ }
171
+ // ─── Choice listing (for init UI) ─────────────────────────────────
172
+ /**
173
+ * Flatten endpoints to a list of (mode, model) choices the user can pick from.
174
+ * Ordered so Anthropic plan/api modes come first (recommended for `plan` profile).
175
+ */
176
+ export function listChoices(endpoints) {
177
+ const flat = flattenModels(endpoints);
178
+ // Sort: anthropic+plan/api first (recommended for plan), then others.
179
+ // Within each group, max-tier first.
180
+ const tierOrder = { max: 0, mid: 1, budget: 2 };
181
+ const isAnthropicNative = (m) => m.endpoint === 'anthropic' && (m.mode === 'plan' || m.mode === 'api');
182
+ flat.sort((a, b) => {
183
+ const aN = isAnthropicNative(a) ? 0 : 1;
184
+ const bN = isAnthropicNative(b) ? 0 : 1;
185
+ if (aN !== bN)
186
+ return aN - bN;
187
+ return (tierOrder[a.tier] ?? 1) - (tierOrder[b.tier] ?? 1);
188
+ });
189
+ return flat.map(m => ({ mode: m.mode, model: m.model }));
190
+ }
191
+ // ─── Main generation ──────────────────────────────────────────────
192
+ /**
193
+ * Generate a profiles.json object from discovered endpoints.
194
+ *
195
+ * Naming: outputs unsuffixed `plan` and `execute` (no provider suffix).
196
+ *
197
+ * Selection rules:
198
+ * - plan: explicit `opts.planChoice` if provided, else max-tier Anthropic.
199
+ * - execute: explicit `opts.executeChoice` if provided, else prefer non-Claude-Code
200
+ * mid-tier (cost), fall back to Anthropic mid-tier, then max.
201
+ *
202
+ * Provider-specific profiles always layered on top:
203
+ * - deepseek-flash / deepseek-pro: if DeepSeek models discovered. `--thinking xhigh`
204
+ * only on PI backend non-flash (the only PI + DeepSeek combo that should get it).
205
+ * - codex: if OpenAI models discovered.
206
+ */
207
+ export function generateProfiles(endpoints, opts = {}) {
208
+ const models = flattenModels(endpoints);
209
+ if (models.length === 0) {
210
+ // Minimal fallback — user needs to log in first
211
+ return {
212
+ defaultProfile: 'plan',
213
+ profiles: {
214
+ plan: { model: 'opus', backend: 'claude', mode: 'plan' },
215
+ },
216
+ };
217
+ }
218
+ const profiles = {};
219
+ const anthropicModels = models.filter(m => m.endpoint === 'anthropic' && (m.mode === 'plan' || m.mode === 'api'));
220
+ // ── plan ──
221
+ const planEntry = opts.planChoice
222
+ ? findModelEntry(models, opts.planChoice, 'planChoice')
223
+ : pickModel(anthropicModels, 'max');
224
+ if (planEntry) {
225
+ profiles.plan = makeProfileEntry(planEntry, models);
226
+ }
227
+ // ── execute ──
228
+ let executeEntry;
229
+ if (opts.executeChoice) {
230
+ executeEntry = findModelEntry(models, opts.executeChoice, 'executeChoice');
231
+ }
232
+ else {
233
+ // Prefer mid-tier non-Anthropic-native models for cost savings
234
+ const nonClaudeMid = models.find(m => m.tier === 'mid' && !(m.endpoint === 'anthropic' && (m.mode === 'plan' || m.mode === 'api')));
235
+ executeEntry = nonClaudeMid || pickModel(anthropicModels, 'mid') || pickModel(anthropicModels, 'max');
236
+ }
237
+ if (executeEntry) {
238
+ profiles.execute = makeProfileEntry(executeEntry, models);
239
+ }
240
+ // ── Provider-specific profiles ──
241
+ Object.assign(profiles, generateDeepSeekProfiles(models));
242
+ Object.assign(profiles, generateCodexProfile(models));
243
+ return { defaultProfile: 'plan', profiles };
244
+ }
245
+ // ─── File I/O ─────────────────────────────────────────────────────
246
+ /**
247
+ * Merge generated profiles into existing profiles.json.
248
+ * - Non-(plan/execute) existing profiles are always preserved.
249
+ * - For `plan` and `execute`: `overwrite=true` replaces them with generated;
250
+ * `overwrite=false` (default) preserves existing user customization.
251
+ * - defaultProfile is only updated if the current default doesn't exist in merged.
252
+ */
253
+ export function mergeProfilesJson(generated, outputDir, overwrite = false) {
254
+ const existingPath = outputDir
255
+ ? path.join(outputDir, 'profiles.json')
256
+ : path.join(os.homedir(), '.cortex', 'config', 'profiles.json');
257
+ let existing = null;
258
+ try {
259
+ if (existsSync(existingPath)) {
260
+ existing = JSON.parse(readFileSync(existingPath, 'utf-8'));
261
+ }
262
+ }
263
+ catch (e) {
264
+ log.warn(`Failed to read existing profiles.json: ${e.message}`);
265
+ }
266
+ if (!existing || !existing.profiles) {
267
+ return generated;
268
+ }
269
+ const merged = { ...existing.profiles };
270
+ for (const [name, profile] of Object.entries(generated.profiles)) {
271
+ const isManaged = name === 'plan' || name === 'execute';
272
+ if (!merged[name]) {
273
+ merged[name] = profile;
274
+ log.info(`Added new profile: ${name}`);
275
+ }
276
+ else if (isManaged && overwrite) {
277
+ merged[name] = profile;
278
+ log.info(`Overwrote managed profile: ${name}`);
279
+ }
280
+ // else: preserve existing
281
+ }
282
+ // Keep existing defaultProfile if it still exists in merged profiles
283
+ let defaultProfile = existing.defaultProfile;
284
+ if (!merged[defaultProfile]) {
285
+ defaultProfile = generated.defaultProfile;
286
+ }
287
+ return { defaultProfile, profiles: merged };
288
+ }
289
+ /**
290
+ * Write profiles.json to ~/.cortex/config/profiles.json (or outputDir/profiles.json).
291
+ * Merges with existing file to preserve user customizations unless overwrite=true.
292
+ */
293
+ export function writeProfilesJson(endpoints, optsOrOutputDir) {
294
+ // Back-compat: previous signature was (endpoints, outputDir?: string)
295
+ const opts = typeof optsOrOutputDir === 'string'
296
+ ? { outputDir: optsOrOutputDir }
297
+ : (optsOrOutputDir ?? {});
298
+ const generated = generateProfiles(endpoints, {
299
+ planChoice: opts.planChoice,
300
+ executeChoice: opts.executeChoice,
301
+ });
302
+ const merged = mergeProfilesJson(generated, opts.outputDir, opts.overwrite ?? false);
303
+ const configDir = opts.outputDir || path.join(os.homedir(), '.cortex', 'config');
304
+ const outputPath = path.join(configDir, 'profiles.json');
305
+ mkdirSync(configDir, { recursive: true });
306
+ const content = JSON.stringify(merged, null, 2) + '\n';
307
+ writeFileSync(outputPath, content, 'utf-8');
308
+ log.info(`Written profiles.json to ${outputPath}`);
309
+ return outputPath;
310
+ }
@@ -0,0 +1,88 @@
1
+ import type { EventBus } from '../events/index.js';
2
+ export interface RunningExecution {
3
+ threadId: string | null;
4
+ channel: string | null;
5
+ registryKey: string;
6
+ agentSlotId: string | null;
7
+ executionId: string | null;
8
+ kill: () => boolean;
9
+ startTime: number;
10
+ backend: string;
11
+ /** Agent process reference — used by PI backend to route extension_ui_response for plan/ask interactions. */
12
+ agentProcess?: unknown;
13
+ /** Claude session ID — saved on cancel so the next message can resume the same session. */
14
+ sessionId?: string | null;
15
+ }
16
+ export type RunningExecutionInput = Omit<RunningExecution, 'registryKey' | 'startTime'>;
17
+ export declare class RunningExecutions {
18
+ /** Primary index: key is channel or hookHandleKey (arbitrary string). */
19
+ private byKey;
20
+ /** Secondary index: threadId → RunningExecution, only if threadId is non-null. */
21
+ private byThreadId;
22
+ /** Secondary index: executionId → RunningExecution, only if executionId is non-null. */
23
+ private byExecutionId;
24
+ /** EventBus for publishing agent.* lifecycle events. May be set after construction. */
25
+ private _bus;
26
+ constructor(bus?: EventBus);
27
+ setBus(bus: EventBus): void;
28
+ /**
29
+ * Register a new execution under an arbitrary key.
30
+ * Silently replaces any existing entry at the same key.
31
+ * Secondary indices (byThreadId / byExecutionId) are kept in sync.
32
+ * Publishes agent.started if executionId is non-null and bus is wired.
33
+ */
34
+ register(key: string, exec: RunningExecutionInput): void;
35
+ /** Look up an execution by its primary registry key. Returns null if not found. */
36
+ getByKey(key: string): RunningExecution | null;
37
+ /** Look up an execution by threadId. Returns null if not found or threadId was null at registration. */
38
+ getByThreadId(threadId: string): RunningExecution | null;
39
+ /** Look up an execution by executionId. Returns null if not found. */
40
+ getByExecutionId(executionId: string): RunningExecution | null;
41
+ /** Returns true if an execution is registered under the given key. */
42
+ has(key: string): boolean;
43
+ /**
44
+ * Kill the execution for a key, remove it from all indices, and return the result of kill().
45
+ * Returns false if no entry is registered for the key.
46
+ */
47
+ killByKey(key: string): boolean;
48
+ /**
49
+ * Kill the execution for a threadId, remove it from all indices, and return true.
50
+ * Resolves through byThreadId secondary index.
51
+ * Returns false if no entry has that threadId.
52
+ */
53
+ killByThreadId(threadId: string): boolean;
54
+ /**
55
+ * Remove an execution by key without calling kill() or publishing events.
56
+ * No-op if the key is not registered.
57
+ */
58
+ remove(key: string): void;
59
+ /** Return all registered executions (snapshot of the primary index). */
60
+ getAll(): RunningExecution[];
61
+ /**
62
+ * Mark the execution for a key as completed and publish agent.completed.
63
+ * Returns false if no entry is registered for the key (e.g., already removed).
64
+ * Publishes agent.completed only if executionId is non-null and bus is wired.
65
+ */
66
+ complete(key: string, costUsd?: number): boolean;
67
+ /**
68
+ * Mark the execution for a key as failed and publish agent.failed.
69
+ * Returns false if no entry is registered for the key (e.g., already removed by supersede).
70
+ * Publishes agent.failed only if executionId is non-null and bus is wired.
71
+ */
72
+ fail(key: string, error: string): boolean;
73
+ /**
74
+ * Kill the execution for a key, remove it, and publish agent.superseded.
75
+ * Returns false if no entry is registered for the key.
76
+ * Publishes agent.superseded only if executionId is non-null and bus is wired.
77
+ */
78
+ supersede(key: string, reason: string): boolean;
79
+ /**
80
+ * Remove an entry from secondary indices (byThreadId / byExecutionId).
81
+ * Guards each delete with identity check: only clears the index if it still points
82
+ * to this entry. This prevents corruption when a stale entry (whose threadId/executionId
83
+ * has been claimed by a newer entry) is removed.
84
+ */
85
+ private _removeFromIndices;
86
+ }
87
+ /** Singleton instance of RunningExecutions. */
88
+ export declare const runningExecutions: RunningExecutions;