@adhdev/session-host-core 1.0.82-rc.33 → 1.0.82-rc.34
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/dist/index.d.mts +149 -3
- package/dist/index.d.ts +149 -3
- package/dist/index.js +199 -27
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +193 -27
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/cli-child-priority.ts +45 -9
- package/src/index.ts +4 -1
- package/src/ipc.ts +27 -13
- package/src/operator-recovery.ts +134 -0
- package/src/registry.ts +41 -0
- package/src/types.ts +24 -0
package/package.json
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
1
2
|
import * as os from 'node:os';
|
|
2
3
|
import { hiddenSpawn } from './process/hidden-spawn.js';
|
|
3
4
|
|
|
@@ -17,6 +18,36 @@ function setDarwinBackground(pid: number, onFailure: (error: unknown) => void):
|
|
|
17
18
|
});
|
|
18
19
|
}
|
|
19
20
|
|
|
21
|
+
const POSIX_NICE_BINARY = '/usr/bin/nice';
|
|
22
|
+
|
|
23
|
+
export interface NiceLaunch {
|
|
24
|
+
readonly command: string;
|
|
25
|
+
readonly args: string[];
|
|
26
|
+
/** True when the child will START at the lowered priority (spawnCliChild must not lower it again). */
|
|
27
|
+
readonly preApplied: boolean;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Launch through `nice -n <increment>` on macOS/Linux so the child runs at the
|
|
32
|
+
* lowered priority from its first instruction. `nice` execs the target in
|
|
33
|
+
* place: same pid, and every descendant inherits the niceness. This closes the
|
|
34
|
+
* spawn→setPriority race where a child forked before the post-spawn call and
|
|
35
|
+
* its early descendants escaped at NI=0. Windows (no nice) and shell-string
|
|
36
|
+
* launches keep the post-spawn path.
|
|
37
|
+
*/
|
|
38
|
+
export function niceLaunch(
|
|
39
|
+
command: string,
|
|
40
|
+
args: readonly string[],
|
|
41
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
42
|
+
platform: NodeJS.Platform = process.platform,
|
|
43
|
+
niceAvailable: () => boolean = () => fs.existsSync(POSIX_NICE_BINARY),
|
|
44
|
+
): NiceLaunch {
|
|
45
|
+
if (env[CLI_CHILD_NICE_ENV] === '0' || (platform !== 'darwin' && platform !== 'linux') || !command || !niceAvailable()) {
|
|
46
|
+
return { command, args: [...args], preApplied: false };
|
|
47
|
+
}
|
|
48
|
+
return { command: POSIX_NICE_BINARY, args: ['-n', String(CLI_CHILD_NICE_INCREMENT), command, ...args], preApplied: true };
|
|
49
|
+
}
|
|
50
|
+
|
|
20
51
|
interface PriorityDependencies {
|
|
21
52
|
platform: NodeJS.Platform;
|
|
22
53
|
getPriority: typeof os.getPriority;
|
|
@@ -36,6 +67,7 @@ export function createCliChildPriorityPolicy(deps: PriorityDependencies = {
|
|
|
36
67
|
spawnChild: () => T,
|
|
37
68
|
env: NodeJS.ProcessEnv = process.env,
|
|
38
69
|
logInfo: (message: string) => void = console.info,
|
|
70
|
+
opts: { preApplied?: boolean } = {},
|
|
39
71
|
): T {
|
|
40
72
|
const child = spawnChild();
|
|
41
73
|
const pid = child.pid;
|
|
@@ -48,15 +80,19 @@ export function createCliChildPriorityPolicy(deps: PriorityDependencies = {
|
|
|
48
80
|
logInfo(`[cli-child-priority] Could not apply CLI child scheduling (pid ${pid}); continuing: ${detail}`);
|
|
49
81
|
}
|
|
50
82
|
};
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
83
|
+
// Launched through niceLaunch: already lowered from birth; lowering again
|
|
84
|
+
// would stack a second increment.
|
|
85
|
+
if (!opts.preApplied) {
|
|
86
|
+
try {
|
|
87
|
+
const priority = deps.platform === 'win32'
|
|
88
|
+
? os.constants.priority.PRIORITY_BELOW_NORMAL
|
|
89
|
+
: Math.min(19, deps.getPriority(pid) + CLI_CHILD_NICE_INCREMENT);
|
|
90
|
+
deps.setPriority(pid, priority);
|
|
91
|
+
} catch (error) {
|
|
92
|
+
// EACCES/EPERM (policy/permissions) and ESRCH (already exited), as well
|
|
93
|
+
// as unexpected OS errors, are best effort. Never fail a CLI launch.
|
|
94
|
+
onFailure(error);
|
|
95
|
+
}
|
|
60
96
|
}
|
|
61
97
|
if (deps.platform === 'darwin' && env[CLI_CHILD_SCHEDULING_ENV] === 'darwin-bg') {
|
|
62
98
|
try { deps.setDarwinBackground?.(pid, onFailure); } catch (error) { onFailure(error); }
|
package/src/index.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
export { OPERATOR_RECOVERY_TARGET, recoveryTargetBytes, RecoveryOwnerAdmission, assertRecoveryLaunchIdentity, isRecoveryEndpoint } from './operator-recovery.js';
|
|
2
|
+
export type { RecoveryOwnerOperation, RecoveryOwnerGrant, RecoveryOwnerChallenge, RecoveryOwnerEnrollment, RecoveryHostBinding, RecoveryPhysicalProof } from './operator-recovery.js';
|
|
1
3
|
export type {
|
|
2
4
|
MeshWriterAssignment,
|
|
3
5
|
MeshWriterStopTarget,
|
|
@@ -24,6 +26,7 @@ export type {
|
|
|
24
26
|
SessionBufferSnapshot,
|
|
25
27
|
SessionClientType,
|
|
26
28
|
SessionHostDiagnostics,
|
|
29
|
+
SessionHostCensus,
|
|
27
30
|
SessionHostDuplicateSessionGroup,
|
|
28
31
|
SessionHostCategory,
|
|
29
32
|
SessionHostSurfaceKind,
|
|
@@ -53,7 +56,7 @@ export type {
|
|
|
53
56
|
|
|
54
57
|
export { SESSION_HOST_SUPPORTED_REQUEST_TYPES } from './types.js';
|
|
55
58
|
export { classifyTermination } from './termination.js';
|
|
56
|
-
export { CLI_CHILD_NICE_INCREMENT, CLI_CHILD_NICE_ENV, CLI_CHILD_SCHEDULING_ENV, createCliChildPriorityPolicy, spawnCliChild } from './cli-child-priority.js';
|
|
59
|
+
export { CLI_CHILD_NICE_INCREMENT, CLI_CHILD_NICE_ENV, CLI_CHILD_SCHEDULING_ENV, createCliChildPriorityPolicy, niceLaunch, spawnCliChild, type NiceLaunch } from './cli-child-priority.js';
|
|
57
60
|
export { hiddenSpawn as hiddenSpawnProcess } from './process/hidden-spawn.js';
|
|
58
61
|
|
|
59
62
|
export { DEFAULT_SESSION_RING_BUFFER_MAX_BYTES, SessionRingBuffer } from './buffer.js';
|
package/src/ipc.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as os from 'os';
|
|
2
2
|
import * as path from 'path';
|
|
3
3
|
import * as net from 'net';
|
|
4
|
+
import { createHash } from 'crypto';
|
|
4
5
|
import { generateUUID } from './uuid.js';
|
|
5
6
|
import { StringDecoder } from 'string_decoder';
|
|
6
7
|
import type {
|
|
@@ -41,6 +42,8 @@ export interface SessionHostEndpointOptions {
|
|
|
41
42
|
ipcKey?: string;
|
|
42
43
|
/** Test seam: override the platform the endpoint shape is derived for. */
|
|
43
44
|
platform?: NodeJS.Platform;
|
|
45
|
+
/** Test seam: override the temporary directory used for endpoint derivation. */
|
|
46
|
+
tmpDir?: string;
|
|
44
47
|
}
|
|
45
48
|
|
|
46
49
|
export function getDefaultSessionHostEndpoint(
|
|
@@ -62,10 +65,25 @@ export function getDefaultSessionHostEndpoint(
|
|
|
62
65
|
};
|
|
63
66
|
}
|
|
64
67
|
|
|
65
|
-
|
|
68
|
+
const endpoint: SessionHostEndpoint = {
|
|
66
69
|
kind: 'unix',
|
|
67
|
-
path: path.join(os.tmpdir(), `${appName}-session-host${suffix}.sock`),
|
|
70
|
+
path: path.join(options.tmpDir ?? os.tmpdir(), `${appName}-session-host${suffix}.sock`),
|
|
68
71
|
};
|
|
72
|
+
const limit = platform === 'linux' ? 108 : 104;
|
|
73
|
+
if (Buffer.byteLength(endpoint.path, 'utf8') + 1 <= limit) return endpoint;
|
|
74
|
+
|
|
75
|
+
// Only an endpoint that cannot fit sockaddr_un changes. In particular, do not
|
|
76
|
+
// probe, relocate or unlink a legacy socket: every valid short path stays
|
|
77
|
+
// identical, including discovery by already-running hosts. Parent, host and
|
|
78
|
+
// CLI share this pure derivation. Hash the complete legacy namespace (tmpdir,
|
|
79
|
+
// app name and config-derived ipcKey), plus uid for the shared /tmp directory.
|
|
80
|
+
// A full SHA-256 avoids truncating long/multibyte names into aliases. Keep the
|
|
81
|
+
// literal /tmp spelling: Darwin's /private/tmp realpath needlessly adds bytes.
|
|
82
|
+
const identity = JSON.stringify([endpoint.path, appName, rawKey, process.getuid?.() ?? null]);
|
|
83
|
+
const digest = createHash('sha256').update(identity, 'utf8').digest('hex');
|
|
84
|
+
const shortened: SessionHostEndpoint = { kind: 'unix', path: `/tmp/adhdev-sh-${digest}.sock` };
|
|
85
|
+
validateSessionHostEndpoint(shortened, platform);
|
|
86
|
+
return shortened;
|
|
69
87
|
}
|
|
70
88
|
|
|
71
89
|
function serializeEnvelope(envelope: SessionHostWireEnvelope): string {
|
|
@@ -344,14 +362,10 @@ export class SessionHostClient {
|
|
|
344
362
|
observerLagMs,
|
|
345
363
|
},
|
|
346
364
|
);
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
this.disconnectedSockets.add(socket);
|
|
352
|
-
try { socket.destroy(); } catch { /* noop */ }
|
|
353
|
-
reject(timeoutError);
|
|
354
|
-
}
|
|
365
|
+
// A deadline says nothing about socket or process liveness. Remove only
|
|
366
|
+
// this waiter; the parser safely discards its eventual late response.
|
|
367
|
+
this.requestWaiters.delete(requestId);
|
|
368
|
+
reject(timeoutError);
|
|
355
369
|
}, timeoutMs);
|
|
356
370
|
this.requestWaiters.set(requestId, {
|
|
357
371
|
resolve: (value) => { clearTimeout(timeout); resolve(value as SessionHostResponse<T>); },
|
|
@@ -507,14 +521,15 @@ export class SessionHostClient {
|
|
|
507
521
|
const deadline = Date.now() + timeoutMs;
|
|
508
522
|
const alreadyConnected = this.isConnected() && !this.connectPromise;
|
|
509
523
|
// A probe must also bound a connect/re-attach already in flight on this
|
|
510
|
-
// client; that task may have started with the normal 30s timeout.
|
|
524
|
+
// client; that task may have started with the normal 30s timeout. The
|
|
525
|
+
// request budget must not shorten or cancel that shared connection task.
|
|
511
526
|
if (options.timeoutMs !== undefined) {
|
|
512
527
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
513
528
|
const raceStartedAt = Date.now();
|
|
514
529
|
const raceStartedMonotonicAt = performance.now();
|
|
515
530
|
try {
|
|
516
531
|
await Promise.race([
|
|
517
|
-
this.connect(
|
|
532
|
+
this.connect(),
|
|
518
533
|
new Promise<never>((_resolve, reject) => {
|
|
519
534
|
timer = setTimeout(() => {
|
|
520
535
|
const actualElapsedMs = Math.max(0, Math.round(performance.now() - raceStartedMonotonicAt));
|
|
@@ -531,7 +546,6 @@ export class SessionHostClient {
|
|
|
531
546
|
},
|
|
532
547
|
);
|
|
533
548
|
reject(error);
|
|
534
|
-
this.disconnect(error);
|
|
535
549
|
}, timeoutMs);
|
|
536
550
|
}),
|
|
537
551
|
]);
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { createPublicKey, randomBytes, verify, type KeyObject } from 'node:crypto';
|
|
2
|
+
import { isAbsolute, basename } from 'node:path';
|
|
3
|
+
import { performance } from 'node:perf_hooks';
|
|
4
|
+
|
|
5
|
+
/** This association is owner asserted, never a historical native receipt. */
|
|
6
|
+
export const OPERATOR_RECOVERY_TARGET = Object.freeze({
|
|
7
|
+
association: 'operator_asserted' as const,
|
|
8
|
+
taskId: 'a1cdf3c0-f029-4d17-a8e9-db64e0a55501',
|
|
9
|
+
meshId: 'mesh_271444af883843e9b36c67155b87b22f',
|
|
10
|
+
attemptId: 'mesh_queue:mesh_271444af883843e9b36c67155b87b22f:a1cdf3c0-f029-4d17-a8e9-db64e0a55501:0',
|
|
11
|
+
generation: 0, dispatchNonce: 1,
|
|
12
|
+
deliveryId: 'dlv-7e259b34-b049-47ee-a466-2ca9c12bcff4',
|
|
13
|
+
ownerDaemonId: 'daemon_mach_4462a75330c548be9c2e74dd9f7f6ffb',
|
|
14
|
+
nodeId: 'node_d82de0cef9b042b6948986609e32142f',
|
|
15
|
+
workerDaemonId: 'daemon_mach_6733c865d60f432dbeb119a6875ee303',
|
|
16
|
+
sessionId: 'de321185-4ebc-40aa-8c6e-b4919e87fae3',
|
|
17
|
+
providerSessionId: '60806c79-7d77-4614-9fa6-e628533478ba',
|
|
18
|
+
namespace: '6a2ef3162182',
|
|
19
|
+
});
|
|
20
|
+
export const recoveryTargetBytes = JSON.stringify(OPERATOR_RECOVERY_TARGET);
|
|
21
|
+
/** Shared final admission guard for saved IDs, new aliases and provider argv.
|
|
22
|
+
* This is a permanent exact-target denial, independent of journal availability. */
|
|
23
|
+
export function assertRecoveryLaunchIdentity(value: unknown): void {
|
|
24
|
+
if (!value || typeof value !== 'object') return;
|
|
25
|
+
const identities = new Set(['sessionId', 'runtimeId', 'runtimeSessionId', 'providerSessionId',
|
|
26
|
+
'presetSessionKey', 'resumeSessionId', 'key']);
|
|
27
|
+
const nested = new Set(['options', 'meta', 'settings', 'settingsOverride', 'restartBinding', 'sessionBinding', 'launchCommand']);
|
|
28
|
+
for (const [key, field] of Object.entries(value)) {
|
|
29
|
+
if (identities.has(key) || ['args', 'cliArgs', 'cliArgsWithBrain'].includes(key)) {
|
|
30
|
+
const bytes = JSON.stringify(field)?.toLowerCase();
|
|
31
|
+
if (bytes?.includes(OPERATOR_RECOVERY_TARGET.sessionId) || bytes?.includes(OPERATOR_RECOVERY_TARGET.providerSessionId)) {
|
|
32
|
+
throw new Error('operator_recovery_fenced');
|
|
33
|
+
}
|
|
34
|
+
} else if (nested.has(key)) assertRecoveryLaunchIdentity(field);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
export type RecoveryOwnerOperation = 'anchor_recover' | 'fence_install' | 'witness_enroll';
|
|
38
|
+
export interface RecoveryOwnerGrant { readonly purpose: 'operator_recovery_v1'; readonly operation: RecoveryOwnerOperation }
|
|
39
|
+
export function isRecoveryEndpoint(endpoint: string): boolean {
|
|
40
|
+
return isAbsolute(endpoint) && basename(endpoint) === `adhdev-preview-session-host-${OPERATOR_RECOVERY_TARGET.namespace}.sock`;
|
|
41
|
+
}
|
|
42
|
+
export interface RecoveryOwnerChallenge { readonly message: string }
|
|
43
|
+
export interface RecoveryOwnerEnrollment {
|
|
44
|
+
/** Trusted boot dependency, provisioned outside delegated worker authority.
|
|
45
|
+
* Do not load this from daemon config, IPC arguments or an MCP credential. */
|
|
46
|
+
publicKey: string;
|
|
47
|
+
enrollmentId: string;
|
|
48
|
+
coordinatorBootId: string;
|
|
49
|
+
authEpoch: string;
|
|
50
|
+
verifyCurrent: () => boolean;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Signature possession authenticates the separately enrolled owner signer.
|
|
54
|
+
* This verifier does not enroll keys or assert user presence on their behalf. */
|
|
55
|
+
export class RecoveryOwnerAdmission {
|
|
56
|
+
private readonly key: KeyObject;
|
|
57
|
+
private readonly enrollment: Readonly<RecoveryOwnerEnrollment>;
|
|
58
|
+
private readonly pending = new Map<string, { deadline: number; operation: RecoveryOwnerOperation }>();
|
|
59
|
+
private readonly grants = new WeakMap<object, { deadline: number; operation: RecoveryOwnerOperation }>();
|
|
60
|
+
private lastNow = -Infinity;
|
|
61
|
+
constructor(enrollment: RecoveryOwnerEnrollment, private readonly clock = () => performance.now()) {
|
|
62
|
+
this.enrollment = Object.freeze({ ...enrollment });
|
|
63
|
+
if (!enrollment.enrollmentId || !enrollment.coordinatorBootId || !enrollment.authEpoch ||
|
|
64
|
+
typeof enrollment.verifyCurrent !== 'function') throw new Error('recovery_owner_enrollment_required');
|
|
65
|
+
this.key = createPublicKey(enrollment.publicKey);
|
|
66
|
+
if (this.key.asymmetricKeyType !== 'ed25519') throw new Error('recovery_owner_key_type');
|
|
67
|
+
}
|
|
68
|
+
private now(): number {
|
|
69
|
+
const n = this.clock();
|
|
70
|
+
if (!Number.isFinite(n) || n < this.lastNow || this.enrollment.verifyCurrent() !== true) {
|
|
71
|
+
this.pending.clear();
|
|
72
|
+
this.lastNow = Infinity; // A revocation or clock rollback cannot be undone.
|
|
73
|
+
throw new Error('recovery_owner_revoked');
|
|
74
|
+
}
|
|
75
|
+
this.lastNow = n;
|
|
76
|
+
return n;
|
|
77
|
+
}
|
|
78
|
+
challenge(operation: RecoveryOwnerOperation = 'anchor_recover'): RecoveryOwnerChallenge {
|
|
79
|
+
if (!['anchor_recover', 'fence_install', 'witness_enroll'].includes(operation)) throw new Error('recovery_owner_operation_rejected');
|
|
80
|
+
const now = this.now();
|
|
81
|
+
for (const [message, entry] of this.pending) if (entry.deadline <= now) this.pending.delete(message);
|
|
82
|
+
if (this.pending.size >= 16) throw new Error('recovery_owner_challenge_limit');
|
|
83
|
+
const message = JSON.stringify(['operator_recovery_v1', operation, recoveryTargetBytes,
|
|
84
|
+
this.enrollment.enrollmentId, this.enrollment.coordinatorBootId, this.enrollment.authEpoch,
|
|
85
|
+
randomBytes(32).toString('hex')]);
|
|
86
|
+
this.pending.set(message, { deadline: now + 30_000, operation });
|
|
87
|
+
return Object.freeze({ message });
|
|
88
|
+
}
|
|
89
|
+
authorize(message: string, signature: string): RecoveryOwnerGrant {
|
|
90
|
+
const now = this.now();
|
|
91
|
+
const entry = this.pending.get(message);
|
|
92
|
+
this.pending.delete(message); // Every verification attempt burns the challenge.
|
|
93
|
+
if (!entry || now >= entry.deadline || !/^[a-f0-9]{128}$/.test(signature) ||
|
|
94
|
+
!verify(null, Buffer.from(message), this.key, Buffer.from(signature, 'hex'))) {
|
|
95
|
+
throw new Error('recovery_owner_signature_rejected');
|
|
96
|
+
}
|
|
97
|
+
const grant = Object.freeze({ purpose: 'operator_recovery_v1' as const, operation: entry.operation });
|
|
98
|
+
this.grants.set(grant, entry);
|
|
99
|
+
return grant;
|
|
100
|
+
}
|
|
101
|
+
assertGrant(grant: unknown): asserts grant is RecoveryOwnerGrant {
|
|
102
|
+
const now = this.now();
|
|
103
|
+
const entry = typeof grant === 'object' && grant !== null ? this.grants.get(grant) : undefined;
|
|
104
|
+
if (!entry || now >= entry.deadline) throw new Error('recovery_owner_grant_rejected');
|
|
105
|
+
}
|
|
106
|
+
/** Burn synchronously before any work or await. The private continuation
|
|
107
|
+
* rechecks the ORIGINAL deadline and revocation; it cannot mint a new grant. */
|
|
108
|
+
reserve(grant: unknown, operation: RecoveryOwnerOperation): () => void {
|
|
109
|
+
this.assertGrant(grant);
|
|
110
|
+
const entry = this.grants.get(grant as object)!;
|
|
111
|
+
this.grants.delete(grant as object);
|
|
112
|
+
if (entry.operation !== operation) throw new Error('recovery_owner_operation_rejected');
|
|
113
|
+
return () => {
|
|
114
|
+
if (this.now() >= entry.deadline) throw new Error('recovery_owner_grant_rejected');
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
consume(grant: unknown): void {
|
|
118
|
+
this.assertGrant(grant);
|
|
119
|
+
this.grants.delete(grant as object);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export interface RecoveryHostBinding {
|
|
124
|
+
namespace: string; endpoint: string; hostBootId: string; workerDaemonId: string;
|
|
125
|
+
}
|
|
126
|
+
export interface RecoveryPhysicalProof extends RecoveryHostBinding {
|
|
127
|
+
protocol: 1;
|
|
128
|
+
verdict: 'ABSENT' | 'LIVE' | 'UNKNOWN';
|
|
129
|
+
reason: string;
|
|
130
|
+
nonce: string;
|
|
131
|
+
fenceDigest: string;
|
|
132
|
+
sessionId: string;
|
|
133
|
+
providerSessionId: string;
|
|
134
|
+
}
|
package/src/registry.ts
CHANGED
|
@@ -7,6 +7,7 @@ import type {
|
|
|
7
7
|
ReleaseWritePayload,
|
|
8
8
|
SessionAttachedClient,
|
|
9
9
|
SessionHostRecord,
|
|
10
|
+
SessionHostRequest,
|
|
10
11
|
SessionTermination,
|
|
11
12
|
} from './types.js';
|
|
12
13
|
import { SessionRingBuffer } from './buffer.js';
|
|
@@ -125,11 +126,51 @@ export class SessionHostRegistry {
|
|
|
125
126
|
.sort((a, b) => b.lastActivityAt - a.lastActivityAt);
|
|
126
127
|
}
|
|
127
128
|
|
|
129
|
+
/** No launch bodies are cloned. Unknown role evidence stays conservative. */
|
|
130
|
+
getSessionCensus(sessionIds: string[]): { liveSessionIds: string[]; hasOtherAssistantCandidates: boolean } {
|
|
131
|
+
if (!Array.isArray(sessionIds) || sessionIds.length > 128
|
|
132
|
+
|| sessionIds.some(id => typeof id !== 'string' || id.length === 0 || id.length > 256)) {
|
|
133
|
+
throw new Error('Invalid session census: at most 128 identities of 256 characters');
|
|
134
|
+
}
|
|
135
|
+
const requested = new Set(sessionIds);
|
|
136
|
+
const liveSessionIds: string[] = [];
|
|
137
|
+
let hasOtherAssistantCandidates = false;
|
|
138
|
+
for (const { record } of this.sessions.values()) {
|
|
139
|
+
if (record.category !== 'cli' || record.termination
|
|
140
|
+
|| !['starting', 'running', 'stopping', 'interrupted'].includes(record.lifecycle)) continue;
|
|
141
|
+
if (requested.has(record.sessionId)) liveSessionIds.push(record.sessionId);
|
|
142
|
+
else {
|
|
143
|
+
const launch = record.meta?.launchRecord as { launchedBy?: unknown; roleLaunch?: { role?: unknown } } | undefined;
|
|
144
|
+
// This is uncertainty, never positive provenance or permission to attach.
|
|
145
|
+
// A role-marked writer created since the caller's disk scan must still
|
|
146
|
+
// prevent a duplicate, without returning any of its user-authored data.
|
|
147
|
+
if (record.meta?.assistant === true || launch?.launchedBy === 'assistant' || launch?.roleLaunch?.role === 'assistant') {
|
|
148
|
+
hasOtherAssistantCandidates = true;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return { liveSessionIds, hasOtherAssistantCandidates };
|
|
153
|
+
}
|
|
154
|
+
|
|
128
155
|
getSession(sessionId: string): SessionHostRecord | null {
|
|
129
156
|
const state = this.sessions.get(sessionId);
|
|
130
157
|
return state ? this.cloneRecord(state.record) : null;
|
|
131
158
|
}
|
|
132
159
|
|
|
160
|
+
attachClientIfIncarnation(payload: Extract<SessionHostRequest, { type: 'attach_session_if_incarnation' }>['payload']): SessionHostRecord {
|
|
161
|
+
const record = this.requireSession(payload.sessionId).record;
|
|
162
|
+
const expected = payload.expectedIncarnation;
|
|
163
|
+
if (!expected || expected.sessionId !== record.sessionId
|
|
164
|
+
|| typeof expected.runtimeKey !== 'string' || !expected.runtimeKey
|
|
165
|
+
|| !Number.isFinite(expected.startedAt) || expected.startedAt <= 0
|
|
166
|
+
|| expected.runtimeKey !== record.runtimeKey || expected.startedAt !== record.startedAt) {
|
|
167
|
+
throw new Error(`Runtime not found for session: ${payload.sessionId} (incarnation changed)`);
|
|
168
|
+
}
|
|
169
|
+
// No await between comparison and mutation; a failed pin cannot evict an
|
|
170
|
+
// existing daemon, clear its owner, or grant this client an attachment.
|
|
171
|
+
return this.attachClient(payload);
|
|
172
|
+
}
|
|
173
|
+
|
|
133
174
|
attachClient(payload: AttachSessionPayload): SessionHostRecord {
|
|
134
175
|
const state = this.requireSession(payload.sessionId);
|
|
135
176
|
const now = Date.now();
|
package/src/types.ts
CHANGED
|
@@ -246,6 +246,17 @@ export interface UpdateSessionMetaPayload {
|
|
|
246
246
|
replace?: boolean;
|
|
247
247
|
}
|
|
248
248
|
|
|
249
|
+
/** Bounded liveness check for identities whose provenance the caller already holds.
|
|
250
|
+
* No launch arguments, metadata, snapshots or diagnostic log bodies cross IPC. */
|
|
251
|
+
export interface SessionHostCensus {
|
|
252
|
+
hostStartedAt: number;
|
|
253
|
+
endpoint: string;
|
|
254
|
+
hostEntryPath?: string;
|
|
255
|
+
liveSessionIds: string[];
|
|
256
|
+
/** A live role-marked writer outside the caller's persisted identities. */
|
|
257
|
+
hasOtherAssistantCandidates: boolean;
|
|
258
|
+
}
|
|
259
|
+
|
|
249
260
|
export interface GetHostDiagnosticsPayload {
|
|
250
261
|
includeSessions?: boolean;
|
|
251
262
|
limit?: number;
|
|
@@ -355,11 +366,16 @@ export interface HostUpgradeLeasePayload {
|
|
|
355
366
|
}
|
|
356
367
|
|
|
357
368
|
export type SessionHostRequest =
|
|
369
|
+
| { type: 'prepare_operator_recovery_fence_v1'; payload?: {} }
|
|
370
|
+
| { type: 'install_operator_recovery_fence_v1'; payload: { message: string; signature: string } }
|
|
371
|
+
| { type: 'attest_operator_recovery_v1'; payload: { nonce: string; fenceDigest: string } }
|
|
372
|
+
| { type: 'get_operator_recovery_coverage_v1'; payload: { nonce: string } }
|
|
358
373
|
| { type: 'get_upgrade_lease'; payload?: {} }
|
|
359
374
|
| { type: 'acquire_upgrade_lease'; payload: HostUpgradeLeasePayload }
|
|
360
375
|
| { type: 'release_upgrade_lease'; payload: HostUpgradeLeasePayload }
|
|
361
376
|
| { type: 'create_session'; payload: CreateSessionPayload }
|
|
362
377
|
| { type: 'attach_session'; payload: AttachSessionPayload }
|
|
378
|
+
| { type: 'attach_session_if_incarnation'; payload: AttachSessionPayload & { expectedIncarnation: { sessionId: string; runtimeKey: string; startedAt: number } } }
|
|
363
379
|
| { type: 'detach_session'; payload: DetachSessionPayload }
|
|
364
380
|
| { type: 'send_input'; payload: SendInputPayload }
|
|
365
381
|
| { type: 'send_input_if_seq'; payload: SendInputIfSeqPayload }
|
|
@@ -380,17 +396,24 @@ export type SessionHostRequest =
|
|
|
380
396
|
| { type: 'send_signal'; payload: SendSignalPayload }
|
|
381
397
|
| { type: 'restart_session'; payload: RestartSessionPayload }
|
|
382
398
|
| { type: 'prune_duplicate_sessions'; payload?: PruneDuplicateSessionsPayload }
|
|
399
|
+
| { type: 'get_session_census'; payload: { sessionIds: string[] } }
|
|
383
400
|
| { type: 'get_session'; payload: { sessionId: string } }
|
|
384
401
|
| { type: 'list_sessions'; payload?: { activeOnly?: boolean } };
|
|
385
402
|
|
|
386
403
|
export type SessionHostRequestType = SessionHostRequest['type'];
|
|
387
404
|
|
|
388
405
|
export const SESSION_HOST_SUPPORTED_REQUEST_TYPES: readonly SessionHostRequestType[] = [
|
|
406
|
+
'prepare_operator_recovery_fence_v1',
|
|
407
|
+
'install_operator_recovery_fence_v1',
|
|
408
|
+
'attest_operator_recovery_v1',
|
|
409
|
+
'get_operator_recovery_coverage_v1',
|
|
389
410
|
'get_upgrade_lease',
|
|
390
411
|
'acquire_upgrade_lease',
|
|
391
412
|
'release_upgrade_lease',
|
|
392
413
|
'create_session',
|
|
393
414
|
'attach_session',
|
|
415
|
+
// Distinct request kind: old hosts must refuse instead of ignoring a pin.
|
|
416
|
+
'attach_session_if_incarnation',
|
|
394
417
|
'detach_session',
|
|
395
418
|
'send_input',
|
|
396
419
|
'send_input_if_seq',
|
|
@@ -411,6 +434,7 @@ export const SESSION_HOST_SUPPORTED_REQUEST_TYPES: readonly SessionHostRequestTy
|
|
|
411
434
|
'send_signal',
|
|
412
435
|
'restart_session',
|
|
413
436
|
'prune_duplicate_sessions',
|
|
437
|
+
'get_session_census',
|
|
414
438
|
'get_session',
|
|
415
439
|
'list_sessions',
|
|
416
440
|
];
|