@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,62 @@
1
+ /**
2
+ * Subset of Anthropic API's `usage` object as it appears in jsonl `assistant` entries.
3
+ * Older sessions may lack `cache_creation` sub-object (only flat counts); newer ones split 5m vs 1h.
4
+ */
5
+ export interface ClaudeUsage {
6
+ input_tokens?: number;
7
+ output_tokens?: number;
8
+ cache_creation_input_tokens?: number;
9
+ cache_read_input_tokens?: number;
10
+ cache_creation?: {
11
+ ephemeral_5m_input_tokens?: number;
12
+ ephemeral_1h_input_tokens?: number;
13
+ };
14
+ }
15
+ export interface ModelPricing {
16
+ inputPerMTok: number;
17
+ outputPerMTok: number;
18
+ cacheCreation5mPerMTok: number;
19
+ cacheCreation1hPerMTok: number;
20
+ cacheReadPerMTok: number;
21
+ }
22
+ /**
23
+ * Pricing table per Anthropic public rates (USD per 1M tokens). Keyed by model **family**
24
+ * (sonnet-4 / opus-4 / haiku-4), not specific revisions — revisions within a family share rates.
25
+ *
26
+ * If Anthropic publishes a price change, update here and bump the comment block date.
27
+ * Last verified: 2026-05-15.
28
+ *
29
+ * Rate references (Anthropic public pricing, Claude 4 family):
30
+ * sonnet-4: $3 input, $15 output, $3.75 cache-write-5m, $6 cache-write-1h, $0.30 cache-read
31
+ * opus-4: $15 input, $75 output, $18.75 cache-write-5m, $30 cache-write-1h, $1.50 cache-read
32
+ * haiku-4: $1 input, $5 output, $1.25 cache-write-5m, $2 cache-write-1h, $0.10 cache-read
33
+ */
34
+ export declare const PRICING_TABLE: Record<string, ModelPricing>;
35
+ /**
36
+ * Map a full Anthropic API model id (e.g. "claude-sonnet-4-5-20250929") to a pricing family key.
37
+ * Returns null for unrecognized strings — caller treats null as "cost unknown" rather than zero.
38
+ */
39
+ export declare function normalizeModelId(modelId: string | null | undefined): string | null;
40
+ export interface CostBreakdown {
41
+ input: number;
42
+ output: number;
43
+ cacheCreation5m: number;
44
+ cacheCreation1h: number;
45
+ cacheRead: number;
46
+ }
47
+ export interface CostResult {
48
+ totalUsd: number;
49
+ modelFamily: string;
50
+ breakdown: CostBreakdown;
51
+ }
52
+ /**
53
+ * Reverse-derive USD cost from a Claude `usage` object and the model id used for that message.
54
+ * Returns null when the model family is unknown — callers must handle null explicitly (do not
55
+ * silently fall through to zero, which would understate spend).
56
+ *
57
+ * Cache creation rule: prefer `cache_creation.ephemeral_{5m,1h}_input_tokens` split; if absent,
58
+ * fall back to treating the flat `cache_creation_input_tokens` count as 5m (conservative lower bound).
59
+ *
60
+ * @see DR-0012 §3.4 — per-message cost is summed across a turn by adapter-tui.ts using msg.id dedup.
61
+ */
62
+ export declare function usageToCost(usage: ClaudeUsage | null | undefined, modelId: string | null | undefined): CostResult | null;
@@ -0,0 +1,97 @@
1
+ // input: ClaudeUsage object (from assistant.message.usage in jsonl) + model id string
2
+ // output: usageToCost { totalUsd, modelFamily, breakdown }, PRICING_TABLE, normalizeModelId
3
+ // pos: Cost reconstruction for Claude TUI mode — jsonl has no total_cost_usd, so we reverse-derive from usage tokens
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ /**
6
+ * Pricing table per Anthropic public rates (USD per 1M tokens). Keyed by model **family**
7
+ * (sonnet-4 / opus-4 / haiku-4), not specific revisions — revisions within a family share rates.
8
+ *
9
+ * If Anthropic publishes a price change, update here and bump the comment block date.
10
+ * Last verified: 2026-05-15.
11
+ *
12
+ * Rate references (Anthropic public pricing, Claude 4 family):
13
+ * sonnet-4: $3 input, $15 output, $3.75 cache-write-5m, $6 cache-write-1h, $0.30 cache-read
14
+ * opus-4: $15 input, $75 output, $18.75 cache-write-5m, $30 cache-write-1h, $1.50 cache-read
15
+ * haiku-4: $1 input, $5 output, $1.25 cache-write-5m, $2 cache-write-1h, $0.10 cache-read
16
+ */
17
+ export const PRICING_TABLE = {
18
+ 'sonnet-4': {
19
+ inputPerMTok: 3.0,
20
+ outputPerMTok: 15.0,
21
+ cacheCreation5mPerMTok: 3.75,
22
+ cacheCreation1hPerMTok: 6.0,
23
+ cacheReadPerMTok: 0.30,
24
+ },
25
+ 'opus-4': {
26
+ inputPerMTok: 15.0,
27
+ outputPerMTok: 75.0,
28
+ cacheCreation5mPerMTok: 18.75,
29
+ cacheCreation1hPerMTok: 30.0,
30
+ cacheReadPerMTok: 1.50,
31
+ },
32
+ 'haiku-4': {
33
+ inputPerMTok: 1.0,
34
+ outputPerMTok: 5.0,
35
+ cacheCreation5mPerMTok: 1.25,
36
+ cacheCreation1hPerMTok: 2.0,
37
+ cacheReadPerMTok: 0.10,
38
+ },
39
+ };
40
+ /**
41
+ * Map a full Anthropic API model id (e.g. "claude-sonnet-4-5-20250929") to a pricing family key.
42
+ * Returns null for unrecognized strings — caller treats null as "cost unknown" rather than zero.
43
+ */
44
+ export function normalizeModelId(modelId) {
45
+ if (!modelId || typeof modelId !== 'string')
46
+ return null;
47
+ if (modelId.includes('sonnet-4'))
48
+ return 'sonnet-4';
49
+ if (modelId.includes('opus-4'))
50
+ return 'opus-4';
51
+ if (modelId.includes('haiku-4'))
52
+ return 'haiku-4';
53
+ return null;
54
+ }
55
+ /**
56
+ * Reverse-derive USD cost from a Claude `usage` object and the model id used for that message.
57
+ * Returns null when the model family is unknown — callers must handle null explicitly (do not
58
+ * silently fall through to zero, which would understate spend).
59
+ *
60
+ * Cache creation rule: prefer `cache_creation.ephemeral_{5m,1h}_input_tokens` split; if absent,
61
+ * fall back to treating the flat `cache_creation_input_tokens` count as 5m (conservative lower bound).
62
+ *
63
+ * @see DR-0012 §3.4 — per-message cost is summed across a turn by adapter-tui.ts using msg.id dedup.
64
+ */
65
+ export function usageToCost(usage, modelId) {
66
+ const family = normalizeModelId(modelId);
67
+ if (!family)
68
+ return null;
69
+ const pricing = PRICING_TABLE[family];
70
+ if (!pricing)
71
+ return null;
72
+ const u = usage || {};
73
+ const inputTok = u.input_tokens ?? 0;
74
+ const outputTok = u.output_tokens ?? 0;
75
+ const cacheCreationTotal = u.cache_creation_input_tokens ?? 0;
76
+ const cacheReadTok = u.cache_read_input_tokens ?? 0;
77
+ // Split cache_creation into 5m vs 1h when sub-object is present; otherwise assume 5m.
78
+ let cacheCreate5mTok;
79
+ let cacheCreate1hTok;
80
+ if (u.cache_creation && (typeof u.cache_creation.ephemeral_5m_input_tokens === 'number' || typeof u.cache_creation.ephemeral_1h_input_tokens === 'number')) {
81
+ cacheCreate5mTok = u.cache_creation.ephemeral_5m_input_tokens ?? 0;
82
+ cacheCreate1hTok = u.cache_creation.ephemeral_1h_input_tokens ?? 0;
83
+ }
84
+ else {
85
+ cacheCreate5mTok = cacheCreationTotal;
86
+ cacheCreate1hTok = 0;
87
+ }
88
+ const breakdown = {
89
+ input: (inputTok * pricing.inputPerMTok) / 1_000_000,
90
+ output: (outputTok * pricing.outputPerMTok) / 1_000_000,
91
+ cacheCreation5m: (cacheCreate5mTok * pricing.cacheCreation5mPerMTok) / 1_000_000,
92
+ cacheCreation1h: (cacheCreate1hTok * pricing.cacheCreation1hPerMTok) / 1_000_000,
93
+ cacheRead: (cacheReadTok * pricing.cacheReadPerMTok) / 1_000_000,
94
+ };
95
+ const totalUsd = breakdown.input + breakdown.output + breakdown.cacheCreation5m + breakdown.cacheCreation1h + breakdown.cacheRead;
96
+ return { totalUsd, modelFamily: family, breakdown };
97
+ }
@@ -0,0 +1,30 @@
1
+ import { HOOKS_DIR } from '../../core/utils.js';
2
+ export declare const MAX_TIMEOUT = 30000000;
3
+ export declare const IDLE_SESSION_TIMEOUT: number;
4
+ export declare const TURN_IDLE_TIMEOUT: number;
5
+ export declare const LOGS_DIR: string;
6
+ export declare const MCP_CONFIG: string;
7
+ export declare const CORE_MCP_CONFIG: string;
8
+ /** DR-0012: TUI-mode-exclusive MCP set (only cortex-tui-bridge server, no core/ext leakage). */
9
+ export declare const TUI_MCP_CONFIG: string;
10
+ export declare const PROJECT_SETTINGS: string;
11
+ export declare const DEFAULT_PLAN_DIRS: string[];
12
+ export declare const DEFAULT_TOOLS = "Agent,AskUserQuestion,Bash,Edit,EnterPlanMode,ExitPlanMode,Glob,Grep,Read,Skill,TaskStop,TodoWrite,WebFetch,WebSearch,Write";
13
+ /**
14
+ * DR-0012: Tool whitelist for TUI mode. Removes the three interaction tools that conflict with
15
+ * Cortex's MCP-mediated approval flow (AskUserQuestion / EnterPlanMode / ExitPlanMode) and adds
16
+ * their MCP replacements served by the cortex-tui-bridge MCP server.
17
+ *
18
+ * Tool name prefix `mcp__<server-name>__<tool-name>` is Claude's canonical form for MCP tools.
19
+ */
20
+ export declare const TUI_TOOLS: string;
21
+ /** DR-0012: tmux session name prefix for TUI-mode Claude processes. */
22
+ export declare const TUI_TMUX_NAME_PREFIX = "cortex-claude-";
23
+ /** DR-0012: Base directory where Claude writes per-session jsonl transcripts (per-cwd encoded). */
24
+ export declare const TUI_JSONL_BASE: string;
25
+ export { HOOKS_DIR };
26
+ export declare const HOOK_TIMEOUT_S: number;
27
+ export declare class CancelledError extends Error {
28
+ cancelled: boolean;
29
+ constructor();
30
+ }
@@ -0,0 +1,49 @@
1
+ // input: DATA_DIR from utils.js, fs
2
+ // output: Claude constants + CancelledError class
3
+ // pos: Claude adapter submodule shared constants and error types
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import * as path from 'path';
6
+ import * as os from 'os';
7
+ import { mkdirSync } from 'fs';
8
+ import { DATA_DIR, CONFIG_DIR, HOOKS_DIR } from '../../core/utils.js';
9
+ export const MAX_TIMEOUT = 30_000_000;
10
+ export const IDLE_SESSION_TIMEOUT = 65 * 60 * 1000;
11
+ export const TURN_IDLE_TIMEOUT = 60 * 60 * 1000;
12
+ export const LOGS_DIR = path.join(DATA_DIR, 'logs', 'sessions');
13
+ mkdirSync(LOGS_DIR, { recursive: true });
14
+ export const MCP_CONFIG = path.join(CONFIG_DIR, 'mcp-config.json');
15
+ export const CORE_MCP_CONFIG = path.join(CONFIG_DIR, 'mcp-config-core.json');
16
+ /** DR-0012: TUI-mode-exclusive MCP set (only cortex-tui-bridge server, no core/ext leakage). */
17
+ export const TUI_MCP_CONFIG = path.join(CONFIG_DIR, 'mcp-config-tui.json');
18
+ // User-customizable Claude settings live under DATA_DIR (init copies the seed from
19
+ // defaults/.claude/settings.json on first run). The installed package's defaults/.claude/
20
+ // is read-only and used only as the init source.
21
+ export const PROJECT_SETTINGS = path.join(DATA_DIR, '.claude', 'settings.json');
22
+ export const DEFAULT_PLAN_DIRS = ['plan'];
23
+ export const DEFAULT_TOOLS = 'Agent,AskUserQuestion,Bash,Edit,EnterPlanMode,ExitPlanMode,Glob,Grep,Read,Skill,TaskStop,TodoWrite,WebFetch,WebSearch,Write';
24
+ /**
25
+ * DR-0012: Tool whitelist for TUI mode. Removes the three interaction tools that conflict with
26
+ * Cortex's MCP-mediated approval flow (AskUserQuestion / EnterPlanMode / ExitPlanMode) and adds
27
+ * their MCP replacements served by the cortex-tui-bridge MCP server.
28
+ *
29
+ * Tool name prefix `mcp__<server-name>__<tool-name>` is Claude's canonical form for MCP tools.
30
+ */
31
+ export const TUI_TOOLS = [
32
+ 'Agent', 'Bash', 'Edit', 'Glob', 'Grep', 'Read', 'Skill', 'TaskStop', 'TodoWrite', 'WebFetch', 'WebSearch', 'Write',
33
+ 'mcp__cortex-tui-bridge__cortex_plan_enter',
34
+ 'mcp__cortex-tui-bridge__cortex_plan_exit',
35
+ 'mcp__cortex-tui-bridge__cortex_ask_user',
36
+ ].join(',');
37
+ /** DR-0012: tmux session name prefix for TUI-mode Claude processes. */
38
+ export const TUI_TMUX_NAME_PREFIX = 'cortex-claude-';
39
+ /** DR-0012: Base directory where Claude writes per-session jsonl transcripts (per-cwd encoded). */
40
+ export const TUI_JSONL_BASE = path.join(os.homedir(), '.claude', 'projects');
41
+ export { HOOKS_DIR };
42
+ export const HOOK_TIMEOUT_S = 60 * 60;
43
+ export class CancelledError extends Error {
44
+ cancelled;
45
+ constructor() {
46
+ super('Cancelled by user');
47
+ this.cancelled = true;
48
+ }
49
+ }
@@ -0,0 +1,28 @@
1
+ export declare function extractAskUserQuestions(data: any, sessionId: string): Array<{
2
+ toolUseId: string | null;
3
+ questions: any[];
4
+ sessionId: string;
5
+ }>;
6
+ export declare function formatAssistantEvent(data: any): string | null;
7
+ export declare function formatUserEvent(data: any): string | null;
8
+ export declare function formatResultEvent(data: any): string;
9
+ export declare function formatEvent(data: any): string | null;
10
+ export declare function buildPrompt(userMessage: string, files: any[]): string;
11
+ /** Merge a brief epilogue with a substantially longer earlier message (e.g. an orient briefing) so Slack gets the real content.
12
+ * Triggers only when final is both absolutely short (<300) AND relatively short (<50% of longest). */
13
+ export declare function mergeSubstantialOutput(finalOutput: string | null, longestOutput: string | null): string | null;
14
+ export type ExtractResultOutcome = {
15
+ resolved: true;
16
+ value: any;
17
+ error?: undefined;
18
+ } | {
19
+ resolved: false;
20
+ error: Error;
21
+ value?: undefined;
22
+ };
23
+ export declare function extractResult(resultData: any, effectiveSessionId: string, killed: boolean, code: number, stderr: string, planFilePath: string | null, enteredPlanMode: boolean, exitedPlanMode: boolean, askUserQuestions: any[], finalOutput: string | null, longestOutput: string | null): ExtractResultOutcome;
24
+ export declare const PLAN_DIRS: string[];
25
+ export declare function isPlanFilePath(filePath: unknown): boolean;
26
+ export declare function setActivePlanFile(sessionId: string, path: string): void;
27
+ export declare function clearActivePlanFile(sessionId: string): void;
28
+ export declare function getCurrentPlanFilePath(sessionId: string): string | null;
@@ -0,0 +1,173 @@
1
+ // input: Claude stream-json events, user message, sessionId
2
+ // output: formatters, extractors, buildPrompt, plan-file helpers
3
+ // pos: Claude event parsing and plan file tracking
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { readFileSync } from 'fs';
6
+ import { CancelledError, DEFAULT_PLAN_DIRS, PROJECT_SETTINGS } from './defaults.js';
7
+ import { summarizeToolInput } from './tool-summarizers.js';
8
+ import { buildPrompt as sharedBuildPrompt } from '../normalize/prompt-builder.js';
9
+ export function extractAskUserQuestions(data, sessionId) {
10
+ const questions = [];
11
+ for (const block of (data.message?.content || [])) {
12
+ if (block.type !== 'tool_use' || block.name !== 'AskUserQuestion')
13
+ continue;
14
+ questions.push({
15
+ toolUseId: block.id || null,
16
+ questions: Array.isArray(block.input?.questions) ? block.input.questions : [],
17
+ sessionId,
18
+ });
19
+ }
20
+ return questions;
21
+ }
22
+ export function formatAssistantEvent(data) {
23
+ const parts = [];
24
+ for (const block of (data.message?.content || [])) {
25
+ if (block.type === 'text') {
26
+ parts.push(`[assistant] ${block.text || ''}`);
27
+ }
28
+ else if (block.type === 'tool_use') {
29
+ parts.push(`[tool_use] ${block.name || '?'}: ${summarizeToolInput(block.name, block.input || {})}`);
30
+ }
31
+ }
32
+ return parts.length ? parts.join('\n') : null;
33
+ }
34
+ export function formatUserEvent(data) {
35
+ const parts = [];
36
+ for (const block of (data.message?.content || [])) {
37
+ if (block.type !== 'tool_result')
38
+ continue;
39
+ let inner = block.content || '';
40
+ let preview;
41
+ if (Array.isArray(inner))
42
+ preview = inner.filter((b) => b.type === 'text').map((b) => b.text || '').join(' ');
43
+ else if (typeof inner === 'string')
44
+ preview = inner;
45
+ else
46
+ preview = JSON.stringify(inner);
47
+ parts.push(`[tool_result]${block.is_error ? ' [ERROR]' : ''}: ${preview}`);
48
+ }
49
+ return parts.length ? parts.join('\n') : null;
50
+ }
51
+ export function formatResultEvent(data) {
52
+ const resultText = data.result || '';
53
+ const costStr = data.total_cost_usd != null ? `$${data.total_cost_usd.toFixed(4)}` : '?';
54
+ const durStr = data.duration_ms != null ? `${(data.duration_ms / 1000).toFixed(1)}s` : '?';
55
+ return `[result] turns=${data.num_turns}, cost=${costStr}, duration=${durStr}\n → ${resultText}`;
56
+ }
57
+ const EVENT_FORMATTERS = {
58
+ assistant: formatAssistantEvent,
59
+ user: formatUserEvent,
60
+ result: formatResultEvent,
61
+ };
62
+ export function formatEvent(data) {
63
+ const type = data.type || '';
64
+ if (type === 'system' && data.subtype === 'init') {
65
+ return `[init] model=${data.model || '?'}, session=${(data.session_id || '').substring(0, 8)}`;
66
+ }
67
+ if (type === 'system' || type === 'rate_limit_event')
68
+ return null;
69
+ const fn = EVENT_FORMATTERS[type];
70
+ return fn ? fn(data) : null;
71
+ }
72
+ export function buildPrompt(userMessage, files) {
73
+ const normalized = files.map(f => ({ mimeType: f.mimetype ?? f.mimeType, path: f.localPath ?? f.path }));
74
+ return sharedBuildPrompt(userMessage, normalized);
75
+ }
76
+ /** Merge a brief epilogue with a substantially longer earlier message (e.g. an orient briefing) so Slack gets the real content.
77
+ * Triggers only when final is both absolutely short (<300) AND relatively short (<50% of longest). */
78
+ export function mergeSubstantialOutput(finalOutput, longestOutput) {
79
+ if (!finalOutput || !longestOutput)
80
+ return finalOutput;
81
+ if (finalOutput === longestOutput)
82
+ return finalOutput;
83
+ if (finalOutput.length < 300 && finalOutput.length < longestOutput.length * 0.5) {
84
+ return longestOutput + '\n\n---\n' + finalOutput;
85
+ }
86
+ return finalOutput;
87
+ }
88
+ export function extractResult(resultData, effectiveSessionId, killed, code, stderr, planFilePath, enteredPlanMode, exitedPlanMode, askUserQuestions, finalOutput, longestOutput) {
89
+ let total_cost_usd = null, num_turns = null, rateLimited = false, rateLimitMessage = null;
90
+ // When Claude creates a new session (e.g. because --resume failed), capture the actual
91
+ // session_id so we don't keep reusing a stale one.
92
+ let resolvedSessionId = effectiveSessionId;
93
+ if (resultData) {
94
+ if (resultData.total_cost_usd != null)
95
+ total_cost_usd = resultData.total_cost_usd;
96
+ if (resultData.num_turns != null)
97
+ num_turns = resultData.num_turns;
98
+ if (resultData.is_error && typeof resultData.result === 'string' && resultData.result.includes('hit your limit')) {
99
+ rateLimited = true;
100
+ rateLimitMessage = resultData.result;
101
+ }
102
+ // Capture the actual session_id Claude used (may differ from requested on --resume failure)
103
+ if (typeof resultData.session_id === 'string' && resultData.session_id !== effectiveSessionId) {
104
+ resolvedSessionId = resultData.session_id;
105
+ }
106
+ // Non-rate-limit errors from Claude (e.g. "No conversation found with session ID"),
107
+ // reported inline via is_error on the result event. Previously these were silently
108
+ // treated as success because the process exit code was 0.
109
+ if (resultData.is_error && !rateLimited) {
110
+ const errorMsg = Array.isArray(resultData.errors) && resultData.errors.length > 0
111
+ ? resultData.errors.join('; ')
112
+ : (typeof resultData.result === 'string' && resultData.result ? resultData.result : 'Claude reported an error during execution');
113
+ return { resolved: false, error: new Error(errorMsg) };
114
+ }
115
+ }
116
+ const effectiveOutput = mergeSubstantialOutput(finalOutput, longestOutput);
117
+ const value = { sessionId: resolvedSessionId, total_cost_usd, num_turns, rateLimited, rateLimitMessage, planFilePath, enteredPlanMode, exitedPlanMode, askUserQuestions, finalOutput: effectiveOutput || null };
118
+ if (rateLimited)
119
+ return { resolved: true, value };
120
+ if (code !== 0)
121
+ return { resolved: false, error: killed ? new CancelledError() : new Error(stderr || `claude exited with code ${code}`) };
122
+ return { resolved: true, value };
123
+ }
124
+ // --- Plan file detection ---
125
+ function normalizePlanDir(value) {
126
+ if (typeof value !== 'string')
127
+ return null;
128
+ const trimmed = value.trim();
129
+ if (!trimmed)
130
+ return null;
131
+ return trimmed.replace(/^\.\//, '').replace(/\\/g, '/').replace(/\/+$/, '');
132
+ }
133
+ function resolvePlanDirectories() {
134
+ const dirs = [];
135
+ try {
136
+ const settings = JSON.parse(readFileSync(PROJECT_SETTINGS, 'utf8'));
137
+ const configured = normalizePlanDir(settings?.plansDirectory);
138
+ if (configured)
139
+ dirs.push(configured);
140
+ }
141
+ catch { }
142
+ for (const dir of DEFAULT_PLAN_DIRS) {
143
+ if (!dirs.includes(dir))
144
+ dirs.push(dir);
145
+ }
146
+ return dirs;
147
+ }
148
+ export const PLAN_DIRS = resolvePlanDirectories();
149
+ export function isPlanFilePath(filePath) {
150
+ if (typeof filePath !== 'string' || !filePath)
151
+ return false;
152
+ const normalized = filePath.replace(/\\/g, '/');
153
+ return PLAN_DIRS.some(dir => normalized.includes(`${dir}/`) || normalized.endsWith(`/${dir}`));
154
+ }
155
+ // sessionId → most recent plan file written in the active turn. Module-scoped per
156
+ // DR-0008 task e0b6 Design Decision 3: external callers mutate via setActivePlanFile /
157
+ // clearActivePlanFile and read via getCurrentPlanFilePath; the Map is never exported.
158
+ const activePlanFiles = new Map();
159
+ export function setActivePlanFile(sessionId, path) {
160
+ if (!sessionId || !path)
161
+ return;
162
+ activePlanFiles.set(sessionId, path);
163
+ }
164
+ export function clearActivePlanFile(sessionId) {
165
+ if (!sessionId)
166
+ return;
167
+ activePlanFiles.delete(sessionId);
168
+ }
169
+ export function getCurrentPlanFilePath(sessionId) {
170
+ if (!sessionId)
171
+ return null;
172
+ return activePlanFiles.get(sessionId) || null;
173
+ }
@@ -0,0 +1,36 @@
1
+ export declare function buildPreToolUseHooks(toolsList: string[]): any[];
2
+ export declare const POST_TOOL_USE_HOOKS: {
3
+ matcher: string;
4
+ hooks: Record<string, unknown>[];
5
+ }[];
6
+ export declare const PERMISSION_REQUEST_HOOKS: {
7
+ matcher: string;
8
+ hooks: {
9
+ type: string;
10
+ command: string;
11
+ timeout: number;
12
+ }[];
13
+ }[];
14
+ export declare const SESSION_START_HOOKS: {
15
+ matcher: string;
16
+ hooks: Record<string, unknown>[];
17
+ }[];
18
+ export declare function buildHooksSettings(tools: string | null): {
19
+ PreToolUse: any[];
20
+ PostToolUse: {
21
+ matcher: string;
22
+ hooks: Record<string, unknown>[];
23
+ }[];
24
+ PermissionRequest: {
25
+ matcher: string;
26
+ hooks: {
27
+ type: string;
28
+ command: string;
29
+ timeout: number;
30
+ }[];
31
+ }[];
32
+ SessionStart: {
33
+ matcher: string;
34
+ hooks: Record<string, unknown>[];
35
+ }[];
36
+ };
@@ -0,0 +1,57 @@
1
+ // input: tools string or null, constants from defaults.js
2
+ // output: buildHooksSettings + hook helpers
3
+ // pos: Generate Claude --settings hooks configuration
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import * as path from 'path';
6
+ import { DEFAULT_TOOLS, HOOKS_DIR, HOOK_TIMEOUT_S } from './defaults.js';
7
+ function nodeHook(script, timeout) {
8
+ const hook = { type: 'command', command: `node ${path.join(HOOKS_DIR, script)}` };
9
+ if (timeout != null)
10
+ hook.timeout = timeout;
11
+ return hook;
12
+ }
13
+ export function buildPreToolUseHooks(toolsList) {
14
+ const hooks = [
15
+ { matcher: 'Edit|Write', hooks: [
16
+ nodeHook('sensitive-file-edit.mjs', 10),
17
+ nodeHook('tasks-yaml-guard.mjs', 10),
18
+ ] },
19
+ ];
20
+ if (toolsList.includes('AskUserQuestion')) {
21
+ hooks.push({ matcher: 'AskUserQuestion', hooks: [nodeHook('ask-user-question-hook.mjs', HOOK_TIMEOUT_S)] });
22
+ }
23
+ if (toolsList.includes('ExitPlanMode')) {
24
+ hooks.push({ matcher: 'ExitPlanMode', hooks: [nodeHook('exit-plan-mode-hook.mjs', HOOK_TIMEOUT_S)] });
25
+ }
26
+ return hooks;
27
+ }
28
+ export const POST_TOOL_USE_HOOKS = [
29
+ { matcher: 'Read|Grep', hooks: [
30
+ nodeHook('memory-ref-tracker.mjs'),
31
+ nodeHook('rules-loader.mjs'),
32
+ ] },
33
+ { matcher: 'Read|Edit|Write|Skill', hooks: [nodeHook('session-activity-tracker.mjs')] },
34
+ { matcher: 'Read', hooks: [nodeHook('cortex-md-injector.mjs')] },
35
+ ];
36
+ export const PERMISSION_REQUEST_HOOKS = [
37
+ {
38
+ matcher: 'Edit|Write',
39
+ hooks: [{
40
+ type: 'command',
41
+ command: "printf '{\"hookSpecificOutput\":{\"hookEventName\":\"PermissionRequest\",\"decision\":{\"behavior\":\"allow\"}}}'",
42
+ timeout: 5,
43
+ }],
44
+ },
45
+ ];
46
+ export const SESSION_START_HOOKS = [
47
+ { matcher: 'startup|resume|clear|compact', hooks: [nodeHook('cortex-md-injector.mjs')] },
48
+ ];
49
+ export function buildHooksSettings(tools) {
50
+ const toolsList = (tools || DEFAULT_TOOLS).split(',').map(t => t.trim());
51
+ return {
52
+ PreToolUse: buildPreToolUseHooks(toolsList),
53
+ PostToolUse: POST_TOOL_USE_HOOKS,
54
+ PermissionRequest: PERMISSION_REQUEST_HOOKS,
55
+ SessionStart: SESSION_START_HOOKS,
56
+ };
57
+ }
@@ -0,0 +1,68 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import type { NormalizedEvent } from '../normalize/event-types.js';
3
+ /**
4
+ * Pure stateful translator. One instance per Claude session. Holds:
5
+ * - `seenMsgIds`: msg.id dedup set (one Claude API message may produce multiple jsonl entries)
6
+ * - `currentTurnUsages`: per-message usage accumulator, summed at turn boundary
7
+ * - `turnCount`: number of distinct messages so far in the current turn
8
+ *
9
+ * Reset implicitly happens when a `system/turn_duration` event is consumed.
10
+ *
11
+ * @see DR-0012 §3.4 — cost reconstructed from per-message usage; per-message dedup avoids double-counting.
12
+ */
13
+ export declare class JsonlEventNormalizer {
14
+ private seenMsgIds;
15
+ private currentTurnUsages;
16
+ private turnCount;
17
+ consume(raw: any): NormalizedEvent[];
18
+ private handleAssistant;
19
+ private handleUser;
20
+ private handleTurnDuration;
21
+ /** Reset all state (typically called when starting a fresh session, not between turns). */
22
+ reset(): void;
23
+ }
24
+ export interface JsonlTailOptions {
25
+ /** Read pre-existing content when start() is called. Default false (skip to end-of-file). */
26
+ fromStart?: boolean;
27
+ /** Max time to wait for file to appear before start() rejects, in ms. Default 5000. */
28
+ waitForFileMs?: number;
29
+ /** Poll interval for file size changes, in ms. Default 200. fs.watch is not used because it's
30
+ * unreliable on some filesystems; polling is universal and the throughput here is low. */
31
+ pollIntervalMs?: number;
32
+ }
33
+ type JsonlTailEvents = {
34
+ /** Raw parsed JSON object from one jsonl line. Emitted for EVERY line including unparseable ones (with type='_parse_error'). */
35
+ event: (raw: any) => void;
36
+ /** Emitted when a `system/turn_duration` event is observed. Convenience signal for turn boundary. */
37
+ 'turn-end': (raw: {
38
+ durationMs?: number;
39
+ messageCount?: number;
40
+ }) => void;
41
+ error: (err: Error) => void;
42
+ };
43
+ /**
44
+ * Tails a Claude session jsonl file by polling its size and reading appended bytes. Buffers across
45
+ * partial-line writes. Stops on `stop()`.
46
+ *
47
+ * @see DR-0012 §3.2 — feeds JsonlEventNormalizer in the TUI adapter.
48
+ */
49
+ export declare class JsonlTail extends EventEmitter {
50
+ private readonly filePath;
51
+ private offset;
52
+ private buffer;
53
+ private pollTimer;
54
+ private stopped;
55
+ private readonly waitForFileMs;
56
+ private readonly pollIntervalMs;
57
+ private readonly fromStart;
58
+ constructor(filePath: string, opts?: JsonlTailOptions);
59
+ on<K extends keyof JsonlTailEvents>(event: K, listener: JsonlTailEvents[K]): this;
60
+ start(): Promise<void>;
61
+ stop(): Promise<void>;
62
+ private waitForFile;
63
+ private schedulePoll;
64
+ private readNewBytes;
65
+ private drainBuffer;
66
+ private dispatchLine;
67
+ }
68
+ export {};