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
|
@@ -74,7 +74,13 @@ try {
|
|
|
74
74
|
debug(`payload source=${source} session_id=${sessionId} transcript=${transcriptPath}`);
|
|
75
75
|
|
|
76
76
|
const internalToken = process.env.CCVIEWER_INTERNAL_TOKEN || '';
|
|
77
|
-
|
|
77
|
+
// Same-cwd twin routing (R1): the PTY that spawned this claude stamped its
|
|
78
|
+
// instanceKey into the env. Forward it so an in-terminal /resume is routed to
|
|
79
|
+
// THIS instance's pending switch, not a sibling twin sharing the same project.
|
|
80
|
+
// Validate the shape — a stale/foreign value must never steer routing.
|
|
81
|
+
const rawInstance = process.env.CCVIEWER_INSTANCE_KEY || '';
|
|
82
|
+
const instanceKey = /^ccv-[0-9a-f]+$/.test(rawInstance) ? rawInstance : null;
|
|
83
|
+
const body = JSON.stringify({ source, sessionId, transcriptPath, cwd, agentId, instanceKey, ts: Date.now() });
|
|
78
84
|
const reqOpts = {
|
|
79
85
|
hostname: '127.0.0.1',
|
|
80
86
|
port: parseInt(port, 10),
|
package/server/lib/update-job.js
CHANGED
|
@@ -221,7 +221,7 @@ export class UpdateJob {
|
|
|
221
221
|
try { await handler(this.state.version); }
|
|
222
222
|
catch (err) { this.setState({ status: 'restart_required', error: err.message }); throw err; }
|
|
223
223
|
}
|
|
224
|
-
async start() {
|
|
224
|
+
async start({ force = false } = {}) {
|
|
225
225
|
if (['checking', 'downloading', 'installing', 'restarting', 'restart_required'].includes(this.state.status)) return this.getState();
|
|
226
226
|
if (!this.state.version || !this.state.release) {
|
|
227
227
|
const state = await this.check();
|
|
@@ -237,11 +237,11 @@ export class UpdateJob {
|
|
|
237
237
|
return this.getState();
|
|
238
238
|
}
|
|
239
239
|
}
|
|
240
|
-
this.setState({ status: 'downloading', error: null, downloaded: 0, total: null });
|
|
240
|
+
this.setState({ status: 'downloading', error: null, errorCode: null, downloaded: 0, total: null });
|
|
241
241
|
const directory = dirname(UPDATE_STATE_FILE);
|
|
242
242
|
let file;
|
|
243
243
|
try {
|
|
244
|
-
if (await (this.options.hasOtherInstanceImpl || hasOtherNormalInstance)({ currentPort: this.options.currentPort })) throw updateError('Exit other cc-viewer instances before updating', 'another_instance');
|
|
244
|
+
if (!force && await (this.options.hasOtherInstanceImpl || hasOtherNormalInstance)({ currentPort: this.options.currentPort })) throw updateError('Exit other cc-viewer instances before updating', 'another_instance');
|
|
245
245
|
const root = await (this.options.resolveRootImpl || resolveNpmInstallRoot)();
|
|
246
246
|
const actualRoot = await realpath(root);
|
|
247
247
|
await withFileLockAsync(join(dirname(UPDATE_STATE_FILE), 'update-install.lock'), async () => {
|
|
@@ -302,9 +302,16 @@ export function isDiscardableSession(dir, meta) {
|
|
|
302
302
|
* cross-instance FALLBACK pool to sessions stamped with this cwd (or with NO meta.cwd —
|
|
303
303
|
* keep-missing). Applies ONLY to the fallback pool, never the instance filter; an empty
|
|
304
304
|
* value disables the cwd filter. No effect without `instanceKey`.
|
|
305
|
+
* `suppressFallback` (forceNew, 2026-11): when set WITH `instanceKey`, skip the
|
|
306
|
+
* cross-instance fallback entirely — a deliberately brand-new instance ("New Workspace
|
|
307
|
+
* (Session)") has NO conversation yet, and the fallback would serve the live twin's OLD
|
|
308
|
+
* one. Returns null when the instance has no own main-turn session (events.js then serves
|
|
309
|
+
* the empty-view contract). The instance's OWN main turn always wins (the `own` check
|
|
310
|
+
* above runs first). No effect without `instanceKey`; default false preserves today's
|
|
311
|
+
* fallback for reused/rebuilt instances and header chip clicks.
|
|
305
312
|
* @returns {{dir:string, sessionId:string}|null}
|
|
306
313
|
*/
|
|
307
|
-
export function latestMainSession(projectDir, { excludeDir = '', skipForeignLive = false, instanceKey = '', targetCwd = '' } = {}) {
|
|
314
|
+
export function latestMainSession(projectDir, { excludeDir = '', skipForeignLive = false, instanceKey = '', targetCwd = '', suppressFallback = false } = {}) {
|
|
308
315
|
if (!projectDir) return null;
|
|
309
316
|
const instanceCandidates = []; // session dirs stamped with the requested instanceKey
|
|
310
317
|
const projectCandidates = []; // every eligible session dir of the project (any/no instance)
|
|
@@ -352,6 +359,15 @@ export function latestMainSession(projectDir, { excludeDir = '', skipForeignLive
|
|
|
352
359
|
if (instanceKey) {
|
|
353
360
|
const own = newestWithMainTurn(instanceCandidates);
|
|
354
361
|
if (own) return own;
|
|
362
|
+
// forceNew (2026-11): a deliberately brand-new instance has no conversation yet. The
|
|
363
|
+
// cross-instance fallback below would serve the project's newest content-bearing
|
|
364
|
+
// session — the live twin's OLD conversation — which is exactly the "new workspace
|
|
365
|
+
// still shows the OLD conversation" bug. Return null so events.js serves the empty
|
|
366
|
+
// view (load_start{empty:true}); the live feed streams the first turn in place.
|
|
367
|
+
// NOTE: we must NOT degrade to `ownAny` here — a launch-time quota probe writes a
|
|
368
|
+
// session dir stamped with this instance but no main turn, and serving it would
|
|
369
|
+
// defeat the empty view. `own` above already guarantees a real main turn wins.
|
|
370
|
+
if (suppressFallback) return null;
|
|
355
371
|
// Same-name isolation (2026-10-07): scope the cross-instance fallback to the
|
|
356
372
|
// TARGET cwd so a cross-dir same-basename project sharing this pool can't be
|
|
357
373
|
// served. Keep-missing: legacy dirs with NO meta.cwd (null) stay eligible —
|
|
@@ -379,7 +395,7 @@ export function latestMainSession(projectDir, { excludeDir = '', skipForeignLive
|
|
|
379
395
|
* Absolute dir of the newest readable, non-teammate session that HAS a main
|
|
380
396
|
* turn, or '' if there is none. Thin wrapper over {@link latestMainSession}.
|
|
381
397
|
* @param {string} projectDir - absolute LOG_DIR/<project>
|
|
382
|
-
* @param {{excludeDir?: string, skipForeignLive?: boolean, instanceKey?: string, targetCwd?: string}} [opts] - see {@link latestMainSession}
|
|
398
|
+
* @param {{excludeDir?: string, skipForeignLive?: boolean, instanceKey?: string, targetCwd?: string, suppressFallback?: boolean}} [opts] - see {@link latestMainSession}
|
|
383
399
|
* @returns {string} absolute session dir, or ''
|
|
384
400
|
*/
|
|
385
401
|
export function latestMainSessionDir(projectDir, opts) { return latestMainSession(projectDir, opts)?.dir || '';
|
|
@@ -90,7 +90,25 @@ export class V2Writer {
|
|
|
90
90
|
// — a crash skips release harmlessly (claim validity is pid liveness).
|
|
91
91
|
this._claimedDirs = new Set();
|
|
92
92
|
this._currentSid = null; // last successfully resolved session (fallback routing §8.3)
|
|
93
|
-
|
|
93
|
+
// Multi-instance (same-cwd twin): per-instance fallback pointer so a
|
|
94
|
+
// metadata-less request (heartbeat/countTokens) from twin B routes to B's
|
|
95
|
+
// own session, never to the process-global _currentSid (twin A). Keyed by
|
|
96
|
+
// `_ccvInstance` → {sid, project}. Only ever SET on a main-agent turn
|
|
97
|
+
// (teammate/subagent children inherit the parent's x-ccv-instance but run
|
|
98
|
+
// their own sid — letting them set this would hijack the parent's pointer).
|
|
99
|
+
this._currentSidByInstance = new Map(); // instKey → {sid, project}
|
|
100
|
+
this._pendingNoSid = []; // legacy (no-instance) requests seen before any sid.
|
|
101
|
+
// Per-instance cold-start hold buckets: instKeyOr'' → {project, items:[]}.
|
|
102
|
+
// Kept separate from _pendingNoSid so a twin's held heartbeats flush only on
|
|
103
|
+
// that twin's first sid-bearing request, not on the other twin's.
|
|
104
|
+
this._pendingNoSidByInstance = new Map();
|
|
105
|
+
// forceNew (2026-11): instanceKeys of RETIRED generations (an SDK forceNew teardown).
|
|
106
|
+
// A retired instance's late traffic (a draining child's heartbeat/completion) may still
|
|
107
|
+
// write into its OWN old dir (history stays consistent) but must NEVER move the live
|
|
108
|
+
// pointers (`_currentSid` / `_currentSidByInstance` / `_onSessionResolved`) — else the
|
|
109
|
+
// fresh generation's bound cold-load flips back to the old conversation. Append-only;
|
|
110
|
+
// random keys never collide with a future generation. Cleared only by resetSessions().
|
|
111
|
+
this._retiredInstances = new Set();
|
|
94
112
|
// Contract with the caller: originalMessages held here must be a reference
|
|
95
113
|
// the caller never MUTATES (the interceptor's original array is only ever
|
|
96
114
|
// REASSIGNED away from body.messages, never mutated in place — safe).
|
|
@@ -114,10 +132,12 @@ export class V2Writer {
|
|
|
114
132
|
this._adopted = new Set();
|
|
115
133
|
// In-terminal /resume switch (SessionStart hook, source:'resume'): the
|
|
116
134
|
// next MAIN request must be re-routed to the resumed conversation's dir.
|
|
117
|
-
//
|
|
118
|
-
//
|
|
119
|
-
//
|
|
120
|
-
|
|
135
|
+
// Two-level: project → instance. The instance level (R1) stops a same-cwd
|
|
136
|
+
// twin from consuming the OTHER twin's armed switch; '' is the legacy
|
|
137
|
+
// (no-instance) slot, preserving the old per-project behavior for producers
|
|
138
|
+
// that carry no x-ccv-instance. Value: {transcriptUuid, hookSid}; consumed
|
|
139
|
+
// one-shot on the matching instance's next main request.
|
|
140
|
+
this._pendingResumeSwitch = new Map(); // projSan → Map<instKeyOr'', {transcriptUuid, hookSid}>
|
|
121
141
|
}
|
|
122
142
|
|
|
123
143
|
/** P2: true once any session's FIRST main wire already carried assistant
|
|
@@ -190,6 +210,11 @@ export class V2Writer {
|
|
|
190
210
|
// live window's dir — it just doesn't stamp ownership of its own.
|
|
191
211
|
const prev = latestMainSession(projectDir, { skipForeignLive: true });
|
|
192
212
|
if (!prev || !prev.sessionId) return null;
|
|
213
|
+
// Same-process twin guard: the pid-level skipForeignLive above is blind to a
|
|
214
|
+
// same-cwd twin of THIS process (shared pid). A `-c`/history-replay on one
|
|
215
|
+
// twin must never adopt the OTHER twin's live dir (two Journals, one file).
|
|
216
|
+
if (this._isBoundToOtherInstance(basename(prev.dir), project,
|
|
217
|
+
(entry && typeof entry._ccvInstance === 'string' && entry._ccvInstance) ? entry._ccvInstance : null)) return null;
|
|
193
218
|
if (this._claimsEnabled()) {
|
|
194
219
|
if (!acquireSessionClaim(prev.dir).ok) return null;
|
|
195
220
|
// Record immediately (not only in _session): a throw between here and
|
|
@@ -199,6 +224,27 @@ export class V2Writer {
|
|
|
199
224
|
return { dirName: basename(prev.dir), identityUUID: prev.sessionId };
|
|
200
225
|
}
|
|
201
226
|
|
|
227
|
+
/** Per-instance fallback pointer for metadata-less routing (R3): the sid a
|
|
228
|
+
* twin's heartbeat/countTokens should resolve to. Returns null when the
|
|
229
|
+
* instance has not yet run a main turn — in that case the caller must NOT
|
|
230
|
+
* fall back to the process-global `_currentSid` (that would write twin B's
|
|
231
|
+
* cold-start traffic into twin A's dir). */
|
|
232
|
+
_currentSidFor(instKey) {
|
|
233
|
+
if (!instKey) return this._currentSid;
|
|
234
|
+
const cur = this._currentSidByInstance.get(instKey);
|
|
235
|
+
return cur ? cur.sid : null;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** The sid an instance is CURRENTLY bound to (main-turn routing pointer), or null.
|
|
239
|
+
* Read-only; used by the resume twin-ownership guard to tell "this instance owns the
|
|
240
|
+
* conversation it is actively writing" apart from "this instance merely shares a
|
|
241
|
+
* deterministic key with a dead prior author". */
|
|
242
|
+
currentSidForInstance(instKey) {
|
|
243
|
+
if (typeof instKey !== 'string' || !instKey) return null;
|
|
244
|
+
const cur = this._currentSidByInstance.get(instKey);
|
|
245
|
+
return cur ? cur.sid : null;
|
|
246
|
+
}
|
|
247
|
+
|
|
202
248
|
/** In-terminal /resume signal (interceptor.markSessionStart → here): arm a
|
|
203
249
|
* one-shot routing switch. `transcriptUuid` is the resumed conversation's
|
|
204
250
|
* stable identity (transcript basename); `hookSid` is the fresh session
|
|
@@ -206,14 +252,19 @@ export class V2Writer {
|
|
|
206
252
|
* conversation was never recorded by ccv (it must not be the old wire sid:
|
|
207
253
|
* `<ts>_<oldSid>` would be re-resolved back to the OLD dir by
|
|
208
254
|
* resolveSessionDirName). Last-wins across repeated /resume picks. */
|
|
209
|
-
beginResumeSwitch({ transcriptUuid, hookSid, project } = {}) {
|
|
255
|
+
beginResumeSwitch({ transcriptUuid, hookSid, project, instanceKey = null } = {}) {
|
|
210
256
|
try {
|
|
211
257
|
if (!transcriptUuid || typeof transcriptUuid !== 'string') return;
|
|
212
258
|
// Keyed by the project the resumed conversation belongs to (defaults to the
|
|
213
259
|
// currently-bound project — markSessionStart's guard already ensures the
|
|
214
260
|
// hook's cwd matches it). Per-project so a scoped reset clears only that one.
|
|
215
261
|
const key = sanitizePathComponent(project || this._projectFn() || '');
|
|
216
|
-
|
|
262
|
+
const inst = (typeof instanceKey === 'string' && /^ccv-[0-9a-f]+$/.test(instanceKey)) ? instanceKey : '';
|
|
263
|
+
let bucket = this._pendingResumeSwitch.get(key);
|
|
264
|
+
if (!bucket) { bucket = new Map(); this._pendingResumeSwitch.set(key, bucket); }
|
|
265
|
+
// Last-wins across repeated /resume picks, but ONLY within the same
|
|
266
|
+
// (project, instance) — a twin must not clobber its sibling's armed switch.
|
|
267
|
+
bucket.set(inst, {
|
|
217
268
|
transcriptUuid,
|
|
218
269
|
hookSid: (typeof hookSid === 'string' && hookSid) ? hookSid : null,
|
|
219
270
|
});
|
|
@@ -222,6 +273,33 @@ export class V2Writer {
|
|
|
222
273
|
}
|
|
223
274
|
}
|
|
224
275
|
|
|
276
|
+
/** Same-process live-bind guard (R1/R7): is `dirName` currently bound in THIS
|
|
277
|
+
* process's `_sessions` to a DIFFERENT instance? The pid-level `owner.lock`
|
|
278
|
+
* guard (`isForeignLiveOwned`) is blind to same-cwd twins — both share this
|
|
279
|
+
* process's pid, so a twin adopting the other's live dir would produce two
|
|
280
|
+
* Journal objects writing the same file with independently-seeded seqs
|
|
281
|
+
* (certain corruption). Used by the resume-switch and `-c` adoption paths to
|
|
282
|
+
* fall back to fork semantics instead. */
|
|
283
|
+
_isBoundToOtherInstance(dirName, project, instKey) {
|
|
284
|
+
const projectDir = join(this._logDir, sanitizePathComponent(project));
|
|
285
|
+
const targetDir = join(projectDir, this._sessionsDirName, dirName);
|
|
286
|
+
for (const s of this._sessions.values()) {
|
|
287
|
+
if (s && s.paths && s.paths.dir === targetDir) {
|
|
288
|
+
const owner = s._instanceKey || null;
|
|
289
|
+
// Same identity → not a conflict (a twin re-joining its OWN dir).
|
|
290
|
+
if (owner === instKey && owner !== null) return false;
|
|
291
|
+
// Owner is a known twin but the caller is a DIFFERENT instance, OR the
|
|
292
|
+
// caller carries no instance identity while the dir is owned by one
|
|
293
|
+
// (a legacy producer must not re-bind a twin's dir — that is the very
|
|
294
|
+
// "two Journals, one file" this guard exists to prevent). Both conflict.
|
|
295
|
+
// An unattributed legacy binding (owner null) with an unattributed caller
|
|
296
|
+
// (instKey null) is allowed to preserve legacy self re-join semantics.
|
|
297
|
+
return !(owner === null && instKey === null);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
return false;
|
|
301
|
+
}
|
|
302
|
+
|
|
225
303
|
/**
|
|
226
304
|
* Consume the pending /resume switch for the arriving MAIN request: pick
|
|
227
305
|
* the target dir, take its claim, drop the old same-sid binding, and return
|
|
@@ -238,10 +316,13 @@ export class V2Writer {
|
|
|
238
316
|
* it, not by the incoming `sid`
|
|
239
317
|
* @returns {{dirName:string, identityUUID:string}}
|
|
240
318
|
*/
|
|
241
|
-
_resolveResumeSwitch(sid, project, prevSid = null) {
|
|
319
|
+
_resolveResumeSwitch(sid, project, prevSid = null, instanceKey = null) {
|
|
242
320
|
const key = this._projKey(project);
|
|
243
|
-
const
|
|
244
|
-
|
|
321
|
+
const bucket = this._pendingResumeSwitch.get(key);
|
|
322
|
+
const inst = (typeof instanceKey === 'string' && instanceKey) ? instanceKey : '';
|
|
323
|
+
const sw = bucket ? bucket.get(inst) : null;
|
|
324
|
+
if (bucket) { bucket.delete(inst); if (bucket.size === 0) this._pendingResumeSwitch.delete(key); } // one-shot
|
|
325
|
+
if (!sw) return null;
|
|
245
326
|
const projectDir = join(this._logDir, sanitizePathComponent(project));
|
|
246
327
|
let dirName = resolveSessionDirName(projectDir, sw.transcriptUuid, this._sessionsDirName);
|
|
247
328
|
let identity = sw.transcriptUuid;
|
|
@@ -251,9 +332,13 @@ export class V2Writer {
|
|
|
251
332
|
// unconditional skipForeignLive): even a non-claiming writer must never
|
|
252
333
|
// re-bind into a dir another live window is writing. The acquire below
|
|
253
334
|
// additionally arbitrates for claiming writers.
|
|
335
|
+
// Same-process twin guard: the pid-level check above is blind to two
|
|
336
|
+
// same-cwd instances of THIS process (shared pid) — also refuse a dir
|
|
337
|
+
// currently bound to a different instance here (manual /resume in a twin).
|
|
254
338
|
if (isForeignLiveOwned(targetDir)
|
|
339
|
+
|| this._isBoundToOtherInstance(dirName, project, inst)
|
|
255
340
|
|| (this._claimsEnabled() && !acquireSessionClaim(targetDir).ok)) {
|
|
256
|
-
dirName = null; // live foreign owner — never share its journal
|
|
341
|
+
dirName = null; // live foreign owner / live twin — never share its journal
|
|
257
342
|
}
|
|
258
343
|
}
|
|
259
344
|
if (dirName) {
|
|
@@ -459,13 +544,24 @@ export class V2Writer {
|
|
|
459
544
|
if (!this._diskOk()) return null;
|
|
460
545
|
|
|
461
546
|
const parsed = parseUserId(entry.body && entry.body.metadata && entry.body.metadata.user_id);
|
|
547
|
+
// Instance this request belongs to (same-cwd twin routing). Extracted once
|
|
548
|
+
// at the top so the resume-switch/adoption/metadata-less paths all agree.
|
|
549
|
+
const instKey = (typeof entry._ccvInstance === 'string' && entry._ccvInstance) ? entry._ccvInstance : null;
|
|
550
|
+
// forceNew (2026-11): a RETIRED generation (SDK forceNew teardown) may still be
|
|
551
|
+
// draining — its trailing completion should land in its OWN old dir, but it must
|
|
552
|
+
// never move `_currentSid` / `_currentSidByInstance` / `_onSessionResolved`, and its
|
|
553
|
+
// metadata-less traffic must not be routed or held (it would misroute into the fresh
|
|
554
|
+
// generation's dir). Read once; gates below.
|
|
555
|
+
const retired = !!(instKey && this._retiredInstances.has(instKey));
|
|
462
556
|
// Captured BEFORE the reassignment below: when a /resume switch arrives
|
|
463
557
|
// on a FRESH wire sid, the departing conversation's binding is keyed by
|
|
464
558
|
// this previous sid, not the incoming one (review P2 — the fresh-sid
|
|
465
559
|
// variant would otherwise leak the old dir's claim + map entry until
|
|
466
560
|
// process exit, blocking other windows from resuming that ended
|
|
467
|
-
// conversation).
|
|
468
|
-
|
|
561
|
+
// conversation). Per-instance (R3): a twin must depart from ITS OWN
|
|
562
|
+
// previous sid, not the process-global last-writer — otherwise twin A's
|
|
563
|
+
// /resume would resolve against twin B's binding and release B's claim.
|
|
564
|
+
const prevSid = this._currentSidFor(instKey);
|
|
469
565
|
let sid;
|
|
470
566
|
if (parsed) {
|
|
471
567
|
sid = parsed.sessionId;
|
|
@@ -484,9 +580,20 @@ export class V2Writer {
|
|
|
484
580
|
const entryProject = (typeof entry._resumeProject === 'string' && entry._resumeProject)
|
|
485
581
|
? entry._resumeProject
|
|
486
582
|
: this._projectFn();
|
|
487
|
-
if (entryProject && entryProject === this._projectFn()) {
|
|
583
|
+
if (entryProject && entryProject === this._projectFn() && !retired) {
|
|
488
584
|
this._currentSid = sid;
|
|
489
585
|
}
|
|
586
|
+
// Per-instance pointer (R3): pin the sid for THIS instance so its later
|
|
587
|
+
// metadata-less requests route back here. MAIN-AGENT GATE mirrors the
|
|
588
|
+
// `_onSessionResolved` gate below: only the main interactive claude's own
|
|
589
|
+
// turn sets it. A teammate/subagent child INHERITS the parent's
|
|
590
|
+
// `x-ccv-instance` but runs its OWN conversation/sid — without this gate
|
|
591
|
+
// it would overwrite the parent instance's pointer with the teammate's
|
|
592
|
+
// sid, misrouting the parent's heartbeats into the teammate's session.
|
|
593
|
+
const isMainAgentTurn = entry.mainAgent === true && !entry.teammate && !entry.isHeartbeat && !entry.isCountTokens;
|
|
594
|
+
if (instKey && isMainAgentTurn && !retired) {
|
|
595
|
+
this._currentSidByInstance.set(instKey, { sid, project: entryProject });
|
|
596
|
+
}
|
|
490
597
|
// Feed the PTY sid index: this request's owning project just resolved a
|
|
491
598
|
// concrete sessionId, so the PTY serving that project can be addressed by
|
|
492
599
|
// sid. Multi-instance (2026-10-06): also forward the self-reported instanceKey
|
|
@@ -499,11 +606,34 @@ export class V2Writer {
|
|
|
499
606
|
// its OWN conversation/sid — without this gate it would overwrite the parent record's
|
|
500
607
|
// sessionId with the teammate's sid, mis-pinning the instance. Teammate / heartbeat /
|
|
501
608
|
// count_tokens requests are skipped.
|
|
502
|
-
|
|
503
|
-
if (this._onSessionResolved && entryProject && isMainAgentTurn) {
|
|
504
|
-
const instKey = (typeof entry._ccvInstance === 'string' && entry._ccvInstance) ? entry._ccvInstance : null;
|
|
609
|
+
if (this._onSessionResolved && entryProject && isMainAgentTurn && !retired) {
|
|
505
610
|
try { this._onSessionResolved(sid, entryProject, instKey); } catch (err) { reportSwallowed('v2-write.session-resolved', err); }
|
|
506
611
|
}
|
|
612
|
+
} else if (instKey) {
|
|
613
|
+
// forceNew (2026-11): a retired generation's metadata-less traffic is dropped, not
|
|
614
|
+
// routed (its pointer is gone) nor held (a held heartbeat would later flush into the
|
|
615
|
+
// NEW generation's dir). Returning null writes nothing — clean for a dead generation.
|
|
616
|
+
if (retired) return null;
|
|
617
|
+
// Metadata-less request from a known instance: route to that instance's
|
|
618
|
+
// own session. If it has not run a main turn yet, there is NO pointer —
|
|
619
|
+
// deliberately do NOT fall back to the process-global `_currentSid`,
|
|
620
|
+
// which would write twin B's cold-start heartbeat into twin A's dir.
|
|
621
|
+
const own = this._currentSidByInstance.get(instKey);
|
|
622
|
+
if (own) {
|
|
623
|
+
sid = own.sid;
|
|
624
|
+
} else {
|
|
625
|
+
let bucket = this._pendingNoSidByInstance.get(instKey);
|
|
626
|
+
if (!bucket) { bucket = { project, items: [] }; this._pendingNoSidByInstance.set(instKey, bucket); }
|
|
627
|
+
if (bucket.items.length < 64) {
|
|
628
|
+
bucket.items.push({ entry, originalMessages, rid: entry.requestId || null });
|
|
629
|
+
return null;
|
|
630
|
+
}
|
|
631
|
+
// Bucket overflow safety valve: mint a throwaway noid sid for THIS
|
|
632
|
+
// request only. Deliberately NOT written into _currentSidByInstance —
|
|
633
|
+
// this branch may be a heartbeat/teammate (not a gated main turn), and
|
|
634
|
+
// a noid must never become the instance's durable pointer.
|
|
635
|
+
sid = `noid-${process.pid}-${Date.now()}`;
|
|
636
|
+
}
|
|
507
637
|
} else if (this._currentSid) {
|
|
508
638
|
sid = this._currentSid; // §8.3 fallback: route metadata-less requests to the active session
|
|
509
639
|
} else {
|
|
@@ -532,7 +662,9 @@ export class V2Writer {
|
|
|
532
662
|
// probes and heartbeats wear main-agent body shapes but are not the
|
|
533
663
|
// user's resumed turn — consuming on them would re-bind too early
|
|
534
664
|
// with the same result, but keep the gate strict for clarity).
|
|
535
|
-
|
|
665
|
+
// Instance-keyed (R1): a twin consumes only ITS OWN armed switch.
|
|
666
|
+
const rsBucket = this._pendingResumeSwitch.get(this._projKey(project));
|
|
667
|
+
if (rsBucket && rsBucket.has(instKey || '') && entry.mainAgent
|
|
536
668
|
&& !entry.isCountTokens && !entry.isHeartbeat) {
|
|
537
669
|
// Locally guarded (review P2): the switch resolution does dir-scan
|
|
538
670
|
// fs work (resolveSessionDirName → readdirSync) whose residual
|
|
@@ -540,7 +672,7 @@ export class V2Writer {
|
|
|
540
672
|
// outer catch and drop THIS request entirely — the resumed
|
|
541
673
|
// conversation's first main turn. A failure must degrade to normal
|
|
542
674
|
// routing (recorded in the current dir), never to a lost entry.
|
|
543
|
-
try { adoptTarget = this._resolveResumeSwitch(sid, project, prevSid); }
|
|
675
|
+
try { adoptTarget = this._resolveResumeSwitch(sid, project, prevSid, instKey); }
|
|
544
676
|
catch (err) { reportSwallowed('v2-write.resume-switch-apply', err); }
|
|
545
677
|
}
|
|
546
678
|
if (!adoptTarget) {
|
|
@@ -608,9 +740,16 @@ export class V2Writer {
|
|
|
608
740
|
|
|
609
741
|
// Flush requests that arrived before the first sid (they belong here).
|
|
610
742
|
// Their handles are parked in _lateHandles so a completion that arrives
|
|
611
|
-
// after the flush still gets its done line (folded by rid).
|
|
612
|
-
|
|
743
|
+
// after the flush still gets its done line (folded by rid). R3: flush the
|
|
744
|
+
// legacy no-instance bucket AND only THIS request's instance bucket — a
|
|
745
|
+
// twin's held heartbeats must never be flushed into the other twin's dir.
|
|
746
|
+
const instBucket = instKey ? this._pendingNoSidByInstance.get(instKey) : null;
|
|
747
|
+
if (this._pendingNoSid.length > 0 || (instBucket && instBucket.items.length > 0)) {
|
|
613
748
|
const pending = this._pendingNoSid.splice(0);
|
|
749
|
+
if (instBucket) {
|
|
750
|
+
pending.push(...instBucket.items);
|
|
751
|
+
this._pendingNoSidByInstance.delete(instKey);
|
|
752
|
+
}
|
|
614
753
|
for (const p of pending) {
|
|
615
754
|
const pseq = this._ingestInto(s, sid, p.entry, p.originalMessages);
|
|
616
755
|
const prid = p.rid; // captured at hold time — the seam may have deleted entry.requestId by now
|
|
@@ -1041,6 +1180,8 @@ export class V2Writer {
|
|
|
1041
1180
|
s.resolver.reset();
|
|
1042
1181
|
}
|
|
1043
1182
|
this._currentSid = null;
|
|
1183
|
+
this._currentSidByInstance.clear();
|
|
1184
|
+
this._pendingNoSidByInstance.clear();
|
|
1044
1185
|
} catch (err) {
|
|
1045
1186
|
reportSwallowed('v2-write.reset', err);
|
|
1046
1187
|
}
|
|
@@ -1085,14 +1226,21 @@ export class V2Writer {
|
|
|
1085
1226
|
}
|
|
1086
1227
|
}
|
|
1087
1228
|
this._pendingNoSid.length = 0;
|
|
1229
|
+
this._pendingNoSidByInstance.clear();
|
|
1088
1230
|
this._lateHandles.clear();
|
|
1089
1231
|
// _currentSid only clears when it pointed at the dropped project — the
|
|
1090
1232
|
// background project's live "current" pointer survives a scoped reset.
|
|
1091
1233
|
if (matchAll) {
|
|
1092
1234
|
this._currentSid = null;
|
|
1235
|
+
this._currentSidByInstance.clear();
|
|
1093
1236
|
} else {
|
|
1094
1237
|
const cur = this._currentSid ? this._sessions.get(this._currentSid) : null;
|
|
1095
1238
|
if (this._currentSid && !cur) this._currentSid = null;
|
|
1239
|
+
// Drop only the switched-away project's per-instance pointers (mirrors
|
|
1240
|
+
// the _currentSid rule): a background project's twin keeps its pointer.
|
|
1241
|
+
for (const [k, v] of [...this._currentSidByInstance]) {
|
|
1242
|
+
if (sanitizePathComponent(v.project || '') === targetSan) this._currentSidByInstance.delete(k);
|
|
1243
|
+
}
|
|
1096
1244
|
}
|
|
1097
1245
|
// `-c` adoption latch + pending /resume switch, both per-project now: a
|
|
1098
1246
|
// scoped reset clears only the switched-away project's latch (a background
|
|
@@ -1100,6 +1248,7 @@ export class V2Writer {
|
|
|
1100
1248
|
if (matchAll) {
|
|
1101
1249
|
this._adopted.clear();
|
|
1102
1250
|
this._pendingResumeSwitch.clear();
|
|
1251
|
+
this._retiredInstances.clear(); // full reset: no retired generation survives a workspace wipe
|
|
1103
1252
|
} else {
|
|
1104
1253
|
this._adopted.delete(targetSan);
|
|
1105
1254
|
this._pendingResumeSwitch.delete(targetSan);
|
|
@@ -1109,6 +1258,85 @@ export class V2Writer {
|
|
|
1109
1258
|
}
|
|
1110
1259
|
}
|
|
1111
1260
|
|
|
1261
|
+
/** Same-project forceNew relaunch (R2): a NEW claude instance is being spawned
|
|
1262
|
+
* in the SAME cwd as a live twin. The twin keeps its session bindings
|
|
1263
|
+
* (`_sessions`) and owner.lock claims (`_claimedDirs`) — releasing them would
|
|
1264
|
+
* expose its live dirs to the sibling's cold-load/adoption. Only
|
|
1265
|
+
* launch-boundary state that could hijack or misroute the FRESH twin is
|
|
1266
|
+
* cleared: held pre-sid traffic, late handles, and any armed /resume switch
|
|
1267
|
+
* (which belongs to the outgoing launch context, not the new twin). The
|
|
1268
|
+
* `-c` adoption latch is intentionally LEFT SET — forceNew never adopts an
|
|
1269
|
+
* old folder, and clearing it would wrongly re-enable adoption for the
|
|
1270
|
+
* still-live twin. Same-process mis-adoption is prevented by the
|
|
1271
|
+
* `_isBoundToOtherInstance` guard in _resolveAdoption/_resolveResumeSwitch,
|
|
1272
|
+
* not by poisoning the project latch. */
|
|
1273
|
+
resetForLiveRelaunch(targetProject) {
|
|
1274
|
+
try {
|
|
1275
|
+
const key = this._projKey(targetProject);
|
|
1276
|
+
this._pendingNoSid.length = 0;
|
|
1277
|
+
this._pendingNoSidByInstance.clear();
|
|
1278
|
+
// Late handles are _openHandle-counted when parked; a bare clear() would
|
|
1279
|
+
// leak their in-flight count and wedge shard rotation for the surviving
|
|
1280
|
+
// twin's session (resetSessions gets away with it only because it also
|
|
1281
|
+
// drops the sessions). Close each without re-arming rotation first.
|
|
1282
|
+
for (const h of this._lateHandles.values()) this._closeHandle(h, { rotate: false });
|
|
1283
|
+
this._lateHandles.clear();
|
|
1284
|
+
this._pendingResumeSwitch.delete(key);
|
|
1285
|
+
// Clear the process-global current pointer only when it pointed at this
|
|
1286
|
+
// project (mirrors the scoped-reset terminal state), so the fresh twin's
|
|
1287
|
+
// pre-sid traffic cannot follow it into the OLD twin's dir. The
|
|
1288
|
+
// per-instance pointers are kept — they are how the still-live twin's own
|
|
1289
|
+
// metadata-less traffic keeps routing to its own dir.
|
|
1290
|
+
if (this._currentSid) {
|
|
1291
|
+
const cur = this._sessions.get(this._currentSid);
|
|
1292
|
+
if (!cur || this._projKey(cur.project || '') === key) this._currentSid = null;
|
|
1293
|
+
}
|
|
1294
|
+
// DELIBERATELY NOT touched: _sessions, _claimedDirs, _adopted,
|
|
1295
|
+
// _currentSidByInstance.
|
|
1296
|
+
} catch (err) {
|
|
1297
|
+
reportSwallowed('v2-write.reset-relaunch', err);
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
/**
|
|
1302
|
+
* Retire a CLOSED random-key SDK session (2026-11). Marks the instanceKey retired so
|
|
1303
|
+
* its late traffic stops moving the live pointers, and clears the per-instance routing
|
|
1304
|
+
* state the closed session held.
|
|
1305
|
+
*
|
|
1306
|
+
* Call ONLY from the explicit SDK close path (routes/resume.js, wasFreshKey===true) —
|
|
1307
|
+
* a random per-generation key is never re-created, so retirement is permanent and safe.
|
|
1308
|
+
* Never from a launch or initForWorkspace/resetForLiveRelaunch: a same-cwd sibling stays
|
|
1309
|
+
* LIVE and depends on its per-instance pointers surviving a relaunch.
|
|
1310
|
+
*/
|
|
1311
|
+
retireInstance(instKey) {
|
|
1312
|
+
if (typeof instKey !== 'string' || !/^ccv-[0-9a-f]+$/.test(instKey)) return;
|
|
1313
|
+
this._retiredInstances.add(instKey);
|
|
1314
|
+
// Cap the append-only set (random keys never collide with a future generation).
|
|
1315
|
+
if (this._retiredInstances.size > 64) this._retiredInstances.delete(this._retiredInstances.values().next().value);
|
|
1316
|
+
// The retired instance's own routing state: its metadata-less traffic must not route
|
|
1317
|
+
// to its old sid, and any held cold-start bucket must never flush into the new dir.
|
|
1318
|
+
const prior = this._currentSidByInstance.get(instKey);
|
|
1319
|
+
this._currentSidByInstance.delete(instKey);
|
|
1320
|
+
this._pendingNoSidByInstance.delete(instKey);
|
|
1321
|
+
if (prior && this._currentSid === prior.sid) this._currentSid = null;
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
/**
|
|
1325
|
+
* Release a CLOSED instance's per-instance routing state WITHOUT retiring the key
|
|
1326
|
+
* (2026-11, same-cwd sibling close). Unlike retireInstance this does NOT add the key to
|
|
1327
|
+
* `_retiredInstances`: a DETERMINISTIC cwd-derived key is re-created by a later normal
|
|
1328
|
+
* relaunch, so retiring it would permanently gate the legitimate rebuilt session. Only
|
|
1329
|
+
* clears the closed instance's per-instance pointer + cold-start bucket so its draining
|
|
1330
|
+
* traffic stops moving the live pointers. Used by the SDK close path for wasFreshKey=false.
|
|
1331
|
+
*/
|
|
1332
|
+
releaseInstance(instKey) {
|
|
1333
|
+
if (typeof instKey !== 'string' || !/^ccv-[0-9a-f]+$/.test(instKey)) return;
|
|
1334
|
+
const prior = this._currentSidByInstance.get(instKey);
|
|
1335
|
+
this._currentSidByInstance.delete(instKey);
|
|
1336
|
+
this._pendingNoSidByInstance.delete(instKey);
|
|
1337
|
+
if (prior && this._currentSid === prior.sid) this._currentSid = null;
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1112
1340
|
/** Flush pending queue writes (tests / graceful shutdown). */
|
|
1113
1341
|
async flush() {
|
|
1114
1342
|
await this._queue.flush();
|
package/server/proxy.js
CHANGED
|
@@ -136,12 +136,19 @@ export function startProxy() {
|
|
|
136
136
|
// req.url 是 origin-form 相对路径,new URL 需补基址,否则锚定判定落空到宽松正则。
|
|
137
137
|
const _reqPath = (() => { try { return new URL(req.url || '/', 'http://x').pathname; } catch { return req.url || ''; } })();
|
|
138
138
|
const _isUtility = /\/messages\/count_tokens$/.test(_reqPath) || /^\/api\/eval\/sdk-/.test(_reqPath);
|
|
139
|
+
// Per-session override: the spawned claude self-reports its instanceKey via
|
|
140
|
+
// x-ccv-instance; a bound session's proxy choice overrides the global one. This
|
|
141
|
+
// must stay consistent with the interceptor fetch hook's per-request rewrite.
|
|
142
|
+
const _instKey = (() => {
|
|
143
|
+
const v = findHeader(headers, 'x-ccv-instance');
|
|
144
|
+
return (typeof v === 'string' && /^ccv-[0-9a-f]+$/.test(v)) ? v : undefined;
|
|
145
|
+
})();
|
|
139
146
|
let roleProfile;
|
|
140
147
|
let _role; // live system 改写的 role 门(仅 main 生效);未分类 → undefined → main 语义
|
|
141
148
|
const _needClassify = body.length > 0 && isAnthropicApiPath(_reqPath) && !_isUtility;
|
|
142
149
|
// 角色分类在两种情况下都必须做:显式角色分配(选路)或 live system 已启用
|
|
143
150
|
// (否则默认配置下 subagent/teammate 会以 role=undefined 穿过 proxy 侧门被注入主 system)。
|
|
144
|
-
if (_needClassify && (interceptor.hasExplicitRoleAssignments() || liveSystemPromptEnabled())) {
|
|
151
|
+
if (_needClassify && (interceptor.hasExplicitRoleAssignments(_instKey) || liveSystemPromptEnabled())) {
|
|
145
152
|
let parsedBody = null;
|
|
146
153
|
try { parsedBody = JSON.parse(body.toString('utf8')); } catch { /* 非 JSON body → 保持 main 语义 */ }
|
|
147
154
|
if (parsedBody && typeof parsedBody === 'object') {
|
|
@@ -157,13 +164,13 @@ export function startProxy() {
|
|
|
157
164
|
_role = _agent
|
|
158
165
|
? (_agent.named ? 'teammate' : 'subagent')
|
|
159
166
|
: classifyProxyRole(parsedBody, {});
|
|
160
|
-
if (interceptor.hasExplicitRoleAssignments()) {
|
|
161
|
-
roleProfile = interceptor.getEffectiveRoleProfile(_role);
|
|
167
|
+
if (interceptor.hasExplicitRoleAssignments(_instKey)) {
|
|
168
|
+
roleProfile = interceptor.getEffectiveRoleProfile(_role, _instKey);
|
|
162
169
|
}
|
|
163
170
|
} catch (err) { reportSwallowed('proxy.role-classify', err); }
|
|
164
171
|
}
|
|
165
172
|
}
|
|
166
|
-
const originalBaseUrl = getOriginalBaseUrl(roleProfile);
|
|
173
|
+
const originalBaseUrl = getOriginalBaseUrl(roleProfile !== undefined ? roleProfile : interceptor.getEffectiveMainProfile(_instKey));
|
|
167
174
|
|
|
168
175
|
const fetchOptions = {
|
|
169
176
|
method: req.method,
|
|
@@ -185,7 +192,7 @@ export function startProxy() {
|
|
|
185
192
|
// 模型替换由重试引擎用 resolveProfileModel 纯函数完成(interceptor 对 trace 请求会再跑一次,幂等 no-op)。
|
|
186
193
|
// 非大模型 API 请求走原逻辑(同样用 x-cc-viewer-trace 让 interceptor 记录,但不经重试引擎)。
|
|
187
194
|
if (isAnthropicApiPath(fullUrl)) {
|
|
188
|
-
await handleLlmApiRequest(req, res, fullUrl, fetchOptions, body, proxyDispatcher, roleProfile, { role: _role, isUtility: _isUtility });
|
|
195
|
+
await handleLlmApiRequest(req, res, fullUrl, fetchOptions, body, proxyDispatcher, roleProfile, { role: _role, isUtility: _isUtility, instanceKey: _instKey });
|
|
189
196
|
return;
|
|
190
197
|
}
|
|
191
198
|
|
|
@@ -304,8 +311,9 @@ const _retryConfigGetter = () => interceptor._retryConfigState;
|
|
|
304
311
|
async function handleLlmApiRequest(req, res, fullUrl, fetchOptions, body, proxyDispatcher, roleProfile, liveCtx = {}) {
|
|
305
312
|
const statsEnabled = process.env.CCV_PROXY_STATS !== 'off';
|
|
306
313
|
const retryConfig = _retryConfigGetter(); // live binding:每请求取最新重试配置
|
|
307
|
-
// 角色解析后的有效 profile(上游/模型替换/统计归属)。undefined = 未分类 → 沿用 main 活跃 profile
|
|
308
|
-
|
|
314
|
+
// 角色解析后的有效 profile(上游/模型替换/统计归属)。undefined = 未分类 → 沿用 main 活跃 profile
|
|
315
|
+
// (会话有绑定时为该会话的 main,否则为全局 _activeProfile)。
|
|
316
|
+
const profile = roleProfile !== undefined ? roleProfile : (interceptor.getEffectiveMainProfile(liveCtx.instanceKey) || null);
|
|
309
317
|
|
|
310
318
|
// 清理可能的 trace 头(singleFetch 会重新加,避免旧值干扰);interceptor 会正常记录请求
|
|
311
319
|
// 同时清理 hop-by-hop / 传输编码头:body 已被 buffer 成完整 Buffer,
|