@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
@@ -9,6 +9,7 @@ import { createUiSessionStore, DEFAULT_SESSION_TTL_MS } from '../platform/ui-htt
9
9
  import { createUiAuthRoutes, createUiSessionProbeRoute, UI_LOGIN_PATH, UI_SESSION_PATH, } from '../platform/ui-http/ui-auth-routes.js';
10
10
  import { createOtaRoutes } from '../platform/ui-http/ui-ota.js';
11
11
  import { createAppUpdateRoutes } from '../platform/ui-http/app-update.js';
12
+ import { isUpdateDevMode } from '../domain/system/server-update-check.js';
12
13
  import { createForwardRoutes } from '../platform/ui-http/port-forward.js';
13
14
  import { createBrowserStatusRoutes } from '../platform/ui-http/browser-status.js';
14
15
  import { createDevicePortRoutes } from '../platform/ui-http/device-ports.js';
@@ -393,7 +394,8 @@ export function startUiHttpServer(opts) {
393
394
  // App shell self-update: advertises the newest GitHub release carrying native app assets
394
395
  // (capped at this server's version) so the shell can offer a one-prompt update. JSON only —
395
396
  // the binaries download straight from the GitHub CDN. Same auth gate as tRPC.
396
- ...createAppUpdateRoutes(),
397
+ // A dev server never advertises app releases: see AppUpdateRouteOptions.devMode.
398
+ ...createAppUpdateRoutes({ devMode: isUpdateDevMode() }),
397
399
  // Listening-port discovery for the desktop port forward: tells the shell which loopback
398
400
  // services exist here so the Ports list can offer them. Same auth gate as tRPC.
399
401
  ...createForwardRoutes(),
@@ -120,6 +120,11 @@ export type CortexEvent = {
120
120
  ts: string;
121
121
  sessionId: string;
122
122
  channel: string;
123
+ } | {
124
+ type: 'session.commission';
125
+ ts: string;
126
+ sessionId: string;
127
+ channel: string;
123
128
  } | {
124
129
  type: 'plan.submitted';
125
130
  ts: string;
@@ -43,7 +43,7 @@ export declare class AgentRunner {
43
43
  * Resolve what a turn needs but is not part of it — the files, the session record (found or
44
44
  * created) with its use lease, the browser the session opted into — and open the turn.
45
45
  *
46
- * `sessionId` here is the STABLE tracking id: sessions.json binds channel → track id (not the
46
+ * `sessionId` here is the STABLE tracking id: the registry binds channel → track id (not the
47
47
  * backend id), and everything downstream (publish / history / status / Destination) keys on it.
48
48
  * The backend resume target is resolved separately. A channel with no bound session yet (fresh
49
49
  * Slack/Feishu/etc.) mints + registers + binds a track id up front, unifying it with the web path
@@ -136,7 +136,7 @@ export class AgentRunner {
136
136
  * Resolve what a turn needs but is not part of it — the files, the session record (found or
137
137
  * created) with its use lease, the browser the session opted into — and open the turn.
138
138
  *
139
- * `sessionId` here is the STABLE tracking id: sessions.json binds channel → track id (not the
139
+ * `sessionId` here is the STABLE tracking id: the registry binds channel → track id (not the
140
140
  * backend id), and everything downstream (publish / history / status / Destination) keys on it.
141
141
  * The backend resume target is resolved separately. A channel with no bound session yet (fresh
142
142
  * Slack/Feishu/etc.) mints + registers + binds a track id up front, unifying it with the web path
@@ -154,10 +154,9 @@ export class AgentRunner {
154
154
  let sessionLease = null;
155
155
  /** Opt-in browser access, read off the session record (plan/embedded-browser.md §17). */
156
156
  let sessionBrowser = null;
157
- /** Set while the session is in commission mode but its contract has not been named yet; that
158
- * is exactly the window in which the commission-creation tools are injected (DR-0037 v3). */
159
- let sessionCommissionDraft = null;
160
- /** Set once a contract has landed. Either field means the session is in commission mode. */
157
+ /** Set once a contract has landed — the state that loads the commission skill (DR-0037 v4).
158
+ * Drafting is not tracked here: the drill needs no plugin, and the [Commission] block reads the
159
+ * session record itself (see resolveConversationCommission). */
161
160
  let sessionCommissionId = null;
162
161
  if (sessionId) {
163
162
  sessionLease = await acquireSessionUseLease(sessionId);
@@ -167,11 +166,10 @@ export class AgentRunner {
167
166
  backendSessionId = effectiveBackendSessionId(sessionLease.session);
168
167
  projectId = sessionLease.session.projectId ?? 'general';
169
168
  sessionBrowser = sessionLease.session.browser ?? null;
170
- // settings.commissionEnabled is the global switch for the feature (off by default while it
171
- // is under test). With it off, a session that was bound while it was on reverts to an
172
- // ordinary session: no commission tools, no commission skill, no contract block.
169
+ // settings.commissionEnabled is the global switch for the feature. With it off, a session
170
+ // that was bound while it was on reverts to an ordinary session: no commission skill, no
171
+ // contract block, and the commission tools refuse.
173
172
  const commissionOn = getSettings().commissionEnabled;
174
- sessionCommissionDraft = commissionOn ? sessionLease.session.commissionDraft ?? null : null;
175
173
  sessionCommissionId = commissionOn ? sessionLease.session.commissionId ?? null : null;
176
174
  }
177
175
  else {
@@ -218,8 +216,7 @@ export class AgentRunner {
218
216
  files: allFiles,
219
217
  trigger: 'user',
220
218
  browserCdpEndpoint: browser.cdpEndpoint,
221
- commissionTools: !!sessionCommissionDraft,
222
- commissionMode: !!(sessionCommissionDraft || sessionCommissionId),
219
+ commissionMode: !!sessionCommissionId,
223
220
  onPromptBuilt: debugEnabled ? (prompt) => {
224
221
  recordHistory(conversationHistory.appendUserPrompt(trackSessionId, { agentMessage: prompt }), () => publishSessionDebugUpdated({ sessionId: trackSessionId, channel }));
225
222
  } : null,
@@ -27,9 +27,7 @@ export interface PrepareConversationRequestOptions {
27
27
  profileOverride?: string | null;
28
28
  /** CDP endpoint of the browser this session opted into, or null for the usual no-browser session. */
29
29
  browserCdpEndpoint?: string | null;
30
- /** Expose the commission-creation tools this turn — true only while a contract is being drafted. */
31
- commissionTools?: boolean;
32
- /** True while the session is in commission mode; loads the commission skill bundle. */
30
+ /** True once the session is bound to a landed commission; loads the commission skill bundle. */
33
31
  commissionMode?: boolean;
34
32
  /** Receives the backend-ready prompt after context and attachment paths are assembled. */
35
33
  onPromptBuilt?: ((prompt: string) => void) | null;
@@ -57,20 +55,40 @@ export declare function resolveConversationProject(args: {
57
55
  id: string;
58
56
  contextDir: string;
59
57
  } | null;
58
+ /** The delivery key for a session's current commission binding, or null outside the mode. Bound
59
+ * wins over drafting: finalize clears the draft, and the two are never both meaningful. */
60
+ export declare function commissionBindingKey(session: {
61
+ commissionId?: string | null;
62
+ commissionDraft?: string | null;
63
+ } | null): string | null;
60
64
  /**
61
- * Load the [Commission] injection payload for a fresh commission-bound session, or null for
62
- * ordinary sessions. Same first-turn-only economics as USER.md / [Session Project]: resume keeps the
63
- * block in backend history, and mid-run contract edits reach the agent through the checkpoint
64
- * protocol's mandatory re-read, not through re-injection. Best-effort: any failure injects nothing.
65
+ * Load the [Commission] injection payload for this turn, or null when nothing needs delivering.
66
+ *
67
+ * Delivery follows the STATE, not the session's age (DR-0037 v4). v3 injected on the first turn
68
+ * only, on the same economics as USER.md / [Session Project]: resume keeps the block in backend
69
+ * history, so re-sending it every turn is waste. True — but it silently assumed the binding is
70
+ * decided before the first turn, and it is not: a session can enter the mode mid-conversation (the
71
+ * agent calls `cortex_commission_start`, or the user switches it on) and it always binds its
72
+ * contract mid-conversation. Those sessions received the block never. So the marker records WHICH
73
+ * binding was delivered, and a turn injects when the current binding differs from it.
74
+ *
75
+ * `isFreshSession` still forces delivery: a spawn that died before writing history leaves the
76
+ * marker set against a conversation that does not contain the block.
77
+ *
78
+ * Best-effort throughout: any failure injects nothing rather than failing the turn.
65
79
  */
66
- export declare function resolveConversationCommission(trackSessionId: string, deps?: {
80
+ export declare function resolveConversationCommission(trackSessionId: string, args?: {
81
+ isFreshSession?: boolean;
82
+ }, deps?: {
67
83
  getSession?: (id: string) => Promise<{
68
84
  commissionId?: string | null;
69
85
  commissionDraft?: string | null;
70
86
  projectId?: string | null;
87
+ commissionBlockFor?: string | null;
71
88
  } | null>;
72
89
  load?: typeof loadCommissionPromptContext;
73
90
  loadDraft?: typeof loadCommissionDraftContext;
91
+ markDelivered?: (sessionId: string, key: string) => Promise<unknown>;
74
92
  enabled?: () => boolean;
75
93
  }): Promise<CommissionPromptContext | null>;
76
94
  /**
@@ -56,29 +56,59 @@ export function resolveConversationProject(args) {
56
56
  return null;
57
57
  return { id: project.id, contextDir: project.contextDir };
58
58
  }
59
+ /** The delivery key for a session's current commission binding, or null outside the mode. Bound
60
+ * wins over drafting: finalize clears the draft, and the two are never both meaningful. */
61
+ export function commissionBindingKey(session) {
62
+ if (session?.commissionId)
63
+ return `active:${session.commissionId}`;
64
+ if (session?.commissionDraft)
65
+ return `draft:${session.commissionDraft}`;
66
+ return null;
67
+ }
59
68
  /**
60
- * Load the [Commission] injection payload for a fresh commission-bound session, or null for
61
- * ordinary sessions. Same first-turn-only economics as USER.md / [Session Project]: resume keeps the
62
- * block in backend history, and mid-run contract edits reach the agent through the checkpoint
63
- * protocol's mandatory re-read, not through re-injection. Best-effort: any failure injects nothing.
69
+ * Load the [Commission] injection payload for this turn, or null when nothing needs delivering.
70
+ *
71
+ * Delivery follows the STATE, not the session's age (DR-0037 v4). v3 injected on the first turn
72
+ * only, on the same economics as USER.md / [Session Project]: resume keeps the block in backend
73
+ * history, so re-sending it every turn is waste. True — but it silently assumed the binding is
74
+ * decided before the first turn, and it is not: a session can enter the mode mid-conversation (the
75
+ * agent calls `cortex_commission_start`, or the user switches it on) and it always binds its
76
+ * contract mid-conversation. Those sessions received the block never. So the marker records WHICH
77
+ * binding was delivered, and a turn injects when the current binding differs from it.
78
+ *
79
+ * `isFreshSession` still forces delivery: a spawn that died before writing history leaves the
80
+ * marker set against a conversation that does not contain the block.
81
+ *
82
+ * Best-effort throughout: any failure injects nothing rather than failing the turn.
64
83
  */
65
- export async function resolveConversationCommission(trackSessionId, deps = {}) {
84
+ export async function resolveConversationCommission(trackSessionId, args = {}, deps = {}) {
66
85
  try {
67
- // Global feature switch (off by default while commission mode is under test). Off means no
68
- // contract block reaches any prompt, matching the tool/skill gate in agent-runner.
86
+ // Global feature switch. Off means no contract block reaches any prompt, matching the skill
87
+ // gate in agent-runner and the refusal in the commission tools.
69
88
  if (!(deps.enabled ?? (() => getSettings().commissionEnabled))())
70
89
  return null;
71
90
  const getSession = deps.getSession ?? ((id) => sessionStore.getById(id));
72
91
  const session = await getSession(trackSessionId);
73
- if (session?.commissionId) {
74
- return await (deps.load ?? loadCommissionPromptContext)(session.commissionId);
75
- }
76
- // A session still drafting its contract has no commission id yet — it is the FIRST session of
77
- // the commission, and the one that most needs to be told what it is here to do.
78
- if (session?.commissionDraft && session.projectId) {
79
- return (deps.loadDraft ?? loadCommissionDraftContext)(session.projectId, session.commissionDraft);
80
- }
81
- return null;
92
+ const key = commissionBindingKey(session ?? null);
93
+ if (!key)
94
+ return null;
95
+ if (!args.isFreshSession && key === session?.commissionBlockFor)
96
+ return null;
97
+ const context = session?.commissionId
98
+ ? await (deps.load ?? loadCommissionPromptContext)(session.commissionId)
99
+ // A session still drafting has no commission id yet — it is the FIRST session of the
100
+ // commission, and the one that most needs to be told what it is here to do.
101
+ : (session?.commissionDraft && session.projectId
102
+ ? (deps.loadDraft ?? loadCommissionDraftContext)(session.projectId, session.commissionDraft)
103
+ : null);
104
+ // Nothing loadable (contract still empty, directory gone) — leave the marker alone so the next
105
+ // turn tries again rather than recording a delivery that never happened.
106
+ if (!context)
107
+ return null;
108
+ const mark = deps.markDelivered
109
+ ?? ((id, value) => sessionStore.markCommissionBlockDelivered(id, value));
110
+ await mark(trackSessionId, key);
111
+ return context;
82
112
  }
83
113
  catch {
84
114
  return null;
@@ -109,9 +139,9 @@ export async function prepareConversationRequest(opts) {
109
139
  // Web UI direct sessions are bound to a project at create time; tell the agent which one
110
140
  // on the session's first turn (see resolveConversationProject for the exact gating).
111
141
  project: resolveConversationProject({ channel: opts.channel, projectId, isFreshSession }),
112
- // Commission-bound sessions additionally get the contract + ledger digest + protocol block
113
- // on their first turn (see resolveConversationCommission).
114
- commission: isFreshSession ? await resolveConversationCommission(sessionId) : null,
142
+ // Commission sessions additionally get the contract + ledger index + protocol block, once per
143
+ // binding rather than once per session (see resolveConversationCommission).
144
+ commission: await resolveConversationCommission(sessionId, { isFreshSession }),
115
145
  });
116
146
  const backendPrompt = buildBackendPrompt(prompt, opts.files);
117
147
  opts.onPromptBuilt?.(backendPrompt);
@@ -158,7 +188,6 @@ export async function prepareConversationRequest(opts) {
158
188
  executionKind: trigger === 'scheduled' ? 'scheduled' : 'local',
159
189
  isUserInitiated: true,
160
190
  commissionMode: opts.commissionMode ?? false,
161
- commissionTools: opts.commissionTools ?? false,
162
191
  scheduleTaskId: opts.scheduleTaskId ?? null,
163
192
  },
164
193
  // The three fields that differ from the shared direct-run policy; every field NOT named here
@@ -4,6 +4,7 @@ import { t } from '../core/i18n.js';
4
4
  import { trackPendingTask } from './busy-tracker.js';
5
5
  import { enqueue } from './conduit-queue.js';
6
6
  import { getSessionAsync } from '../domain/sessions/session.js';
7
+ import { acquireSessionUse } from '../domain/sessions/session-use.js';
7
8
  import { sessionStore, effectiveBackendSessionId } from '../store/session-registry-repo.js';
8
9
  import { conversationLedger } from '../store/conversation-ledger-repo.js';
9
10
  import { getActiveProfile } from '../domain/agents/index.js';
@@ -76,7 +77,7 @@ export async function runRetryAgent({ channel, text, adapter, statusMsg, startTi
76
77
  let lease = null;
77
78
  try {
78
79
  if (sessionId) {
79
- const release = await sessionStore.acquireSessionUse(sessionId);
80
+ const release = await acquireSessionUse(sessionId);
80
81
  if (!release)
81
82
  throw new Error(`Session not found or pending deletion: ${sessionId}`);
82
83
  lease = { release };
@@ -1,5 +1,6 @@
1
1
  import { createLogger } from '../../core/log.js';
2
2
  import { sessionStore, effectiveBackendSessionId } from '../../store/session-registry-repo.js';
3
+ import { acquireSessionUse } from '../../domain/sessions/session-use.js';
3
4
  import { continuationRunRequest } from '../../domain/runs/builders.js';
4
5
  import { getDefaultProfileName } from '../../domain/agents/profile-manager.js';
5
6
  import { resolveRunConfig } from '../../domain/runs/config-resolver.js';
@@ -11,7 +12,7 @@ const log = createLogger('ask-user-resume');
11
12
  export async function resumeAskUserQuestionGroup({ adapter, group, responseText }) {
12
13
  let sessionRelease = null;
13
14
  try {
14
- sessionRelease = await sessionStore.acquireSessionUse(group.sessionId);
15
+ sessionRelease = await acquireSessionUse(group.sessionId);
15
16
  if (!sessionRelease) {
16
17
  log.warn(`AskUserQuestion resume skipped for missing or deleting session: ${group.sessionId}`);
17
18
  return;
@@ -0,0 +1,8 @@
1
+ import type { UpdatePrompt } from '../../domain/system/update-prompt.js';
2
+ /** How long the dialog gets the question to itself before the chat prompt is posted too. */
3
+ export declare const DEFAULT_FALLBACK_MS = 600000;
4
+ export interface UiUpdatePromptOptions {
5
+ /** Override the fallback delay (tests use a few milliseconds). */
6
+ fallbackMs?: number;
7
+ }
8
+ export declare function createUiUpdatePrompt(fallback: UpdatePrompt, opts?: UiUpdatePromptOptions): UpdatePrompt;
@@ -0,0 +1,47 @@
1
+ // input: a fallback UpdatePrompt (the chat-message one from ./update-prompt.js) + domain update state
2
+ // output: createUiUpdatePrompt(fallback, opts?) => UpdatePrompt
3
+ // pos: Dialog-first UpdatePrompt: ask() publishes `prompting` for the SPA's system.updateStatus
4
+ // query and waits for system.applyUpdate / system.skipUpdate. A fallback timer hands the
5
+ // same question to the chat-message prompt so Slack/Feishu/headless users are not stranded.
6
+ import { openServerUpdatePrompt, settleServerUpdatePrompt, } from '../../domain/system/update-ui-state.js';
7
+ import { createLogger } from '../../core/log.js';
8
+ const log = createLogger('ui-update-prompt');
9
+ /** How long the dialog gets the question to itself before the chat prompt is posted too. */
10
+ export const DEFAULT_FALLBACK_MS = 600_000; // 10 min
11
+ export function createUiUpdatePrompt(fallback, opts) {
12
+ const fallbackMs = opts?.fallbackMs ?? DEFAULT_FALLBACK_MS;
13
+ return {
14
+ ask(spec) {
15
+ return new Promise((resolve) => {
16
+ let settled = false;
17
+ let timer;
18
+ // The one place an answer becomes final, whichever side produced it. The loser's
19
+ // answer arrives later (a chat button click has no cancel API — `createUpdatePrompt`
20
+ // only clears its pending state on click or on its own 24h timeout) and is dropped here.
21
+ const finish = (choice) => {
22
+ if (settled)
23
+ return;
24
+ settled = true;
25
+ if (timer !== undefined)
26
+ clearTimeout(timer);
27
+ settleServerUpdatePrompt(choice);
28
+ resolve(choice);
29
+ };
30
+ openServerUpdatePrompt(spec.latestVersion, finish);
31
+ timer = setTimeout(() => {
32
+ if (settled)
33
+ return;
34
+ // Nobody has the SPA open (or nobody looked). Ask again over chat rather than let the
35
+ // update sit behind a dialog no one will ever see.
36
+ void fallback
37
+ .ask(spec)
38
+ .then(finish)
39
+ .catch((e) => {
40
+ log.error(`Chat-message update prompt failed: ${e.message}`);
41
+ });
42
+ }, fallbackMs);
43
+ timer.unref?.();
44
+ });
45
+ },
46
+ };
47
+ }
@@ -7,7 +7,7 @@ import { openThreadRun } from './thread-run/index.js';
7
7
  import { resumeThreadRunInput } from './thread-callback.js';
8
8
  import { trackPendingTask } from './busy-tracker.js';
9
9
  import { threadStore } from '../store/thread-repo.js';
10
- import { sessionStore } from '../store/session-registry-repo.js';
10
+ import { acquireSessionUse } from '../domain/sessions/session-use.js';
11
11
  import { runRegistry } from '../core/run-registry.js';
12
12
  import { createLogger } from '../core/log.js';
13
13
  const log = createLogger('resume-dispatcher');
@@ -33,7 +33,7 @@ function defaultDeps() {
33
33
  getThread: (id) => threadStore.get(id),
34
34
  channelBusy: (ch) => runRegistry.hasChannel(ch),
35
35
  directSessionBusy: (ch) => runRegistry.getByChannel(ch).some(e => !e.threadId),
36
- acquireSessionUse: (sessionId) => sessionStore.acquireSessionUse(sessionId),
36
+ acquireSessionUse: (sessionId) => acquireSessionUse(sessionId),
37
37
  track: trackPendingTask,
38
38
  delay: (ms) => new Promise((r) => setTimeout(r, ms)),
39
39
  };
@@ -12,6 +12,8 @@ import { registerAskQuestion, registerPlanApproval } from './hook-bridge.js';
12
12
  import { normalizeAskLevel } from '../../platform/index.js';
13
13
  import { sessionStore } from '../../store/session-registry-repo.js';
14
14
  import { validateCommissionFinalize, finalizeCommission } from '../../domain/commissions/commission-finalize.js';
15
+ import { enterCommissionDraft } from '../../domain/commissions/commission-draft.js';
16
+ import { publishSessionCommission } from '../session-events.js';
15
17
  import { getCurrentPlanFilePath } from '../../agent-adapter/claude/event-parser.js';
16
18
  import { orchestrationAdapter, orchestrationBus } from '../runtime.js';
17
19
  import { createThread, cancelThread, readArtifact, listTemplates, listAgents, checkSpawnGuards, getRootThreadId, registerChildSpawn, buildThreadTree, getTreeThreads, buildContractPrompt, buildMissionChain, isArtifactUnchangedSinceStepStart } from '../../domain/threads/index.js';
@@ -653,6 +655,51 @@ function createWebhookHandler(_options = {}) {
653
655
  });
654
656
  return;
655
657
  }
658
+ // --- MCP tool: cortex_commission_start ---
659
+ //
660
+ // The tool runs in the bundled MCP process and cannot touch the registry, so entering the mode
661
+ // is a loopback call like every other state change an agent makes. Idempotent: a second call
662
+ // returns the same directory, which is what lets the [Commission] block say "call it if you
663
+ // have not already" without worrying about which entry the session came through.
664
+ if (req.method === 'POST' && req.url === '/hook/commission-start') {
665
+ readJsonBody(req, async (error, _body, data) => {
666
+ if (error) {
667
+ res.writeHead(400);
668
+ res.end('Bad JSON');
669
+ return;
670
+ }
671
+ const reply = (status, payload) => {
672
+ res.writeHead(status, { 'Content-Type': 'application/json' });
673
+ res.end(JSON.stringify(payload));
674
+ };
675
+ const sessionId = typeof data?.sessionId === 'string' ? data.sessionId : '';
676
+ if (!sessionId) {
677
+ reply(200, { error: 'no originating session id — commission start requires CORTEX_SESSION_ID' });
678
+ return;
679
+ }
680
+ // The kill switch has to bite HERE too: since v4 this tool is the entry point, not a
681
+ // capability handed only to sessions the user already opted in.
682
+ if (!getSettings().commissionEnabled) {
683
+ reply(200, { error: 'commission mode is disabled on this server (settings.commissionEnabled)' });
684
+ return;
685
+ }
686
+ try {
687
+ const result = await enterCommissionDraft(sessionId);
688
+ if (result.ok === false) {
689
+ reply(200, { error: result.error });
690
+ return;
691
+ }
692
+ if (!result.alreadyDrafting && typeof data?.channel === 'string' && data.channel) {
693
+ publishSessionCommission({ sessionId, channel: data.channel });
694
+ }
695
+ reply(200, { ok: true, dir: result.dir, draftDir: result.draftDir, alreadyDrafting: result.alreadyDrafting });
696
+ }
697
+ catch (e) {
698
+ reply(500, { error: e.message });
699
+ }
700
+ });
701
+ return;
702
+ }
656
703
  // --- PreToolUse hook: ExitPlanMode ---
657
704
  if (req.method === 'POST' && req.url === '/hook/exit-plan-mode') {
658
705
  readJsonBody(req, async (error, _body, data) => {
@@ -27,6 +27,9 @@ export interface CompactSessionDeps {
27
27
  sessions: {
28
28
  getById(sessionId: string): Promise<CompactSessionRecord | null>;
29
29
  updateContextUsage(sessionId: string, usage: SessionContextUsage | null): Promise<void>;
30
+ /** Compaction removes the already-delivered [Commission] block from backend history, so the
31
+ * delivery marker has to go with it or the block is never seen again (DR-0037 v4). */
32
+ clearCommissionBlockDelivery(sessionId: string): Promise<unknown>;
30
33
  };
31
34
  /** The registry's one answer to "may a command touch this session's pooled engine": see
32
35
  * `core/session-state.ts`'s `channelEngineBusy`. */
@@ -1,5 +1,5 @@
1
1
  import { channelEngineBusy } from '../core/session-state.js';
2
- import { sessionRepo } from '../store/session-repo.js';
2
+ import { getSessionAsync } from '../domain/sessions/session.js';
3
3
  import { effectiveBackendSessionId, sessionStore, } from '../store/session-registry-repo.js';
4
4
  import { compactAgentContext, isSessionCompactionSupported, } from '../domain/runs/compact.js';
5
5
  import { resolveBackendForChannel } from '../domain/agents/config.js';
@@ -39,6 +39,7 @@ async function applyCompactResult(session, result, deps) {
39
39
  ? { ...result.contextUsage, updatedAt: deps.now() }
40
40
  : null;
41
41
  await deps.sessions.updateContextUsage(session.sessionId, contextUsage);
42
+ await deps.sessions.clearCommissionBlockDelivery(session.sessionId);
42
43
  deps.publish({
43
44
  sessionId: session.sessionId,
44
45
  channel: session.channel,
@@ -49,7 +50,7 @@ async function applyCompactResult(session, result, deps) {
49
50
  }
50
51
  export async function compactActiveSessionContext(opts) {
51
52
  const backend = resolveBackendForChannel(opts.channel);
52
- const sessionId = await sessionRepo.getSessionAsync(opts.channel);
53
+ const sessionId = await getSessionAsync(opts.channel);
53
54
  if (!sessionId)
54
55
  return { ok: false, reason: 'no-session' };
55
56
  return compactSessionContext(sessionId);
@@ -135,6 +135,12 @@ export declare function publishSessionRewound(p: {
135
135
  * the model. The web hold (turn/background-hold.ts) keeps `running:true, backgroundRunning:true` for the
136
136
  * whole wait so the session is NOT prematurely marked idle, then publishes `running:false` once the
137
137
  * background work finishes. Omitted (undefined) on the normal turn-start / turn-end edges. */
138
+ /** The session's commission binding moved (entered drafting, left it) without any commission
139
+ * record changing, so `commission.updated` would have nothing to name. */
140
+ export declare function publishSessionCommission(p: {
141
+ sessionId: string;
142
+ channel: string;
143
+ }): void;
138
144
  export declare function publishSessionStatus(p: {
139
145
  sessionId: string;
140
146
  channel: string;
@@ -113,6 +113,11 @@ export function publishSessionRewound(p) {
113
113
  * the model. The web hold (turn/background-hold.ts) keeps `running:true, backgroundRunning:true` for the
114
114
  * whole wait so the session is NOT prematurely marked idle, then publishes `running:false` once the
115
115
  * background work finishes. Omitted (undefined) on the normal turn-start / turn-end edges. */
116
+ /** The session's commission binding moved (entered drafting, left it) without any commission
117
+ * record changing, so `commission.updated` would have nothing to name. */
118
+ export function publishSessionCommission(p) {
119
+ orchestrationBus()?.publish({ type: 'session.commission', sessionId: p.sessionId, channel: p.channel });
120
+ }
116
121
  export function publishSessionStatus(p) {
117
122
  orchestrationBus()?.publish({
118
123
  type: 'session.status',
@@ -17,6 +17,7 @@ import { sessionStore } from '../../store/session-registry-repo.js';
17
17
  import { getActiveProfile, getDefaultAgent, resolveBackendForChannel } from '../../domain/agents/index.js';
18
18
  import { resolveProfileConfig } from '../../domain/agents/profile-manager.js';
19
19
  import { registerNamedSession } from '../../domain/sessions/session-lifecycle.js';
20
+ import { acquireSessionUse } from '../../domain/sessions/session-use.js';
20
21
  import { getAgent } from '../../domain/threads/index.js';
21
22
  import { acquireBrowser, releaseBrowser, backendSupportsBrowser, BROWSER_DEVICE_SERVER } from '../../platform/browser/managed-browser.js';
22
23
  import { acquireDeviceBrowser, releaseDeviceBrowser } from '../../domain/remote/device-browser.js';
@@ -27,7 +28,7 @@ export async function acquireSessionUseLease(sessionId) {
27
28
  const session = await sessionStore.getById(sessionId);
28
29
  if (!session)
29
30
  return null;
30
- const release = await sessionStore.acquireSessionUse(sessionId);
31
+ const release = await acquireSessionUse(sessionId);
31
32
  if (!release)
32
33
  return null;
33
34
  return { session, release };
@@ -45,6 +45,17 @@ export declare function parseAppAssetName(name: string): {
45
45
  */
46
46
  export declare function buildAppUpdateManifest(releases: GhRelease[], serverVersion: string): AppUpdateManifest | null;
47
47
  export interface AppUpdateRouteOptions {
48
+ /**
49
+ * When true the route serves `{}` unconditionally, which the shell reads as "no update".
50
+ *
51
+ * A server running out of a source checkout (`CORTEX_REPO`) is a development install whose
52
+ * version bears no relation to any published release, and the shell caps itself at OUR version —
53
+ * so advertising releases from here would either offer nothing or offer the wrong thing, and with
54
+ * silent updating on it would do so without asking. Same rule the npm self-update path applies
55
+ * (domain/system/server-update-check.ts), decided by the caller because the platform layer may
56
+ * not import from domain.
57
+ */
58
+ devMode?: boolean;
48
59
  serverVersion?: string;
49
60
  fetchReleases?: () => Promise<GhRelease[]>;
50
61
  ttlMs?: number;
@@ -112,12 +112,15 @@ async function defaultFetchReleases() {
112
112
  */
113
113
  export function createAppUpdateRoutes(opts = {}) {
114
114
  const serverVersion = opts.serverVersion ?? CORTEX_VERSION;
115
+ const devMode = opts.devMode ?? false;
115
116
  const fetchReleases = opts.fetchReleases ?? defaultFetchReleases;
116
117
  const ttlMs = opts.ttlMs ?? DEFAULT_TTL_MS;
117
118
  const now = opts.now ?? Date.now;
118
119
  let lastGood = null;
119
120
  let fetchedAt = null;
120
121
  const manifest = async () => {
122
+ if (devMode)
123
+ return null;
121
124
  if (fetchedAt !== null && now() - fetchedAt < ttlMs)
122
125
  return lastGood;
123
126
  fetchedAt = now();
@@ -1,16 +1,8 @@
1
- export type TurnStatus = 'processing' | 'completed' | 'superseded';
2
- export interface LedgerTurn {
3
- turnIndex: number;
4
- userMessageTs: string;
5
- userMessageText: string;
6
- statusMessageTs: string | null;
7
- responseMessageTimestamps: string[];
8
- executionId: string | null;
9
- backupPath: string | null;
10
- status: TurnStatus;
11
- createdAt: string;
12
- updatedAt: string;
13
- }
1
+ import { type SessionRegistryRepo } from './session-registry-repo.js';
2
+ import type { TurnRecord, TurnStatus } from './session-registry-journal.js';
3
+ export type { TurnStatus };
4
+ /** The ledger's turn IS the registry's turn record — one definition, no drift. */
5
+ export type LedgerTurn = TurnRecord;
14
6
  export interface ChannelConversation {
15
7
  sessionId: string | null;
16
8
  sessionName: string | null;
@@ -23,8 +15,8 @@ export interface ChannelConversation {
23
15
  }
24
16
  export type LedgerData = Record<string, ChannelConversation>;
25
17
  export declare class ConversationLedgerRepo {
26
- private repo;
27
- constructor(filePath?: string);
18
+ private readonly registry;
19
+ constructor(registry?: SessionRegistryRepo);
28
20
  getConversation(channel: string): Promise<ChannelConversation | null>;
29
21
  findTurn(channel: string, userMessageTs: string): Promise<{
30
22
  conversation: ChannelConversation;
@@ -58,7 +50,6 @@ export declare class ConversationLedgerRepo {
58
50
  channel: string;
59
51
  }>>;
60
52
  clearBySessionIds(sessionIds: Iterable<string>): Promise<number>;
61
- deleteExceptSessionIds(sessionIds: Iterable<string>): Promise<number>;
62
53
  switchSession(channel: string, opts: {
63
54
  sessionId: string;
64
55
  sessionName: string | null;
@@ -66,7 +57,7 @@ export declare class ConversationLedgerRepo {
66
57
  profileName?: string | null;
67
58
  }): Promise<void>;
68
59
  /**
69
- * Atomic init-if-missing + beginTurn. Captures the turn index under mutex
60
+ * Atomic init-if-missing + beginTurn. Captures the turn index under one lock
70
61
  * so callers can safely pass it to sessionBackup.createBackup.
71
62
  * Returns { turn, turnIndex } for the caller.
72
63
  */
@@ -84,9 +75,9 @@ export declare class ConversationLedgerRepo {
84
75
  }>;
85
76
  /** Set the backup path on the turn identified by userMessageTs. */
86
77
  setBackupPath(channel: string, userMessageTs: string, backupPath: string | null): Promise<void>;
87
- /** Drop the in-memory cache so the next read() fetches from disk. For testing. */
78
+ /** Drop the registry's in-memory cache so the next read fetches from disk. For testing. */
88
79
  invalidate(): void;
89
- /** Wait for any in-flight mutate() to complete. For graceful SIGTERM drain. */
80
+ /** Wait for any in-flight registry mutation to complete. For graceful SIGTERM drain. */
90
81
  flush(): Promise<void>;
91
82
  }
92
83
  export declare const conversationLedger: ConversationLedgerRepo;