@cortex-agent/server 2026.9.14 → 2026.9.21

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 (259) hide show
  1. package/README.md +3 -2
  2. package/defaults/config/hooks/08-agents-md-injector-post-tool.json +10 -0
  3. package/defaults/config/hooks/{10-cortex-md-injector-session-start.json → 10-agents-md-injector-session-start.json} +3 -3
  4. package/defaults/config/hooks/{CORTEX.md → AGENTS.md} +2 -2
  5. package/defaults/hooks/{CORTEX.md → AGENTS.md} +1 -1
  6. package/defaults/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  7. package/defaults/hooks/cortex-hook-api.mjs +2 -2
  8. package/defaults/hooks/new-session-hook.mjs +2 -2
  9. package/defaults/hooks/rules-loader.mjs +2 -2
  10. package/defaults/hooks/status-md-guard.mjs +8 -8
  11. package/defaults/hooks/task-status-check.mjs +18 -76
  12. package/defaults/hooks/tasks-yaml-guard.mjs +2 -2
  13. package/defaults/plugins/cortex-commission/.claude-plugin/plugin.json +2 -2
  14. package/defaults/plugins/cortex-commission/plugin.json +2 -2
  15. package/defaults/plugins/cortex-commission/skills/commission/SKILL.md +3 -3
  16. package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +1 -1
  17. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +2 -2
  18. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +4 -4
  19. package/defaults/plugins/cortex-system/skills/task/SKILL.md +1 -1
  20. package/defaults/rules/{cortex-md.md → agents-md.md} +4 -4
  21. package/defaults/rules/decision-records.md +1 -1
  22. package/defaults/rules/meta-conventions.md +4 -4
  23. package/defaults/rules/mission-md.md +1 -1
  24. package/dist/agent-adapter/claude/adapter.d.ts +0 -6
  25. package/dist/agent-adapter/claude/adapter.js +0 -8
  26. package/dist/agent-adapter/claude/defaults.d.ts +10 -7
  27. package/dist/agent-adapter/claude/defaults.js +18 -16
  28. package/dist/agent-adapter/claude/hooks-builder.js +2 -2
  29. package/dist/agent-adapter/claude/spawn-args.d.ts +0 -3
  30. package/dist/agent-adapter/claude/spawn-args.js +20 -16
  31. package/dist/agent-adapter/claude/turn-machine.d.ts +11 -0
  32. package/dist/agent-adapter/claude/turn-machine.js +46 -5
  33. package/dist/agent-adapter/normalize/prompt-builder.d.ts +16 -1
  34. package/dist/agent-adapter/normalize/prompt-builder.js +24 -6
  35. package/dist/agent-adapter/pi/mcp-bridge-logic.d.ts +11 -2
  36. package/dist/agent-adapter/pi/mcp-bridge-logic.js +32 -1
  37. package/dist/agent-adapter/pi/mcp-bridge.js +16 -15
  38. package/dist/agent-adapter/pi/session-options.d.ts +0 -6
  39. package/dist/agent-adapter/pi/session-options.js +1 -8
  40. package/dist/agent-adapter/types.d.ts +1 -1
  41. package/dist/core/mcp-tool-gate.d.ts +3 -17
  42. package/dist/core/mcp-tool-gate.js +4 -19
  43. package/dist/core/media-types.d.ts +10 -0
  44. package/dist/core/media-types.js +34 -0
  45. package/dist/core/platform-settings-spec.js +1 -1
  46. package/dist/core/settings-spec.d.ts +22 -1
  47. package/dist/core/settings-spec.js +33 -2
  48. package/dist/core/types/agent-types.d.ts +3 -1
  49. package/dist/core/utils.d.ts +1 -1
  50. package/dist/core/utils.js +1 -1
  51. package/dist/domain/agents/config.d.ts +1 -1
  52. package/dist/domain/agents/config.js +1 -1
  53. package/dist/domain/agents/profile-switch.d.ts +1 -1
  54. package/dist/domain/agents/profile-switch.js +3 -5
  55. package/dist/domain/agents/subagent/runner.js +0 -1
  56. package/dist/domain/commissions/commission-draft.d.ts +58 -0
  57. package/dist/domain/commissions/commission-draft.js +87 -4
  58. package/dist/domain/commissions/commission-finalize.d.ts +8 -3
  59. package/dist/domain/commissions/commission-finalize.js +14 -0
  60. package/dist/domain/executions/registry.d.ts +1 -2
  61. package/dist/domain/executions/registry.js +0 -3
  62. package/dist/domain/mcp/bundled-server.js +4 -3
  63. package/dist/domain/mcp/feishu/file.js +37 -18
  64. package/dist/domain/mcp/feishu/types.d.ts +3 -0
  65. package/dist/domain/mcp/feishu-server.js +1 -1
  66. package/dist/domain/mcp/tools/{cortex-md.d.ts → agents-md.d.ts} +6 -6
  67. package/dist/domain/mcp/tools/{cortex-md.js → agents-md.js} +6 -6
  68. package/dist/domain/mcp/tools/commission-tools.d.ts +12 -1
  69. package/dist/domain/mcp/tools/commission-tools.js +68 -14
  70. package/dist/domain/mcp/tools/remote-file.d.ts +20 -0
  71. package/dist/domain/mcp/tools/remote-file.js +44 -0
  72. package/dist/domain/mcp/tools/slack.d.ts +2 -0
  73. package/dist/domain/mcp/tools/slack.js +22 -7
  74. package/dist/domain/mcp/tools/task-ops.js +5 -13
  75. package/dist/domain/mcp/tools/ui-file.js +23 -10
  76. package/dist/domain/mcp/tools/waitpoint.d.ts +3 -0
  77. package/dist/domain/mcp/tools/waitpoint.js +122 -0
  78. package/dist/domain/memory/agents-md-injector.d.ts +24 -0
  79. package/dist/domain/memory/{cortex-md-injector.js → agents-md-injector.js} +10 -7
  80. package/dist/domain/projects/project-store.d.ts +1 -1
  81. package/dist/domain/projects/project-store.js +3 -3
  82. package/dist/domain/remote/client-hot-reload.js +3 -1
  83. package/dist/domain/remote/client-manager.js +105 -126
  84. package/dist/domain/remote/client-ssh-tunnel.d.ts +16 -5
  85. package/dist/domain/remote/client-ssh-tunnel.js +12 -5
  86. package/dist/domain/remote/cortex-client-config.d.ts +1 -1
  87. package/dist/domain/remote/cortex-client-config.js +1 -1
  88. package/dist/domain/remote/device-file.d.ts +51 -0
  89. package/dist/domain/remote/device-file.js +193 -0
  90. package/dist/domain/remote/device-port.js +3 -0
  91. package/dist/domain/remote/reverse-stream.d.ts +18 -7
  92. package/dist/domain/remote/reverse-stream.js +19 -6
  93. package/dist/domain/runs/builders.js +0 -1
  94. package/dist/domain/runs/compact.js +0 -1
  95. package/dist/domain/runs/engine-spec.d.ts +11 -4
  96. package/dist/domain/runs/engine-spec.js +7 -4
  97. package/dist/domain/runs/prompt.js +16 -10
  98. package/dist/domain/runs/request.d.ts +0 -1
  99. package/dist/domain/sessions/session-hooks.d.ts +5 -12
  100. package/dist/domain/sessions/session-hooks.js +6 -13
  101. package/dist/domain/sessions/session-lifecycle.d.ts +4 -4
  102. package/dist/domain/sessions/session-lifecycle.js +5 -6
  103. package/dist/domain/sessions/session-retention.d.ts +1 -3
  104. package/dist/domain/sessions/session-retention.js +9 -26
  105. package/dist/domain/sessions/session-use.d.ts +32 -0
  106. package/dist/domain/sessions/session-use.js +63 -0
  107. package/dist/domain/sessions/session.js +6 -5
  108. package/dist/domain/system/server-update-check.js +29 -1
  109. package/dist/domain/system/update-ui-state.d.ts +32 -0
  110. package/dist/domain/system/update-ui-state.js +63 -0
  111. package/dist/domain/tasks/claim-recovery.js +2 -2
  112. package/dist/domain/tasks/dispatch-utils.d.ts +10 -1
  113. package/dist/domain/tasks/dispatch-utils.js +46 -1
  114. package/dist/domain/tasks/dispatcher.js +4 -5
  115. package/dist/domain/tasks/mutator.d.ts +2 -2
  116. package/dist/domain/tasks/mutator.js +2 -2
  117. package/dist/domain/tasks/system/task-cli.js +2 -2
  118. package/dist/domain/tasks/system/task-state.js +1 -1
  119. package/dist/domain/threads/runner.js +3 -2
  120. package/dist/domain/ui-service/app-router.d.ts +54 -3
  121. package/dist/domain/ui-service/app-router.js +12 -14
  122. package/dist/domain/ui-service/input-schemas.d.ts +49 -5
  123. package/dist/domain/ui-service/input-schemas.js +35 -9
  124. package/dist/domain/ui-service/mutate/platform-settings.js +1 -1
  125. package/dist/domain/ui-service/mutate/sessions.d.ts +17 -1
  126. package/dist/domain/ui-service/mutate/sessions.js +83 -3
  127. package/dist/domain/ui-service/mutate/system.d.ts +3 -1
  128. package/dist/domain/ui-service/mutate/system.js +13 -0
  129. package/dist/domain/ui-service/mutate/waitpoints.d.ts +2 -0
  130. package/dist/domain/ui-service/mutate/waitpoints.js +20 -0
  131. package/dist/domain/ui-service/platform-settings.js +1 -1
  132. package/dist/domain/ui-service/plugins-shared.js +1 -1
  133. package/dist/domain/ui-service/query/config.js +1 -1
  134. package/dist/domain/ui-service/query/executions.js +0 -2
  135. package/dist/domain/ui-service/query/machine-detail.js +3 -8
  136. package/dist/domain/ui-service/query/memory.js +1 -1
  137. package/dist/domain/ui-service/query/sessions.js +7 -0
  138. package/dist/domain/ui-service/query/system.d.ts +2 -1
  139. package/dist/domain/ui-service/query/system.js +4 -0
  140. package/dist/domain/ui-service/query/threads.js +1 -54
  141. package/dist/domain/ui-service/query/waitpoints.d.ts +30 -0
  142. package/dist/domain/ui-service/query/waitpoints.js +117 -0
  143. package/dist/domain/ui-service/query-input-schemas.d.ts +3 -0
  144. package/dist/domain/ui-service/query-input-schemas.js +3 -0
  145. package/dist/domain/ui-service/trpc.js +1 -1
  146. package/dist/domain/ui-service/types.d.ts +175 -50
  147. package/dist/domain/ui-service/types.js +1 -1
  148. package/dist/domain/ui-service/ui-service.js +13 -33
  149. package/dist/domain/waitpoints/notices.d.ts +21 -0
  150. package/dist/domain/waitpoints/notices.js +115 -0
  151. package/dist/domain/waitpoints/service.d.ts +91 -0
  152. package/dist/domain/waitpoints/service.js +243 -0
  153. package/dist/entry/app.js +39 -29
  154. package/dist/entry/auth-login-cli.js +1 -1
  155. package/dist/entry/auth-login-terminal.js +1 -1
  156. package/dist/entry/init-auth.js +1 -1
  157. package/dist/entry/init.js +6 -6
  158. package/dist/entry/signal-cli.d.ts +30 -0
  159. package/dist/entry/signal-cli.js +207 -0
  160. package/dist/entry/start-ui-http.d.ts +1 -1
  161. package/dist/entry/start-ui-http.js +5 -3
  162. package/dist/events/event-types.d.ts +5 -7
  163. package/dist/hooks/{cortex-md-injector.mjs → agents-md-injector.mjs} +117 -26
  164. package/dist/hooks/cortex-hook-api.mjs +2 -2
  165. package/dist/hooks/new-session-hook.mjs +2 -2
  166. package/dist/hooks/rules-loader.mjs +2 -2
  167. package/dist/hooks/status-md-guard.mjs +8 -8
  168. package/dist/hooks/task-status-check.mjs +18 -76
  169. package/dist/hooks/tasks-yaml-guard.mjs +2 -2
  170. package/dist/orchestration/agent-file-send.d.ts +9 -0
  171. package/dist/orchestration/agent-file-send.js +21 -2
  172. package/dist/orchestration/agent-runner.d.ts +4 -3
  173. package/dist/orchestration/agent-runner.js +25 -23
  174. package/dist/orchestration/attachments-store.d.ts +31 -0
  175. package/dist/orchestration/attachments-store.js +184 -0
  176. package/dist/orchestration/conversation-request.d.ts +30 -8
  177. package/dist/orchestration/conversation-request.js +62 -26
  178. package/dist/orchestration/edit-retry.js +2 -1
  179. package/dist/orchestration/interactions/ask-user-resume.js +2 -1
  180. package/dist/orchestration/interactions/plan-approvals.js +1 -1
  181. package/dist/orchestration/interactions/ui-update-prompt.d.ts +8 -0
  182. package/dist/orchestration/interactions/ui-update-prompt.js +47 -0
  183. package/dist/orchestration/outputs-store.d.ts +11 -0
  184. package/dist/orchestration/outputs-store.js +32 -6
  185. package/dist/orchestration/resume-dispatcher.js +2 -2
  186. package/dist/orchestration/routing/file-handler.d.ts +23 -2
  187. package/dist/orchestration/routing/file-handler.js +22 -5
  188. package/dist/orchestration/routing/webhook.js +240 -39
  189. package/dist/orchestration/session-compact.d.ts +3 -0
  190. package/dist/orchestration/session-compact.js +3 -2
  191. package/dist/orchestration/session-events.d.ts +6 -0
  192. package/dist/orchestration/session-events.js +5 -0
  193. package/dist/orchestration/session-gateway.d.ts +1 -1
  194. package/dist/orchestration/session-gateway.js +1 -0
  195. package/dist/orchestration/thread-executor.d.ts +2 -0
  196. package/dist/orchestration/thread-executor.js +11 -1
  197. package/dist/orchestration/thread-input.d.ts +3 -2
  198. package/dist/orchestration/thread-input.js +8 -9
  199. package/dist/orchestration/turn/turn-prep.d.ts +15 -1
  200. package/dist/orchestration/turn/turn-prep.js +21 -9
  201. package/dist/orchestration/waitpoint-ingress.d.ts +41 -0
  202. package/dist/orchestration/waitpoint-ingress.js +172 -0
  203. package/dist/orchestration/waitpoint-notifier.d.ts +21 -0
  204. package/dist/orchestration/waitpoint-notifier.js +119 -0
  205. package/dist/orchestration/waitpoint-remote-drain.d.ts +20 -0
  206. package/dist/orchestration/waitpoint-remote-drain.js +147 -0
  207. package/dist/orchestration/waitpoint-sweep.d.ts +42 -0
  208. package/dist/orchestration/waitpoint-sweep.js +87 -0
  209. package/dist/platform/adapters/feishu-image.d.ts +19 -0
  210. package/dist/platform/adapters/feishu-image.js +71 -0
  211. package/dist/platform/adapters/feishu.d.ts +2 -0
  212. package/dist/platform/adapters/feishu.js +26 -16
  213. package/dist/platform/ui-http/app-update.d.ts +11 -0
  214. package/dist/platform/ui-http/app-update.js +3 -0
  215. package/dist/platform/ui-http/listening-ports.d.ts +1 -1
  216. package/dist/platform/ui-http/listening-ports.js +1 -1
  217. package/dist/platform/ui-http/ui-session.js +1 -1
  218. package/dist/store/conversation-ledger-repo.d.ts +10 -19
  219. package/dist/store/conversation-ledger-repo.js +143 -152
  220. package/dist/store/execution-repo.d.ts +1 -19
  221. package/dist/store/execution-repo.js +1 -18
  222. package/dist/store/project-notes-repo.js +11 -2
  223. package/dist/store/prompt-migration-replacements.js +1 -1
  224. package/dist/store/session-registry-import.d.ts +34 -0
  225. package/dist/store/session-registry-import.js +182 -0
  226. package/dist/store/session-registry-journal.d.ts +107 -0
  227. package/dist/store/session-registry-journal.js +308 -19
  228. package/dist/store/session-registry-repo.d.ts +113 -28
  229. package/dist/store/session-registry-repo.js +288 -105
  230. package/dist/store/version-migrations.d.ts +29 -3
  231. package/dist/store/version-migrations.js +288 -24
  232. package/dist/store/waitpoint-repo.d.ts +108 -0
  233. package/dist/store/waitpoint-repo.js +94 -0
  234. package/package.json +2 -2
  235. package/web/dist/assets/index-CwwQNMpP.css +1 -0
  236. package/web/dist/assets/index-DLSfgq3o.js +444 -0
  237. package/web/dist/assets/{index-aHbOZSP6.js → index-DZTuqUO4.js} +1 -1
  238. package/web/dist/index.html +2 -2
  239. package/defaults/config/hooks/08-cortex-md-injector-post-tool.json +0 -10
  240. package/dist/domain/executions/log-tailer.d.ts +0 -71
  241. package/dist/domain/executions/log-tailer.js +0 -194
  242. package/dist/domain/memory/cortex-md-injector.d.ts +0 -24
  243. package/dist/domain/memory/cortex-md-scanner.d.ts +0 -10
  244. package/dist/domain/memory/cortex-md-scanner.js +0 -66
  245. package/dist/domain/remote/cortex-client.d.ts +0 -1
  246. package/dist/domain/remote/cortex-client.js +0 -662
  247. package/dist/domain/tasks/system/cortex-run.d.ts +0 -25
  248. package/dist/domain/tasks/system/cortex-run.js +0 -360
  249. package/dist/store/session-repo.d.ts +0 -65
  250. package/dist/store/session-repo.js +0 -184
  251. package/web/dist/assets/index-BuXbCsuz.js +0 -444
  252. package/web/dist/assets/index-CCPxQ94C.css +0 -1
  253. /package/defaults/{CORTEX.md → AGENTS.md} +0 -0
  254. /package/defaults/config/{CORTEX.md → AGENTS.md} +0 -0
  255. /package/defaults/context/{CORTEX.md → AGENTS.md} +0 -0
  256. /package/defaults/context/ideas/{CORTEX.md → AGENTS.md} +0 -0
  257. /package/defaults/context/projects/{CORTEX.md → AGENTS.md} +0 -0
  258. /package/defaults/context/scans/{CORTEX.md → AGENTS.md} +0 -0
  259. /package/defaults/context/user/{CORTEX.md → AGENTS.md} +0 -0
@@ -6,10 +6,10 @@ import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
6
6
  import { Type } from '@sinclair/typebox';
7
7
  import { createLogger } from '../../core/log.js';
8
8
  import { MCP_INFRASTRUCTURE_TIMEOUT_MS } from '../../core/mcp-timeout.js';
9
- import { MCP_TOOL_ALLOWLIST_ENV, MCP_TOOLS_BY_SERVER, parseMcpToolAllowlist, validateMcpToolAllowlist, withoutCommissionTools, withoutSubagentTools, } from '../../core/mcp-tool-gate.js';
9
+ import { MCP_TOOL_ALLOWLIST_ENV, MCP_TOOLS_BY_SERVER, parseMcpToolAllowlist, validateMcpToolAllowlist, withoutSubagentTools, } from '../../core/mcp-tool-gate.js';
10
10
  import { createRedirectRejectingFetch } from '../mcp-remote-fetch.js';
11
11
  import { mapMcpContent, shouldLoadFeishu, shouldLoadSlack, shouldLoadThreadControl, shouldLoadWeb, } from './mcp-bridge-logic.js';
12
- import { PI_COMMISSION_TOOLS_ENV, PI_INTERACTION_BRIDGE_ENV, PI_MCP_COMPOSITION_ENV, } from './session-options.js';
12
+ import { PI_INTERACTION_BRIDGE_ENV, PI_MCP_COMPOSITION_ENV, } from './session-options.js';
13
13
  import { safeNativeComposite, safeNativeName } from '../../core/native-name.js';
14
14
  const log = createLogger('pi-mcp-bridge');
15
15
  const DEFAULT_TRANSPORT_CONSTRUCTORS = {
@@ -31,23 +31,21 @@ function builtinEnv(env) {
31
31
  * bundle. This runs here rather than in the adapter because this is the first place that knows PI's
32
32
  * bundle set.
33
33
  *
34
- * Two exclusions are applied:
34
+ * One exclusion is applied: **delegation tools, always.** `agent` / `agent_stop` exist in
35
+ * `cortex-core` for backends that have no subagent of their own; PI registers its own in-process
36
+ * `agent`, and a bundled MCP tool is exposed under its bare name, so leaving them in would mean two
37
+ * tools called `agent`. The native one wins by construction because the MCP pair never reaches PI.
35
38
  *
36
- * - **Commission tools**, unless this session is drafting a commission — that one gets no allowlist
37
- * at all and is therefore allowed everything, the two commission tools included.
38
- * - **Delegation tools, always.** `agent` / `agent_stop` exist in `cortex-core` for backends that
39
- * have no subagent of their own; PI registers its own in-process `agent`, and a bundled MCP tool
40
- * is exposed under its bare name, so leaving them in would mean two tools called `agent`. The
41
- * native one wins by construction because the MCP pair never reaches PI at all.
39
+ * The commission-creation tools used to be excluded here too, which made PI the only backend where
40
+ * that gate actually worked — Claude's equivalent (`--tools`) cannot filter MCP tools at all. Rather
41
+ * than teach Claude the same trick, DR-0037 v4 dropped the gate on both: the two tools are part of
42
+ * the direct surface everywhere, and a submit from a session that never entered the mode is refused
43
+ * by `commission-finalize` instead.
42
44
  */
43
45
  function toolGatedEnv(bundles, env) {
44
46
  const toolEnv = builtinEnv(env);
45
- const dropCommission = bundles.includes('cortex-interaction-bridge')
46
- && env[PI_COMMISSION_TOOLS_ENV] !== '1';
47
47
  const declared = parseMcpToolAllowlist(env[MCP_TOOL_ALLOWLIST_ENV]);
48
- let allowlist = withoutSubagentTools(declared ? [...declared] : undefined, bundles);
49
- if (dropCommission)
50
- allowlist = withoutCommissionTools(allowlist, bundles);
48
+ const allowlist = withoutSubagentTools(declared ? [...declared] : undefined, bundles);
51
49
  toolEnv[MCP_TOOL_ALLOWLIST_ENV] = JSON.stringify(allowlist);
52
50
  return toolEnv;
53
51
  }
@@ -368,7 +366,10 @@ class McpBridgeSession {
368
366
  });
369
367
  const content = result.content.map(mapMcpContent);
370
368
  if (result.isError) {
371
- const message = content.map(item => item.text).filter(Boolean).join('\n');
369
+ const message = content
370
+ .map(item => (item.type === 'text' ? item.text : ''))
371
+ .filter(Boolean)
372
+ .join('\n');
372
373
  throw new Error(message || `${exposedName} failed`);
373
374
  }
374
375
  return { content, details: undefined };
@@ -1,10 +1,6 @@
1
1
  import type { CortexContextEnv, EngineSpec, McpComposition, McpServerConfig } from '../types.js';
2
2
  export declare const PI_MCP_COMPOSITION_ENV = "CORTEX_PI_MCP_COMPOSITION";
3
3
  export declare const PI_INTERACTION_BRIDGE_ENV = "CORTEX_PI_INTERACTION_BRIDGE";
4
- /** Set while a NEW commission is being drafted. Read by the MCP bridge, which is where PI knows its
5
- * bundle set and can therefore write the allowlist that hides the commission tools from every other
6
- * session. */
7
- export declare const PI_COMMISSION_TOOLS_ENV = "CORTEX_PI_COMMISSION_TOOLS";
8
4
  export interface PIEnvOptions {
9
5
  sessionId?: string | null;
10
6
  channel?: string | null;
@@ -23,8 +19,6 @@ export interface PIEnvOptions {
23
19
  mcpToolAllowlist?: string[] | null;
24
20
  /** Trusted marker enabling the shared interaction MCP bridge. */
25
21
  enableInteractionBridge?: boolean;
26
- /** Expose the commission-creation tools; ignored when the bridge is off. */
27
- commissionTools?: boolean;
28
22
  /** Explicit marker for the restricted PI subagent surface. */
29
23
  subagentMarker?: string | null;
30
24
  }
@@ -4,10 +4,6 @@ import { browserMcpServer } from '../browser-mcp-server.js';
4
4
  import { MCP_TOOL_ALLOWLIST_ENV } from '../../core/mcp-tool-gate.js';
5
5
  export const PI_MCP_COMPOSITION_ENV = 'CORTEX_PI_MCP_COMPOSITION';
6
6
  export const PI_INTERACTION_BRIDGE_ENV = 'CORTEX_PI_INTERACTION_BRIDGE';
7
- /** Set while a NEW commission is being drafted. Read by the MCP bridge, which is where PI knows its
8
- * bundle set and can therefore write the allowlist that hides the commission tools from every other
9
- * session. */
10
- export const PI_COMMISSION_TOOLS_ENV = 'CORTEX_PI_COMMISSION_TOOLS';
11
7
  const RESET_CONTEXT_KEYS = [
12
8
  'SLACK_CHANNEL', 'FEISHU_CHANNEL',
13
9
  'CORTEX_SESSION_ID', 'CORTEX_THREAD_ID', 'CORTEX_PROFILE',
@@ -20,7 +16,7 @@ const RESET_CONTEXT_KEYS = [
20
16
  'CORTEX_WEBHOOK_SINGLE_ROOT_TEMPLATE',
21
17
  'CORTEX_PRODUCTION_BENCHMARK_EVIDENCE_CONTEXT_FILE',
22
18
  'CORTEX_PI_ALLOWED_TOOLS', 'CORTEX_PI_SUBAGENT',
23
- PI_MCP_COMPOSITION_ENV, PI_INTERACTION_BRIDGE_ENV, PI_COMMISSION_TOOLS_ENV,
19
+ PI_MCP_COMPOSITION_ENV, PI_INTERACTION_BRIDGE_ENV,
24
20
  MCP_TOOL_ALLOWLIST_ENV,
25
21
  ];
26
22
  function setOptional(env, key, value) {
@@ -67,8 +63,6 @@ export function buildPiEnv(options, inheritedEnv = process.env) {
67
63
  }
68
64
  if (options.enableInteractionBridge === true)
69
65
  env[PI_INTERACTION_BRIDGE_ENV] = '1';
70
- if (options.commissionTools === true)
71
- env[PI_COMMISSION_TOOLS_ENV] = '1';
72
66
  setOptional(env, 'CORTEX_PI_SUBAGENT', options.subagentMarker);
73
67
  applyContext(env, options);
74
68
  return env;
@@ -139,7 +133,6 @@ export function buildSessionRequest(spec, inputs) {
139
133
  enableInteractionBridge: composition === 'direct'
140
134
  && spec.flags.isUserInitiated === true
141
135
  && marker === undefined,
142
- commissionTools: spec.mcp.commissionTools === true,
143
136
  subagentMarker: marker,
144
137
  }, spec.env.pinned);
145
138
  return {
@@ -86,7 +86,6 @@ export interface EngineSpec {
86
86
  servers?: McpServerConfig[];
87
87
  allowlist?: string[];
88
88
  configPaths?: string[];
89
- commissionTools?: boolean;
90
89
  browserCdpEndpoint?: string;
91
90
  };
92
91
  env: {
@@ -136,6 +135,7 @@ export interface UserMessage {
136
135
  attachments?: {
137
136
  mimeType: string;
138
137
  path: string;
138
+ name?: string;
139
139
  }[];
140
140
  }
141
141
  export interface McpStdioServerConfig {
@@ -1,29 +1,15 @@
1
1
  import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  export declare const MCP_TOOL_ALLOWLIST_ENV = "CORTEX_MCP_TOOL_ALLOWLIST";
3
3
  export declare const MCP_TOOLS_BY_SERVER: Readonly<Record<string, readonly string[]>>;
4
- /**
5
- * The two commission-creation tools. They are standalone — they do NOT replace cortex_plan_enter /
6
- * cortex_plan_exit, and a session creating a commission holds both sets. They are injected only
7
- * while a new commission is being drafted, so no other session ever sees them (DR-0037 v3).
8
- */
9
- export declare const COMMISSION_TOOLS: readonly string[];
10
- /**
11
- * A per-spawn allowlist with the commission tools removed.
12
- *
13
- * Only backends without a per-tool launch flag need this: Claude keeps the tools out of an ordinary
14
- * session through `--tools`, but PI has no equivalent, so the allowlist is its only lever. The gate
15
- * is fail-OPEN (see {@link parseMcpToolAllowlist}: absent env ⇒ everything registers), so exclusion
16
- * can never be expressed by *withholding* an allowlist — when the caller has none of its own we
17
- * synthesize one from the selected bundles' full surface.
18
- */
19
- export declare function withoutCommissionTools(allowlist: readonly string[] | undefined, selectedBundles: readonly string[]): string[];
20
4
  /**
21
5
  * The delegation tools. A subagent is a leaf: it never gets these, on either backend, which is what
22
6
  * makes the recursion guard structural rather than a depth counter (plan §6.1).
23
7
  */
24
8
  export declare const SUBAGENT_TOOLS: readonly string[];
25
9
  /** A per-spawn allowlist a subagent child runs under: everything its bundles offer, minus
26
- * delegation. Same fail-open reasoning as {@link withoutCommissionTools}. */
10
+ * delegation. The gate is fail-OPEN (see {@link parseMcpToolAllowlist}: absent env ⇒ everything
11
+ * registers), so exclusion can never be expressed by *withholding* an allowlist — when the caller
12
+ * has none of its own we synthesize one from the selected bundles' full surface. */
27
13
  export declare function withoutSubagentTools(allowlist: readonly string[] | undefined, selectedBundles: readonly string[]): string[];
28
14
  export declare function canonicalizeMcpToolAllowlist(values: readonly string[]): string[];
29
15
  export declare function validateMcpToolAllowlist(allowlist: readonly string[], knownTools?: ReadonlySet<string>): void;
@@ -12,6 +12,7 @@ export const MCP_TOOLS_BY_SERVER = {
12
12
  'cost_query', 'query_executions', 'cortex_context', 'cortex_schedule_add',
13
13
  'cortex_schedule_list', 'cortex_schedule_get', 'cortex_schedule_remove',
14
14
  'cortex_schedule_pause', 'cortex_schedule_resume',
15
+ 'wait_create', 'wait_check', 'wait_cancel',
15
16
  ],
16
17
  'cortex-interaction-bridge': [
17
18
  'cortex_plan_enter', 'cortex_plan_exit',
@@ -24,31 +25,15 @@ export const MCP_TOOLS_BY_SERVER = {
24
25
  'cortex-benchmark-thread': ['thread_run'],
25
26
  };
26
27
  const ALL_MCP_TOOLS = new Set(Object.values(MCP_TOOLS_BY_SERVER).flat());
27
- /**
28
- * The two commission-creation tools. They are standalone — they do NOT replace cortex_plan_enter /
29
- * cortex_plan_exit, and a session creating a commission holds both sets. They are injected only
30
- * while a new commission is being drafted, so no other session ever sees them (DR-0037 v3).
31
- */
32
- export const COMMISSION_TOOLS = ['cortex_commission_start', 'cortex_commission_submit'];
33
- /**
34
- * A per-spawn allowlist with the commission tools removed.
35
- *
36
- * Only backends without a per-tool launch flag need this: Claude keeps the tools out of an ordinary
37
- * session through `--tools`, but PI has no equivalent, so the allowlist is its only lever. The gate
38
- * is fail-OPEN (see {@link parseMcpToolAllowlist}: absent env ⇒ everything registers), so exclusion
39
- * can never be expressed by *withholding* an allowlist — when the caller has none of its own we
40
- * synthesize one from the selected bundles' full surface.
41
- */
42
- export function withoutCommissionTools(allowlist, selectedBundles) {
43
- return withoutTools(allowlist, selectedBundles, COMMISSION_TOOLS);
44
- }
45
28
  /**
46
29
  * The delegation tools. A subagent is a leaf: it never gets these, on either backend, which is what
47
30
  * makes the recursion guard structural rather than a depth counter (plan §6.1).
48
31
  */
49
32
  export const SUBAGENT_TOOLS = ['agent', 'agent_stop'];
50
33
  /** A per-spawn allowlist a subagent child runs under: everything its bundles offer, minus
51
- * delegation. Same fail-open reasoning as {@link withoutCommissionTools}. */
34
+ * delegation. The gate is fail-OPEN (see {@link parseMcpToolAllowlist}: absent env ⇒ everything
35
+ * registers), so exclusion can never be expressed by *withholding* an allowlist — when the caller
36
+ * has none of its own we synthesize one from the selected bundles' full surface. */
52
37
  export function withoutSubagentTools(allowlist, selectedBundles) {
53
38
  return withoutTools(allowlist, selectedBundles, SUBAGENT_TOOLS);
54
39
  }
@@ -3,3 +3,13 @@
3
3
  * two sets, so they live below both rather than in either one. */
4
4
  export declare const IMAGE_MIMES: Set<string>;
5
5
  export declare const VIDEO_MIMES: Set<string>;
6
+ /** The mime a file's first bytes actually declare, or null when they are not a known image.
7
+ *
8
+ * A platform's metadata is a claim, not a fact: Feishu hands every inbound image out as
9
+ * `image_key` with no type at all (Cortex called them all PNG), Slack can mislabel, and a user
10
+ * can rename anything. Backends sniff the bytes themselves, so a wrong mime never broke reading —
11
+ * it broke everything that classifies on the declared value (prompt bucket, UI attachment kind,
12
+ * the extension the file is stored under). */
13
+ export declare function sniffImageMime(head: Buffer): string | null;
14
+ /** The extension an image mime should be stored under, or null for a mime with no fixed one. */
15
+ export declare function imageMimeExtension(mimeType: string): string | null;
@@ -3,3 +3,37 @@
3
3
  * two sets, so they live below both rather than in either one. */
4
4
  export const IMAGE_MIMES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);
5
5
  export const VIDEO_MIMES = new Set(['video/mp4', 'video/webm', 'video/quicktime', 'video/x-msvideo', 'video/x-matroska']);
6
+ /** Canonical extension per image mime, for naming a file whose declared type turned out to be a lie. */
7
+ const IMAGE_MIME_EXTENSIONS = {
8
+ 'image/png': '.png',
9
+ 'image/jpeg': '.jpg',
10
+ 'image/gif': '.gif',
11
+ 'image/webp': '.webp',
12
+ 'image/bmp': '.bmp',
13
+ };
14
+ /** The mime a file's first bytes actually declare, or null when they are not a known image.
15
+ *
16
+ * A platform's metadata is a claim, not a fact: Feishu hands every inbound image out as
17
+ * `image_key` with no type at all (Cortex called them all PNG), Slack can mislabel, and a user
18
+ * can rename anything. Backends sniff the bytes themselves, so a wrong mime never broke reading —
19
+ * it broke everything that classifies on the declared value (prompt bucket, UI attachment kind,
20
+ * the extension the file is stored under). */
21
+ export function sniffImageMime(head) {
22
+ if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff)
23
+ return 'image/jpeg';
24
+ if (head.length >= 8 && head.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])))
25
+ return 'image/png';
26
+ if (head.length >= 6 && head.subarray(0, 3).toString('latin1') === 'GIF')
27
+ return 'image/gif';
28
+ if (head.length >= 12
29
+ && head.subarray(0, 4).toString('latin1') === 'RIFF'
30
+ && head.subarray(8, 12).toString('latin1') === 'WEBP')
31
+ return 'image/webp';
32
+ if (head.length >= 2 && head.subarray(0, 2).toString('latin1') === 'BM')
33
+ return 'image/bmp';
34
+ return null;
35
+ }
36
+ /** The extension an image mime should be stored under, or null for a mime with no fixed one. */
37
+ export function imageMimeExtension(mimeType) {
38
+ return IMAGE_MIME_EXTENSIONS[mimeType] ?? null;
39
+ }
@@ -1,7 +1,7 @@
1
1
  // input: zod and platform credential field definitions
2
2
  // output: platform configuration contract and safe patch schema
3
3
  // pos: Browser-safe platform settings boundary
4
- // >>> Once updated, update this header and parent CORTEX.md <<<
4
+ // >>> Once updated, update this header and parent AGENTS.md <<<
5
5
  import { z } from 'zod';
6
6
  export const PLATFORM_FIELDS = {
7
7
  feishu: ['FEISHU_APP_ID', 'FEISHU_APP_SECRET', 'FEISHU_DOMAIN', 'FEISHU_ENCRYPT_KEY', 'FEISHU_VERIFICATION_TOKEN'],
@@ -29,6 +29,9 @@ export interface Settings {
29
29
  feishuSkillsInWeb: boolean;
30
30
  managerRotateSteps: number;
31
31
  waitingSweepMs: number;
32
+ waitpointSweepMs: number;
33
+ waitpointTtlMs: number;
34
+ waitpointMaxWakesPerHour: number;
32
35
  injectWaitMaxS: number;
33
36
  threadMaxDepth: number;
34
37
  taskArtifactTemplates: string[];
@@ -171,7 +174,7 @@ export declare const SETTINGS_SPEC: {
171
174
  commissionEnabled: {
172
175
  envVar: string;
173
176
  type: "boolean";
174
- default: false;
177
+ default: true;
175
178
  legacyParse: (raw: string) => raw is "1";
176
179
  };
177
180
  managerRotateSteps: {
@@ -186,6 +189,24 @@ export declare const SETTINGS_SPEC: {
186
189
  default: number;
187
190
  legacyParse: (raw: string) => number;
188
191
  };
192
+ waitpointSweepMs: {
193
+ envVar: string;
194
+ type: "number";
195
+ default: number;
196
+ legacyParse: (raw: string) => number;
197
+ };
198
+ waitpointTtlMs: {
199
+ envVar: string;
200
+ type: "number";
201
+ default: number;
202
+ legacyParse: (raw: string) => number;
203
+ };
204
+ waitpointMaxWakesPerHour: {
205
+ envVar: string;
206
+ type: "number";
207
+ default: number;
208
+ legacyParse: (raw: string) => number;
209
+ };
189
210
  injectWaitMaxS: {
190
211
  envVar: string;
191
212
  type: "number";
@@ -1,7 +1,7 @@
1
1
  // input: raw environment and runtime setting policy shapes
2
2
  // output: settings types, defaults, parsers and validators
3
3
  // pos: Browser-safe runtime settings contract
4
- // >>> Once updated, update this header and parent CORTEX.md <<<
4
+ // >>> Once updated, update this header and parent AGENTS.md <<<
5
5
  export const MAX_TIMER_DELAY_MS = 2_147_483_647;
6
6
  export const MAX_SESSION_RETENTION_DAYS = Math.floor(Number.MAX_SAFE_INTEGER / 86_400_000);
7
7
  function validateJobInterval(value) {
@@ -135,7 +135,11 @@ export const SETTINGS_SPEC = {
135
135
  commissionEnabled: {
136
136
  envVar: 'CORTEX_COMMISSION_ENABLED',
137
137
  type: 'boolean',
138
- default: false,
138
+ // On by default since DR-0037 v4: entering the mode is now a decision the agent (or the user)
139
+ // makes inside an ordinary session, so a switch defaulting to off would hide a capability
140
+ // nobody has to opt into. It stays a switch because it is the kill switch — off refuses every
141
+ // entry point (create, composer, the start webhook) and stops injecting contract blocks.
142
+ default: true,
139
143
  legacyParse: (raw) => raw === '1',
140
144
  },
141
145
  managerRotateSteps: {
@@ -156,6 +160,33 @@ export const SETTINGS_SPEC = {
156
160
  return Number.isFinite(value) ? value : 60_000;
157
161
  },
158
162
  },
163
+ waitpointSweepMs: {
164
+ envVar: 'CORTEX_WAITPOINT_SWEEP_MS',
165
+ type: 'number',
166
+ default: 30_000,
167
+ legacyParse: (raw) => {
168
+ const value = Number.parseInt(raw || '', 10);
169
+ return Number.isFinite(value) ? value : 30_000;
170
+ },
171
+ },
172
+ waitpointTtlMs: {
173
+ envVar: 'CORTEX_WAITPOINT_TTL_MS',
174
+ type: 'number',
175
+ default: 7 * 24 * 60 * 60 * 1000,
176
+ legacyParse: (raw) => {
177
+ const value = Number.parseInt(raw || '', 10);
178
+ return Number.isFinite(value) && value > 0 ? value : 7 * 24 * 60 * 60 * 1000;
179
+ },
180
+ },
181
+ waitpointMaxWakesPerHour: {
182
+ envVar: 'CORTEX_WAITPOINT_MAX_WAKES_PER_HOUR',
183
+ type: 'number',
184
+ default: 12,
185
+ legacyParse: (raw) => {
186
+ const value = Number.parseInt(raw || '', 10);
187
+ return Number.isFinite(value) && value > 0 ? value : 12;
188
+ },
189
+ },
159
190
  injectWaitMaxS: {
160
191
  envVar: 'CORTEX_INJECT_WAIT_MAX_S',
161
192
  type: 'number',
@@ -31,7 +31,9 @@ export type SystemTurnOrigin =
31
31
  /** A subtask escalated a question to the manager session (`ask_manager`). */
32
32
  | 'subtask-question'
33
33
  /** A backgrounded `agent` run delivered its result. */
34
- | 'agent-result';
34
+ | 'agent-result'
35
+ /** A waitpoint an agent armed was resolved by a signal from outside the process. */
36
+ | 'external-signal';
35
37
  export interface AuthNoticeAction {
36
38
  kind: 'auth-login';
37
39
  noticeId: string;
@@ -16,7 +16,7 @@ declare function todayISO(): string;
16
16
  * List subdirectories of PROJECTS_DIR that look like project folders.
17
17
  *
18
18
  * Filters out:
19
- * - non-directories (e.g. top-level files like CORTEX.md, AGENTS.md that
19
+ * - non-directories (e.g. top-level files like AGENTS.md, AGENTS.md that
20
20
  * some users keep next to their projects/ tree)
21
21
  * - dotfiles (.git, .obsidian, etc.)
22
22
  *
@@ -74,7 +74,7 @@ function todayISO() {
74
74
  * List subdirectories of PROJECTS_DIR that look like project folders.
75
75
  *
76
76
  * Filters out:
77
- * - non-directories (e.g. top-level files like CORTEX.md, AGENTS.md that
77
+ * - non-directories (e.g. top-level files like AGENTS.md, AGENTS.md that
78
78
  * some users keep next to their projects/ tree)
79
79
  * - dotfiles (.git, .obsidian, etc.)
80
80
  *
@@ -23,7 +23,7 @@ export declare function getActiveProfile(channel?: string): string | null;
23
23
  * The backend a channel runs: its profile's, falling back to the default profile's.
24
24
  *
25
25
  * DEVIATION from plan D5, which has this "degenerate into reading the session record". That was
26
- * the right move while sessions.json keyed on `backend:channel` and the caller had to know the
26
+ * the right move while the session store keyed on `backend:channel` and the caller had to know the
27
27
  * backend to find the session at all — but the backend is no longer part of the key, so no session
28
28
  * lookup needs this any more. What is left are callers asking which backend a channel runs
29
29
  * (conversation ledger, rollback, compaction support), and for them the profile is the source of
@@ -246,7 +246,7 @@ export function getActiveProfile(channel) {
246
246
  * The backend a channel runs: its profile's, falling back to the default profile's.
247
247
  *
248
248
  * DEVIATION from plan D5, which has this "degenerate into reading the session record". That was
249
- * the right move while sessions.json keyed on `backend:channel` and the caller had to know the
249
+ * the right move while the session store keyed on `backend:channel` and the caller had to know the
250
250
  * backend to find the session at all — but the backend is no longer part of the key, so no session
251
251
  * lookup needs this any more. What is left are callers asking which backend a channel runs
252
252
  * (conversation ledger, rollback, compaction support), and for them the profile is the source of
@@ -38,7 +38,7 @@ export interface SwitchProfileResult {
38
38
  reason?: SwitchProfileFailure;
39
39
  }
40
40
  /** Does the channel's session already carry conversation history? A fresh (just-created) session has
41
- * a ledger entry with zero turns; a live conversation has ≥1 turn. */
41
+ * zero turns; a live conversation has ≥1 turn. Read straight from the registry's channel turns. */
42
42
  export declare function channelHasHistory(channel: string): Promise<boolean>;
43
43
  /**
44
44
  * Switch the active profile for a channel/session under the shared rule. Validates the profile,
@@ -1,5 +1,5 @@
1
1
  // input: profile-manager (resolveProfile/resolveProfileConfig) + config (resolveBackendForChannel/
2
- // setActiveProfile) + conversation-ledger-repo (history) + session-registry-repo (record sync)
2
+ // setActiveProfile) + session-registry-repo (channel turn history + record sync)
3
3
  // output: decideProfileSwitch (pure policy) + switchChannelProfile (composed switch used by
4
4
  // Slack/Feishu commands AND the Web UI, so the rule has ONE source of truth)
5
5
  // pos: domain/agents — the single "switch the active profile for a channel/session" rule.
@@ -7,7 +7,6 @@
7
7
  // same-backend profiles (switching in place, no session reset); a fresh session (no
8
8
  // history) may switch to any profile freely. A same-backend switch never resets the
9
9
  // session — the agent runner re-resolves the profile per turn, so only the model changes.
10
- import { conversationLedger } from '../../store/conversation-ledger-repo.js';
11
10
  import { sessionStore } from '../../store/session-registry-repo.js';
12
11
  import { resolveBackendForChannel, setActiveProfile } from './config.js';
13
12
  import { resolveProfile, resolveProfileConfig } from './profile-manager.js';
@@ -32,10 +31,9 @@ export function decideProfileSwitch(opts) {
32
31
  return { allowed: true, backendChanged };
33
32
  }
34
33
  /** Does the channel's session already carry conversation history? A fresh (just-created) session has
35
- * a ledger entry with zero turns; a live conversation has ≥1 turn. */
34
+ * zero turns; a live conversation has ≥1 turn. Read straight from the registry's channel turns. */
36
35
  export async function channelHasHistory(channel) {
37
- const conv = await conversationLedger.getConversation(channel);
38
- return !!conv && conv.turns.length > 0;
36
+ return (await sessionStore.getTurns(channel)).length > 0;
39
37
  }
40
38
  /**
41
39
  * Switch the active profile for a channel/session under the shared rule. Validates the profile,
@@ -240,7 +240,6 @@ function claudeChildRequest(request, config) {
240
240
  executionKind: 'local',
241
241
  isUserInitiated: false,
242
242
  commissionMode: false,
243
- commissionTools: false,
244
243
  scheduleTaskId: null,
245
244
  },
246
245
  policy: {
@@ -28,3 +28,61 @@ export declare function resolveCommissionCreate(projectId: string, sessionName:
28
28
  mkdir?: (dir: string) => void;
29
29
  resolveRoot?: (projectId: string) => string | null;
30
30
  }): Promise<CommissionSessionFields>;
31
+ /**
32
+ * Create (or reuse) the draft directory for `sessionName` and return both halves of its identity.
33
+ * Split out of {@link resolveCommissionCreate} because three callers need exactly this and nothing
34
+ * else: session creation, the `cortex_commission_start` tool, and the composer switching a live
35
+ * session into the mode (DR-0037 v4).
36
+ *
37
+ * `mkdir -p` is the idempotency: a second call on the same session lands on the same directory,
38
+ * which is what lets the tool be called twice without consequence.
39
+ */
40
+ export declare function startCommissionDraft(projectId: string, sessionName: string, deps?: {
41
+ mkdir?: (dir: string) => void;
42
+ resolveRoot?: (projectId: string) => string | null;
43
+ }): {
44
+ draftDir: string;
45
+ dir: string;
46
+ };
47
+ export type CommissionEnterResult = {
48
+ ok: true;
49
+ draftDir: string;
50
+ dir: string;
51
+ alreadyDrafting: boolean;
52
+ } | {
53
+ ok: false;
54
+ error: string;
55
+ };
56
+ export interface CommissionEnterDeps {
57
+ getSession?: (id: string) => Promise<{
58
+ projectId?: string | null;
59
+ name?: string | null;
60
+ commissionId?: string | null;
61
+ commissionDraft?: string | null;
62
+ } | null>;
63
+ setDraft?: (sessionId: string, draftDir: string | null) => Promise<unknown>;
64
+ start?: typeof startCommissionDraft;
65
+ resolveRoot?: (projectId: string) => string | null;
66
+ }
67
+ /**
68
+ * Put a session into the drafting half of commission mode: directory on disk, `commissionDraft` in
69
+ * the registry. The single implementation behind both entries — the agent's `cortex_commission_start`
70
+ * and the user's composer switch — so the two cannot drift into different states.
71
+ *
72
+ * Idempotent, and a no-op refusal once the session is bound: one commission per session, and a
73
+ * bound one is terminal (a second contract would orphan the first).
74
+ */
75
+ export declare function enterCommissionDraft(sessionId: string, deps?: CommissionEnterDeps): Promise<CommissionEnterResult>;
76
+ /** Leave the drafting half: clear the registry field and remove the directory IF nothing was
77
+ * written into it. A draft holding real text is left on disk — the user can read it, and silently
78
+ * deleting someone's writing is never the right default. */
79
+ export declare function leaveCommissionDraft(sessionId: string, deps?: CommissionEnterDeps & {
80
+ readContract?: (file: string) => string | null;
81
+ removeDir?: (dir: string) => void;
82
+ }): Promise<{
83
+ ok: true;
84
+ removed: boolean;
85
+ } | {
86
+ ok: false;
87
+ error: string;
88
+ }>;
@@ -2,6 +2,7 @@ import * as fs from 'node:fs';
2
2
  import * as path from 'node:path';
3
3
  import { commissionsRoot, DRAFT_DIR_PREFIX } from './commission-paths.js';
4
4
  import { commissionRepo } from '../../store/commission-repo.js';
5
+ import { sessionStore } from '../../store/session-registry-repo.js';
5
6
  /**
6
7
  * Resolve a create-time commission request into registry fields, creating the draft directory for
7
8
  * `new`. The server owns this directory (v1 let the agent create it, which made the name
@@ -22,11 +23,93 @@ export async function resolveCommissionCreate(projectId, sessionName, request, d
22
23
  }
23
24
  return { commissionId: request.commissionId, commissionDraft: null };
24
25
  }
26
+ const { draftDir } = startCommissionDraft(projectId, sessionName, {
27
+ mkdir: deps.mkdir, resolveRoot: deps.resolveRoot,
28
+ });
29
+ return { commissionId: null, commissionDraft: draftDir };
30
+ }
31
+ /**
32
+ * Create (or reuse) the draft directory for `sessionName` and return both halves of its identity.
33
+ * Split out of {@link resolveCommissionCreate} because three callers need exactly this and nothing
34
+ * else: session creation, the `cortex_commission_start` tool, and the composer switching a live
35
+ * session into the mode (DR-0037 v4).
36
+ *
37
+ * `mkdir -p` is the idempotency: a second call on the same session lands on the same directory,
38
+ * which is what lets the tool be called twice without consequence.
39
+ */
40
+ export function startCommissionDraft(projectId, sessionName, deps = {}) {
25
41
  const root = (deps.resolveRoot ?? commissionsRoot)(projectId);
26
42
  if (!root)
27
43
  throw new Error(`Project ${projectId} has no context directory; commission mode needs one`);
28
- const draft = DRAFT_DIR_PREFIX + sessionName;
29
- const mkdir = deps.mkdir ?? ((dir) => fs.mkdirSync(dir, { recursive: true }));
30
- mkdir(path.join(root, draft));
31
- return { commissionId: null, commissionDraft: draft };
44
+ const draftDir = DRAFT_DIR_PREFIX + sessionName;
45
+ const dir = path.join(root, draftDir);
46
+ (deps.mkdir ?? ((target) => fs.mkdirSync(target, { recursive: true })))(dir);
47
+ return { draftDir, dir };
48
+ }
49
+ /**
50
+ * Put a session into the drafting half of commission mode: directory on disk, `commissionDraft` in
51
+ * the registry. The single implementation behind both entries — the agent's `cortex_commission_start`
52
+ * and the user's composer switch — so the two cannot drift into different states.
53
+ *
54
+ * Idempotent, and a no-op refusal once the session is bound: one commission per session, and a
55
+ * bound one is terminal (a second contract would orphan the first).
56
+ */
57
+ export async function enterCommissionDraft(sessionId, deps = {}) {
58
+ const session = await (deps.getSession ?? ((id) => sessionStore.getById(id)))(sessionId);
59
+ if (!session)
60
+ return { ok: false, error: `unknown session ${sessionId}` };
61
+ if (session.commissionId) {
62
+ return { ok: false, error: `this session is already bound to commission ${session.commissionId} — open a new session for another one` };
63
+ }
64
+ if (!session.projectId || !session.name) {
65
+ return { ok: false, error: 'session record is missing its project or name' };
66
+ }
67
+ const alreadyDrafting = !!session.commissionDraft;
68
+ try {
69
+ const { draftDir, dir } = (deps.start ?? startCommissionDraft)(session.projectId, session.name, { resolveRoot: deps.resolveRoot });
70
+ if (!alreadyDrafting) {
71
+ await (deps.setDraft ?? ((id, value) => sessionStore.setCommissionDraft(id, value)))(sessionId, draftDir);
72
+ }
73
+ return { ok: true, draftDir, dir, alreadyDrafting };
74
+ }
75
+ catch (error) {
76
+ return { ok: false, error: error.message };
77
+ }
78
+ }
79
+ /** Leave the drafting half: clear the registry field and remove the directory IF nothing was
80
+ * written into it. A draft holding real text is left on disk — the user can read it, and silently
81
+ * deleting someone's writing is never the right default. */
82
+ export async function leaveCommissionDraft(sessionId, deps = {}) {
83
+ const session = await (deps.getSession ?? ((id) => sessionStore.getById(id)))(sessionId);
84
+ if (!session)
85
+ return { ok: false, error: `unknown session ${sessionId}` };
86
+ if (session.commissionId)
87
+ return { ok: false, error: 'a bound commission cannot be left; close the commission instead' };
88
+ // Read the directory name off the record BEFORE clearing it: the store may hand back the same
89
+ // object it caches, and clearing the field first would leave nothing to point at on disk.
90
+ const draftDir = session.commissionDraft;
91
+ if (!draftDir)
92
+ return { ok: true, removed: false };
93
+ await (deps.setDraft ?? ((id, value) => sessionStore.setCommissionDraft(id, value)))(sessionId, null);
94
+ const root = session.projectId ? (deps.resolveRoot ?? commissionsRoot)(session.projectId) : null;
95
+ if (!root)
96
+ return { ok: true, removed: false };
97
+ const dir = path.join(root, draftDir);
98
+ const read = deps.readContract ?? ((file) => {
99
+ try {
100
+ return fs.readFileSync(file, 'utf8');
101
+ }
102
+ catch {
103
+ return null;
104
+ }
105
+ });
106
+ if ((read(path.join(dir, 'contract.md')) ?? '').trim())
107
+ return { ok: true, removed: false };
108
+ try {
109
+ (deps.removeDir ?? ((target) => fs.rmSync(target, { recursive: true, force: true })))(dir);
110
+ return { ok: true, removed: true };
111
+ }
112
+ catch {
113
+ return { ok: true, removed: false };
114
+ }
32
115
  }