@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,916 @@
1
+ // input: user message + session context, ~/.codex/auth.json
2
+ // output: runCodex / CodexAdapter / shutdownCodex
3
+ // pos: Codex app-server lifecycle and AgentAdapter implementation
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { spawn } from 'child_process';
6
+ import { createWriteStream, writeFileSync, readFileSync, mkdirSync, copyFileSync, existsSync } from 'fs';
7
+ import { createInterface } from 'readline';
8
+ import * as path from 'path';
9
+ import * as crypto from 'crypto';
10
+ import * as os from 'os';
11
+ import { moduleDir, readableTimestamp, DATA_DIR, WORKSPACE_DIR, INSTALL_ROOT } from '../../core/utils.js';
12
+ import { createLogger } from '../../core/log.js';
13
+ import { summarizeRateLimits, parseRateLimitsFromRawLog } from '../../domain/costs/rate-limit-parser.js';
14
+ import { CODEX_LOG_MODE, shouldLogCodexEvent, formatCodexEvent } from '../../domain/costs/codex-event-format.js';
15
+ import { CAPABILITIES_BY_BACKEND } from '../capabilities.js';
16
+ import { createEventStream } from '../normalize/event-stream.js';
17
+ import { codexEventToNormalized } from './event-parser.js';
18
+ import { buildCodexSystemPrompt } from './spawn-args.js';
19
+ const log = createLogger('codex-adapter');
20
+ const MODULE_DIR = moduleDir(import.meta.url);
21
+ const LOGS_DIR = path.join(DATA_DIR, 'logs', 'sessions');
22
+ mkdirSync(LOGS_DIR, { recursive: true });
23
+ const MAX_TIMEOUT = 30_000_000; // ~8.3 hours
24
+ const IDLE_TIMEOUT = 10 * 60 * 1000; // 10 minutes with no output on a turn
25
+ const GLOBAL_CODEX_DIR = path.join(os.homedir(), '.codex');
26
+ const GLOBAL_CODEX_CONFIG_PATH = path.join(GLOBAL_CODEX_DIR, 'config.toml');
27
+ const GLOBAL_CODEX_AUTH_PATH = path.join(GLOBAL_CODEX_DIR, 'auth.json');
28
+ const ROUTE_RUNTIME_ROOT = path.join(WORKSPACE_DIR, 'codex-routes');
29
+ const ROUTE_IDLE_TIMEOUT_MS = Number(process.env.CODEX_ROUTE_IDLE_TIMEOUT_MS || 20 * 60 * 1000);
30
+ mkdirSync(ROUTE_RUNTIME_ROOT, { recursive: true });
31
+ class CancelledError extends Error {
32
+ cancelled;
33
+ constructor() { super('Cancelled by user'); this.cancelled = true; }
34
+ }
35
+ // --- Token → USD cost estimation via aistatus.cc ---
36
+ import { CostCalculator } from 'aistatus';
37
+ const codexCostCalculator = new CostCalculator();
38
+ function estimateCost(usage, authMode) {
39
+ // ChatGPT plan usage is included in subscription — no API cost
40
+ if (authMode === 'chatgpt')
41
+ return 0;
42
+ const model = process.env.CODEX_MODEL || 'o4-mini';
43
+ const inputTokens = Number(usage.inputTokens || usage.promptTokens || 0);
44
+ const outputTokens = Number(usage.outputTokens || usage.completionTokens || 0);
45
+ return codexCostCalculator.calculateCost('openai', model, inputTokens, outputTokens);
46
+ }
47
+ // --- Auth detection ---
48
+ /**
49
+ * Determine auth mode: default to ChatGPT plan when both are available.
50
+ * CODEX_AUTH_MODE env var can force a specific mode.
51
+ */
52
+ function detectAuthMode() {
53
+ const forced = process.env.CODEX_AUTH_MODE;
54
+ if (forced === 'apiKey' || forced === 'chatgpt')
55
+ return forced;
56
+ try {
57
+ const auth = JSON.parse(readFileSync(GLOBAL_CODEX_AUTH_PATH, 'utf8'));
58
+ if (auth.auth_mode === 'chatgpt' && auth.tokens?.access_token)
59
+ return 'chatgpt';
60
+ }
61
+ catch { }
62
+ if (process.env.OPENAI_API_KEY)
63
+ return 'apiKey';
64
+ return null; // no auth available
65
+ }
66
+ function readCodexAuth() {
67
+ try {
68
+ return JSON.parse(readFileSync(GLOBAL_CODEX_AUTH_PATH, 'utf8'));
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ }
74
+ function closeStream(stream) {
75
+ if (!stream)
76
+ return Promise.resolve();
77
+ return new Promise((resolve) => stream.end(resolve));
78
+ }
79
+ // --- Per-route runtime config ---
80
+ function stripCortexMcpSections(tomlText) {
81
+ const lines = tomlText.split('\n');
82
+ const filtered = [];
83
+ let inCortexSection = false;
84
+ for (const line of lines) {
85
+ const trimmed = line.trim();
86
+ if (trimmed === '[mcp_servers.cortex]' || trimmed === '[mcp_servers.cortex.env]'
87
+ || trimmed === '[mcp_servers.cortex-core]' || trimmed === '[mcp_servers.cortex-core.env]'
88
+ || trimmed === '[mcp_servers.cortex-ext]' || trimmed === '[mcp_servers.cortex-ext.env]') {
89
+ inCortexSection = true;
90
+ continue;
91
+ }
92
+ if (inCortexSection && trimmed.startsWith('[')) {
93
+ inCortexSection = false;
94
+ }
95
+ if (!inCortexSection)
96
+ filtered.push(line);
97
+ }
98
+ return filtered.join('\n').trimEnd();
99
+ }
100
+ function writeRouteContext(routeContextPath, { channel, callbackSource, sessionId, context }) {
101
+ writeFileSync(routeContextPath, JSON.stringify({
102
+ channel,
103
+ callbackSource: callbackSource || null,
104
+ sessionId: sessionId || null,
105
+ threadId: context?.threadId || null,
106
+ profile: context?.profile || null,
107
+ project: context?.project || null,
108
+ sessionName: context?.sessionName || null,
109
+ updatedAt: new Date().toISOString(),
110
+ }));
111
+ }
112
+ function ensureCodexConfig({ runtimeHome, channel, callbackSource = null, sessionId = null, routeContextPath, context }) {
113
+ const runtimeCodexDir = path.join(runtimeHome, '.codex');
114
+ mkdirSync(runtimeCodexDir, { recursive: true });
115
+ try {
116
+ const runtimeAuthPath = path.join(runtimeCodexDir, 'auth.json');
117
+ if (!existsSync(runtimeAuthPath) && existsSync(GLOBAL_CODEX_AUTH_PATH))
118
+ copyFileSync(GLOBAL_CODEX_AUTH_PATH, runtimeAuthPath);
119
+ }
120
+ catch { }
121
+ let base = '';
122
+ try {
123
+ base = stripCortexMcpSections(readFileSync(GLOBAL_CODEX_CONFIG_PATH, 'utf8'));
124
+ }
125
+ catch { }
126
+ writeRouteContext(routeContextPath, { channel, callbackSource, sessionId, context });
127
+ writeFileSync(path.join(runtimeCodexDir, 'config.toml'), base + '\n' + buildMcpBlock(channel, sessionId, callbackSource, routeContextPath, context));
128
+ }
129
+ function buildMcpBlock(channel, sessionId, callbackSource, routeContextPath, context) {
130
+ // Point at compiled .js MCP servers so the installed package (which only ships dist/+defaults/)
131
+ // can locate them. The tsx loader is no longer needed for plain JS.
132
+ const coreServerPath = path.join(INSTALL_ROOT, 'dist', 'domain', 'mcp', 'core-server.js');
133
+ const extServerPath = path.join(INSTALL_ROOT, 'dist', 'domain', 'mcp', 'server.js');
134
+ const escapedPath = (p) => p.replace(/\\/g, '/');
135
+ const baseEnv = { CORTEX_SESSION_ID: sessionId || '', CORTEX_BACKEND: 'codex', CORTEX_ROUTE_CONTEXT_FILE: routeContextPath };
136
+ if (callbackSource)
137
+ baseEnv.CORTEX_CALLBACK_SOURCE = callbackSource;
138
+ if (context?.threadId)
139
+ baseEnv.CORTEX_THREAD_ID = context.threadId;
140
+ if (context?.profile)
141
+ baseEnv.CORTEX_PROFILE = context.profile;
142
+ if (context?.project)
143
+ baseEnv.CORTEX_PROJECT = context.project;
144
+ if (context?.sessionName)
145
+ baseEnv.CORTEX_SESSION_NAME = context.sessionName;
146
+ if (context?.executionId)
147
+ baseEnv.CORTEX_EXECUTION_ID = context.executionId;
148
+ const formatEnv = (extra) => Object.entries({ ...baseEnv, ...extra })
149
+ .map(([k, v]) => `${k} = "${String(v).replace(/"/g, '\\"')}"`)
150
+ .join('\n');
151
+ const coreSection = `\n[mcp_servers.cortex-core]\ncommand = "node"\nargs = ["${escapedPath(coreServerPath)}", "--route-context-file", "${escapedPath(routeContextPath)}"]\n\n[mcp_servers.cortex-core.env]\n${formatEnv({})}\n`;
152
+ // Thread sessions: core server only (remote_* tools)
153
+ if (context?.threadId)
154
+ return coreSection;
155
+ // Direct sessions: core + ext (everything else)
156
+ const extSection = `\n[mcp_servers.cortex-ext]\ncommand = "node"\nargs = ["${escapedPath(extServerPath)}", "--route-context-file", "${escapedPath(routeContextPath)}"]\n\n[mcp_servers.cortex-ext.env]\n${formatEnv({ SLACK_BOT_TOKEN: process.env.SLACK_BOT_TOKEN || '', SLACK_CHANNEL: channel || '' })}\n`;
157
+ return coreSection + extSection;
158
+ }
159
+ // ============================================================
160
+ // CodexAppServer — manages a long-lived codex app-server process
161
+ // ============================================================
162
+ class CodexAppServer {
163
+ routeKey;
164
+ channel;
165
+ callbackSource;
166
+ runtimeHome;
167
+ routeContextPath;
168
+ proc;
169
+ rl;
170
+ requestId;
171
+ pendingRequests;
172
+ eventListeners;
173
+ _stderr;
174
+ _authMode;
175
+ /** Most recent CortexAgentContext snapshot (refreshed via updateContext per turn).
176
+ * Persisted to route-context.json on each refresh so the MCP server can read live values. */
177
+ _context;
178
+ constructor({ routeKey, channel, callbackSource = null }) {
179
+ this.routeKey = routeKey;
180
+ this.channel = channel;
181
+ this.callbackSource = callbackSource;
182
+ const routeHash = crypto.createHash('sha1').update(routeKey).digest('hex').slice(0, 12);
183
+ this.runtimeHome = path.join(ROUTE_RUNTIME_ROOT, routeHash);
184
+ this.routeContextPath = path.join(this.runtimeHome, '.codex', 'route-context.json');
185
+ this.proc = null;
186
+ this.rl = null;
187
+ this.requestId = 0;
188
+ this.pendingRequests = new Map();
189
+ this.eventListeners = new Map();
190
+ this._stderr = '';
191
+ this._authMode = null;
192
+ this._context = undefined;
193
+ }
194
+ // --- Process lifecycle ---
195
+ /** Refresh the CortexAgentContext snapshot used for subsequent route-context.json writes.
196
+ * Caller invokes this per turn, before send(), so the MCP server's cortex_context tool
197
+ * sees the live thread/profile/project/session-name for the current turn. */
198
+ updateContext(context) {
199
+ this._context = context;
200
+ }
201
+ updateRouteContext(sessionId) {
202
+ writeRouteContext(this.routeContextPath, {
203
+ channel: this.channel,
204
+ callbackSource: this.callbackSource,
205
+ sessionId,
206
+ context: this._context,
207
+ });
208
+ }
209
+ async start(sessionId) {
210
+ if (this.isRunning())
211
+ return;
212
+ ensureCodexConfig({ runtimeHome: this.runtimeHome, channel: this.channel, callbackSource: this.callbackSource, sessionId, routeContextPath: this.routeContextPath, context: this._context });
213
+ const authMode = detectAuthMode();
214
+ if (!authMode)
215
+ throw new Error('No Codex auth available — set OPENAI_API_KEY or run `codex login`');
216
+ this._authMode = authMode;
217
+ this._spawnProcess();
218
+ await this._initialize();
219
+ await this._login();
220
+ log.info(`[codex-server:${this.routeKey}] Ready (auth=${authMode})`);
221
+ }
222
+ _spawnProcess() {
223
+ const env = { ...process.env, HOME: this.runtimeHome, CORTEX_BACKEND: 'codex', CORTEX_ROUTE_CONTEXT_FILE: this.routeContextPath };
224
+ this.proc = spawn('codex', ['app-server', '-c', 'history.persistence="none"'], { cwd: DATA_DIR, env, stdio: ['pipe', 'pipe', 'pipe'] });
225
+ this._stderr = '';
226
+ this.proc.stderr.on('data', (d) => {
227
+ this._stderr = (this._stderr + d.toString()).slice(-2000);
228
+ log.info(`[codex-server:${this.routeKey}] stderr:`, d.toString().trim());
229
+ });
230
+ this.proc.on('close', (code) => {
231
+ this.proc = null;
232
+ for (const [, req] of this.pendingRequests) {
233
+ clearTimeout(req.timer);
234
+ req.reject(new Error(`Codex process exited (code ${code})`));
235
+ }
236
+ this.pendingRequests.clear();
237
+ this.eventListeners.clear();
238
+ });
239
+ this.rl = createInterface({ input: this.proc.stdout, crlfDelay: Infinity });
240
+ this.rl.on('line', (line) => this._onLine(line));
241
+ }
242
+ stop() {
243
+ if (this.proc && this.proc.exitCode === null) {
244
+ this.proc.kill('SIGTERM');
245
+ }
246
+ this.proc = null;
247
+ }
248
+ isRunning() {
249
+ return this.proc != null && this.proc.exitCode === null;
250
+ }
251
+ // --- JSON-RPC transport ---
252
+ _write(obj) {
253
+ if (!this.isRunning())
254
+ throw new Error('Codex app-server not running');
255
+ this.proc.stdin.write(JSON.stringify(obj) + '\n');
256
+ }
257
+ _sendRequest(method, params = {}, timeout = 120_000) {
258
+ const id = ++this.requestId;
259
+ return new Promise((resolve, reject) => {
260
+ const timer = setTimeout(() => {
261
+ this.pendingRequests.delete(id);
262
+ reject(new Error(`Timeout waiting for response: ${method} (id=${id})`));
263
+ }, timeout);
264
+ this.pendingRequests.set(id, { resolve, reject, timer });
265
+ this._write({ method, id, params });
266
+ });
267
+ }
268
+ _sendNotification(method, params = {}) {
269
+ this._write({ method, params });
270
+ }
271
+ _sendResponse(id, result) {
272
+ this._write({ id, result });
273
+ }
274
+ _sendErrorResponse(id, code, message) {
275
+ this._write({ id, error: { code, message } });
276
+ }
277
+ _resolvePendingResponse(msg) {
278
+ const pending = this.pendingRequests.get(msg.id);
279
+ if (!pending)
280
+ return;
281
+ clearTimeout(pending.timer);
282
+ this.pendingRequests.delete(msg.id);
283
+ if (msg.error)
284
+ pending.reject(new Error(`${msg.error.message} (code ${msg.error.code})`));
285
+ else
286
+ pending.resolve(msg.result);
287
+ }
288
+ _onLine(line) {
289
+ if (!line.trim())
290
+ return;
291
+ let msg;
292
+ try {
293
+ msg = JSON.parse(line);
294
+ }
295
+ catch {
296
+ log.info(`[codex-server:${this.routeKey}] Non-JSON line:`, line.substring(0, 200));
297
+ return;
298
+ }
299
+ if (msg.id != null && (msg.result !== undefined || msg.error)) {
300
+ this._resolvePendingResponse(msg);
301
+ return;
302
+ }
303
+ if (msg.id != null && msg.method) {
304
+ this._handleServerRequest(msg);
305
+ return;
306
+ }
307
+ if (msg.method && msg.id == null) {
308
+ this._dispatchEvent(msg.method, msg.params || {});
309
+ }
310
+ }
311
+ _handleServerRequest(msg) {
312
+ const { method, id, params } = msg;
313
+ // Auto-approve all operations (equivalent to --full-auto)
314
+ if (method === 'item/commandExecution/requestApproval' ||
315
+ method === 'item/fileChange/requestApproval') {
316
+ log.info(`[codex-server:${this.routeKey}] Auto-approving: ${method} (id=${id})`);
317
+ this._sendResponse(id, 'accept');
318
+ return;
319
+ }
320
+ // Token refresh — use refresh_token to get new access token
321
+ if (method === 'account/chatgptAuthTokens/refresh') {
322
+ log.info(`[codex-server:${this.routeKey}] Token refresh requested, reason:`, params?.reason);
323
+ this._refreshChatgptTokens(id).catch(err => {
324
+ log.error(`[codex-server:${this.routeKey}] Token refresh failed:`, err.message);
325
+ this._sendErrorResponse(id, -32601, `Token refresh failed: ${err.message}`);
326
+ });
327
+ return;
328
+ }
329
+ // tool/requestUserInput — provide empty responses
330
+ if (method === 'tool/requestUserInput') {
331
+ log.info(`[codex-server:${this.routeKey}] Auto-responding to user input request`);
332
+ this._sendResponse(id, { answers: [] });
333
+ return;
334
+ }
335
+ log.info(`[codex-server:${this.routeKey}] Unhandled server request: ${method} (id=${id})`);
336
+ this._sendErrorResponse(id, -32601, `Not handled: ${method}`);
337
+ }
338
+ _dispatchEvent(method, params) {
339
+ for (const [, listener] of this.eventListeners) {
340
+ try {
341
+ listener(method, params);
342
+ }
343
+ catch (e) {
344
+ log.error(`[codex-server:${this.routeKey}] Event listener error:`, e.message);
345
+ }
346
+ }
347
+ }
348
+ // --- Token refresh ---
349
+ async _fetchRefreshedTokens(refreshToken) {
350
+ const resp = await fetch('https://auth.openai.com/oauth/token', {
351
+ method: 'POST',
352
+ headers: { 'Content-Type': 'application/json' },
353
+ body: JSON.stringify({
354
+ grant_type: 'refresh_token',
355
+ refresh_token: refreshToken,
356
+ client_id: 'app_EMoamEEZ73f0CkXaXp7hrann',
357
+ }),
358
+ });
359
+ if (!resp.ok) {
360
+ const body = await resp.text();
361
+ throw new Error(`OAuth refresh failed (${resp.status}): ${body.substring(0, 200)}`);
362
+ }
363
+ return resp.json();
364
+ }
365
+ async _refreshChatgptTokens(requestId) {
366
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- auth.json is deeply nested untyped JSON
367
+ const auth = readCodexAuth();
368
+ if (!auth?.tokens?.refresh_token)
369
+ throw new Error('No refresh_token in auth.json');
370
+ const data = await this._fetchRefreshedTokens(auth.tokens.refresh_token);
371
+ log.info('Token refreshed successfully');
372
+ auth.tokens.access_token = data.access_token;
373
+ if (data.id_token)
374
+ auth.tokens.id_token = data.id_token;
375
+ if (data.refresh_token)
376
+ auth.tokens.refresh_token = data.refresh_token;
377
+ auth.last_refresh = new Date().toISOString();
378
+ writeFileSync(GLOBAL_CODEX_AUTH_PATH, JSON.stringify(auth, null, 2));
379
+ this._sendResponse(requestId, {
380
+ accessToken: data.access_token,
381
+ chatgptAccountId: auth.tokens.account_id,
382
+ chatgptPlanType: null,
383
+ });
384
+ }
385
+ // --- Protocol methods ---
386
+ async _initialize() {
387
+ const result = await this._sendRequest('initialize', {
388
+ clientInfo: { name: 'cortex', title: 'Cortex Agent', version: '1.0.0' },
389
+ capabilities: { experimentalApi: true },
390
+ }, 30_000);
391
+ this._sendNotification('initialized', {});
392
+ log.info(`[codex-server:${this.routeKey}] Initialized:`, result?.userAgent || 'unknown');
393
+ return result;
394
+ }
395
+ async _login() {
396
+ if (this._authMode === 'apiKey') {
397
+ const apiKey = process.env.OPENAI_API_KEY;
398
+ if (!apiKey)
399
+ throw new Error('OPENAI_API_KEY not set');
400
+ await this._sendRequest('account/login/start', {
401
+ type: 'apiKey',
402
+ apiKey,
403
+ }, 30_000);
404
+ log.info(`[codex-server:${this.routeKey}] Logged in with API key`);
405
+ }
406
+ else {
407
+ // ChatGPT plan — pass cached tokens from ~/.codex/auth.json
408
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- auth.json is deeply nested untyped JSON
409
+ const auth = readCodexAuth();
410
+ if (!auth?.tokens?.access_token || !auth?.tokens?.account_id) {
411
+ throw new Error('No ChatGPT tokens in ~/.codex/auth.json — run `codex login`');
412
+ }
413
+ await this._sendRequest('account/login/start', {
414
+ type: 'chatgptAuthTokens',
415
+ accessToken: auth.tokens.access_token,
416
+ chatgptAccountId: auth.tokens.account_id,
417
+ }, 30_000);
418
+ log.info(`[codex-server:${this.routeKey}] Logged in with ChatGPT plan`);
419
+ }
420
+ }
421
+ async startThread(cwd) {
422
+ const params = {
423
+ cwd,
424
+ approvalPolicy: 'never',
425
+ sandbox: 'danger-full-access',
426
+ };
427
+ // Only override model if explicitly set; otherwise use ~/.codex/config.toml
428
+ if (process.env.CODEX_MODEL)
429
+ params.model = process.env.CODEX_MODEL;
430
+ const result = await this._sendRequest('thread/start', params, 30_000);
431
+ log.info(`[codex-server:${this.routeKey}] Thread started:`, result?.thread?.id);
432
+ return result.thread;
433
+ }
434
+ async resumeThread(threadId) {
435
+ const params = { threadId };
436
+ if (process.env.CODEX_MODEL)
437
+ params.model = process.env.CODEX_MODEL;
438
+ const result = await this._sendRequest('thread/resume', params, 30_000);
439
+ log.info(`[codex-server:${this.routeKey}] Thread resumed:`, threadId);
440
+ return (result.thread || result);
441
+ }
442
+ /**
443
+ * Send a turn and wait for completion.
444
+ * Returns { turn, tokenUsage, itemCount }.
445
+ */
446
+ sendTurn(threadId, input, { cwd, onEvent, timeout = MAX_TIMEOUT } = {}) {
447
+ return new Promise((resolve, reject) => {
448
+ let tokenUsage = null;
449
+ let itemCount = 0;
450
+ let settled = false;
451
+ const listenerKey = `turn-${Date.now()}-${Math.random()}`;
452
+ const idleTimer = { ref: null };
453
+ const maxTimer = setTimeout(() => {
454
+ cleanup();
455
+ reject(new Error('Turn max timeout'));
456
+ }, timeout);
457
+ function resetIdle() {
458
+ if (idleTimer.ref)
459
+ clearTimeout(idleTimer.ref);
460
+ idleTimer.ref = setTimeout(() => {
461
+ cleanup();
462
+ reject(new Error(`Turn idle timeout (${IDLE_TIMEOUT / 1000}s no events)`));
463
+ }, IDLE_TIMEOUT);
464
+ }
465
+ const cleanup = () => {
466
+ if (settled)
467
+ return;
468
+ settled = true;
469
+ clearTimeout(maxTimer);
470
+ if (idleTimer.ref)
471
+ clearTimeout(idleTimer.ref);
472
+ this.eventListeners.delete(listenerKey);
473
+ };
474
+ resetIdle();
475
+ this.eventListeners.set(listenerKey, (method, params) => {
476
+ if (settled)
477
+ return;
478
+ resetIdle();
479
+ if (onEvent)
480
+ onEvent(method, params);
481
+ if (method === 'thread/tokenUsage/updated') {
482
+ tokenUsage = params.tokenUsage?.total;
483
+ }
484
+ if (method === 'item/completed') {
485
+ itemCount++;
486
+ }
487
+ if (method === 'turn/completed') {
488
+ cleanup();
489
+ resolve({ turn: params.turn, tokenUsage, itemCount });
490
+ }
491
+ });
492
+ // Fire turn/start
493
+ this._sendRequest('turn/start', {
494
+ threadId,
495
+ input,
496
+ cwd: cwd || DATA_DIR,
497
+ approvalPolicy: 'never',
498
+ sandboxPolicy: { type: 'dangerFullAccess' },
499
+ }, 60_000).catch((err) => {
500
+ cleanup();
501
+ reject(err);
502
+ });
503
+ });
504
+ }
505
+ async interruptTurn(threadId, turnId) {
506
+ const params = { threadId };
507
+ if (typeof turnId === 'string' && turnId.length > 0) {
508
+ params.turnId = turnId;
509
+ }
510
+ try {
511
+ await this._sendRequest('turn/interrupt', params, 10_000);
512
+ return true;
513
+ }
514
+ catch (e) {
515
+ log.info(`[codex-server:${this.routeKey}] Interrupt failed:`, e.message);
516
+ return false;
517
+ }
518
+ }
519
+ }
520
+ // ============================================================
521
+ // Route runtime pool (parallel across routes, serialized per route)
522
+ // ============================================================
523
+ class RouteRuntime {
524
+ routeKey;
525
+ channel;
526
+ callbackSource;
527
+ server;
528
+ queueTail;
529
+ activeTurns;
530
+ idleTimer;
531
+ constructor({ routeKey, channel, callbackSource = null }) {
532
+ this.routeKey = routeKey;
533
+ this.channel = channel;
534
+ this.callbackSource = callbackSource;
535
+ this.server = new CodexAppServer({ routeKey, channel, callbackSource });
536
+ this.queueTail = Promise.resolve();
537
+ this.activeTurns = 0;
538
+ this.idleTimer = null;
539
+ }
540
+ enqueue(taskFn) {
541
+ this._clearIdleTimer();
542
+ const run = async () => {
543
+ this.activeTurns++;
544
+ try {
545
+ return await taskFn(this.server);
546
+ }
547
+ finally {
548
+ this.activeTurns--;
549
+ this._armIdleTimer();
550
+ }
551
+ };
552
+ const p = this.queueTail.then(run, run);
553
+ this.queueTail = p.catch(() => { });
554
+ return p;
555
+ }
556
+ stop() {
557
+ this._clearIdleTimer();
558
+ this.server.stop();
559
+ }
560
+ _clearIdleTimer() {
561
+ if (this.idleTimer) {
562
+ clearTimeout(this.idleTimer);
563
+ this.idleTimer = null;
564
+ }
565
+ }
566
+ _armIdleTimer() {
567
+ this._clearIdleTimer();
568
+ if (!(ROUTE_IDLE_TIMEOUT_MS > 0) || this.activeTurns > 0)
569
+ return;
570
+ this.idleTimer = setTimeout(() => {
571
+ if (this.activeTurns > 0)
572
+ return;
573
+ const current = routeRuntimePool.get(this.routeKey);
574
+ if (current !== this)
575
+ return;
576
+ log.info(`[codex-route] Idle timeout (${Math.round(ROUTE_IDLE_TIMEOUT_MS / 1000)}s): ${this.routeKey}`);
577
+ this.stop();
578
+ routeRuntimePool.delete(this.routeKey);
579
+ }, ROUTE_IDLE_TIMEOUT_MS);
580
+ }
581
+ }
582
+ const routeRuntimePool = new Map();
583
+ function buildRouteKey(channel, callbackSource) {
584
+ return `${channel || ''}|${callbackSource || ''}`;
585
+ }
586
+ function getRouteRuntime(channel, callbackSource) {
587
+ const routeKey = buildRouteKey(channel, callbackSource);
588
+ let runtime = routeRuntimePool.get(routeKey);
589
+ if (!runtime) {
590
+ runtime = new RouteRuntime({ routeKey, channel, callbackSource });
591
+ routeRuntimePool.set(routeKey, runtime);
592
+ log.info(`[codex-route] Created runtime: ${routeKey}`);
593
+ }
594
+ return runtime;
595
+ }
596
+ function shutdownCodex() {
597
+ for (const runtime of routeRuntimePool.values()) {
598
+ runtime.stop();
599
+ }
600
+ routeRuntimePool.clear();
601
+ }
602
+ // ============================================================
603
+ // runCodex() — drop-in replacement for runClaude()
604
+ // ============================================================
605
+ const IMAGE_MIMES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);
606
+ function buildTurnInput(userMessage, files, systemPrompt) {
607
+ const input = [];
608
+ if (systemPrompt) {
609
+ input.push({ type: 'text', text: systemPrompt });
610
+ }
611
+ if (files.length > 0) {
612
+ const imageFiles = files.filter((f) => IMAGE_MIMES.has(f.mimetype));
613
+ const otherFiles = files.filter((f) => !IMAGE_MIMES.has(f.mimetype));
614
+ for (const f of imageFiles) {
615
+ input.push({ type: 'localImage', path: f.localPath.replace(/\\/g, '/') });
616
+ }
617
+ if (otherFiles.length > 0) {
618
+ const fileList = otherFiles.map((f) => `${f.localPath.replace(/\\/g, '/')} (${f.name})`).join('\n');
619
+ input.push({ type: 'text', text: `[User sent ${otherFiles.length} file(s). Read these files:\n${fileList}\n]` });
620
+ }
621
+ }
622
+ input.push({ type: 'text', text: userMessage || 'Please analyze the attached file(s).' });
623
+ return input;
624
+ }
625
+ function openCodexLogs(channel, threadId) {
626
+ const ts = readableTimestamp();
627
+ const rawLogPath = path.join(LOGS_DIR, `codex-output-${ts}.jsonl`);
628
+ const txtLogPath = path.join(LOGS_DIR, `codex-output-${ts}.txt`);
629
+ const writeDetailedLogs = CODEX_LOG_MODE !== 'off';
630
+ const rawStream = writeDetailedLogs ? createWriteStream(rawLogPath, { flags: 'a' }) : null;
631
+ const txtStream = writeDetailedLogs ? createWriteStream(txtLogPath, { flags: 'a' }) : null;
632
+ if (txtStream) {
633
+ txtStream.write(`=== Codex turn started at ${new Date().toISOString()} ===\n`);
634
+ txtStream.write(`=== channel=${channel}, thread=${threadId}, log_mode=${CODEX_LOG_MODE} ===\n\n`);
635
+ }
636
+ return { rawLogPath, rawStream, txtStream, writeDetailedLogs };
637
+ }
638
+ /** If the last assistant message is a brief epilogue but there was a much longer earlier
639
+ * message, merge them so Slack gets the real content.
640
+ * Triggers only when final is both absolutely short (<300) AND relatively short (<50% of longest). */
641
+ function mergeSubstantialOutput(finalOutput, longestOutput) {
642
+ if (!finalOutput || !longestOutput)
643
+ return finalOutput;
644
+ if (finalOutput === longestOutput)
645
+ return finalOutput;
646
+ if (finalOutput.length < 300 && finalOutput.length < longestOutput.length * 0.5) {
647
+ return longestOutput + '\n\n---\n' + finalOutput;
648
+ }
649
+ return finalOutput;
650
+ }
651
+ function buildCodexResult({ threadId, turn, tokenUsage, itemCount, authMode, rawLogPath, writeDetailedLogs, liveRateLimitsById, finalOutput, longestOutput }) {
652
+ const total_cost_usd = tokenUsage ? estimateCost(tokenUsage, authMode) : null;
653
+ const rateLimited = turn.status === 'failed' &&
654
+ (turn.error?.codexErrorInfo === 'UsageLimitExceeded' ||
655
+ turn.error?.message?.toLowerCase().includes('rate limit'));
656
+ const parsedRateLimits = writeDetailedLogs ? parseRateLimitsFromRawLog(rawLogPath) : summarizeRateLimits([], 'log');
657
+ const eventRateLimits = summarizeRateLimits(Array.from(liveRateLimitsById.values()), 'event');
658
+ const codexRateLimits = parsedRateLimits.limits.length > 0 ? parsedRateLimits : eventRateLimits;
659
+ return {
660
+ sessionId: threadId, total_cost_usd, num_turns: itemCount || 1,
661
+ rateLimited, rateLimitMessage: rateLimited ? turn.error?.message : null,
662
+ codexRateLimits, codexRawLogPath: writeDetailedLogs ? rawLogPath : null,
663
+ finalOutput: mergeSubstantialOutput(finalOutput, longestOutput) || null,
664
+ planFilePath: null, enteredPlanMode: false, exitedPlanMode: false,
665
+ };
666
+ }
667
+ async function resolveThread(server, sessionId) {
668
+ if (sessionId) {
669
+ try {
670
+ return await server.resumeThread(sessionId);
671
+ }
672
+ catch (e) {
673
+ log.info('Resume failed, starting new:', e.message);
674
+ return await server.startThread(DATA_DIR);
675
+ }
676
+ }
677
+ return await server.startThread(DATA_DIR);
678
+ }
679
+ function runCodexInternal(userMessage, opts) {
680
+ const { channel, sessionId, files = [], callbackSource = null, cortexMdPrompt, context, _onNormalizedEvent, _onThreadIdResolved } = opts;
681
+ let killed = false;
682
+ let currentThreadId = null;
683
+ let currentTurnId = null;
684
+ const runtime = getRouteRuntime(channel, callbackSource);
685
+ const promise = runtime.enqueue(async (server) => {
686
+ if (killed)
687
+ throw new CancelledError();
688
+ server.updateContext(context);
689
+ await server.start(sessionId || crypto.randomUUID());
690
+ if (killed)
691
+ throw new CancelledError();
692
+ const thread = await resolveThread(server, sessionId);
693
+ currentThreadId = thread.id;
694
+ server.updateRouteContext(currentThreadId);
695
+ log.info('Thread:', currentThreadId, sessionId ? '(resumed)' : '(new)');
696
+ if (_onThreadIdResolved) {
697
+ try {
698
+ _onThreadIdResolved(currentThreadId);
699
+ }
700
+ catch (e) {
701
+ log.error('_onThreadIdResolved error:', e.message);
702
+ }
703
+ }
704
+ const input = buildTurnInput(userMessage, files, cortexMdPrompt);
705
+ const { rawLogPath, rawStream, txtStream, writeDetailedLogs } = openCodexLogs(channel, currentThreadId);
706
+ const liveRateLimitsById = new Map();
707
+ let finalOutput = null;
708
+ let longestOutput = null;
709
+ try {
710
+ let progressTurnCount = 0;
711
+ const { turn, tokenUsage, itemCount } = await server.sendTurn(currentThreadId, input, {
712
+ cwd: DATA_DIR,
713
+ onEvent: (method, params) => {
714
+ if (method === 'turn/started')
715
+ currentTurnId = params?.turn?.id || currentTurnId;
716
+ else if (method === 'turn/completed')
717
+ currentTurnId = null;
718
+ else if (method === 'account/rateLimits/updated' && params?.rateLimits?.limitId)
719
+ liveRateLimitsById.set(params.rateLimits.limitId, params.rateLimits);
720
+ else if (method === 'item/completed' && params?.item?.type === 'agentMessage') {
721
+ const text = String(params.item.text || '').trim();
722
+ if (text) {
723
+ finalOutput = text;
724
+ if (text.length > (longestOutput?.length || 0))
725
+ longestOutput = text;
726
+ }
727
+ progressTurnCount++;
728
+ if (_onNormalizedEvent) {
729
+ try {
730
+ _onNormalizedEvent({ type: 'turn_progress', numTurns: progressTurnCount });
731
+ }
732
+ catch (e) {
733
+ log.error('_onNormalizedEvent error:', e.message);
734
+ }
735
+ }
736
+ }
737
+ if (rawStream && (shouldLogCodexEvent(method) || method === 'account/rateLimits/updated'))
738
+ rawStream.write(JSON.stringify({ method, params, timestamp: new Date().toISOString() }) + '\n');
739
+ const formatted = formatCodexEvent(method, params);
740
+ if (formatted && txtStream) {
741
+ txtStream.write(formatted + '\n');
742
+ log.info(formatted.substring(0, 200));
743
+ }
744
+ if (_onNormalizedEvent) {
745
+ const normalized = codexEventToNormalized(method, params);
746
+ if (normalized) {
747
+ try {
748
+ _onNormalizedEvent(normalized);
749
+ }
750
+ catch (e) {
751
+ log.error('_onNormalizedEvent error:', e.message);
752
+ }
753
+ }
754
+ }
755
+ },
756
+ });
757
+ if (txtStream)
758
+ txtStream.write(`\n=== Turn completed at ${new Date().toISOString()} ===\n`);
759
+ await Promise.all([closeStream(rawStream), closeStream(txtStream)]);
760
+ if (writeDetailedLogs)
761
+ log.info(`Logs saved (${CODEX_LOG_MODE}):`, rawLogPath);
762
+ currentTurnId = null;
763
+ const result = buildCodexResult({ threadId: currentThreadId, turn, tokenUsage, itemCount, authMode: server._authMode || 'apiKey', rawLogPath, writeDetailedLogs, liveRateLimitsById, finalOutput, longestOutput });
764
+ // Emit cost_record from Codex token usage (available in this scope)
765
+ if (_onNormalizedEvent && result.total_cost_usd != null) {
766
+ const model = process.env.CODEX_MODEL || 'o4-mini';
767
+ _onNormalizedEvent({
768
+ type: 'cost_record',
769
+ provider: 'openai',
770
+ model,
771
+ tokens_in: Number(tokenUsage?.inputTokens || tokenUsage?.promptTokens || 0),
772
+ tokens_out: Number(tokenUsage?.outputTokens || tokenUsage?.completionTokens || 0),
773
+ cost_usd: result.total_cost_usd,
774
+ });
775
+ }
776
+ return result;
777
+ }
778
+ catch (err) {
779
+ if (txtStream) {
780
+ txtStream.write(`\n[ERROR] ${err.message}\n`);
781
+ txtStream.write(`=== Turn failed at ${new Date().toISOString()} ===\n`);
782
+ }
783
+ await Promise.all([closeStream(rawStream), closeStream(txtStream)]);
784
+ currentTurnId = null;
785
+ throw err;
786
+ }
787
+ }).catch((err) => { if (killed)
788
+ throw new CancelledError(); throw err; });
789
+ return {
790
+ promise,
791
+ kill() {
792
+ if (killed)
793
+ return false;
794
+ killed = true;
795
+ if (currentThreadId && runtime.server.isRunning()) {
796
+ runtime.server.interruptTurn(currentThreadId, currentTurnId).then((ok) => {
797
+ if (!ok && runtime.server.isRunning()) {
798
+ runtime.stop();
799
+ routeRuntimePool.delete(runtime.routeKey);
800
+ }
801
+ }).catch(() => { runtime.stop(); routeRuntimePool.delete(runtime.routeKey); });
802
+ }
803
+ return true;
804
+ },
805
+ };
806
+ }
807
+ function runCodex(userMessage, { channel, sessionId, files = [], callbackSource = null, context }) {
808
+ return runCodexInternal(userMessage, { channel, sessionId, files, callbackSource, context });
809
+ }
810
+ // ============================================================
811
+ // CodexAdapter — DR-0008 §3.2 AgentAdapter implementation
812
+ // ============================================================
813
+ class CodexAdapterSession {
814
+ sessionKey;
815
+ sessionId;
816
+ events;
817
+ _channel;
818
+ _callbackSource;
819
+ _context;
820
+ _cortexMdPrompt;
821
+ _push;
822
+ _closeStream;
823
+ _onClosed;
824
+ _activeHandle = null;
825
+ _closed = false;
826
+ constructor(config, onClosed) {
827
+ this.sessionKey = config.sessionKey;
828
+ this.sessionId = config.sessionId;
829
+ // task f7cf: typed config.channel / callbackSource preferred; env fallbacks kept for backward
830
+ // compat with callers that still pass these through env.
831
+ this._channel = config.channel ?? config.env?.CORTEX_CHANNEL ?? config.sessionKey;
832
+ this._callbackSource = config.callbackSource ?? config.env?.CORTEX_CALLBACK_SOURCE ?? null;
833
+ this._context = config.cortexContext;
834
+ this._cortexMdPrompt = buildCodexSystemPrompt(config.cwd || DATA_DIR);
835
+ this._onClosed = onClosed;
836
+ const stream = createEventStream();
837
+ this.events = stream.iterable;
838
+ this._push = stream.push;
839
+ this._closeStream = stream.close;
840
+ }
841
+ send(message) {
842
+ if (this._closed)
843
+ return Promise.reject(new Error('CodexAdapterSession: send after close'));
844
+ const files = (message.attachments || []).map((a) => ({
845
+ mimetype: a.mimeType,
846
+ localPath: a.path,
847
+ name: path.basename(a.path),
848
+ }));
849
+ const handle = runCodexInternal(message.text, {
850
+ channel: this._channel,
851
+ sessionId: this.sessionId,
852
+ files,
853
+ callbackSource: this._callbackSource,
854
+ cortexMdPrompt: this._cortexMdPrompt,
855
+ context: this._context,
856
+ _onNormalizedEvent: (e) => this._push(e),
857
+ _onThreadIdResolved: (id) => {
858
+ if (this.sessionId !== id) {
859
+ this.sessionId = id;
860
+ this._push({ type: 'session_started', sessionId: id });
861
+ }
862
+ },
863
+ });
864
+ this._activeHandle = handle;
865
+ return handle.promise.then((result) => {
866
+ if (result.sessionId)
867
+ this.sessionId = result.sessionId;
868
+ this._push({
869
+ type: 'turn_complete',
870
+ numTurns: result.num_turns ?? 0,
871
+ totalCostUsd: result.total_cost_usd,
872
+ });
873
+ return result;
874
+ }, (err) => {
875
+ if (!err.cancelled) {
876
+ // kill() path: do not surface as event; event loop terminates via stream.close() from caller.
877
+ this._push({ type: 'error', message: String(err.message || err), fatal: true });
878
+ }
879
+ throw err;
880
+ });
881
+ }
882
+ async close() {
883
+ if (this._closed)
884
+ return;
885
+ this._closed = true;
886
+ this._closeStream();
887
+ this._onClosed();
888
+ }
889
+ kill() {
890
+ return this._activeHandle?.kill() ?? false;
891
+ }
892
+ }
893
+ export class CodexAdapter {
894
+ backend = 'codex';
895
+ capabilities = CAPABILITIES_BY_BACKEND.codex;
896
+ openSessions = new Map();
897
+ spawn(config) {
898
+ const session = new CodexAdapterSession(config, () => {
899
+ this.openSessions.delete(config.sessionKey);
900
+ });
901
+ this.openSessions.set(config.sessionKey, session);
902
+ return session;
903
+ }
904
+ async close(sessionKey) {
905
+ const session = this.openSessions.get(sessionKey);
906
+ if (session)
907
+ await session.close();
908
+ }
909
+ kill(sessionKey) {
910
+ return this.openSessions.get(sessionKey)?.kill() ?? false;
911
+ }
912
+ listSessions() {
913
+ return Array.from(this.openSessions.keys());
914
+ }
915
+ }
916
+ export { runCodex, CancelledError, shutdownCodex, buildMcpBlock };