@rig-c/review 2.1.0 → 2.3.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.
package/src/job-front.ts CHANGED
@@ -40,6 +40,7 @@ function result<Value>(value: JobResult<Value>): Response {
40
40
  export function createJobFront(options: {
41
41
  origin: string;
42
42
  ports: JobHostPorts;
43
+ hubIncarnation?: string;
43
44
  resource: (name: 'index.html' | 'job.js' | 'styles.css') => Promise<BodyInit>;
44
45
  publication?: (jobId: string, publicationId: string, instanceKey: string, path: string, request: Request) => Promise<Response>;
45
46
  }) {
@@ -124,8 +125,16 @@ export function createJobFront(options: {
124
125
  });
125
126
  return new Response(body, { headers: { ...headers, 'Content-Type': 'application/x-ndjson' } });
126
127
  }
127
- if (url.search && !(route === '' && ['?lang=en', '?lang=ko'].includes(url.search)))
128
+ const embedded = route === '' && url.searchParams.has('hub');
129
+ if (embedded) {
130
+ if (!options.hubIncarnation || url.searchParams.get('hub') !== options.hubIncarnation ||
131
+ [...url.searchParams.keys()].some(key => !['hub', 'lang'].includes(key) || url.searchParams.getAll(key).length !== 1) ||
132
+ url.searchParams.has('lang') && !['en', 'ko'].includes(url.searchParams.get('lang')!)) {
133
+ return failure('JOB_REQUEST_INVALID', 400);
134
+ }
135
+ } else if (url.search && !(route === '' && ['?lang=en', '?lang=ko'].includes(url.search))) {
128
136
  return failure('JOB_REQUEST_INVALID', 400);
137
+ }
129
138
  const instance = /^publications\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\/instances\/([a-f0-9]{64})\/(.*)$/.exec(route);
130
139
  if (instance && options.publication) {
131
140
  return options.publication(jobId, instance[1]!, instance[2]!, instance[3]!, request);
@@ -138,7 +147,9 @@ export function createJobFront(options: {
138
147
  return failure('JOB_REQUEST_INVALID', 404);
139
148
  const type = name === 'index.html' ? 'text/html; charset=utf-8' : name === 'job.js' ? 'text/javascript' : 'text/css';
140
149
  return new Response(request.method === 'HEAD' ? null : await options.resource(name), {
141
- headers: { ...headers, 'Content-Type': type },
150
+ headers: { ...headers, 'Content-Type': type, ...(embedded ? {
151
+ 'Content-Security-Policy': headers['Content-Security-Policy'].replace("frame-ancestors 'none'", "frame-ancestors 'self'"),
152
+ } : {}) },
142
153
  });
143
154
  }
144
155
  return {
@@ -274,7 +285,7 @@ function retainedPublicationRoutes(session: JobSession) {
274
285
  };
275
286
  }
276
287
 
277
- interface JobHostRecord {
288
+ export interface JobHostRecord {
278
289
  schema: 'rig-review-job-host/1';
279
290
  apiSchema: typeof JOB_API_SCHEMA;
280
291
  actSchema: typeof JOB_ACT_SCHEMA;
@@ -330,37 +341,75 @@ export interface JobOwnerHost {
330
341
  stop(): void;
331
342
  }
332
343
 
333
- /** Full standing owner host. #489 can publish this seam after its own contract review. */
334
- export async function startJobHost(options: JobHostOptions): Promise<JobOwnerHost> {
335
- const startup = {...options};
344
+ export function jobHostIdentity(startup: JobHostOptions) {
336
345
  const readerId = declaredHostId('readPublished', startup.readPublished, startup.readerId);
337
346
  const bindingId = declaredHostId('installWriterBinding', startup.installWriterBinding, startup.bindingId);
338
347
  const partsEnumeratorId = declaredHostId('partsEnumerator', startup.partsEnumerator?.enumerate, startup.partsEnumeratorId);
339
348
  const partsEnumeratorVersion = startup.partsEnumerator?.version ?? null;
340
- const session = new JobSession(startup);
341
- async function installBinding(origin: string): Promise<void> {
342
- try {await startup.installWriterBinding?.({...session.writerGrant(), origin});}
343
- catch {throw new JobError('JOB_AUTHORITY_REFUSED', 'Writer binding installation failed');}
349
+ return {readerId, bindingId, partsEnumeratorId, partsEnumeratorVersion};
350
+ }
351
+
352
+ export async function installJobWriterBinding(session: JobSession, startup: JobHostOptions, origin: string): Promise<void> {
353
+ try {await startup.installWriterBinding?.({...session.writerGrant(), origin});}
354
+ catch {throw new JobError('JOB_AUTHORITY_REFUSED', 'Writer binding installation failed');}
355
+ }
356
+
357
+ export function assertJobHostCompatible(record: JobHostRecord, identity: ReturnType<typeof jobHostIdentity>): void {
358
+ for (const [option, actual, requested] of [
359
+ ['readPublished', record.readerId, identity.readerId],
360
+ ['installWriterBinding', record.bindingId, identity.bindingId],
361
+ ['partsEnumerator', record.partsEnumeratorId, identity.partsEnumeratorId],
362
+ ['partsEnumeratorVersion', record.partsEnumeratorVersion, identity.partsEnumeratorVersion],
363
+ ['apiSchema', record.apiSchema, JOB_API_SCHEMA],
364
+ ['actSchema', record.actSchema, JOB_ACT_SCHEMA],
365
+ ] as const) {
366
+ if (actual !== requested) {
367
+ throw new JobHostOptionError('JOB_HOST_REUSE_MISMATCH', option, actual, requested);
368
+ }
344
369
  }
370
+ }
371
+
372
+ /** One live job request context. Its caller owns the listener and session lifetime. */
373
+ export function createJobRequestContext(session: JobSession, startup: JobHostOptions, origin: string,
374
+ identity: ReturnType<typeof jobHostIdentity>, resource = jobWindowResources(), hubIncarnation?: string) {
375
+ const ports = createJobHostPorts(session, origin);
376
+ const record: JobHostRecord = {schema: 'rig-review-job-host/1', apiSchema: JOB_API_SCHEMA, actSchema: JOB_ACT_SCHEMA,
377
+ ...identity, jobId: session.jobId, origin, fingerprint: startup.fingerprint, pid: process.pid};
378
+ const front = createJobFront({origin, ports, resource, hubIncarnation, publication: retainedPublicationRoutes(session)});
379
+ let requests = 0;
380
+ return {
381
+ ports, record,
382
+ get busy() {return requests > 0 || session.busy;},
383
+ async fetch(request: Request): Promise<Response> {
384
+ requests++;
385
+ try {
386
+ const url = new URL(request.url);
387
+ if (url.pathname === `/jobs/${session.jobId}/host`) {
388
+ if (url.origin !== origin || request.method !== 'GET' || url.search ||
389
+ request.headers.get('sec-fetch-site') === 'cross-site' ||
390
+ request.headers.get('origin') !== null && request.headers.get('origin') !== origin) return failure('JOB_REQUEST_INVALID', 403);
391
+ try {session.authorize('ui', request.headers.get('X-Review-Capability'));}
392
+ catch {return failure('JOB_CAPABILITY_REQUIRED', 403);}
393
+ return Response.json(record, {headers});
394
+ }
395
+ return await front.fetch(request) ?? failure('JOB_REQUEST_INVALID', 404);
396
+ } finally {requests--;}
397
+ },
398
+ stop() {front.stop();},
399
+ };
400
+ }
401
+
402
+ /** Full standing owner host. #489 can publish this seam after its own contract review. */
403
+ export async function startJobHost(options: JobHostOptions): Promise<JobOwnerHost> {
404
+ const startup = {...options};
405
+ const identity = jobHostIdentity(startup);
406
+ const session = new JobSession(startup);
407
+ const installBinding = (origin: string) => installJobWriterBinding(session, startup, origin);
345
408
  const credentials = session.hostCredentials();
346
409
  const control = join(canonicalStatePath(startup.stateDir), 'job-ui');
347
410
  await mkdir(control, {recursive: true, mode: 0o700}).catch(error => {session.dispose(); throw error;});
348
411
  const recordPath = join(control, session.jobId + '.json');
349
412
  let previousPort = 0;
350
- function compatible(record: JobHostRecord): void {
351
- for (const [option, actual, requested] of [
352
- ['readPublished', record.readerId, readerId],
353
- ['installWriterBinding', record.bindingId, bindingId],
354
- ['partsEnumerator', record.partsEnumeratorId, partsEnumeratorId],
355
- ['partsEnumeratorVersion', record.partsEnumeratorVersion, partsEnumeratorVersion],
356
- ['apiSchema', record.apiSchema, JOB_API_SCHEMA],
357
- ['actSchema', record.actSchema, JOB_ACT_SCHEMA],
358
- ] as const) {
359
- if (actual !== requested) {
360
- throw new JobHostOptionError('JOB_HOST_REUSE_MISMATCH', option, actual, requested);
361
- }
362
- }
363
- }
364
413
  const reuse = async (): Promise<JobHostRecord | null> => {
365
414
  try {
366
415
  const info = await lstat(recordPath);
@@ -378,8 +427,8 @@ export async function startJobHost(options: JobHostOptions): Promise<JobOwnerHos
378
427
  if (!response?.ok) {void response?.body?.cancel(); return null;}
379
428
  const value = await response.json() as JobHostRecord;
380
429
  if (value.schema !== row.schema || value.jobId !== row.jobId || value.fingerprint !== row.fingerprint) return null;
381
- compatible(row);
382
- compatible(value);
430
+ assertJobHostCompatible(row, identity);
431
+ assertJobHostCompatible(value, identity);
383
432
  return row;
384
433
  } catch (error) {
385
434
  if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
@@ -401,37 +450,21 @@ export async function startJobHost(options: JobHostOptions): Promise<JobOwnerHos
401
450
  reused: true, stop: () => session.dispose()};
402
451
  }
403
452
  claim = acquired.claim;
404
- let front: ReturnType<typeof createJobFront>;
405
- let ports: JobHostPorts;
453
+ let context: ReturnType<typeof createJobRequestContext>;
406
454
  const preferredPort = startup.port ?? previousPort;
407
455
  const server = Bun.serve({hostname: '127.0.0.1', port: preferredPort, idleTimeout: 0,
408
- async fetch(request) {
409
- const url = new URL(request.url);
410
- if (url.pathname === `/jobs/${session.jobId}/host`) {
411
- if (url.origin !== origin || request.method !== 'GET' || url.search ||
412
- request.headers.get('sec-fetch-site') === 'cross-site' ||
413
- request.headers.get('origin') !== null && request.headers.get('origin') !== origin) return failure('JOB_REQUEST_INVALID', 403);
414
- try {session.authorize('ui', request.headers.get('X-Review-Capability'));}
415
- catch {return failure('JOB_CAPABILITY_REQUIRED', 403);}
416
- return Response.json(record, {headers});
417
- }
418
- return await front.fetch(request) ?? failure('JOB_REQUEST_INVALID', 404);
419
- },
456
+ fetch(request) {return context.fetch(request);},
420
457
  });
421
458
  const origin = `http://127.0.0.1:${server.port}`;
422
- const record: JobHostRecord = {schema: 'rig-review-job-host/1', apiSchema: JOB_API_SCHEMA, actSchema: JOB_ACT_SCHEMA,
423
- partsEnumeratorId, partsEnumeratorVersion, jobId: session.jobId, origin,
424
- fingerprint: startup.fingerprint, pid: process.pid, readerId, bindingId};
425
- ports = createJobHostPorts(session, origin);
426
- front = createJobFront({origin, ports, resource: jobWindowResources(),
427
- publication: retainedPublicationRoutes(session)});
459
+ context = createJobRequestContext(session, startup, origin, identity);
460
+ const {ports, record} = context;
428
461
  const closed = new AbortController();
429
462
  let stopped = false;
430
463
  stop = () => {
431
464
  if (stopped) return;
432
465
  stopped = true;
433
466
  closed.abort();
434
- front.stop();
467
+ context.stop();
435
468
  server.stop(true);
436
469
  session.dispose();
437
470
  };
package/src/job-host.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  /** Stable installed managed owner host and semantic A/B contract. See docs/STABILITY.md. */
2
2
  export {startJobHost} from './job-front.ts';
3
+ export {startJobHub} from './job-hub.ts';
4
+ export type {JobHubOptions, JobHubJobOptions, JobHubJob, JobOwnerHub} from './job-hub.ts';
3
5
  export type {JobHostOptions, JobOwnerHost} from './job-front.ts';
4
6
  export type {JobSessionOptions, JobSession} from './job-session.ts';
5
7
  export type {JobWorkerOptions} from './job-worker.ts';
package/src/job-hub.ts ADDED
@@ -0,0 +1,298 @@
1
+ /** Embedded job owner. Trusted callback registrations never cross a process boundary. */
2
+ import {randomBytes, randomUUID} from 'node:crypto';
3
+ import {mkdir, unlink} from 'node:fs/promises';
4
+ import {join} from 'node:path';
5
+ import {buildWeb} from './build.ts';
6
+ import {jobBody, jobObject, sameCapability} from './job-api.ts';
7
+ import {JOB_API_SCHEMA, JOB_ACT_SCHEMA, type JobHostPorts, type JobReviewerBinding} from './job-contract.ts';
8
+ import {assertJobHostCompatible, createJobRequestContext, installJobWriterBinding, jobHostIdentity,
9
+ jobWindowResources, type JobHostOptions, type JobHostRecord} from './job-front.ts';
10
+ import {JobSession} from './job-session.ts';
11
+ import {captureJobRoot} from './job-source.ts';
12
+ import {JobError} from './job-store.ts';
13
+ import {acquireClaim, readOpenStatus, releaseClaim, running} from './open.ts';
14
+ import {assertPrivate, readPrivate, writePrivate} from './open-workspace-state.ts';
15
+ import {canonicalStatePath} from './state-dir.ts';
16
+
17
+ export interface JobHubOptions {
18
+ readonly stateDir: string;
19
+ readonly reviewer: JobReviewerBinding;
20
+ readonly port?: number;
21
+ }
22
+ export type JobHubJobOptions = Omit<JobHostOptions, 'stateDir' | 'port' | 'reviewer'>;
23
+ export interface JobHubJob {
24
+ readonly session: JobSession;
25
+ readonly ports: JobHostPorts;
26
+ readonly origin: string;
27
+ readonly jobUrl: string;
28
+ readonly reused: boolean;
29
+ }
30
+ export interface JobOwnerHub {
31
+ readonly origin: string;
32
+ readonly ownerUrl: string;
33
+ openJob(options: JobHubJobOptions): Promise<JobHubJob>;
34
+ stop(): Promise<void>;
35
+ }
36
+
37
+ export interface JobHubRow {
38
+ jobId: string;
39
+ generation: number;
40
+ status: 'active' | 'closed';
41
+ publication: {publicationId: string; instanceKey: string; sourceHash: string; label: string} | null;
42
+ pendingCount: number;
43
+ }
44
+ export interface JobHubList {
45
+ schema: 'rig-review-job-hub/1';
46
+ incarnation: string;
47
+ limit: number;
48
+ jobs: JobHubRow[];
49
+ }
50
+
51
+ const schema = 'rig-review-job-hub/1';
52
+ const maximumJobs = 32;
53
+ const responseHeaders = {'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer'};
54
+ type HubCode = 'JOB_HUB_ALREADY_RUNNING' | 'JOB_HUB_EXTERNAL_HOST' | 'JOB_HUB_HOST_UNRESPONSIVE' |
55
+ 'JOB_HUB_CLOSED' | 'JOB_HUB_LIMIT' | 'JOB_HUB_STATE_INVALID';
56
+ class HubError extends Error {
57
+ constructor(readonly code: HubCode) {super(code);}
58
+ }
59
+ interface HubRecord {
60
+ schema: typeof schema;
61
+ pid: number;
62
+ origin: string;
63
+ incarnation: string;
64
+ capability: string;
65
+ }
66
+ interface Member {
67
+ root: string;
68
+ fingerprint: string;
69
+ session: JobSession;
70
+ context: ReturnType<typeof createJobRequestContext>;
71
+ recordPath: string;
72
+ ready: boolean;
73
+ }
74
+ function refused(code: string, status: number) {
75
+ return Response.json({ok: false, error: {code, message: code}}, {status, headers: responseHeaders});
76
+ }
77
+ function hostRecord(value: unknown, jobId?: string): JobHostRecord {
78
+ if (!value || typeof value !== 'object') throw new HubError('JOB_HUB_STATE_INVALID');
79
+ const row = value as JobHostRecord;
80
+ let origin: URL;
81
+ try {origin = new URL(row.origin);} catch {throw new HubError('JOB_HUB_STATE_INVALID');}
82
+ if (row.schema !== 'rig-review-job-host/1' || typeof row.jobId !== 'string' || jobId && row.jobId !== jobId ||
83
+ typeof row.fingerprint !== 'string' || !Number.isSafeInteger(row.pid) || row.pid < 1 ||
84
+ origin.origin !== row.origin || origin.protocol !== 'http:' || origin.hostname !== '127.0.0.1') {
85
+ throw new HubError('JOB_HUB_STATE_INVALID');
86
+ }
87
+ return row;
88
+ }
89
+
90
+ export async function startJobHub(options: JobHubOptions): Promise<JobOwnerHub> {
91
+ const reviewer = structuredClone(options.reviewer);
92
+ if (!reviewer?.id || !['owner', 'delegate'].includes(reviewer.role)) throw new JobError('JOB_AUTHORITY_REFUSED');
93
+ if (options.port !== undefined && (!Number.isSafeInteger(options.port) || options.port < 0 || options.port > 65535)) {
94
+ throw new JobError('JOB_REQUEST_INVALID');
95
+ }
96
+ const stateDir = canonicalStatePath(options.stateDir);
97
+ const directory = join(stateDir, 'job-hub'), control = join(stateDir, 'job-ui');
98
+ for (const path of [directory, control]) {
99
+ await mkdir(path, {recursive: true, mode: 0o700}); await assertPrivate(path, true);
100
+ }
101
+ const recordPath = join(directory, 'host.json'), incarnation = randomUUID();
102
+ const capability = randomBytes(32).toString('hex');
103
+ async function refuseLiveHub(): Promise<null> {
104
+ const previous = await readPrivate(recordPath) as HubRecord | null;
105
+ if (!previous) return null;
106
+ if (previous.schema !== schema || !Number.isSafeInteger(previous.pid) || previous.pid < 1) {
107
+ throw new HubError('JOB_HUB_STATE_INVALID');
108
+ }
109
+ if (running(previous.pid)) throw new HubError('JOB_HUB_ALREADY_RUNNING');
110
+ return null;
111
+ }
112
+ await refuseLiveHub();
113
+ const acquired = await acquireClaim(directory, 'hub', incarnation, refuseLiveHub,
114
+ performance.now() + 20_000, 'JOB_HUB_ALREADY_RUNNING');
115
+ if (!('claim' in acquired)) throw new HubError('JOB_HUB_ALREADY_RUNNING');
116
+ const hubClaim = acquired.claim;
117
+ let server: ReturnType<typeof Bun.serve> | undefined;
118
+ const members = new Map<string, Member>();
119
+ let queue = Promise.resolve(), closing = false, requests = 0;
120
+ let stopping: Promise<void> | undefined;
121
+ const resources = jobWindowResources();
122
+ let hubBundle: Promise<Blob> | undefined;
123
+ async function removeOwned(path: string) {
124
+ const value = await readPrivate(path) as {incarnation?: string; hubIncarnation?: string} | null;
125
+ if (value?.incarnation === incarnation || value?.hubIncarnation === incarnation) {
126
+ await unlink(path).catch(error => {if (error.code !== 'ENOENT') throw error;});
127
+ }
128
+ }
129
+ function stop(): Promise<void> {
130
+ if (stopping) return stopping;
131
+ closing = true;
132
+ stopping = (async () => {
133
+ await queue;
134
+ for (const member of members.values()) member.context.stop();
135
+ while (requests || [...members.values()].some(member => member.context.busy)) await Bun.sleep(10);
136
+ await server?.stop(true);
137
+ for (const member of members.values()) {
138
+ member.session.dispose(); await removeOwned(member.recordPath);
139
+ }
140
+ members.clear();
141
+ await removeOwned(recordPath);
142
+ await releaseClaim(hubClaim, incarnation);
143
+ })();
144
+ return stopping;
145
+ }
146
+ try {
147
+ await refuseLiveHub();
148
+ server = Bun.serve({hostname: '127.0.0.1', port: options.port ?? 0, idleTimeout: 0,
149
+ async fetch(request): Promise<Response> {
150
+ if (closing) return refused('JOB_HUB_CLOSED', 503);
151
+ requests++;
152
+ try {
153
+ const url = new URL(request.url);
154
+ if (url.origin !== origin) return refused('JOB_LOOPBACK_REQUIRED', 403);
155
+ const resource = url.pathname === '/hub/' ? 'job-hub.html' : url.pathname === '/hub/job-hub.js' ? 'job-hub.js'
156
+ : url.pathname === '/hub/job-hub.css' ? 'job-hub.css' : url.pathname === '/hub/styles.css' ? 'styles.css' : null;
157
+ if (resource) {
158
+ if (!['GET', 'HEAD'].includes(request.method)) return refused('JOB_REQUEST_INVALID', 405);
159
+ if (request.headers.get('sec-fetch-site') === 'cross-site' ||
160
+ request.headers.get('origin') !== null && request.headers.get('origin') !== origin) return refused('JOB_SAME_ORIGIN_REQUIRED', 403);
161
+ if (resource === 'job-hub.html') {
162
+ if (url.searchParams.get('workspace') !== incarnation ||
163
+ [...url.searchParams.keys()].some(key => !['workspace', 'lang'].includes(key) || url.searchParams.getAll(key).length !== 1) ||
164
+ url.searchParams.has('lang') && !['en', 'ko'].includes(url.searchParams.get('lang')!)) return refused('JOB_REQUEST_INVALID', 400);
165
+ } else if (url.search) return refused('JOB_REQUEST_INVALID', 400);
166
+ let body: BodyInit | null = null;
167
+ if (request.method !== 'HEAD') {
168
+ if (resource === 'job-hub.js') body = await (hubBundle ??= buildWeb('job-hub'));
169
+ else body = Bun.file(new URL('../web/' + resource, import.meta.url));
170
+ }
171
+ return new Response(body, {headers: {...responseHeaders,
172
+ 'Content-Type': resource.endsWith('.html') ? 'text/html; charset=utf-8' : resource.endsWith('.js') ? 'text/javascript' : 'text/css',
173
+ 'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; frame-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'"}});
174
+ }
175
+ const selected = /^\/hub\/api\/jobs\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\/open$/.exec(url.pathname);
176
+ if (url.pathname === '/hub/host' || url.pathname === '/hub/api/jobs' || selected) {
177
+ if (request.method !== (selected ? 'POST' : 'GET') || url.search) return refused('JOB_REQUEST_INVALID', 400);
178
+ if (request.headers.get('sec-fetch-site') === 'cross-site' ||
179
+ request.headers.get('origin') !== null && request.headers.get('origin') !== origin) {
180
+ return refused('JOB_SAME_ORIGIN_REQUIRED', 403);
181
+ }
182
+ if (!sameCapability(request.headers.get('X-Review-Capability'), capability)) {
183
+ return refused('JOB_CAPABILITY_REQUIRED', 403);
184
+ }
185
+ if (selected) {
186
+ if (request.headers.get('origin') !== origin) return refused('JOB_SAME_ORIGIN_REQUIRED', 403);
187
+ try {
188
+ const input = jobObject(await jobBody(request), ['schema', 'incarnation']);
189
+ if (input.schema !== schema || input.incarnation !== incarnation) return refused('JOB_REQUEST_INVALID', 400);
190
+ } catch (error) {return refused(error instanceof JobError ? error.code : 'JOB_REQUEST_INVALID',
191
+ error instanceof JobError && error.code === 'JOB_BODY_LIMIT' ? 413 : 400);}
192
+ const member = members.get(selected[1]!);
193
+ if (!member?.ready) return refused('JOB_UNKNOWN', 404);
194
+ if (member.session.status().status === 'closed') return refused('JOB_CLOSED', 409);
195
+ return Response.json({schema, incarnation, jobId: selected[1],
196
+ entry: `/jobs/${selected[1]}/?hub=${incarnation}`, capability: member.session.hostCredentials().ui}, {headers: responseHeaders});
197
+ }
198
+ if (url.pathname === '/hub/host') return Response.json({schema, incarnation, pid: process.pid,
199
+ origin, apiSchema: JOB_API_SCHEMA, actSchema: JOB_ACT_SCHEMA}, {headers: responseHeaders});
200
+ return Response.json({schema, incarnation, limit: maximumJobs, jobs: [...members.values()].filter(member => member.ready).map(member => {
201
+ const status = member.session.status();
202
+ return {jobId: status.jobId, generation: status.generation, status: status.status,
203
+ publication: status.publication && {publicationId: status.publication.publicationId,
204
+ instanceKey: status.publication.instanceKey, sourceHash: status.publication.source.sourceHash,
205
+ label: status.publication.label.slice(0, 512)}, pendingCount: status.pending.length};
206
+ })}, {headers: responseHeaders});
207
+ }
208
+ const match = /^\/jobs\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\//.exec(url.pathname);
209
+ const member = match && members.get(match[1]!);
210
+ return member ? await member.context.fetch(request) : refused('JOB_UNKNOWN', 404);
211
+ } finally {requests--;}
212
+ },
213
+ });
214
+ const origin: string = `http://127.0.0.1:${server.port}`;
215
+ const record: HubRecord = {schema, pid: process.pid, origin, incarnation, capability};
216
+ await writePrivate(recordPath, record);
217
+ async function register(input: JobHubJobOptions): Promise<JobHubJob> {
218
+ if (closing) throw new HubError('JOB_HUB_CLOSED');
219
+ const startup: JobHostOptions = {...input, stateDir, reviewer};
220
+ const identity = jobHostIdentity(startup);
221
+ const root = captureJobRoot(startup.root).path;
222
+ if (members.size >= maximumJobs && ![...members.values()].some(member =>
223
+ member.root === root && member.fingerprint === startup.fingerprint && member.session.status().status === 'active')) {
224
+ throw new HubError('JOB_HUB_LIMIT');
225
+ }
226
+ const session = new JobSession(startup);
227
+ let retained = false;
228
+ let claim: string | undefined;
229
+ let member: Member | undefined;
230
+ const nonce = randomUUID();
231
+ try {
232
+ const existing = members.get(session.jobId);
233
+ if (existing) {
234
+ assertJobHostCompatible(existing.context.record, identity);
235
+ await installJobWriterBinding(existing.session, startup, origin);
236
+ return {session: existing.session, ports: existing.context.ports, origin,
237
+ jobUrl: origin + `/jobs/${session.jobId}/#cap=${existing.session.hostCredentials().ui}`, reused: true};
238
+ }
239
+ if (members.size >= maximumJobs) throw new HubError('JOB_HUB_LIMIT');
240
+ const path = join(control, session.jobId + '.json');
241
+ async function refuseExternal(): Promise<null> {
242
+ const value = await readPrivate(path);
243
+ if (!value) return null;
244
+ const row = hostRecord(value, session.jobId);
245
+ if (row.fingerprint !== startup.fingerprint) throw new HubError('JOB_HUB_STATE_INVALID');
246
+ if (!running(row.pid)) return null;
247
+ let remote: JobHostRecord;
248
+ try {
249
+ const response = await fetch(row.origin + `/jobs/${session.jobId}/host`, {
250
+ headers: {'X-Review-Capability': session.hostCredentials().ui}, redirect: 'error', signal: AbortSignal.timeout(1500),
251
+ });
252
+ if (!response.ok) {await response.body?.cancel(); throw new HubError('JOB_HUB_HOST_UNRESPONSIVE');}
253
+ remote = hostRecord(await readOpenStatus(response, 1500), session.jobId);
254
+ if (remote.origin !== row.origin || remote.pid !== row.pid || remote.fingerprint !== row.fingerprint) {
255
+ throw new HubError('JOB_HUB_HOST_UNRESPONSIVE');
256
+ }
257
+ } catch {throw new HubError('JOB_HUB_HOST_UNRESPONSIVE');}
258
+ assertJobHostCompatible(row, identity); assertJobHostCompatible(remote, identity);
259
+ throw new HubError('JOB_HUB_EXTERNAL_HOST');
260
+ }
261
+ await refuseExternal();
262
+ const acquiredJob = await acquireClaim(control, 'job-' + session.jobId, nonce, refuseExternal,
263
+ performance.now() + 20_000, 'JOB_HUB_EXTERNAL_HOST');
264
+ if (!('claim' in acquiredJob)) throw new HubError('JOB_HUB_EXTERNAL_HOST');
265
+ claim = acquiredJob.claim;
266
+ await refuseExternal();
267
+ const context = createJobRequestContext(session, startup, origin, identity, resources, incarnation);
268
+ Object.assign(context.record, {hubIncarnation: incarnation});
269
+ member = {root, fingerprint: startup.fingerprint, session, context, recordPath: path, ready: false};
270
+ members.set(session.jobId, member);
271
+ await installJobWriterBinding(session, startup, origin);
272
+ if (closing) throw new HubError('JOB_HUB_CLOSED');
273
+ await writePrivate(path, context.record);
274
+ member.ready = true; retained = true;
275
+ return {session, ports: context.ports, origin,
276
+ jobUrl: origin + `/jobs/${session.jobId}/#cap=${session.hostCredentials().ui}`, reused: false};
277
+ } finally {
278
+ if (!retained) {
279
+ if (member) {
280
+ members.delete(session.jobId); member.context.stop();
281
+ while (member.context.busy) await Bun.sleep(10);
282
+ }
283
+ session.dispose();
284
+ }
285
+ if (claim) await releaseClaim(claim, nonce);
286
+ }
287
+ }
288
+ return {origin, ownerUrl: origin + '/hub/?workspace=' + incarnation + '#cap=' + capability,
289
+ openJob(input) {
290
+ const startup = {...input};
291
+ const task = queue.then(() => register(startup));
292
+ queue = task.then(() => {}, () => {});
293
+ return task;
294
+ }, stop};
295
+ } catch (error) {
296
+ await stop(); throw error;
297
+ }
298
+ }
@@ -23,7 +23,7 @@ async function register(record: WorkspaceRecord, targets: WorkspaceDesignation[]
23
23
  }
24
24
 
25
25
  /** Launchers exchange designated package data, never callbacks or human acts. */
26
- export async function openWorkspace(inputs: readonly OpenInputs[], options: OpenOptions = {}) {
26
+ export async function openWorkspace(inputs: readonly OpenInputs[], options: OpenOptions & {foreground?: boolean} = {}) {
27
27
  const fingerprint = await openFingerprint();
28
28
  const prepared = [];
29
29
  for (const input of inputs) prepared.push(await prepareOpenTarget(input, options, fingerprint));
@@ -40,11 +40,20 @@ export async function openWorkspace(inputs: readonly OpenInputs[], options: Open
40
40
  const acquired = ready ? {row: ready} : await acquireClaim(directory, 'host', nonce, reuse,
41
41
  performance.now() + 20_000, 'WORKSPACE_START_BUSY');
42
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);};
43
47
  try {
44
48
  let record: WorkspaceRecord;
45
49
  const reused = 'row' in acquired;
46
50
  if ('row' in acquired) record = acquired.row;
47
- else {
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 {
48
57
  request = join(directory, nonce + '.request.json');
49
58
  await writePrivate(request, {schema: WORKSPACE_SCHEMA, stateDir, fingerprint, port,
50
59
  ...(options.idleMs !== undefined ? {idleMs: options.idleMs} : {}),
@@ -73,9 +82,18 @@ export async function openWorkspace(inputs: readonly OpenInputs[], options: Open
73
82
  await Bun.sleep(30);
74
83
  }
75
84
  }
76
- await register(record, designations);
85
+ try {await register(record, designations);}
86
+ catch (error) {if (!interrupted) throw error;}
77
87
  handedOff = true;
78
- return {url: record.origin + '/?workspace=' + record.incarnation + '#cap=' + record.ownerCapability, reused, prepared};
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;
79
97
  } finally {
80
98
  if (child && !handedOff && child.exitCode === null && child.signalCode === null) child.kill('SIGTERM');
81
99
  if ('claim' in acquired) await releaseClaim(acquired.claim, nonce);
package/web/catalog-en.ts CHANGED
@@ -3393,6 +3393,21 @@ export const enCatalog: Readonly<Record<string, string>> = {
3393
3393
  "JOB_SOURCE_MISMATCH": "JOB_SOURCE_MISMATCH",
3394
3394
  "JOB_SOURCE_UNRETAINABLE": "JOB_SOURCE_UNRETAINABLE",
3395
3395
  "JOB_STORAGE_FAILED": "JOB_STORAGE_FAILED",
3396
+ "rig-review-job-hub/1": "rig-review-job-hub/1",
3397
+ "JOB_HUB_ALREADY_RUNNING": "JOB_HUB_ALREADY_RUNNING",
3398
+ "JOB_HUB_EXTERNAL_HOST": "JOB_HUB_EXTERNAL_HOST",
3399
+ "JOB_HUB_HOST_UNRESPONSIVE": "JOB_HUB_HOST_UNRESPONSIVE",
3400
+ "JOB_HUB_CLOSED": "JOB_HUB_CLOSED",
3401
+ "JOB_HUB_LIMIT": "JOB_HUB_LIMIT",
3402
+ "JOB_HUB_STATE_INVALID": "JOB_HUB_STATE_INVALID",
3403
+ "JOB_HUB_REQUEST_REFUSED": "JOB_HUB_REQUEST_REFUSED",
3404
+ "rig-review-job-hub-ready/1": "rig-review-job-hub-ready/1",
3405
+ "rig-review-job-hub-visibility/1": "rig-review-job-hub-visibility/1",
3406
+ "job.hubTitle": "Review jobs",
3407
+ "job.hubJobs": "Review jobs",
3408
+ "job.hubHint": "Select a job. Drafts stay with their original source.",
3409
+ "job.hubClosed": "Explicitly closed",
3410
+ "job.hubPending": "Active · {0} pending asks",
3396
3411
  "JOB_STREAM_FAILED": "JOB_STREAM_FAILED",
3397
3412
  "JOB_STREAM_INCOMPLETE": "JOB_STREAM_INCOMPLETE",
3398
3413
  "JOB_UNKNOWN": "JOB_UNKNOWN",
package/web/catalog-ko.ts CHANGED
@@ -3393,6 +3393,21 @@ export const koCatalog: Readonly<Record<string, string>> = {
3393
3393
  "JOB_SOURCE_MISMATCH": "JOB_SOURCE_MISMATCH",
3394
3394
  "JOB_SOURCE_UNRETAINABLE": "JOB_SOURCE_UNRETAINABLE",
3395
3395
  "JOB_STORAGE_FAILED": "JOB_STORAGE_FAILED",
3396
+ "rig-review-job-hub/1": "rig-review-job-hub/1",
3397
+ "JOB_HUB_ALREADY_RUNNING": "JOB_HUB_ALREADY_RUNNING",
3398
+ "JOB_HUB_EXTERNAL_HOST": "JOB_HUB_EXTERNAL_HOST",
3399
+ "JOB_HUB_HOST_UNRESPONSIVE": "JOB_HUB_HOST_UNRESPONSIVE",
3400
+ "JOB_HUB_CLOSED": "JOB_HUB_CLOSED",
3401
+ "JOB_HUB_LIMIT": "JOB_HUB_LIMIT",
3402
+ "JOB_HUB_STATE_INVALID": "JOB_HUB_STATE_INVALID",
3403
+ "JOB_HUB_REQUEST_REFUSED": "JOB_HUB_REQUEST_REFUSED",
3404
+ "rig-review-job-hub-ready/1": "rig-review-job-hub-ready/1",
3405
+ "rig-review-job-hub-visibility/1": "rig-review-job-hub-visibility/1",
3406
+ "job.hubTitle": "리뷰 작업",
3407
+ "job.hubJobs": "리뷰 작업",
3408
+ "job.hubHint": "작업을 선택해. 초안은 원래 소스에 보관돼.",
3409
+ "job.hubClosed": "명시적으로 종료됨",
3410
+ "job.hubPending": "진행 중 · 대기 요청 {0}개",
3396
3411
  "JOB_STREAM_FAILED": "JOB_STREAM_FAILED",
3397
3412
  "JOB_STREAM_INCOMPLETE": "JOB_STREAM_INCOMPLETE",
3398
3413
  "JOB_UNKNOWN": "JOB_UNKNOWN",
@@ -0,0 +1,14 @@
1
+ html, body, #job-hub { height: 100%; margin: 0; }
2
+ #job-hub { display: grid; grid-template: auto 1fr / minmax(12rem, 18rem) minmax(0, 1fr); color: var(--fg); background: var(--bg); }
3
+ .hub-header { grid-column: 1 / -1; display: flex; align-items: center; gap: 1rem; padding: .75rem 1rem; border-bottom: 1px solid var(--border); }
4
+ .hub-header h1 { margin: 0; font-size: 1rem; flex: 0 0 auto; }
5
+ .hub-header select { width: auto; min-width: 6rem; max-width: 12rem; flex: 0 0 auto; }
6
+ .hub-status { flex: 1; min-width: 0; color: var(--fg-muted); }
7
+ .hub-list { overflow: auto; border-right: 1px solid var(--border); padding: .5rem; }
8
+ .hub-list button { width: 100%; display: grid; gap: .25rem; margin-bottom: .5rem; padding: .75rem; text-align: left; }
9
+ .hub-list button[aria-pressed="true"] { border-color: var(--pass); }
10
+ .hub-list span { overflow-wrap: anywhere; }
11
+ .hub-job-state, .hub-job-source { color: var(--fg-muted); font-size: .8rem; }
12
+ .hub-stage { position: relative; min-width: 0; min-height: 0; }
13
+ .hub-stage iframe { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; }
14
+ .hub-stage iframe[hidden] { display: block !important; visibility: hidden; pointer-events: none; }
@@ -0,0 +1,5 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title></title><link rel="stylesheet" href="styles.css"><link rel="stylesheet" href="job-hub.css"></head>
4
+ <body data-job-hub><div id="job-hub"></div><script type="module" src="job-hub.js"></script></body>
5
+ </html>