@cortex-agent/server 2026.6.24 → 2026.7.30

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 (588) hide show
  1. package/README.md +25 -13
  2. package/defaults/.claude/settings.json +4 -0
  3. package/defaults/config/CORTEX.md +9 -0
  4. package/defaults/config/hooks/01-sensitive-file-edit.json +11 -0
  5. package/defaults/config/hooks/02-tasks-yaml-guard.json +11 -0
  6. package/defaults/config/hooks/03-ask-user-question-hook.json +19 -0
  7. package/defaults/config/hooks/04-exit-plan-mode-hook.json +19 -0
  8. package/defaults/config/hooks/05-memory-ref-tracker.json +10 -0
  9. package/defaults/config/hooks/06-rules-loader.json +10 -0
  10. package/defaults/config/hooks/07-session-activity-tracker.json +10 -0
  11. package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +10 -0
  12. package/defaults/config/hooks/09-permission-request-auto-allow.json +11 -0
  13. package/defaults/config/hooks/10-cortex-md-injector-session-start.json +10 -0
  14. package/defaults/config/hooks/11-task-status-check.json +14 -0
  15. package/defaults/config/hooks/12-session-new-hook.json +11 -0
  16. package/defaults/config/hooks/CORTEX.md +18 -0
  17. package/defaults/config/thread-templates/agents/coder-reviewer.json +25 -0
  18. package/defaults/config/thread-templates/agents/coder.json +30 -0
  19. package/defaults/config/thread-templates/agents/direct-review.json +17 -0
  20. package/defaults/config/thread-templates/agents/direct-web.json +16 -0
  21. package/defaults/config/thread-templates/agents/direct.json +16 -0
  22. package/defaults/config/thread-templates/agents/director.json +14 -0
  23. package/defaults/config/thread-templates/agents/doc-reviewer.json +14 -0
  24. package/defaults/config/thread-templates/agents/doc-writer.json +25 -0
  25. package/defaults/config/thread-templates/agents/executor-reviewer.json +14 -0
  26. package/defaults/config/thread-templates/agents/executor.json +25 -0
  27. package/defaults/config/thread-templates/agents/main.json +16 -0
  28. package/defaults/config/thread-templates/agents/manager.json +17 -0
  29. package/defaults/config/thread-templates/agents/scheduler-main.json +16 -0
  30. package/defaults/config/thread-templates/shells/worker-review.json +19 -0
  31. package/defaults/config/thread-templates/templates/coder-review.json +53 -0
  32. package/defaults/config/thread-templates/templates/default.json +10 -0
  33. package/defaults/config/thread-templates/templates/doc-review.json +6 -0
  34. package/defaults/config/thread-templates/templates/execute-review.json +6 -0
  35. package/defaults/config/thread-templates/templates/manager.json +11 -0
  36. package/defaults/config/thread-templates/templates/scheduler.json +19 -0
  37. package/defaults/context/decisions/DR-0012.md +1 -1
  38. package/defaults/gitignore +3 -0
  39. package/defaults/hooks/CORTEX.md +18 -0
  40. package/defaults/hooks/cortex-hook-api.mjs +84 -0
  41. package/defaults/hooks/cortex-md-injector.mjs +99 -49
  42. package/defaults/hooks/session-activity-tracker.mjs +8 -101
  43. package/defaults/hooks/task-status-check.mjs +10 -11
  44. package/defaults/mcp-config-web.json +11 -0
  45. package/defaults/pi/agents/explore.md +9 -0
  46. package/defaults/pi/agents/general-purpose.md +6 -0
  47. package/defaults/pi/agents/plan.md +9 -0
  48. package/defaults/plugins/cortex-coder/.claude-plugin/plugin.json +1 -1
  49. package/defaults/plugins/cortex-coder/skills/cli-standards/SKILL.md +2 -2
  50. package/defaults/plugins/cortex-coder/skills/develop/SKILL.md +33 -0
  51. package/defaults/plugins/cortex-common/.claude-plugin/plugin.json +2 -2
  52. package/defaults/plugins/cortex-common/skills/debug-campaign/SKILL.md +16 -16
  53. package/defaults/plugins/cortex-common/skills/execute-method/SKILL.md +53 -0
  54. package/defaults/plugins/cortex-common/skills/execute-review-rubric/SKILL.md +102 -0
  55. package/defaults/plugins/cortex-common/skills/manager-method/SKILL.md +67 -0
  56. package/defaults/plugins/cortex-common/skills/solution-design/SKILL.md +3 -3
  57. package/defaults/plugins/cortex-stage-gate/.claude-plugin/plugin.json +2 -2
  58. package/defaults/plugins/cortex-stage-gate/skills/director-method/SKILL.md +54 -0
  59. package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +132 -112
  60. package/defaults/plugins/cortex-system/.claude-plugin/plugin.json +1 -1
  61. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +17 -10
  62. package/defaults/plugins/cortex-system/skills/feedback/SKILL.md +2 -2
  63. package/defaults/plugins/cortex-system/skills/orient/SKILL.md +1 -1
  64. package/defaults/plugins/cortex-system/skills/orient-project/SKILL.md +2 -2
  65. package/defaults/plugins/cortex-system/skills/thread/SKILL.md +66 -17
  66. package/defaults/prompts/directives/coder.md +7 -31
  67. package/defaults/prompts/directives/director.md +4 -17
  68. package/defaults/prompts/directives/doc-reviewer.md +2 -35
  69. package/defaults/prompts/directives/doc-writer.md +2 -7
  70. package/defaults/prompts/directives/executor-reviewer.md +2 -39
  71. package/defaults/prompts/directives/executor.md +2 -7
  72. package/defaults/prompts/directives/manager.md +12 -27
  73. package/defaults/prompts/systemPrompts/coder.md +1 -1
  74. package/defaults/prompts/systemPrompts/direct.md +1 -1
  75. package/defaults/prompts/systemPrompts/web.md +5 -0
  76. package/defaults/prompts/systemPrompts/worker.md +1 -1
  77. package/dist/agent-adapter/bg-wait.d.ts +44 -0
  78. package/dist/agent-adapter/bg-wait.js +197 -0
  79. package/dist/agent-adapter/capabilities.d.ts +7 -1
  80. package/dist/agent-adapter/capabilities.js +18 -9
  81. package/dist/agent-adapter/claude/adapter-tui.d.ts +2 -0
  82. package/dist/agent-adapter/claude/adapter-tui.js +1 -0
  83. package/dist/agent-adapter/claude/adapter.d.ts +89 -5
  84. package/dist/agent-adapter/claude/adapter.js +404 -38
  85. package/dist/agent-adapter/claude/bg-task-tracker.d.ts +22 -15
  86. package/dist/agent-adapter/claude/bg-task-tracker.js +48 -32
  87. package/dist/agent-adapter/claude/compact-window.d.ts +9 -0
  88. package/dist/agent-adapter/claude/compact-window.js +46 -0
  89. package/dist/agent-adapter/claude/context-usage.d.ts +28 -0
  90. package/dist/agent-adapter/claude/context-usage.js +177 -0
  91. package/dist/agent-adapter/claude/defaults.d.ts +17 -3
  92. package/dist/agent-adapter/claude/defaults.js +25 -9
  93. package/dist/agent-adapter/claude/event-parser.d.ts +30 -0
  94. package/dist/agent-adapter/claude/event-parser.js +68 -4
  95. package/dist/agent-adapter/claude/hooks-builder.d.ts +23 -23
  96. package/dist/agent-adapter/claude/hooks-builder.js +63 -7
  97. package/dist/agent-adapter/claude/spawn-args.d.ts +25 -6
  98. package/dist/agent-adapter/claude/spawn-args.js +62 -22
  99. package/dist/agent-adapter/index.js +2 -4
  100. package/dist/agent-adapter/normalize/event-types.d.ts +8 -1
  101. package/dist/agent-adapter/normalize/event-types.js +1 -1
  102. package/dist/agent-adapter/normalize/tool-names.js +0 -9
  103. package/dist/agent-adapter/pi/adapter.d.ts +3 -33
  104. package/dist/agent-adapter/pi/adapter.js +461 -229
  105. package/dist/agent-adapter/pi/agent-dir.d.ts +6 -0
  106. package/dist/agent-adapter/pi/agent-dir.js +24 -14
  107. package/dist/agent-adapter/pi/defaults.d.ts +4 -0
  108. package/dist/agent-adapter/pi/defaults.js +11 -0
  109. package/dist/agent-adapter/pi/discovery.d.ts +4 -0
  110. package/dist/agent-adapter/pi/discovery.js +63 -0
  111. package/dist/agent-adapter/pi/event-parser.d.ts +13 -2
  112. package/dist/agent-adapter/pi/event-parser.js +139 -69
  113. package/dist/agent-adapter/pi/hook-bridge.d.ts +13 -28
  114. package/dist/agent-adapter/pi/hook-bridge.js +272 -167
  115. package/dist/agent-adapter/pi/mcp-bridge-logic.d.ts +24 -0
  116. package/dist/agent-adapter/pi/mcp-bridge-logic.js +39 -0
  117. package/dist/agent-adapter/pi/mcp-bridge.d.ts +13 -35
  118. package/dist/agent-adapter/pi/mcp-bridge.js +147 -137
  119. package/dist/agent-adapter/pi/pi-ext-types.d.ts +30 -0
  120. package/dist/agent-adapter/pi/pi-ext-types.js +2 -2
  121. package/dist/agent-adapter/pi/session-support.d.ts +96 -0
  122. package/dist/agent-adapter/pi/session-support.js +213 -0
  123. package/dist/agent-adapter/pi/spawn-args.d.ts +15 -0
  124. package/dist/agent-adapter/pi/spawn-args.js +46 -3
  125. package/dist/agent-adapter/pi/subagent.d.ts +68 -0
  126. package/dist/agent-adapter/pi/subagent.js +521 -0
  127. package/dist/agent-adapter/pi/tool-shims.d.ts +1 -13
  128. package/dist/agent-adapter/pi/tool-shims.js +182 -198
  129. package/dist/agent-adapter/pi/web-fetch.d.ts +13 -0
  130. package/dist/agent-adapter/pi/web-fetch.js +201 -0
  131. package/dist/agent-adapter/pi/web-search.d.ts +9 -0
  132. package/dist/agent-adapter/pi/web-search.js +513 -0
  133. package/dist/agent-adapter/types.d.ts +61 -10
  134. package/dist/agent-adapter/types.js +4 -4
  135. package/dist/core/atomic-write.d.ts +3 -5
  136. package/dist/core/atomic-write.js +26 -12
  137. package/dist/core/bg-held-sessions.d.ts +35 -0
  138. package/dist/core/bg-held-sessions.js +79 -0
  139. package/dist/core/calver.d.ts +1 -0
  140. package/dist/core/calver.js +29 -0
  141. package/dist/core/config-generator.d.ts +13 -2
  142. package/dist/core/config-generator.js +55 -5
  143. package/dist/core/debug-mode.d.ts +14 -0
  144. package/dist/core/debug-mode.js +32 -0
  145. package/dist/core/gateway-generator.js +5 -10
  146. package/dist/core/hook-bus.d.ts +23 -0
  147. package/dist/core/hook-bus.js +111 -0
  148. package/dist/core/hook-exec.d.ts +15 -0
  149. package/dist/core/hook-exec.js +90 -0
  150. package/dist/core/icons.d.ts +2 -0
  151. package/dist/core/icons.js +2 -0
  152. package/dist/core/locales/en.d.ts +24 -7
  153. package/dist/core/locales/en.js +4 -1
  154. package/dist/core/locales/slices/commands.d.ts +12 -2
  155. package/dist/core/locales/slices/commands.js +31 -7
  156. package/dist/core/locales/slices/init.d.ts +1 -1
  157. package/dist/core/locales/slices/init.js +2 -2
  158. package/dist/core/locales/slices/status.d.ts +7 -3
  159. package/dist/core/locales/slices/status.js +16 -8
  160. package/dist/core/log.js +4 -3
  161. package/dist/core/paths.d.ts +9 -0
  162. package/dist/core/paths.js +20 -1
  163. package/dist/core/profile-generator.d.ts +2 -2
  164. package/dist/core/profile-generator.js +6 -9
  165. package/dist/core/running-executions.d.ts +10 -1
  166. package/dist/core/running-executions.js +10 -0
  167. package/dist/core/task-node.d.ts +7 -0
  168. package/dist/core/task-node.js +29 -0
  169. package/dist/core/types/agent-types.d.ts +23 -2
  170. package/dist/core/types/agent-types.js +2 -2
  171. package/dist/core/types/thread-types.d.ts +87 -15
  172. package/dist/core/types/thread-types.js +3 -3
  173. package/dist/core/utils.d.ts +2 -2
  174. package/dist/core/utils.js +3 -3
  175. package/dist/domain/agents/config.d.ts +6 -5
  176. package/dist/domain/agents/config.js +17 -5
  177. package/dist/domain/agents/facade.d.ts +61 -10
  178. package/dist/domain/agents/facade.js +309 -61
  179. package/dist/domain/agents/index.d.ts +1 -0
  180. package/dist/domain/agents/index.js +1 -0
  181. package/dist/domain/agents/profile-manager.d.ts +14 -7
  182. package/dist/domain/agents/profile-manager.js +23 -7
  183. package/dist/domain/agents/profile-switch.d.ts +53 -0
  184. package/dist/domain/agents/profile-switch.js +79 -0
  185. package/dist/domain/costs/cost-tracker.d.ts +21 -1
  186. package/dist/domain/costs/cost-tracker.js +54 -26
  187. package/dist/domain/costs/gateway-manager.js +5 -3
  188. package/dist/domain/costs/rate-limit-throttle.d.ts +44 -19
  189. package/dist/domain/costs/rate-limit-throttle.js +331 -103
  190. package/dist/domain/costs/resume-registry.d.ts +17 -9
  191. package/dist/domain/costs/resume-registry.js +63 -8
  192. package/dist/domain/executions/log-tailer.d.ts +71 -0
  193. package/dist/domain/executions/log-tailer.js +195 -0
  194. package/dist/domain/executions/registry.d.ts +10 -1
  195. package/dist/domain/executions/registry.js +14 -0
  196. package/dist/domain/hooks/hook-view.d.ts +22 -0
  197. package/dist/domain/hooks/hook-view.js +38 -0
  198. package/dist/domain/mcp/core-server.d.ts +0 -1
  199. package/dist/domain/mcp/core-server.js +8 -40
  200. package/dist/domain/mcp/feishu/file.js +1 -11
  201. package/dist/domain/mcp/feishu/index.d.ts +0 -2
  202. package/dist/domain/mcp/feishu/index.js +3 -8
  203. package/dist/domain/mcp/feishu-server.d.ts +0 -1
  204. package/dist/domain/mcp/feishu-server.js +4 -6
  205. package/dist/domain/mcp/manager-qa-server.d.ts +1 -0
  206. package/dist/domain/mcp/manager-qa-server.js +23 -0
  207. package/dist/domain/mcp/server.d.ts +0 -1
  208. package/dist/domain/mcp/server.js +5 -31
  209. package/dist/domain/mcp/slack-server.d.ts +0 -1
  210. package/dist/domain/mcp/slack-server.js +3 -5
  211. package/dist/domain/mcp/tasks-server.d.ts +1 -0
  212. package/dist/domain/mcp/tasks-server.js +23 -0
  213. package/dist/domain/mcp/thread-server.d.ts +1 -0
  214. package/dist/domain/mcp/thread-server.js +25 -0
  215. package/dist/domain/mcp/tools/context.d.ts +3 -10
  216. package/dist/domain/mcp/tools/context.js +13 -29
  217. package/dist/domain/mcp/tools/manager-qa.d.ts +2 -1
  218. package/dist/domain/mcp/tools/manager-qa.js +49 -53
  219. package/dist/domain/mcp/tools/schedule.d.ts +1 -2
  220. package/dist/domain/mcp/tools/schedule.js +7 -10
  221. package/dist/domain/mcp/tools/slack.d.ts +0 -1
  222. package/dist/domain/mcp/tools/slack.js +2 -13
  223. package/dist/domain/mcp/tools/task-ops.js +10 -137
  224. package/dist/domain/mcp/tools/thread-ops.js +6 -11
  225. package/dist/domain/mcp/tools/tui-ask.d.ts +2 -0
  226. package/dist/domain/mcp/tools/tui-ask.js +8 -0
  227. package/dist/domain/mcp/tools/ui-file.d.ts +2 -0
  228. package/dist/domain/mcp/tools/ui-file.js +49 -0
  229. package/dist/domain/mcp/tui-server.d.ts +0 -1
  230. package/dist/domain/mcp/tui-server.js +39 -24
  231. package/dist/domain/mcp/web-server.d.ts +1 -0
  232. package/dist/domain/mcp/web-server.js +25 -0
  233. package/dist/domain/memory/cortex-md-injector.d.ts +4 -10
  234. package/dist/domain/memory/cortex-md-injector.js +113 -77
  235. package/dist/domain/memory/cortex-md-scanner.d.ts +1 -0
  236. package/dist/domain/memory/cortex-md-scanner.js +5 -2
  237. package/dist/domain/memory/skill-scanner.d.ts +3 -1
  238. package/dist/domain/memory/skill-scanner.js +8 -12
  239. package/dist/domain/monitor/disk-monitor.js +2 -3
  240. package/dist/domain/projects/index.d.ts +1 -0
  241. package/dist/domain/projects/project-store.d.ts +18 -0
  242. package/dist/domain/projects/project-store.js +39 -3
  243. package/dist/domain/remote/client-hot-reload.js +4 -3
  244. package/dist/domain/remote/client-manager.d.ts +15 -1
  245. package/dist/domain/remote/client-manager.js +75 -11
  246. package/dist/domain/remote/cortex-client.js +6 -48
  247. package/dist/domain/scheduling/job-registry.d.ts +0 -2
  248. package/dist/domain/scheduling/job-registry.js +2 -6
  249. package/dist/domain/scheduling/jobs/_shared.d.ts +5 -1
  250. package/dist/domain/scheduling/jobs/_shared.js +2 -1
  251. package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.d.ts +1 -0
  252. package/dist/domain/scheduling/jobs/failed-dispatch-reconciliation.js +78 -0
  253. package/dist/domain/scheduling/jobs/scheduled-task.js +1 -3
  254. package/dist/domain/scheduling/jobs/task-dispatch.js +39 -31
  255. package/dist/domain/scheduling/scheduler.d.ts +0 -10
  256. package/dist/domain/scheduling/scheduler.js +9 -9
  257. package/dist/domain/sessions/session-hooks.d.ts +7 -14
  258. package/dist/domain/sessions/session-hooks.js +66 -112
  259. package/dist/domain/sessions/session-lifecycle.d.ts +38 -1
  260. package/dist/domain/sessions/session-lifecycle.js +41 -4
  261. package/dist/domain/sessions/session-registry.d.ts +3 -1
  262. package/dist/domain/system/doctor.js +4 -7
  263. package/dist/domain/system/server-update-check.d.ts +2 -1
  264. package/dist/domain/system/server-update-check.js +7 -26
  265. package/dist/domain/system/system-notice.d.ts +18 -0
  266. package/dist/domain/system/system-notice.js +34 -0
  267. package/dist/domain/tasks/acceptance-ledger.d.ts +31 -0
  268. package/dist/domain/tasks/acceptance-ledger.js +83 -0
  269. package/dist/domain/tasks/claim-recovery.d.ts +10 -0
  270. package/dist/domain/tasks/claim-recovery.js +64 -0
  271. package/dist/domain/tasks/dispatch-utils.d.ts +19 -0
  272. package/dist/domain/tasks/dispatcher.js +1 -3
  273. package/dist/domain/tasks/mutator.d.ts +7 -1
  274. package/dist/domain/tasks/mutator.js +55 -3
  275. package/dist/domain/tasks/recommendation/extractor.js +3 -3
  276. package/dist/domain/tasks/system/cortex-run.js +0 -0
  277. package/dist/domain/tasks/system/task-cli.d.ts +2 -0
  278. package/dist/domain/tasks/system/task-cli.js +30 -3
  279. package/dist/domain/tasks/system/task-completion.js +148 -42
  280. package/dist/domain/tasks/system/task-lifecycle-edit.js +3 -0
  281. package/dist/domain/threads/artifact-io.d.ts +3 -15
  282. package/dist/domain/threads/artifact-io.js +13 -119
  283. package/dist/domain/threads/hook-runner.d.ts +7 -2
  284. package/dist/domain/threads/hook-runner.js +68 -85
  285. package/dist/domain/threads/index.js +6 -1
  286. package/dist/domain/threads/prompt-builder.d.ts +7 -0
  287. package/dist/domain/threads/prompt-builder.js +30 -13
  288. package/dist/domain/threads/runner.d.ts +19 -5
  289. package/dist/domain/threads/runner.js +211 -78
  290. package/dist/domain/threads/shell-templates.d.ts +9 -0
  291. package/dist/domain/threads/shell-templates.js +117 -0
  292. package/dist/domain/threads/state-machine.d.ts +35 -7
  293. package/dist/domain/threads/state-machine.js +170 -29
  294. package/dist/domain/threads/template-loader.d.ts +15 -7
  295. package/dist/domain/threads/template-loader.js +204 -87
  296. package/dist/domain/threads/thread-transcript.d.ts +47 -0
  297. package/dist/domain/threads/thread-transcript.js +64 -0
  298. package/dist/domain/threads/utils.d.ts +8 -1
  299. package/dist/domain/threads/utils.js +17 -1
  300. package/dist/domain/tui-session/tui-session-service.js +9 -16
  301. package/dist/domain/tui-session/types.d.ts +12 -0
  302. package/dist/domain/ui-service/app-router.d.ts +670 -0
  303. package/dist/domain/ui-service/app-router.js +195 -0
  304. package/dist/domain/ui-service/index.d.ts +1 -1
  305. package/dist/domain/ui-service/input-schemas.d.ts +644 -0
  306. package/dist/domain/ui-service/input-schemas.js +385 -0
  307. package/dist/domain/ui-service/mutate/approvals.d.ts +31 -0
  308. package/dist/domain/ui-service/mutate/approvals.js +140 -0
  309. package/dist/domain/ui-service/mutate/config.d.ts +16 -0
  310. package/dist/domain/ui-service/mutate/config.js +72 -0
  311. package/dist/domain/ui-service/mutate/hooks.d.ts +16 -0
  312. package/dist/domain/ui-service/mutate/hooks.js +138 -0
  313. package/dist/domain/ui-service/mutate/issues.d.ts +18 -0
  314. package/dist/domain/ui-service/mutate/issues.js +111 -0
  315. package/dist/domain/ui-service/mutate/notes.d.ts +6 -0
  316. package/dist/domain/ui-service/mutate/notes.js +36 -0
  317. package/dist/domain/ui-service/mutate/projects.d.ts +4 -0
  318. package/dist/domain/ui-service/mutate/projects.js +10 -0
  319. package/dist/domain/ui-service/mutate/schedules.d.ts +2 -1
  320. package/dist/domain/ui-service/mutate/schedules.js +57 -3
  321. package/dist/domain/ui-service/mutate/sessions.d.ts +11 -0
  322. package/dist/domain/ui-service/mutate/sessions.js +198 -0
  323. package/dist/domain/ui-service/mutate/system.d.ts +2 -0
  324. package/dist/domain/ui-service/mutate/system.js +97 -0
  325. package/dist/domain/ui-service/query/approvals.d.ts +10 -0
  326. package/dist/domain/ui-service/query/approvals.js +109 -0
  327. package/dist/domain/ui-service/query/config.d.ts +8 -0
  328. package/dist/domain/ui-service/query/config.js +138 -0
  329. package/dist/domain/ui-service/query/executions.d.ts +2 -1
  330. package/dist/domain/ui-service/query/executions.js +47 -3
  331. package/dist/domain/ui-service/query/hooks.d.ts +7 -0
  332. package/dist/domain/ui-service/query/hooks.js +110 -0
  333. package/dist/domain/ui-service/query/issues.d.ts +14 -0
  334. package/dist/domain/ui-service/query/issues.js +85 -0
  335. package/dist/domain/ui-service/query/machines.d.ts +2 -0
  336. package/dist/domain/ui-service/query/machines.js +39 -0
  337. package/dist/domain/ui-service/query/memory.d.ts +5 -0
  338. package/dist/domain/ui-service/query/memory.js +199 -0
  339. package/dist/domain/ui-service/query/notes.d.ts +3 -0
  340. package/dist/domain/ui-service/query/notes.js +18 -0
  341. package/dist/domain/ui-service/query/schedules.js +1 -0
  342. package/dist/domain/ui-service/query/sessions.d.ts +3 -1
  343. package/dist/domain/ui-service/query/sessions.js +227 -15
  344. package/dist/domain/ui-service/query/skills.d.ts +2 -0
  345. package/dist/domain/ui-service/query/skills.js +14 -0
  346. package/dist/domain/ui-service/query/system.d.ts +3 -0
  347. package/dist/domain/ui-service/query/system.js +132 -0
  348. package/dist/domain/ui-service/query/task-verification.d.ts +2 -0
  349. package/dist/domain/ui-service/query/task-verification.js +60 -0
  350. package/dist/domain/ui-service/query/tasks.d.ts +1 -0
  351. package/dist/domain/ui-service/query/tasks.js +24 -16
  352. package/dist/domain/ui-service/query/thread-templates.d.ts +8 -0
  353. package/dist/domain/ui-service/query/thread-templates.js +54 -0
  354. package/dist/domain/ui-service/query/threads.d.ts +2 -1
  355. package/dist/domain/ui-service/query/threads.js +213 -4
  356. package/dist/domain/ui-service/subscribe.js +27 -1
  357. package/dist/domain/ui-service/trpc.d.ts +13 -0
  358. package/dist/domain/ui-service/trpc.js +12 -0
  359. package/dist/domain/ui-service/types.d.ts +1266 -4
  360. package/dist/domain/ui-service/types.js +4 -4
  361. package/dist/domain/ui-service/ui-service.d.ts +2 -1
  362. package/dist/domain/ui-service/ui-service.js +112 -10
  363. package/dist/entry/app.js +281 -34
  364. package/dist/entry/daemon-notice.d.ts +17 -0
  365. package/dist/entry/daemon-notice.js +26 -0
  366. package/dist/entry/daemon.d.ts +23 -1
  367. package/dist/entry/daemon.js +126 -41
  368. package/dist/entry/hook-cli.d.ts +18 -0
  369. package/dist/entry/hook-cli.js +468 -0
  370. package/dist/entry/init.js +22 -18
  371. package/dist/entry/start-ui-http.d.ts +44 -0
  372. package/dist/entry/start-ui-http.js +289 -0
  373. package/dist/entry/startup-notify.js +5 -9
  374. package/dist/entry/ui-http-gate.d.ts +11 -0
  375. package/dist/entry/ui-http-gate.js +29 -0
  376. package/dist/events/event-bus.d.ts +7 -2
  377. package/dist/events/event-bus.js +5 -2
  378. package/dist/events/event-logger.js +14 -0
  379. package/dist/events/event-types.d.ts +110 -0
  380. package/dist/events/event-types.js +3 -3
  381. package/dist/hooks/cortex-hook-api.mjs +84 -0
  382. package/dist/hooks/cortex-md-injector.mjs +99 -49
  383. package/dist/hooks/session-activity-tracker.mjs +8 -101
  384. package/dist/hooks/task-status-check.mjs +10 -11
  385. package/dist/orchestration/agent-file-send.d.ts +54 -0
  386. package/dist/orchestration/agent-file-send.js +110 -0
  387. package/dist/orchestration/agent-runner.d.ts +49 -0
  388. package/dist/orchestration/agent-runner.js +365 -53
  389. package/dist/orchestration/bg-continuation.d.ts +51 -9
  390. package/dist/orchestration/bg-continuation.js +53 -15
  391. package/dist/orchestration/bg-wait-guard.d.ts +28 -0
  392. package/dist/orchestration/bg-wait-guard.js +73 -0
  393. package/dist/orchestration/conduit-queue.d.ts +2 -0
  394. package/dist/orchestration/conduit-queue.js +14 -1
  395. package/dist/orchestration/conversation-runner.d.ts +37 -5
  396. package/dist/orchestration/conversation-runner.js +70 -15
  397. package/dist/orchestration/delta-coalescer.d.ts +69 -0
  398. package/dist/orchestration/delta-coalescer.js +128 -0
  399. package/dist/orchestration/interactions/ask-user-question.d.ts +11 -3
  400. package/dist/orchestration/interactions/ask-user-question.js +27 -3
  401. package/dist/orchestration/interactions/interaction-handlers.js +11 -36
  402. package/dist/orchestration/interactions/interaction-records.d.ts +59 -0
  403. package/dist/orchestration/interactions/interaction-records.js +156 -0
  404. package/dist/orchestration/interactions/plan-approvals.d.ts +5 -0
  405. package/dist/orchestration/interactions/plan-approvals.js +8 -0
  406. package/dist/orchestration/interactions/plan-response.d.ts +8 -0
  407. package/dist/orchestration/interactions/plan-response.js +37 -0
  408. package/dist/orchestration/lifecycle.d.ts +8 -3
  409. package/dist/orchestration/lifecycle.js +143 -62
  410. package/dist/orchestration/manager-qa.d.ts +12 -2
  411. package/dist/orchestration/manager-qa.js +34 -33
  412. package/dist/orchestration/mid-turn-inject.d.ts +105 -0
  413. package/dist/orchestration/mid-turn-inject.js +298 -0
  414. package/dist/orchestration/pending-injection-recovery.d.ts +35 -0
  415. package/dist/orchestration/pending-injection-recovery.js +92 -0
  416. package/dist/orchestration/resume-dispatcher.d.ts +21 -4
  417. package/dist/orchestration/resume-dispatcher.js +67 -37
  418. package/dist/orchestration/routing/commands/cancel.d.ts +26 -0
  419. package/dist/orchestration/routing/commands/cancel.js +64 -18
  420. package/dist/orchestration/routing/commands/compact.d.ts +10 -0
  421. package/dist/orchestration/routing/commands/compact.js +26 -0
  422. package/dist/orchestration/routing/commands/index.d.ts +2 -0
  423. package/dist/orchestration/routing/commands/index.js +9 -0
  424. package/dist/orchestration/routing/commands/mode.js +24 -11
  425. package/dist/orchestration/routing/commands/restart.d.ts +22 -0
  426. package/dist/orchestration/routing/commands/restart.js +49 -0
  427. package/dist/orchestration/routing/commands/session.js +4 -0
  428. package/dist/orchestration/routing/commands/status.js +5 -0
  429. package/dist/orchestration/routing/edit-handler.js +1 -1
  430. package/dist/orchestration/routing/hook-bridge-subscribers.d.ts +2 -1
  431. package/dist/orchestration/routing/hook-bridge-subscribers.js +45 -4
  432. package/dist/orchestration/routing/hook-bridge.d.ts +10 -3
  433. package/dist/orchestration/routing/hook-bridge.js +26 -14
  434. package/dist/orchestration/routing/webhook.js +110 -19
  435. package/dist/orchestration/session-compact.d.ts +58 -0
  436. package/dist/orchestration/session-compact.js +82 -0
  437. package/dist/orchestration/session-events.d.ts +111 -0
  438. package/dist/orchestration/session-events.js +113 -0
  439. package/dist/orchestration/session-rewind.d.ts +72 -0
  440. package/dist/orchestration/session-rewind.js +104 -0
  441. package/dist/orchestration/session-send.d.ts +19 -0
  442. package/dist/orchestration/session-send.js +39 -0
  443. package/dist/orchestration/status-helpers.d.ts +4 -0
  444. package/dist/orchestration/status-helpers.js +18 -0
  445. package/dist/orchestration/thread-callback.d.ts +75 -7
  446. package/dist/orchestration/thread-callback.js +300 -49
  447. package/dist/orchestration/thread-executor.d.ts +1 -0
  448. package/dist/orchestration/thread-executor.js +23 -31
  449. package/dist/orchestration/web-bg-hold.d.ts +52 -0
  450. package/dist/orchestration/web-bg-hold.js +105 -0
  451. package/dist/platform/adapter.d.ts +3 -0
  452. package/dist/platform/adapter.js +2 -2
  453. package/dist/platform/adapters/composite-adapter.d.ts +6 -1
  454. package/dist/platform/adapters/composite-adapter.js +64 -4
  455. package/dist/platform/adapters/feishu.d.ts +6 -1
  456. package/dist/platform/adapters/feishu.js +52 -12
  457. package/dist/platform/adapters/slack.d.ts +2 -1
  458. package/dist/platform/adapters/slack.js +41 -9
  459. package/dist/platform/adapters/tui/index.d.ts +1 -1
  460. package/dist/platform/adapters/tui/ports.d.ts +8 -7
  461. package/dist/platform/adapters/tui/tui-gateway.d.ts +7 -0
  462. package/dist/platform/adapters/tui/tui-gateway.js +48 -5
  463. package/dist/platform/adapters/tui/tui-transcript.js +17 -29
  464. package/dist/platform/index.d.ts +1 -1
  465. package/dist/platform/index.js +1 -1
  466. package/dist/platform/interactive-builder.d.ts +7 -0
  467. package/dist/platform/interactive-builder.js +22 -2
  468. package/dist/platform/testing.d.ts +5 -0
  469. package/dist/platform/testing.js +7 -2
  470. package/dist/platform/tui/protocol.d.ts +0 -2
  471. package/dist/platform/tui/protocol.js +4 -53
  472. package/dist/platform/types.d.ts +12 -0
  473. package/dist/platform/types.js +5 -0
  474. package/dist/platform/ui-http/access-jwt.d.ts +28 -0
  475. package/dist/platform/ui-http/access-jwt.js +67 -0
  476. package/dist/platform/ui-http/app-update.d.ts +58 -0
  477. package/dist/platform/ui-http/app-update.js +155 -0
  478. package/dist/platform/ui-http/ui-http-server.d.ts +56 -0
  479. package/dist/platform/ui-http/ui-http-server.js +231 -0
  480. package/dist/platform/ui-http/ui-ota.d.ts +20 -0
  481. package/dist/platform/ui-http/ui-ota.js +128 -0
  482. package/dist/platform/ui-http/zip-writer.d.ts +13 -0
  483. package/dist/platform/ui-http/zip-writer.js +102 -0
  484. package/dist/platform/utils/reaction-diagnostics.d.ts +4 -0
  485. package/dist/platform/utils/reaction-diagnostics.js +23 -0
  486. package/dist/store/conversation-history-repo.d.ts +243 -0
  487. package/dist/store/conversation-history-repo.js +399 -0
  488. package/dist/store/execution-repo.d.ts +19 -1
  489. package/dist/store/execution-repo.js +18 -1
  490. package/dist/store/hook-registry.d.ts +83 -0
  491. package/dist/store/hook-registry.js +318 -0
  492. package/dist/store/hook-sync.d.ts +12 -16
  493. package/dist/store/hook-sync.js +169 -70
  494. package/dist/store/hook-writer.d.ts +49 -0
  495. package/dist/store/hook-writer.js +132 -0
  496. package/dist/store/outbound-queue.d.ts +8 -0
  497. package/dist/store/outbound-queue.js +24 -3
  498. package/dist/store/pending-injection-repo.d.ts +30 -0
  499. package/dist/store/pending-injection-repo.js +51 -0
  500. package/dist/store/profile-repo.d.ts +2 -1
  501. package/dist/store/profile-repo.js +6 -11
  502. package/dist/store/project-notes-repo.d.ts +27 -0
  503. package/dist/store/project-notes-repo.js +214 -0
  504. package/dist/store/provider-state-repo.d.ts +18 -0
  505. package/dist/store/provider-state-repo.js +107 -0
  506. package/dist/store/schedule-repo.d.ts +0 -21
  507. package/dist/store/schedule-repo.js +4 -25
  508. package/dist/store/session-registry-repo.d.ts +47 -1
  509. package/dist/store/session-registry-repo.js +71 -3
  510. package/dist/store/version-migrations.d.ts +2 -0
  511. package/dist/store/version-migrations.js +186 -9
  512. package/dist/tui/App.js +208 -20
  513. package/dist/tui/components/Dashboard.d.ts +3 -1
  514. package/dist/tui/components/Dashboard.js +5 -1
  515. package/dist/tui/components/DashboardCostTab.js +17 -2
  516. package/dist/tui/components/DashboardExecutionsTab.js +21 -1
  517. package/dist/tui/components/DashboardSchedulesTab.js +8 -3
  518. package/dist/tui/components/DashboardTasksTab.js +11 -6
  519. package/dist/tui/components/DashboardThreadsTab.js +20 -2
  520. package/dist/tui/components/InputBox.d.ts +17 -1
  521. package/dist/tui/components/InputBox.js +237 -21
  522. package/dist/tui/components/Notifications.js +7 -2
  523. package/dist/tui/components/ProjectSwitcher.js +7 -2
  524. package/dist/tui/components/SessionPicker.js +10 -1
  525. package/dist/tui/components/SidePanel.d.ts +3 -1
  526. package/dist/tui/components/SidePanel.js +4 -2
  527. package/dist/tui/components/SlashMenu.d.ts +8 -0
  528. package/dist/tui/components/SlashMenu.js +14 -0
  529. package/dist/tui/components/StatusLine.d.ts +12 -3
  530. package/dist/tui/components/StatusLine.js +29 -10
  531. package/dist/tui/components/Transcript.d.ts +9 -0
  532. package/dist/tui/components/Transcript.js +131 -26
  533. package/dist/tui/components/dashboard-constants.d.ts +1 -0
  534. package/dist/tui/components/dashboard-constants.js +7 -0
  535. package/dist/tui/hooks/useKeybindings.d.ts +1 -0
  536. package/dist/tui/hooks/useKeybindings.js +9 -14
  537. package/dist/tui/hooks/useMouseHandler.d.ts +17 -0
  538. package/dist/tui/hooks/useMouseHandler.js +103 -0
  539. package/dist/tui/hooks/useTranscript.d.ts +7 -2
  540. package/dist/tui/hooks/useTranscript.js +76 -57
  541. package/dist/tui/index.js +106 -10
  542. package/dist/tui/logic.d.ts +146 -2
  543. package/dist/tui/logic.js +411 -6
  544. package/dist/tui/raf-batch.d.ts +33 -0
  545. package/dist/tui/raf-batch.js +103 -0
  546. package/dist/tui/render/inline-markdown.d.ts +22 -0
  547. package/dist/tui/render/inline-markdown.js +99 -0
  548. package/dist/tui/render/rich-blocks.js +10 -8
  549. package/dist/tui/render-output.d.ts +46 -0
  550. package/dist/tui/render-output.js +86 -0
  551. package/dist/tui/slash-commands.d.ts +21 -0
  552. package/dist/tui/slash-commands.js +73 -0
  553. package/dist/tui/turn-status.d.ts +10 -0
  554. package/dist/tui/turn-status.js +53 -0
  555. package/package.json +17 -7
  556. package/web/dist/apple-touch-icon.png +0 -0
  557. package/web/dist/assets/index-B19jLgji.js +138 -0
  558. package/web/dist/assets/index-BuFyPyRW.css +1 -0
  559. package/web/dist/assets/index-DCgngTJG.js +1 -0
  560. package/web/dist/assets/pdf-worker-DIEXcFxP.js +55 -0
  561. package/web/dist/assets/pdf.worker.min-DqNZU1-t.js +53 -0
  562. package/web/dist/favicon-32.png +0 -0
  563. package/web/dist/favicon.svg +7 -0
  564. package/web/dist/index.html +37 -0
  565. package/defaults/config/session-hooks.json +0 -7
  566. package/defaults/config/thread-templates.json +0 -600
  567. package/defaults/prompts/directives/milestone-executor.md +0 -119
  568. package/defaults/prompts/directives/milestone-reviewer.md +0 -108
  569. package/defaults/prompts/directives/plan-executor.md +0 -121
  570. package/defaults/prompts/directives/plan-reviewer.md +0 -99
  571. package/dist/agent-adapter/codex/adapter.d.ts +0 -42
  572. package/dist/agent-adapter/codex/adapter.js +0 -916
  573. package/dist/agent-adapter/codex/event-parser.d.ts +0 -17
  574. package/dist/agent-adapter/codex/event-parser.js +0 -41
  575. package/dist/agent-adapter/codex/spawn-args.d.ts +0 -6
  576. package/dist/agent-adapter/codex/spawn-args.js +0 -30
  577. package/dist/domain/costs/codex-event-format.d.ts +0 -4
  578. package/dist/domain/costs/codex-event-format.js +0 -66
  579. package/dist/domain/costs/codex-usage-monitor.d.ts +0 -6
  580. package/dist/domain/costs/codex-usage-monitor.js +0 -73
  581. package/dist/domain/costs/rate-limit-parser.d.ts +0 -11
  582. package/dist/domain/costs/rate-limit-parser.js +0 -87
  583. package/dist/domain/mcp/feishu/block-types.d.ts +0 -44
  584. package/dist/domain/mcp/feishu/block-types.js +0 -127
  585. package/dist/tui/components/Header.d.ts +0 -11
  586. package/dist/tui/components/Header.js +0 -5
  587. package/dist/tui/components/MessageRow.d.ts +0 -7
  588. package/dist/tui/components/MessageRow.js +0 -10
@@ -1,104 +1,63 @@
1
1
  // input: AgentSpawnConfig, session keys, injectable spawner
2
- // output: PIAdapter + PISession + switch_session API
3
- // pos: PI CLI session pool and AgentAdapter implementation
2
+ // output: PIAdapter runtime sessions, context stats, manual compact, steering
3
+ // pos: PI CLI session pool; private spawn/codec helpers stay module-internal
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
- import { spawn as defaultSpawn, execSync } from 'child_process';
5
+ import { spawn as defaultSpawn } from 'child_process';
6
6
  import { mkdirSync } from 'fs';
7
7
  import * as path from 'path';
8
- import { DATA_DIR, INSTALL_ROOT } from '../../core/utils.js';
8
+ import { DATA_DIR } from '../../core/utils.js';
9
9
  import { createLogger } from '../../core/log.js';
10
10
  import { CAPABILITIES_BY_BACKEND } from '../capabilities.js';
11
- import { buildSpawnArgs } from './spawn-args.js';
11
+ import { buildPiEnv, buildSpawnArgs } from './spawn-args.js';
12
12
  import { createLineSplitter, encodeCommand } from './framing.js';
13
- import { piRpcLineToNormalized, createPIEventParserState } from './event-parser.js';
14
- import { PI_AGENT_DIR, PI_SESSIONS_DIR, writeProvidersConfig, buildProviderOverrides, ensureAuthVisible } from './agent-dir.js';
15
- import { parsePiListModelsOutput } from '../../core/gateway-generator.js';
16
- import { buildPrompt } from '../normalize/prompt-builder.js';
13
+ import { piRpcLineToNormalized, createPIEventParserState, piContextUsageFromStats } from './event-parser.js';
14
+ import { PI_AGENT_DIR, writeProvidersConfig, buildProviderOverrides, ensureAuthVisible } from './agent-dir.js';
17
15
  import { fromCanonical } from '../normalize/tool-names.js';
16
+ import { discoverPIProviders, piSessionFileExists } from './discovery.js';
17
+ import { CLOSE_EXIT_WAIT_MS, DEFAULT_PI_BINARY, EventQueue, PI_IDLE_SESSION_TIMEOUT, PI_MAX_TIMEOUT, PI_TURN_IDLE_TIMEOUT, PIContextUsageProbe, PI_CONTEXT_USAGE_TIMEOUT_MS, PISteeringQueue, SWITCH_SESSION_TIMEOUT_MS, buildPromptText, isPIContextSampleBoundary, parseRpcObject, } from './session-support.js';
18
+ import { DEFAULT_SESSION_DIR, HOOK_BRIDGE_PATH, MCP_BRIDGE_PATH, TOOL_SHIMS_PATH } from './defaults.js';
18
19
  const log = createLogger('pi-adapter');
19
- function buildPromptText(msg) {
20
- return buildPrompt(msg.text, msg.attachments ?? []);
20
+ function record(value) {
21
+ return value && typeof value === 'object' && !Array.isArray(value)
22
+ ? value
23
+ : {};
21
24
  }
22
- /**
23
- * Discover unique PI provider names by shelling out to `pi --list-models`. Called at spawn time
24
- * so the multi-provider models.json reflects whatever the user has currently authenticated to.
25
- *
26
- * PI writes the table to stderr — merge via 2>&1. Returns empty array on any failure (PI not
27
- * installed, timeout, parse error); the caller logs a warning and proceeds without overriding
28
- * models.json, which means the PI subprocess will fall back to direct upstream calls.
29
- *
30
- * Uses the user's real ~/.pi/agent/ for discovery (no PI_CODING_AGENT_DIR override) — symmetric
31
- * with cortex init's gateway-generator.scanPIViaListModels(). ensureAuthVisible() then mirrors
32
- * the auth file into PI_AGENT_DIR so the actual spawn can see those credentials.
33
- */
34
- function discoverPIProviders() {
35
- try {
36
- const stdout = execSync('pi --list-models 2>&1', {
37
- timeout: 10_000,
38
- encoding: 'utf-8',
39
- // Intentionally do NOT set PI_CODING_AGENT_DIR — read user's real PI config.
40
- env: { ...process.env, PI_CODING_AGENT_DIR: '' },
41
- });
42
- const models = parsePiListModelsOutput(stdout);
43
- const uniq = new Set();
44
- for (const m of models)
45
- uniq.add(m.provider);
46
- return Array.from(uniq);
47
- }
48
- catch (err) {
49
- log.info(`pi --list-models failed at spawn: ${err.message ?? 'unknown'}`);
50
- return [];
51
- }
25
+ function numberOrNull(value) {
26
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
52
27
  }
53
- const DEFAULT_PI_BINARY = 'pi';
54
- // DEFAULT_SESSION_DIR: sessionId.jsonl files are stored here (convention: <sessionDir>/<sessionId>.jsonl).
55
- // Sessions stored under logs/sessions-pi/; PI_CODING_AGENT_DIR points to data/ for models.json.
56
- const DEFAULT_SESSION_DIR = PI_SESSIONS_DIR;
57
- // PI extensions point at compiled dist/.js files — PI's extension loader accepts both .ts and .js
58
- // (pi-coding-agent dist/core/extensions/loader.js:367). Shipping .js avoids depending on src/ in
59
- // the installed package (package.json#files only ships dist/ + defaults/).
60
- const MCP_BRIDGE_PATH = path.join(INSTALL_ROOT, 'dist/agent-adapter/pi/mcp-bridge.js');
61
- const TOOL_SHIMS_PATH = path.join(INSTALL_ROOT, 'dist/agent-adapter/pi/tool-shims.js');
62
- const HOOK_BRIDGE_PATH = path.join(INSTALL_ROOT, 'dist/agent-adapter/pi/hook-bridge.js');
63
- // Per FINDINGS.md §S1, pi rpc exits cleanly on stdin close; observed bootstrap cost ≈ 500 ms.
64
- // 5 s is a safety margin; if pi does not exit in that window close() falls back to SIGTERM.
65
- const CLOSE_EXIT_WAIT_MS = 5000;
66
- // switch_session response timeout: if pi does not ack within this window, reject the pending promise.
67
- const SWITCH_SESSION_TIMEOUT_MS = 5000;
68
- const PI_IDLE_SESSION_TIMEOUT = 65 * 60 * 1000;
69
- const PI_TURN_IDLE_TIMEOUT = 60 * 60 * 1000;
70
- const PI_MAX_TIMEOUT = 30_000_000;
71
- class EventQueue {
72
- pending = [];
73
- waiters = [];
74
- closed = false;
75
- push(evt) {
76
- if (this.closed)
77
- return;
78
- const waiter = this.waiters.shift();
79
- if (waiter)
80
- waiter({ value: evt, done: false });
81
- else
82
- this.pending.push(evt);
83
- }
84
- next() {
85
- const buffered = this.pending.shift();
86
- if (buffered)
87
- return Promise.resolve({ value: buffered, done: false });
88
- if (this.closed)
89
- return Promise.resolve({ value: undefined, done: true });
90
- return new Promise((resolve) => {
91
- this.waiters.push(resolve);
92
- });
93
- }
94
- close() {
95
- if (this.closed)
96
- return;
97
- this.closed = true;
98
- for (const w of this.waiters.splice(0)) {
99
- w({ value: undefined, done: true });
100
- }
101
- }
28
+ function compactUsage(data) {
29
+ const usage = record(data['usage']);
30
+ if (Object.keys(usage).length === 0)
31
+ return null;
32
+ return {
33
+ inputTokens: numberOrNull(usage['input']) ?? 0,
34
+ outputTokens: numberOrNull(usage['output']) ?? 0,
35
+ cacheReadTokens: numberOrNull(usage['cacheRead']) ?? 0,
36
+ cacheWriteTokens: numberOrNull(usage['cacheWrite']) ?? 0,
37
+ costUsd: numberOrNull(record(usage['cost'])['total']),
38
+ };
39
+ }
40
+ function compactBase(data) {
41
+ const value = record(data);
42
+ return {
43
+ status: 'compacted',
44
+ tokensBefore: numberOrNull(value['tokensBefore']),
45
+ estimatedTokensAfter: numberOrNull(value['estimatedTokensAfter']),
46
+ usage: compactUsage(value),
47
+ };
48
+ }
49
+ function rpcErrorMessage(raw) {
50
+ const error = raw['error'];
51
+ if (typeof error === 'string')
52
+ return error;
53
+ const nested = record(error)['message'];
54
+ if (typeof nested === 'string')
55
+ return nested;
56
+ const dataMessage = record(raw['data'])['message'];
57
+ return typeof dataMessage === 'string' ? dataMessage : 'PI compact failed';
58
+ }
59
+ function isNothingToCompact(message) {
60
+ return /no messages to compact/i.test(message);
102
61
  }
103
62
  class PISession {
104
63
  sessionKey;
@@ -125,23 +84,48 @@ class PISession {
125
84
  exitPromise;
126
85
  /** Buffer for assistant_text deltas; flushed on message_end / turn_complete / non-text events. */
127
86
  textBuffer = '';
87
+ /** blockId of the text currently in textBuffer; attached to the flushed assistant_text. */
88
+ textBlockId = null;
89
+ /**
90
+ * Streaming preview gate, resolved once at spawn time (CORTEX_STREAM_DELTAS=0 disables it).
91
+ * Only assistant_delta is suppressed — the buffered whole message is unaffected.
92
+ */
93
+ streamDeltas;
128
94
  idleTimer = null;
129
95
  turnIdleTimer = null;
130
96
  maxTimer = null;
131
97
  pendingSwitch = null;
132
98
  pendingSwitchTimer = null;
133
- /** Accumulator for the current in-flight turn. Resolved/rejected by handleRawLine. */
99
+ /** Accumulator for the current in-flight Cortex turn. Resolved/rejected by handleRawLine. */
134
100
  pendingTurn = null;
101
+ steering = new PISteeringQueue();
102
+ /**
103
+ * Where PI's own agent loop is, tracked off its event stream because the injection RPC form
104
+ * depends on it. `starting` = a prompt is written but PI has not entered the loop yet; PI still
105
+ * reads its internal run flag as inactive there and only the dedicated steer command is safe.
106
+ */
107
+ loopState = 'idle';
108
+ contextUsageProbe;
109
+ readyWaiters = [];
110
+ pendingCompact = null;
111
+ compactSequence = 0;
135
112
  constructor(opts) {
136
113
  this.sessionKey = opts.sessionKey;
137
114
  this.registry = opts.registry;
138
115
  this.registrySessionDir = opts.registrySessionDir;
139
116
  this.onClose = opts.onClose;
117
+ this.streamDeltas = process.env['CORTEX_STREAM_DELTAS'] !== '0';
140
118
  this.proc = opts.spawner(DEFAULT_PI_BINARY, opts.cliArgs, {
141
119
  cwd: opts.cwd,
142
120
  env: opts.env,
143
121
  stdio: ['pipe', 'pipe', 'pipe'],
144
122
  });
123
+ this.contextUsageProbe = new PIContextUsageProbe((command) => {
124
+ const stdin = this.proc.stdin;
125
+ if (!stdin || stdin.destroyed || stdin.writableEnded)
126
+ throw new Error('PI stdin unavailable');
127
+ stdin.write(encodeCommand(command));
128
+ }, (event) => this.emitNormalizedEvent(event));
145
129
  this.proc.stdout?.on('data', (chunk) => {
146
130
  for (const line of this.splitter.push(chunk))
147
131
  this.handleRawLine(line);
@@ -153,6 +137,9 @@ class PISession {
153
137
  this.exitPromise = new Promise((resolve) => {
154
138
  this.proc.once('close', (code) => {
155
139
  this.alive = false;
140
+ const exitError = new Error(this.stderrTail || `pi exited with code ${code ?? 0}`);
141
+ this.settleReadyWaiters(exitError);
142
+ this.rejectCompact(exitError);
156
143
  // Reject any pending switch_session promise on unexpected subprocess exit.
157
144
  if (this.pendingSwitch !== null) {
158
145
  const entry = this.pendingSwitch;
@@ -163,6 +150,10 @@ class PISession {
163
150
  }
164
151
  entry.reject(new Error('pi subprocess exited while switch_session was pending'));
165
152
  }
153
+ // Seal every accepted steering message before rejecting the outer turn. This releases
154
+ // orchestration's pending UI row and busy bracket even when PI dies before consumption.
155
+ this.steering.abandon();
156
+ this.steering.clearSink();
166
157
  // Reject any pending turn promise if the process exits without a turn_complete.
167
158
  if (this.pendingTurn !== null) {
168
159
  const t = this.pendingTurn;
@@ -181,6 +172,7 @@ class PISession {
181
172
  fatal: true,
182
173
  });
183
174
  }
175
+ this.contextUsageProbe.close();
184
176
  this.events.close();
185
177
  // Remove stream listeners and destroy streams so stub PassThrough streams
186
178
  // (used in tests) don't keep the event loop alive after close.
@@ -207,12 +199,18 @@ class PISession {
207
199
  this.onClose?.(this.sessionKey);
208
200
  }, PI_MAX_TIMEOUT);
209
201
  }
210
- /** Flush buffered text as a single assistant_text event. */
202
+ /**
203
+ * Flush buffered text as a single assistant_text event, tagged with the blockId its deltas
204
+ * carried so the UI can replace the streamed preview with this authoritative message.
205
+ */
211
206
  flushTextBuffer() {
212
207
  if (this.textBuffer.length > 0) {
213
- this.events.push({ type: 'assistant_text', text: this.textBuffer });
208
+ this.events.push(this.textBlockId !== null
209
+ ? { type: 'assistant_text', text: this.textBuffer, blockId: this.textBlockId }
210
+ : { type: 'assistant_text', text: this.textBuffer });
214
211
  this.textBuffer = '';
215
212
  }
213
+ this.textBlockId = null;
216
214
  }
217
215
  clearTimers() {
218
216
  if (this.idleTimer) {
@@ -227,6 +225,7 @@ class PISession {
227
225
  clearTimeout(this.maxTimer);
228
226
  this.maxTimer = null;
229
227
  }
228
+ this.contextUsageProbe.close();
230
229
  this.flushTextBuffer();
231
230
  }
232
231
  resetIdleTimer() {
@@ -251,6 +250,117 @@ class PISession {
251
250
  clearTimeout(this.turnIdleTimer);
252
251
  this.startTurnIdleTimer();
253
252
  }
253
+ waitForBootstrap() {
254
+ if (this.sessionId !== null)
255
+ return Promise.resolve();
256
+ return new Promise((resolve, reject) => {
257
+ const waiter = {};
258
+ waiter.resolve = resolve;
259
+ waiter.reject = reject;
260
+ waiter.timer = setTimeout(() => {
261
+ const index = this.readyWaiters.indexOf(waiter);
262
+ if (index !== -1)
263
+ this.readyWaiters.splice(index, 1);
264
+ reject(new Error('PI compact timed out waiting for bootstrap'));
265
+ }, SWITCH_SESSION_TIMEOUT_MS);
266
+ waiter.timer.unref?.();
267
+ this.readyWaiters.push(waiter);
268
+ });
269
+ }
270
+ settleReadyWaiters(error) {
271
+ for (const waiter of this.readyWaiters.splice(0)) {
272
+ clearTimeout(waiter.timer);
273
+ if (error)
274
+ waiter.reject(error);
275
+ else
276
+ waiter.resolve();
277
+ }
278
+ }
279
+ async compact() {
280
+ if (this.pendingCompact)
281
+ throw new Error('PI compact already in progress');
282
+ await this.waitForBootstrap();
283
+ const id = `compact-${++this.compactSequence}`;
284
+ return new Promise((resolve, reject) => {
285
+ const timer = setTimeout(() => this.rejectCompact(new Error('PI compact timed out')), PI_TURN_IDLE_TIMEOUT);
286
+ timer.unref?.();
287
+ this.pendingCompact = { id, statsId: null, base: null, resolve, reject, timer };
288
+ try {
289
+ this.proc.stdin?.write(encodeCommand({ id, type: 'compact' }));
290
+ }
291
+ catch (error) {
292
+ this.rejectCompact(error instanceof Error ? error : new Error(String(error)));
293
+ }
294
+ });
295
+ }
296
+ handleCompactResponse(raw) {
297
+ const pending = this.pendingCompact;
298
+ if (!pending || raw?.['type'] !== 'response')
299
+ return false;
300
+ if (raw['command'] === 'compact' && raw['id'] === pending.id) {
301
+ this.handleCompactCommandResponse(raw);
302
+ return true;
303
+ }
304
+ if (raw['command'] === 'get_session_stats' && raw['id'] === pending.statsId) {
305
+ this.handleCompactStatsResponse(raw);
306
+ return true;
307
+ }
308
+ return false;
309
+ }
310
+ handleCompactCommandResponse(raw) {
311
+ if (raw['success'] === true) {
312
+ this.requestCompactStats(compactBase(raw['data']));
313
+ return;
314
+ }
315
+ const message = rpcErrorMessage(raw);
316
+ if (isNothingToCompact(message)) {
317
+ this.resolveCompact({
318
+ status: 'not-needed', tokensBefore: null, estimatedTokensAfter: null,
319
+ contextUsage: null, usage: null,
320
+ });
321
+ return;
322
+ }
323
+ this.rejectCompact(new Error(message));
324
+ }
325
+ requestCompactStats(base) {
326
+ const pending = this.pendingCompact;
327
+ if (!pending)
328
+ return;
329
+ pending.base = base;
330
+ pending.statsId = `compact-stats-${++this.compactSequence}`;
331
+ clearTimeout(pending.timer);
332
+ pending.timer = setTimeout(() => this.resolveCompact({ ...base, contextUsage: null }), PI_CONTEXT_USAGE_TIMEOUT_MS);
333
+ pending.timer.unref?.();
334
+ try {
335
+ this.proc.stdin?.write(encodeCommand({ id: pending.statsId, type: 'get_session_stats' }));
336
+ }
337
+ catch {
338
+ this.resolveCompact({ ...base, contextUsage: null });
339
+ }
340
+ }
341
+ handleCompactStatsResponse(raw) {
342
+ const base = this.pendingCompact?.base;
343
+ if (!base)
344
+ return;
345
+ const contextUsage = raw['success'] === true ? piContextUsageFromStats(raw['data']) : null;
346
+ this.resolveCompact({ ...base, contextUsage });
347
+ }
348
+ resolveCompact(result) {
349
+ const pending = this.pendingCompact;
350
+ if (!pending)
351
+ return;
352
+ clearTimeout(pending.timer);
353
+ this.pendingCompact = null;
354
+ pending.resolve(result);
355
+ }
356
+ rejectCompact(error) {
357
+ const pending = this.pendingCompact;
358
+ if (!pending)
359
+ return;
360
+ clearTimeout(pending.timer);
361
+ this.pendingCompact = null;
362
+ pending.reject(error);
363
+ }
254
364
  get eventsIterable() {
255
365
  return {
256
366
  [Symbol.asyncIterator]: () => ({
@@ -263,124 +373,233 @@ class PISession {
263
373
  return;
264
374
  this.resetIdleTimer();
265
375
  this.bumpTurnIdleTimer();
266
- // Intercept switch_session response BEFORE event-parser: event-parser silently drops
267
- // successful non-bootstrap responses (return []), so switch_session acks must be
268
- // correlated here to resolve/reject the pending promise.
269
- if (this.pendingSwitch !== null) {
270
- let obj = null;
271
- try {
272
- obj = JSON.parse(line);
273
- }
274
- catch { /* fall through to event-parser */ }
275
- if (obj && typeof obj === 'object') {
276
- const r = obj;
277
- if (r['type'] === 'response' &&
278
- r['command'] === 'switch_session' &&
279
- r['id'] === this.pendingSwitch.id) {
280
- const entry = this.pendingSwitch;
281
- this.pendingSwitch = null;
282
- if (this.pendingSwitchTimer !== null) {
283
- clearTimeout(this.pendingSwitchTimer);
284
- this.pendingSwitchTimer = null;
285
- }
286
- const data = r['data'];
287
- const cancelled = data && typeof data === 'object'
288
- ? Boolean(data['cancelled'])
289
- : false;
290
- entry.resolve({ ok: r['success'] === true, cancelled });
291
- return;
292
- }
293
- }
294
- }
376
+ const raw = parseRpcObject(line);
377
+ if (this.handleCompactResponse(raw))
378
+ return;
379
+ if (this.handleSwitchResponse(raw))
380
+ return;
381
+ const finishDeferred = this.handleInjectionProtocol(raw);
295
382
  for (const evt of piRpcLineToNormalized(line, this.parserState)) {
296
- if (evt.type === 'session_started' && this.sessionId === null) {
297
- this.sessionId = evt.sessionId;
298
- this.currentSessionId = evt.sessionId;
299
- // Use sessionFile from bootstrap if available; fall back to legacy path guess.
300
- if (evt.sessionFile) {
301
- this.sessionFile = evt.sessionFile;
302
- this.registry.set(evt.sessionId, evt.sessionFile);
303
- }
304
- else {
305
- this.registry.set(evt.sessionId, path.join(this.registrySessionDir, `${evt.sessionId}.jsonl`));
306
- }
307
- }
308
- // Accumulate turn result data for pending send() promise.
309
- if (this.pendingTurn !== null) {
310
- if (evt.type === 'plan_written') {
311
- this.pendingTurn.planFilePath = evt.path;
312
- }
313
- else if (evt.type === 'ask_user_question') {
314
- // Do NOT accumulate in pendingTurn.askUserQuestions: PI ask_user_question
315
- // events are handled in real-time via the facade event loop → onAskUserQuestion
316
- // callback → Slack interaction → sendExtensionUiResponse. Accumulating here
317
- // would cause handleAgentSuccess to re-post the already-answered questions
318
- // via sendMessages after turn_complete, leaving the agent stuck in
319
- // "Waiting for user input" forever.
320
- }
321
- else if (evt.type === 'rate_limit') {
322
- this.pendingTurn.rateLimited = true;
323
- }
324
- else if (evt.type === 'turn_complete') {
325
- // Flush buffered text before resolving the turn so downstream sees all text.
326
- this.flushTextBuffer();
327
- if (this.turnIdleTimer) {
328
- clearTimeout(this.turnIdleTimer);
329
- this.turnIdleTimer = null;
330
- }
331
- const t = this.pendingTurn;
332
- this.pendingTurn = null;
333
- if (evt.error) {
334
- // Turn-level error (e.g. gateway "400 Unknown mode") — fail the turn so the lifecycle
335
- // shows ❌ Error and posts the message, matching the Claude adapter's is_error path.
336
- // Fall through (no continue) so turn_complete is still pushed to this.events and the
337
- // facade event loop terminates cleanly, exactly like the fatal-error branch below.
338
- t.reject(new Error(evt.error));
339
- }
340
- else {
341
- const result = {
342
- sessionId: this.sessionId,
343
- total_cost_usd: evt.totalCostUsd,
344
- num_turns: evt.numTurns,
345
- rateLimited: t.rateLimited,
346
- rateLimitMessage: null,
347
- planFilePath: t.planFilePath,
348
- enteredPlanMode: false,
349
- exitedPlanMode: t.planFilePath !== null,
350
- askUserQuestions: t.askUserQuestions.length > 0 ? t.askUserQuestions : undefined,
351
- finalOutput: null,
352
- };
353
- t.resolve(result);
354
- }
355
- }
356
- else if (evt.type === 'error' && evt.fatal) {
357
- this.flushTextBuffer();
358
- if (this.turnIdleTimer) {
359
- clearTimeout(this.turnIdleTimer);
360
- this.turnIdleTimer = null;
361
- }
362
- const t = this.pendingTurn;
363
- this.pendingTurn = null;
364
- t.reject(new Error(evt.message));
365
- }
366
- }
367
- // Buffer assistant_text deltas until a message boundary (turn_progress from
368
- // message_end) or a non-text event arrives, then flush as a single event.
369
- // This matches Claude adapter behavior where onAssistantMessage fires once
370
- // per complete assistant message block, not per token.
371
- if (evt.type === 'assistant_text') {
372
- this.textBuffer += evt.text;
373
- }
374
- else {
375
- this.flushTextBuffer();
376
- this.events.push(evt);
377
- }
383
+ this.captureSessionStarted(evt);
384
+ const output = this.processPendingTurnEvent(evt);
385
+ if (output !== null)
386
+ this.emitOrProbeContext(output);
387
+ }
388
+ if (finishDeferred) {
389
+ const terminal = this.finishDeferredTurn();
390
+ if (terminal !== null)
391
+ this.emitOrProbeContext(terminal);
392
+ }
393
+ this.contextUsageProbe.observe(raw);
394
+ if (this.pendingTurn && isPIContextSampleBoundary(raw))
395
+ this.contextUsageProbe.requestSnapshot();
396
+ }
397
+ emitOrProbeContext(event) {
398
+ if (event.type === 'turn_complete')
399
+ this.contextUsageProbe.deferTerminal(event);
400
+ else
401
+ this.emitNormalizedEvent(event);
402
+ }
403
+ /** Correlate switch_session before the generic parser drops its response. */
404
+ handleSwitchResponse(raw) {
405
+ const pending = this.pendingSwitch;
406
+ if (pending === null || raw?.['type'] !== 'response' ||
407
+ raw['command'] !== 'switch_session' || raw['id'] !== pending.id)
408
+ return false;
409
+ this.pendingSwitch = null;
410
+ if (this.pendingSwitchTimer !== null) {
411
+ clearTimeout(this.pendingSwitchTimer);
412
+ this.pendingSwitchTimer = null;
413
+ }
414
+ const data = raw['data'];
415
+ const cancelled = data && typeof data === 'object'
416
+ ? Boolean(data['cancelled'])
417
+ : false;
418
+ pending.resolve({ ok: raw['success'] === true, cancelled });
419
+ return true;
420
+ }
421
+ /** Observe PI-only delivery/rejection events that intentionally stay out of NormalizedEvent. */
422
+ handleInjectionProtocol(raw) {
423
+ // agent_start is emitted from inside the loop, so it is the first point at which PI's own run
424
+ // flag is provably set; agent_settled is the point at which it is provably clear again.
425
+ if (raw?.['type'] === 'agent_start')
426
+ this.loopState = 'running';
427
+ else if (raw?.['type'] === 'agent_settled')
428
+ this.loopState = 'idle';
429
+ if (raw?.['type'] === 'message_start' && this.isUserStart(raw['message'])) {
430
+ const turn = this.pendingTurn;
431
+ if (turn && !turn.openingUserSeen)
432
+ turn.openingUserSeen = true;
433
+ else if (turn)
434
+ this.steering.consumeNext();
435
+ return false;
436
+ }
437
+ if (!raw || !this.steering.rejectFromResponse(raw))
438
+ return false;
439
+ return !this.steering.hasPending && this.pendingTurn?.deferredCompletion === true;
440
+ }
441
+ isUserStart(message) {
442
+ return !!message && typeof message === 'object' &&
443
+ message['role'] === 'user';
444
+ }
445
+ captureSessionStarted(evt) {
446
+ if (evt.type !== 'session_started' || this.sessionId !== null)
447
+ return;
448
+ this.sessionId = evt.sessionId;
449
+ this.currentSessionId = evt.sessionId;
450
+ this.settleReadyWaiters();
451
+ if (evt.sessionFile) {
452
+ this.sessionFile = evt.sessionFile;
453
+ this.registry.set(evt.sessionId, evt.sessionFile);
454
+ }
455
+ else {
456
+ this.registry.set(evt.sessionId, path.join(this.registrySessionDir, `${evt.sessionId}.jsonl`));
457
+ }
458
+ }
459
+ /** Update the outer send() promise and optionally replace/suppress a terminal event. */
460
+ processPendingTurnEvent(evt) {
461
+ const turn = this.pendingTurn;
462
+ if (!turn)
463
+ return evt;
464
+ if (evt.type === 'plan_written')
465
+ turn.planFilePath = evt.path;
466
+ // ask_user_question is handled live by the facade; accumulating it would post it twice.
467
+ else if (evt.type === 'ask_user_question') { /* intentionally not accumulated */ }
468
+ else if (evt.type === 'turn_complete')
469
+ return this.handleTurnComplete(evt);
470
+ else if (evt.type === 'error' && evt.fatal) {
471
+ this.flushTextBuffer();
472
+ this.clearTurnIdleTimer();
473
+ this.steering.abandon();
474
+ this.pendingTurn = null;
475
+ turn.reject(new Error(evt.message));
476
+ }
477
+ return evt;
478
+ }
479
+ handleTurnComplete(evt) {
480
+ const turn = this.pendingTurn;
481
+ this.flushTextBuffer();
482
+ turn.numTurns += evt.numTurns;
483
+ if (evt.totalCostUsd !== null)
484
+ turn.totalCostUsd = (turn.totalCostUsd ?? 0) + evt.totalCostUsd;
485
+ if (evt.error) {
486
+ this.steering.abandon();
487
+ return this.settlePendingTurn(evt.error);
488
+ }
489
+ if (this.steering.hasPending) {
490
+ turn.deferredCompletion = true;
491
+ return null;
492
+ }
493
+ return this.settlePendingTurn();
494
+ }
495
+ finishDeferredTurn() {
496
+ if (!this.pendingTurn?.deferredCompletion || this.steering.hasPending)
497
+ return null;
498
+ return this.settlePendingTurn();
499
+ }
500
+ settlePendingTurn(error) {
501
+ const turn = this.pendingTurn;
502
+ this.pendingTurn = null;
503
+ this.clearTurnIdleTimer();
504
+ const terminal = error
505
+ ? { type: 'turn_complete', numTurns: turn.numTurns, totalCostUsd: turn.totalCostUsd, error }
506
+ : { type: 'turn_complete', numTurns: turn.numTurns, totalCostUsd: turn.totalCostUsd };
507
+ if (error)
508
+ turn.reject(new Error(error));
509
+ else
510
+ turn.resolve(this.buildAgentResult(turn));
511
+ return terminal;
512
+ }
513
+ buildAgentResult(turn) {
514
+ return {
515
+ sessionId: this.sessionId,
516
+ total_cost_usd: turn.totalCostUsd,
517
+ num_turns: turn.numTurns,
518
+ rateLimited: false,
519
+ rateLimitMessage: null,
520
+ planFilePath: turn.planFilePath,
521
+ enteredPlanMode: false,
522
+ exitedPlanMode: turn.planFilePath !== null,
523
+ askUserQuestions: turn.askUserQuestions.length > 0 ? turn.askUserQuestions : undefined,
524
+ finalOutput: null,
525
+ };
526
+ }
527
+ clearTurnIdleTimer() {
528
+ if (!this.turnIdleTimer)
529
+ return;
530
+ clearTimeout(this.turnIdleTimer);
531
+ this.turnIdleTimer = null;
532
+ }
533
+ /** Buffer deltas into whole assistant messages while preserving Web preview events. */
534
+ emitNormalizedEvent(evt) {
535
+ if (evt.type === 'context_usage') {
536
+ this.events.push(evt);
537
+ return;
538
+ }
539
+ if (evt.type !== 'assistant_text') {
540
+ this.flushTextBuffer();
541
+ this.events.push(evt);
542
+ return;
378
543
  }
544
+ const blockId = evt.blockId ?? null;
545
+ if (this.textBuffer.length > 0 && blockId !== this.textBlockId)
546
+ this.flushTextBuffer();
547
+ this.textBlockId = blockId;
548
+ if (this.streamDeltas && blockId !== null) {
549
+ this.events.push({ type: 'assistant_delta', text: evt.text, blockId });
550
+ }
551
+ this.textBuffer += evt.text;
379
552
  }
380
553
  send(msg) {
381
554
  if (!this.alive)
382
555
  throw new Error('PISession.send: subprocess is not alive');
383
- this.proc.stdin?.write(encodeCommand({ type: 'prompt', message: buildPromptText(msg) }));
556
+ this.writeOpeningPrompt(buildPromptText(msg));
557
+ }
558
+ writeOpeningPrompt(promptText) {
559
+ const stdin = this.proc.stdin;
560
+ if (!stdin)
561
+ throw new Error('PISession: subprocess stdin is unavailable');
562
+ stdin.write(encodeCommand({ type: 'prompt', message: promptText }));
563
+ this.loopState = 'starting';
564
+ if (this.pendingTurn)
565
+ this.pendingTurn.promptDispatched = true;
566
+ }
567
+ /**
568
+ * Queue a message at PI's next agent-loop boundary without opening a new Cortex run.
569
+ *
570
+ * The RPC form has to follow PI's loop state. A `prompt` with streamingBehavior=steer is only
571
+ * queued when PI already considers itself streaming; written during the prompt preflight window
572
+ * (which includes our own before_agent_start hook scripts, seconds long) PI instead takes its
573
+ * plain-prompt path, acks success, then throws internally and drops the message — and that failed
574
+ * path clears PI's run flag, so every later injection in the same turn takes the same broken
575
+ * branch. The dedicated `steer` command bypasses that check entirely and is drained by the
576
+ * opening steering poll of the loop that is about to start. Once the loop is running, or once PI
577
+ * has settled and the message must reopen a turn, prompt+steer is the correct form.
578
+ */
579
+ injectUserMessage(msg) {
580
+ const stdin = this.proc.stdin;
581
+ if (!this.alive || !this.pendingTurn?.promptDispatched || !stdin ||
582
+ stdin.destroyed || stdin.writableEnded)
583
+ return false;
584
+ const entry = this.steering.begin(msg.text);
585
+ const message = buildPromptText(msg);
586
+ const preflight = this.loopState === 'starting';
587
+ try {
588
+ stdin.write(encodeCommand(preflight
589
+ ? { id: entry.id, type: 'steer', message }
590
+ : { id: entry.id, type: 'prompt', message, streamingBehavior: 'steer' }));
591
+ // A prompt written to an idle PI opens a fresh run, so the next injection is a preflight one.
592
+ if (this.loopState === 'idle')
593
+ this.loopState = 'starting';
594
+ return true;
595
+ }
596
+ catch {
597
+ this.steering.rollback(entry);
598
+ return false;
599
+ }
600
+ }
601
+ setInjectionAckSink(sink) {
602
+ this.steering.setSink(sink);
384
603
  }
385
604
  /**
386
605
  * Send switch_session RPC and await ack from pi.
@@ -420,7 +639,7 @@ class PISession {
420
639
  if (this.currentSessionId !== targetSessionId) {
421
640
  if (targetPath === null) {
422
641
  // Can't switch without a path; write prompt to current session as fallback.
423
- this.proc.stdin?.write(encodeCommand({ type: 'prompt', message: promptText }));
642
+ this.writeOpeningPrompt(promptText);
424
643
  return { switched: false, cancelled: false };
425
644
  }
426
645
  const result = await this.sendSwitchSession(targetPath);
@@ -430,11 +649,11 @@ class PISession {
430
649
  // BLOCKER-1 fix: write prompt in every branch regardless of result.ok.
431
650
  // NTH-A: if result.ok===false (pi rejected switch), the prompt goes to the current
432
651
  // (un-switched) session — intentional best-effort, caller can inspect result.ok.
433
- this.proc.stdin?.write(encodeCommand({ type: 'prompt', message: promptText }));
652
+ this.writeOpeningPrompt(promptText);
434
653
  return { switched: result.ok, cancelled: result.cancelled };
435
654
  }
436
655
  // Same session: write prompt directly.
437
- this.proc.stdin?.write(encodeCommand({ type: 'prompt', message: promptText }));
656
+ this.writeOpeningPrompt(promptText);
438
657
  return { switched: false, cancelled: false };
439
658
  }
440
659
  /**
@@ -462,9 +681,11 @@ class PISession {
462
681
  reject,
463
682
  planFilePath: null,
464
683
  askUserQuestions: [],
465
- rateLimited: false,
466
- numTurns: null,
684
+ numTurns: 0,
467
685
  totalCostUsd: null,
686
+ promptDispatched: false,
687
+ openingUserSeen: false,
688
+ deferredCompletion: false,
468
689
  };
469
690
  this.startTurnIdleTimer();
470
691
  }
@@ -473,6 +694,7 @@ class PISession {
473
694
  if (this.pendingTurn !== null) {
474
695
  const t = this.pendingTurn;
475
696
  this.pendingTurn = null;
697
+ this.steering.abandon();
476
698
  t.reject(err);
477
699
  }
478
700
  }
@@ -524,7 +746,21 @@ export class PIAdapter {
524
746
  // The sessionPathRegistry is populated below from the bootstrap session_started
525
747
  // event for switchSession / sendTurn path lookups — it is NOT used for the
526
748
  // --session CLI flag here.
527
- const sessionIdForSpawn = (config.resume && config.sessionId) ? config.sessionId : null;
749
+ //
750
+ // Guard (mirrors Claude's resolveResumeForPrint): PI's `--session <id>` can only RESUME an
751
+ // existing session — unlike Claude it cannot create/force a session under an externally-supplied
752
+ // id. If the requested id has no matching session (a fresh session, or a stale backendSessionId
753
+ // whose file was pruned), passing --session makes PI exit with "No session found matching <id>".
754
+ // So only resume when the session is known: either bootstrapped in THIS adapter instance (path
755
+ // registry) or present on disk (a prior process / persisted backendSessionId). Otherwise start
756
+ // fresh and let PI bootstrap its own id (captured back as backendSessionId by the caller).
757
+ const wantResume = !!(config.resume && config.sessionId);
758
+ const sessionKnown = wantResume &&
759
+ (this.sessionPathRegistry.has(config.sessionId) || piSessionFileExists(sessionDir, config.sessionId));
760
+ const sessionIdForSpawn = sessionKnown ? config.sessionId : null;
761
+ if (wantResume && sessionIdForSpawn === null) {
762
+ log.info(`PI resume target '${config.sessionId}' not found (no live session or file in ${sessionDir}); starting fresh`);
763
+ }
528
764
  const cliArgs = buildSpawnArgs({
529
765
  sessionDir,
530
766
  sessionId: sessionIdForSpawn,
@@ -535,6 +771,7 @@ export class PIAdapter {
535
771
  pluginDirs: config.pluginDirs ?? null,
536
772
  // All three extensions always injected: MCP bridge (task 5754) + tool shims (task 5b5c) + hook bridge (task d3ae).
537
773
  extensionPaths: [MCP_BRIDGE_PATH, TOOL_SHIMS_PATH, HOOK_BRIDGE_PATH],
774
+ thinking: config.thinking ?? null,
538
775
  extraOption: config.extraOption ?? null,
539
776
  });
540
777
  // Pre-spawn config sync (sole writers of PI_AGENT_DIR — no other code path touches these files):
@@ -568,11 +805,6 @@ export class PIAdapter {
568
805
  log.warn(`Failed to write PI models.json: ${err.message}`);
569
806
  }
570
807
  }
571
- const env = { ...process.env, ...(config.env ?? {}), PI_CODING_AGENT_DIR: PI_AGENT_DIR };
572
- if (config.channel) {
573
- env.SLACK_CHANNEL = config.channel;
574
- env.FEISHU_CHANNEL = config.channel;
575
- }
576
808
  // Forward the agent's tool allowlist (Claude-native names) so tool-shims.ts can gate which
577
809
  // pseudo-tools it registers — mirroring the Claude backend's `--tools` allowlist. Without this,
578
810
  // thread-dispatched agents (whose config excludes AskUserQuestion/EnterPlanMode/ExitPlanMode)
@@ -581,8 +813,16 @@ export class PIAdapter {
581
813
  ?? (config.tools && config.tools.length > 0
582
814
  ? config.tools.map((t) => fromCanonical('claude', t)).filter((n) => !!n).join(',')
583
815
  : undefined);
584
- if (allowedTools)
585
- env.CORTEX_PI_ALLOWED_TOOLS = allowedTools;
816
+ const env = buildPiEnv({
817
+ sessionId: config.sessionId,
818
+ channel: config.channel,
819
+ callbackSource: config.callbackSource,
820
+ scheduleTaskId: config.scheduleTaskId,
821
+ extraEnv: config.env,
822
+ context: config.cortexContext,
823
+ piAgentDir: PI_AGENT_DIR,
824
+ allowedTools,
825
+ });
586
826
  const cwd = config.cwd ?? DATA_DIR;
587
827
  const session = new PISession({
588
828
  sessionKey: config.sessionKey,
@@ -628,9 +868,12 @@ export class PIAdapter {
628
868
  }
629
869
  });
630
870
  },
871
+ compact: () => session.compact(),
631
872
  sendExtensionUiResponse: (id, payload) => {
632
873
  session.sendExtensionUiResponse(id, payload);
633
874
  },
875
+ injectUserMessage: (msg) => session.injectUserMessage(msg),
876
+ setInjectionAckSink: (sink) => session.setInjectionAckSink(sink),
634
877
  events: session.eventsIterable,
635
878
  close: async () => {
636
879
  await session.close();
@@ -689,14 +932,3 @@ export class PIAdapter {
689
932
  return Array.from(this.sessions.keys());
690
933
  }
691
934
  }
692
- export const _test = {
693
- buildSpawnArgs,
694
- encodeCommand,
695
- createLineSplitter,
696
- DEFAULT_SESSION_DIR,
697
- MCP_BRIDGE_PATH,
698
- TOOL_SHIMS_PATH,
699
- HOOK_BRIDGE_PATH,
700
- CLOSE_EXIT_WAIT_MS,
701
- SWITCH_SESSION_TIMEOUT_MS,
702
- };