@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.
- package/defaults/plugins/cortex-commission/.claude-plugin/plugin.json +2 -2
- package/defaults/plugins/cortex-commission/plugin.json +2 -2
- package/defaults/plugins/cortex-commission/skills/commission/SKILL.md +3 -3
- package/dist/agent-adapter/claude/adapter.d.ts +0 -6
- package/dist/agent-adapter/claude/adapter.js +0 -8
- package/dist/agent-adapter/claude/defaults.d.ts +10 -7
- package/dist/agent-adapter/claude/defaults.js +18 -16
- package/dist/agent-adapter/claude/spawn-args.d.ts +0 -3
- package/dist/agent-adapter/claude/spawn-args.js +16 -16
- package/dist/agent-adapter/pi/mcp-bridge-logic.d.ts +11 -2
- package/dist/agent-adapter/pi/mcp-bridge-logic.js +32 -1
- package/dist/agent-adapter/pi/mcp-bridge.js +16 -15
- package/dist/agent-adapter/pi/session-options.d.ts +0 -6
- package/dist/agent-adapter/pi/session-options.js +1 -8
- package/dist/agent-adapter/types.d.ts +0 -1
- package/dist/core/mcp-tool-gate.d.ts +3 -17
- package/dist/core/mcp-tool-gate.js +3 -19
- package/dist/core/settings-spec.d.ts +1 -1
- package/dist/core/settings-spec.js +5 -1
- package/dist/domain/agents/config.d.ts +1 -1
- package/dist/domain/agents/config.js +1 -1
- package/dist/domain/agents/profile-switch.d.ts +1 -1
- package/dist/domain/agents/profile-switch.js +3 -5
- package/dist/domain/agents/subagent/runner.js +0 -1
- package/dist/domain/commissions/commission-draft.d.ts +58 -0
- package/dist/domain/commissions/commission-draft.js +87 -4
- package/dist/domain/commissions/commission-finalize.d.ts +8 -3
- package/dist/domain/commissions/commission-finalize.js +14 -0
- package/dist/domain/mcp/tools/commission-tools.d.ts +12 -1
- package/dist/domain/mcp/tools/commission-tools.js +68 -14
- package/dist/domain/remote/client-manager.js +66 -7
- package/dist/domain/remote/client-ssh-tunnel.d.ts +16 -5
- package/dist/domain/remote/client-ssh-tunnel.js +12 -5
- package/dist/domain/runs/builders.js +0 -1
- package/dist/domain/runs/compact.js +0 -1
- package/dist/domain/runs/engine-spec.d.ts +11 -4
- package/dist/domain/runs/engine-spec.js +7 -4
- package/dist/domain/runs/prompt.js +16 -10
- package/dist/domain/runs/request.d.ts +0 -1
- package/dist/domain/sessions/session-hooks.d.ts +5 -12
- package/dist/domain/sessions/session-hooks.js +6 -13
- package/dist/domain/sessions/session-lifecycle.d.ts +4 -4
- package/dist/domain/sessions/session-lifecycle.js +5 -6
- package/dist/domain/sessions/session-retention.d.ts +1 -3
- package/dist/domain/sessions/session-retention.js +9 -26
- package/dist/domain/sessions/session-use.d.ts +32 -0
- package/dist/domain/sessions/session-use.js +63 -0
- package/dist/domain/sessions/session.js +6 -5
- package/dist/domain/system/server-update-check.js +29 -1
- package/dist/domain/system/update-ui-state.d.ts +32 -0
- package/dist/domain/system/update-ui-state.js +63 -0
- package/dist/domain/threads/runner.js +0 -1
- package/dist/domain/ui-service/app-router.d.ts +30 -0
- package/dist/domain/ui-service/app-router.js +5 -1
- package/dist/domain/ui-service/input-schemas.d.ts +32 -0
- package/dist/domain/ui-service/input-schemas.js +22 -0
- package/dist/domain/ui-service/mutate/sessions.d.ts +13 -1
- package/dist/domain/ui-service/mutate/sessions.js +69 -3
- package/dist/domain/ui-service/mutate/system.d.ts +3 -1
- package/dist/domain/ui-service/mutate/system.js +13 -0
- package/dist/domain/ui-service/query/system.d.ts +2 -1
- package/dist/domain/ui-service/query/system.js +4 -0
- package/dist/domain/ui-service/types.d.ts +44 -3
- package/dist/domain/ui-service/ui-service.js +7 -3
- package/dist/entry/app.js +11 -23
- package/dist/entry/start-ui-http.js +3 -1
- package/dist/events/event-types.d.ts +5 -0
- package/dist/orchestration/agent-runner.d.ts +1 -1
- package/dist/orchestration/agent-runner.js +8 -11
- package/dist/orchestration/conversation-request.d.ts +26 -8
- package/dist/orchestration/conversation-request.js +49 -20
- package/dist/orchestration/edit-retry.js +2 -1
- package/dist/orchestration/interactions/ask-user-resume.js +2 -1
- package/dist/orchestration/interactions/ui-update-prompt.d.ts +8 -0
- package/dist/orchestration/interactions/ui-update-prompt.js +47 -0
- package/dist/orchestration/resume-dispatcher.js +2 -2
- package/dist/orchestration/routing/webhook.js +47 -0
- package/dist/orchestration/session-compact.d.ts +3 -0
- package/dist/orchestration/session-compact.js +3 -2
- package/dist/orchestration/session-events.d.ts +6 -0
- package/dist/orchestration/session-events.js +5 -0
- package/dist/orchestration/turn/turn-prep.js +2 -1
- package/dist/platform/ui-http/app-update.d.ts +11 -0
- package/dist/platform/ui-http/app-update.js +3 -0
- package/dist/store/conversation-ledger-repo.d.ts +10 -19
- package/dist/store/conversation-ledger-repo.js +143 -152
- package/dist/store/session-registry-import.d.ts +34 -0
- package/dist/store/session-registry-import.js +182 -0
- package/dist/store/session-registry-journal.d.ts +107 -0
- package/dist/store/session-registry-journal.js +307 -18
- package/dist/store/session-registry-repo.d.ts +113 -28
- package/dist/store/session-registry-repo.js +287 -104
- package/dist/store/version-migrations.d.ts +16 -0
- package/dist/store/version-migrations.js +34 -0
- package/package.json +1 -1
- package/web/dist/assets/{index-aHbOZSP6.js → index-CEZ0DSei.js} +1 -1
- package/web/dist/assets/{index-CCPxQ94C.css → index-CRDJo39X.css} +1 -1
- package/web/dist/assets/index-DjuPJVZE.js +444 -0
- package/web/dist/index.html +2 -2
- package/dist/store/session-repo.d.ts +0 -65
- package/dist/store/session-repo.js +0 -184
- package/web/dist/assets/index-BuXbCsuz.js +0 -444
|
@@ -81,19 +81,25 @@ const COMMISSION_PROTOCOL = `Commission protocol:
|
|
|
81
81
|
2. Completion claims need evidence pointers (file paths, command outputs, EXP ids) in ledger.md. Scope cuts and deferrals go in the plan section's "Cuts and deferrals" note.
|
|
82
82
|
3. Before this session ends, and at each stage boundary, append a checkpoint CP-N to ledger.md with three diffs — plan vs done, contract vs current direction, assumptions vs reality — graded ok / attention / gate. Re-read contract.md (including its Revisions section) before writing it.
|
|
83
83
|
4. Contract gates are blocking: ask the user and wait. A streak of approvals never downgrades a gate.`;
|
|
84
|
-
/** A session
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
84
|
+
/** A session drafting a contract. It has no contract and no ledger yet, so the block's whole job is
|
|
85
|
+
* to say so and hand the agent to cortex_commission_start, which carries the drill protocol.
|
|
86
|
+
*
|
|
87
|
+
* Two ways in since v4 — the agent called the tool itself, or the user switched the mode on for a
|
|
88
|
+
* session already in flight — and the block cannot tell which. It does not need to: the tool is
|
|
89
|
+
* idempotent, so "call it if you have not already" is correct either way, and the second sentence
|
|
90
|
+
* keeps a user-initiated entry from turning into a round of asking whether to proceed. */
|
|
88
91
|
function buildDraftCommissionBlock(c) {
|
|
89
92
|
return [
|
|
90
|
-
'[Commission] This session
|
|
91
|
-
+ '
|
|
92
|
-
`Draft directory
|
|
93
|
+
'[Commission] This session is drafting a commission contract: a long task anchored by a '
|
|
94
|
+
+ 'contract the user approves before any work begins.',
|
|
95
|
+
`Draft directory: ${c.dir}`,
|
|
93
96
|
'',
|
|
94
|
-
'
|
|
95
|
-
+ '
|
|
96
|
-
+ '
|
|
97
|
+
'If you have not already received the creation protocol in this session, call '
|
|
98
|
+
+ 'cortex_commission_start now, before investigating or asking anything — it carries the drill '
|
|
99
|
+
+ 'protocol and the contract structure, and is idempotent. If the user turned this mode on for '
|
|
100
|
+
+ 'you, that is the decision made: start drilling rather than asking whether to.',
|
|
101
|
+
'Implement nothing until the contract is approved through cortex_commission_submit. If you '
|
|
102
|
+
+ 'conclude the task does not warrant a commission, say so plainly and let the user close it.',
|
|
97
103
|
].join('\n');
|
|
98
104
|
}
|
|
99
105
|
/** Index, not snapshot: the block names the two files and tells the agent to read them. Their
|
|
@@ -82,23 +82,16 @@ export interface SessionHookSpec {
|
|
|
82
82
|
/** Run configured session subscribers and preserve the display/injection pipeline. */
|
|
83
83
|
export declare function runSessionHook(spec: SessionHookSpec, stream: OutputStream, deps?: InjectDeps): Promise<void>;
|
|
84
84
|
/** Resolve the profile name to use when injecting the onNew hook's stdout as a fresh
|
|
85
|
-
* agent turn.
|
|
86
|
-
*
|
|
87
|
-
*
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
* The two sources can disagree on a channel that hosts both kinds of session — e.g.
|
|
92
|
-
* a thread session running profile `deepseek-pro` while the user's main conversation
|
|
93
|
-
* is on profile `plan`. Reading from the ledger alone causes Cortex to resume the
|
|
94
|
-
* thread session with the wrong profile, which routes through the wrong gateway mode
|
|
95
|
-
* and triggers Anthropic's "Invalid signature in thinking block" 400.
|
|
85
|
+
* agent turn. The session registry is the SINGLE source of truth (B.T2): the per-session
|
|
86
|
+
* record carries the profileName, correct for both user-conversation and thread-spawned
|
|
87
|
+
* sessions. The old channel-level conversation-ledger fallback is gone — it could disagree
|
|
88
|
+
* with the registry on a channel hosting both kinds of session and resume with the wrong
|
|
89
|
+
* profile (routing through the wrong gateway mode → Anthropic 400 on thinking blocks).
|
|
96
90
|
*
|
|
97
91
|
* Exported (rather than inlined) so the priority logic is unit-testable in isolation
|
|
98
92
|
* without spinning up the real repo singletons. */
|
|
99
93
|
export interface ProfileLookupDeps {
|
|
100
94
|
lookupRegistryProfile: (sessionId: string) => Promise<string | null>;
|
|
101
|
-
lookupLedgerProfile: (channel: string) => Promise<string | null>;
|
|
102
95
|
}
|
|
103
96
|
export declare function resolveOnNewProfileName(channel: string, sessionId: string, deps: ProfileLookupDeps): Promise<string | null>;
|
|
104
97
|
/** Fire-and-forget onNew hook used by the !new command and the "New" status button.
|
|
@@ -249,10 +249,7 @@ async function resolveOnNewThreadAnchor(channel, threadAnchorId) {
|
|
|
249
249
|
return null;
|
|
250
250
|
}
|
|
251
251
|
export async function resolveOnNewProfileName(channel, sessionId, deps) {
|
|
252
|
-
|
|
253
|
-
if (fromRegistry)
|
|
254
|
-
return fromRegistry;
|
|
255
|
-
return deps.lookupLedgerProfile(channel);
|
|
252
|
+
return deps.lookupRegistryProfile(sessionId);
|
|
256
253
|
}
|
|
257
254
|
/** Default binding of the registry lookup — composes lookupBySessionId + lookupSession.
|
|
258
255
|
* Extracted so prepareOnNewRun's call site stays one line and tests can swap in fakes. */
|
|
@@ -263,10 +260,6 @@ async function defaultLookupRegistryProfile(sessionId) {
|
|
|
263
260
|
const record = await sessionStore.lookupSession(name);
|
|
264
261
|
return record?.profileName ?? null;
|
|
265
262
|
}
|
|
266
|
-
async function defaultLookupLedgerProfile(channel) {
|
|
267
|
-
const conv = await conversationLedger.getConversation(channel);
|
|
268
|
-
return conv?.profileName ?? null;
|
|
269
|
-
}
|
|
270
263
|
/** Build the onNew SessionHookSpec + a fresh stream. Returns null when the hook isn't
|
|
271
264
|
* configured or there's no live session to capture context from. */
|
|
272
265
|
async function prepareOnNewRun(channel, adapter, threadAnchorId) {
|
|
@@ -279,11 +272,9 @@ async function prepareOnNewRun(channel, adapter, threadAnchorId) {
|
|
|
279
272
|
return null;
|
|
280
273
|
}
|
|
281
274
|
const sessionName = (await sessionStore.lookupBySessionId(sessionId)) || sessionId.slice(0, 8);
|
|
282
|
-
//
|
|
283
|
-
// Registry is the per-session truth; ledger is the channel-level fallback.
|
|
275
|
+
// Registry is the single source of truth for the per-session profileName.
|
|
284
276
|
const profileName = await resolveOnNewProfileName(channel, sessionId, {
|
|
285
277
|
lookupRegistryProfile: defaultLookupRegistryProfile,
|
|
286
|
-
lookupLedgerProfile: defaultLookupLedgerProfile,
|
|
287
278
|
});
|
|
288
279
|
const anchor = await resolveOnNewThreadAnchor(channel, threadAnchorId);
|
|
289
280
|
const stream = adapter.openOutputStream({ type: 'interactive-reply', conduit: channel, sessionId: '' }, { threadId: anchor });
|
|
@@ -358,13 +349,15 @@ export async function runMessageEndForTurn(args) {
|
|
|
358
349
|
return;
|
|
359
350
|
}
|
|
360
351
|
try {
|
|
361
|
-
|
|
352
|
+
// Profile comes from the session registry (the single source of truth), keyed by the turn's
|
|
353
|
+
// sessionId — never from the channel-level ledger, which could name a different session.
|
|
354
|
+
const profile = await defaultLookupRegistryProfile(args.sessionId);
|
|
362
355
|
await runMessageEndSessionHook({
|
|
363
356
|
channel: args.channel,
|
|
364
357
|
sessionId: args.sessionId,
|
|
365
358
|
sessionName: args.sessionName ?? '',
|
|
366
359
|
executionId: args.executionId ?? '',
|
|
367
|
-
profile
|
|
360
|
+
profile,
|
|
368
361
|
stream: args.stream,
|
|
369
362
|
});
|
|
370
363
|
}
|
|
@@ -46,7 +46,7 @@ export interface RegisterNamedSessionOpts {
|
|
|
46
46
|
export declare function registerNamedSession(store: SessionRegistryWriter, opts: RegisterNamedSessionOpts): Promise<string>;
|
|
47
47
|
export interface CreateDirectSessionDeps {
|
|
48
48
|
sessionStore: SessionRegistryWriter;
|
|
49
|
-
/**
|
|
49
|
+
/** Bind the channel to the new session in the registry (so a later send resumes it). */
|
|
50
50
|
setChannelSession(channel: string, sessionId: string, backend: string): Promise<void>;
|
|
51
51
|
/** Initialize the conversation ledger for the new channel/session. */
|
|
52
52
|
initConversation(channel: string, opts: {
|
|
@@ -90,8 +90,8 @@ export interface AttachExistingSessionOpts {
|
|
|
90
90
|
backend: string;
|
|
91
91
|
profileName?: string | null;
|
|
92
92
|
}
|
|
93
|
-
/** Attach a channel to an existing session: restore its profile (if any),
|
|
94
|
-
* and switch the conversation ledger. Mirrors the !resume switch sequence. */
|
|
93
|
+
/** Attach a channel to an existing session: restore its profile (if any), bind the channel to it in
|
|
94
|
+
* the registry, and switch the conversation ledger. Mirrors the !resume switch sequence. */
|
|
95
95
|
export declare function attachExistingSession(channel: string, opts: AttachExistingSessionOpts): Promise<void>;
|
|
96
96
|
export interface AdoptScheduledSessionStore {
|
|
97
97
|
getById(sessionId: string): Promise<{
|
|
@@ -115,6 +115,6 @@ export interface AdoptScheduledSessionStore {
|
|
|
115
115
|
export declare function adoptScheduledSession(store: AdoptScheduledSessionStore, sessionId: string): Promise<{
|
|
116
116
|
channel: string;
|
|
117
117
|
} | null>;
|
|
118
|
-
/** Clear a channel's session state:
|
|
118
|
+
/** Clear a channel's session state: unbind the channel in the registry, clean session
|
|
119
119
|
* backups, and clear the conversation ledger. Mirrors the store-level half of !new. */
|
|
120
120
|
export declare function resetChannelSession(channel: string): Promise<void>;
|
|
@@ -71,7 +71,7 @@ export async function createDirectSession(deps, opts) {
|
|
|
71
71
|
mode: opts.selection.mode ?? null,
|
|
72
72
|
});
|
|
73
73
|
}
|
|
74
|
-
//
|
|
74
|
+
// settings.commissionEnabled is the feature's kill switch (on by default since DR-0037 v4).
|
|
75
75
|
// Refuse here rather than downgrade: a caller that asked for a commission and silently got an
|
|
76
76
|
// ordinary session would only discover it much later. This is the server-side backstop for every
|
|
77
77
|
// create path; the UI hides the opt-in and the ui-service handlers reject earlier with a 400.
|
|
@@ -94,8 +94,8 @@ export async function createDirectSession(deps, opts) {
|
|
|
94
94
|
await deps.initConversation(channel, { sessionId, sessionName, backend });
|
|
95
95
|
return { sessionId, sessionName, channel };
|
|
96
96
|
}
|
|
97
|
-
/** Attach a channel to an existing session: restore its profile (if any),
|
|
98
|
-
* and switch the conversation ledger. Mirrors the !resume switch sequence. */
|
|
97
|
+
/** Attach a channel to an existing session: restore its profile (if any), bind the channel to it in
|
|
98
|
+
* the registry, and switch the conversation ledger. Mirrors the !resume switch sequence. */
|
|
99
99
|
export async function attachExistingSession(channel, opts) {
|
|
100
100
|
if (opts.profileName)
|
|
101
101
|
setActiveProfile(opts.profileName, channel);
|
|
@@ -123,7 +123,7 @@ export async function adoptScheduledSession(store, sessionId) {
|
|
|
123
123
|
await store.convertToDirect(sessionId, { channel });
|
|
124
124
|
return { channel };
|
|
125
125
|
}
|
|
126
|
-
/** Clear a channel's session state:
|
|
126
|
+
/** Clear a channel's session state: unbind the channel in the registry, clean session
|
|
127
127
|
* backups, and clear the conversation ledger. Mirrors the store-level half of !new. */
|
|
128
128
|
export async function resetChannelSession(channel) {
|
|
129
129
|
const conv = await conversationLedger.getConversation(channel);
|
|
@@ -131,7 +131,6 @@ export async function resetChannelSession(channel) {
|
|
|
131
131
|
sessionBackup.cleanupAllBackups(conv.sessionId);
|
|
132
132
|
await conversationLedger.clearConversation(channel);
|
|
133
133
|
}
|
|
134
|
-
// One channel, one binding: `deleteSessionAsync`
|
|
135
|
-
// backend-prefixed form of it, so the per-backend fan-out is gone.
|
|
134
|
+
// One channel, one binding: `deleteSessionAsync` unbinds the channel in the registry.
|
|
136
135
|
await deleteSessionAsync(channel).catch(() => { });
|
|
137
136
|
}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { type SessionRegistryRepo } from '../../store/session-registry-repo.js';
|
|
2
|
-
import type { SessionRepo } from '../../store/session-repo.js';
|
|
3
2
|
import type { ConversationLedgerRepo } from '../../store/conversation-ledger-repo.js';
|
|
4
3
|
import type { ConversationHistoryRepo } from '../../store/conversation-history-repo.js';
|
|
5
4
|
import type { RetentionCandidateRepo } from '../../store/retention-candidate-repo.js';
|
|
@@ -21,8 +20,7 @@ export interface SessionRetentionDeps {
|
|
|
21
20
|
retentionDays: number;
|
|
22
21
|
now?: () => number;
|
|
23
22
|
registry: SessionRegistryRepo;
|
|
24
|
-
|
|
25
|
-
ledgerRepo: Pick<ConversationLedgerRepo, 'listBySessionIds' | 'clearBySessionIds' | 'deleteExceptSessionIds'>;
|
|
23
|
+
ledgerRepo: Pick<ConversationLedgerRepo, 'clearBySessionIds'>;
|
|
26
24
|
historyRepo: Pick<ConversationHistoryRepo, 'clearBySessionIds'>;
|
|
27
25
|
/** Per-session cumulative stats carried over from archived executions. Optional so existing
|
|
28
26
|
* callers and fixtures keep working; absent ⇒ the carry is simply not pruned. */
|
|
@@ -4,6 +4,7 @@ import { createLogger } from '../../core/log.js';
|
|
|
4
4
|
import { parsePISessionFilename } from '../../core/pi-session-filename.js';
|
|
5
5
|
import { effectiveBackendSessionId } from '../../store/session-registry-repo.js';
|
|
6
6
|
import { sessionTotalsCarry } from '../../store/session-totals-repo.js';
|
|
7
|
+
import { activeSessionUseIds } from '../sessions/session-use.js';
|
|
7
8
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
8
9
|
const CAPTURE_PREFIX = 'claude-output-';
|
|
9
10
|
const log = createLogger('session-retention');
|
|
@@ -13,16 +14,16 @@ export async function runSessionRetentionSweep(deps) {
|
|
|
13
14
|
const cutoffMs = now() - deps.retentionDays * DAY_MS;
|
|
14
15
|
const helper = await safeClaudeSync(deps, errors);
|
|
15
16
|
const committed = await retryPendingDeletes(deps, errors);
|
|
16
|
-
|
|
17
|
+
// This is the ONE place that must protect in-use sessions: the store's `beginDeleteExpired` no
|
|
18
|
+
// longer keeps a use counter, so the runtime lease set (`@domain/sessions/session-use.ts`) is
|
|
19
|
+
// unioned into the protected ids here before any delete-intent is written.
|
|
20
|
+
const protectedTracks = new Set([...deps.liveness.protectedTrackSessionIds, ...activeSessionUseIds()]);
|
|
17
21
|
const pending = await safeRegistryBeginDeleteExpired(deps, cutoffMs, protectedTracks, errors);
|
|
18
22
|
const newlyCommitted = await commitDeletes(deps, pending, errors);
|
|
19
23
|
const registryCommitted = committed + newlyCommitted;
|
|
20
24
|
const live = await safeRegistryListRecentSessions(deps, errors);
|
|
21
25
|
const stillPending = await safeRegistryListPendingDeletions(deps, errors);
|
|
22
26
|
const registryReadable = live.ok && stillPending.ok;
|
|
23
|
-
if (registryReadable) {
|
|
24
|
-
await repairDanglingReferences(deps, live.value, stillPending.value, errors);
|
|
25
|
-
}
|
|
26
27
|
const protectedBackendIds = new Set(deps.liveness.protectedBackendSessionIds);
|
|
27
28
|
const historyOrphanDeleted = registryReadable
|
|
28
29
|
? await deleteHistoryOrphans(deps, live.value, stillPending.value, cutoffMs, errors)
|
|
@@ -56,7 +57,7 @@ async function safeClaudeSync(deps, errors) {
|
|
|
56
57
|
}
|
|
57
58
|
async function safeRegistryBeginDeleteExpired(deps, cutoffMs, protectedTracks, errors) {
|
|
58
59
|
try {
|
|
59
|
-
return await deps.registry.beginDeleteExpired(cutoffMs, protectedTracks, session => prepareDeleteCleanup(deps, session));
|
|
60
|
+
return await deps.registry.beginDeleteExpired(cutoffMs, protectedTracks, (session, turns) => prepareDeleteCleanup(deps, session, turns));
|
|
60
61
|
}
|
|
61
62
|
catch (error) {
|
|
62
63
|
errors.push(`registry.beginDeleteExpired: ${error.message}`);
|
|
@@ -95,14 +96,13 @@ async function commitDeletes(deps, entries, errors) {
|
|
|
95
96
|
}
|
|
96
97
|
return committed;
|
|
97
98
|
}
|
|
98
|
-
async function prepareDeleteCleanup(deps, session) {
|
|
99
|
+
async function prepareDeleteCleanup(deps, session, turns) {
|
|
99
100
|
if (session.backend !== 'claude')
|
|
100
101
|
return { claudeBackupPaths: [] };
|
|
101
102
|
const backendId = effectiveBackendSessionId(session);
|
|
102
103
|
if (!backendId)
|
|
103
104
|
return { claudeBackupPaths: [] };
|
|
104
|
-
const
|
|
105
|
-
const candidates = ledgerRows.flatMap(row => row.turns.map(turn => turn.backupPath));
|
|
105
|
+
const candidates = turns.map(turn => turn.backupPath);
|
|
106
106
|
return {
|
|
107
107
|
claudeBackupPaths: await trustedClaudeBackupPaths(deps.paths.claudeProjectDir, backendId, candidates),
|
|
108
108
|
};
|
|
@@ -110,7 +110,7 @@ async function prepareDeleteCleanup(deps, session) {
|
|
|
110
110
|
async function cleanupPendingDelete(deps, entry) {
|
|
111
111
|
const session = entry.session;
|
|
112
112
|
const backendId = effectiveBackendSessionId(session);
|
|
113
|
-
await deps.
|
|
113
|
+
await deps.registry.unbindBySessionIds([session.sessionId]);
|
|
114
114
|
await deps.ledgerRepo.clearBySessionIds([session.sessionId]);
|
|
115
115
|
await deps.historyRepo.clearBySessionIds([session.sessionId]);
|
|
116
116
|
// Otherwise the carry would outlive every session it describes and grow without bound.
|
|
@@ -155,23 +155,6 @@ async function realpathOrNull(filePath) {
|
|
|
155
155
|
throw error;
|
|
156
156
|
}
|
|
157
157
|
}
|
|
158
|
-
async function repairDanglingReferences(deps, live, pending, errors) {
|
|
159
|
-
const liveIds = new Set(live.map((session) => session.sessionId));
|
|
160
|
-
for (const entry of pending)
|
|
161
|
-
liveIds.add(entry.session.sessionId);
|
|
162
|
-
try {
|
|
163
|
-
await deps.sessionRepo.deleteExceptSessionIds(liveIds);
|
|
164
|
-
}
|
|
165
|
-
catch (error) {
|
|
166
|
-
errors.push(`bindings-repair: ${error.message}`);
|
|
167
|
-
}
|
|
168
|
-
try {
|
|
169
|
-
await deps.ledgerRepo.deleteExceptSessionIds(liveIds);
|
|
170
|
-
}
|
|
171
|
-
catch (error) {
|
|
172
|
-
errors.push(`ledger-repair: ${error.message}`);
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
158
|
async function deleteHistoryOrphans(deps, live, pending, cutoffMs, errors) {
|
|
176
159
|
const protectedIds = new Set([
|
|
177
160
|
...live.map(session => session.sessionId),
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** The one storage call this tracker needs: patch `lastUsedAt=now` iff the session is live and not
|
|
2
|
+
* pending deletion, returning whether the touch landed. Narrowed so tests can inject a fake. */
|
|
3
|
+
export interface UseCountStore {
|
|
4
|
+
touchSessionUse(sessionId: string): Promise<boolean>;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* In-memory use counter for live sessions. `acquireSessionUse` asks the store to touch the session
|
|
8
|
+
* (which fails for unknown / pending-deletion ids); on success it bumps a per-session count and
|
|
9
|
+
* returns an idempotent `release()` that decrements it. While a session's count is > 0 it appears in
|
|
10
|
+
* {@link activeSessionUseIds}, which the retention sweep unions into its protected set so a session
|
|
11
|
+
* cannot be deleted out from under a turn that is still opening.
|
|
12
|
+
*/
|
|
13
|
+
export declare class SessionUseTracker {
|
|
14
|
+
private readonly store;
|
|
15
|
+
private readonly activeUses;
|
|
16
|
+
constructor(store: UseCountStore);
|
|
17
|
+
/** Take a use lease, or null when the record is gone / pending deletion. Nested acquires stack;
|
|
18
|
+
* each returns its own idempotent release. */
|
|
19
|
+
acquireSessionUse(sessionId: string): Promise<(() => void) | null>;
|
|
20
|
+
/** Run `fn` while holding a use lease; returns null (without running `fn`) when the lease is
|
|
21
|
+
* refused. The lease is always released, even if `fn` throws. */
|
|
22
|
+
withSessionUse<T>(sessionId: string, fn: () => Promise<T>): Promise<T | null>;
|
|
23
|
+
/** The sessionIds with at least one live use lease — a snapshot the caller may keep. */
|
|
24
|
+
activeSessionUseIds(): ReadonlySet<string>;
|
|
25
|
+
/** Drop all counts. Tests only — production leases are balanced by their releases. */
|
|
26
|
+
_resetForTests(): void;
|
|
27
|
+
}
|
|
28
|
+
/** Process-wide tracker bound to the real registry singleton. */
|
|
29
|
+
export declare const sessionUse: SessionUseTracker;
|
|
30
|
+
export declare const acquireSessionUse: (sessionId: string) => Promise<(() => void) | null>;
|
|
31
|
+
export declare const withSessionUse: <T>(sessionId: string, fn: () => Promise<T>) => Promise<T | null>;
|
|
32
|
+
export declare const activeSessionUseIds: () => ReadonlySet<string>;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// input: the store's `touchSessionUse` storage primitive (patch lastUsedAt iff live && !pending)
|
|
2
|
+
// output: the runtime use-count lease that keeps retention off a session while a turn holds it
|
|
3
|
+
// pos: domain/sessions — the use-count bookkeeping that used to live inside
|
|
4
|
+
// `store/session-registry-repo.ts`. The store now owns only storage; this owns policy.
|
|
5
|
+
import { sessionStore } from '../../store/session-registry-repo.js';
|
|
6
|
+
/**
|
|
7
|
+
* In-memory use counter for live sessions. `acquireSessionUse` asks the store to touch the session
|
|
8
|
+
* (which fails for unknown / pending-deletion ids); on success it bumps a per-session count and
|
|
9
|
+
* returns an idempotent `release()` that decrements it. While a session's count is > 0 it appears in
|
|
10
|
+
* {@link activeSessionUseIds}, which the retention sweep unions into its protected set so a session
|
|
11
|
+
* cannot be deleted out from under a turn that is still opening.
|
|
12
|
+
*/
|
|
13
|
+
export class SessionUseTracker {
|
|
14
|
+
store;
|
|
15
|
+
activeUses = new Map();
|
|
16
|
+
constructor(store) {
|
|
17
|
+
this.store = store;
|
|
18
|
+
}
|
|
19
|
+
/** Take a use lease, or null when the record is gone / pending deletion. Nested acquires stack;
|
|
20
|
+
* each returns its own idempotent release. */
|
|
21
|
+
async acquireSessionUse(sessionId) {
|
|
22
|
+
if (!(await this.store.touchSessionUse(sessionId)))
|
|
23
|
+
return null;
|
|
24
|
+
this.activeUses.set(sessionId, (this.activeUses.get(sessionId) ?? 0) + 1);
|
|
25
|
+
let released = false;
|
|
26
|
+
return () => {
|
|
27
|
+
if (released)
|
|
28
|
+
return;
|
|
29
|
+
released = true;
|
|
30
|
+
const next = (this.activeUses.get(sessionId) ?? 1) - 1;
|
|
31
|
+
if (next <= 0)
|
|
32
|
+
this.activeUses.delete(sessionId);
|
|
33
|
+
else
|
|
34
|
+
this.activeUses.set(sessionId, next);
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** Run `fn` while holding a use lease; returns null (without running `fn`) when the lease is
|
|
38
|
+
* refused. The lease is always released, even if `fn` throws. */
|
|
39
|
+
async withSessionUse(sessionId, fn) {
|
|
40
|
+
const release = await this.acquireSessionUse(sessionId);
|
|
41
|
+
if (!release)
|
|
42
|
+
return null;
|
|
43
|
+
try {
|
|
44
|
+
return await fn();
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
release();
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** The sessionIds with at least one live use lease — a snapshot the caller may keep. */
|
|
51
|
+
activeSessionUseIds() {
|
|
52
|
+
return new Set(this.activeUses.keys());
|
|
53
|
+
}
|
|
54
|
+
/** Drop all counts. Tests only — production leases are balanced by their releases. */
|
|
55
|
+
_resetForTests() {
|
|
56
|
+
this.activeUses.clear();
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** Process-wide tracker bound to the real registry singleton. */
|
|
60
|
+
export const sessionUse = new SessionUseTracker(sessionStore);
|
|
61
|
+
export const acquireSessionUse = (sessionId) => sessionUse.acquireSessionUse(sessionId);
|
|
62
|
+
export const withSessionUse = (sessionId, fn) => sessionUse.withSessionUse(sessionId, fn);
|
|
63
|
+
export const activeSessionUseIds = () => sessionUse.activeSessionUseIds();
|
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { sessionStore } from '../../store/session-registry-repo.js';
|
|
2
2
|
// A channel has ONE session; the backend it runs is on the session record. `backend` is
|
|
3
|
-
// accepted and ignored here so call sites migrate one at a time.
|
|
3
|
+
// accepted and ignored here so call sites migrate one at a time. These are thin wrappers over the
|
|
4
|
+
// session registry's channel bindings — the registry is the single owner of channel→session identity.
|
|
4
5
|
export async function getSessionAsync(channel, backend) {
|
|
5
|
-
return
|
|
6
|
+
return (await sessionStore.getBoundSessionId(channel)) ?? undefined;
|
|
6
7
|
}
|
|
7
8
|
export async function setSessionAsync(channel, sessionId, backend) {
|
|
8
|
-
|
|
9
|
+
await sessionStore.bindChannel(channel, sessionId);
|
|
9
10
|
}
|
|
10
11
|
export async function deleteSessionAsync(channel, backend) {
|
|
11
|
-
|
|
12
|
+
await sessionStore.unbindChannel(channel);
|
|
12
13
|
}
|
|
@@ -3,6 +3,7 @@ import { execSync, spawn } from 'node:child_process';
|
|
|
3
3
|
import { getSettings } from '../../core/settings.js';
|
|
4
4
|
import { CORTEX_VERSION } from '../../core/version.js';
|
|
5
5
|
import { loadUpdateState, saveUpdateState } from './update-state.js';
|
|
6
|
+
import { reportServerUpdateFailed, reportServerUpdateInstalled } from './update-ui-state.js';
|
|
6
7
|
// ── CalVer comparison ────────────────────────────────────────────
|
|
7
8
|
// Lives in @core/calver.js (platform/ui-http/app-update.ts needs it too and the platform layer may
|
|
8
9
|
// not depend on domain). Re-exported here so existing importers keep working.
|
|
@@ -36,12 +37,39 @@ function defaultGetLatest() {
|
|
|
36
37
|
return null;
|
|
37
38
|
}
|
|
38
39
|
}
|
|
40
|
+
/** Keep the reported stderr small enough to sit in a dialog and in the status snapshot. */
|
|
41
|
+
const INSTALL_STDERR_CAP = 2000;
|
|
42
|
+
function describeInstallFailure(code, signal, stderr) {
|
|
43
|
+
const how = signal !== null ? `killed by ${signal}` : `exited with code ${code}`;
|
|
44
|
+
const tail = stderr.trim().split('\n').slice(-6).join('\n').trim();
|
|
45
|
+
return tail ? `npm install -g ${how}\n${tail}` : `npm install -g ${how}`;
|
|
46
|
+
}
|
|
39
47
|
function defaultSpawnInstall() {
|
|
40
48
|
const child = spawn('npm', ['install', '-g', '@cortex-agent/server@latest'], {
|
|
49
|
+
// Detached + unref'd as before: the package's postinstall touches $STORE_DIR/.restart and the
|
|
50
|
+
// daemon respawns app.js, so the install has to outlive this process. Only stderr changes —
|
|
51
|
+
// piping it is what lets the SPA dialog report a real failure instead of pretending success.
|
|
41
52
|
detached: true,
|
|
42
|
-
stdio: 'ignore',
|
|
53
|
+
stdio: ['ignore', 'ignore', 'pipe'],
|
|
43
54
|
cwd: '/tmp',
|
|
44
55
|
});
|
|
56
|
+
let stderr = '';
|
|
57
|
+
child.stderr?.on('data', (chunk) => {
|
|
58
|
+
if (stderr.length < INSTALL_STDERR_CAP)
|
|
59
|
+
stderr += String(chunk);
|
|
60
|
+
});
|
|
61
|
+
// The pipe is a separate libuv handle from the child; unref it too so a still-running install
|
|
62
|
+
// cannot hold this event loop open. Typed as Readable, but a spawned pipe is a net.Socket.
|
|
63
|
+
child.stderr?.unref?.();
|
|
64
|
+
child.on('error', (err) => {
|
|
65
|
+
reportServerUpdateFailed(`npm install -g could not start: ${err.message}`);
|
|
66
|
+
});
|
|
67
|
+
child.on('exit', (code, signal) => {
|
|
68
|
+
if (code === 0)
|
|
69
|
+
reportServerUpdateInstalled();
|
|
70
|
+
else
|
|
71
|
+
reportServerUpdateFailed(describeInstallFailure(code, signal, stderr));
|
|
72
|
+
});
|
|
45
73
|
child.unref();
|
|
46
74
|
}
|
|
47
75
|
function defaultNow() {
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { UpdateChoice } from './update-prompt.js';
|
|
2
|
+
export type ServerUpdateState = 'idle' | 'prompting' | 'installing' | 'restarting' | 'failed';
|
|
3
|
+
export interface ServerUpdateStatus {
|
|
4
|
+
/** Version the server could move to, or null when there is nothing pending. */
|
|
5
|
+
available: string | null;
|
|
6
|
+
state: ServerUpdateState;
|
|
7
|
+
/** Set only in the `failed` state — the npm exit code / stderr tail. */
|
|
8
|
+
error?: string;
|
|
9
|
+
}
|
|
10
|
+
export declare function getServerUpdateStatus(): ServerUpdateStatus;
|
|
11
|
+
/**
|
|
12
|
+
* Publish a prompt for `version` and register the sink that resolves the waiting `ask()`.
|
|
13
|
+
* The sink is owned by the prompt, not by this module: it is what enforces first-answer-wins
|
|
14
|
+
* between the SPA dialog and the chat-message fallback.
|
|
15
|
+
*/
|
|
16
|
+
export declare function openServerUpdatePrompt(version: string, settle: (choice: UpdateChoice | null) => void): void;
|
|
17
|
+
/** Answer from the SPA. Returns false when nothing was pending — a stale button. */
|
|
18
|
+
export declare function answerServerUpdatePrompt(choice: UpdateChoice): boolean;
|
|
19
|
+
/**
|
|
20
|
+
* Called by the prompt once EITHER side has answered. `apply` hands over to the install
|
|
21
|
+
* reporters below; anything else (skip / cancel / dismissed) drops back to idle.
|
|
22
|
+
*/
|
|
23
|
+
export declare function settleServerUpdatePrompt(choice: UpdateChoice | null): void;
|
|
24
|
+
/**
|
|
25
|
+
* The npm install exited 0. That means "install finished", NOT "the server is already new":
|
|
26
|
+
* the package's postinstall touches $STORE_DIR/.restart and the daemon respawns app.js when it
|
|
27
|
+
* is idle, so `restarting` is the honest label for the window the SPA has to wait through.
|
|
28
|
+
*/
|
|
29
|
+
export declare function reportServerUpdateInstalled(): void;
|
|
30
|
+
export declare function reportServerUpdateFailed(error: string): void;
|
|
31
|
+
/** Test-only: drop the prompt and the status back to their process-start values. */
|
|
32
|
+
export declare function _resetServerUpdateStatus(): void;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// input: UpdateChoice from the UpdatePrompt contract
|
|
2
|
+
// output: the single in-memory server-update status the SPA dialog renders, plus the sink that
|
|
3
|
+
// lets a tRPC mutation answer a pending prompt
|
|
4
|
+
// pos: Shared between orchestration/interactions/ui-update-prompt.ts (writes `prompting`),
|
|
5
|
+
// domain/system/server-update-check.ts (writes the install outcome) and
|
|
6
|
+
// domain/ui-service/{query,mutate}/system.ts (reads / answers). Process-local by design:
|
|
7
|
+
// the npm install restarts app.js, so anything durable here would be stale on the way back.
|
|
8
|
+
const IDLE = { available: null, state: 'idle' };
|
|
9
|
+
let status = IDLE;
|
|
10
|
+
let settleSink = null;
|
|
11
|
+
export function getServerUpdateStatus() {
|
|
12
|
+
return status;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Publish a prompt for `version` and register the sink that resolves the waiting `ask()`.
|
|
16
|
+
* The sink is owned by the prompt, not by this module: it is what enforces first-answer-wins
|
|
17
|
+
* between the SPA dialog and the chat-message fallback.
|
|
18
|
+
*/
|
|
19
|
+
export function openServerUpdatePrompt(version, settle) {
|
|
20
|
+
// A later check (the 24h timer) while a dialog is still up supersedes the earlier one. Resolve
|
|
21
|
+
// the old ask() with null first, or its checkServerUpdate call would wait forever on a promise
|
|
22
|
+
// no button can reach any more.
|
|
23
|
+
const superseded = settleSink;
|
|
24
|
+
settleSink = null;
|
|
25
|
+
superseded?.(null);
|
|
26
|
+
settleSink = settle;
|
|
27
|
+
status = { available: version, state: 'prompting' };
|
|
28
|
+
}
|
|
29
|
+
/** Answer from the SPA. Returns false when nothing was pending — a stale button. */
|
|
30
|
+
export function answerServerUpdatePrompt(choice) {
|
|
31
|
+
const settle = settleSink;
|
|
32
|
+
if (!settle)
|
|
33
|
+
return false;
|
|
34
|
+
settleSink = null;
|
|
35
|
+
settle(choice);
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Called by the prompt once EITHER side has answered. `apply` hands over to the install
|
|
40
|
+
* reporters below; anything else (skip / cancel / dismissed) drops back to idle.
|
|
41
|
+
*/
|
|
42
|
+
export function settleServerUpdatePrompt(choice) {
|
|
43
|
+
settleSink = null;
|
|
44
|
+
status = choice === 'apply'
|
|
45
|
+
? { available: status.available, state: 'installing' }
|
|
46
|
+
: IDLE;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The npm install exited 0. That means "install finished", NOT "the server is already new":
|
|
50
|
+
* the package's postinstall touches $STORE_DIR/.restart and the daemon respawns app.js when it
|
|
51
|
+
* is idle, so `restarting` is the honest label for the window the SPA has to wait through.
|
|
52
|
+
*/
|
|
53
|
+
export function reportServerUpdateInstalled() {
|
|
54
|
+
status = { available: status.available, state: 'restarting' };
|
|
55
|
+
}
|
|
56
|
+
export function reportServerUpdateFailed(error) {
|
|
57
|
+
status = { available: status.available, state: 'failed', error };
|
|
58
|
+
}
|
|
59
|
+
/** Test-only: drop the prompt and the status back to their process-start values. */
|
|
60
|
+
export function _resetServerUpdateStatus() {
|
|
61
|
+
status = IDLE;
|
|
62
|
+
settleSink = null;
|
|
63
|
+
}
|
|
@@ -137,6 +137,21 @@ export declare function createAppRouter(service: UiService): import("@trpc/serve
|
|
|
137
137
|
output: import("./types.js").SessionsSetSelectionReturn;
|
|
138
138
|
meta: object;
|
|
139
139
|
}>;
|
|
140
|
+
setCommission: import("@trpc/server").TRPCMutationProcedure<{
|
|
141
|
+
input: {
|
|
142
|
+
sessionId: string;
|
|
143
|
+
commission?: {
|
|
144
|
+
mode: "off";
|
|
145
|
+
} | {
|
|
146
|
+
mode: "new";
|
|
147
|
+
} | {
|
|
148
|
+
mode: "join";
|
|
149
|
+
commissionId: string;
|
|
150
|
+
};
|
|
151
|
+
};
|
|
152
|
+
output: import("./types.js").SessionsSetCommissionReturn;
|
|
153
|
+
meta: object;
|
|
154
|
+
}>;
|
|
140
155
|
createAndSend: import("@trpc/server").TRPCMutationProcedure<{
|
|
141
156
|
input: {
|
|
142
157
|
projectId: string;
|
|
@@ -1163,6 +1178,21 @@ export declare function createAppRouter(service: UiService): import("@trpc/serve
|
|
|
1163
1178
|
output: import("./types.js").SystemRefreshUsageReturn;
|
|
1164
1179
|
meta: object;
|
|
1165
1180
|
}>;
|
|
1181
|
+
updateStatus: import("@trpc/server").TRPCQueryProcedure<{
|
|
1182
|
+
input: Record<string, never>;
|
|
1183
|
+
output: import("./types.js").ServerUpdateStatus;
|
|
1184
|
+
meta: object;
|
|
1185
|
+
}>;
|
|
1186
|
+
applyUpdate: import("@trpc/server").TRPCMutationProcedure<{
|
|
1187
|
+
input: Record<string, never>;
|
|
1188
|
+
output: import("./types.js").SystemUpdateDecisionReturn;
|
|
1189
|
+
meta: object;
|
|
1190
|
+
}>;
|
|
1191
|
+
skipUpdate: import("@trpc/server").TRPCMutationProcedure<{
|
|
1192
|
+
input: Record<string, never>;
|
|
1193
|
+
output: import("./types.js").SystemUpdateDecisionReturn;
|
|
1194
|
+
meta: object;
|
|
1195
|
+
}>;
|
|
1166
1196
|
}>>;
|
|
1167
1197
|
subscribe: import("@trpc/server").TRPCSubscriptionProcedure<{
|
|
1168
1198
|
input: {
|