@cortex-agent/server 2026.7.30 → 2026.8.3-2

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 (353) 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/core/utils.d.ts +21 -1
  107. package/dist/core/utils.js +37 -1
  108. package/dist/domain/agent-run/access-probe-cli.d.ts +7 -0
  109. package/dist/domain/agent-run/access-probe-cli.js +139 -0
  110. package/dist/domain/agent-run/access-probe-policy.d.ts +61 -0
  111. package/dist/domain/agent-run/access-probe-policy.js +614 -0
  112. package/dist/domain/agent-run/access-probe.d.ts +21 -0
  113. package/dist/domain/agent-run/access-probe.js +194 -0
  114. package/dist/domain/agent-run/agent-run-cli.d.ts +19 -0
  115. package/dist/domain/agent-run/agent-run-cli.js +171 -0
  116. package/dist/domain/agent-run/atif.d.ts +54 -0
  117. package/dist/domain/agent-run/atif.js +211 -0
  118. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.d.ts +32 -0
  119. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.js +616 -0
  120. package/dist/domain/agent-run/benchmark-thread-identity.d.ts +34 -0
  121. package/dist/domain/agent-run/benchmark-thread-identity.js +106 -0
  122. package/dist/domain/agent-run/identity.d.ts +62 -0
  123. package/dist/domain/agent-run/identity.js +118 -0
  124. package/dist/domain/agent-run/journal.d.ts +51 -0
  125. package/dist/domain/agent-run/journal.js +259 -0
  126. package/dist/domain/agent-run/manifest-contract.d.ts +44 -0
  127. package/dist/domain/agent-run/manifest-contract.js +134 -0
  128. package/dist/domain/agent-run/manifest.d.ts +51 -0
  129. package/dist/domain/agent-run/manifest.js +801 -0
  130. package/dist/domain/agent-run/pinned-node-process.d.ts +35 -0
  131. package/dist/domain/agent-run/pinned-node-process.js +206 -0
  132. package/dist/domain/agent-run/role-surface.d.ts +4 -0
  133. package/dist/domain/agent-run/role-surface.js +99 -0
  134. package/dist/domain/agent-run/run-config.d.ts +22 -0
  135. package/dist/domain/agent-run/run-config.js +135 -0
  136. package/dist/domain/agent-run/runner.d.ts +7 -0
  137. package/dist/domain/agent-run/runner.js +518 -0
  138. package/dist/domain/agent-run/supervisor.d.ts +78 -0
  139. package/dist/domain/agent-run/supervisor.js +425 -0
  140. package/dist/domain/agent-run/trajectory-merge-cli.d.ts +11 -0
  141. package/dist/domain/agent-run/trajectory-merge-cli.js +111 -0
  142. package/dist/domain/agent-run/trajectory-merge.d.ts +39 -0
  143. package/dist/domain/agent-run/trajectory-merge.js +505 -0
  144. package/dist/domain/agents/config.d.ts +10 -0
  145. package/dist/domain/agents/config.js +149 -44
  146. package/dist/domain/agents/facade.d.ts +42 -7
  147. package/dist/domain/agents/facade.js +174 -170
  148. package/dist/domain/agents/provider-run-lifecycle.d.ts +18 -0
  149. package/dist/domain/agents/provider-run-lifecycle.js +60 -0
  150. package/dist/domain/auth/auth-events.d.ts +18 -0
  151. package/dist/domain/auth/auth-events.js +38 -0
  152. package/dist/domain/auth/auth-format.d.ts +2 -0
  153. package/dist/domain/auth/auth-format.js +58 -0
  154. package/dist/domain/auth/auth-status.d.ts +61 -0
  155. package/dist/domain/auth/auth-status.js +304 -0
  156. package/dist/domain/auth/auth-watch.d.ts +16 -0
  157. package/dist/domain/auth/auth-watch.js +125 -0
  158. package/dist/domain/auth/cc-login.d.ts +7 -0
  159. package/dist/domain/auth/cc-login.js +16 -0
  160. package/dist/domain/auth/cc-subscription.d.ts +38 -0
  161. package/dist/domain/auth/cc-subscription.js +204 -0
  162. package/dist/domain/auth/index.d.ts +12 -0
  163. package/dist/domain/auth/index.js +16 -0
  164. package/dist/domain/auth/login-flow.d.ts +120 -0
  165. package/dist/domain/auth/login-flow.js +253 -0
  166. package/dist/domain/auth/login-service.d.ts +32 -0
  167. package/dist/domain/auth/login-service.js +97 -0
  168. package/dist/domain/auth/logout.d.ts +32 -0
  169. package/dist/domain/auth/logout.js +123 -0
  170. package/dist/domain/auth/pi-login.d.ts +36 -0
  171. package/dist/domain/auth/pi-login.js +72 -0
  172. package/dist/domain/auth/pi-oauth.d.ts +36 -0
  173. package/dist/domain/auth/pi-oauth.js +84 -0
  174. package/dist/domain/auth/pi-runtime.d.ts +72 -0
  175. package/dist/domain/auth/pi-runtime.js +86 -0
  176. package/dist/domain/mcp/benchmark-thread-server.d.ts +1 -0
  177. package/dist/domain/mcp/benchmark-thread-server.js +26 -0
  178. package/dist/domain/mcp/tools/benchmark-thread-run.d.ts +23 -0
  179. package/dist/domain/mcp/tools/benchmark-thread-run.js +146 -0
  180. package/dist/domain/memory/user-context.js +6 -8
  181. package/dist/domain/monitor/disk-monitor.js +47 -16
  182. package/dist/domain/projects/project-store.js +23 -6
  183. package/dist/domain/remote/client-hot-reload.d.ts +9 -1
  184. package/dist/domain/remote/client-hot-reload.js +60 -12
  185. package/dist/domain/remote/client-manager.js +12 -6
  186. package/dist/domain/scheduling/jobs/auth-expiry-scan.d.ts +14 -0
  187. package/dist/domain/scheduling/jobs/auth-expiry-scan.js +86 -0
  188. package/dist/domain/scheduling/jobs/task-dispatch.js +36 -40
  189. package/dist/domain/scheduling/runner.d.ts +2 -0
  190. package/dist/domain/scheduling/runner.js +7 -4
  191. package/dist/domain/sessions/session-backup.d.ts +14 -20
  192. package/dist/domain/sessions/session-backup.js +57 -68
  193. package/dist/domain/system/doctor.d.ts +4 -0
  194. package/dist/domain/system/doctor.js +113 -28
  195. package/dist/domain/system/install-cli.js +8 -3
  196. package/dist/domain/system/server-update-check.js +7 -5
  197. package/dist/domain/system/system-notice.d.ts +3 -1
  198. package/dist/domain/system/system-notice.js +6 -11
  199. package/dist/domain/tasks/archiver.d.ts +1 -0
  200. package/dist/domain/tasks/archiver.js +13 -7
  201. package/dist/domain/tasks/claim-recovery.d.ts +3 -3
  202. package/dist/domain/tasks/claim-recovery.js +12 -8
  203. package/dist/domain/tasks/dispatch-utils.d.ts +15 -14
  204. package/dist/domain/tasks/dispatch-utils.js +22 -18
  205. package/dist/domain/tasks/dispatcher.d.ts +1 -0
  206. package/dist/domain/tasks/dispatcher.js +9 -5
  207. package/dist/domain/tasks/mutator.d.ts +21 -11
  208. package/dist/domain/tasks/mutator.js +30 -24
  209. package/dist/domain/tasks/pending-tracker.d.ts +5 -2
  210. package/dist/domain/tasks/pending-tracker.js +11 -5
  211. package/dist/domain/tasks/system/cortex-run.d.ts +2 -1
  212. package/dist/domain/tasks/system/cortex-run.js +24 -4
  213. package/dist/domain/tasks/system/task-cli.d.ts +1 -0
  214. package/dist/domain/tasks/system/task-cli.js +72 -22
  215. package/dist/domain/tasks/system/task-completion.d.ts +19 -2
  216. package/dist/domain/tasks/system/task-completion.js +31 -17
  217. package/dist/domain/tasks/system/task-file-input.d.ts +10 -0
  218. package/dist/domain/tasks/system/task-file-input.js +57 -0
  219. package/dist/domain/tasks/system/task-id-utils.d.ts +9 -9
  220. package/dist/domain/tasks/system/task-id-utils.js +13 -4
  221. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -2
  222. package/dist/domain/tasks/system/task-lifecycle-edit.js +200 -6
  223. package/dist/domain/tasks/system/task-lock.js +19 -5
  224. package/dist/domain/tasks/system/task-mutations.d.ts +22 -12
  225. package/dist/domain/tasks/system/task-mutations.js +28 -4
  226. package/dist/domain/tasks/system/task-process.js +10 -8
  227. package/dist/domain/tasks/system/task-state.d.ts +65 -11
  228. package/dist/domain/tasks/system/task-state.js +86 -13
  229. package/dist/domain/threads/local-runtime-deps.d.ts +32 -0
  230. package/dist/domain/threads/local-runtime-deps.js +91 -0
  231. package/dist/domain/threads/local-runtime-scope.d.ts +6 -0
  232. package/dist/domain/threads/local-runtime-scope.js +12 -0
  233. package/dist/domain/threads/pending-user-inputs.d.ts +3 -0
  234. package/dist/domain/threads/pending-user-inputs.js +37 -0
  235. package/dist/domain/threads/prompt-builder.d.ts +12 -1
  236. package/dist/domain/threads/prompt-builder.js +73 -26
  237. package/dist/domain/threads/runner.d.ts +15 -3
  238. package/dist/domain/threads/runner.js +261 -105
  239. package/dist/domain/threads/state-machine.d.ts +1 -1
  240. package/dist/domain/threads/state-machine.js +17 -8
  241. package/dist/domain/ui-service/app-router.d.ts +86 -6
  242. package/dist/domain/ui-service/app-router.js +171 -133
  243. package/dist/domain/ui-service/input-schemas.d.ts +132 -10
  244. package/dist/domain/ui-service/input-schemas.js +59 -5
  245. package/dist/domain/ui-service/mutate/approvals.d.ts +2 -1
  246. package/dist/domain/ui-service/mutate/approvals.js +2 -1
  247. package/dist/domain/ui-service/mutate/auth.d.ts +6 -0
  248. package/dist/domain/ui-service/mutate/auth.js +83 -0
  249. package/dist/domain/ui-service/mutate/config.js +11 -10
  250. package/dist/domain/ui-service/query/approvals.js +3 -0
  251. package/dist/domain/ui-service/query/auth.d.ts +6 -0
  252. package/dist/domain/ui-service/query/auth.js +12 -0
  253. package/dist/domain/ui-service/query/config.d.ts +5 -5
  254. package/dist/domain/ui-service/query/config.js +27 -17
  255. package/dist/domain/ui-service/query/tasks.d.ts +1 -1
  256. package/dist/domain/ui-service/query/tasks.js +69 -30
  257. package/dist/domain/ui-service/query/threads.js +3 -3
  258. package/dist/domain/ui-service/types.d.ts +67 -8
  259. package/dist/domain/ui-service/types.js +2 -2
  260. package/dist/domain/ui-service/ui-service.js +16 -2
  261. package/dist/entry/admin-channel-hot-reload.d.ts +4 -0
  262. package/dist/entry/admin-channel-hot-reload.js +22 -0
  263. package/dist/entry/app.js +38 -38
  264. package/dist/entry/auth-cli.d.ts +10 -0
  265. package/dist/entry/auth-cli.js +52 -0
  266. package/dist/entry/cli-help.d.ts +5 -0
  267. package/dist/entry/cli-help.js +130 -0
  268. package/dist/entry/cli.d.ts +5 -5
  269. package/dist/entry/cli.js +174 -248
  270. package/dist/entry/daemon.d.ts +11 -0
  271. package/dist/entry/daemon.js +204 -103
  272. package/dist/entry/draft-attachments.d.ts +8 -0
  273. package/dist/entry/draft-attachments.js +83 -0
  274. package/dist/entry/feishu-login.d.ts +2 -6
  275. package/dist/entry/feishu-login.js +16 -21
  276. package/dist/entry/init.js +6 -4
  277. package/dist/entry/start-ui-http.d.ts +2 -8
  278. package/dist/entry/start-ui-http.js +7 -34
  279. package/dist/events/event-logger.js +11 -13
  280. package/dist/events/event-types.d.ts +19 -1
  281. package/dist/events/event-types.js +3 -3
  282. package/dist/events/index.d.ts +1 -1
  283. package/dist/events/index.js +3 -3
  284. package/dist/hooks/new-session-hook.mjs +2 -2
  285. package/dist/hooks/status-md-guard.mjs +193 -0
  286. package/dist/orchestration/agent-file-send.js +44 -14
  287. package/dist/orchestration/agent-runner.d.ts +7 -3
  288. package/dist/orchestration/agent-runner.js +65 -41
  289. package/dist/orchestration/conversation-runner.d.ts +5 -1
  290. package/dist/orchestration/conversation-runner.js +16 -7
  291. package/dist/orchestration/lifecycle.d.ts +23 -1
  292. package/dist/orchestration/lifecycle.js +103 -40
  293. package/dist/orchestration/mid-turn-inject.d.ts +2 -0
  294. package/dist/orchestration/mid-turn-inject.js +29 -13
  295. package/dist/orchestration/resume-dispatcher.d.ts +3 -5
  296. package/dist/orchestration/resume-dispatcher.js +9 -17
  297. package/dist/orchestration/routing/commands/index.d.ts +4 -1
  298. package/dist/orchestration/routing/commands/index.js +83 -61
  299. package/dist/orchestration/routing/commands/login-notice.d.ts +21 -0
  300. package/dist/orchestration/routing/commands/login-notice.js +97 -0
  301. package/dist/orchestration/routing/commands/login.d.ts +12 -0
  302. package/dist/orchestration/routing/commands/login.js +555 -0
  303. package/dist/orchestration/routing/commands/status.js +45 -59
  304. package/dist/orchestration/routing/edit-handler.d.ts +5 -0
  305. package/dist/orchestration/routing/edit-handler.js +127 -73
  306. package/dist/orchestration/routing/webhook.js +5 -4
  307. package/dist/orchestration/session-rewind.d.ts +5 -1
  308. package/dist/orchestration/session-rewind.js +106 -62
  309. package/dist/orchestration/session-send.d.ts +2 -0
  310. package/dist/orchestration/session-send.js +5 -6
  311. package/dist/orchestration/status-helpers.d.ts +1 -2
  312. package/dist/orchestration/status-helpers.js +7 -10
  313. package/dist/orchestration/thread-callback.d.ts +19 -11
  314. package/dist/orchestration/thread-callback.js +132 -61
  315. package/dist/orchestration/thread-executor.js +37 -27
  316. package/dist/orchestration/turn-mutation-lock.d.ts +3 -0
  317. package/dist/orchestration/turn-mutation-lock.js +36 -0
  318. package/dist/orchestration/turn-notify.d.ts +2 -5
  319. package/dist/orchestration/turn-notify.js +9 -21
  320. package/dist/platform/adapter.d.ts +1 -0
  321. package/dist/platform/adapter.js +2 -2
  322. package/dist/platform/adapters/composite-adapter.d.ts +2 -0
  323. package/dist/platform/adapters/composite-adapter.js +13 -3
  324. package/dist/platform/adapters/feishu.d.ts +2 -4
  325. package/dist/platform/adapters/feishu.js +38 -59
  326. package/dist/platform/adapters/index.d.ts +1 -1
  327. package/dist/platform/adapters/index.js +13 -12
  328. package/dist/platform/adapters/slack.d.ts +1 -1
  329. package/dist/platform/adapters/slack.js +12 -35
  330. package/dist/platform/index.d.ts +2 -1
  331. package/dist/platform/index.js +3 -3
  332. package/dist/platform/testing.d.ts +1 -0
  333. package/dist/platform/testing.js +13 -4
  334. package/dist/platform/tool-trace.js +6 -11
  335. package/dist/platform/ui-http/ui-http-server.d.ts +1 -1
  336. package/dist/platform/ui-http/ui-http-server.js +6 -18
  337. package/dist/store/execution-repo.d.ts +17 -1
  338. package/dist/store/execution-repo.js +55 -4
  339. package/dist/store/prompt-migration-replacements.d.ts +4 -0
  340. package/dist/store/prompt-migration-replacements.js +149 -0
  341. package/dist/store/thread-repo.d.ts +15 -4
  342. package/dist/store/thread-repo.js +61 -24
  343. package/dist/store/version-migrations.js +36 -1
  344. package/native/cortex-supervisor/dist/build-manifest.json +22 -0
  345. package/native/cortex-supervisor/dist/cortex-supervisor +0 -0
  346. package/package.json +5 -2
  347. package/web/dist/assets/index-XqBCYtkw.js +139 -0
  348. package/web/dist/assets/index-zpf3OSKC.css +1 -0
  349. package/web/dist/index.html +2 -2
  350. package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.d.ts +0 -1
  351. package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.js +0 -78
  352. package/web/dist/assets/index-B19jLgji.js +0 -138
  353. package/web/dist/assets/index-BuFyPyRW.css +0 -1
@@ -1,12 +1,7 @@
1
- // input: ${CORTEX_REPO}/src/**/*.ts changes (auto rebuild + install + app.js restart),
2
- // .restart trigger file (manual restart; in dev mode: rebuild pipeline; in prod: hot-reload app.js),
3
- // CONFIG_DIR/.env changes
4
- // output: process supervisor — fork(app.js) with hot-restart, crash recovery, graceful shutdown;
5
- // on src change: npm run build (server→ui-contract→web) → npm pack → npm install -g <tgz> → restart();
6
- // on .restart in dev mode (CORTEX_REPO set): same rebuild pipeline
7
- // pos: system entry point, top-level process in daemon mode (node dist/entry/daemon.js);
8
- // logs/PID persisted to DATA_DIR
9
- // >>> If I am updated, update my header comment and CORTEX.md <<<
1
+ // input: runtime env, source changes, restart triggers
2
+ // output: supervised app, resilient watchers, serialized restarts
3
+ // pos: Agent-server process supervisor
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
10
5
  /**
11
6
  * Cortex Daemon — Supervisor for app.ts
12
7
  *
@@ -45,17 +40,17 @@
45
40
  * watcher below picks up. In dev mode (CORTEX_REPO set) this triggers the full
46
41
  * rebuild pipeline; in production mode it just respawns app.js.
47
42
  */
48
- import * as dotenv from 'dotenv';
49
43
  import { fork, spawn } from 'child_process';
50
- import { watch, existsSync, unlinkSync, statSync, writeFileSync, readdirSync } from 'fs';
44
+ import { watch, existsSync, unlinkSync, statSync, writeFileSync, readdirSync, } from 'fs';
51
45
  import * as path from 'path';
52
46
  import { createLogger } from '../core/log.js';
47
+ import { loadRuntimeDotenv } from '../core/runtime-env.js';
53
48
  import { isMainModule, moduleDir, DATA_DIR, CONFIG_DIR, STORE_DIR } from '../core/utils.js';
54
49
  import { tryAcquireSingletonLock, releaseSingletonLock as releaseLock } from '../core/singleton-lock.js';
55
50
  // Load .env BEFORE reading any CORTEX_* env vars below. Mirrors app.ts §61 — the
56
51
  // daemon needs CORTEX_REPO (and potentially other vars) from .env, not just from
57
52
  // the OS shell env. Must be sync and before the `CORTEX_REPO` constant below.
58
- dotenv.config({ path: path.join(CONFIG_DIR, '.env') });
53
+ loadRuntimeDotenv(path.join(CONFIG_DIR, '.env'));
59
54
  // --- Logger ---
60
55
  const log = createLogger('daemon');
61
56
  // --- Paths ---
@@ -82,6 +77,7 @@ const BUILD_DEBOUNCE_MS = 2500; // src/*.ts — slower, build takes seconds anyw
82
77
  const BACKOFF_INITIAL = 1000;
83
78
  const BACKOFF_MAX = 30_000;
84
79
  const HEALTHY_THRESHOLD = 10_000; // if alive > 10s, reset backoff
80
+ const WATCH_FALLBACK_MS = 5000;
85
81
  // Src-watch filter: paths under SRC_WATCH_PATH that should NOT trigger a rebuild.
86
82
  const SRC_IGNORE_PREFIXES = ['tests/', 'tmp/', 'node_modules/', 'dist/', 'vendor/'];
87
83
  const SRC_IGNORE_SUFFIXES = ['.d.ts', '.test.ts', '.spec.ts'];
@@ -99,6 +95,7 @@ let pendingRebuild = null; // reason string if rebuild is deferred (busy or in-f
99
95
  let restarting = false; // true while restart() stop→start cycle is in progress
100
96
  let rebuilding = false; // true while runRebuildPipeline() is running
101
97
  let nextRestartReason = null; // forwarded to next child via CORTEX_RESTART_REASON
98
+ let watchMonitors = [];
102
99
  // Daemon logs are written by the centralized logger (src/core/log.ts)
103
100
  // — console + daily-rotating file output in DATA_DIR/logs/.
104
101
  // --- Cancel all pending restart timers ---
@@ -268,13 +265,67 @@ async function restart(reason) {
268
265
  nextRestartReason = reason;
269
266
  startChild();
270
267
  }
271
- // --- File Watching ---
272
- /** Recursively walk a directory tree and return an fs.FSWatcher for each subdirectory.
273
- * Used on Windows where fs.watch({recursive:true}) throws EPERM. */
268
+ function formatWatchError(error) {
269
+ if (!(error instanceof Error))
270
+ return String(error);
271
+ const code = error.code;
272
+ return code ? `${code}: ${error.message}` : error.message;
273
+ }
274
+ function closeWatchers(watchers) {
275
+ for (const watcher of watchers.splice(0)) {
276
+ try {
277
+ watcher.close();
278
+ }
279
+ catch { }
280
+ }
281
+ }
282
+ function pollSafely(options, warn) {
283
+ try {
284
+ options.poll?.();
285
+ }
286
+ catch (error) {
287
+ warn(`${options.label} polling failed (${formatWatchError(error)})`);
288
+ }
289
+ }
290
+ function failWatchMonitor(state, options, warn, error) {
291
+ if (state.failed || state.closed)
292
+ return;
293
+ state.failed = true;
294
+ closeWatchers(state.watchers);
295
+ const detail = formatWatchError(error);
296
+ if (!options.poll) {
297
+ warn(`${options.label} watcher failed (${detail}); watcher disabled`);
298
+ return;
299
+ }
300
+ warn(`${options.label} watcher failed (${detail}); polling every ${WATCH_FALLBACK_MS}ms`);
301
+ state.pollTimer = setInterval(() => pollSafely(options, warn), WATCH_FALLBACK_MS);
302
+ }
303
+ function closeWatchMonitor(state) {
304
+ state.closed = true;
305
+ closeWatchers(state.watchers);
306
+ if (state.pollTimer)
307
+ clearInterval(state.pollTimer);
308
+ state.pollTimer = null;
309
+ }
310
+ export function createResilientWatchMonitor(options) {
311
+ const state = { watchers: [], pollTimer: null, failed: false, closed: false };
312
+ const warn = options.warn ?? (message => log.warn(message));
313
+ const fallBack = (error) => failWatchMonitor(state, options, warn, error);
314
+ try {
315
+ state.watchers = options.startWatching();
316
+ for (const watcher of state.watchers)
317
+ watcher.on('error', fallBack);
318
+ }
319
+ catch (error) {
320
+ fallBack(error);
321
+ }
322
+ return { close: () => closeWatchMonitor(state) };
323
+ }
324
+ /** Recursively watch each directory on Windows, closing partial setup on failure. */
274
325
  function watchTree(root, callback) {
275
326
  const watchers = [];
276
327
  const walk = (dir) => {
277
- watchers.push(watch(dir, (et, fn) => callback(et, fn)));
328
+ watchers.push(watch(dir, (eventType, filename) => callback(eventType, filename)));
278
329
  let entries;
279
330
  try {
280
331
  entries = readdirSync(dir, { withFileTypes: true });
@@ -290,79 +341,133 @@ function watchTree(root, callback) {
290
341
  walk(path.join(dir, entry.name));
291
342
  }
292
343
  };
293
- walk(root);
344
+ try {
345
+ walk(root);
346
+ }
347
+ catch (error) {
348
+ closeWatchers(watchers);
349
+ throw error;
350
+ }
294
351
  return watchers;
295
352
  }
296
- function setupWatchers() {
297
- const watchers = [];
298
- // Watch ${CORTEX_REPO}/src/**/*.ts — when source files change, rebuild the package,
299
- // npm install -g the fresh tgz, then restart() the app.js child from the new dist.
300
- // The daemon process itself does NOT reload; edits to daemon.ts require manual restart.
301
- // If CORTEX_REPO is unset or src/ is missing, this watcher is skipped — the daemon then
302
- // relies purely on the .restart trigger below (manual upgrade flow).
303
- if (SRC_WATCH_PATH && existsSync(SRC_WATCH_PATH) && statSync(SRC_WATCH_PATH).isDirectory()) {
304
- const onChange = (_eventType, filename) => {
305
- if (!filename)
306
- return;
307
- const changedName = String(filename).replace(/\\/g, '/');
308
- if (!changedName.endsWith('.ts'))
309
- return;
310
- if (SRC_IGNORE_SUFFIXES.some(s => changedName.endsWith(s)))
311
- return;
312
- if (SRC_IGNORE_PREFIXES.some(p => changedName.startsWith(p) || changedName.includes(`/${p}`)))
313
- return;
314
- debouncedRebuild(`src change: ${changedName}`);
315
- };
316
- // Windows: recursive watch throws EPERM — watch each directory individually
317
- if (process.platform === 'win32') {
318
- const srcWatchers = watchTree(SRC_WATCH_PATH, onChange);
319
- watchers.push(...srcWatchers);
320
- log.info(`Watching src: ${SRC_WATCH_PATH} (per-directory, *.ts, ${srcWatchers.length} dirs)`);
321
- }
322
- else {
323
- const watcher = watch(SRC_WATCH_PATH, { recursive: true }, onChange);
324
- watchers.push(watcher);
353
+ function isDirectory(dir) {
354
+ try {
355
+ return existsSync(dir) && statSync(dir).isDirectory();
356
+ }
357
+ catch {
358
+ return false;
359
+ }
360
+ }
361
+ function handleSourceChange(filename) {
362
+ if (!filename)
363
+ return;
364
+ const changedName = String(filename).replace(/\\/g, '/');
365
+ if (!changedName.endsWith('.ts'))
366
+ return;
367
+ if (SRC_IGNORE_SUFFIXES.some(suffix => changedName.endsWith(suffix)))
368
+ return;
369
+ if (SRC_IGNORE_PREFIXES.some(prefix => changedName.startsWith(prefix) || changedName.includes(`/${prefix}`)))
370
+ return;
371
+ debouncedRebuild(`src change: ${changedName}`);
372
+ }
373
+ function setupSourceMonitor() {
374
+ if (!SRC_WATCH_PATH || !isDirectory(SRC_WATCH_PATH)) {
375
+ const detail = CORTEX_REPO
376
+ ? `CORTEX_REPO=${CORTEX_REPO} set but ${SRC_WATCH_PATH} not a directory`
377
+ : 'CORTEX_REPO unset';
378
+ log.warn(`${detail} — src watcher disabled, only .restart trigger available`);
379
+ return null;
380
+ }
381
+ return createResilientWatchMonitor({
382
+ label: `Source ${SRC_WATCH_PATH}`,
383
+ startWatching: () => {
384
+ if (process.platform === 'win32') {
385
+ const watchers = watchTree(SRC_WATCH_PATH, (_event, filename) => handleSourceChange(filename));
386
+ log.info(`Watching src: ${SRC_WATCH_PATH} (per-directory, *.ts, ${watchers.length} dirs)`);
387
+ return watchers;
388
+ }
389
+ const watcher = watch(SRC_WATCH_PATH, { recursive: true }, (_event, filename) => handleSourceChange(filename));
325
390
  log.info(`Watching src: ${SRC_WATCH_PATH} (recursive, *.ts)`);
326
- }
391
+ return [watcher];
392
+ },
393
+ });
394
+ }
395
+ function consumeRestartTrigger() {
396
+ if (!existsSync(RESTART_TRIGGER))
397
+ return;
398
+ try {
399
+ unlinkSync(RESTART_TRIGGER);
327
400
  }
328
- else if (CORTEX_REPO) {
329
- log.warn(`CORTEX_REPO=${CORTEX_REPO} set but ${SRC_WATCH_PATH} not a directory — src watcher disabled`);
401
+ catch { }
402
+ if (CORTEX_REPO) {
403
+ debouncedRebuild('manual trigger (.restart file)');
330
404
  }
331
405
  else {
332
- log.warn('CORTEX_REPO unset — src watcher disabled, only .restart trigger available');
406
+ debouncedRestart('manual trigger (.restart file)');
333
407
  }
334
- // Watch for .restart trigger file
408
+ }
409
+ function setupRestartTriggerMonitor() {
335
410
  const triggerDir = path.dirname(RESTART_TRIGGER);
336
411
  const triggerName = path.basename(RESTART_TRIGGER);
337
- const triggerWatcher = watch(triggerDir, (eventType, filename) => {
338
- if (filename === triggerName && existsSync(RESTART_TRIGGER)) {
339
- try {
340
- unlinkSync(RESTART_TRIGGER);
341
- }
342
- catch { }
343
- if (CORTEX_REPO) {
344
- debouncedRebuild('manual trigger (.restart file)');
345
- }
346
- else {
347
- debouncedRestart('manual trigger (.restart file)');
348
- }
349
- }
412
+ return createResilientWatchMonitor({
413
+ label: `Restart trigger ${RESTART_TRIGGER}`,
414
+ startWatching: () => {
415
+ const watcher = watch(triggerDir, (_event, filename) => {
416
+ if (filename && String(filename) === triggerName)
417
+ consumeRestartTrigger();
418
+ });
419
+ log.info(`Watching for restart trigger: ${RESTART_TRIGGER}`);
420
+ return [watcher];
421
+ },
422
+ poll: consumeRestartTrigger,
423
+ });
424
+ }
425
+ function fileStamp(filePath) {
426
+ try {
427
+ const stat = statSync(filePath);
428
+ return `${stat.mtimeMs}:${stat.size}`;
429
+ }
430
+ catch {
431
+ return null;
432
+ }
433
+ }
434
+ function startEnvWatcher(envDir, envName, onChange) {
435
+ const watcher = watch(envDir, (_event, filename) => {
436
+ if (filename && String(filename) === envName)
437
+ onChange();
350
438
  });
351
- watchers.push(triggerWatcher);
352
- log.info(`Watching for restart trigger: ${RESTART_TRIGGER}`);
353
- // Watch .env (parent dir, since editors often replace the file atomically)
439
+ log.info(`Watching env file: ${ENV_FILE}`);
440
+ return [watcher];
441
+ }
442
+ function setupEnvMonitor() {
354
443
  const envDir = path.dirname(ENV_FILE);
444
+ if (!existsSync(envDir))
445
+ return null;
355
446
  const envName = path.basename(ENV_FILE);
356
- if (existsSync(envDir)) {
357
- const envWatcher = watch(envDir, (eventType, filename) => {
358
- if (filename && String(filename) === envName) {
359
- debouncedRestart('env change (.env)');
360
- }
361
- });
362
- watchers.push(envWatcher);
363
- log.info(`Watching env file: ${ENV_FILE}`);
364
- }
365
- return watchers;
447
+ let observedStamp = fileStamp(ENV_FILE);
448
+ const handleChange = () => {
449
+ observedStamp = fileStamp(ENV_FILE);
450
+ debouncedRestart('env change (.env)');
451
+ };
452
+ const poll = () => {
453
+ const nextStamp = fileStamp(ENV_FILE);
454
+ if (nextStamp === observedStamp)
455
+ return;
456
+ observedStamp = nextStamp;
457
+ debouncedRestart('env change (.env)');
458
+ };
459
+ return createResilientWatchMonitor({
460
+ label: `Environment file ${ENV_FILE}`,
461
+ startWatching: () => startEnvWatcher(envDir, envName, handleChange),
462
+ poll,
463
+ });
464
+ }
465
+ function setupWatchers() {
466
+ const monitors = [setupRestartTriggerMonitor(), setupEnvMonitor()];
467
+ const sourceMonitor = setupSourceMonitor();
468
+ if (sourceMonitor)
469
+ monitors.push(sourceMonitor);
470
+ return monitors.filter((monitor) => monitor !== null);
366
471
  }
367
472
  function debouncedRestart(reason) {
368
473
  if (restartTimer)
@@ -550,6 +655,10 @@ async function runRebuildPipeline(reason) {
550
655
  }
551
656
  }
552
657
  // --- Graceful Shutdown ---
658
+ function closeWatchMonitors() {
659
+ for (const monitor of watchMonitors.splice(0))
660
+ monitor.close();
661
+ }
553
662
  function setupShutdown() {
554
663
  const shutdown = async (signal) => {
555
664
  if (shuttingDown)
@@ -557,6 +666,7 @@ function setupShutdown() {
557
666
  shuttingDown = true;
558
667
  log.info(`Received ${signal}, shutting down...`);
559
668
  cancelPendingTimers();
669
+ closeWatchMonitors();
560
670
  await stopChild();
561
671
  log.info('Daemon stopped.');
562
672
  process.exit(0);
@@ -585,45 +695,36 @@ function releaseSingletonLock() {
585
695
  }
586
696
  catch { }
587
697
  }
588
- function main() {
589
- // Recursion guard: if log.error() itself throws (e.g. EPIPE on a broken stderr),
590
- // the uncaughtException handler would be re-entered, causing an infinite loop that
591
- // fills the log file and the disk. This flag breaks that cycle.
592
- let inExceptionHandler = false;
593
- process.on('uncaughtException', (err) => {
594
- if (inExceptionHandler)
595
- return; // already handling an exception — avoid re-entrant loop
596
- inExceptionHandler = true;
597
- try {
598
- log.error(`uncaughtException: ${err?.stack ?? err}`);
599
- }
600
- catch {
601
- // log.error() itself threw (shouldn't happen after log.ts EPIPE fix, but guard anyway)
602
- }
603
- finally {
604
- inExceptionHandler = false;
605
- }
606
- });
607
- process.on('unhandledRejection', (reason) => {
608
- if (inExceptionHandler)
698
+ function setupProcessErrorHandlers() {
699
+ // Prevent log failures from recursively re-entering the process error handlers.
700
+ let handlingError = false;
701
+ const report = (kind, detail) => {
702
+ if (handlingError)
609
703
  return;
610
- inExceptionHandler = true;
704
+ handlingError = true;
611
705
  try {
612
- log.error(`unhandledRejection: ${reason instanceof Error ? reason.stack : String(reason)}`);
706
+ log.error(`${kind}: ${String(detail)}`);
613
707
  }
614
708
  catch {
615
- // log.error() itself threw
709
+ // The logger may itself fail on a broken stderr; avoid recursive handling.
616
710
  }
617
711
  finally {
618
- inExceptionHandler = false;
712
+ handlingError = false;
619
713
  }
714
+ };
715
+ process.on('uncaughtException', error => report('uncaughtException', error?.stack ?? error));
716
+ process.on('unhandledRejection', reason => {
717
+ report('unhandledRejection', reason instanceof Error ? reason.stack : reason);
620
718
  });
719
+ }
720
+ function main() {
721
+ setupProcessErrorHandlers();
621
722
  acquireSingletonLock();
622
723
  process.on('exit', releaseSingletonLock);
623
724
  log.info('Cortex Daemon starting...');
624
725
  setupShutdown();
625
- setupWatchers();
626
726
  startChild();
727
+ watchMonitors = setupWatchers();
627
728
  }
628
729
  if (isMainModule(import.meta.url)) {
629
730
  main();
@@ -0,0 +1,8 @@
1
+ import type { AttachmentMeta } from '../domain/ui-service/types.js';
2
+ interface MoveDraftAttachmentsOptions {
3
+ draftUploadId: string | null;
4
+ sessionId: string;
5
+ attachments: AttachmentMeta[];
6
+ }
7
+ export declare function moveDraftAttachments(opts: MoveDraftAttachmentsOptions): Promise<AttachmentMeta[]>;
8
+ export {};
@@ -0,0 +1,83 @@
1
+ // input: draft/session ids, attachment metadata, workspace filesystem
2
+ // output: moveDraftAttachments with canonical truthful aliases
3
+ // pos: Promotes Web draft uploads into session storage
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
+ import * as path from 'node:path';
6
+ import { promises as fs } from 'node:fs';
7
+ import { createLogger } from '../core/log.js';
8
+ import { WORKSPACE_DIR, resolveWorkspaceRelPath } from '../core/paths.js';
9
+ const log = createLogger('draft-attachments');
10
+ const ATTACHMENTS_DIR = path.resolve(WORKSPACE_DIR, 'attachments');
11
+ const SAFE_BUCKET_ID = /^[A-Za-z0-9_-]+$/;
12
+ function bucketDirectory(id) {
13
+ if (!SAFE_BUCKET_ID.test(id))
14
+ return null;
15
+ const directory = path.resolve(ATTACHMENTS_DIR, id);
16
+ return path.dirname(directory) === ATTACHMENTS_DIR ? directory : null;
17
+ }
18
+ function resolveCandidate(draftUploadId, sessionId, attachment) {
19
+ const draftDir = bucketDirectory(draftUploadId);
20
+ const sessionDir = bucketDirectory(sessionId);
21
+ const prefix = `workspace/attachments/${draftUploadId}/`;
22
+ if (!draftDir || !sessionDir || !attachment.path.startsWith(prefix))
23
+ return null;
24
+ const fileName = attachment.path.slice(prefix.length);
25
+ if (!fileName || path.basename(fileName) !== fileName || fileName === '.' || fileName === '..')
26
+ return null;
27
+ const source = resolveWorkspaceRelPath(attachment.path);
28
+ if (!source || path.dirname(source) !== draftDir)
29
+ return null;
30
+ return {
31
+ source,
32
+ destination: path.join(sessionDir, fileName),
33
+ promotedAlias: `workspace/attachments/${sessionId}/${fileName}`,
34
+ };
35
+ }
36
+ async function isRegularFile(filename) {
37
+ try {
38
+ const stat = await fs.lstat(filename);
39
+ return stat.isFile() && !stat.isSymbolicLink();
40
+ }
41
+ catch {
42
+ return false;
43
+ }
44
+ }
45
+ async function promoteCandidate(candidate) {
46
+ if (!await isRegularFile(candidate.source))
47
+ return { kind: 'drop' };
48
+ try {
49
+ await fs.mkdir(path.dirname(candidate.destination), { recursive: true });
50
+ await fs.link(candidate.source, candidate.destination);
51
+ }
52
+ catch {
53
+ return await isRegularFile(candidate.source) ? { kind: 'retain' } : { kind: 'drop' };
54
+ }
55
+ if (!await isRegularFile(candidate.destination)) {
56
+ await fs.unlink(candidate.destination).catch(() => { });
57
+ return await isRegularFile(candidate.source) ? { kind: 'retain' } : { kind: 'drop' };
58
+ }
59
+ await fs.unlink(candidate.source).catch((error) => {
60
+ log.warn(`Promoted draft attachment but could not remove source: ${error.message}`);
61
+ });
62
+ return { kind: 'promoted', alias: candidate.promotedAlias };
63
+ }
64
+ export async function moveDraftAttachments(opts) {
65
+ if (!opts.draftUploadId || opts.attachments.length === 0)
66
+ return opts.attachments;
67
+ const outcomes = new Map();
68
+ const result = [];
69
+ for (const attachment of opts.attachments) {
70
+ const candidate = resolveCandidate(opts.draftUploadId, opts.sessionId, attachment);
71
+ if (!candidate)
72
+ continue;
73
+ if (!outcomes.has(candidate.source)) {
74
+ outcomes.set(candidate.source, await promoteCandidate(candidate));
75
+ }
76
+ const outcome = outcomes.get(candidate.source);
77
+ if (outcome.kind === 'promoted')
78
+ result.push({ ...attachment, path: outcome.alias });
79
+ else if (outcome.kind === 'retain')
80
+ result.push(attachment);
81
+ }
82
+ return result;
83
+ }
@@ -18,11 +18,7 @@ export interface FeishuCliDeps {
18
18
  /** dotenv file that a successful login flips to FEISHU_AUTH_MODE=user (default: CONFIG_DIR/.env). */
19
19
  envFile?: string;
20
20
  }
21
- /**
22
- * Idempotently set KEY=value in a dotenv file: rewrite the line if KEY already
23
- * exists, append it otherwise, creating the file (and parent dir) when missing.
24
- * The rest of the file is preserved so hand-written credentials stay intact.
25
- */
26
- export declare function upsertEnvVar(file: string, key: string, value: string): void;
21
+ /** Serialize dotenv read-modify-write across processes so unrelated settings survive. */
22
+ export declare function upsertEnvVar(file: string, key: string, value: string): Promise<void>;
27
23
  export declare function getFeishuHelp(): string;
28
24
  export declare function cmdFeishu(args: string[], deps?: FeishuCliDeps): Promise<CliResult>;
@@ -1,36 +1,31 @@
1
- // input: readline, dotenv, @core/utils (CONFIG_DIR), feishu/user-auth
2
- // output: cmdFeishu() — `cortex feishu login | status | logout` (user_access_token lifecycle)
3
- // pos: CLI for FEISHU_AUTH_MODE=user. login runs the OAuth device-authorization flow (print a
4
- // URL, poll for the token); --manual keeps the legacy paste-the-code flow. status/logout
5
- // inspect/clear the on-disk token. Dispatched from cli.ts.
1
+ // input: readline, dotenv, atomic mutation, Feishu user auth
2
+ // output: cmdFeishu and serialized dotenv updates
3
+ // pos: Feishu user-login command-line adapter
6
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
7
5
  import * as readline from 'readline';
8
6
  import * as path from 'path';
9
7
  import * as dotenv from 'dotenv';
10
- import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
8
+ import { mutateFileAtomically } from '../core/atomic-write.js';
11
9
  import { CONFIG_DIR } from '../core/utils.js';
12
10
  import { buildAuthorizeUrl, parseCodeFromInput, exchangeCode, requestDeviceAuthorization, pollDeviceToken, saveUserToken, loadUserToken, clearUserToken, userTokenPath, DEFAULT_DOC_SCOPE, } from '../domain/mcp/feishu/user-auth.js';
13
- /**
14
- * Idempotently set KEY=value in a dotenv file: rewrite the line if KEY already
15
- * exists, append it otherwise, creating the file (and parent dir) when missing.
16
- * The rest of the file is preserved so hand-written credentials stay intact.
17
- */
18
- export function upsertEnvVar(file, key, value) {
11
+ function upsertEnvContents(existing, key, value) {
19
12
  const line = `${key}=${value}`;
20
- const existing = existsSync(file) ? readFileSync(file, 'utf8') : '';
21
13
  const lines = existing === '' ? [] : existing.replace(/\n+$/, '').split('\n');
22
14
  const re = new RegExp(`^\\s*${key}\\s*=`);
23
- const idx = lines.findIndex((l) => re.test(l));
15
+ const idx = lines.findIndex(candidate => re.test(candidate));
24
16
  if (idx >= 0) {
25
17
  if (lines[idx] === line)
26
- return; // already set — skip the write
18
+ return existing;
27
19
  lines[idx] = line;
28
20
  }
29
21
  else {
30
22
  lines.push(line);
31
23
  }
32
- mkdirSync(path.dirname(file), { recursive: true });
33
- writeFileSync(file, lines.join('\n') + '\n');
24
+ return lines.join('\n') + '\n';
25
+ }
26
+ /** Serialize dotenv read-modify-write across processes so unrelated settings survive. */
27
+ export function upsertEnvVar(file, key, value) {
28
+ return mutateFileAtomically(file, existing => upsertEnvContents(existing, key, value), { mode: 0o600 });
34
29
  }
35
30
  export function getFeishuHelp() {
36
31
  return [
@@ -93,11 +88,11 @@ export async function cmdFeishu(args, deps = {}) {
93
88
  // restart — without it the login succeeds but the MCP server keeps bot identity.
94
89
  // Skipped when loadDotenv is off (tests) so the real .env is never touched there.
95
90
  const envFile = deps.envFile ?? path.join(CONFIG_DIR, '.env');
96
- const persistAuthMode = () => {
91
+ const persistAuthMode = async () => {
97
92
  if (deps.loadDotenv === false)
98
93
  return false;
99
94
  try {
100
- upsertEnvVar(envFile, 'FEISHU_AUTH_MODE', 'user');
95
+ await upsertEnvVar(envFile, 'FEISHU_AUTH_MODE', 'user');
101
96
  return true;
102
97
  }
103
98
  catch {
@@ -149,7 +144,7 @@ export async function cmdFeishu(args, deps = {}) {
149
144
  try {
150
145
  const tok = await exchangeCode({ appId, appSecret, code, redirectUri, domain, fetchImpl: deps.fetchImpl, now: deps.now });
151
146
  saveUserToken(tok, tokenFile);
152
- return successResult(tok, persistAuthMode());
147
+ return successResult(tok, await persistAuthMode());
153
148
  }
154
149
  catch (e) {
155
150
  return { exitCode: 1, stdout: '', stderr: `Login failed: ${e.message}\n` };
@@ -181,7 +176,7 @@ export async function cmdFeishu(args, deps = {}) {
181
176
  onPending: () => process.stdout.write('.'),
182
177
  });
183
178
  saveUserToken(tok, tokenFile);
184
- return successResult(tok, persistAuthMode());
179
+ return successResult(tok, await persistAuthMode());
185
180
  }
186
181
  catch (e) {
187
182
  return { exitCode: 1, stdout: '', stderr: `\nLogin failed: ${e.message}\n` };
@@ -1,6 +1,6 @@
1
- // input: defaults, filesystem, MCP builders, platform setup
2
- // output: runInit and initialization helpers
3
- // pos: Initializes Cortex home and runtime configuration
1
+ // input: defaults, filesystem, MCP builders, setup
2
+ // output: runInit and runtime configuration
3
+ // pos: Initializes Cortex home and config surfaces
4
4
  // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
5
  import { mkdirSync, writeFileSync, copyFileSync, existsSync, readFileSync, readdirSync } from 'fs';
6
6
  import { randomBytes } from 'crypto';
@@ -12,7 +12,7 @@ import { createInterface } from 'readline/promises';
12
12
  import { stdin as processStdin } from 'process';
13
13
  import * as clack from '@clack/prompts';
14
14
  import * as yaml from 'yaml';
15
- import { buildCoreConfig, buildFullConfig, buildManagerQaConfig, buildTasksConfig, buildThreadConfig, buildTuiConfig, } from '../core/config-generator.js';
15
+ import { buildBenchmarkThreadConfig, buildCoreConfig, buildEmptyConfig, buildFullConfig, buildManagerQaConfig, buildTasksConfig, buildThreadConfig, buildTuiConfig, } from '../core/config-generator.js';
16
16
  import { discoverEndpoints, writeMergedGatewayYaml, validateProfilesAgainstGateway } from '../core/gateway-generator.js';
17
17
  import { generateProfiles, writeProfilesJson, listChoices } from '../core/profile-generator.js';
18
18
  import { mergeThreadTemplates } from '../domain/threads/index.js';
@@ -1117,6 +1117,8 @@ function writeMcpConfigs(configDir) {
1117
1117
  ['mcp-config-tasks.json', buildTasksConfig(INSTALL_ROOT)],
1118
1118
  ['mcp-config-manager-qa.json', buildManagerQaConfig(INSTALL_ROOT)],
1119
1119
  ['mcp-config-thread.json', buildThreadConfig(INSTALL_ROOT)],
1120
+ ['mcp-config-empty.json', buildEmptyConfig()],
1121
+ ['mcp-config-benchmark-thread.json', buildBenchmarkThreadConfig(INSTALL_ROOT)],
1120
1122
  ['mcp-config-tui.json', buildTuiConfig(INSTALL_ROOT)],
1121
1123
  ];
1122
1124
  for (const [fileName, config] of configs) {
@@ -6,20 +6,14 @@ export interface StartUiHttpOptions {
6
6
  uiService: UiService;
7
7
  /** Token accessor the server accepts. Defaults to getClientToken (the shared secret clients carry). */
8
8
  getToken?: () => string;
9
- /** Env to read the gate/port from. Defaults to process.env (injectable for tests). */
9
+ /** Env to read the startup gate/port from. Defaults to process.env (injectable for tests). */
10
10
  env?: NodeJS.ProcessEnv;
11
11
  /**
12
12
  * Directory of the built SPA to serve for non-tRPC paths. When omitted, resolved from
13
13
  * CORTEX_UI_SPA_DIR else the monorepo web/dist. Absent/missing on disk → 404 stub.
14
14
  */
15
15
  spaDir?: string;
16
- /**
17
- * Explicit CORS allow-list forwarded to the transport-host. When omitted, the list is parsed
18
- * from the CORTEX_UI_CORS_ORIGINS env var (comma-separated; entries trimmed, empties dropped).
19
- * Env-driven so the running-server path (agent-server) can enable CORS for the Tauri desktop
20
- * webview (e.g. tauri://localhost) with no code change — just the env var. Absent/empty → no
21
- * CORS headers.
22
- */
16
+ /** Explicit static CORS allow-list override; production reads runtime settings per request. */
23
17
  corsOrigins?: string[];
24
18
  /**
25
19
  * Explicit Cloudflare Access JWT verifier forwarded to the transport-host (the browser auth path).