@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,3 +1,9 @@
1
+ // input: message edits, ledger snapshots, PI path registry
2
+ // output: exact transcript rollback and reprocessing
3
+ // pos: Platform message edit retry orchestration
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
+ import { registerPISessionPath } from '../../agent-adapter/index.js';
6
+ import { effectiveBackendSessionId, sessionStore } from '../../store/session-registry-repo.js';
1
7
  import { createLogger } from '../../core/log.js';
2
8
  import { Icons } from '../../core/icons.js';
3
9
  import { conversationLedger } from '../../store/conversation-ledger-repo.js';
@@ -6,6 +12,8 @@ import { deleteSessionAsync } from '../../domain/sessions/session.js';
6
12
  import { resolveBackendForChannel } from '../../domain/agents/index.js';
7
13
  import { conduitQueues } from '../conduit-queue.js';
8
14
  import { supersededEdits } from '../superseded-edits.js';
15
+ import { isTurnTrackingPending, markPendingTurnSuperseded, waitForTurnTracking } from '../lifecycle.js';
16
+ import { acquireTurnMutationLock } from '../turn-mutation-lock.js';
9
17
  const log = createLogger('edit-handler');
10
18
  const DEBOUNCE_MS = 500;
11
19
  // Per-channel debounce timers for rapid edits
@@ -56,86 +64,132 @@ function createEditHandler(deps) {
56
64
  }, DEBOUNCE_MS));
57
65
  };
58
66
  }
59
- async function processEdit({ channel, adapter, originalTs, newText, turnIndex, conversation, deps }) {
60
- const { activeAgents, reprocessMessage, closePooledSession } = deps;
61
- // Resolve the *effective* backend for this channel. conversation.backend was captured at
62
- // initTurnTracking time using the global activeBackend, which doesn't honor channel
63
- // profiles — a channel running profile `execute` (backend=pi) but global backend=claude
64
- // would otherwise be routed to the Claude restore branch and miss the PI backup file.
65
- // resolveBackendForChannel reads the channel's profile and falls back to global if absent.
66
- const backend = resolveBackendForChannel(channel) || conversation.backend;
67
- // Step 1: Cancel any active processing on this channel
68
- if (activeAgents.hasChannel(channel)) {
69
- supersededEdits.mark(channel);
70
- activeAgents.supersedeByChannel(channel, 'edit');
71
- conduitQueues.delete(channel);
72
- log.info('Killed active process for edit retry');
67
+ async function processEdit(args) {
68
+ const snapshotPending = args.deps.isTurnTrackingPending ?? isTurnTrackingPending;
69
+ if (snapshotPending(args.channel)) {
70
+ (args.deps.markPendingTurnSuperseded ?? markPendingTurnSuperseded)(args.channel);
71
+ await (args.deps.waitForTurnTracking ?? waitForTurnTracking)(args.channel);
73
72
  }
74
- // Step 2: Rollback — mark all turns from editedTurnIndex onward as superseded
75
- const rollbackResult = await conversationLedger.rollbackTo(channel, turnIndex);
76
- if (!rollbackResult) {
77
- log.error('Rollback failed — no conversation found');
78
- return;
73
+ const releaseMutation = await acquireTurnMutationLock(args.channel);
74
+ try {
75
+ await processEditLocked(args);
79
76
  }
80
- const { supersededTurns } = rollbackResult;
81
- // Step 3: Delete old response messages + collect superseded status ts for permalink backfill
82
- const supersededStatusTimestamps = await cleanupSupersededMessages(supersededTurns, channel, adapter);
83
- // Step 4: Restore session backup
84
- const sessionId = conversation.sessionId;
85
- let useSessionId = sessionId;
86
- let sessionName = conversation.sessionName;
87
- if (turnIndex === 0) {
88
- // Editing the first message — no prior context to preserve
89
- await deleteSessionAsync(channel, backend);
90
- useSessionId = null;
91
- sessionName = null;
77
+ finally {
78
+ releaseMutation();
92
79
  }
93
- else if (backend === 'pi') {
94
- // PI: restore via file-path-based backup + switch_session on next spawn
95
- const piFile = sessionId ? sessionBackup.findPISessionFile(sessionId) : null;
96
- const restored = piFile ? sessionBackup.restoreSessionFile(piFile, turnIndex) : false;
97
- if (!restored) {
98
- log.warn('No backup found for PI session, falling back to new session');
99
- await deleteSessionAsync(channel, backend);
100
- useSessionId = null;
101
- sessionName = null;
102
- }
80
+ }
81
+ async function restorePIEdit(backendSessionId, backupPath, turnIndex) {
82
+ const recordedFile = backupPath
83
+ ? sessionBackup.sessionFileFromBackupPath(backupPath, turnIndex)
84
+ : null;
85
+ const sessionFile = backupPath || !backendSessionId
86
+ ? recordedFile
87
+ : await sessionBackup.findPISessionFile(backendSessionId);
88
+ const restored = backupPath
89
+ ? await sessionBackup.restoreSessionBackup(backupPath, turnIndex)
90
+ : sessionFile ? await sessionBackup.restoreSessionFile(sessionFile, turnIndex) : false;
91
+ return { restored, sessionFile };
92
+ }
93
+ async function restoreFirstEditedTurn(input, state) {
94
+ let piSessionFile = null;
95
+ if (input.backend === 'pi') {
96
+ piSessionFile = input.targetBackupPath
97
+ ? sessionBackup.sessionFileFromBackupPath(input.targetBackupPath, input.turnIndex)
98
+ : state.backendSessionId ? await sessionBackup.findPISessionFile(state.backendSessionId) : null;
103
99
  }
104
- else {
105
- // Claude / other backends: restore via sessionId-based backup
106
- const restored = sessionId ? sessionBackup.restoreBackup(sessionId, turnIndex) : false;
107
- if (!restored) {
108
- log.warn('No backup found, falling back to new session');
109
- await deleteSessionAsync(channel, backend);
110
- useSessionId = null;
111
- sessionName = null;
112
- }
100
+ await deleteSessionAsync(input.channel, input.backend);
101
+ return { ...state, useSessionId: null, sessionName: null, piSessionFile };
102
+ }
103
+ async function restoreEditedPISession(input, state) {
104
+ const restored = await restorePIEdit(state.backendSessionId, input.targetBackupPath, input.turnIndex);
105
+ const next = { ...state, restored: restored.restored, piSessionFile: restored.sessionFile };
106
+ if (restored.restored)
107
+ return next;
108
+ log.warn('No backup found for PI session, falling back to new session');
109
+ await deleteSessionAsync(input.channel, input.backend);
110
+ return { ...next, useSessionId: null, sessionName: null };
111
+ }
112
+ async function restoreEditedClaudeSession(input, state) {
113
+ const restored = state.backendSessionId
114
+ ? await sessionBackup.restoreBackup(state.backendSessionId, input.turnIndex)
115
+ : false;
116
+ if (restored)
117
+ return { ...state, restored };
118
+ log.warn('No backup found, falling back to new session');
119
+ await deleteSessionAsync(input.channel, input.backend);
120
+ return { ...state, restored, useSessionId: null, sessionName: null };
121
+ }
122
+ async function initialEditRestoreState(conversation) {
123
+ const sessionId = conversation.sessionId;
124
+ const sessionRecord = sessionId ? await sessionStore.getById(sessionId) : null;
125
+ const backendSessionId = sessionRecord ? effectiveBackendSessionId(sessionRecord) : sessionId;
126
+ return {
127
+ backendSessionId, useSessionId: sessionId, sessionName: conversation.sessionName,
128
+ restored: false, piSessionFile: null,
129
+ };
130
+ }
131
+ async function restoreEditedSession(args, backend, targetBackupPath) {
132
+ const state = await initialEditRestoreState(args.conversation);
133
+ const input = { channel: args.channel, backend, turnIndex: args.turnIndex, targetBackupPath };
134
+ if (args.turnIndex === 0)
135
+ return restoreFirstEditedTurn(input, state);
136
+ if (backend === 'pi')
137
+ return restoreEditedPISession(input, state);
138
+ return restoreEditedClaudeSession(input, state);
139
+ }
140
+ function stopActiveEdit(channel, activeAgents) {
141
+ if (!activeAgents.hasChannel(channel))
142
+ return;
143
+ supersededEdits.mark(channel);
144
+ activeAgents.supersedeByChannel(channel, 'edit');
145
+ conduitQueues.delete(channel);
146
+ log.info('Killed active process for edit retry');
147
+ }
148
+ async function rollbackEditedTurn(args) {
149
+ const result = await conversationLedger.rollbackTo(args.channel, args.turnIndex);
150
+ if (!result) {
151
+ log.error('Rollback failed — no conversation found');
152
+ return null;
113
153
  }
114
- // Step 4.5: Tear down any pooled agent process for this channel BEFORE reprocessing.
115
- // Claude CLI runs in stream-json mode as a long-lived process and keeps the conversation
116
- // in memory; restoring the JSONL on disk is a no-op unless we kill that process so the
117
- // next runAgent spawns a fresh one with `--resume <sessionId>`. Without this, the
118
- // edited message is appended as turn N+1 instead of replacing turn N — the symptom the
119
- // user reported. PI spawns a new subprocess per turn, so close is a no-op for it
120
- // (the wiring still calls through but the function-level no-ops handle that branch).
121
- closePooledSession?.(channel, backend);
122
- // Step 5: Cleanup — remove superseded turns from ledger and invalidated backups
123
- await conversationLedger.truncateTurns(channel, turnIndex);
124
- if (backend === 'pi' && sessionId) {
125
- const piFile = sessionBackup.findPISessionFile(sessionId);
126
- if (piFile)
127
- sessionBackup.cleanupBackupsForFile(piFile, turnIndex);
154
+ const targetBackupPath = result.supersededTurns.find((turn) => turn.turnIndex === args.turnIndex)?.backupPath
155
+ ?? args.conversation.turns[args.turnIndex]?.backupPath
156
+ ?? null;
157
+ const supersededStatusTimestamps = await cleanupSupersededMessages(result.supersededTurns, args.channel, args.adapter);
158
+ return { targetBackupPath, supersededStatusTimestamps };
159
+ }
160
+ function registerRestoredEditPath(backend, state, register) {
161
+ if (backend !== 'pi' || !state.restored || !state.backendSessionId || !state.piSessionFile)
162
+ return;
163
+ register(state.backendSessionId, state.piSessionFile);
164
+ }
165
+ function cleanupEditedSession(backend, turnIndex, state) {
166
+ if (backend !== 'pi') {
167
+ sessionBackup.cleanupBackupsAfter(state.backendSessionId ?? '', turnIndex);
168
+ return;
169
+ }
170
+ if (state.piSessionFile && state.restored) {
171
+ sessionBackup.cleanupBackupsForFile(state.piSessionFile, turnIndex);
128
172
  }
129
- else {
130
- sessionBackup.cleanupBackupsAfter(sessionId ?? '', turnIndex);
173
+ else if (state.piSessionFile) {
174
+ sessionBackup.cleanupAllBackupsForFile(state.piSessionFile);
131
175
  }
132
- // Step 6: Re-enqueue the edited message for processing
133
- reprocessMessage(channel, newText, adapter, {
134
- originalTs,
135
- isRetry: true,
136
- sessionId: useSessionId,
137
- sessionName,
138
- supersededStatusTimestamps,
176
+ }
177
+ async function processEditLocked(args) {
178
+ const { channel, originalTs, newText, turnIndex, deps } = args;
179
+ const backend = (deps.resolveBackend ?? resolveBackendForChannel)(channel) || args.conversation.backend;
180
+ stopActiveEdit(channel, deps.activeAgents);
181
+ const rollback = await rollbackEditedTurn(args);
182
+ if (!rollback)
183
+ return;
184
+ const state = await restoreEditedSession(args, backend, rollback.targetBackupPath);
185
+ registerRestoredEditPath(backend, state, deps.registerPISessionPath ?? registerPISessionPath);
186
+ deps.closePooledSession?.(channel, backend);
187
+ await conversationLedger.truncateTurns(channel, turnIndex);
188
+ cleanupEditedSession(backend, turnIndex, state);
189
+ deps.reprocessMessage(channel, newText, args.adapter, {
190
+ originalTs, isRetry: true, sessionId: state.useSessionId,
191
+ sessionName: state.sessionName,
192
+ supersededStatusTimestamps: rollback.supersededStatusTimestamps,
139
193
  });
140
194
  }
141
195
  /**
@@ -1,8 +1,9 @@
1
- // input: MCP sidecars, GitHub push, remote commands, hook events
1
+ // input: sidecars, remote commands, hooks, runtime settings
2
2
  // output: startWebhookServer
3
- // pos: GitHub/task-op/thread-op/manager-qa/hook webhook HTTP entry point
4
- // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
3
+ // pos: Serves task, thread, manager, and hook webhooks
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
5
  import { createLogger } from '../../core/log.js';
6
+ import { getSettings } from '../../core/settings.js';
6
7
  import { AUTH_HEADER, getWebhookToken, timingSafeEqualStr } from '../../core/auth.js';
7
8
  import * as http from 'http';
8
9
  import * as crypto from 'crypto';
@@ -274,7 +275,7 @@ function createWebhookHandler(_options = {}) {
274
275
  }
275
276
  if (!message)
276
277
  return reply({ success: false, error: 'message required' });
277
- const maxDepth = parseInt(process.env.CORTEX_THREAD_MAX_DEPTH || '5', 10) || 5;
278
+ const maxDepth = getSettings().threadMaxDepth;
278
279
  const curDepth = Number(data.depth) || 0;
279
280
  if (curDepth >= maxDepth) {
280
281
  return reply({ success: false, error: `max thread depth (${maxDepth}) reached — cannot spawn nested thread at depth ${curDepth}` });
@@ -14,6 +14,8 @@ export interface RewindDeps {
14
14
  activeAgents: {
15
15
  hasChannel(channel: string): boolean;
16
16
  };
17
+ snapshotPending(channel: string): boolean;
18
+ tryAcquireMutation(channel: string): (() => void) | null;
17
19
  ledger: {
18
20
  getConversation(channel: string): Promise<ChannelConversation | null>;
19
21
  rollbackTo(channel: string, turnIndex: number): Promise<{
@@ -39,14 +41,16 @@ export interface RewindDeps {
39
41
  backendSessionId: string | null;
40
42
  }): Promise<void>;
41
43
  };
42
- backup: Pick<typeof sessionBackup, 'restoreBackup' | 'cleanupBackupsAfter' | 'cleanupAllBackups' | 'findPISessionFile' | 'restoreSessionFile' | 'cleanupBackupsForFile'>;
44
+ backup: Pick<typeof sessionBackup, 'restoreBackup' | 'cleanupBackupsAfter' | 'cleanupAllBackups' | 'findPISessionFile' | 'restoreSessionFile' | 'restoreSessionBackup' | 'sessionFileFromBackupPath' | 'cleanupBackupsForFile' | 'cleanupAllBackupsForFile'>;
43
45
  resolveBackend: (channel: string) => string;
46
+ registerPISessionPath: (sessionId: string, sessionPath: string) => void;
44
47
  closePooledSession: (channel: string, backend: string) => void;
45
48
  send: (opts: {
46
49
  channel: string;
47
50
  text: string;
48
51
  attachments?: AttachmentMeta[];
49
52
  adapter: PlatformAdapter;
53
+ mutationRelease?: () => void;
50
54
  }) => void;
51
55
  publishRewound: (payload: {
52
56
  sessionId: string;
@@ -1,12 +1,8 @@
1
- // input: { sessionId, channel, turnIndex, text, adapter } + ledger/backup/history/session singletons
2
- // output: rewindWebSession — channel-agnostic message edit + rewind for web sessions
3
- // pos: orch/ — the web analogue of routing/edit-handler.ts processEdit: rollback the ledger,
4
- // restore the backend session backup, close the pooled CLI, truncate the display history,
5
- // then re-send the edited text as a genuine user turn. Unlike the Slack path there are no
6
- // platform messages to delete (the web transcript refetches) and the track sessionId /
7
- // channel binding is ALWAYS kept — a turn-0 edit only clears the backendSessionId so the
8
- // backend starts a fresh conversation under the same UI identity.
9
- // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
1
+ // input: rewind request, ledger snapshots, PI path registry
2
+ // output: exact transcript restore and admitted resend result
3
+ // pos: Web message edit rollback orchestration
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
+ import { registerPISessionPath } from '../agent-adapter/index.js';
10
6
  import { createLogger } from '../core/log.js';
11
7
  import { runningExecutions } from '../core/running-executions.js';
12
8
  import { conversationLedger } from '../store/conversation-ledger-repo.js';
@@ -16,15 +12,20 @@ import * as sessionBackup from '../domain/sessions/session-backup.js';
16
12
  import { resolveBackendForChannel, closeSession as closeClaudePooledSession } from '../domain/agents/index.js';
17
13
  import { publishSessionRewound } from './session-events.js';
18
14
  import { sendWebUserMessage } from './session-send.js';
15
+ import { isTurnTrackingPending } from './lifecycle.js';
16
+ import { tryAcquireTurnMutationLock } from './turn-mutation-lock.js';
19
17
  const log = createLogger('session-rewind');
20
18
  function defaultDeps() {
21
19
  return {
22
20
  activeAgents: runningExecutions,
21
+ snapshotPending: isTurnTrackingPending,
22
+ tryAcquireMutation: tryAcquireTurnMutationLock,
23
23
  ledger: conversationLedger,
24
24
  history: conversationHistory,
25
25
  sessionStore,
26
26
  backup: sessionBackup,
27
27
  resolveBackend: (channel) => resolveBackendForChannel(channel),
28
+ registerPISessionPath,
28
29
  closePooledSession: (channel, backend) => { if (backend === 'claude')
29
30
  closeClaudePooledSession(channel); },
30
31
  send: sendWebUserMessage,
@@ -41,64 +42,107 @@ function defaultDeps() {
41
42
  * and when the session/turn cannot be found ('not-found').
42
43
  */
43
44
  export async function rewindWebSession(opts, deps = defaultDeps()) {
44
- const { sessionId, channel, turnIndex, text, adapter } = opts;
45
- // Editing is only allowed while idle (design: 运行中编辑置灰). Server-side guard mirrors the UI.
46
- if (deps.activeAgents.hasChannel(channel))
45
+ if (deps.snapshotPending(opts.channel))
47
46
  return { ok: false, reason: 'running' };
48
- const conv = await deps.ledger.getConversation(channel);
49
- if (!conv || turnIndex < 0 || turnIndex >= conv.turns.length)
50
- return { ok: false, reason: 'not-found' };
51
- const rec = await deps.sessionStore.getById(sessionId);
52
- if (!rec)
53
- return { ok: false, reason: 'not-found' };
54
- const backendSessionId = effectiveBackendSessionId(rec);
55
- const backend = deps.resolveBackend(channel) || conv.backend;
56
- log.info('Rewinding session:', { channel, turnIndex, backend });
57
- // 1. Ledger: mark turns from turnIndex onward superseded.
58
- await deps.ledger.rollbackTo(channel, turnIndex);
59
- // 2. Backend session file: restore the pre-turn backup. A turn-0 edit (or a missing backup)
60
- // resets the BACKEND conversation only — clear backendSessionId so the next turn starts a
61
- // fresh CLI session; the track sessionId and channel binding are untouched (web identity).
62
- let restored = false;
63
- if (turnIndex > 0 && backendSessionId) {
64
- if (backend === 'pi') {
65
- const piFile = deps.backup.findPISessionFile(backendSessionId);
66
- restored = piFile ? deps.backup.restoreSessionFile(piFile, turnIndex) : false;
67
- }
68
- else {
69
- restored = deps.backup.restoreBackup(backendSessionId, turnIndex);
70
- }
47
+ let releaseMutation = deps.tryAcquireMutation(opts.channel);
48
+ if (!releaseMutation)
49
+ return { ok: false, reason: 'running' };
50
+ try {
51
+ const result = await rewindLocked(opts, deps, releaseMutation);
52
+ if (result.ok)
53
+ releaseMutation = null;
54
+ return result;
55
+ }
56
+ finally {
57
+ releaseMutation?.();
58
+ }
59
+ }
60
+ async function restoreSnapshot(backend, backendSessionId, backupPath, turnIndex, backup) {
61
+ if (backend !== 'pi') {
62
+ const restored = turnIndex > 0 && backendSessionId
63
+ ? await backup.restoreBackup(backendSessionId, turnIndex)
64
+ : false;
65
+ return { restored, piSessionFile: null };
66
+ }
67
+ const recordedFile = backupPath
68
+ ? backup.sessionFileFromBackupPath(backupPath, turnIndex)
69
+ : null;
70
+ const piSessionFile = backupPath || !backendSessionId
71
+ ? recordedFile
72
+ : await backup.findPISessionFile(backendSessionId);
73
+ if (turnIndex === 0 || !backendSessionId)
74
+ return { restored: false, piSessionFile };
75
+ const restored = backupPath
76
+ ? await backup.restoreSessionBackup(backupPath, turnIndex)
77
+ : piSessionFile ? await backup.restoreSessionFile(piSessionFile, turnIndex) : false;
78
+ return { restored, piSessionFile };
79
+ }
80
+ function registerRestoredPIPath(backend, backendSessionId, snapshot, register) {
81
+ if (backend !== 'pi' || !backendSessionId || !snapshot.restored || !snapshot.piSessionFile)
82
+ return;
83
+ register(backendSessionId, snapshot.piSessionFile);
84
+ }
85
+ function cleanupSnapshot(backend, backendSessionId, turnIndex, snapshot, backup) {
86
+ if (backend === 'pi') {
87
+ if (!snapshot.piSessionFile)
88
+ return;
89
+ if (snapshot.restored)
90
+ backup.cleanupBackupsForFile(snapshot.piSessionFile, turnIndex);
91
+ else
92
+ backup.cleanupAllBackupsForFile(snapshot.piSessionFile);
93
+ return;
71
94
  }
72
- if (!restored) {
95
+ if (!backendSessionId)
96
+ return;
97
+ if (snapshot.restored)
98
+ backup.cleanupBackupsAfter(backendSessionId, turnIndex);
99
+ else
100
+ backup.cleanupAllBackups(backendSessionId);
101
+ }
102
+ async function resolveRewindContext(opts, deps) {
103
+ const conversation = await deps.ledger.getConversation(opts.channel);
104
+ if (!conversation || opts.turnIndex < 0 || opts.turnIndex >= conversation.turns.length)
105
+ return null;
106
+ const session = await deps.sessionStore.getById(opts.sessionId);
107
+ if (!session)
108
+ return null;
109
+ const backend = deps.resolveBackend(opts.channel) || conversation.backend;
110
+ return { conversation, session, backend, backendSessionId: effectiveBackendSessionId(session) };
111
+ }
112
+ async function restoreRewindBackend(context, channel, turnIndex, deps) {
113
+ await deps.ledger.rollbackTo(channel, turnIndex);
114
+ const backupPath = context.conversation.turns[turnIndex].backupPath;
115
+ const snapshot = await restoreSnapshot(context.backend, context.backendSessionId, backupPath, turnIndex, deps.backup);
116
+ registerRestoredPIPath(context.backend, context.backendSessionId, snapshot, deps.registerPISessionPath);
117
+ if (!snapshot.restored) {
73
118
  if (turnIndex > 0)
74
119
  log.warn('No backup found — starting a fresh backend session (display history keeps earlier turns)');
75
- await deps.sessionStore.updateSession(rec.name, { backendSessionId: null });
76
- if (backendSessionId)
77
- deps.backup.cleanupAllBackups(backendSessionId);
120
+ await deps.sessionStore.updateSession(context.session.name, { backendSessionId: null });
78
121
  }
79
- // 3. Kill any pooled CLI process — an alive stream-json Claude keeps the old conversation in
80
- // memory and would ignore the restored jsonl on disk.
81
- deps.closePooledSession(channel, backend);
82
- // 4. Ledger + backup cleanup for the superseded range.
122
+ deps.closePooledSession(channel, context.backend);
83
123
  await deps.ledger.truncateTurns(channel, turnIndex);
84
- if (restored && backendSessionId) {
85
- if (backend === 'pi') {
86
- const piFile = deps.backup.findPISessionFile(backendSessionId);
87
- if (piFile)
88
- deps.backup.cleanupBackupsForFile(piFile, turnIndex);
89
- }
90
- else {
91
- deps.backup.cleanupBackupsAfter(backendSessionId, turnIndex);
92
- }
93
- }
94
- // 5. Display history: drop the edited turn and everything after; remember the original message.
95
- const removed = await deps.history.truncateFromTurn(sessionId, turnIndex);
96
- const originalText = removed?.text ?? conv.turns[turnIndex]?.userMessageText ?? '';
97
- await deps.history.appendEditMarker(sessionId, { originalText, originalTs: removed?.ts ?? '' });
98
- // 6. Tell live clients the transcript changed shape (they drop their live tails + refetch).
99
- deps.publishRewound({ sessionId, channel, turnIndex });
100
- // 7. Re-send the edited text as a genuine user turn (original attachments preserved —
101
- // the edit UI cannot add or remove them).
102
- deps.send({ channel, text, attachments: removed?.attachments, adapter });
124
+ cleanupSnapshot(context.backend, context.backendSessionId, turnIndex, snapshot, deps.backup);
125
+ }
126
+ async function resendRewoundTurn(opts, conversation, deps, mutationRelease) {
127
+ const removed = await deps.history.truncateFromTurn(opts.sessionId, opts.turnIndex);
128
+ const originalText = removed?.text ?? conversation.turns[opts.turnIndex]?.userMessageText ?? '';
129
+ await deps.history.appendEditMarker(opts.sessionId, {
130
+ originalText, originalTs: removed?.ts ?? '',
131
+ });
132
+ deps.publishRewound({ sessionId: opts.sessionId, channel: opts.channel, turnIndex: opts.turnIndex });
133
+ deps.send({
134
+ channel: opts.channel, text: opts.text, attachments: removed?.attachments,
135
+ adapter: opts.adapter, mutationRelease,
136
+ });
137
+ }
138
+ async function rewindLocked(opts, deps, mutationRelease) {
139
+ if (deps.activeAgents.hasChannel(opts.channel))
140
+ return { ok: false, reason: 'running' };
141
+ const context = await resolveRewindContext(opts, deps);
142
+ if (!context)
143
+ return { ok: false, reason: 'not-found' };
144
+ log.info('Rewinding session:', { channel: opts.channel, turnIndex: opts.turnIndex, backend: context.backend });
145
+ await restoreRewindBackend(context, opts.channel, opts.turnIndex, deps);
146
+ await resendRewoundTurn(opts, context.conversation, deps, mutationRelease);
103
147
  return { ok: true };
104
148
  }
@@ -1,6 +1,7 @@
1
1
  import type { IncomingMessage, PlatformAdapter } from '../platform/index.js';
2
2
  import type { AttachmentMeta } from '../domain/ui-service/types.js';
3
3
  import { type AgentRunnerCtx } from './agent-runner.js';
4
+ import type { TurnMutationRelease } from './turn-mutation-lock.js';
4
5
  /** Sender id for web-originated user turns. Distinct from SYNTHETIC_CALLBACK_SENDER so the message
5
6
  * flows through route as a real user message (not a self-consumed callback). */
6
7
  export declare const WEB_UI_SENDER = "cortex-web-ui";
@@ -15,5 +16,6 @@ export declare function sendWebUserMessage(opts: {
15
16
  text: string;
16
17
  attachments?: AttachmentMeta[];
17
18
  adapter: PlatformAdapter;
19
+ mutationRelease?: TurnMutationRelease;
18
20
  route?: (ctx: AgentRunnerCtx) => Promise<void>;
19
21
  }): void;
@@ -1,9 +1,7 @@
1
- // input: { channel, text, adapter } + agentRunner.route
2
- // output: sendWebUserMessage — inject a GENUINE user turn into a session (S4 chat send)
3
- // pos: orch/ — reuses the agentRunner.route synthetic-message path (like wakeSession), but with a
4
- // non-synthetic senderId so it is treated as a real user turn (eligible for the human
5
- // backstop). Wired into ui-service via the injected `sendSessionMessage` dep in entry/app.ts,
6
- // keeping the ui-service domain free of any orchestration import (layer safety).
1
+ // input: channel text, adapter, optional mutation lease
2
+ // output: fire-and-forget Web user turn routing
3
+ // pos: Web session turn admission adapter
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
7
5
  import { agentRunner } from './agent-runner.js';
8
6
  /** Sender id for web-originated user turns. Distinct from SYNTHETIC_CALLBACK_SENDER so the message
9
7
  * flows through route as a real user message (not a self-consumed callback). */
@@ -35,5 +33,6 @@ export function sendWebUserMessage(opts) {
35
33
  hasFiles: false,
36
34
  userMessage: opts.text,
37
35
  agentMessage: opts.text,
36
+ mutationRelease: opts.mutationRelease,
38
37
  }).catch(() => { });
39
38
  }
@@ -3,8 +3,7 @@ import type { AgentResult } from '../core/types/agent-types.js';
3
3
  import type { ExecutionRecord } from '../domain/executions/registry.js';
4
4
  import type { ThreadRunResult } from '../domain/threads/runner.js';
5
5
  export { computeElapsed, formatMetricsSuffix, buildSessionTag, buildUserProcessingMessage } from '../core/status-format.js';
6
- /** Feature gate: the "New (quiet)" status button (=!newq, skips the pre-close hook)
7
- * is OFF by default. Opt in with CORTEX_STATUS_NEWQ_BUTTON = 1/true/on/yes. */
6
+ /** Feature gate: the "New (quiet)" status button (=!newq, skips the pre-close hook). */
8
7
  export declare function isStatusNewqButtonEnabled(): boolean;
9
8
  export declare function resolveExecutionProject({ execution, fallbackMessage }: {
10
9
  execution: ExecutionRecord | null;
@@ -1,8 +1,9 @@
1
- // input: execution-registry, mode-manager, utils, platform, ...
2
- // output: status/session/exec helper functions
3
- // pos: Status message and execution helper functions collection
4
- // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
1
+ // input: executions, threads, platform, runtime settings
2
+ // output: status, session, and execution helpers
3
+ // pos: Builds and serializes status messages and actions
4
+ // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
5
  import { createLogger } from '../core/log.js';
6
+ import { getSettings } from '../core/settings.js';
6
7
  import { Icons } from '../core/icons.js';
7
8
  import { t } from '../core/i18n.js';
8
9
  import * as executionRegistry from '../domain/executions/registry.js';
@@ -15,13 +16,9 @@ import { durableUpdate } from './durable-helpers.js';
15
16
  // Pure formatters live in core/ so the domain layer can consume them without an orch dep.
16
17
  export { computeElapsed, formatMetricsSuffix, buildSessionTag, buildUserProcessingMessage } from '../core/status-format.js';
17
18
  const log = createLogger('status-helpers');
18
- /** Feature gate: the "New (quiet)" status button (=!newq, skips the pre-close hook)
19
- * is OFF by default. Opt in with CORTEX_STATUS_NEWQ_BUTTON = 1/true/on/yes. */
19
+ /** Feature gate: the "New (quiet)" status button (=!newq, skips the pre-close hook). */
20
20
  export function isStatusNewqButtonEnabled() {
21
- const v = process.env.CORTEX_STATUS_NEWQ_BUTTON;
22
- if (v === undefined)
23
- return false;
24
- return ['1', 'true', 'on', 'yes'].includes(v.trim().toLowerCase());
21
+ return getSettings().statusNewqButton;
25
22
  }
26
23
  export function resolveExecutionProject({ execution, fallbackMessage }) {
27
24
  return execution?.project || (projectStore.resolveFromMessage(fallbackMessage || '')?.id ?? 'general');