rig-review 2.0.0 → 2.2.0

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.
@@ -20,7 +20,7 @@ import { createRequirementsCheck } from './requirements-run.ts';
20
20
  import { REQUIREMENTS_LIMIT, RequirementsError } from './requirements.ts';
21
21
  import { createEnvironmentCheck, ENVIRONMENT_CHECK_LIMIT, EnvironmentCheckError } from './environment-check.ts';
22
22
  import { renderCompareHtml } from './compare-html.ts';
23
- import { createLiveLifecycle, LIVE_PATH, type LiveExitInfo, type UpgradableServer } from './live-lifecycle.ts';
23
+ import { createLiveLifecycle, LIVE_PATH, type LiveExitInfo, type LiveLifecycle, type UpgradableServer } from './live-lifecycle.ts';
24
24
 
25
25
  const headers={'X-Content-Type-Options':'nosniff','Cache-Control':'no-store','Content-Security-Policy':"default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; media-src 'self'; frame-src 'self'; connect-src 'self'; font-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",'Referrer-Policy':'no-referrer'};
26
26
  const MALFORMED=new Set(['REBUILD_REQUEST_INVALID','DENSITY_STRIP_REQUEST_INVALID','DENSITY_STRIP_FIELD','MESH_PATCH_SCOPE','EDIT_PATCH_INVALID','EDIT_PATCH_OP_UNKNOWN','EDIT_PATCH_POINTER_INVALID','EDIT_PATCH_CMD_UNKNOWN','EDIT_PATCH_ARG_UNKNOWN','BONES_OP_OUT_OF_SCOPE','RETARGET_REQUEST_INVALID']);
@@ -43,9 +43,32 @@ function serveAsset(req:Request,path:string):Response{
43
43
  return new Response(req.method==='HEAD'?null:file,{headers:{...assetHeaders,'Content-Length':String(size)}});
44
44
  }
45
45
  /** `capability` (open workers and foreground CLI serving) gates every non-GET request; tests may omit it. */
46
- export async function startCompareServer(p:ComparePackage,options:{port?:number;stateDir?:string;open?:OpenIdentity;activity?:()=>void;control?:ControlIdentity;capability?:string;cwd?:string;stripConcurrency?:number;graceMs?:number;unopenedTimeoutMs?:number;exitOnClose?:boolean;onClose?:(info:LiveExitInfo)=>void|Promise<void>;log?:(line:string)=>void}={}){
46
+ export interface CompareServerOptions {
47
+ port?: number;
48
+ stateDir?: string;
49
+ open?: OpenIdentity;
50
+ activity?: () => void;
51
+ control?: ControlIdentity;
52
+ capability?: string;
53
+ cwd?: string;
54
+ stripConcurrency?: number;
55
+ graceMs?: number;
56
+ unopenedTimeoutMs?: number;
57
+ exitOnClose?: boolean;
58
+ onClose?: (info: LiveExitInfo) => void | Promise<void>;
59
+ log?: (line: string) => void;
60
+ }
61
+
62
+ export interface CompareRequestContextOptions extends CompareServerOptions {
63
+ lifecycle?: LiveLifecycle;
64
+ bundle?: Blob;
65
+ stopServer?: () => void | Promise<void>;
66
+ }
67
+
68
+ /** Comparison-scoped routes without a listener. An injected lifecycle belongs to its caller. */
69
+ export async function createCompareRequestContext(p: ComparePackage, options: CompareRequestContextOptions = {}) {
47
70
  const stageParts=stagePartsRoutes({a:p.a,b:p.b});
48
- const bundle=await buildWeb('compare');
71
+ const bundle=options.bundle??await buildWeb('compare');
49
72
  const frames=referenceFrameIndex(p.referencePath,p.response.binding.reference.sha256,p.response.sourceHash);
50
73
  const stateDir=options.stateDir??process.env.RIG_REVIEW_STATE_DIR??join(homedir(),'.local','state','rig-c-review');
51
74
  const makeSideTools=(side:'a'|'b',pkg:ReviewPackage)=>{
@@ -59,16 +82,17 @@ export async function startCompareServer(p:ComparePackage,options:{port?:number;
59
82
  };
60
83
  const sideTools={a:makeSideTools('a',p.a),b:makeSideTools('b',p.b)};
61
84
  const control=options.control?createControlServer({identity:options.control,sourceHash:p.response.sourceHash,mode:'compare',unchanged:()=>assertCompareUnchanged(p),activity:options.activity}):null;
62
- let rawStop:((closeActiveConnections?:boolean)=>void)|null=null;
63
- const live=createLiveLifecycle({
85
+ const busy=()=>sideTools.a.busy()||sideTools.b.busy();
86
+ const ownsLifecycle=options.lifecycle===undefined;
87
+ const live=options.lifecycle??createLiveLifecycle({
64
88
  label:'review compare',
65
89
  graceMs:options.graceMs,
66
90
  unopenedTimeoutMs:options.unopenedTimeoutMs,
67
91
  exitOnClose:options.exitOnClose,
68
92
  onClose:options.onClose,
69
93
  log:options.log,
70
- busy:()=>sideTools.a.busy()||sideTools.b.busy(),
71
- stopServer:()=>{rawStop?.(true);},
94
+ busy,
95
+ stopServer:options.stopServer,
72
96
  });
73
97
  const handle=async(req:Request,port:number|undefined,srv:UpgradableServer):Promise<Response|undefined>=>{try{
74
98
  const url=new URL(req.url),origin=`http://127.0.0.1:${port}`;
@@ -174,8 +198,22 @@ export async function startCompareServer(p:ComparePackage,options:{port?:number;
174
198
  return json({error:'Not found'},404);
175
199
  } finally { live.onRequestEnd(url.pathname); }
176
200
  }catch(e){const message=e instanceof Error?e.message:'Request failed';return json({error:message},message.includes('inputs changed')?409:400);}};
177
- const server=Bun.serve({hostname:'127.0.0.1',port:options.port??4317,websocket:live.websocket,async fetch(req,srv){const res=await handle(req,srv.port,srv);if(!res)return undefined as unknown as Response;return stampOpen(req,res,options.open);}});
201
+ return {
202
+ live,
203
+ busy,
204
+ async handle(req: Request, port: number | undefined, srv: UpgradableServer): Promise<Response | undefined> {
205
+ const response=await handle(req,port,srv);
206
+ return response?stampOpen(req,response,options.open):undefined;
207
+ },
208
+ stop() { if(ownsLifecycle)live.stop(); },
209
+ };
210
+ }
211
+
212
+ export async function startCompareServer(p: ComparePackage, options: CompareServerOptions = {}) {
213
+ let rawStop:((closeActiveConnections?:boolean)=>void)|null=null;
214
+ const context=await createCompareRequestContext(p,{...options,stopServer:()=>{rawStop?.(true);}});
215
+ const server=Bun.serve({hostname:'127.0.0.1',port:options.port??4317,websocket:context.live.websocket,async fetch(req,srv){return await context.handle(req,srv.port,srv) as Response;}});
178
216
  rawStop=server.stop.bind(server);
179
- server.stop=((closeActiveConnections?:boolean)=>{live.stop();return rawStop!(closeActiveConnections);}) as typeof server.stop;
180
- return Object.assign(server,{live});
217
+ server.stop=((closeActiveConnections?:boolean)=>{context.stop();return rawStop!(closeActiveConnections);}) as typeof server.stop;
218
+ return Object.assign(server,{live:context.live});
181
219
  }
package/src/front.ts CHANGED
@@ -90,7 +90,7 @@ export function frontRoute(mode:'single'|'compare',method:string,path:string):Ro
90
90
  if(/^\/api\/environment-check\/[a-f0-9]{64}$/.test(toolPath))return read?get:null;
91
91
  return null;
92
92
  }
93
- async function boundedBody(req:Request,limit:number,timeoutMs=10000):Promise<ArrayBuffer>{
93
+ export async function boundedBody(req:Request,limit:number,timeoutMs=10000):Promise<ArrayBuffer>{
94
94
  if(!/^application\/json(?:\s*;|$)/i.test(req.headers.get('content-type')??''))throw new Error('FRONT_JSON_REQUIRED');
95
95
  const declared=req.headers.get('content-length');if(declared!==null&&(!/^\d+$/.test(declared)||Number(declared)>limit))throw new Error('FRONT_BODY_LIMIT');
96
96
  if(!req.body)throw new Error('FRONT_JSON_REQUIRED');const reader=req.body.getReader();let timer:ReturnType<typeof setTimeout>|undefined;
@@ -0,0 +1,60 @@
1
+ import type {OpenInputs} from './open.ts';
2
+
3
+ export const WORKSPACE_SCHEMA = 'rig-review-open-workspace/1';
4
+ export const WORKSPACE_TARGETS_SCHEMA = 'rig-review-open-targets/1';
5
+ export const WORKSPACE_VISIBILITY_SCHEMA = 'rig-review-workspace-visibility/1';
6
+ export const WORKSPACE_READY_SCHEMA = 'rig-review-workspace-ready/1';
7
+ export const WORKSPACE_TARGET_DOMAIN = 'rig-review-target/1';
8
+ export const WORKSPACE_TARGET_LIMIT = 32;
9
+ export const WORKSPACE_SOCKET_LIMIT = 64;
10
+ export const WORKSPACE_BODY_LIMIT = 64 * 1024;
11
+ export const WORKSPACE_REGISTRATION_QUEUE = 8;
12
+
13
+ export interface WorkspaceDesignation {
14
+ key: string;
15
+ contentHash: string;
16
+ inputs: OpenInputs;
17
+ cwd: string;
18
+ viewOnly: boolean;
19
+ }
20
+
21
+ export interface WorkspaceRecord {
22
+ schema: typeof WORKSPACE_SCHEMA;
23
+ incarnation: string;
24
+ pid: number;
25
+ uid: number;
26
+ origin: string;
27
+ installation: string;
28
+ fingerprint: string;
29
+ runtime: string;
30
+ registrationCapability: string;
31
+ ownerCapability: string;
32
+ }
33
+
34
+ export interface WorkspaceStoredTarget {
35
+ designation: WorkspaceDesignation;
36
+ controlToken?: string;
37
+ }
38
+
39
+ export interface WorkspaceRegistry {
40
+ schema: typeof WORKSPACE_TARGETS_SCHEMA;
41
+ incarnation: string;
42
+ targets: WorkspaceStoredTarget[];
43
+ }
44
+
45
+ export interface WorkspaceTargetView {
46
+ key: string;
47
+ contentHash: string;
48
+ title: string;
49
+ mode: 'single' | 'compare';
50
+ animation: string | null;
51
+ viewOnly: boolean;
52
+ unavailable: string | null;
53
+ entry: string;
54
+ }
55
+
56
+ export interface WorkspaceList {
57
+ schema: typeof WORKSPACE_SCHEMA;
58
+ incarnation: string;
59
+ targets: WorkspaceTargetView[];
60
+ }
@@ -0,0 +1,121 @@
1
+ import {spawn} from 'node:child_process';
2
+ import {randomUUID} from 'node:crypto';
3
+ import {open, readFile, unlink} from 'node:fs/promises';
4
+ import {join} from 'node:path';
5
+ import {appRoot} from './build.ts';
6
+ import {frontPort} from './front.ts';
7
+ import {acquireClaim, defaultStateDir, openFingerprint, prepareOpenTarget, readOpenStatus, releaseClaim,
8
+ type OpenInputs, type OpenOptions} from './open.ts';
9
+ import {canonicalStatePath} from './state-dir.ts';
10
+ import {assertPrivate, parseRegistry, probeWorkspace, readPrivate, targetCapability, workspaceDirectory, workspaceError, writePrivate} from './open-workspace-state.ts';
11
+ import {WORKSPACE_BODY_LIMIT, WORKSPACE_SCHEMA, type WorkspaceDesignation, type WorkspaceRecord} from './open-workspace-contract.ts';
12
+
13
+ async function register(record: WorkspaceRecord, targets: WorkspaceDesignation[]) {
14
+ const text = JSON.stringify({schema: WORKSPACE_SCHEMA, incarnation: record.incarnation, targets});
15
+ if (Buffer.byteLength(text) > WORKSPACE_BODY_LIMIT) throw workspaceError('WORKSPACE_BODY_LIMIT');
16
+ const response = await fetch(record.origin + '/workspace/api/register', {
17
+ method: 'POST', redirect: 'error', signal: AbortSignal.timeout(20_000),
18
+ headers: {'Content-Type': 'application/json', Authorization: 'Bearer ' + record.registrationCapability}, body: text,
19
+ });
20
+ const value = await readOpenStatus(response, 20_000) as {error?: string; schema?: string; incarnation?: string};
21
+ if (!response.ok) throw workspaceError(value.error?.startsWith('WORKSPACE_') ? value.error : 'WORKSPACE_REGISTRATION_REFUSED');
22
+ if (value.schema !== WORKSPACE_SCHEMA || value.incarnation !== record.incarnation) throw workspaceError('WORKSPACE_HOST_MISMATCH');
23
+ }
24
+
25
+ /** Launchers exchange designated package data, never callbacks or human acts. */
26
+ export async function openWorkspace(inputs: readonly OpenInputs[], options: OpenOptions & {foreground?: boolean} = {}) {
27
+ const fingerprint = await openFingerprint();
28
+ const prepared = [];
29
+ for (const input of inputs) prepared.push(await prepareOpenTarget(input, options, fingerprint));
30
+ if (!prepared.length || inputs.some(input => input.direct)) throw workspaceError('WORKSPACE_REQUEST_INVALID');
31
+ const stateDir = canonicalStatePath(options.stateDir ?? defaultStateDir());
32
+ const designations: WorkspaceDesignation[] = prepared.map(target => ({key: target.key,
33
+ contentHash: target.package.contentHash, cwd: target.cwd, viewOnly: target.viewOnly,
34
+ inputs: {...target.package.inputs, viewOnly: target.viewOnly}}));
35
+ if (Buffer.byteLength(JSON.stringify(designations)) > WORKSPACE_BODY_LIMIT - 256) throw workspaceError('WORKSPACE_BODY_LIMIT');
36
+ const directory = await workspaceDirectory(stateDir), port = frontPort(options.frontPort);
37
+ const nonce = randomUUID();
38
+ const reuse = () => probeWorkspace(directory, fingerprint, port);
39
+ const ready = await reuse();
40
+ const acquired = ready ? {row: ready} : await acquireClaim(directory, 'host', nonce, reuse,
41
+ performance.now() + 20_000, 'WORKSPACE_START_BUSY');
42
+ let child: ReturnType<typeof spawn> | undefined, handedOff = false, request: string | undefined;
43
+ let owner: Awaited<ReturnType<typeof import('./open-workspace.ts').startOpenWorkspace>> | undefined;
44
+ let interrupted = false;
45
+ const stopOwner = () => {interrupted = true; void owner!.stop().catch(() => {});};
46
+ const detach = () => {process.removeListener('SIGINT', stopOwner); process.removeListener('SIGTERM', stopOwner);};
47
+ try {
48
+ let record: WorkspaceRecord;
49
+ const reused = 'row' in acquired;
50
+ if ('row' in acquired) record = acquired.row;
51
+ else if (options.foreground) {
52
+ const {startOpenWorkspace} = await import('./open-workspace.ts');
53
+ owner = await startOpenWorkspace({stateDir, fingerprint, port, idleMs: options.idleMs, graceMs: options.graceMs});
54
+ process.once('SIGINT', stopOwner); process.once('SIGTERM', stopOwner);
55
+ record = owner.record;
56
+ } else {
57
+ request = join(directory, nonce + '.request.json');
58
+ await writePrivate(request, {schema: WORKSPACE_SCHEMA, stateDir, fingerprint, port,
59
+ ...(options.idleMs !== undefined ? {idleMs: options.idleMs} : {}),
60
+ ...(options.graceMs !== undefined ? {graceMs: options.graceMs} : {})});
61
+ const logPath = join(directory, nonce + '.log');
62
+ const log = await open(logPath, 'a', 0o600);
63
+ try {
64
+ child = spawn(process.execPath, [join(appRoot, 'src/open-workspace-worker.ts'), request],
65
+ {cwd: directory, detached: true, stdio: ['ignore', log.fd, log.fd], env: process.env});
66
+ child.unref();
67
+ } finally {await log.close();}
68
+ let failure = false;
69
+ child.on('error', () => {failure = true;});
70
+ child.on('exit', () => {failure = true;});
71
+ const deadline = performance.now() + 20_000;
72
+ for (;;) {
73
+ const current = await reuse();
74
+ if (current) {record = current; break;}
75
+ if (failure) {
76
+ const diagnostic = (await readFile(logPath, 'utf8')).trim();
77
+ const occupied = `FRONT_PORT_BUSY: 127.0.0.1:${port} is held by another listener; use --direct (or set RIG_REVIEW_FRONT_PORT)`;
78
+ const safeCodes = ['WORKSPACE_REQUEST_INVALID', 'WORKSPACE_STATE_INVALID', 'WORKSPACE_BODY_LIMIT', 'WORKSPACE_START_REFUSED'];
79
+ throw workspaceError(diagnostic === occupied || safeCodes.includes(diagnostic) ? diagnostic : 'WORKSPACE_START_REFUSED');
80
+ }
81
+ if (performance.now() >= deadline) throw workspaceError('WORKSPACE_START_TIMEOUT');
82
+ await Bun.sleep(30);
83
+ }
84
+ }
85
+ try {await register(record, designations);}
86
+ catch (error) {if (!interrupted) throw error;}
87
+ handedOff = true;
88
+ const waitForExit = owner ? async () => {
89
+ try {await owner!.live.exited; await owner!.stop();}
90
+ finally {detach();}
91
+ } : undefined;
92
+ return {url: record.origin + '/?workspace=' + record.incarnation + '#cap=' + record.ownerCapability,
93
+ reused, prepared, interrupted, waitForExit};
94
+ } catch (error) {
95
+ if (owner) {detach(); await owner.stop().catch(() => {});}
96
+ throw error;
97
+ } finally {
98
+ if (child && !handedOff && child.exitCode === null && child.signalCode === null) child.kill('SIGTERM');
99
+ if ('claim' in acquired) await releaseClaim(acquired.claim, nonce);
100
+ if (request) await unlink(request).catch(error => {if (error.code !== 'ENOENT') throw error;});
101
+ }
102
+ }
103
+
104
+ /** Trusted control CLI resolves only its exact opted-in target after authenticating the live workspace. */
105
+ export async function workspaceControlLocator(stateDir: string, key: string) {
106
+ const directory = join(canonicalStatePath(stateDir), 'owner-workspace');
107
+ try {await assertPrivate(directory, true);}
108
+ catch (error) {if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error;}
109
+ const value = await readPrivate(join(directory, 'host.json'));
110
+ if (!value) return null;
111
+ const record = await probeWorkspace(directory, await openFingerprint());
112
+ if (!record) return null;
113
+ const registry = await readPrivate(join(directory, 'targets.json'));
114
+ if (!registry) throw workspaceError('WORKSPACE_STATE_INVALID');
115
+ const stored = parseRegistry(registry);
116
+ if (stored.incarnation !== record.incarnation) throw workspaceError('WORKSPACE_HOST_MISMATCH');
117
+ const target = stored.targets.find(target => target.designation.key === key);
118
+ if (!target?.controlToken) return null;
119
+ return {origin: record.origin, prefix: '/instances/' + key, controlToken: target.controlToken,
120
+ capability: targetCapability(record.ownerCapability, record.incarnation, key)};
121
+ }
@@ -0,0 +1,125 @@
1
+ import {createHmac, randomUUID} from 'node:crypto';
2
+ import {lstat, mkdir, rename, unlink, writeFile} from 'node:fs/promises';
3
+ import {isAbsolute, join} from 'node:path';
4
+ import {appRoot} from './build.ts';
5
+ import {readOpenStatus, running, smallJson} from './open.ts';
6
+ import {canonicalStatePath} from './state-dir.ts';
7
+ import {capabilityPattern} from './open-protocol.ts';
8
+ import {WORKSPACE_BODY_LIMIT, WORKSPACE_SCHEMA, WORKSPACE_TARGETS_SCHEMA, WORKSPACE_TARGET_DOMAIN, WORKSPACE_TARGET_LIMIT,
9
+ type WorkspaceDesignation, type WorkspaceRecord, type WorkspaceRegistry} from './open-workspace-contract.ts';
10
+
11
+ export function workspaceError(code: string): Error {return new Error(code);}
12
+
13
+ export async function assertPrivate(path: string, directory: boolean) {
14
+ const info = await lstat(path);
15
+ if (!(directory ? info.isDirectory() : info.isFile()) || (info.mode & 0o077) !== 0 ||
16
+ typeof process.getuid === 'function' && info.uid !== process.getuid() || !directory && info.nlink !== 1) throw workspaceError('WORKSPACE_STATE_INVALID');
17
+ }
18
+
19
+ export async function workspaceDirectory(stateDir: string) {
20
+ const directory = join(canonicalStatePath(stateDir), 'owner-workspace');
21
+ await mkdir(directory, {recursive: true, mode: 0o700});
22
+ await assertPrivate(directory, true);
23
+ return directory;
24
+ }
25
+
26
+ export async function readPrivate(path: string): Promise<unknown | null> {
27
+ try {await assertPrivate(path, false); return await smallJson(path);}
28
+ catch (error) {if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw workspaceError('WORKSPACE_STATE_INVALID');}
29
+ }
30
+
31
+ export async function writePrivate(path: string, value: unknown) {
32
+ const text = JSON.stringify(value);
33
+ if (Buffer.byteLength(text) > WORKSPACE_BODY_LIMIT) throw workspaceError('WORKSPACE_BODY_LIMIT');
34
+ await readPrivate(path);
35
+ const temporary = path + '.' + randomUUID() + '.tmp';
36
+ try {
37
+ await writeFile(temporary, text, {flag: 'wx', mode: 0o600});
38
+ await rename(temporary, path);
39
+ } finally {await unlink(temporary).catch(error => {if (error.code !== 'ENOENT') throw error;});}
40
+ }
41
+
42
+ export function targetCapability(ownerCapability: string, incarnation: string, key: string) {
43
+ return createHmac('sha256', ownerCapability).update(WORKSPACE_TARGET_DOMAIN + '\0' + incarnation + '\0' + key).digest('hex');
44
+ }
45
+
46
+ function object(value: unknown): Record<string, unknown> {
47
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw workspaceError('WORKSPACE_REQUEST_INVALID');
48
+ return value as Record<string, unknown>;
49
+ }
50
+
51
+ export function parseDesignation(value: unknown): WorkspaceDesignation {
52
+ const row = object(value), inputs = object(row.inputs);
53
+ if (Object.keys(row).some(key => !['key', 'contentHash', 'inputs', 'cwd', 'viewOnly'].includes(key)) ||
54
+ !capabilityPattern.test(String(row.key)) || !capabilityPattern.test(String(row.contentHash)) ||
55
+ typeof row.cwd !== 'string' || row.cwd.length > 4096 || !isAbsolute(row.cwd) || typeof row.viewOnly !== 'boolean') {
56
+ throw workspaceError('WORKSPACE_REQUEST_INVALID');
57
+ }
58
+ const strings = ['input', 'compare', 'reference', 'animation', 'config', 'parts', 'source', 'full', 'head', 'keypoints'];
59
+ for (const [key, item] of Object.entries(inputs)) {
60
+ if (strings.includes(key)) {
61
+ if (typeof item !== 'string' || !item || item.length > 4096) throw workspaceError('WORKSPACE_REQUEST_INVALID');
62
+ } else if (key === 'control' || key === 'viewOnly') {
63
+ if (typeof item !== 'boolean') throw workspaceError('WORKSPACE_REQUEST_INVALID');
64
+ } else if (key === 'project') {
65
+ const project = object(item);
66
+ for (const [field, entry] of Object.entries(project)) {
67
+ if (['root', 'picksDir', 'draftId', 'partsVerdictDir'].includes(field)) {
68
+ if (typeof entry !== 'string' || !entry || entry.length > 4096) throw workspaceError('WORKSPACE_REQUEST_INVALID');
69
+ } else if (field === 'version' || field === 'postVersion') {
70
+ if (!Number.isSafeInteger(entry) || Number(entry) < 1) throw workspaceError('WORKSPACE_REQUEST_INVALID');
71
+ } else throw workspaceError('WORKSPACE_REQUEST_INVALID');
72
+ }
73
+ if (typeof project.root !== 'string' || typeof project.picksDir !== 'string') throw workspaceError('WORKSPACE_REQUEST_INVALID');
74
+ } else throw workspaceError('WORKSPACE_REQUEST_INVALID');
75
+ }
76
+ if (typeof inputs.input !== 'string' || !isAbsolute(inputs.input)) throw workspaceError('WORKSPACE_REQUEST_INVALID');
77
+ return row as unknown as WorkspaceDesignation;
78
+ }
79
+
80
+ export function parseRegistry(value: unknown): WorkspaceRegistry {
81
+ const row = object(value);
82
+ if (row.schema !== WORKSPACE_TARGETS_SCHEMA || typeof row.incarnation !== 'string' || !Array.isArray(row.targets) ||
83
+ row.targets.length > WORKSPACE_TARGET_LIMIT) throw workspaceError('WORKSPACE_STATE_INVALID');
84
+ const seen = new Set<string>();
85
+ for (const entry of row.targets) {
86
+ const target = object(entry), designation = parseDesignation(target.designation);
87
+ if (seen.has(designation.key) || target.controlToken !== undefined &&
88
+ (typeof target.controlToken !== 'string' || !/^[a-f0-9-]{36}$/.test(target.controlToken))) throw workspaceError('WORKSPACE_STATE_INVALID');
89
+ seen.add(designation.key);
90
+ }
91
+ return row as unknown as WorkspaceRegistry;
92
+ }
93
+
94
+ export function parseWorkspaceRecord(value: unknown): WorkspaceRecord {
95
+ const row = object(value);
96
+ let origin: URL;
97
+ try {origin = new URL(String(row.origin));} catch {throw workspaceError('WORKSPACE_STATE_INVALID');}
98
+ if (row.schema !== WORKSPACE_SCHEMA || !/^[a-f0-9-]{36}$/.test(String(row.incarnation)) ||
99
+ !Number.isSafeInteger(row.pid) || Number(row.pid) < 1 || !Number.isSafeInteger(row.uid) ||
100
+ typeof row.installation !== 'string' || !isAbsolute(row.installation) || typeof row.runtime !== 'string' ||
101
+ !capabilityPattern.test(String(row.fingerprint)) || !capabilityPattern.test(String(row.registrationCapability)) ||
102
+ !capabilityPattern.test(String(row.ownerCapability)) || origin.origin !== row.origin ||
103
+ origin.protocol !== 'http:' || origin.hostname !== '127.0.0.1' || !origin.port) throw workspaceError('WORKSPACE_STATE_INVALID');
104
+ return row as unknown as WorkspaceRecord;
105
+ }
106
+
107
+ /** A live but silent PID remains owned. A timeout never authorizes replacement. */
108
+ export async function probeWorkspace(directory: string, fingerprint: string, port?: number): Promise<WorkspaceRecord | null> {
109
+ await assertPrivate(directory, true);
110
+ const value = await readPrivate(join(directory, 'host.json'));
111
+ if (value === null) return null;
112
+ const record = parseWorkspaceRecord(value);
113
+ if (record.uid !== (process.getuid?.() ?? 0)) throw workspaceError('WORKSPACE_OWNER_MISMATCH');
114
+ if (!running(record.pid)) return null;
115
+ if (record.fingerprint !== fingerprint || record.installation !== appRoot || record.runtime !== Bun.version ||
116
+ port !== undefined && new URL(record.origin).port !== String(port)) throw workspaceError('WORKSPACE_HOST_MISMATCH');
117
+ const response = await fetch(record.origin + '/workspace/api/status', {
118
+ headers: {Authorization: 'Bearer ' + record.registrationCapability}, redirect: 'error', signal: AbortSignal.timeout(1500),
119
+ }).catch(() => null);
120
+ if (!response?.ok) {void response?.body?.cancel(); throw workspaceError('WORKSPACE_HOST_UNRESPONSIVE');}
121
+ const status = object(await readOpenStatus(response));
122
+ if (status.schema !== WORKSPACE_SCHEMA || status.incarnation !== record.incarnation || status.pid !== record.pid ||
123
+ status.fingerprint !== fingerprint || status.runtime !== record.runtime) throw workspaceError('WORKSPACE_HOST_MISMATCH');
124
+ return record;
125
+ }
@@ -0,0 +1,33 @@
1
+ import {dirname, join} from 'node:path';
2
+ import {realpath, unlink} from 'node:fs/promises';
3
+ import {startOpenWorkspace} from './open-workspace.ts';
4
+ import {openFingerprint} from './open.ts';
5
+ import {readPrivate, workspaceDirectory, workspaceError} from './open-workspace-state.ts';
6
+ import {WORKSPACE_SCHEMA} from './open-workspace-contract.ts';
7
+
8
+ async function main(path: string) {
9
+ const value = await readPrivate(path) as {schema?: unknown; stateDir?: unknown; fingerprint?: unknown;
10
+ port?: unknown; idleMs?: unknown; graceMs?: unknown} | null;
11
+ if (!value || value.schema !== WORKSPACE_SCHEMA || typeof value.stateDir !== 'string' ||
12
+ value.fingerprint !== await openFingerprint() || !Number.isSafeInteger(value.port) ||
13
+ Number(value.port) < 1 || Number(value.port) > 65535 ||
14
+ [value.idleMs, value.graceMs].some(item => item !== undefined && (!Number.isSafeInteger(item) || Number(item) < 100))) {
15
+ throw workspaceError('WORKSPACE_REQUEST_INVALID');
16
+ }
17
+ const directory = await workspaceDirectory(value.stateDir);
18
+ if (dirname(await realpath(path)) !== directory) throw workspaceError('WORKSPACE_STATE_INVALID');
19
+ await unlink(path).catch(error => {if (error.code !== 'ENOENT') throw error;});
20
+ const host = await startOpenWorkspace({stateDir: value.stateDir, fingerprint: String(value.fingerprint),
21
+ port: Number(value.port), idleMs: value.idleMs as number | undefined, graceMs: value.graceMs as number | undefined});
22
+ const stop = () => {void host.stop().then(() => process.exit(0));};
23
+ process.once('SIGTERM', stop); process.once('SIGINT', stop);
24
+ void host.live.exited.then(info => {if (info) process.exit(0);});
25
+ }
26
+
27
+ if (import.meta.main) main(Bun.argv[2] ?? join(process.cwd(), 'missing.request')).catch(error => {
28
+ const message = error instanceof Error ? error.message : '';
29
+ const occupied = /^FRONT_PORT_BUSY: 127\.0\.0\.1:[1-9]\d{0,4} is held by another listener; use --direct \(or set RIG_REVIEW_FRONT_PORT\)$/.test(message);
30
+ const safeCodes = ['WORKSPACE_REQUEST_INVALID', 'WORKSPACE_STATE_INVALID', 'WORKSPACE_BODY_LIMIT', 'WORKSPACE_START_REFUSED'];
31
+ console.error(occupied || safeCodes.includes(message) ? message : 'WORKSPACE_START_REFUSED');
32
+ process.exitCode = 1;
33
+ });