@cortex-agent/server 2026.7.30 → 2026.8.3

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 (348) hide show
  1. package/README.md +1 -1
  2. package/defaults/CORTEX.md +1 -0
  3. package/defaults/config/CORTEX.md +2 -1
  4. package/defaults/config/hooks/13-status-md-guard.json +11 -0
  5. package/defaults/config/hooks/CORTEX.md +1 -0
  6. package/defaults/config/mcp-config-empty.json +3 -0
  7. package/defaults/config/thread-templates/agents/benchmark-coder.json +22 -0
  8. package/defaults/config/thread-templates/agents/benchmark-reviewer.json +22 -0
  9. package/defaults/config/thread-templates/agents/coder-reviewer.json +4 -9
  10. package/defaults/config/thread-templates/agents/coder.json +4 -14
  11. package/defaults/config/thread-templates/templates/benchmark-coder-review.json +37 -0
  12. package/defaults/config/thread-templates/templates/coder-review.json +3 -27
  13. package/defaults/context/projects/CORTEX.md +1 -1
  14. package/defaults/data/schedules.json +12 -0
  15. package/defaults/hooks/CORTEX.md +1 -0
  16. package/defaults/hooks/new-session-hook.mjs +2 -2
  17. package/defaults/hooks/status-md-guard.mjs +193 -0
  18. package/defaults/plugins/cortex-coder/.claude-plugin/plugin.json +1 -1
  19. package/defaults/plugins/cortex-coder/skills/develop/SKILL.md +28 -2
  20. package/defaults/plugins/cortex-common/.claude-plugin/plugin.json +1 -1
  21. package/defaults/plugins/cortex-common/skills/compound/SKILL.md +1 -1
  22. package/defaults/plugins/cortex-common/skills/compound-simple/SKILL.md +4 -2
  23. package/defaults/plugins/cortex-common/skills/postmortem/SKILL.md +1 -1
  24. package/defaults/plugins/cortex-stage-gate/.claude-plugin/plugin.json +1 -1
  25. package/defaults/plugins/cortex-stage-gate/skills/director-method/SKILL.md +1 -1
  26. package/defaults/plugins/cortex-stage-gate/skills/need-approval/SKILL.md +1 -0
  27. package/defaults/plugins/cortex-stage-gate/skills/reorient/SKILL.md +2 -2
  28. package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +11 -8
  29. package/defaults/plugins/cortex-system/skills/feedback/SKILL.md +1 -1
  30. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +13 -16
  31. package/defaults/prompts/directives/coder-reviewer.md +24 -20
  32. package/defaults/prompts/directives/coder.md +4 -5
  33. package/defaults/prompts/directives/director.md +4 -10
  34. package/defaults/prompts/directives/manager.md +9 -10
  35. package/defaults/prompts/systemPrompts/worker.md +2 -2
  36. package/defaults/rules/cortex-md.md +31 -0
  37. package/defaults/rules/experiment-format.md +8 -1
  38. package/defaults/rules/issues-md.md +10 -9
  39. package/defaults/rules/meta-conventions.md +5 -4
  40. package/defaults/rules/mission-md.md +2 -1
  41. package/defaults/rules/status-md.md +39 -21
  42. package/dist/agent-adapter/bg-wait.d.ts +10 -12
  43. package/dist/agent-adapter/bg-wait.js +209 -129
  44. package/dist/agent-adapter/claude/adapter-tui.d.ts +3 -1
  45. package/dist/agent-adapter/claude/adapter-tui.js +8 -5
  46. package/dist/agent-adapter/claude/adapter.d.ts +43 -14
  47. package/dist/agent-adapter/claude/adapter.js +276 -161
  48. package/dist/agent-adapter/claude/defaults.d.ts +2 -0
  49. package/dist/agent-adapter/claude/defaults.js +5 -5
  50. package/dist/agent-adapter/claude/event-parser.d.ts +3 -8
  51. package/dist/agent-adapter/claude/event-parser.js +28 -31
  52. package/dist/agent-adapter/claude/hooks-builder.js +4 -3
  53. package/dist/agent-adapter/claude/jsonl-tail.js +54 -35
  54. package/dist/agent-adapter/claude/spawn-args.d.ts +15 -12
  55. package/dist/agent-adapter/claude/spawn-args.js +44 -38
  56. package/dist/agent-adapter/claude/tmux-control.d.ts +4 -17
  57. package/dist/agent-adapter/claude/tmux-control.js +39 -32
  58. package/dist/agent-adapter/event-tee.d.ts +19 -0
  59. package/dist/agent-adapter/event-tee.js +145 -0
  60. package/dist/agent-adapter/index.d.ts +1 -0
  61. package/dist/agent-adapter/index.js +7 -3
  62. package/dist/agent-adapter/normalize/event-types.d.ts +17 -9
  63. package/dist/agent-adapter/normalize/event-types.js +4 -4
  64. package/dist/agent-adapter/pi/adapter.d.ts +16 -4
  65. package/dist/agent-adapter/pi/adapter.js +69 -36
  66. package/dist/agent-adapter/pi/discovery.d.ts +19 -3
  67. package/dist/agent-adapter/pi/discovery.js +81 -43
  68. package/dist/agent-adapter/pi/event-parser.js +4 -2
  69. package/dist/agent-adapter/pi/spawn-args.d.ts +2 -4
  70. package/dist/agent-adapter/pi/spawn-args.js +6 -5
  71. package/dist/agent-adapter/types.d.ts +43 -2
  72. package/dist/agent-adapter/types.js +8 -4
  73. package/dist/core/atomic-write.d.ts +6 -1
  74. package/dist/core/atomic-write.js +183 -7
  75. package/dist/core/cli-utils.d.ts +15 -2
  76. package/dist/core/cli-utils.js +46 -41
  77. package/dist/core/config-generator.d.ts +4 -0
  78. package/dist/core/config-generator.js +34 -21
  79. package/dist/core/json-repository.d.ts +4 -0
  80. package/dist/core/json-repository.js +6 -3
  81. package/dist/core/locales/en.d.ts +94 -0
  82. package/dist/core/locales/slices/commands.d.ts +76 -0
  83. package/dist/core/locales/slices/commands.js +155 -1
  84. package/dist/core/locales/slices/status.d.ts +18 -0
  85. package/dist/core/locales/slices/status.js +43 -2
  86. package/dist/core/log.d.ts +5 -0
  87. package/dist/core/log.js +25 -23
  88. package/dist/core/pi-session-filename.d.ts +2 -0
  89. package/dist/core/pi-session-filename.js +18 -0
  90. package/dist/core/resume-reminder.d.ts +5 -0
  91. package/dist/core/resume-reminder.js +18 -0
  92. package/dist/core/runtime-env.d.ts +1 -0
  93. package/dist/core/runtime-env.js +15 -0
  94. package/dist/core/settings-migration.d.ts +5 -0
  95. package/dist/core/settings-migration.js +128 -0
  96. package/dist/core/settings-spec.d.ts +174 -0
  97. package/dist/core/settings-spec.js +150 -0
  98. package/dist/core/settings.d.ts +10 -0
  99. package/dist/core/settings.js +235 -0
  100. package/dist/core/task-parser.d.ts +11 -1
  101. package/dist/core/task-parser.js +34 -3
  102. package/dist/core/types/agent-types.d.ts +19 -0
  103. package/dist/core/types/agent-types.js +1 -1
  104. package/dist/core/types/thread-types.d.ts +48 -3
  105. package/dist/core/types/thread-types.js +2 -2
  106. package/dist/domain/agent-run/access-probe-cli.d.ts +7 -0
  107. package/dist/domain/agent-run/access-probe-cli.js +139 -0
  108. package/dist/domain/agent-run/access-probe-policy.d.ts +61 -0
  109. package/dist/domain/agent-run/access-probe-policy.js +614 -0
  110. package/dist/domain/agent-run/access-probe.d.ts +21 -0
  111. package/dist/domain/agent-run/access-probe.js +194 -0
  112. package/dist/domain/agent-run/agent-run-cli.d.ts +19 -0
  113. package/dist/domain/agent-run/agent-run-cli.js +171 -0
  114. package/dist/domain/agent-run/atif.d.ts +54 -0
  115. package/dist/domain/agent-run/atif.js +211 -0
  116. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.d.ts +32 -0
  117. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.js +616 -0
  118. package/dist/domain/agent-run/benchmark-thread-identity.d.ts +34 -0
  119. package/dist/domain/agent-run/benchmark-thread-identity.js +106 -0
  120. package/dist/domain/agent-run/identity.d.ts +62 -0
  121. package/dist/domain/agent-run/identity.js +118 -0
  122. package/dist/domain/agent-run/journal.d.ts +51 -0
  123. package/dist/domain/agent-run/journal.js +259 -0
  124. package/dist/domain/agent-run/manifest-contract.d.ts +44 -0
  125. package/dist/domain/agent-run/manifest-contract.js +134 -0
  126. package/dist/domain/agent-run/manifest.d.ts +51 -0
  127. package/dist/domain/agent-run/manifest.js +801 -0
  128. package/dist/domain/agent-run/pinned-node-process.d.ts +35 -0
  129. package/dist/domain/agent-run/pinned-node-process.js +206 -0
  130. package/dist/domain/agent-run/role-surface.d.ts +4 -0
  131. package/dist/domain/agent-run/role-surface.js +99 -0
  132. package/dist/domain/agent-run/run-config.d.ts +22 -0
  133. package/dist/domain/agent-run/run-config.js +135 -0
  134. package/dist/domain/agent-run/runner.d.ts +7 -0
  135. package/dist/domain/agent-run/runner.js +518 -0
  136. package/dist/domain/agent-run/supervisor.d.ts +78 -0
  137. package/dist/domain/agent-run/supervisor.js +425 -0
  138. package/dist/domain/agent-run/trajectory-merge-cli.d.ts +11 -0
  139. package/dist/domain/agent-run/trajectory-merge-cli.js +111 -0
  140. package/dist/domain/agent-run/trajectory-merge.d.ts +39 -0
  141. package/dist/domain/agent-run/trajectory-merge.js +505 -0
  142. package/dist/domain/agents/config.d.ts +10 -0
  143. package/dist/domain/agents/config.js +149 -44
  144. package/dist/domain/agents/facade.d.ts +42 -7
  145. package/dist/domain/agents/facade.js +174 -170
  146. package/dist/domain/agents/provider-run-lifecycle.d.ts +18 -0
  147. package/dist/domain/agents/provider-run-lifecycle.js +60 -0
  148. package/dist/domain/auth/auth-events.d.ts +18 -0
  149. package/dist/domain/auth/auth-events.js +38 -0
  150. package/dist/domain/auth/auth-format.d.ts +2 -0
  151. package/dist/domain/auth/auth-format.js +58 -0
  152. package/dist/domain/auth/auth-status.d.ts +61 -0
  153. package/dist/domain/auth/auth-status.js +304 -0
  154. package/dist/domain/auth/auth-watch.d.ts +16 -0
  155. package/dist/domain/auth/auth-watch.js +125 -0
  156. package/dist/domain/auth/cc-login.d.ts +7 -0
  157. package/dist/domain/auth/cc-login.js +16 -0
  158. package/dist/domain/auth/cc-subscription.d.ts +38 -0
  159. package/dist/domain/auth/cc-subscription.js +204 -0
  160. package/dist/domain/auth/index.d.ts +12 -0
  161. package/dist/domain/auth/index.js +16 -0
  162. package/dist/domain/auth/login-flow.d.ts +120 -0
  163. package/dist/domain/auth/login-flow.js +253 -0
  164. package/dist/domain/auth/login-service.d.ts +32 -0
  165. package/dist/domain/auth/login-service.js +97 -0
  166. package/dist/domain/auth/logout.d.ts +32 -0
  167. package/dist/domain/auth/logout.js +123 -0
  168. package/dist/domain/auth/pi-login.d.ts +36 -0
  169. package/dist/domain/auth/pi-login.js +72 -0
  170. package/dist/domain/auth/pi-oauth.d.ts +36 -0
  171. package/dist/domain/auth/pi-oauth.js +84 -0
  172. package/dist/domain/auth/pi-runtime.d.ts +72 -0
  173. package/dist/domain/auth/pi-runtime.js +86 -0
  174. package/dist/domain/mcp/benchmark-thread-server.d.ts +1 -0
  175. package/dist/domain/mcp/benchmark-thread-server.js +26 -0
  176. package/dist/domain/mcp/tools/benchmark-thread-run.d.ts +23 -0
  177. package/dist/domain/mcp/tools/benchmark-thread-run.js +146 -0
  178. package/dist/domain/memory/user-context.js +6 -8
  179. package/dist/domain/monitor/disk-monitor.js +47 -16
  180. package/dist/domain/projects/project-store.js +23 -6
  181. package/dist/domain/remote/client-manager.js +12 -6
  182. package/dist/domain/scheduling/jobs/auth-expiry-scan.d.ts +14 -0
  183. package/dist/domain/scheduling/jobs/auth-expiry-scan.js +86 -0
  184. package/dist/domain/scheduling/jobs/task-dispatch.js +36 -40
  185. package/dist/domain/scheduling/runner.d.ts +2 -0
  186. package/dist/domain/scheduling/runner.js +7 -4
  187. package/dist/domain/sessions/session-backup.d.ts +14 -20
  188. package/dist/domain/sessions/session-backup.js +57 -68
  189. package/dist/domain/system/doctor.d.ts +4 -0
  190. package/dist/domain/system/doctor.js +113 -28
  191. package/dist/domain/system/server-update-check.js +7 -5
  192. package/dist/domain/system/system-notice.d.ts +3 -1
  193. package/dist/domain/system/system-notice.js +6 -11
  194. package/dist/domain/tasks/archiver.d.ts +1 -0
  195. package/dist/domain/tasks/archiver.js +13 -7
  196. package/dist/domain/tasks/claim-recovery.d.ts +3 -3
  197. package/dist/domain/tasks/claim-recovery.js +12 -8
  198. package/dist/domain/tasks/dispatch-utils.d.ts +15 -14
  199. package/dist/domain/tasks/dispatch-utils.js +22 -18
  200. package/dist/domain/tasks/dispatcher.d.ts +1 -0
  201. package/dist/domain/tasks/dispatcher.js +9 -5
  202. package/dist/domain/tasks/mutator.d.ts +21 -11
  203. package/dist/domain/tasks/mutator.js +30 -24
  204. package/dist/domain/tasks/pending-tracker.d.ts +5 -2
  205. package/dist/domain/tasks/pending-tracker.js +11 -5
  206. package/dist/domain/tasks/system/cortex-run.d.ts +2 -1
  207. package/dist/domain/tasks/system/cortex-run.js +24 -4
  208. package/dist/domain/tasks/system/task-cli.d.ts +1 -0
  209. package/dist/domain/tasks/system/task-cli.js +72 -22
  210. package/dist/domain/tasks/system/task-completion.d.ts +19 -2
  211. package/dist/domain/tasks/system/task-completion.js +31 -17
  212. package/dist/domain/tasks/system/task-file-input.d.ts +10 -0
  213. package/dist/domain/tasks/system/task-file-input.js +57 -0
  214. package/dist/domain/tasks/system/task-id-utils.d.ts +9 -9
  215. package/dist/domain/tasks/system/task-id-utils.js +13 -4
  216. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -2
  217. package/dist/domain/tasks/system/task-lifecycle-edit.js +200 -6
  218. package/dist/domain/tasks/system/task-lock.js +19 -5
  219. package/dist/domain/tasks/system/task-mutations.d.ts +22 -12
  220. package/dist/domain/tasks/system/task-mutations.js +28 -4
  221. package/dist/domain/tasks/system/task-process.js +10 -8
  222. package/dist/domain/tasks/system/task-state.d.ts +65 -11
  223. package/dist/domain/tasks/system/task-state.js +86 -13
  224. package/dist/domain/threads/local-runtime-deps.d.ts +32 -0
  225. package/dist/domain/threads/local-runtime-deps.js +91 -0
  226. package/dist/domain/threads/local-runtime-scope.d.ts +6 -0
  227. package/dist/domain/threads/local-runtime-scope.js +12 -0
  228. package/dist/domain/threads/pending-user-inputs.d.ts +3 -0
  229. package/dist/domain/threads/pending-user-inputs.js +37 -0
  230. package/dist/domain/threads/prompt-builder.d.ts +12 -1
  231. package/dist/domain/threads/prompt-builder.js +73 -26
  232. package/dist/domain/threads/runner.d.ts +15 -3
  233. package/dist/domain/threads/runner.js +261 -105
  234. package/dist/domain/threads/state-machine.d.ts +1 -1
  235. package/dist/domain/threads/state-machine.js +17 -8
  236. package/dist/domain/ui-service/app-router.d.ts +86 -6
  237. package/dist/domain/ui-service/app-router.js +171 -133
  238. package/dist/domain/ui-service/input-schemas.d.ts +132 -10
  239. package/dist/domain/ui-service/input-schemas.js +59 -5
  240. package/dist/domain/ui-service/mutate/approvals.d.ts +2 -1
  241. package/dist/domain/ui-service/mutate/approvals.js +2 -1
  242. package/dist/domain/ui-service/mutate/auth.d.ts +6 -0
  243. package/dist/domain/ui-service/mutate/auth.js +83 -0
  244. package/dist/domain/ui-service/mutate/config.js +11 -10
  245. package/dist/domain/ui-service/query/approvals.js +3 -0
  246. package/dist/domain/ui-service/query/auth.d.ts +6 -0
  247. package/dist/domain/ui-service/query/auth.js +12 -0
  248. package/dist/domain/ui-service/query/config.d.ts +5 -5
  249. package/dist/domain/ui-service/query/config.js +27 -17
  250. package/dist/domain/ui-service/query/tasks.d.ts +1 -1
  251. package/dist/domain/ui-service/query/tasks.js +69 -30
  252. package/dist/domain/ui-service/query/threads.js +3 -3
  253. package/dist/domain/ui-service/types.d.ts +67 -8
  254. package/dist/domain/ui-service/types.js +2 -2
  255. package/dist/domain/ui-service/ui-service.js +16 -2
  256. package/dist/entry/admin-channel-hot-reload.d.ts +4 -0
  257. package/dist/entry/admin-channel-hot-reload.js +22 -0
  258. package/dist/entry/app.js +38 -38
  259. package/dist/entry/auth-cli.d.ts +10 -0
  260. package/dist/entry/auth-cli.js +52 -0
  261. package/dist/entry/cli-help.d.ts +5 -0
  262. package/dist/entry/cli-help.js +130 -0
  263. package/dist/entry/cli.d.ts +5 -5
  264. package/dist/entry/cli.js +174 -248
  265. package/dist/entry/daemon.d.ts +11 -0
  266. package/dist/entry/daemon.js +204 -103
  267. package/dist/entry/draft-attachments.d.ts +8 -0
  268. package/dist/entry/draft-attachments.js +83 -0
  269. package/dist/entry/feishu-login.d.ts +2 -6
  270. package/dist/entry/feishu-login.js +16 -21
  271. package/dist/entry/init.js +6 -4
  272. package/dist/entry/start-ui-http.d.ts +2 -8
  273. package/dist/entry/start-ui-http.js +7 -34
  274. package/dist/events/event-logger.js +11 -13
  275. package/dist/events/event-types.d.ts +19 -1
  276. package/dist/events/event-types.js +3 -3
  277. package/dist/events/index.d.ts +1 -1
  278. package/dist/events/index.js +3 -3
  279. package/dist/hooks/new-session-hook.mjs +2 -2
  280. package/dist/hooks/status-md-guard.mjs +193 -0
  281. package/dist/orchestration/agent-file-send.js +44 -14
  282. package/dist/orchestration/agent-runner.d.ts +7 -3
  283. package/dist/orchestration/agent-runner.js +65 -41
  284. package/dist/orchestration/conversation-runner.d.ts +5 -1
  285. package/dist/orchestration/conversation-runner.js +16 -7
  286. package/dist/orchestration/lifecycle.d.ts +23 -1
  287. package/dist/orchestration/lifecycle.js +103 -40
  288. package/dist/orchestration/mid-turn-inject.d.ts +2 -0
  289. package/dist/orchestration/mid-turn-inject.js +29 -13
  290. package/dist/orchestration/resume-dispatcher.d.ts +3 -5
  291. package/dist/orchestration/resume-dispatcher.js +9 -17
  292. package/dist/orchestration/routing/commands/index.d.ts +4 -1
  293. package/dist/orchestration/routing/commands/index.js +83 -61
  294. package/dist/orchestration/routing/commands/login-notice.d.ts +21 -0
  295. package/dist/orchestration/routing/commands/login-notice.js +97 -0
  296. package/dist/orchestration/routing/commands/login.d.ts +12 -0
  297. package/dist/orchestration/routing/commands/login.js +555 -0
  298. package/dist/orchestration/routing/commands/status.js +45 -59
  299. package/dist/orchestration/routing/edit-handler.d.ts +5 -0
  300. package/dist/orchestration/routing/edit-handler.js +127 -73
  301. package/dist/orchestration/routing/webhook.js +5 -4
  302. package/dist/orchestration/session-rewind.d.ts +5 -1
  303. package/dist/orchestration/session-rewind.js +106 -62
  304. package/dist/orchestration/session-send.d.ts +2 -0
  305. package/dist/orchestration/session-send.js +5 -6
  306. package/dist/orchestration/status-helpers.d.ts +1 -2
  307. package/dist/orchestration/status-helpers.js +7 -10
  308. package/dist/orchestration/thread-callback.d.ts +19 -11
  309. package/dist/orchestration/thread-callback.js +132 -61
  310. package/dist/orchestration/thread-executor.js +37 -27
  311. package/dist/orchestration/turn-mutation-lock.d.ts +3 -0
  312. package/dist/orchestration/turn-mutation-lock.js +36 -0
  313. package/dist/orchestration/turn-notify.d.ts +2 -5
  314. package/dist/orchestration/turn-notify.js +9 -21
  315. package/dist/platform/adapter.d.ts +1 -0
  316. package/dist/platform/adapter.js +2 -2
  317. package/dist/platform/adapters/composite-adapter.d.ts +2 -0
  318. package/dist/platform/adapters/composite-adapter.js +13 -3
  319. package/dist/platform/adapters/feishu.d.ts +2 -4
  320. package/dist/platform/adapters/feishu.js +38 -59
  321. package/dist/platform/adapters/index.d.ts +1 -1
  322. package/dist/platform/adapters/index.js +13 -12
  323. package/dist/platform/adapters/slack.d.ts +1 -1
  324. package/dist/platform/adapters/slack.js +12 -35
  325. package/dist/platform/index.d.ts +2 -1
  326. package/dist/platform/index.js +3 -3
  327. package/dist/platform/testing.d.ts +1 -0
  328. package/dist/platform/testing.js +13 -4
  329. package/dist/platform/tool-trace.js +6 -11
  330. package/dist/platform/ui-http/ui-http-server.d.ts +1 -1
  331. package/dist/platform/ui-http/ui-http-server.js +6 -18
  332. package/dist/store/execution-repo.d.ts +17 -1
  333. package/dist/store/execution-repo.js +55 -4
  334. package/dist/store/prompt-migration-replacements.d.ts +4 -0
  335. package/dist/store/prompt-migration-replacements.js +149 -0
  336. package/dist/store/thread-repo.d.ts +15 -4
  337. package/dist/store/thread-repo.js +61 -24
  338. package/dist/store/version-migrations.js +36 -1
  339. package/native/cortex-supervisor/dist/build-manifest.json +22 -0
  340. package/native/cortex-supervisor/dist/cortex-supervisor +0 -0
  341. package/package.json +5 -2
  342. package/web/dist/assets/index-DrNx9R6c.js +139 -0
  343. package/web/dist/assets/index-zpf3OSKC.css +1 -0
  344. package/web/dist/index.html +2 -2
  345. package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.d.ts +0 -1
  346. package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.js +0 -78
  347. package/web/dist/assets/index-B19jLgji.js +0 -138
  348. package/web/dist/assets/index-BuFyPyRW.css +0 -1
@@ -1,6 +1,6 @@
1
- // input: ../adapter.js, ../types.js, ../output-stream.js, ./tui/index.js
2
- // output: CompositeAdapter, FanOutOutputStream, extractTuiAdapter
3
- // pos: Routes platform operations and marker lifecycle by conduit
1
+ // input: platform contracts and TUI adapter
2
+ // output: composite streams, routing, and adapter update helpers
3
+ // pos: Routes platform operations and live settings
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { TuiGatewayAdapter } from './tui/index.js';
6
6
  // ── Capability merging ────────────────────────────────────────────
@@ -360,6 +360,16 @@ export class CompositeAdapter {
360
360
  return this._adapters.some(a => a.ownsConduit(conduit));
361
361
  }
362
362
  }
363
+ export function setPlatformAdminChannel(adapter, platform, channel) {
364
+ const adapters = adapter instanceof CompositeAdapter
365
+ ? adapter._adapters
366
+ : [adapter];
367
+ const names = platform === 'slack' ? new Set(['slack', 'mock']) : new Set(['feishu']);
368
+ for (const candidate of adapters) {
369
+ if (names.has(candidate.name))
370
+ candidate.setAdminChannel?.(channel);
371
+ }
372
+ }
363
373
  // ── extractTuiAdapter ─────────────────────────────────────────────
364
374
  /**
365
375
  * Extract the TuiGatewayAdapter from an adapter.
@@ -65,10 +65,7 @@ export declare class FeishuAdapter implements PlatformAdapter {
65
65
  * (unconfigured admin channel).
66
66
  */
67
67
  private resolveDestination;
68
- /**
69
- * Upsert FEISHU_ADMIN_CHANNEL=<chatId> into <CONFIG_DIR>/.env so the detected
70
- * admin DM survives restarts. Mirrors SlackAdapter._persistAdminChannel.
71
- */
68
+ setAdminChannel(channel: string | null): void;
72
69
  private _persistAdminChannel;
73
70
  private handleIncomingMessage;
74
71
  /**
@@ -108,6 +105,7 @@ export declare class FeishuAdapter implements PlatformAdapter {
108
105
  * string), NOT the top-level `content` field the receive_v1 event uses.
109
106
  */
110
107
  private fetchQuotedParent;
108
+ private handleFormSubmission;
111
109
  private handleCardAction;
112
110
  private buildMessagePayload;
113
111
  private buildCardJson;
@@ -1,12 +1,13 @@
1
- // input: @larksuiteoapi/node-sdk, ../adapter.js, ../types.js
2
- // output: FeishuAdapter with messages, files, cards, and markers
1
+ // input: Lark SDK, core/settings, platform types
2
+ // output: FeishuAdapter messaging, rich-text links, forms, routing
3
3
  // pos: Feishu PlatformAdapter implementation
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import * as lark from '@larksuiteoapi/node-sdk';
6
6
  import * as fs from 'fs';
7
7
  import * as path from 'path';
8
8
  import { createLogger } from '../../core/log.js';
9
- import { STORE_DIR, CONFIG_DIR } from '../../core/paths.js';
9
+ import { STORE_DIR } from '../../core/paths.js';
10
+ import { updateSettings } from '../../core/settings.js';
10
11
  import { FeishuOutputStream } from './feishu-output-stream.js';
11
12
  import { ProjectConduitsStore } from './project-conduits.js';
12
13
  import { reactionFailureReason, shouldWarnReactionFailure } from '../utils/reaction-diagnostics.js';
@@ -437,33 +438,12 @@ export class FeishuAdapter {
437
438
  // =========================================================================
438
439
  // Internal: Inbound event handlers
439
440
  // =========================================================================
440
- /**
441
- * Upsert FEISHU_ADMIN_CHANNEL=<chatId> into <CONFIG_DIR>/.env so the detected
442
- * admin DM survives restarts. Mirrors SlackAdapter._persistAdminChannel.
443
- */
441
+ setAdminChannel(channel) {
442
+ this.config.adminChannel = channel ?? undefined;
443
+ }
444
444
  async _persistAdminChannel(chatId) {
445
- const envPath = path.join(CONFIG_DIR, '.env');
446
- let content = '';
447
- try {
448
- content = await fs.promises.readFile(envPath, 'utf-8');
449
- }
450
- catch {
451
- // File doesn't exist yet — will be created.
452
- }
453
- const lines = content.split('\n');
454
- let found = false;
455
- for (let i = 0; i < lines.length; i++) {
456
- if (lines[i].startsWith('FEISHU_ADMIN_CHANNEL=')) {
457
- lines[i] = `FEISHU_ADMIN_CHANNEL=${chatId}`;
458
- found = true;
459
- break;
460
- }
461
- }
462
- if (!found)
463
- lines.push(`FEISHU_ADMIN_CHANNEL=${chatId}`);
464
- await fs.promises.mkdir(CONFIG_DIR, { recursive: true });
465
- await fs.promises.writeFile(envPath, lines.join('\n'), 'utf-8');
466
- log.info(`FEISHU_ADMIN_CHANNEL=${chatId} written to ${envPath}`);
445
+ await updateSettings({ feishuAdminChannel: chatId });
446
+ log.info(`feishuAdminChannel=${chatId} written to settings.json`);
467
447
  }
468
448
  async handleIncomingMessage(data) {
469
449
  if (!this.messageHandler)
@@ -478,20 +458,14 @@ export class FeishuAdapter {
478
458
  const parentId = message.parent_id || undefined;
479
459
  const messageType = message.message_type || '';
480
460
  const chatType = message.chat_type || ''; // 'p2p' (DM) | 'group'
481
- // Auto-detect the admin channel from a DM when FEISHU_ADMIN_CHANNEL is not
482
- // configured. Mirrors the Slack adapter: the first p2p (DM) message from a
483
- // non-bot user is registered as the admin channel, persisted to .env, and set
484
- // on process.env. Feishu deliberately does NOT fall back to CORTEX_ADMIN_CHANNEL
485
- // (that is a Slack channel id).
461
+ // Feishu uses its own p2p chat id and never inherits Slack's admin channel.
486
462
  if (!this.config.adminChannel && !this._adminAutoDetected && chatType === 'p2p' && !isBot && chatId) {
487
463
  this._adminAutoDetected = true;
488
464
  this.config.adminChannel = chatId;
489
- process.env.FEISHU_ADMIN_CHANNEL = chatId;
490
465
  log.info(`Admin channel auto-detected from DM: ${chatId}`);
491
- // Persist to .env and notify (fire-and-forget, non-blocking).
492
- this._persistAdminChannel(chatId).catch(e => log.warn(`Failed to persist FEISHU_ADMIN_CHANNEL to .env: ${e.message}`));
466
+ this._persistAdminChannel(chatId).catch(e => log.warn(`Failed to persist feishuAdminChannel to settings.json: ${e.message}`));
493
467
  this.postMessage({ type: 'system-notice' }, {
494
- text: `👋 This DM has been auto-registered as the Cortex admin channel. \`FEISHU_ADMIN_CHANNEL=${chatId}\` has been written to \`.env\`. System notifications (startup, rate-limit, disk alerts) will be sent here.`,
468
+ text: `👋 This DM has been auto-registered as the Cortex admin channel. \`feishuAdminChannel=${chatId}\` has been written to \`settings.json\`. System notifications (startup, rate-limit, disk alerts) will be sent here.`,
495
469
  }).catch(e => log.warn(`Failed to send admin auto-detect notification: ${e.message}`));
496
470
  }
497
471
  // Parse message content (JSON string). For file/image/media/audio messages,
@@ -631,10 +605,14 @@ export class FeishuAdapter {
631
605
  continue;
632
606
  switch (node.tag) {
633
607
  case 'text':
634
- case 'a':
635
608
  if (typeof node.text === 'string')
636
609
  line += node.text;
637
610
  break;
611
+ case 'a':
612
+ if (typeof node.text === 'string') {
613
+ line += typeof node.href === 'string' ? `[${node.text}](${node.href})` : node.text;
614
+ }
615
+ break;
638
616
  case 'at':
639
617
  if (typeof node.user_name === 'string')
640
618
  line += `@${node.user_name}`;
@@ -703,6 +681,26 @@ export class FeishuAdapter {
703
681
  return null;
704
682
  }
705
683
  }
684
+ async handleFormSubmission(action, userId) {
685
+ const formName = action.name || '';
686
+ const handler = this.modalHandlers.get(formName);
687
+ if (!handler)
688
+ return undefined;
689
+ let ackResponse;
690
+ await handler({
691
+ callbackId: formName,
692
+ privateMetadata: JSON.stringify(action.value || {}),
693
+ values: this.normalizeFormValues(action.form_value),
694
+ userId,
695
+ async ack(response) {
696
+ ackResponse = response;
697
+ },
698
+ });
699
+ const error = Object.values(ackResponse?.errors ?? {})[0];
700
+ return error
701
+ ? { toast: { type: 'error', content: error } }
702
+ : { toast: { type: 'success', content: 'OK' } };
703
+ }
706
704
  async handleCardAction(data) {
707
705
  const event = data.event || data;
708
706
  const action = event.action || {};
@@ -711,27 +709,8 @@ export class FeishuAdapter {
711
709
  const chatId = context.open_chat_id || '';
712
710
  const messageId = context.open_message_id || '';
713
711
  const userId = operator.open_id || '';
714
- // Check if this is a form submission (has form_value)
715
712
  if (action.form_value && typeof action.form_value === 'object') {
716
- // Form submission → route to modalHandlers
717
- // The form name serves as the callbackId
718
- const formName = action.name || '';
719
- const handler = this.modalHandlers.get(formName);
720
- if (handler) {
721
- const normalizedValues = this.normalizeFormValues(action.form_value);
722
- await handler({
723
- callbackId: formName,
724
- privateMetadata: JSON.stringify(action.value || {}),
725
- values: normalizedValues,
726
- userId,
727
- async ack(_response) {
728
- // Feishu ack is implicit via the callback return value — nothing to do.
729
- },
730
- });
731
- // Return toast or updated card if needed
732
- return { toast: { type: 'success', content: 'OK' } };
733
- }
734
- return undefined;
713
+ return this.handleFormSubmission(action, userId);
735
714
  }
736
715
  // Button click → route to actionHandlers
737
716
  // actionId can be in action.value.actionId (our convention) or action.name
@@ -13,7 +13,7 @@ export interface AdapterOverrides {
13
13
  }
14
14
  /**
15
15
  * Detect and create all primary (Slack / Feishu / test) adapters from
16
- * environment variables. `CORTEX_PLATFORM` is a comma-separated list (e.g.
16
+ * env credentials and settings. `CORTEX_PLATFORM` is a comma-separated list (e.g.
17
17
  * `slack,feishu`); a single value is fully back-compatible. Platforms whose
18
18
  * credentials are missing are silently skipped. Returns an empty array when no
19
19
  * primary platform is configured — the caller falls back to TUI-only mode.
@@ -1,12 +1,13 @@
1
- // input: ../adapter.js, ./slack.js, ./feishu.js, ../testing.js, ./tui/index.js, ./composite-adapter.js
2
- // output: PlatformType + AdapterConfig + createAdapter factory + createAdapterFromEnv + createPrimaryAdapters(FromEnv)
3
- // pos: Select & compose adapters based on CORTEX_PLATFORM (comma list) / CORTEX_TUI
1
+ // input: core/settings, adapter implementations, process env
2
+ // output: adapter factories and primary adapter composition
3
+ // pos: Selects and composes configured platform adapters
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { SlackAdapter } from './slack.js';
6
6
  import { FeishuAdapter } from './feishu.js';
7
7
  import { MockAdapter } from '../testing.js';
8
8
  import { TuiGatewayAdapter } from './tui/index.js';
9
9
  import { CompositeAdapter } from './composite-adapter.js';
10
+ import { getSettings } from '../../core/settings.js';
10
11
  export function createAdapter(config) {
11
12
  switch (config.platform) {
12
13
  case 'slack':
@@ -26,12 +27,13 @@ export function createAdapter(config) {
26
27
  throw new Error(`Unknown platform: ${config.platform}`);
27
28
  }
28
29
  }
29
- // ─── Primary adapter from env (existing detection logic factored out) ───
30
+ // ─── Primary adapters from credentials and settings ────────────────────
30
31
  /**
31
- * Build a single primary adapter by platform name from environment variables.
32
+ * Build a primary adapter from env credentials and runtime settings.
32
33
  * Returns `null` when that platform's credentials are not configured.
33
34
  */
34
35
  function buildPrimaryAdapter(platform) {
36
+ const settings = getSettings();
35
37
  if (platform === 'slack') {
36
38
  const botToken = process.env.SLACK_BOT_TOKEN;
37
39
  const signingSecret = process.env.SLACK_SIGNING_SECRET;
@@ -43,7 +45,7 @@ function buildPrimaryAdapter(platform) {
43
45
  botToken,
44
46
  signingSecret,
45
47
  appToken,
46
- adminChannel: process.env.SLACK_ADMIN_CHANNEL || process.env.CORTEX_ADMIN_CHANNEL || undefined,
48
+ adminChannel: settings.adminChannel ?? undefined,
47
49
  });
48
50
  }
49
51
  if (platform === 'feishu') {
@@ -57,21 +59,20 @@ function buildPrimaryAdapter(platform) {
57
59
  appSecret,
58
60
  encryptKey: process.env.FEISHU_ENCRYPT_KEY || undefined,
59
61
  verificationToken: process.env.FEISHU_VERIFICATION_TOKEN || undefined,
60
- // Feishu must NOT inherit CORTEX_ADMIN_CHANNEL (that is a Slack channel id).
61
- // The admin/DM channel is auto-detected from the first p2p message and
62
- // persisted as FEISHU_ADMIN_CHANNEL (see FeishuAdapter.handleIncomingMessage).
63
- adminChannel: process.env.FEISHU_ADMIN_CHANNEL || undefined,
62
+ // Feishu must not inherit adminChannel because Slack channel ids are incompatible.
63
+ // Its first p2p message is persisted independently as feishuAdminChannel.
64
+ adminChannel: settings.feishuAdminChannel ?? undefined,
64
65
  domain: process.env.FEISHU_DOMAIN || undefined,
65
66
  });
66
67
  }
67
68
  if (platform === 'test') {
68
- return new MockAdapter({ adminChannel: process.env.CORTEX_ADMIN_CHANNEL || 'test-admin' });
69
+ return new MockAdapter({ adminChannel: settings.adminChannel ?? undefined });
69
70
  }
70
71
  return null;
71
72
  }
72
73
  /**
73
74
  * Detect and create all primary (Slack / Feishu / test) adapters from
74
- * environment variables. `CORTEX_PLATFORM` is a comma-separated list (e.g.
75
+ * env credentials and settings. `CORTEX_PLATFORM` is a comma-separated list (e.g.
75
76
  * `slack,feishu`); a single value is fully back-compatible. Platforms whose
76
77
  * credentials are missing are silently skipped. Returns an empty array when no
77
78
  * primary platform is configured — the caller falls back to TUI-only mode.
@@ -84,7 +84,7 @@ export declare class SlackAdapter implements PlatformAdapter {
84
84
  uploadFile(destination: Destination, filePath: string, opts?: FileUploadOpts): Promise<void>;
85
85
  downloadFile(fileRef: PlatformFileRef, destDir: string): Promise<DownloadedFile>;
86
86
  getPermalink(ref: MessageRef): Promise<string | null>;
87
- /** Write CORTEX_ADMIN_CHANNEL to the .env file for persistence across restarts. */
87
+ setAdminChannel(channel: string | null): void;
88
88
  private _persistAdminChannel;
89
89
  /** Expose the rate limiter for sharing with MCP tools and testing. */
90
90
  getRateLimiter(): TokenBucketRateLimiter;
@@ -1,5 +1,5 @@
1
- // input: @slack/bolt, @slack/web-api, ../adapter.js, ../types.js
2
- // output: SlackAdapter with messages, files, and reaction markers
1
+ // input: @slack/bolt, core/settings, platform types
2
+ // output: SlackAdapter messaging and live admin-channel routing
3
3
  // pos: Slack PlatformAdapter implementation
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { App } from '@slack/bolt';
@@ -9,8 +9,8 @@ import { SlackOutputStream } from './slack-output-stream.js';
9
9
  import { SlackProjectConduitsStore } from './slack-project-conduits.js';
10
10
  import * as fs from 'fs';
11
11
  import * as path from 'path';
12
- import { writeFile, readFile, mkdir } from 'fs/promises';
13
- import { CONFIG_DIR } from '../../core/utils.js';
12
+ import { writeFile } from 'fs/promises';
13
+ import { updateSettings } from '../../core/settings.js';
14
14
  import { reactionFailureReason, shouldWarnReactionFailure } from '../utils/reaction-diagnostics.js';
15
15
  const log = createLogger('slack');
16
16
  /** Waiting behind other work. */
@@ -137,18 +137,14 @@ export class SlackAdapter {
137
137
  }
138
138
  return;
139
139
  }
140
- // Auto-detect admin channel from DM when CORTEX_ADMIN_CHANNEL is not configured.
141
- // The first DM (channel starting with "D") from a non-bot user is registered
142
- // as the admin channel, persisted to .env, and set on process.env.
140
+ // Auto-detect the admin channel from the first non-bot DM when none is configured.
143
141
  if (!this.config.adminChannel && !this._adminAutoDetected && msg.channel?.startsWith('D') && !msg.bot_id) {
144
142
  this._adminAutoDetected = true;
145
143
  this.config.adminChannel = msg.channel;
146
- process.env.CORTEX_ADMIN_CHANNEL = msg.channel;
147
144
  log.info(`Admin channel auto-detected from DM: ${msg.channel}`);
148
- // Persist to .env and notify (fire-and-forget, non-blocking)
149
- this._persistAdminChannel(msg.channel).catch(e => log.warn(`Failed to persist CORTEX_ADMIN_CHANNEL to .env: ${e.message}`));
145
+ this._persistAdminChannel(msg.channel).catch(e => log.warn(`Failed to persist adminChannel to settings.json: ${e.message}`));
150
146
  this.postMessage({ type: 'system-notice' }, {
151
- text: `:wave: This DM channel has been auto-registered as the Cortex admin channel. \`CORTEX_ADMIN_CHANNEL=${msg.channel}\` has been written to \`.env\`. System notifications (startup, rate-limit, disk alerts) will be sent here.`,
147
+ text: `:wave: This DM channel has been auto-registered as the Cortex admin channel. \`adminChannel=${msg.channel}\` has been written to \`settings.json\`. System notifications (startup, rate-limit, disk alerts) will be sent here.`,
152
148
  }).catch(e => log.warn(`Failed to send admin auto-detect notification: ${e.message}`));
153
149
  }
154
150
  const ref = {
@@ -534,31 +530,12 @@ export class SlackAdapter {
534
530
  return null;
535
531
  }
536
532
  }
537
- /** Write CORTEX_ADMIN_CHANNEL to the .env file for persistence across restarts. */
533
+ setAdminChannel(channel) {
534
+ this.config.adminChannel = channel ?? undefined;
535
+ }
538
536
  async _persistAdminChannel(channel) {
539
- const envPath = path.join(CONFIG_DIR, '.env');
540
- let content = '';
541
- try {
542
- content = await readFile(envPath, 'utf-8');
543
- }
544
- catch {
545
- // File doesn't exist yet, will be created
546
- }
547
- const lines = content.split('\n');
548
- let found = false;
549
- for (let i = 0; i < lines.length; i++) {
550
- if (lines[i].startsWith('CORTEX_ADMIN_CHANNEL=')) {
551
- lines[i] = `CORTEX_ADMIN_CHANNEL=${channel}`;
552
- found = true;
553
- break;
554
- }
555
- }
556
- if (!found) {
557
- lines.push(`CORTEX_ADMIN_CHANNEL=${channel}`);
558
- }
559
- await mkdir(CONFIG_DIR, { recursive: true });
560
- await writeFile(envPath, lines.join('\n'), 'utf-8');
561
- log.info(`CORTEX_ADMIN_CHANNEL=${channel} written to ${envPath}`);
537
+ await updateSettings({ adminChannel: channel });
538
+ log.info(`adminChannel=${channel} written to settings.json`);
562
539
  }
563
540
  /** Expose the rate limiter for sharing with MCP tools and testing. */
564
541
  getRateLimiter() {
@@ -11,4 +11,5 @@ export { SlackAdapter } from './adapters/slack.js';
11
11
  export type { SlackAdapterConfig } from './adapters/slack.js';
12
12
  export { FeishuAdapter } from './adapters/feishu.js';
13
13
  export type { FeishuAdapterConfig } from './adapters/feishu.js';
14
- export { CompositeAdapter, extractTuiAdapter } from './adapters/composite-adapter.js';
14
+ export { CompositeAdapter, extractTuiAdapter, setPlatformAdminChannel, } from './adapters/composite-adapter.js';
15
+ export type { AdminChannelPlatform } from './adapters/composite-adapter.js';
@@ -1,5 +1,5 @@
1
- // input: adapter + types + output-stream + adapters/* + composite-adapter
2
- // output: Re-export full family of PlatformAdapter public APIs
1
+ // input: platform contracts and concrete adapter exports
2
+ // output: public platform API and live adapter update helpers
3
3
  // pos: Public API export of the Platform abstraction
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  export { postOnce } from './output-stream-helpers.js';
@@ -8,4 +8,4 @@ export { buildQuestionGroupBlocks, buildQuestionModalDefinition, buildPlanApprov
8
8
  export { createAdapter, createAdapterFromEnv } from './adapters/index.js';
9
9
  export { SlackAdapter } from './adapters/slack.js';
10
10
  export { FeishuAdapter } from './adapters/feishu.js';
11
- export { CompositeAdapter, extractTuiAdapter } from './adapters/composite-adapter.js';
11
+ export { CompositeAdapter, extractTuiAdapter, setPlatformAdminChannel, } from './adapters/composite-adapter.js';
@@ -100,6 +100,7 @@ export declare class MockAdapter implements PlatformAdapter {
100
100
  uploadFile(destination: Destination, filePath: string, opts?: FileUploadOpts): Promise<void>;
101
101
  downloadFile(fileRef: PlatformFileRef, destDir: string): Promise<DownloadedFile>;
102
102
  getPermalink(ref: MessageRef): Promise<string | null>;
103
+ setAdminChannel(channel: string | null): void;
103
104
  openOutputStream(destination: Destination, opts?: OpenOutputStreamOpts): OutputStream;
104
105
  private _projectConduits;
105
106
  bindProjectConduit(projectId: string, conduitHint: string): Promise<void>;
@@ -1,5 +1,5 @@
1
- // input: ./adapter.js + ./types.js
2
- // output: MockAdapter + recorded message/modal/marker types
1
+ // input: platform adapter, message, and stream contracts
2
+ // output: configurable MockAdapter with nullable admin routing
3
3
  // pos: In-memory platform adapter for unit tests
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { resolveDestinationConduit } from './types.js';
@@ -127,7 +127,10 @@ export class MockAdapter {
127
127
  this.failPostMessageCount--;
128
128
  throw new Error('mock: postMessage transient failure');
129
129
  }
130
- const channel = resolveDestinationConduit(destination, this._adminChannel);
130
+ if (destination.type === 'system-notice' && !this._adminChannel) {
131
+ return { conduit: '', messageId: '' };
132
+ }
133
+ const channel = resolveDestinationConduit(destination, this._adminChannel ?? undefined);
131
134
  const messageId = String(this.nextId++);
132
135
  this.posted.push({ destination, content, threadId: opts?.threadId });
133
136
  return { conduit: channel, messageId, threadId: opts?.threadId };
@@ -147,7 +150,10 @@ export class MockAdapter {
147
150
  this.failPostInteractiveCount--;
148
151
  throw new Error('mock: postInteractive transient failure');
149
152
  }
150
- const channel = resolveDestinationConduit(destination, this._adminChannel);
153
+ if (destination.type === 'system-notice' && !this._adminChannel) {
154
+ return { conduit: '', messageId: '' };
155
+ }
156
+ const channel = resolveDestinationConduit(destination, this._adminChannel ?? undefined);
151
157
  const messageId = String(this.nextId++);
152
158
  this.posted.push({ destination, content, threadId: opts?.threadId, actions: content.actions });
153
159
  return { conduit: channel, messageId, threadId: opts?.threadId };
@@ -170,6 +176,9 @@ export class MockAdapter {
170
176
  async getPermalink(ref) {
171
177
  return `https://mock.test/permalink/${ref.conduit}/${ref.messageId}`;
172
178
  }
179
+ setAdminChannel(channel) {
180
+ this._adminChannel = channel;
181
+ }
173
182
  // --- Output stream ---
174
183
  openOutputStream(destination, opts) {
175
184
  return new MockOutputStream(this, destination, opts);
@@ -1,18 +1,13 @@
1
- // input: platform/OutputStream, CORTEX_SHOW_TOOL_CALLS env
2
- // output: ToolTrace class + createToolTrace factory + isToolTraceEnabled
3
- // pos: Compact tool_use trace rendered via OutputStream openMutable/update
4
- // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
1
+ // input: OutputStream, icons, runtime settings
2
+ // output: ToolTrace, factory, and enablement gate
3
+ // pos: Renders compact tool-use traces through OutputStream
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
5
  import { Icons } from '../core/icons.js';
6
+ import { getSettings } from '../core/settings.js';
6
7
  const MAX_LINE_LEN = 120;
7
8
  const ELLIPSIS = '…';
8
- function isEnvTruthy(v) {
9
- if (!v)
10
- return false;
11
- const s = v.trim().toLowerCase();
12
- return s === '1' || s === 'true' || s === 'yes' || s === 'on';
13
- }
14
9
  export function isToolTraceEnabled() {
15
- return isEnvTruthy(process.env.CORTEX_SHOW_TOOL_CALLS);
10
+ return getSettings().showToolCalls;
16
11
  }
17
12
  function firstLine(s) {
18
13
  const i = s.indexOf('\n');
@@ -20,7 +20,7 @@ export interface UiHttpServerOptions {
20
20
  * (non-wildcard). OPTIONS preflight is answered 204 with CORS headers (no auth required).
21
21
  * When absent or empty, no CORS headers are emitted — backward-compatible default.
22
22
  */
23
- corsOrigins?: string[];
23
+ corsOrigins?: string[] | (() => string[] | undefined);
24
24
  /**
25
25
  * Optional Cloudflare Access JWT verifier. When present, a request that fails the x-cortex-token
26
26
  * check is admitted if it carries a valid `Cf-Access-Jwt-Assertion` (signature/aud/iss/exp all
@@ -1,19 +1,6 @@
1
- // input: an AnyRouter (injected) + a token accessor + optional Access-JWT verifier + core/auth +
2
- // @trpc/server standalone adapter
3
- // output: createUiHttpServer({ router, getToken, port, host?, spaDir?, corsOrigins?, verifyAccessJwt? }) -> { server, close() }
4
- // pos: Web UI transport-host, in-core (agent-server platform/ui-http). Mounts the injected tRPC
5
- // router on the standalone HTTP adapter (query/mutate over HTTP, subscription over SSE —
6
- // tRPC v11), gated by a DUAL-PATH auth check BEFORE tRPC, and serves the built SPA static
7
- // files for non-tRPC paths. Generic over AnyRouter — the concrete AppRouter is injected by
8
- // start-ui-http.ts, keeping this file router-agnostic. Bound 127.0.0.1 by default. Reads
9
- // AUTH_HEADER / timingSafeEqualStr and createLogger from the core package's built dist.
10
- // Auth gate: (1) a matching x-cortex-token (desktop/machine clients — byte-for-byte the
11
- // prior behaviour, checked first, synchronous) OR (2) a validly-signed Cf-Access-Jwt-Assertion
12
- // (Cloudflare Access JWT — the browser path; verified via the injected verifyAccessJwt).
13
- // Neither/invalid → 401. When no verifier is injected, only the token path is live.
14
- // CORS allow-list: optional corsOrigins[] lets the Tauri desktop webview (cross-origin,
15
- // e.g. tauri://localhost) reach tRPC endpoints directly without a proxy. Non-wildcard only
16
- // — the origin is echoed verbatim when it's in the allow-list.
1
+ // input: tRPC router, auth accessors, SPA, per-request CORS source
2
+ // output: authenticated HTTP/SSE server with static and custom routes
3
+ // pos: Web UI HTTP transport host
17
4
  // >>> If I am updated, update CORTEX.md <<<
18
5
  import * as fs from 'fs';
19
6
  import * as path from 'path';
@@ -72,12 +59,13 @@ async function isAccessAuthorized(req, verifyAccessJwt) {
72
59
  * `writeHead` only overrides the same-name entries. Returns the matched origin (or undefined).
73
60
  */
74
61
  function applyCorsHeaders(req, res, corsOrigins) {
75
- if (!corsOrigins || corsOrigins.length === 0)
62
+ const resolvedOrigins = typeof corsOrigins === 'function' ? corsOrigins() : corsOrigins;
63
+ if (!resolvedOrigins || resolvedOrigins.length === 0)
76
64
  return undefined;
77
65
  const origin = Array.isArray(req.headers['origin'])
78
66
  ? req.headers['origin'][0]
79
67
  : req.headers['origin'];
80
- if (!origin || !corsOrigins.includes(origin))
68
+ if (!origin || !resolvedOrigins.includes(origin))
81
69
  return undefined;
82
70
  // Non-wildcard: echo the exact origin so the response is origin-specific and cacheable.
83
71
  res.setHeader('Access-Control-Allow-Origin', origin);
@@ -67,6 +67,8 @@ declare class ExecutionRepo {
67
67
  private mutex;
68
68
  /** Promise chain for fire-and-forget persists, guarded by this.mutex. */
69
69
  private _pendingPersist;
70
+ /** True while a persist is queued but not yet snapshotting — lets queuePersist coalesce. */
71
+ private _persistQueued;
70
72
  constructor(opts?: ExecutionRepoOptions);
71
73
  /** Load executions from disk into memory. Populates the Map from executions.json. */
72
74
  load(): void;
@@ -184,9 +186,23 @@ declare class ExecutionRepo {
184
186
  count: number;
185
187
  staled: string[];
186
188
  }>;
189
+ /** Default archive sibling: <dir>/archive/<basename>-archive.jsonl */
190
+ private defaultArchivePath;
191
+ private selectArchivable;
192
+ /** Move terminal records older than `olderThanMs` into an append-only JSONL archive.
193
+ * Append-then-delete ordering: a crash between the two steps can duplicate archive lines
194
+ * but never loses a record. Returns the number of archived records. */
195
+ archiveTerminal({ olderThanMs, archivePath }?: {
196
+ olderThanMs?: number;
197
+ archivePath?: string;
198
+ }): Promise<number>;
187
199
  /** Await all pending fire-and-forget disk writes AND any in-flight async operations. */
188
200
  flush(): Promise<void>;
189
- /** Return the current _pendingPersist promise (for tests that want to await a specific persist batch). */
201
+ /** Return the current _pendingPersist promise (for tests that want to await a specific persist batch).
202
+ * Coalescing: map mutations are synchronous and persist() snapshots the whole map, so any
203
+ * mutation made before a queued persist STARTS is covered by it — a second queue entry would
204
+ * only re-write identical state. The flag resets right before the snapshot; mutations landing
205
+ * after that queue a fresh persist. Collapses sync bursts from N stringifies to 1. */
190
206
  queuePersist(): Promise<void>;
191
207
  /** Atomically persist the entire Map to disk. */
192
208
  private persist;