@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,24 +1,6 @@
1
- // input: a real UiService (injected) + env (CORTEX_UI_HTTP gate, CORTEX_UI_PORT,
2
- // CORTEX_UI_CORS_ORIGINS, CORTEX_UI_SPA_DIR)
3
- // output: startUiHttpServer(opts) -> UiHttpServer | null — builds the tRPC AppRouter over the
4
- // injected UiService and starts the Web UI HTTP+SSE transport-host behind the dual-path
5
- // auth gate — x-cortex-token (getClientToken) OR a Cloudflare Access JWT verifier built
6
- // from env (accessVerifierFromEnv) — bound 127.0.0.1. Returns null (clean skip) when the
7
- // env gate is off. Same-origin: serves the built SPA (web/dist) and /trpc on one port.
8
- // pos: Web UI wiring, in-core (entry layer). The only place that binds the AppRouter
9
- // (createAppRouter, domain/ui-service) to the transport-host (createUiHttpServer,
10
- // platform/ui-http) — kept out of both so the router stays transport-agnostic and the
11
- // transport-host stays router-agnostic; the wiring sits in entry, the one layer allowed to
12
- // depend on both domain and platform. app.ts loads this on demand via a CORTEX_UI_HTTP-gated
13
- // dynamic import (entry/ui-http-gate.ts), so @trpc/server + jose stay runtime-lazy, and
14
- // closes the returned handle on shutdown. SPA dir: opts.spaDir ?? CORTEX_UI_SPA_DIR ??
15
- // web/dist resolved relative to this module's compiled location (installed-package root,
16
- // else the monorepo repo-root — see defaultSpaDir).
17
- // CORS: resolves the transport-host's allow-list from opts.corsOrigins else the
18
- // CORTEX_UI_CORS_ORIGINS env var (comma-separated) — lets the Tauri desktop webview reach
19
- // tRPC directly. Also mounts the frontend-OTA custom routes (createOtaRoutes(spaDir)) so the
20
- // desktop shell can self-update its SPA (disabled cleanly when the SPA is not built), and
21
- // the app-update manifest route (createAppUpdateRoutes) for native shell self-update.
1
+ // input: UiService, runtime settings, HTTP/auth/static dependencies
2
+ // output: optional Web UI HTTP/SSE server with live CORS wiring
3
+ // pos: Entry-layer Web UI transport composition
22
4
  // >>> If I am updated, update CORTEX.md <<<
23
5
  import * as path from 'node:path';
24
6
  import * as fs from 'node:fs';
@@ -32,6 +14,7 @@ import { createAppUpdateRoutes } from '../platform/ui-http/app-update.js';
32
14
  import { accessVerifierFromEnv } from '../platform/ui-http/access-jwt.js';
33
15
  import { getClientToken } from '../core/auth.js';
34
16
  import { createLogger } from '../core/log.js';
17
+ import { getSettings } from '../core/settings.js';
35
18
  import { WORKSPACE_DIR, resolveWorkspaceRelPath } from '../core/paths.js';
36
19
  const log = createLogger('ui-http');
37
20
  /** Default TCP port for the Web UI tRPC endpoint (loopback-only; exposure is via a tunnel). */
@@ -64,17 +47,6 @@ function defaultSpaDir() {
64
47
  return undefined;
65
48
  }
66
49
  }
67
- /**
68
- * Parse a comma-separated origin list (from CORTEX_UI_CORS_ORIGINS) into a trimmed, empties-dropped
69
- * array. Returns undefined when the raw value is absent or yields no entries, so the transport-host
70
- * keeps its backward-compatible "no CORS headers" default rather than an empty allow-list.
71
- */
72
- function parseCorsOrigins(raw) {
73
- if (!raw)
74
- return undefined;
75
- const origins = raw.split(',').map((o) => o.trim()).filter((o) => o.length > 0);
76
- return origins.length > 0 ? origins : undefined;
77
- }
78
50
  // ── File upload route (15a attachments) ───────────────────────────────────────
79
51
  const ATTACHMENTS_DIR = path.join(WORKSPACE_DIR, 'attachments');
80
52
  const UPLOAD_PATH = '/api/attachments/upload';
@@ -259,12 +231,13 @@ export function startUiHttpServer(opts) {
259
231
  const parsedPort = parseInt(env.CORTEX_UI_PORT ?? '', 10);
260
232
  const port = Number.isNaN(parsedPort) ? DEFAULT_UI_PORT : parsedPort;
261
233
  const router = createAppRouter(opts.uiService);
262
- const corsOrigins = opts.corsOrigins ?? parseCorsOrigins(env.CORTEX_UI_CORS_ORIGINS);
234
+ const corsOrigins = opts.corsOrigins ?? (() => getSettings().uiCorsOrigins);
235
+ const initialCorsOrigins = typeof corsOrigins === 'function' ? corsOrigins() : corsOrigins;
263
236
  const spaDir = opts.spaDir ?? env.CORTEX_UI_SPA_DIR ?? defaultSpaDir();
264
237
  const verifyAccessJwt = opts.verifyAccessJwt ?? accessVerifierFromEnv(env);
265
238
  log.info(`Web UI enabled — starting tRPC HTTP+SSE on 127.0.0.1:${port}` +
266
239
  (spaDir ? ` (SPA: ${spaDir})` : ' (SPA: not built — non-tRPC paths 404)') +
267
- (corsOrigins ? ` (CORS allow-list: ${corsOrigins.join(', ')})` : '') +
240
+ (initialCorsOrigins.length > 0 ? ` (CORS allow-list: ${initialCorsOrigins.join(', ')})` : '') +
268
241
  (verifyAccessJwt ? ' (Cloudflare Access JWT path enabled)' : ''));
269
242
  return createUiHttpServer({
270
243
  router,
@@ -1,11 +1,12 @@
1
- // input: EventBus (event-bus.ts), CortexEvent (event-types.ts)
2
- // output: createEventLogger — writes events to daily rolling jsonl files
3
- // pos: events/ layer, depends on event-bus + event-types + core/async-mutex
1
+ // input: EventBus, CortexEvent, runtime settings
2
+ // output: createEventLogger with hot-toggleable JSONL persistence
3
+ // pos: Settings-gated event log writer
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import fs from 'node:fs/promises';
6
6
  import path from 'node:path';
7
7
  import { AsyncMutex } from '../core/async-mutex.js';
8
8
  import { DATA_DIR } from '../core/paths.js';
9
+ import { getSettings } from '../core/settings.js';
9
10
  // ── Constants ────────────────────────────────────────────────────────────────
10
11
  const DEFAULT_BUFFER_SIZE = 1024;
11
12
  const FLUSH_INTERVAL_MS = 100;
@@ -34,7 +35,6 @@ const TRANSIENT_EVENTS = new Set([
34
35
  // ── Implementation ────────────────────────────────────────────────────────────
35
36
  export function createEventLogger(bus, opts) {
36
37
  const bufferSize = opts?.bufferSize ?? DEFAULT_BUFFER_SIZE;
37
- const disabled = process.env.CORTEX_EVENT_LOG === 'off';
38
38
  const logDir = opts?.logDir ?? path.join(DATA_DIR, 'logs', 'events');
39
39
  let buffer = [];
40
40
  let seq = 0;
@@ -46,7 +46,7 @@ export function createEventLogger(bus, opts) {
46
46
  return new Date().toISOString().slice(0, 10).replace(/-/g, '');
47
47
  }
48
48
  function onEvent(e) {
49
- if (disabled)
49
+ if (!getSettings().eventLog)
50
50
  return;
51
51
  // Skip meta-events to prevent re-entrant backpressure loops (see META_EVENTS comment above)
52
52
  if (META_EVENTS.has(e.type))
@@ -84,7 +84,7 @@ export function createEventLogger(bus, opts) {
84
84
  }
85
85
  }
86
86
  async function flushNow() {
87
- if (disabled)
87
+ if (!getSettings().eventLog)
88
88
  return;
89
89
  // Snapshot buffer outside the mutex to minimise lock hold time
90
90
  if (buffer.length === 0)
@@ -137,13 +137,11 @@ export function createEventLogger(bus, opts) {
137
137
  return flushNow();
138
138
  }
139
139
  // ── Wire up ────────────────────────────────────────────────────────────────
140
- if (!disabled) {
141
- bus.subscribe('*', onEvent);
142
- flushTimer = setInterval(() => { void flushNow(); }, FLUSH_INTERVAL_MS);
143
- // Prevent the timer from keeping the process alive after bus.close()
144
- if (flushTimer.unref)
145
- flushTimer.unref();
146
- }
140
+ bus.subscribe('*', onEvent);
141
+ flushTimer = setInterval(() => { void flushNow(); }, FLUSH_INTERVAL_MS);
142
+ // Prevent the timer from keeping the process alive after bus.close()
143
+ if (flushTimer.unref)
144
+ flushTimer.unref();
147
145
  bus.registerCloseHook(close);
148
146
  return { close };
149
147
  }
@@ -1,4 +1,5 @@
1
- import type { ChatNoticeLevel, SessionContextUsage } from '../core/types/agent-types.js';
1
+ import type { AuthNoticeAction, ChatNoticeLevel, SessionContextUsage } from '../core/types/agent-types.js';
2
+ export type AuthErrorKind = 'login_required' | 'oauth_expired' | 'invalid_api_key' | 'unauthorized' | 'invalid_grant';
2
3
  /** All CortexEvent variants. `ts` is ISO-8601, injected by EventBus.publish(). */
3
4
  export type CortexEvent = {
4
5
  type: 'message.received';
@@ -23,6 +24,7 @@ export type CortexEvent = {
23
24
  toolInput?: string;
24
25
  blockId?: string;
25
26
  noticeLevel?: ChatNoticeLevel;
27
+ authAction?: AuthNoticeAction;
26
28
  pending?: boolean;
27
29
  pendingId?: string;
28
30
  attachments?: {
@@ -155,6 +157,20 @@ export type CortexEvent = {
155
157
  seq: number;
156
158
  lines: string[];
157
159
  dropped?: number;
160
+ } | {
161
+ type: 'auth.required';
162
+ ts: string;
163
+ backend: 'claude' | 'pi';
164
+ provider: string;
165
+ authType: 'oauth' | 'api_key' | null;
166
+ kind: AuthErrorKind;
167
+ channel: string | null;
168
+ sessionId: string | null;
169
+ } | {
170
+ type: 'auth.recovered';
171
+ ts: string;
172
+ backend: 'claude' | 'pi';
173
+ provider: string;
158
174
  } | {
159
175
  type: 'thread.created';
160
176
  ts: string;
@@ -199,6 +215,7 @@ export type CortexEvent = {
199
215
  type: 'task.completed';
200
216
  ts: string;
201
217
  taskId: string;
218
+ dispatchGeneration?: string | null;
202
219
  } | {
203
220
  type: 'task.dispatched';
204
221
  ts: string;
@@ -209,6 +226,7 @@ export type CortexEvent = {
209
226
  ts: string;
210
227
  taskId: string;
211
228
  reason: string;
229
+ dispatchGeneration?: string | null;
212
230
  } | {
213
231
  type: 'task.unblocked';
214
232
  ts: string;
@@ -1,5 +1,5 @@
1
- // input: ChatNoticeLevel, SessionContextUsage, and system state-change hints
2
- // output: CortexEvent union including context/compact/notices/lifecycle
1
+ // input: ChatNoticeLevel and SessionContextUsage
2
+ // output: CortexEvent with task provenance and auth notice actions
3
3
  // pos: Typed event contract for the shared EventBus
4
- // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
5
  export {};
@@ -1,4 +1,4 @@
1
- export type { CortexEvent, CortexEventInput, DistributiveOmit } from './event-types.js';
1
+ export type { AuthErrorKind, CortexEvent, CortexEventInput, DistributiveOmit } from './event-types.js';
2
2
  export { EventBus } from './event-bus.js';
3
3
  export type { Subscription } from './event-bus.js';
4
4
  export { createEventLogger } from './event-logger.js';
@@ -1,6 +1,6 @@
1
1
  // input: event-bus, event-types, event-logger
2
- // output: public API for events/ layer
3
- // pos: events/ barrel — import from './index' or './events/index.js'
4
- // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
2
+ // output: public event bus and typed event contracts
3
+ // pos: Public entry point for the events layer
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
5
  export { EventBus } from './event-bus.js';
6
6
  export { createEventLogger } from './event-logger.js';
@@ -49,13 +49,13 @@ Did this session produce findings, decisions, or changes that future sessions ne
49
49
  Examples of what to record:
50
50
  - A new experiment was launched → update STATUS.md with what's running
51
51
  - A non-obvious fact was discovered ("the dataset is on gpu-server at /data/xxx") → create a K-NNN.md entry so it's indexed
52
- - External resource locations → "The paper source is at ~/papers/conference2026/", "Training data lives on gpu-server:/datasets/dataset-v3/", "Reference implementation at https://github.com/xxx/yyy" — record in STATUS.md or as a knowledge entry
52
+ - External resource locations → "The paper source is at ~/papers/conference2026/", "Training data lives on gpu-server:/datasets/dataset-v3/", "Reference implementation at https://github.com/xxx/yyy" — record as a knowledge entry (K-NNN); durable facts do not go in STATUS.md
53
53
  - A recurring friction was encountered ("the GPU on local always OOMs with batch_size > 32") → append to ISSUES.md
54
54
  - A design decision was made → add to decisions/ directory
55
55
  - A new project dependency or constraint was discovered → update STATUS.md
56
56
 
57
57
  File update rules you MUST respect:
58
- - **STATUS.md** — overwrite mode: replace with latest state, do not append
58
+ - **STATUS.md** — state register (hard cap 80 lines AND 6KB): replace stale lines with the latest state, never append; one line + pointer per change, details live in EXP/K/tasks-archive; adding a line requires checking which old lines expired
59
59
  - **ISSUES.md** — append mode: add new entries at the end, keep history
60
60
  - **knowledge/K-NNN.md** — atomic: one file per knowledge entry, with YAML frontmatter
61
61
  - **knowledge/index.md, experiments/index.md, patterns/index.md** — AUTO-GENERATED, do NOT edit manually
@@ -0,0 +1,193 @@
1
+ #!/usr/bin/env node
2
+ // @cortex-hook-version 2026.8.2
3
+ // input: stdin JSON — Claude Code PreToolUse event payload
4
+ // output: stdout JSON — { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision, permissionDecisionReason }, systemMessage? }
5
+ // pos: PreToolUse hook — intercepts Edit/Write on size-capped context files and
6
+ // enforces their caps (limit table below; rules/status-md.md, rules/issues-md.md,
7
+ // rules/cortex-md.md): deny writes whose result exceeds the caps, unless the
8
+ // write shrinks an already-over-limit file (so cleanup stays possible); warn
9
+ // when approaching the cap. Guarded files:
10
+ // context/projects/<p>/STATUS.md — 80 lines / 6KB (state register)
11
+ // context/projects/<p>/ISSUES.md — 80 lines / 6KB (friction log)
12
+ // CORTEX.md anywhere under a context/ tree — 120 lines / 8KB (injected index)
13
+ // >>> If I am updated, be sure to update my header comment and the CORTEX.md in the same folder <<<
14
+
15
+ import { readFileSync, existsSync } from 'fs';
16
+ import { resolve, sep } from 'path';
17
+
18
+ // ── Constants ──
19
+
20
+ const TOOLS = new Set(['Edit', 'Write']);
21
+
22
+ /** .../context/projects/<name>/<file> */
23
+ function isProjectRootFile(parts, fileName) {
24
+ if (parts[parts.length - 1] !== fileName) return false;
25
+ const projectsIdx = parts.length - 3;
26
+ const contextIdx = parts.length - 4;
27
+ return projectsIdx > 0 && parts[projectsIdx] === 'projects' && parts[contextIdx] === 'context';
28
+ }
29
+
30
+ const LIMIT_RULES = [
31
+ {
32
+ name: 'STATUS.md',
33
+ ruleFile: 'rules/status-md.md',
34
+ matches: (parts) => isProjectRootFile(parts, 'STATUS.md'),
35
+ maxLines: 80,
36
+ maxBytes: 6 * 1024,
37
+ warnLines: 60,
38
+ warnBytes: 4 * 1024,
39
+ capLabel: '80 lines AND 6KB',
40
+ trimAdvice: [
41
+ 'STATUS is a state register, not a changelog. Trim before writing:',
42
+ '- delete entries that no longer affect decisions (their content already lives in tasks-archive / git / EXP records),',
43
+ '- compress each bullet to one line + pointer (task-id / EXP-NNN / K-NNN / DR-NNNN / commit SHA),',
44
+ '- move completion reports to the task note, durable facts to knowledge entries, verdict analysis to the gate artifact.',
45
+ ],
46
+ },
47
+ {
48
+ name: 'ISSUES.md',
49
+ ruleFile: 'rules/issues-md.md',
50
+ matches: (parts) => isProjectRootFile(parts, 'ISSUES.md'),
51
+ maxLines: 80,
52
+ maxBytes: 6 * 1024,
53
+ warnLines: 60,
54
+ warnBytes: 4 * 1024,
55
+ capLabel: '80 lines AND 6KB',
56
+ trimAdvice: [
57
+ 'ISSUES.md is a friction log with <=4-line entries. Trim before writing:',
58
+ '- delete resolved entries outright (no changelog),',
59
+ '- compress each entry to symptom + one-line root cause + pointer (K-NNN / task artifact / EXP-NNN / file:line),',
60
+ '- merge same-cause frictions into one entry.',
61
+ ],
62
+ },
63
+ {
64
+ name: 'CORTEX.md',
65
+ ruleFile: 'rules/cortex-md.md',
66
+ matches: (parts) => parts[parts.length - 1] === 'CORTEX.md' && parts.includes('context'),
67
+ maxLines: 120,
68
+ maxBytes: 8 * 1024,
69
+ warnLines: 90,
70
+ warnBytes: 6656,
71
+ capLabel: '120 lines AND 8KB',
72
+ trimAdvice: [
73
+ 'CORTEX.md is an injected index (truncated at 9500 chars): it answers "what is here, where to look", not the content itself. Trim before writing:',
74
+ '- collapse atomic directories (experiments/ knowledge/ patterns/ decisions/) to one line each pointing at their index.md,',
75
+ '- entry summaries already live in the atomic files and their auto-generated index.md — never duplicate them here,',
76
+ '- keep each index line to one sentence + pointer (<=200 chars).',
77
+ ],
78
+ },
79
+ ];
80
+
81
+ // ── Helpers ──
82
+
83
+ function countLines(content) {
84
+ if (content === '') return 0;
85
+ const chunks = content.split('\n');
86
+ return chunks[chunks.length - 1] === '' ? chunks.length - 1 : chunks.length;
87
+ }
88
+
89
+ /** Compute the content the tool call would leave on disk, or null when indeterminable. */
90
+ function proposedContent(toolName, toolInput, currentContent) {
91
+ if (toolName === 'Write') return typeof toolInput.content === 'string' ? toolInput.content : null;
92
+ // Edit
93
+ const oldString = toolInput.old_string;
94
+ const newString = toolInput.new_string;
95
+ if (typeof oldString !== 'string' || typeof newString !== 'string') return null;
96
+ if (currentContent === null || !currentContent.includes(oldString)) return null; // tool will fail on its own
97
+ return toolInput.replace_all
98
+ ? currentContent.split(oldString).join(newString)
99
+ : currentContent.replace(oldString, newString);
100
+ }
101
+
102
+ function denyReason(rule, lineCount, byteCount) {
103
+ return [
104
+ `${rule.name} write rejected: the result would be ${lineCount} lines / ${byteCount} bytes — the hard cap is ${rule.capLabel} (${rule.ruleFile}).`,
105
+ '',
106
+ ...rule.trimAdvice,
107
+ '',
108
+ 'Writes that shrink an already-over-limit file are allowed — reduce the size, then write.',
109
+ ].join('\n');
110
+ }
111
+
112
+ // ── Main ──
113
+
114
+ function main() {
115
+ let input = '';
116
+ try {
117
+ input = readFileSync(0, 'utf8');
118
+ } catch {
119
+ return;
120
+ }
121
+ if (!input.trim()) return;
122
+
123
+ let payload;
124
+ try {
125
+ payload = JSON.parse(input);
126
+ } catch {
127
+ return;
128
+ }
129
+
130
+ if (!TOOLS.has(payload.tool_name)) return;
131
+
132
+ const toolInput = payload.tool_input || {};
133
+ const filePath = toolInput.file_path || '';
134
+ if (!filePath) return;
135
+
136
+ const cwd = payload.cwd || process.cwd();
137
+ const parts = resolve(cwd, filePath).split(sep);
138
+ const rule = LIMIT_RULES.find((r) => r.matches(parts));
139
+ if (!rule) return;
140
+
141
+ const absPath = resolve(cwd, filePath);
142
+ let currentContent = null;
143
+ if (existsSync(absPath)) {
144
+ try {
145
+ currentContent = readFileSync(absPath, 'utf8');
146
+ } catch {
147
+ return;
148
+ }
149
+ }
150
+
151
+ const proposed = proposedContent(payload.tool_name, toolInput, currentContent);
152
+ if (proposed === null) return;
153
+
154
+ const lineCount = countLines(proposed);
155
+ const byteCount = Buffer.byteLength(proposed, 'utf8');
156
+ const currentBytes = currentContent === null ? null : Buffer.byteLength(currentContent, 'utf8');
157
+
158
+ if (lineCount > rule.maxLines || byteCount > rule.maxBytes) {
159
+ // Shrink exception: an over-limit file may be reduced step by step.
160
+ if (currentBytes !== null && byteCount < currentBytes) {
161
+ process.stdout.write(JSON.stringify({
162
+ hookSpecificOutput: {
163
+ hookEventName: 'PreToolUse',
164
+ permissionDecision: 'allow',
165
+ permissionDecisionReason: `Still over the ${rule.name} cap (${lineCount} lines / ${byteCount} bytes > ${rule.capLabel}) but shrinking — keep trimming to within the limit.`,
166
+ },
167
+ systemMessage: `${rule.name} is still over the ${rule.capLabel} cap (${lineCount} lines / ${byteCount} bytes). This write shrinks it and is allowed — keep trimming.`,
168
+ }));
169
+ return;
170
+ }
171
+ process.stdout.write(JSON.stringify({
172
+ hookSpecificOutput: {
173
+ hookEventName: 'PreToolUse',
174
+ permissionDecision: 'deny',
175
+ permissionDecisionReason: denyReason(rule, lineCount, byteCount),
176
+ },
177
+ }));
178
+ return;
179
+ }
180
+
181
+ if (lineCount >= rule.warnLines || byteCount >= rule.warnBytes) {
182
+ process.stdout.write(JSON.stringify({
183
+ hookSpecificOutput: {
184
+ hookEventName: 'PreToolUse',
185
+ permissionDecision: 'allow',
186
+ permissionDecisionReason: `${rule.name} approaching its cap (${lineCount} lines / ${byteCount} bytes; hard cap ${rule.capLabel}) — trim proactively.`,
187
+ },
188
+ systemMessage: `${rule.name} is approaching its cap (${lineCount} lines / ${byteCount} bytes; hard cap ${rule.capLabel}). Trim proactively (${rule.ruleFile}).`,
189
+ }));
190
+ }
191
+ }
192
+
193
+ main();
@@ -1,11 +1,6 @@
1
- // input: { sessionId, filePath, fileName?, caption? } + fs + conversation history + session-events bus
2
- // output: sendAgentFile — deliver an agent-produced file into a web chat session (20a)
3
- // pos: orch/ — the assistant-side mirror of the user composer's upload (15a). Copies the file into
4
- // the session's workspace/outputs/<sessionId>/ area (a stable, download-safe location under
5
- // WORKSPACE_DIR), records it as an assistant message carrying file attachments (so it survives
6
- // reload via sessions.transcript), and publishes a `session.message` event (so the live web UI
7
- // renders the file card immediately). Invoked by the daemon `/webhook/ui-file` route on behalf
8
- // of the web-only `send_file` MCP tool. Deps are injectable for tests.
1
+ // input: file args, filesystem, conversation history, session events
2
+ // output: sendAgentFile and safe workspace copy metadata
3
+ // pos: delivers agent-produced files into Web chat sessions
9
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
10
5
  import * as path from 'path';
11
6
  import { promises as fs } from 'fs';
@@ -37,9 +32,43 @@ export function classifyAttachment(mimeType) {
37
32
  return 'video';
38
33
  return 'file';
39
34
  }
40
- /** Sanitize a filename: keep alphanumeric, dot, hyphen, underscore; replace the rest. */
41
- function sanitizeFilename(name) {
42
- return name.replace(/[^A-Za-z0-9._-]/g, '_').replace(/^_+/, '').substring(0, 200) || 'file';
35
+ const MAX_FILENAME_BYTES = 200;
36
+ /** Bound a Unicode filename without splitting code points, retaining a short extension when possible. */
37
+ function truncateDisplayFilename(name) {
38
+ if (Buffer.byteLength(name) <= MAX_FILENAME_BYTES)
39
+ return name;
40
+ const ext = path.extname(name);
41
+ const keptExt = Buffer.byteLength(ext) <= 32 ? ext : '';
42
+ const stem = keptExt ? name.slice(0, -keptExt.length) : name;
43
+ let result = '';
44
+ let bytes = Buffer.byteLength(keptExt);
45
+ for (const char of stem) {
46
+ const charBytes = Buffer.byteLength(char);
47
+ if (bytes + charBytes > MAX_FILENAME_BYTES)
48
+ break;
49
+ result += char;
50
+ bytes += charBytes;
51
+ }
52
+ return `${result || 'file'}${keptExt}`;
53
+ }
54
+ /** Preserve a safe Unicode leaf name for display and client-side downloads. */
55
+ function sanitizeDisplayFilename(name) {
56
+ const leaf = name.replace(/\\/g, '/').split('/').pop() ?? '';
57
+ const cleaned = leaf.replace(/[\u0000-\u001F\u007F]/g, '_').trim();
58
+ if (!cleaned || cleaned === '.' || cleaned === '..')
59
+ return 'file';
60
+ return truncateDisplayFilename(cleaned);
61
+ }
62
+ /** Derive a narrow ASCII-only basename used solely for internal workspace storage. */
63
+ function sanitizeStorageFilename(displayName) {
64
+ const ext = path.extname(displayName);
65
+ const safeExt = /^\.[A-Za-z0-9]{1,16}$/.test(ext) ? ext : '';
66
+ const stem = safeExt ? displayName.slice(0, -ext.length) : displayName;
67
+ const asciiStem = stem
68
+ .replace(/[^A-Za-z0-9._-]/g, '_')
69
+ .replace(/^[._-]+|[._-]+$/g, '');
70
+ const safeStem = asciiStem || 'file';
71
+ return `${safeStem.slice(0, MAX_FILENAME_BYTES - safeExt.length)}${safeExt}`;
43
72
  }
44
73
  /** Find an available filename in `dir`: on collision try `name_1`, `name_2`, … */
45
74
  async function resolveAvailablePath(dir, base) {
@@ -78,13 +107,14 @@ export async function copyFileIntoOutputs(a) {
78
107
  }
79
108
  if (!stat.isFile())
80
109
  throw new Error(`Not a file: ${resolvedSrc}`);
81
- const baseName = sanitizeFilename(a.fileName || path.basename(resolvedSrc));
110
+ const displayName = sanitizeDisplayFilename(a.fileName || path.basename(resolvedSrc));
111
+ const storageName = sanitizeStorageFilename(displayName);
82
112
  const dir = path.join(OUTPUTS_DIR, a.sessionId);
83
113
  await fs.mkdir(dir, { recursive: true });
84
- const { destPath, finalName } = await resolveAvailablePath(dir, baseName);
114
+ const { destPath, finalName } = await resolveAvailablePath(dir, storageName);
85
115
  await fs.copyFile(resolvedSrc, destPath);
86
116
  const outStat = await fs.stat(destPath);
87
- return { relPath: `workspace/outputs/${a.sessionId}/${finalName}`, name: finalName, size: outStat.size };
117
+ return { relPath: `workspace/outputs/${a.sessionId}/${finalName}`, name: displayName, size: outStat.size };
88
118
  }
89
119
  /**
90
120
  * Deliver a file into a web chat session as an agent-sent attachment (20a). Copies the file into the
@@ -1,11 +1,13 @@
1
- import type { PlatformAdapter, IncomingMessage } from '../platform/index.js';
1
+ import type { PlatformAdapter, DownloadedFile, IncomingMessage } from '../platform/index.js';
2
2
  import type { ContextUsage, SessionContextUsage } from '../core/types/agent-types.js';
3
+ import { type TurnMutationRelease } from './turn-mutation-lock.js';
3
4
  type Enqueuer = (channel: string, fn: () => Promise<void>) => boolean;
4
5
  type Tracker = (delta: number) => void;
5
- type Executor = (ctx: AgentRunnerCtx) => Promise<void>;
6
+ type PlatformFileLoader = () => Promise<DownloadedFile[]>;
7
+ type Executor = (ctx: AgentRunnerCtx, mutationRelease: TurnMutationRelease, loadPlatformFiles: PlatformFileLoader) => Promise<void>;
6
8
  /** Attempt mid-turn injection; true ⇒ the message was delivered into the live turn and must NOT
7
9
  * be queued. Injectable so the routing branch is testable without a live backend. */
8
- type Injector = (ctx: AgentRunnerCtx) => Promise<boolean>;
10
+ type Injector = (ctx: AgentRunnerCtx, loadPlatformFiles: PlatformFileLoader) => Promise<boolean>;
9
11
  interface AgentConfig {
10
12
  effectiveMessage: string;
11
13
  profileForRun: string;
@@ -24,6 +26,7 @@ export interface AgentRunnerCtx {
24
26
  hasFiles: boolean;
25
27
  userMessage: string;
26
28
  agentMessage: string;
29
+ mutationRelease?: TurnMutationRelease;
27
30
  }
28
31
  export declare class AgentRunner {
29
32
  readonly _enqueue: Enqueuer;
@@ -38,6 +41,7 @@ export declare class AgentRunner {
38
41
  tryInject?: Injector;
39
42
  });
40
43
  route(ctx: AgentRunnerCtx): Promise<void>;
44
+ private _routeWithAdmission;
41
45
  private _runQueued;
42
46
  /**
43
47
  * Production mid-turn injection: resolve this channel's live turn and session, then hand the