cc-viewer 1.9.34 → 1.9.36
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/cli.js +355 -59
- package/dist/assets/{App-CjP88gbM.css → App-BJIeZQK0.css} +1 -1
- package/dist/assets/App-C_S65Ygt.js +2 -0
- package/dist/assets/{ArchivePreview-dQkBQGgg.js → ArchivePreview-ezRMkut5.js} +1 -1
- package/dist/assets/{AudioPreview-B6gJoe0v.js → AudioPreview-MxQVazDj.js} +1 -1
- package/dist/assets/{MdxEditorPanel-COJDASLB.js → MdxEditorPanel-CmG2jyvK.js} +1 -1
- package/dist/assets/{Mobile-Cq04x2pS.js → Mobile-BerOQqT4.js} +1 -1
- package/dist/assets/{ProxyStatsModal-BRtZRf0B.js → ProxyStatsModal-dqlP2r2c.js} +1 -1
- package/dist/assets/{SubtitlePreview-C67JiAyR.js → SubtitlePreview-CHRRgV95.js} +1 -1
- package/dist/assets/index-DBmXRTLE.js +2 -0
- package/dist/assets/seqResourceLoaders-BOVRL7Y-.js +2 -0
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/server/i18n.js +4 -0
- package/server/interceptor.js +114 -25
- package/server/lib/anthropic-auth-placeholder.js +147 -0
- package/server/lib/continuation-args.js +25 -0
- package/server/lib/im/im-bridge-core.js +59 -14
- package/server/lib/im/im-permissions.js +48 -0
- package/server/lib/im/im-process-manager.js +6 -5
- package/server/lib/im-deny.js +4 -1
- package/server/lib/interceptor-core.js +51 -0
- package/server/lib/proxy-session-registry.js +156 -0
- package/server/lib/scheduled-task-executor.js +6 -3
- package/server/lib/sdk-manager.js +376 -88
- package/server/lib/session-start-bridge.js +7 -1
- package/server/lib/update-job.js +3 -3
- package/server/lib/v2/session-select.js +18 -2
- package/server/lib/v2/v2-writer.js +249 -21
- package/server/proxy.js +15 -7
- package/server/pty-manager.js +62 -41
- package/server/routes/events.js +16 -4
- package/server/routes/preferences.js +108 -24
- package/server/routes/resume.js +271 -27
- package/server/routes/update.js +15 -2
- package/server/routes/workspaces.js +112 -29
- package/server/server.js +60 -10
- package/dist/assets/App-CZ0L1Cvm.js +0 -2
- package/dist/assets/index-Cb1Ur9uR.js +0 -2
- package/dist/assets/seqResourceLoaders-BQo28rrY.js +0 -2
|
@@ -9,11 +9,12 @@
|
|
|
9
9
|
* - canUseTool callback for AskUserQuestion + permission approval
|
|
10
10
|
* - Turn-end signaling (SDK 'result' message → Stop-hook equivalent)
|
|
11
11
|
*
|
|
12
|
-
* Registry (2026-
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
12
|
+
* Registry (2026-11, multi-instance): keyed by instanceKey, so ONE cwd may host several
|
|
13
|
+
* concurrent Sessions (file-explorer "New Workspace (Session)" on the current root is a
|
|
14
|
+
* +1 sibling, not a replace). `_activeKey` holds the active session's instanceKey (the
|
|
15
|
+
* SDK analogue of pty-manager's activePtyKey). Sessions are kept alive across workspace
|
|
16
|
+
* switches. Each Session is a factory closure — NO classes (avoids this-binding traps).
|
|
17
|
+
* State is GLOBAL, deliberately kept module-level: `_query`
|
|
17
18
|
* (test injection must be settable before any init — 161+ test cases depend on
|
|
18
19
|
* set-then-init), `_onTurnEnd`/`_onQueryError`/`_broadcastWs`/`_runWaterfallHook`
|
|
19
20
|
* (cli.js registers ONE wiring for the whole process; every session reuses it),
|
|
@@ -34,6 +35,7 @@ import { reportSwallowed } from '../lib/error-report.js';
|
|
|
34
35
|
import { resolve as _pathResolve, dirname as _pathDirname, sep as _pathSep } from 'node:path';
|
|
35
36
|
import { createHash, randomBytes } from 'node:crypto';
|
|
36
37
|
import { registerSdkSessionLister } from './sdk-session-index.js';
|
|
38
|
+
import { seedSessionProxyProfile, clearSessionProxyProfile, clearSessionProxyProfiles } from './proxy-session-registry.js';
|
|
37
39
|
import { readPrefsRaw } from './prefs-store.js';
|
|
38
40
|
import { projectKeyForCwd } from './system-prompt-snapshots.js';
|
|
39
41
|
import { AGENT_PROMPT_SNIPPET_LEN } from '@ccv/core/contentFilter';
|
|
@@ -73,12 +75,15 @@ export function __ephemeralHostCountForTests() { return _ephemeralHosts.size; }
|
|
|
73
75
|
export function __ephemeralAbortCountForTests() { return _ephemeralAborts.size; }
|
|
74
76
|
|
|
75
77
|
// ── Session registry ─────────────────────────────────────────────────────────
|
|
76
|
-
//
|
|
77
|
-
//
|
|
78
|
-
//
|
|
79
|
-
//
|
|
80
|
-
|
|
81
|
-
|
|
78
|
+
// Multi-instance (2026-11): keyed by instanceKey (NOT cwd) so one cwd may host
|
|
79
|
+
// several concurrent Sessions (file-explorer "New Workspace (Session)" on the
|
|
80
|
+
// current root is +1, not a replace). Each Session records its own `cwd`; cwd
|
|
81
|
+
// lookups scan _sessions.values() (n is tiny — a second index would just be a
|
|
82
|
+
// second source of truth). `_activeKey` holds the active session's instanceKey —
|
|
83
|
+
// the SDK analogue of pty-manager's activePtyKey. cwd is normalized only, NO
|
|
84
|
+
// realpath (house exact-string convention, routes/resume.js).
|
|
85
|
+
const _sessions = new Map(); // Map<instanceKey, Session>
|
|
86
|
+
let _activeKey = null; // instanceKey of the active session
|
|
82
87
|
// Ephemeral-turn hosts (scheduled-task spawn): sessions whose approval plumbing is
|
|
83
88
|
// currently borrowed by a standalone run. resolveApproval/cancelApproval/
|
|
84
89
|
// getPendingApprovals scan the UNION of _sessions and this set, so an ephemeral run's
|
|
@@ -93,12 +98,41 @@ function _normalizeCwd(cwd) {
|
|
|
93
98
|
try { return _pathResolve(cwd); } catch { return String(cwd); }
|
|
94
99
|
}
|
|
95
100
|
|
|
96
|
-
//
|
|
97
|
-
//
|
|
101
|
+
// The PRIMARY session for a cwd: the active one when it lives in that cwd, else the
|
|
102
|
+
// deterministic boot session (its key is re-created on relaunch — the stable identity a
|
|
103
|
+
// plain launch/bound view should land on), else the most-recently-registered. A plain
|
|
104
|
+
// launch (non-forceNew) reuses this session rather than spawning a sibling.
|
|
105
|
+
// The deterministic-boot-first / newest-fallback scan shared by _primaryForCwd and
|
|
106
|
+
// resolveBoundPrimaryInstanceKey — the two MUST agree on the "which session is the cwd's
|
|
107
|
+
// stable primary" tie-break, so the loop body lives here once (a future weighting change
|
|
108
|
+
// then can't drift them apart). `_primaryForCwd` prepends an active-first head on top.
|
|
109
|
+
function _deterministicOrLatestForCwd(n) {
|
|
110
|
+
let det = null; let latest = null;
|
|
111
|
+
for (const s of _sessions.values()) {
|
|
112
|
+
if (_normalizeCwd(s.cwd) !== n) continue;
|
|
113
|
+
latest = s; // Map insertion order → last match is the newest
|
|
114
|
+
if (!s.isFreshKey) det = s;
|
|
115
|
+
}
|
|
116
|
+
return det || latest;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function _primaryForCwd(cwd) {
|
|
120
|
+
const n = _normalizeCwd(cwd);
|
|
121
|
+
if (!n) return null;
|
|
122
|
+
const active = _active();
|
|
123
|
+
if (active && _normalizeCwd(active.cwd) === n) return active;
|
|
124
|
+
return _deterministicOrLatestForCwd(n);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Get-or-create the cwd's PRIMARY Session (deterministic key). Only creates when the
|
|
128
|
+
// cwd has no session at all — never spawns a sibling. Used by initSdkSession (plain
|
|
129
|
+
// launch). The record holds the launch config so a kept-alive background session can
|
|
130
|
+
// reconstruct with ITS OWN config.
|
|
98
131
|
function _getOrCreateSession(cwd) {
|
|
99
|
-
const
|
|
100
|
-
|
|
101
|
-
|
|
132
|
+
const existing = _primaryForCwd(cwd);
|
|
133
|
+
if (existing) return existing;
|
|
134
|
+
const s = _createSession(cwd); // deterministic boot key
|
|
135
|
+
_sessions.set(s.instanceKey, s);
|
|
102
136
|
return s;
|
|
103
137
|
}
|
|
104
138
|
|
|
@@ -114,26 +148,24 @@ function _matchesProject(sess, project) {
|
|
|
114
148
|
// A project stamp matches a session when it names the session's exact normalized cwd
|
|
115
149
|
// (absolute-path form) or its sanitized/raw basename (the web client's usual form).
|
|
116
150
|
function _sessionMatchesProject(sess, project) {
|
|
117
|
-
return sess.
|
|
151
|
+
return _normalizeCwd(sess.cwd) === _normalizeCwd(project) || _matchesProject(sess, project);
|
|
118
152
|
}
|
|
119
153
|
|
|
120
|
-
// Resolve an anchor { instanceKey|cwd|project } to a Session WITHOUT switching active
|
|
121
|
-
// `cwd` is an absolute path
|
|
122
|
-
//
|
|
123
|
-
//
|
|
124
|
-
//
|
|
125
|
-
//
|
|
126
|
-
//
|
|
127
|
-
|
|
154
|
+
// Resolve an anchor { instanceKey|cwd|project } to a Session WITHOUT switching active.
|
|
155
|
+
// `cwd` is an absolute path; `project` is the SANITIZED project name the web client sends
|
|
156
|
+
// (ChatView stamps `viewProject || projectName`). Multi-instance: instanceKey is the only
|
|
157
|
+
// unambiguous anchor.
|
|
158
|
+
// Ambiguity policy (2026-11): for an ACTION (a user message/Stop — better routed to the
|
|
159
|
+
// workspace's default session than dropped), a cwd/project matching 2+ same-cwd siblings
|
|
160
|
+
// resolves to that cwd's PRIMARY (`allowPrimaryFallback: true`); for a DESTRUCTIVE op
|
|
161
|
+
// (close/attach — never guess), it resolves to null. Returns null when nothing resolves.
|
|
162
|
+
function _sessionForAnchor(anchor, { allowPrimaryFallback = false } = {}) {
|
|
128
163
|
if (!anchor || typeof anchor !== 'object') return null;
|
|
129
164
|
const instanceKey = (typeof anchor.instanceKey === 'string' && anchor.instanceKey) || null;
|
|
130
165
|
const cwd = (typeof anchor.cwd === 'string' && anchor.cwd) || null;
|
|
131
166
|
const project = (typeof anchor.project === 'string' && anchor.project) || null;
|
|
132
167
|
if (instanceKey) {
|
|
133
|
-
|
|
134
|
-
for (const s of _sessions.values()) {
|
|
135
|
-
if (s.instanceKey === instanceKey) { byInstance = s; break; }
|
|
136
|
-
}
|
|
168
|
+
const byInstance = _sessions.get(instanceKey) || null;
|
|
137
169
|
// An exact instance that no longer exists must never fall back to a
|
|
138
170
|
// same-basename sibling — that would execute the user's action in the
|
|
139
171
|
// wrong workspace. The caller's unknown-anchor path drops + reports it.
|
|
@@ -145,33 +177,68 @@ function _sessionForAnchor(anchor) {
|
|
|
145
177
|
if (project && !_sessionMatchesProject(byInstance, project)) return null;
|
|
146
178
|
return byInstance;
|
|
147
179
|
}
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
//
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
180
|
+
// Multi-match helper for an ACTION anchor (allowPrimaryFallback): exact sole match → it;
|
|
181
|
+
// several matches IN THE SAME cwd → that cwd's primary (a same-cwd sibling set). Matches
|
|
182
|
+
// spanning DIFFERENT cwds (two same-named dirs) are genuinely ambiguous — the anchor named
|
|
183
|
+
// no directory, so never guess across workspaces → null. Destructive anchors never guess.
|
|
184
|
+
const pick = (matches) => {
|
|
185
|
+
if (matches.length === 1) return matches[0];
|
|
186
|
+
if (matches.length > 1) {
|
|
187
|
+
if (!allowPrimaryFallback) return null;
|
|
188
|
+
const cwds = new Set(matches.map((s) => _normalizeCwd(s.cwd)));
|
|
189
|
+
if (cwds.size !== 1) return null; // same project name across different directories — ambiguous
|
|
190
|
+
const p = _primaryForCwd(matches[0].cwd);
|
|
191
|
+
return (p && matches.includes(p)) ? p : matches[0];
|
|
192
|
+
}
|
|
193
|
+
return null;
|
|
194
|
+
};
|
|
195
|
+
if (cwd) {
|
|
196
|
+
const n = _normalizeCwd(cwd);
|
|
197
|
+
return pick([..._sessions.values()].filter((s) => _normalizeCwd(s.cwd) === n));
|
|
156
198
|
}
|
|
157
|
-
return
|
|
199
|
+
if (!project) return null;
|
|
200
|
+
const matches = [..._sessions.values()].filter((s) => _sessionMatchesProject(s, project));
|
|
201
|
+
return pick(matches);
|
|
158
202
|
}
|
|
159
203
|
|
|
160
204
|
// Test seams (house `__…ForTests` convention) — assert registry behavior without a real SDK query.
|
|
161
|
-
export function __listSessionsForTests() { return [..._sessions.keys()]; }
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
*
|
|
166
|
-
*
|
|
167
|
-
* for killPtyFor-shape parity (resume.js consumes `r.key === reattachedTo`). Callers
|
|
168
|
-
* must not mix the two namespaces. */
|
|
205
|
+
export function __listSessionsForTests() { return [..._sessions.keys()]; } // instanceKeys
|
|
206
|
+
|
|
207
|
+
/** Enumerate the SDK session registry for live workspace routing. Each entry:
|
|
208
|
+
* { key, cwd, active, instanceKey, freshLaunch, isFreshKey }. Read-only. `key` IS the
|
|
209
|
+
* instanceKey (multi-instance registry; matches the attach/close responses' key alias,
|
|
210
|
+
* which resume.js consumes as `r.key === reattachedTo`). */
|
|
169
211
|
export function listSdkSessions() {
|
|
170
|
-
return [..._sessions.values()].map((s) => ({ key: s.
|
|
212
|
+
return [..._sessions.values()].map((s) => ({ key: s.instanceKey, cwd: s.cwd, active: s.instanceKey === _activeKey, instanceKey: s.instanceKey, freshLaunch: s.freshLaunch === true, isFreshKey: s.isFreshKey === true, sessionId: s.getSessionId() }));
|
|
171
213
|
}
|
|
172
214
|
|
|
173
215
|
registerSdkSessionLister(listSdkSessions);
|
|
174
216
|
|
|
217
|
+
/** Whether a session is registered for the given anchor (cwd/project/instanceKey).
|
|
218
|
+
* Used by the IM worker's isSessionAvailable so a dropped/closed session fails fast
|
|
219
|
+
* (noSession) instead of queuing into a 2-minute timeout (review-concurrency P1-2). */
|
|
220
|
+
export function hasSession(anchor) {
|
|
221
|
+
if (!anchor) return _active() != null;
|
|
222
|
+
return _sessionForAnchor(anchor, { allowPrimaryFallback: true }) != null;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* The BOUND cwd's primary session instanceKey (2026-11, WS attach-stamp coherence).
|
|
227
|
+
* The single source of truth for the bound identity: resume.js's `/api/live-processes`
|
|
228
|
+
* `currentInstanceKey` delegates here, and server.js's WS `_ccvViewInstance` coherence
|
|
229
|
+
* (`_cohereAttachInstance`) resolves through it, so the header's `boundInstance` and the WS
|
|
230
|
+
* stamp always agree on the same instance for the same cwd. Returns the deterministic boot
|
|
231
|
+
* session (non-fresh key) — NOT the ACTIVE sibling (`_primaryForCwd` is active-first for
|
|
232
|
+
* input-side routing; the bound identity must stay stable while a fresh sibling is active).
|
|
233
|
+
* Falls back to the newest same-cwd row; null when the cwd has no live session. Read-only.
|
|
234
|
+
*/
|
|
235
|
+
export function resolveBoundPrimaryInstanceKey(boundCwd) {
|
|
236
|
+
const n = _normalizeCwd(boundCwd);
|
|
237
|
+
if (!n) return null;
|
|
238
|
+
const primary = _deterministicOrLatestForCwd(n);
|
|
239
|
+
return primary ? primary.instanceKey : null;
|
|
240
|
+
}
|
|
241
|
+
|
|
175
242
|
// The turn can legally wait on approval ceilings: perm/plan = 5min, AskUserQuestion =
|
|
176
243
|
// 24h ("GUI effectively has no timeout" is a product contract). A pending approval
|
|
177
244
|
// exempts the turn from probing entirely (the child is parked awaiting our response).
|
|
@@ -436,8 +503,22 @@ function _foldSdkTask(prev, frame) {
|
|
|
436
503
|
// that are process-global by contract (see file header). Arrays stay closure
|
|
437
504
|
// `let` (rebinding, not a frozen property) so assignment paths like
|
|
438
505
|
// `_messageQueue = []` keep working.
|
|
439
|
-
function _createSession(
|
|
440
|
-
|
|
506
|
+
function _createSession(cwd, { freshKey = false } = {}) {
|
|
507
|
+
// instanceKey identity: deterministic `ccv-sha256(normalizedCwd)` for the cwd's primary
|
|
508
|
+
// (boot) session so a close/restart re-registers the same identity (pre-existing dirs
|
|
509
|
+
// stay resolvable); a forceNew "New Workspace (Session)" generation and an isolated
|
|
510
|
+
// ephemeral host get a FRESH random key (freshKey) so their dirs/frames are
|
|
511
|
+
// distinguishable from the resident sibling's — the same identity separation PTY gets
|
|
512
|
+
// from _mintInstanceKey.
|
|
513
|
+
const instanceKey = freshKey
|
|
514
|
+
? `ccv-${randomBytes(16).toString('hex')}`
|
|
515
|
+
: `ccv-${createHash('sha256').update(_normalizeCwd(cwd)).digest('hex').slice(0, 32)}`;
|
|
516
|
+
// Whether this generation's instanceKey is a random per-generation key (forceNew) rather
|
|
517
|
+
// than the deterministic cwd-derived one. The deterministic key is RE-CREATED whenever the
|
|
518
|
+
// registry slot is rebuilt (close + normal relaunch), so it must NEVER be writer-retired —
|
|
519
|
+
// retiring it would permanently gate the legitimate recreated session. Only random fresh
|
|
520
|
+
// keys (never reused) are safe to retire.
|
|
521
|
+
const _isFreshKey = freshKey === true;
|
|
441
522
|
// Launch config (per-session identity; adopted on lazy reconstruction)
|
|
442
523
|
let _cwd = cwd;
|
|
443
524
|
let _permissionMode = 'default';
|
|
@@ -447,6 +528,8 @@ function _createSession(key, cwd) {
|
|
|
447
528
|
let _launchResume = null; // startup continuation intent { continue, resumeId, forkSession } — first query only
|
|
448
529
|
let _userArgs = []; // remaining user args → options.extraArgs passthrough
|
|
449
530
|
let _claudeExecutable = null; // pathToClaudeCodeExecutable — resolved with the same priority as PTY mode (configured → codefuse → native → PATH → npm) so SDK sessions don't fall back to a PATH claude that host security policy may kill on headless spawn
|
|
531
|
+
let _unattended = false; // runImSdkMode (IM worker): no human can answer any approval modal
|
|
532
|
+
let _insideLogDir = false; // caller asserts the cwd is the IM worker dir under LOG_DIR (cli.js passes true) → skip model-prompt matching so the IM persona wins
|
|
450
533
|
// Resident-query state. `_activeQuery` (the Query handle) and `_queryBusy` (a turn in
|
|
451
534
|
// flight) are deliberately decoupled: an idle resident query is alive but not busy.
|
|
452
535
|
let _activeQuery = null;
|
|
@@ -496,6 +579,13 @@ function _createSession(key, cwd) {
|
|
|
496
579
|
let _suspectGeneration = false;
|
|
497
580
|
let _lastFailedTurn = null; // { turnId, retryable, apiStatus, attempt, maxRetries, code, ts } — drives the manual [retry] affordance
|
|
498
581
|
let _sessionId = null;
|
|
582
|
+
// forceNew (2026-11): true while this is a freshly forceNew'd generation that has not yet
|
|
583
|
+
// written its own main-turn session. events.js reads it (via the listSdkSessions projection)
|
|
584
|
+
// to suppress the same-cwd cold-load fallback so the new conversation starts EMPTY. Cleared
|
|
585
|
+
// when the writer binds this generation's first session (see setOnSessionResolved wiring in
|
|
586
|
+
// server.js → clearSdkFreshLaunch) and on switchToSession. NOT cleared by _resetFullState —
|
|
587
|
+
// a re-init/self-heal of a still-fresh generation must keep suppressing the OLD twin's history.
|
|
588
|
+
let _freshLaunch = false;
|
|
499
589
|
let _initAnnouncedSid = ''; // sessionId whose slash-command surface was already announced (reset on full reset)
|
|
500
590
|
let _lastInitSnapshot = null; // last sdk-init payload for WS reconnect replay
|
|
501
591
|
// Last sdk-skills frame (supportedCommands() result) for WS reconnect replay, and the
|
|
@@ -579,7 +669,7 @@ function _createSession(key, cwd) {
|
|
|
579
669
|
}
|
|
580
670
|
|
|
581
671
|
/** Adopt launch config (initSdkSession writes it here). */
|
|
582
|
-
function _init({ permissionMode, env, settings, model, launchResume, userArgs, claudeExecutable }) {
|
|
672
|
+
function _init({ permissionMode, env, settings, model, launchResume, userArgs, claudeExecutable, unattended, insideLogDir }) {
|
|
583
673
|
_permissionMode = permissionMode || 'default';
|
|
584
674
|
_childEnv = env || null;
|
|
585
675
|
_settings = settings || null;
|
|
@@ -587,6 +677,8 @@ function _createSession(key, cwd) {
|
|
|
587
677
|
_launchResume = launchResume || null;
|
|
588
678
|
_userArgs = Array.isArray(userArgs) ? userArgs : [];
|
|
589
679
|
_claudeExecutable = claudeExecutable || null;
|
|
680
|
+
_unattended = unattended === true;
|
|
681
|
+
_insideLogDir = insideLogDir === true;
|
|
590
682
|
// Re-init (tests / hot reload) must not leave a zombie resident generation alive.
|
|
591
683
|
_teardownResident();
|
|
592
684
|
_resetFullState();
|
|
@@ -946,6 +1038,41 @@ function _createSession(key, cwd) {
|
|
|
946
1038
|
canUseTool: _handleCanUseTool,
|
|
947
1039
|
..._permissionMode === 'bypassPermissions' && { allowDangerouslySkipPermissions: true },
|
|
948
1040
|
};
|
|
1041
|
+
// IM worker (CCV_IM_DENY=1): the child deliberately drops CCV_IM_DENY/CCVIEWER_PORT, so the
|
|
1042
|
+
// settings-file PreToolUse bridge stays dormant in the SDK child. And under bypassPermissions the
|
|
1043
|
+
// CLI shadows canUseTool entirely (CLAUDE_SDK_CAN_USE_TOOL_SHADOWED) — so this in-process
|
|
1044
|
+
// PreToolUse hook is the IM worker's AUTHORITATIVE enforcement layer, running inside the CLI
|
|
1045
|
+
// engine regardless of permission mode (a hook deny is authoritative even under bypass). For an
|
|
1046
|
+
// unattended IM worker it ALSO denies the interactive tools (AskUserQuestion/ExitPlanMode) and
|
|
1047
|
+
// publish, which would otherwise hang with nobody to answer them.
|
|
1048
|
+
if (process.env.CCV_IM_DENY === '1') {
|
|
1049
|
+
options.hooks = {
|
|
1050
|
+
PreToolUse: [{
|
|
1051
|
+
hooks: [async (input) => {
|
|
1052
|
+
try {
|
|
1053
|
+
const toolName = input?.tool_name;
|
|
1054
|
+
// Unattended IM worker: interactive prompts and publish can never be answered —
|
|
1055
|
+
// deny them at the engine layer (bypass shadows canUseTool, so this hook is the
|
|
1056
|
+
// only place they can be stopped without hanging).
|
|
1057
|
+
if (_unattended && (toolName === 'AskUserQuestion' || toolName === 'ExitPlanMode')) {
|
|
1058
|
+
return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: 'Unattended IM session: interactive prompts are unavailable. Ask the user in plain chat text instead.' } };
|
|
1059
|
+
}
|
|
1060
|
+
const verdict = evaluateImDeny(toolName, input?.tool_input ?? {});
|
|
1061
|
+
if (verdict.deny) {
|
|
1062
|
+
return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: `cc-viewer IM guard: ${verdict.reason}` } };
|
|
1063
|
+
}
|
|
1064
|
+
} catch (err) {
|
|
1065
|
+
// Fail-closed: this hook is the IM worker's authoritative enforcement layer
|
|
1066
|
+
// (bypass shadows canUseTool). An evaluation error must not silently allow the
|
|
1067
|
+
// tool — deny and surface it, rather than fail open (review-security P2-1).
|
|
1068
|
+
reportSwallowed('sdk-manager.im-hook', err);
|
|
1069
|
+
return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: 'cc-viewer IM guard: evaluation error' } };
|
|
1070
|
+
}
|
|
1071
|
+
return {};
|
|
1072
|
+
}],
|
|
1073
|
+
}],
|
|
1074
|
+
};
|
|
1075
|
+
}
|
|
949
1076
|
// env carries the loopback-proxy base URL — the SDK passes it through to the
|
|
950
1077
|
// spawned CLI verbatim (verified against sdk.mjs: env defaults to process.env
|
|
951
1078
|
// and is only ever added to, never filtered).
|
|
@@ -966,8 +1093,22 @@ function _createSession(key, cwd) {
|
|
|
966
1093
|
// spinner/queue bubbles) and cold-load instance filters never match SDK sessions.
|
|
967
1094
|
const instanceHeader = `x-ccv-instance: ${instanceKey}`;
|
|
968
1095
|
const injected = `${projectHeader}\n${instanceHeader}`;
|
|
969
|
-
options.env
|
|
970
|
-
|
|
1096
|
+
// Strip-then-append (forceNew / re-init hygiene): options.env is the SHARED launch
|
|
1097
|
+
// env object (cli.js hands the same childEnv to the boot session and every new cwd),
|
|
1098
|
+
// so without stripping, a re-mint / re-construction would stack a SECOND
|
|
1099
|
+
// x-ccv-project-dir/x-ccv-instance pair. The interceptor validates instance against
|
|
1100
|
+
// /^ccv-[0-9a-f]+$/ and DROPS a combined value (interceptor.js) — the fresh
|
|
1101
|
+
// generation's requests would fall back to project/_currentSid routing and write into
|
|
1102
|
+
// the OLD generation's dir. Strip stale ccv routing lines (case-insensitive,
|
|
1103
|
+
// CRLF-tolerant), keep every unrelated header, then append exactly one fresh pair.
|
|
1104
|
+
const prior = typeof options.env.ANTHROPIC_CUSTOM_HEADERS === 'string'
|
|
1105
|
+
? options.env.ANTHROPIC_CUSTOM_HEADERS
|
|
1106
|
+
.split('\n')
|
|
1107
|
+
.filter((l) => !/^x-ccv-(project-dir|instance)\s*:/i.test(l.trim()))
|
|
1108
|
+
.join('\n')
|
|
1109
|
+
.trim()
|
|
1110
|
+
: '';
|
|
1111
|
+
options.env.ANTHROPIC_CUSTOM_HEADERS = prior ? `${prior}\n${injected}` : injected;
|
|
971
1112
|
}
|
|
972
1113
|
}
|
|
973
1114
|
if (_settings) options.settings = _settings;
|
|
@@ -1005,6 +1146,9 @@ function _createSession(key, cwd) {
|
|
|
1005
1146
|
launchSettings: _settings,
|
|
1006
1147
|
resume: resumeIntent,
|
|
1007
1148
|
persistPending: !resumeIntent,
|
|
1149
|
+
// IM worker (runImSdkMode): skip the model-prompt pin/match machinery so the
|
|
1150
|
+
// IM_<id>/CC_APPEND_SYSTEM.md persona is not replaced by a LOG_DIR/system_prompt entry.
|
|
1151
|
+
insideLogDir: _insideLogDir === true,
|
|
1008
1152
|
});
|
|
1009
1153
|
options.extraArgs = launchArgsToExtraArgs([...launchArgs, ...lc.sysPrompt.args]);
|
|
1010
1154
|
} catch (err) {
|
|
@@ -1784,7 +1928,12 @@ function _createSession(key, cwd) {
|
|
|
1784
1928
|
// Per-workspace (2026-10): carry the session's own cwd so the server
|
|
1785
1929
|
// can route turn_end to THIS workspace's SSE scope (SDK mode has no
|
|
1786
1930
|
// Stop-hook POST, so this callback is the only turn-end producer).
|
|
1787
|
-
try { _onTurnEnd({ sessionId: _sessionId, ts: Date.now(), cwd: _cwd
|
|
1931
|
+
try { _onTurnEnd({ sessionId: _sessionId, ts: Date.now(), cwd: _cwd,
|
|
1932
|
+
// resultText: the authoritative final assistant text from the SDK result message.
|
|
1933
|
+
// IM workers (runImSdkMode) have no transcript_path, so the bridge falls back to
|
|
1934
|
+
// this when the interceptor live text is empty. Purely additive — existing
|
|
1935
|
+
// consumers ignore it.
|
|
1936
|
+
resultText: typeof msg.result === 'string' ? msg.result : null }); }
|
|
1788
1937
|
catch (err) { console.warn('[sdk-manager] onTurnEnd threw:', err?.message); }
|
|
1789
1938
|
}
|
|
1790
1939
|
if (rec) _settleTurn(rec);
|
|
@@ -2044,6 +2193,9 @@ function _createSession(key, cwd) {
|
|
|
2044
2193
|
* publish force-approval below (an IM worker gets a hard deny, not a modal);
|
|
2045
2194
|
* 2. npm-publish hard gate — forced through the perm approval branch even in
|
|
2046
2195
|
* bypassPermissions mode (perm-bridge.js's bypass exemption equivalent);
|
|
2196
|
+
* 2b. unattended IM worker (runImSdkMode) — no human can answer a modal, so the
|
|
2197
|
+
* interactive tools (ExitPlanMode/AskUserQuestion) and publish are denied
|
|
2198
|
+
* immediately and everything else auto-allows, instead of parking 5min/24h;
|
|
2047
2199
|
* 3. bypass early-allow — bypass auto-approves everything else, but NEVER
|
|
2048
2200
|
* short-circuits the ExitPlanMode/AskUserQuestion interactive branches;
|
|
2049
2201
|
* 4. the three regular branches (plan / ask / perm).
|
|
@@ -2075,6 +2227,26 @@ function _createSession(key, cwd) {
|
|
|
2075
2227
|
// perm branch below.
|
|
2076
2228
|
const isPublish = isPublishCommand(toolName, input);
|
|
2077
2229
|
|
|
2230
|
+
// 2b. Unattended IM worker (runImSdkMode): no human can answer any approval modal,
|
|
2231
|
+
// so never park. The IM hard deny above already ran; here we deny the interactive
|
|
2232
|
+
// tools and the publish floor immediately with an actionable message and auto-allow
|
|
2233
|
+
// everything else. Without this, an unattended bypass session would still hang 5min
|
|
2234
|
+
// (publish/ExitPlanMode) or 24h (AskUserQuestion) on those paths.
|
|
2235
|
+
// NOTE: runImSdkMode runs permissionMode 'bypassPermissions', under which the CLI does
|
|
2236
|
+
// NOT invoke canUseTool at all (CLAUDE_SDK_CAN_USE_TOOL_SHADOWED) — so for the IM worker
|
|
2237
|
+
// this branch is dormant defense-in-depth, and the authoritative IM enforcement layer is
|
|
2238
|
+
// the in-process PreToolUse hook mounted in _ensureResidentQuery (see options.hooks).
|
|
2239
|
+
// It stays live for any future non-bypass unattended caller.
|
|
2240
|
+
if (_unattended && process.env.CCV_IM_DENY === '1') {
|
|
2241
|
+
if (toolName === 'ExitPlanMode' || toolName === 'AskUserQuestion') {
|
|
2242
|
+
return { behavior: 'deny', message: 'Unattended IM session: interactive prompts are unavailable. Ask the user in plain chat text instead.' };
|
|
2243
|
+
}
|
|
2244
|
+
if (isPublish) {
|
|
2245
|
+
return { behavior: 'deny', message: 'Unattended IM session: publishing commands are blocked.' };
|
|
2246
|
+
}
|
|
2247
|
+
return { behavior: 'allow', updatedInput: input };
|
|
2248
|
+
}
|
|
2249
|
+
|
|
2078
2250
|
// 3. Bypass mode auto-approves everything except publish and the two
|
|
2079
2251
|
// interactive tools — those keep their UI channels so a forwarded
|
|
2080
2252
|
// ExitPlanMode/AskUserQuestion still reaches the user.
|
|
@@ -2745,6 +2917,9 @@ function _createSession(key, cwd) {
|
|
|
2745
2917
|
}
|
|
2746
2918
|
_sessionId = sessionId;
|
|
2747
2919
|
_launchResume = null;
|
|
2920
|
+
// Switching INTO a concrete existing conversation lifts the forceNew empty-view
|
|
2921
|
+
// suppression — this generation now owns real content (the resumed one).
|
|
2922
|
+
_freshLaunch = false;
|
|
2748
2923
|
_initAnnouncedSid = '';
|
|
2749
2924
|
_lastInitSnapshot = null; // don't replay the OLD session's sdk-init to the new one
|
|
2750
2925
|
_lastSkillsSnapshot = null; // same for the skill surface
|
|
@@ -2817,9 +2992,15 @@ function _createSession(key, cwd) {
|
|
|
2817
2992
|
// `teardown` = _teardownResident + _resetFullState (the old module-level stopSession
|
|
2818
2993
|
// body, now per-session). `init` = config adoption + that teardown/reset pair.
|
|
2819
2994
|
return {
|
|
2820
|
-
key,
|
|
2821
2995
|
instanceKey,
|
|
2822
2996
|
get cwd() { return _cwd; },
|
|
2997
|
+
// forceNew (2026-11): whether this generation is a fresh "New Workspace (Session)"
|
|
2998
|
+
// instance that has not yet written its own main-turn session. Read live (getter) —
|
|
2999
|
+
// events.js / resume.js see it through the listSdkSessions projection.
|
|
3000
|
+
get freshLaunch() { return _freshLaunch === true; },
|
|
3001
|
+
// True when this generation's instanceKey is a random per-generation key (safe to retire);
|
|
3002
|
+
// false for the deterministic cwd-derived key (re-created on relaunch — never retire it).
|
|
3003
|
+
get isFreshKey() { return _isFreshKey; },
|
|
2823
3004
|
get config() {
|
|
2824
3005
|
return {
|
|
2825
3006
|
permissionMode: _permissionMode,
|
|
@@ -2887,6 +3068,12 @@ function _createSession(key, cwd) {
|
|
|
2887
3068
|
},
|
|
2888
3069
|
switchToSession: _switchToSession,
|
|
2889
3070
|
getSessionId: () => _sessionId,
|
|
3071
|
+
// forceNew (2026-11): the writer's main-turn `_onSessionResolved` calls this once the
|
|
3072
|
+
// new generation owns its first session dir — the empty-view suppression lifts (PTY
|
|
3073
|
+
// parity with setPtySessionIdForInstance clearing the PTY record's freshLaunch).
|
|
3074
|
+
clearFreshLaunch: () => { _freshLaunch = false; },
|
|
3075
|
+
// createSdkSession marks the freshly-ADDED sibling generation (NOT a method for general use).
|
|
3076
|
+
_markFreshLaunch: () => { _freshLaunch = true; },
|
|
2890
3077
|
retryInterruptedTurn: _retryInterruptedTurn,
|
|
2891
3078
|
runEphemeralTurn: _runEphemeralTurn,
|
|
2892
3079
|
close: () => {
|
|
@@ -2949,12 +3136,18 @@ export async function spawnEphemeralSession(prompt, { cwd, project, timeoutMs =
|
|
|
2949
3136
|
if (!cwd) return { ok: false, reason: 'not_initialized' };
|
|
2950
3137
|
|
|
2951
3138
|
const key = _normalizeCwd(cwd);
|
|
2952
|
-
|
|
3139
|
+
// Borrow the cwd's resident session to carry approvals (its canUseTool plumbing).
|
|
3140
|
+
// Active-first so a same-cwd sibling set resolves to the foreground workspace. No
|
|
3141
|
+
// resident session → an isolated, unregistered host is created below.
|
|
3142
|
+
let host = _primaryForCwd(cwd);
|
|
2953
3143
|
let created = false;
|
|
2954
3144
|
if (!host) {
|
|
2955
3145
|
// No resident session for this cwd in this boot: create an isolated host purely to
|
|
2956
|
-
// carry approvals (its canUseTool plumbing). It is NOT registered in _sessions.
|
|
2957
|
-
|
|
3146
|
+
// carry approvals (its canUseTool plumbing). It is NOT registered in _sessions. A fresh
|
|
3147
|
+
// random key keeps its approval frames distinct from any FUTURE resident boot session
|
|
3148
|
+
// for this cwd (a deterministic key would alias them).
|
|
3149
|
+
host = _createSession(cwd, { freshKey: true });
|
|
3150
|
+
host.__ephemeralCwd = key; // test seam marker (isolated host for an unregistered cwd)
|
|
2958
3151
|
try { host.init({ ...cfg }); }
|
|
2959
3152
|
catch (err) { reportSwallowed('sdk-manager.ephemeral-init', err); return { ok: false, reason: 'not_initialized', error: String(err?.message || err) }; }
|
|
2960
3153
|
created = true;
|
|
@@ -2974,7 +3167,7 @@ export async function spawnEphemeralSession(prompt, { cwd, project, timeoutMs =
|
|
|
2974
3167
|
export function __isEphemeralHostForTests(cwd) {
|
|
2975
3168
|
const key = _normalizeCwd(cwd);
|
|
2976
3169
|
for (const host of _ephemeralHosts) {
|
|
2977
|
-
if (host.
|
|
3170
|
+
if (host.__ephemeralCwd === key || _normalizeCwd(host.cwd) === key) return true;
|
|
2978
3171
|
}
|
|
2979
3172
|
return false;
|
|
2980
3173
|
}
|
|
@@ -3006,7 +3199,7 @@ export function __isEphemeralHostForTests(cwd) {
|
|
|
3006
3199
|
* must come from the same selection as PTY mode, else the SDK spawns a PATH claude that
|
|
3007
3200
|
* host security tooling (e.g. agent-security headless guards) may SIGKILL on spawn
|
|
3008
3201
|
*/
|
|
3009
|
-
export function initSdkSession(cwd, projectName, { onTurnEnd, onQueryError, broadcastWs, permissionMode, runWaterfallHook, onAgentLoopStart, onAgentLoopEnd, env, settings, model, launchResume, userArgs, claudeExecutable } = {}) {
|
|
3202
|
+
export function initSdkSession(cwd, projectName, { onTurnEnd, onQueryError, broadcastWs, permissionMode, runWaterfallHook, onAgentLoopStart, onAgentLoopEnd, env, settings, model, launchResume, userArgs, claudeExecutable, unattended, insideLogDir } = {}) {
|
|
3010
3203
|
void projectName; // reserved (display name comes from the wire path)
|
|
3011
3204
|
// Process-global callbacks (cli.js registers one wiring; every session reuses it). Only
|
|
3012
3205
|
// OVERWRITE when a callback is actually passed — a later per-workspace init (the launch
|
|
@@ -3022,12 +3215,73 @@ export function initSdkSession(cwd, projectName, { onTurnEnd, onQueryError, broa
|
|
|
3022
3215
|
// registration). A workspace stop→relaunch omits these callbacks, so without this every
|
|
3023
3216
|
// sdk-* frame would silently stop broadcasting after returning to the workspace list.
|
|
3024
3217
|
_adoptProcessWiring();
|
|
3025
|
-
// Register this
|
|
3026
|
-
// it active. init() adopts the launch config
|
|
3027
|
-
// generation (tests / hot reload) — other
|
|
3218
|
+
// Register this cwd's PRIMARY session (re-using the record on re-init — a plain launch
|
|
3219
|
+
// never spawns a same-cwd sibling) and make it active. init() adopts the launch config
|
|
3220
|
+
// and tears down ONLY this session's prior generation (tests / hot reload) — other
|
|
3221
|
+
// workspaces' sessions (and same-cwd siblings) are untouched.
|
|
3028
3222
|
const sess = _getOrCreateSession(cwd);
|
|
3029
|
-
sess.init({ permissionMode, env, settings, model, launchResume, userArgs, claudeExecutable });
|
|
3030
|
-
_activeKey = sess.
|
|
3223
|
+
sess.init({ permissionMode, env, settings, model, launchResume, userArgs, claudeExecutable, unattended, insideLogDir });
|
|
3224
|
+
_activeKey = sess.instanceKey;
|
|
3225
|
+
// Seed the per-session proxy binding from the global default (no-op when the
|
|
3226
|
+
// session is already bound, so a re-init never clobbers a user's choice).
|
|
3227
|
+
seedSessionProxyProfile(sess.instanceKey);
|
|
3228
|
+
}
|
|
3229
|
+
|
|
3230
|
+
/**
|
|
3231
|
+
* "New Workspace (Session)" on the CURRENT root for SDK mode (2026-11) — a same-cwd
|
|
3232
|
+
* SIBLING, not a replacement. The resident registry is keyed by instanceKey so one cwd
|
|
3233
|
+
* may host several concurrent Sessions. This APPENDS a fresh Session carrying a random
|
|
3234
|
+
* instanceKey (PTY-style generation identity) and leaves every existing same-cwd session
|
|
3235
|
+
* alive (its resident query, conversation, and writer routing untouched). The new
|
|
3236
|
+
* generation's dirs/frames are distinguishable via the new meta.instance key; the old
|
|
3237
|
+
* sibling's dirs keep the OLD key, so instance-scoped readers (cold-load picker, live
|
|
3238
|
+
* feed, SSE attach) keep each view on its own conversation.
|
|
3239
|
+
*
|
|
3240
|
+
* Unlike PTY's retired-generation model, the old sibling stays live — so the route must
|
|
3241
|
+
* NOT retireInstance the old key (retirement freezes a LIVE session's routing). The new
|
|
3242
|
+
* session is marked freshLaunch so its cold-load starts EMPTY instead of falling back to
|
|
3243
|
+
* the sibling's history; the mark lifts on its first main-turn bind.
|
|
3244
|
+
*
|
|
3245
|
+
* Returns { instanceKey } for the route to pin the client view to the new instance.
|
|
3246
|
+
*/
|
|
3247
|
+
export function createSdkSession(cwd, cfg) {
|
|
3248
|
+
const key = _normalizeCwd(cwd);
|
|
3249
|
+
if (!key) return null;
|
|
3250
|
+
// Capture a same-cwd sibling's config BEFORE registering the new one (fallback for
|
|
3251
|
+
// direct/test callers with no process template registered).
|
|
3252
|
+
const sibling = _primaryForCwd(cwd);
|
|
3253
|
+
const sess = _createSession(cwd, { freshKey: true }); // random per-generation key
|
|
3254
|
+
_sessions.set(sess.instanceKey, sess);
|
|
3255
|
+
// Adopt the process-level launch config template so the fresh query gets the proxy env /
|
|
3256
|
+
// model / permission / executable; launchResume is forced null (a boot -c/-r intent must
|
|
3257
|
+
// never resume into a forceNew conversation).
|
|
3258
|
+
const base = cfg || _launchConfigTemplate || (sibling && sibling.config) || {};
|
|
3259
|
+
try {
|
|
3260
|
+
sess.init({ ...base, launchResume: null });
|
|
3261
|
+
} catch (err) {
|
|
3262
|
+
// init failed — roll back the registration so the registry never holds a half-init'd
|
|
3263
|
+
// session, and leave _activeKey on the previous session.
|
|
3264
|
+
_sessions.delete(sess.instanceKey);
|
|
3265
|
+
reportSwallowed('sdk-manager.create-session-init', err);
|
|
3266
|
+
return null;
|
|
3267
|
+
}
|
|
3268
|
+
sess._markFreshLaunch();
|
|
3269
|
+
_adoptProcessWiring();
|
|
3270
|
+
_activeKey = sess.instanceKey;
|
|
3271
|
+
seedSessionProxyProfile(sess.instanceKey);
|
|
3272
|
+
return { instanceKey: sess.instanceKey };
|
|
3273
|
+
}
|
|
3274
|
+
|
|
3275
|
+
/**
|
|
3276
|
+
* Lift a forceNew generation's empty-view suppression. Called from server.js's
|
|
3277
|
+
* v2-writer `_onSessionResolved` wiring (the main-turn gate) once the instance owns its
|
|
3278
|
+
* first session dir — PTY parity with setPtySessionIdForInstance clearing the PTY mark.
|
|
3279
|
+
*/
|
|
3280
|
+
export function clearSdkFreshLaunch(instanceKey) {
|
|
3281
|
+
if (typeof instanceKey !== 'string' || !/^ccv-[0-9a-f]+$/.test(instanceKey)) return;
|
|
3282
|
+
for (const s of _sessions.values()) {
|
|
3283
|
+
if (s.instanceKey === instanceKey && typeof s.clearFreshLaunch === 'function') { s.clearFreshLaunch(); return; }
|
|
3284
|
+
}
|
|
3031
3285
|
}
|
|
3032
3286
|
|
|
3033
3287
|
/**
|
|
@@ -3041,7 +3295,10 @@ export function initSdkSession(cwd, projectName, { onTurnEnd, onQueryError, broa
|
|
|
3041
3295
|
export async function sendUserMessage(text, anchor) {
|
|
3042
3296
|
if (!_query) throw new Error('Agent SDK not available');
|
|
3043
3297
|
if (anchor && (anchor.cwd || anchor.project || anchor.instanceKey)) {
|
|
3044
|
-
|
|
3298
|
+
// An action anchor: a same-cwd ambiguous cwd/project resolves to the cwd's PRIMARY
|
|
3299
|
+
// rather than dropping the user's message (Mobile / pre-poll desktop sends carry no
|
|
3300
|
+
// instanceKey).
|
|
3301
|
+
const target = _sessionForAnchor(anchor, { allowPrimaryFallback: true });
|
|
3045
3302
|
if (!target) {
|
|
3046
3303
|
// A mis-resolved anchor must not silently drop the user's message — log + report,
|
|
3047
3304
|
// and surface a toast through the same channel query errors use (the composer was
|
|
@@ -3059,8 +3316,8 @@ export async function sendUserMessage(text, anchor) {
|
|
|
3059
3316
|
}
|
|
3060
3317
|
return;
|
|
3061
3318
|
}
|
|
3062
|
-
if (target.
|
|
3063
|
-
_activeKey = target.
|
|
3319
|
+
if (target.instanceKey !== _activeKey) {
|
|
3320
|
+
_activeKey = target.instanceKey; // an action re-routes the active session (lazy: no teardown)
|
|
3064
3321
|
}
|
|
3065
3322
|
return target.sendUserMessage(text);
|
|
3066
3323
|
}
|
|
@@ -3131,9 +3388,11 @@ export function getPendingApprovals(anchor) {
|
|
|
3131
3388
|
* cancelled-approval list (see the Session factory's interruptTurn). */
|
|
3132
3389
|
export function interruptTurn(anchor) {
|
|
3133
3390
|
if (anchor) {
|
|
3134
|
-
|
|
3391
|
+
// An action anchor: an ambiguous cwd/project resolves to the cwd's primary so a
|
|
3392
|
+
// Stop without an instanceKey (Mobile) still halts the workspace's default session.
|
|
3393
|
+
const target = _sessionForAnchor(anchor, { allowPrimaryFallback: true });
|
|
3135
3394
|
if (target) {
|
|
3136
|
-
if (target.
|
|
3395
|
+
if (target.instanceKey !== _activeKey) _activeKey = target.instanceKey;
|
|
3137
3396
|
return target.interruptTurn();
|
|
3138
3397
|
}
|
|
3139
3398
|
// Unknown anchor: nothing to interrupt — same empty array the idle path returns.
|
|
@@ -3146,8 +3405,8 @@ export function interruptTurn(anchor) {
|
|
|
3146
3405
|
/** Send-now on a queued bubble of the ACTIVE session (or an anchor's session —
|
|
3147
3406
|
* an action, switches active). Returns the cancelled-approval list. */
|
|
3148
3407
|
export function sendQueuedNow(id, anchor) {
|
|
3149
|
-
const sess = anchor ? _sessionForAnchor(anchor) : _active();
|
|
3150
|
-
if (anchor && sess && sess.
|
|
3408
|
+
const sess = anchor ? _sessionForAnchor(anchor, { allowPrimaryFallback: true }) : _active();
|
|
3409
|
+
if (anchor && sess && sess.instanceKey !== _activeKey) _activeKey = sess.instanceKey;
|
|
3151
3410
|
return sess ? sess.sendQueuedNow(id) : [];
|
|
3152
3411
|
}
|
|
3153
3412
|
|
|
@@ -3190,6 +3449,7 @@ export function stopSession() {
|
|
|
3190
3449
|
}
|
|
3191
3450
|
_sessions.clear();
|
|
3192
3451
|
_activeKey = null;
|
|
3452
|
+
clearSessionProxyProfiles();
|
|
3193
3453
|
// Process-global wiring is cleared on the HARD teardown boundary. initSdkSession only
|
|
3194
3454
|
// overwrites a callback when one is actually passed (so a per-workspace launch init
|
|
3195
3455
|
// cannot wipe cli.js's process-wide wiring mid-run); that guard means an init that
|
|
@@ -3212,9 +3472,9 @@ export function stopSession() {
|
|
|
3212
3472
|
* captured sessionId). Unknown cwd → false (no switch); already-active → true (no-op).
|
|
3213
3473
|
*/
|
|
3214
3474
|
export function setActiveSdkSession(cwd) {
|
|
3215
|
-
const
|
|
3216
|
-
if (!
|
|
3217
|
-
_activeKey =
|
|
3475
|
+
const sess = _primaryForCwd(cwd);
|
|
3476
|
+
if (!sess) return false;
|
|
3477
|
+
_activeKey = sess.instanceKey; // lazy switch: the target's state machine is intact by construction
|
|
3218
3478
|
return true;
|
|
3219
3479
|
}
|
|
3220
3480
|
|
|
@@ -3232,9 +3492,11 @@ export function attachSdkSession(anchor) {
|
|
|
3232
3492
|
}
|
|
3233
3493
|
const sess = _sessionForAnchor(anchor);
|
|
3234
3494
|
if (!sess) return { ok: false, reason: 'not-found' };
|
|
3235
|
-
const switched = sess.
|
|
3236
|
-
_activeKey = sess.
|
|
3237
|
-
//
|
|
3495
|
+
const switched = sess.instanceKey !== _activeKey;
|
|
3496
|
+
_activeKey = sess.instanceKey;
|
|
3497
|
+
// Activating a session binds its proxy (seeded from the global default when the
|
|
3498
|
+
// session predates the mapping or its binding was cleared).
|
|
3499
|
+
seedSessionProxyProfile(sess.instanceKey);
|
|
3238
3500
|
return { ok: true, key: sess.instanceKey, instanceKey: sess.instanceKey, cwd: sess.cwd, switched };
|
|
3239
3501
|
}
|
|
3240
3502
|
|
|
@@ -3249,7 +3511,14 @@ export function closeSdkSession(anchor = {}) {
|
|
|
3249
3511
|
sess = _sessionForAnchor({ instanceKey });
|
|
3250
3512
|
if (!sess) return { ok: false, reason: 'not-found' };
|
|
3251
3513
|
} else if (anchor.cwd) {
|
|
3252
|
-
|
|
3514
|
+
// cwd anchor: refuse same-cwd ambiguity (a same-cwd sibling must be addressed by
|
|
3515
|
+
// instanceKey — closing the wrong twin would kill a live conversation).
|
|
3516
|
+
const n = _normalizeCwd(anchor.cwd);
|
|
3517
|
+
const matches = [..._sessions.values()].filter((s) => _normalizeCwd(s.cwd) === n);
|
|
3518
|
+
if (matches.length > 1) {
|
|
3519
|
+
return { ok: false, reason: 'ambiguous', candidates: matches.map((s) => ({ key: s.instanceKey, instanceKey: s.instanceKey, cwd: s.cwd })) };
|
|
3520
|
+
}
|
|
3521
|
+
sess = matches[0] || null;
|
|
3253
3522
|
} else if (anchor.project) {
|
|
3254
3523
|
const matches = [..._sessions.values()].filter((s) => _matchesProject(s, anchor.project));
|
|
3255
3524
|
if (matches.length > 1) {
|
|
@@ -3263,25 +3532,34 @@ export function closeSdkSession(anchor = {}) {
|
|
|
3263
3532
|
}
|
|
3264
3533
|
if (!sess) return { ok: false, reason: 'not-found' };
|
|
3265
3534
|
|
|
3266
|
-
const killedActive = sess.
|
|
3535
|
+
const killedActive = sess.instanceKey === _activeKey;
|
|
3267
3536
|
const result = {
|
|
3268
3537
|
ok: true,
|
|
3269
|
-
// `key` aliases instanceKey
|
|
3270
|
-
// `p.key === killResult.reattachedTo`).
|
|
3271
|
-
// the registry key is `sess.key`, a different namespace. Do not conflate.
|
|
3538
|
+
// `key` aliases instanceKey (killPtyFor-shape parity: resume.js matches
|
|
3539
|
+
// `p.key === killResult.reattachedTo`).
|
|
3272
3540
|
key: sess.instanceKey,
|
|
3273
3541
|
instanceKey: sess.instanceKey,
|
|
3274
3542
|
cwd: sess.cwd,
|
|
3543
|
+
// Tells the route how to retire the closed instance's writer routing: a random
|
|
3544
|
+
// per-generation key is safe to retire; the deterministic cwd key is RE-created on a
|
|
3545
|
+
// normal relaunch, so it must be RELEASED (cleared), never retired (permanently frozen).
|
|
3546
|
+
wasFreshKey: sess.isFreshKey === true,
|
|
3275
3547
|
killedActive,
|
|
3276
3548
|
reattachedTo: null,
|
|
3277
3549
|
};
|
|
3278
3550
|
// Remove the registry identity BEFORE user-callback-facing teardown frames. A
|
|
3279
3551
|
// close/relaunch triggered by one of those frames must register a fresh session,
|
|
3280
3552
|
// never be deleted by the tail of the older close operation.
|
|
3281
|
-
_sessions.delete(sess.
|
|
3553
|
+
_sessions.delete(sess.instanceKey);
|
|
3554
|
+
clearSessionProxyProfile(sess.instanceKey);
|
|
3282
3555
|
if (killedActive) {
|
|
3283
|
-
|
|
3284
|
-
|
|
3556
|
+
// Prefer a SAME-CWD sibling (the twin the user most likely wants next), else fall
|
|
3557
|
+
// back to the next registered session (Map insertion order).
|
|
3558
|
+
const n = _normalizeCwd(sess.cwd);
|
|
3559
|
+
let survivor = null;
|
|
3560
|
+
for (const s of _sessions.values()) { if (_normalizeCwd(s.cwd) === n) { survivor = s; break; } }
|
|
3561
|
+
if (!survivor) survivor = _sessions.values().next().value || null;
|
|
3562
|
+
_activeKey = survivor ? survivor.instanceKey : null;
|
|
3285
3563
|
result.reattachedTo = survivor ? survivor.instanceKey : null;
|
|
3286
3564
|
}
|
|
3287
3565
|
try {
|
|
@@ -3306,9 +3584,9 @@ export function getActiveSdkCwd() {
|
|
|
3306
3584
|
*/
|
|
3307
3585
|
export function switchToSession(sessionId, anchor) {
|
|
3308
3586
|
if (!_query) return { ok: false, reason: 'unavailable' }; // route maps this to 409 — must fire BEFORE any session lookup
|
|
3309
|
-
const sess = anchor ? _sessionForAnchor(anchor) : _active();
|
|
3587
|
+
const sess = anchor ? _sessionForAnchor(anchor, { allowPrimaryFallback: true }) : _active();
|
|
3310
3588
|
if (!sess) return { ok: false, reason: 'bad-id' };
|
|
3311
|
-
if (anchor && sess.
|
|
3589
|
+
if (anchor && sess.instanceKey !== _activeKey) _activeKey = sess.instanceKey;
|
|
3312
3590
|
return sess.switchToSession(sessionId);
|
|
3313
3591
|
}
|
|
3314
3592
|
|
|
@@ -3318,6 +3596,16 @@ export function getSessionId(anchor) {
|
|
|
3318
3596
|
return sess ? sess.getSessionId() : null;
|
|
3319
3597
|
}
|
|
3320
3598
|
|
|
3599
|
+
/** The sessionId a SPECIFIC instance currently holds (SDK-side, generation-scoped: cleared
|
|
3600
|
+
* on teardown/reset), or null. Unlike the writer's per-instance routing pointer, this
|
|
3601
|
+
* cannot survive a stopSession/rebuild — so it is the safe "is this instance actively on
|
|
3602
|
+
* this conversation NOW" check for the resume twin-ownership guard. */
|
|
3603
|
+
export function getSessionIdForInstance(instanceKey) {
|
|
3604
|
+
if (typeof instanceKey !== 'string' || !instanceKey) return null;
|
|
3605
|
+
const s = _sessions.get(instanceKey);
|
|
3606
|
+
return s ? s.getSessionId() : null;
|
|
3607
|
+
}
|
|
3608
|
+
|
|
3321
3609
|
/**
|
|
3322
3610
|
* Manual [retry] of the last failed turn on the active (or anchored) session. Pushes a
|
|
3323
3611
|
* synthetic continue instruction instead of resending the user's original message.
|
|
@@ -3330,7 +3618,7 @@ export async function retryInterruptedTurn(turnId, anchor) {
|
|
|
3330
3618
|
const r = await sess.retryInterruptedTurn(turnId);
|
|
3331
3619
|
// Only a SUCCESSFUL retry re-routes the process-wide active session — a rejected retry
|
|
3332
3620
|
// (busy/stale/no-session) must not steal the active anchor from the foreground view.
|
|
3333
|
-
if (r && r.ok && anchor && sess.
|
|
3621
|
+
if (r && r.ok && anchor && sess.instanceKey !== _activeKey) _activeKey = sess.instanceKey;
|
|
3334
3622
|
return r;
|
|
3335
3623
|
}
|
|
3336
3624
|
|