@cortex-agent/server 2026.9.14 → 2026.9.15

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 (102) hide show
  1. package/defaults/plugins/cortex-commission/.claude-plugin/plugin.json +2 -2
  2. package/defaults/plugins/cortex-commission/plugin.json +2 -2
  3. package/defaults/plugins/cortex-commission/skills/commission/SKILL.md +3 -3
  4. package/dist/agent-adapter/claude/adapter.d.ts +0 -6
  5. package/dist/agent-adapter/claude/adapter.js +0 -8
  6. package/dist/agent-adapter/claude/defaults.d.ts +10 -7
  7. package/dist/agent-adapter/claude/defaults.js +18 -16
  8. package/dist/agent-adapter/claude/spawn-args.d.ts +0 -3
  9. package/dist/agent-adapter/claude/spawn-args.js +16 -16
  10. package/dist/agent-adapter/pi/mcp-bridge-logic.d.ts +11 -2
  11. package/dist/agent-adapter/pi/mcp-bridge-logic.js +32 -1
  12. package/dist/agent-adapter/pi/mcp-bridge.js +16 -15
  13. package/dist/agent-adapter/pi/session-options.d.ts +0 -6
  14. package/dist/agent-adapter/pi/session-options.js +1 -8
  15. package/dist/agent-adapter/types.d.ts +0 -1
  16. package/dist/core/mcp-tool-gate.d.ts +3 -17
  17. package/dist/core/mcp-tool-gate.js +3 -19
  18. package/dist/core/settings-spec.d.ts +1 -1
  19. package/dist/core/settings-spec.js +5 -1
  20. package/dist/domain/agents/config.d.ts +1 -1
  21. package/dist/domain/agents/config.js +1 -1
  22. package/dist/domain/agents/profile-switch.d.ts +1 -1
  23. package/dist/domain/agents/profile-switch.js +3 -5
  24. package/dist/domain/agents/subagent/runner.js +0 -1
  25. package/dist/domain/commissions/commission-draft.d.ts +58 -0
  26. package/dist/domain/commissions/commission-draft.js +87 -4
  27. package/dist/domain/commissions/commission-finalize.d.ts +8 -3
  28. package/dist/domain/commissions/commission-finalize.js +14 -0
  29. package/dist/domain/mcp/tools/commission-tools.d.ts +12 -1
  30. package/dist/domain/mcp/tools/commission-tools.js +68 -14
  31. package/dist/domain/remote/client-manager.js +66 -7
  32. package/dist/domain/remote/client-ssh-tunnel.d.ts +16 -5
  33. package/dist/domain/remote/client-ssh-tunnel.js +12 -5
  34. package/dist/domain/runs/builders.js +0 -1
  35. package/dist/domain/runs/compact.js +0 -1
  36. package/dist/domain/runs/engine-spec.d.ts +11 -4
  37. package/dist/domain/runs/engine-spec.js +7 -4
  38. package/dist/domain/runs/prompt.js +16 -10
  39. package/dist/domain/runs/request.d.ts +0 -1
  40. package/dist/domain/sessions/session-hooks.d.ts +5 -12
  41. package/dist/domain/sessions/session-hooks.js +6 -13
  42. package/dist/domain/sessions/session-lifecycle.d.ts +4 -4
  43. package/dist/domain/sessions/session-lifecycle.js +5 -6
  44. package/dist/domain/sessions/session-retention.d.ts +1 -3
  45. package/dist/domain/sessions/session-retention.js +9 -26
  46. package/dist/domain/sessions/session-use.d.ts +32 -0
  47. package/dist/domain/sessions/session-use.js +63 -0
  48. package/dist/domain/sessions/session.js +6 -5
  49. package/dist/domain/system/server-update-check.js +29 -1
  50. package/dist/domain/system/update-ui-state.d.ts +32 -0
  51. package/dist/domain/system/update-ui-state.js +63 -0
  52. package/dist/domain/threads/runner.js +0 -1
  53. package/dist/domain/ui-service/app-router.d.ts +30 -0
  54. package/dist/domain/ui-service/app-router.js +5 -1
  55. package/dist/domain/ui-service/input-schemas.d.ts +32 -0
  56. package/dist/domain/ui-service/input-schemas.js +22 -0
  57. package/dist/domain/ui-service/mutate/sessions.d.ts +13 -1
  58. package/dist/domain/ui-service/mutate/sessions.js +69 -3
  59. package/dist/domain/ui-service/mutate/system.d.ts +3 -1
  60. package/dist/domain/ui-service/mutate/system.js +13 -0
  61. package/dist/domain/ui-service/query/system.d.ts +2 -1
  62. package/dist/domain/ui-service/query/system.js +4 -0
  63. package/dist/domain/ui-service/types.d.ts +44 -3
  64. package/dist/domain/ui-service/ui-service.js +7 -3
  65. package/dist/entry/app.js +11 -23
  66. package/dist/entry/start-ui-http.js +3 -1
  67. package/dist/events/event-types.d.ts +5 -0
  68. package/dist/orchestration/agent-runner.d.ts +1 -1
  69. package/dist/orchestration/agent-runner.js +8 -11
  70. package/dist/orchestration/conversation-request.d.ts +26 -8
  71. package/dist/orchestration/conversation-request.js +49 -20
  72. package/dist/orchestration/edit-retry.js +2 -1
  73. package/dist/orchestration/interactions/ask-user-resume.js +2 -1
  74. package/dist/orchestration/interactions/ui-update-prompt.d.ts +8 -0
  75. package/dist/orchestration/interactions/ui-update-prompt.js +47 -0
  76. package/dist/orchestration/resume-dispatcher.js +2 -2
  77. package/dist/orchestration/routing/webhook.js +47 -0
  78. package/dist/orchestration/session-compact.d.ts +3 -0
  79. package/dist/orchestration/session-compact.js +3 -2
  80. package/dist/orchestration/session-events.d.ts +6 -0
  81. package/dist/orchestration/session-events.js +5 -0
  82. package/dist/orchestration/turn/turn-prep.js +2 -1
  83. package/dist/platform/ui-http/app-update.d.ts +11 -0
  84. package/dist/platform/ui-http/app-update.js +3 -0
  85. package/dist/store/conversation-ledger-repo.d.ts +10 -19
  86. package/dist/store/conversation-ledger-repo.js +143 -152
  87. package/dist/store/session-registry-import.d.ts +34 -0
  88. package/dist/store/session-registry-import.js +182 -0
  89. package/dist/store/session-registry-journal.d.ts +107 -0
  90. package/dist/store/session-registry-journal.js +307 -18
  91. package/dist/store/session-registry-repo.d.ts +113 -28
  92. package/dist/store/session-registry-repo.js +287 -104
  93. package/dist/store/version-migrations.d.ts +16 -0
  94. package/dist/store/version-migrations.js +34 -0
  95. package/package.json +1 -1
  96. package/web/dist/assets/{index-aHbOZSP6.js → index-CEZ0DSei.js} +1 -1
  97. package/web/dist/assets/{index-CCPxQ94C.css → index-CRDJo39X.css} +1 -1
  98. package/web/dist/assets/index-DjuPJVZE.js +444 -0
  99. package/web/dist/index.html +2 -2
  100. package/dist/store/session-repo.d.ts +0 -65
  101. package/dist/store/session-repo.js +0 -184
  102. package/web/dist/assets/index-BuXbCsuz.js +0 -444
@@ -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
  }
@@ -5,11 +5,16 @@ export interface CommissionFinalizeArgs {
5
5
  title?: string;
6
6
  contractPath: string;
7
7
  }
8
+ /** The session fields finalize decides on: which project owns the directory, and which commission
9
+ * state the session is in. A submit is only legal from a session that is DRAFTING (DR-0037 v4). */
10
+ export interface CommissionFinalizeSession {
11
+ projectId: string;
12
+ commissionId?: string | null;
13
+ commissionDraft?: string | null;
14
+ }
8
15
  /** Store seams only — path checks run against the real filesystem on purpose (tests use tmp dirs). */
9
16
  export interface CommissionFinalizeDeps {
10
- getSession?: (id: string) => Promise<{
11
- projectId: string;
12
- } | null>;
17
+ getSession?: (id: string) => Promise<CommissionFinalizeSession | null>;
13
18
  resolveRoot?: (projectId: string) => string | null;
14
19
  findBySlug?: (projectId: string, slug: string) => Promise<unknown | null>;
15
20
  addCommission?: (record: CommissionRecord) => Promise<void>;
@@ -42,6 +42,15 @@ export async function validateCommissionFinalize(args, deps = {}) {
42
42
  const session = await (deps.getSession ?? ((id) => sessionStore.getById(id)))(args.sessionId);
43
43
  if (!session)
44
44
  return fail(`unknown session ${args.sessionId}`);
45
+ // The state check, not tool visibility, is what makes a commission impossible to bootstrap from a
46
+ // session that never entered the mode. Visibility was the v3 lever and it never worked on the
47
+ // Claude backend: `--tools` filters the built-in set only, so the MCP tools were always callable.
48
+ if (session.commissionId) {
49
+ return fail(`this session is already bound to commission ${session.commissionId} — one commission per session`);
50
+ }
51
+ if (!session.commissionDraft) {
52
+ return fail('this session is not drafting a commission — call cortex_commission_start first');
53
+ }
45
54
  const slug = slugifyCommissionName(args.name ?? '');
46
55
  if (!slug)
47
56
  return fail(`name "${args.name}" leaves no slug-safe characters — use an ASCII name`);
@@ -51,6 +60,11 @@ export async function validateCommissionFinalize(args, deps = {}) {
51
60
  const draft = resolveDraftDir(root, args.contractPath);
52
61
  if (draft.ok === false)
53
62
  return draft; // (=== false: truthiness narrowing is off with strict:false)
63
+ // Own draft only: the shape check above accepts any `_draft-*` under this project, which would let
64
+ // one session submit another's contract and rename a directory out from under it.
65
+ if (path.basename(draft.dir) !== session.commissionDraft) {
66
+ return fail(`contract.md is in ${path.basename(draft.dir)}, but this session drafts in ${session.commissionDraft}`);
67
+ }
54
68
  const targetDir = path.join(root, slug);
55
69
  if (fs.existsSync(targetDir))
56
70
  return fail(`commissions/${slug} already exists — pick another name`);
@@ -6,9 +6,20 @@ export interface CommissionSubmitArgs {
6
6
  title?: string;
7
7
  summary?: string;
8
8
  }
9
+ /**
10
+ * Enter the drafting phase and hand back the creation protocol.
11
+ *
12
+ * Impure since v4: the session decides for itself whether a task is a commission, so the tool is
13
+ * the entry point rather than a briefing handed to a session the user already opted in. It creates
14
+ * the draft directory and sets `commissionDraft` through the loopback webhook (this process has no
15
+ * registry), which is also what makes `cortex_commission_submit` legal afterwards.
16
+ *
17
+ * Idempotent: a session already drafting gets the same directory and the same protocol back, so the
18
+ * [Commission] block can tell a user-initiated session to call it without risking a second draft.
19
+ */
9
20
  export declare function runCommissionStart(args: {
10
21
  reasoning?: string;
11
- }, deps: InteractionToolDeps): CallToolResultShape;
22
+ }, deps: InteractionToolDeps): Promise<CallToolResultShape>;
12
23
  /**
13
24
  * Posts the contract through the blocking /hook/exit-plan-mode approval channel (shared with
14
25
  * cortex_plan_exit, but this is a separate tool — plan mode is untouched). The
@@ -12,12 +12,24 @@ function okResult(text) {
12
12
  // commission skill covers maintenance only.
13
13
  // =====================================================================================
14
14
  const COMMISSION_START_PROTOCOL = `\
15
- You are starting a commission: a long task anchored by two files the user can read at any time.
15
+ This session is now drafting a commission: a long task anchored by two files the user can read at
16
+ any time.
16
17
 
17
18
  contract.md — the binding statement of intent. Written once, here, through the drill below.
18
19
  Changed afterwards only by appending to its Revisions section.
19
20
  ledger.md — your state record, written after the contract is approved.
20
21
 
22
+ Phase 0 — is this actually one? You may have entered on your own judgement, so check it against the
23
+ criteria before spending the user's time. A commission fits when the work spans several sessions or
24
+ days, when the goal hides decisions only the user can settle, or when "done" needs to be auditable
25
+ later. It does NOT fit a single question, a bounded edit whose shape is already agreed, or open
26
+ exploration with no commitment at the end. If it does not fit, say so and tell the user to switch
27
+ the mode off — do not drill anyway.
28
+
29
+ Announce it, once: unless the user turned this mode on themselves, your first cortex_ask_user call
30
+ must open by stating that you are treating this as a commission and why, and must offer an option
31
+ meaning "skip the contract, just do it". Having said it once, do not keep asking.
32
+
21
33
  Phase 1 — drill. Implement nothing. Investigation is read-only; the only thing you write is the
22
34
  contract draft. The goal is to surface and resolve the decisions hiding inside the user's request
23
35
  BEFORE any work starts.
@@ -62,21 +74,49 @@ Phase 3 — submit it with cortex_commission_submit. That call blocks until the
62
74
  denial the feedback comes back and the draft survives, so revise and call again. On approval the
63
75
  draft directory is renamed to the approved slug, the commission is registered, and this session is
64
76
  bound to it.`;
65
- function draftLocationLine(deps) {
66
- const dir = deps.sessionName
67
- ? `commissions/_draft-${deps.sessionName}/`
68
- : 'the commissions/_draft-* directory';
69
- return `Draft directory (already created by the server, under this project's context directory): ${dir}\n`
77
+ function draftLocationLine(dir) {
78
+ return `Draft directory (created for you): ${dir}\n`
70
79
  + 'Write contract.md there. Do not create or rename that directory yourself.';
71
80
  }
72
- export function runCommissionStart(args, deps) {
81
+ /**
82
+ * Enter the drafting phase and hand back the creation protocol.
83
+ *
84
+ * Impure since v4: the session decides for itself whether a task is a commission, so the tool is
85
+ * the entry point rather than a briefing handed to a session the user already opted in. It creates
86
+ * the draft directory and sets `commissionDraft` through the loopback webhook (this process has no
87
+ * registry), which is also what makes `cortex_commission_submit` legal afterwards.
88
+ *
89
+ * Idempotent: a session already drafting gets the same directory and the same protocol back, so the
90
+ * [Commission] block can tell a user-initiated session to call it without risking a second draft.
91
+ */
92
+ export async function runCommissionStart(args, deps) {
93
+ if (!deps.sessionId)
94
+ return errorResult('cortex_commission_start error: no session id in the MCP env');
95
+ let body;
96
+ try {
97
+ const resp = await deps.httpPost(`${deps.webhookBaseUrl}/hook/commission-start`, {
98
+ sessionId: deps.sessionId, channel: deps.channel, reasoning: args.reasoning ?? null,
99
+ });
100
+ body = resp.body;
101
+ if (resp.status !== 200) {
102
+ return errorResult(`cortex_commission_start error: webhook returned status ${resp.status}`);
103
+ }
104
+ }
105
+ catch (e) {
106
+ return errorResult(`cortex_commission_start error: webhook call failed: ${e.message}`);
107
+ }
108
+ if (typeof body?.error === 'string')
109
+ return errorResult(`cortex_commission_start error: ${body.error}`);
110
+ if (!body?.ok || typeof body.dir !== 'string') {
111
+ return errorResult('cortex_commission_start error: server did not return a draft directory');
112
+ }
73
113
  const reasoning = (args.reasoning && args.reasoning.trim()) || null;
74
- const text = [
114
+ return okResult([
75
115
  COMMISSION_START_PROTOCOL,
76
- draftLocationLine(deps),
116
+ draftLocationLine(body.dir),
117
+ body.alreadyDrafting ? '(This session was already drafting; the directory above is unchanged.)' : null,
77
118
  reasoning ? `(Reasoning recorded: ${reasoning})` : null,
78
- ].filter(Boolean).join('\n\n');
79
- return okResult(text);
119
+ ].filter(Boolean).join('\n\n'));
80
120
  }
81
121
  function validateArgs(args, deps) {
82
122
  if (!deps.channel)
@@ -111,6 +151,14 @@ function formatOutcome(body) {
111
151
  + `Commission directory: ${fin.dir}\n\n`
112
152
  + LEDGER_INIT);
113
153
  }
154
+ /** The same four rules the `[Commission]` block carries (see `domain/runs/prompt.ts`). Repeated
155
+ * here because the skill and the block both arrive on the NEXT turn — the plugin set is fixed at
156
+ * spawn and the block is a prompt prefix — while the contract lands in the MIDDLE of this one. */
157
+ const COMMISSION_EXECUTION_PROTOCOL = `\
158
+ 1. Surprises are three kinds: an obstacle you route around; a fork you align on; a discovery that invalidates a contract premise. A discovery MUST be surfaced against the contract — never silently absorbed.
159
+ 2. Completion claims need evidence pointers (file paths, command outputs, EXP ids) in ledger.md.
160
+ 3. Before this session ends, and at each stage boundary, append a checkpoint CP-N with three diffs — plan vs done, contract vs current direction, assumptions vs reality — graded ok / attention / gate. Re-read contract.md first.
161
+ 4. Contract gates are blocking: ask the user and wait.`;
114
162
  /** Written into the final directory the moment the contract lands, so the state record exists from
115
163
  * the first minute. Everything after this point is maintenance, which the commission skill covers. */
116
164
  const LEDGER_INIT = `\
@@ -130,7 +178,13 @@ Now create ledger.md in that directory, derived from the contract:
130
178
  ## Log
131
179
  (L-NNN entries, appended)
132
180
 
133
- Then start executing. The commission skill describes the checkpoint discipline from here on.`;
181
+ Then start executing.
182
+
183
+ The \`commission\` skill carries the maintenance protocol in full and loads from your NEXT turn (the
184
+ session respawns onto it, keeping this conversation). For the rest of THIS turn, these four rules
185
+ are the whole of it:
186
+
187
+ ${COMMISSION_EXECUTION_PROTOCOL}`;
134
188
  /**
135
189
  * Posts the contract through the blocking /hook/exit-plan-mode approval channel (shared with
136
190
  * cortex_plan_exit, but this is a separate tool — plan mode is untouched). The
@@ -171,8 +225,8 @@ export async function runCommissionSubmit(args, deps) {
171
225
  return formatOutcome(resp.body);
172
226
  }
173
227
  export function registerCommissionTools(server, deps) {
174
- server.tool('cortex_commission_start', 'Start creating a commission — a long task anchored by a user-approved contract. Call this FIRST, before any investigation or questions: it returns the complete creation protocol (drill rules, contract.md structure) and the draft directory to write the contract into. Unrelated to plan mode; cortex_plan_enter/exit still exist and are for ordinary implementation planning. Optional `reasoning` is recorded for the audit trail.', { reasoning: z.string().optional() }, async (args) => runCommissionStart(args ?? {}, deps));
175
- server.tool('cortex_commission_submit', 'Submit a drafted commission contract for human approval, and land the commission if approved. Reads contract.md at `contract_file_path` — it must live in a `commissions/_draft-*/` directory of this session\'s project — and BLOCKS until the human decides. On approval the draft directory is renamed to the slug of `name`, the commission is registered, this session is bound to it, and the final directory is returned. On denial the feedback comes back and the draft survives: revise and call again.', {
228
+ server.tool('cortex_commission_start', 'Put THIS session into commission mode and get the creation protocol: a commission is a long task anchored by a contract the user approves before any work begins. Call it when the work spans several sessions or days, hides decisions only the user can settle, or needs an auditable record of what "done" meant — not for a single question, an already-agreed edit, or open exploration. It creates the draft directory, returns the full drill protocol and contract structure, and is idempotent (safe to call again to re-read the protocol). Unrelated to plan mode; cortex_plan_enter/exit remain for ordinary implementation planning. Optional `reasoning` is recorded for the audit trail.', { reasoning: z.string().optional() }, async (args) => (await runCommissionStart(args ?? {}, deps)));
229
+ server.tool('cortex_commission_submit', 'Submit a drafted commission contract for human approval, and land the commission if approved. Only legal from a session that entered the mode through cortex_commission_start (or that the user switched into it); it reads contract.md at `contract_file_path`, which must be THIS session\'s own `commissions/_draft-*/` directory, and BLOCKS until the human decides. On approval the draft directory is renamed to the slug of `name`, the commission is registered, this session is bound to it, and the final directory is returned. On denial the feedback comes back and the draft survives: revise and call again.', {
176
230
  contract_file_path: z.string().describe('Absolute path of the draft contract.md to submit'),
177
231
  name: z.string().describe('Final commission name; slugified into the directory name'),
178
232
  title: z.string().optional().describe('Display title (defaults to name)'),
@@ -426,14 +426,68 @@ function managedServerUrl(reg) {
426
426
  return `ws://127.0.0.1:${reg.clientReversePort ?? clientManagerPort}`;
427
427
  }
428
428
  /**
429
- * Kill whatever still listens on the tunnel's loopback port on a Windows host. Windows OpenSSH
430
- * neither tears the forward listener down with the session nor refuses a duplicate bind, so a
431
- * dead tunnel can keep answering the cortex-client while a healthy one sits next to it unused.
429
+ * Kill the sshd sessions still listening on the tunnel's loopback port on a Windows host. Windows
430
+ * OpenSSH neither tears the forward listener down with the session nor refuses a duplicate bind,
431
+ * so a dead tunnel can keep answering the cortex-client while a healthy one sits next to it
432
+ * unused — and several can pile up on one port.
433
+ *
434
+ * It loops because `Get-NetTCPConnection` reports a single row per endpoint no matter how many
435
+ * sockets are bound to it: with two listeners on the port, `netstat -ano` and .NET's
436
+ * `GetActiveTcpListeners()` both show two and the cmdlet shows one — the oldest. One pass would
437
+ * evict one listener and leave the rest, so it repeats until no sshd holds the port.
438
+ *
439
+ * The owner is checked by name because the kill is otherwise indiscriminate: whatever happens to
440
+ * be listening on the port gets force-stopped, which is a stray kill waiting to happen if anything
441
+ * else ever binds it. This is the same guard the POSIX command applies through `comm`.
432
442
  */
433
443
  function windowsFreePortCommand(port) {
434
- return 'powershell -NoProfile -Command "Get-NetTCPConnection -State Listen -LocalPort '
435
- + `${port} -ErrorAction SilentlyContinue | `
436
- + 'ForEach-Object { Stop-Process -Id $_.OwningProcess -Force -ErrorAction SilentlyContinue }"';
444
+ return 'powershell -NoProfile -Command "for ($i = 0; $i -lt 8; $i++) { '
445
+ + `$t = @(Get-NetTCPConnection -State Listen -LocalPort ${port} -ErrorAction SilentlyContinue | `
446
+ + "Where-Object { (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName -eq 'sshd' }); "
447
+ + 'if (-not $t) { break }; '
448
+ + '$t | ForEach-Object { Stop-Process -Id $_.OwningProcess -Force -ErrorAction SilentlyContinue }; '
449
+ + 'Start-Sleep -Milliseconds 250 }"';
450
+ }
451
+ /** Tags a POSIX tunnel's remote session so a stale one can be found by name rather than by port. */
452
+ function posixTunnelMarker(port) {
453
+ return `cortex-tunnel-${port}`;
454
+ }
455
+ /**
456
+ * The remote end of a POSIX tunnel: a shell that parks with the marker in its own argv for as long
457
+ * as the sshd that spawned it lives. `ssh -N` would leave nothing on the far side but sshd, and
458
+ * sshd marks itself non-dumpable, so `/proc/<sshd>/fd` is root-only and an unprivileged
459
+ * `fuser`/`lsof`/`ss -p` reports no owner for the forward listener at all — a stale one simply
460
+ * cannot be located from the port. This process is an ordinary child of that sshd, which turns
461
+ * "who holds the port" into a `pgrep`.
462
+ *
463
+ * It has to watch its parent rather than park forever: `-T` gives the session no pty, so nothing
464
+ * sends SIGHUP when sshd goes away, and a plain `sleep` loop would be reparented to init and leak
465
+ * one process per tunnel restart. Watching the parent by pid also keeps the black-hole case right
466
+ * — there sshd is still alive, so the marker stays put and stays findable.
467
+ */
468
+ function posixTunnelCommand(port) {
469
+ return "exec sh -c 'P=$PPID; while kill -0 $P 2>/dev/null; do sleep 30; done"
470
+ + ` # ${posixTunnelMarker(port)}'`;
471
+ }
472
+ /**
473
+ * Evict a stale POSIX tunnel by killing the sshd session that owns its listener. When the link
474
+ * dies without a clean close, sshd blocks writing the session's exit status into the black hole
475
+ * and keeps the forward bound for a full TCP retransmission timeout (~15 min); every `ssh -R` in
476
+ * that window dies on ExitOnForwardFailure. Killing the marker's parent needs no privilege — that
477
+ * sshd runs as us — but it does need care: `/proc/<pid>/stat` is read past the last `)` because a
478
+ * process name may contain spaces, and the kill is gated on the parent actually being an sshd, so
479
+ * neither a recycled PID nor a marker already reparented to init can turn this into a stray kill.
480
+ * The name is matched as a prefix because OpenSSH 9.8+ renamed the per-connection process to
481
+ * `sshd-session`. The `[-]` keeps the pattern from matching the command's own shell, which would
482
+ * otherwise make this hang up on itself.
483
+ */
484
+ function posixFreePortCommand(port) {
485
+ const pattern = posixTunnelMarker(port).replace('cortex-', 'cortex[-]');
486
+ return `for p in $(pgrep -f "${pattern}"); do `
487
+ + 'pp=$(sed -e "s/^.*) //" /proc/$p/stat 2>/dev/null | cut -d" " -f2); '
488
+ + '[ -n "$pp" ] || continue; '
489
+ + 'case "$(cat /proc/$pp/comm 2>/dev/null)" in sshd*) kill "$pp";; esac; '
490
+ + 'done; exit 0';
437
491
  }
438
492
  function tunnelSpec(device, reg) {
439
493
  if (reg.clientConnection !== 'ssh-reverse')
@@ -442,8 +496,13 @@ function tunnelSpec(device, reg) {
442
496
  throw new Error(`SSH reverse route is not ready for ${device}`);
443
497
  const remotePort = reg.clientReversePort ?? clientManagerPort;
444
498
  const spec = { device, host: reg.ssh, remotePort, serverPort: clientManagerPort };
445
- if (reg.win)
499
+ if (reg.win) {
446
500
  spec.freeRemotePortCommand = windowsFreePortCommand(remotePort);
501
+ }
502
+ else {
503
+ spec.markerCommand = posixTunnelCommand(remotePort);
504
+ spec.freeRemotePortCommand = posixFreePortCommand(remotePort);
505
+ }
447
506
  return spec;
448
507
  }
449
508
  async function ensureManagedRoute(device, reg) {
@@ -4,13 +4,24 @@ export interface SshTunnelSpec {
4
4
  host: string;
5
5
  remotePort: number;
6
6
  serverPort: number;
7
+ /**
8
+ * Optional remote command run for the lifetime of the tunnel, in place of `-N`. Its only job is
9
+ * to leave a findable process on the far side: `ssh -N` puts nothing there but sshd itself, and
10
+ * sshd marks itself non-dumpable, so an unprivileged `fuser`/`lsof`/`ss -p` cannot say which
11
+ * process owns a forward listener. A marker command gives the session an ordinary greppable
12
+ * child whose parent is exactly the sshd holding `remotePort`.
13
+ */
14
+ markerCommand?: string;
7
15
  /**
8
16
  * Optional remote shell command run immediately before each `ssh -R` spawn, to release
9
- * `remotePort` on the far side. Needed on Windows: OpenSSH there leaves the forward listener
10
- * behind in an orphaned `sshd -z` child when our side of the tunnel dies, and it lets a second
11
- * sshd bind the same loopback port instead of failing. The cortex-client then reconnects into
12
- * the dead listener and the device stays offline even though a healthy tunnel exists. POSIX
13
- * sshd frees the port with the session, so leave this unset there.
17
+ * `remotePort` on the far side. Both platforms strand the listener when our end dies without a
18
+ * clean close, for different reasons:
19
+ * - Windows OpenSSH leaves it in an orphaned `sshd -z` child and then lets a second sshd bind
20
+ * the same loopback port instead of failing, so the cortex-client reconnects into the dead
21
+ * listener and the device stays offline even though a healthy tunnel exists.
22
+ * - POSIX sshd keeps it while it blocks writing the session's exit status into the black hole,
23
+ * so it outlives the session by a full TCP retransmission timeout (~15 min) and every spawn
24
+ * in between dies on `ExitOnForwardFailure`.
14
25
  */
15
26
  freeRemotePortCommand?: string;
16
27
  }
@@ -20,8 +20,11 @@ function defaultSpawnSsh(args) {
20
20
  return spawn('ssh', args, { stdio: 'ignore' });
21
21
  }
22
22
  export function buildSshTunnelArgs(spec, controlPath) {
23
- return [
24
- '-M', '-S', controlPath, '-N', '-T',
23
+ const args = [
24
+ '-M', '-S', controlPath, '-T',
25
+ // A marker command replaces `-N`: the session has to run something for the far side to be
26
+ // identifiable later. Both forms keep the forward alive for the life of the ssh process.
27
+ ...(spec.markerCommand ? [] : ['-N']),
25
28
  '-o', 'BatchMode=yes',
26
29
  '-o', 'ConnectTimeout=5',
27
30
  '-o', 'StrictHostKeyChecking=no',
@@ -31,11 +34,15 @@ export function buildSshTunnelArgs(spec, controlPath) {
31
34
  '-R', `127.0.0.1:${spec.remotePort}:127.0.0.1:${spec.serverPort}`,
32
35
  spec.host,
33
36
  ];
37
+ if (spec.markerCommand)
38
+ args.push(spec.markerCommand);
39
+ return args;
34
40
  }
35
41
  // Compares where the tunnel points, which is what cannot change under a live supervisor.
36
- // `freeRemotePortCommand` is deliberately excluded: it is derived from the ports compared here
37
- // plus the host's OS, so treating it as a route change would only fire on a `win` flag edit —
38
- // and wedging a device permanently over that is a worse failure than using a stale command.
42
+ // `markerCommand` and `freeRemotePortCommand` are deliberately excluded: both are derived from the
43
+ // ports compared here plus the host's OS, so treating either as a route change would only fire on
44
+ // a `win` flag edit — and wedging a device permanently over that is a worse failure than using a
45
+ // stale command.
39
46
  function sameSpec(a, b) {
40
47
  return a.host === b.host && a.remotePort === b.remotePort && a.serverPort === b.serverPort;
41
48
  }
@@ -44,7 +44,6 @@ export function continuationRunRequest(o) {
44
44
  executionKind: o.executionKind ?? 'local',
45
45
  isUserInitiated: o.isUserInitiated ?? false,
46
46
  commissionMode: false,
47
- commissionTools: false,
48
47
  scheduleTaskId: o.scheduleTaskId ?? null,
49
48
  },
50
49
  policy: { ...DIRECT_RUN_POLICY },
@@ -53,7 +53,6 @@ function compactRequest(request, profile) {
53
53
  executionKind: 'local',
54
54
  isUserInitiated: true,
55
55
  commissionMode: false,
56
- commissionTools: false,
57
56
  },
58
57
  policy: {
59
58
  background: 'none',
@@ -6,7 +6,10 @@ import type { RunRequest } from './request.js';
6
6
  export interface PluginScope {
7
7
  channel?: string;
8
8
  feishuSkillsInWeb?: boolean;
9
- /** True while the session is in commission mode, drafting or already bound. */
9
+ /** True once the session is BOUND to a landed commission. Drafting deliberately does not count
10
+ * (DR-0037 v4): the creation protocol lives in `cortex_commission_start`'s return value, and the
11
+ * skill covers maintenance only — it says so itself. Loading it during the drill would put the
12
+ * wrong half of the procedure in front of the model. */
10
13
  commissionMode?: boolean;
11
14
  }
12
15
  /** Default channel scopes. The Feishu skill bundle also permits web: sessions when
@@ -15,9 +18,13 @@ export declare const CHANNEL_SCOPED_PLUGINS: ReadonlyArray<{
15
18
  plugin: string;
16
19
  channelPrefix: string;
17
20
  }>;
18
- /** Plugins that load only for sessions in commission mode. The commission skill is long and
19
- * prescriptive (drill protocol, contract shape, checkpoint discipline); loading it into every
20
- * session would put a procedure nobody asked for in front of the model (DR-0037 v2). */
21
+ /** Plugins that load only for sessions BOUND to a commission. The commission skill is long and
22
+ * prescriptive (ledger entries, surprise triage, checkpoint discipline); loading it into every
23
+ * session would put a procedure nobody asked for in front of the model (DR-0037 v2).
24
+ *
25
+ * Plugin dirs are part of the pool identity, so a contract landing mid-session brings the skill in
26
+ * on the next turn via a fresh spawn + `--resume`. The turn the contract lands on is covered by
27
+ * the protocol `cortex_commission_submit` returns on approval. */
21
28
  export declare const COMMISSION_SCOPED_PLUGINS: readonly string[];
22
29
  /** Drop scoped plugin dirs the current session does not qualify for. Non-scoped plugins always pass
23
30
  * through. Matched by the plugin dir's final path segment (basename) so substrings like
@@ -10,9 +10,13 @@ import { resolvePluginRuntime } from '../plugins/runtime.js';
10
10
  export const CHANNEL_SCOPED_PLUGINS = [
11
11
  { plugin: 'cortex-feishu', channelPrefix: 'feishu:' },
12
12
  ];
13
- /** Plugins that load only for sessions in commission mode. The commission skill is long and
14
- * prescriptive (drill protocol, contract shape, checkpoint discipline); loading it into every
15
- * session would put a procedure nobody asked for in front of the model (DR-0037 v2). */
13
+ /** Plugins that load only for sessions BOUND to a commission. The commission skill is long and
14
+ * prescriptive (ledger entries, surprise triage, checkpoint discipline); loading it into every
15
+ * session would put a procedure nobody asked for in front of the model (DR-0037 v2).
16
+ *
17
+ * Plugin dirs are part of the pool identity, so a contract landing mid-session brings the skill in
18
+ * on the next turn via a fresh spawn + `--resume`. The turn the contract lands on is covered by
19
+ * the protocol `cortex_commission_submit` returns on approval. */
16
20
  export const COMMISSION_SCOPED_PLUGINS = ['cortex-commission'];
17
21
  /** Drop scoped plugin dirs the current session does not qualify for. Non-scoped plugins always pass
18
22
  * through. Matched by the plugin dir's final path segment (basename) so substrings like
@@ -96,7 +100,6 @@ function spawnPolicy(request) {
96
100
  allowlist: request.policy.mcpToolAllowlist === undefined
97
101
  ? undefined : canonicalizeMcpToolAllowlist(request.policy.mcpToolAllowlist),
98
102
  configPaths: request.isolation?.mcpConfigPaths,
99
- commissionTools: request.context.commissionTools,
100
103
  browserCdpEndpoint: request.policy.browserCdpEndpoint ?? undefined,
101
104
  },
102
105
  flags: {