@rig-c/review 2.4.6 → 2.6.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-cli.ts CHANGED
@@ -1,7 +1,12 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { JOB_API_SCHEMA, type JobAgentRequest } from './job-contract.ts';
3
- import { assertJobApiSchema, jobFailure, parseJobRequest } from './job-api.ts';
2
+ import {closeSync, constants, fstatSync, fsyncSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, writeSync} from 'node:fs';
3
+ import {join} from 'node:path';
4
+ import { JOB_API_SCHEMA, JOB_ACT_SCHEMA, JOB_RIG_REVIEW_ACT_SCHEMA, JOB_ENABLED_ACT_KINDS, jobRawActMediaType, jobStillByteLimit,
5
+ type JobAct, type JobAgentRequest, type JobNextRequest, type JobNextValue } from './job-contract.ts';
6
+ import { assertJobApiSchema, jobFailure, jobHash, jobId, jobInteger, jobObject, jobWaitLimitMs, parseJobRequest } from './job-api.ts';
4
7
  import { JobError } from './job-store.ts';
8
+ import {validatePngBytes} from './comment-crops.ts';
9
+ import {destinationDirectory} from './destination-directory.ts';
5
10
 
6
11
  export interface JobCLIOptions {
7
12
  readonly agentCapability?: string;
@@ -13,13 +18,18 @@ export interface JobCLIOptions {
13
18
  readonly fetch?: typeof fetch;
14
19
  readonly signal?: AbortSignal;
15
20
  readonly write?: (text: string) => void;
21
+ /** Trusted in-process consumer adapter only. Production consumers pipe the same grant on stdin. */
22
+ readonly consumerCapability?: string;
23
+ readonly consumerInput?: ReadableStream<Uint8Array>;
24
+ /** Checked partial writes for consumer stdout and disposable output-fault controls. */
25
+ readonly writeBytes?: (bytes: Uint8Array) => number;
16
26
  }
17
27
 
18
28
  const commonFlags = ['generation', 'key', 'request-id'];
19
29
  const verbFlags: Record<string, readonly string[]> = {
20
30
  publish: [...commonFlags, 'result', 'selector', 'freeze-hold', 'record', 'record-hash'],
21
31
  ask: [...commonFlags, 'publication', 'subject'],
22
- next: ['after', 'wait-ms', 'request-id'],
32
+ next: ['after', 'wait-ms', 'request-id', 'until'],
23
33
  close: [...commonFlags, 'reason'],
24
34
  };
25
35
 
@@ -49,21 +59,24 @@ function semanticJSON(value: string): unknown {
49
59
  /** Public semantic request construction only. There is no act-writing or
50
60
  * consumer-fetch verb, no internal JSON input file and no Review state access.
51
61
  */
52
- export function parseJobCLI(args: readonly string[]): { readonly endpoint: string; readonly request: JobAgentRequest } {
62
+ export function parseJobCLI(args: readonly string[]): { readonly endpoint: string; readonly request: JobAgentRequest; readonly waitUntilActMs?: number } {
53
63
  const [verb, locator, ...rest] = args;
54
64
  if (!verbFlags[verb]) throw new JobError('JOB_REQUEST_INVALID');
55
- let url: URL;
56
- try { url = new URL(locator); }
57
- catch { throw new JobError('JOB_REQUEST_INVALID'); }
58
- const match = /^\/jobs\/([A-Za-z0-9][A-Za-z0-9._-]*)\/?$/.exec(url.pathname);
59
- if (url.protocol !== 'http:' || url.hostname !== '127.0.0.1' || url.username || url.password || url.search || url.hash || !match) {
60
- throw new JobError('JOB_LOOPBACK_REQUIRED');
61
- }
65
+ const {url, job} = jobLocator(locator);
62
66
  const values = flags(rest, verbFlags[verb]);
63
- const base = { schema: JOB_API_SCHEMA, verb, jobId: match[1], requestId: values.get('request-id') ?? randomUUID() };
67
+ const base = { schema: JOB_API_SCHEMA, verb, jobId: job, requestId: values.get('request-id') ?? randomUUID() };
64
68
  let payload: unknown;
69
+ let waitUntilActMs: number | undefined;
65
70
  if (verb === 'next') {
66
- payload = { ...base, after: values.get('after') ?? null, waitMs: Number(values.get('wait-ms') ?? '0') };
71
+ let waitMs = Number(values.get('wait-ms') ?? '0');
72
+ if (values.has('until')) {
73
+ if (values.get('until') !== 'act' || !Number.isSafeInteger(waitMs) || waitMs < 1 || waitMs > 600_000) {
74
+ throw new JobError('JOB_REQUEST_INVALID');
75
+ }
76
+ waitUntilActMs = waitMs;
77
+ waitMs = Math.min(waitMs, jobWaitLimitMs);
78
+ }
79
+ payload = { ...base, after: values.get('after') ?? null, waitMs };
67
80
  } else {
68
81
  const mutation = { ...base, expectedGeneration: Number(required(values, 'generation')), idempotencyKey: required(values, 'key') };
69
82
  switch (verb) {
@@ -85,31 +98,233 @@ export function parseJobCLI(args: readonly string[]): { readonly endpoint: strin
85
98
  }
86
99
  const request = parseJobRequest(payload);
87
100
  if (request.verb === 'fetch-act') throw new JobError('JOB_AUTHORITY_REFUSED');
88
- return { endpoint: `${url.origin}/jobs/${match[1]}/api`, request };
101
+ return { endpoint: `${url.origin}/jobs/${job}/api`, request, ...(waitUntilActMs === undefined ? {} : {waitUntilActMs}) };
89
102
  }
90
103
 
91
- export async function jobCommand(args: readonly string[], options: JobCLIOptions = {}): Promise<void> {
92
- const write = options.write ?? (text => console.log(text));
93
- if (args[0] === 'open') {
94
- if (args.length !== 2 || !options.open) throw new JobError('JOB_AUTHORITY_REFUSED', 'Managed job opening requires the Review host');
95
- write((await options.open(args[1])).ownerUrl);
96
- return;
104
+ function jobLocator(locator: string): {url: URL; job: string} {
105
+ let url: URL;
106
+ try { url = new URL(locator); }
107
+ catch { throw new JobError('JOB_REQUEST_INVALID'); }
108
+ const match = /^\/jobs\/([A-Za-z0-9][A-Za-z0-9._-]*)\/?$/.exec(url.pathname);
109
+ if (url.protocol !== 'http:' || url.hostname !== '127.0.0.1' || url.username || url.password || url.search || url.hash || !match) {
110
+ throw new JobError('JOB_LOOPBACK_REQUIRED');
97
111
  }
98
- const input = parseJobCLI(args);
99
- const capability = options.agentCapability ?? process.env.RIG_REVIEW_JOB_AGENT_CAPABILITY;
100
- if (!capability) throw new JobError('JOB_CAPABILITY_REQUIRED');
101
- const response = await (options.fetch ?? fetch)(input.endpoint, {
102
- method: 'POST', redirect: 'error', signal: options.signal,
103
- headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + capability },
104
- body: JSON.stringify(input.request),
112
+ return {url, job: match[1]};
113
+ }
114
+
115
+ async function consumerBytes(stream: ReadableStream<Uint8Array> | null, maximum: number, signal?: AbortSignal): Promise<Buffer> {
116
+ if (!stream) throw new JobError('JOB_REQUEST_INVALID');
117
+ const reader = stream.getReader();
118
+ let timer: ReturnType<typeof setTimeout> | undefined;
119
+ let abort: (() => void) | undefined;
120
+ const interrupted = new Promise<never>((_resolve, reject) => {
121
+ abort = () => reject(new JobError('JOB_REQUEST_INVALID'));
122
+ timer = setTimeout(abort, 10_000);
123
+ signal?.addEventListener('abort', abort, {once: true});
124
+ if (signal?.aborted) abort();
105
125
  });
126
+ try {
127
+ const chunks: Uint8Array[] = [];
128
+ let length = 0;
129
+ for (;;) {
130
+ const {done, value} = await Promise.race([reader.read(), interrupted]);
131
+ if (done) break;
132
+ length += value.byteLength;
133
+ if (length > maximum) throw new JobError('JOB_BODY_LIMIT');
134
+ chunks.push(value);
135
+ }
136
+ return Buffer.concat(chunks, length);
137
+ } catch (error) {
138
+ void reader.cancel().catch(() => {});
139
+ if (error instanceof JobError) throw error;
140
+ throw new JobError('JOB_REQUEST_INVALID');
141
+ } finally {
142
+ clearTimeout(timer);
143
+ if (abort) signal?.removeEventListener('abort', abort);
144
+ reader.releaseLock();
145
+ }
146
+ }
147
+
148
+ function parseConsumerAct(bytes: Buffer, job: string, actId: string): JobAct {
149
+ let value: unknown;
150
+ try { value = JSON.parse(new TextDecoder('utf-8', {fatal: true}).decode(bytes)); }
151
+ catch { throw new JobError('JOB_REQUEST_INVALID'); }
152
+ const act = jobObject(value, ['schema', 'actId', 'jobId', 'askId', 'publicationId', 'kind', 'authority', 'at', 'source', 'value', 'still']);
153
+ if (act.jobId !== job || act.actId !== actId || (act.schema !== JOB_ACT_SCHEMA && act.schema !== JOB_RIG_REVIEW_ACT_SCHEMA)) {
154
+ throw new JobError('JOB_ACT_INVALID');
155
+ }
156
+ if (act.schema === JOB_RIG_REVIEW_ACT_SCHEMA) {
157
+ if (act.kind !== 'review-verdict' || (act.value as {stage?: unknown})?.stage !== 'rig-review') throw new JobError('JOB_ACT_INVALID');
158
+ const still = jobObject(act.still, ['path', 'sha256', 'camera', 'frame', 'animation']);
159
+ if (typeof still.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(still.sha256) ||
160
+ still.path !== still.sha256 + '.png' || still.camera !== 'fixed' ||
161
+ (still.frame === 'setup' ? still.animation !== undefined :
162
+ typeof still.frame !== 'number' || !Number.isFinite(still.frame) || still.frame < 0 ||
163
+ typeof still.animation !== 'string' || !still.animation)) throw new JobError('JOB_ACT_INVALID');
164
+ } else if (act.still !== undefined) throw new JobError('JOB_ACT_INVALID');
165
+ return act as unknown as JobAct;
166
+ }
167
+
168
+ function unlinkOwned(path: string, identity: {dev: number; ino: number}): void {
169
+ try {
170
+ const info = lstatSync(path);
171
+ if (info.dev === identity.dev && info.ino === identity.ino) unlinkSync(path);
172
+ } catch (error) {
173
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw new JobError('JOB_STILL_OUTPUT_FAILED');
174
+ }
175
+ }
176
+
177
+ function outputConsumerAct(actBytes: Buffer, png: Buffer | undefined, act: JobAct, destination: string | undefined, options: JobCLIOptions): void {
178
+ let temporary: string | undefined;
179
+ let temporaryIdentity: {dev: number; ino: number} | undefined;
180
+ let installed: string | undefined;
181
+ let installedIdentity: {dev: number; ino: number} | undefined;
182
+ let pngDescriptor: number | undefined;
183
+ let lock: string | undefined;
184
+ let lockDescriptor: number | undefined;
185
+ let emitted = 0;
186
+ try {
187
+ if (png && destination && act.schema === JOB_RIG_REVIEW_ACT_SCHEMA) {
188
+ const directory = destinationDirectory(destination, 'JOB_STILL_OUTPUT_FAILED', false);
189
+ const directoryDescriptor = openSync(directory, constants.O_RDONLY | (constants.O_DIRECTORY ?? 0) | constants.O_NOFOLLOW);
190
+ try {
191
+ const directoryIdentity = fstatSync(directoryDescriptor);
192
+ if (!directoryIdentity.isDirectory()) throw new JobError('JOB_STILL_OUTPUT_FAILED');
193
+ lock = join(directory, '.rig-review-still.lock');
194
+ try {
195
+ lockDescriptor = openSync(lock, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
196
+ } catch (error) {
197
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') {
198
+ throw new JobError('JOB_STILL_OUTPUT_FAILED',
199
+ `JOB_STILL_OUTPUT_FAILED: retained lock ${lock} already exists; wait for another writer to finish or remove ${lock} if a killed process left it`);
200
+ }
201
+ throw error;
202
+ }
203
+ const target = join(directory, act.still.path);
204
+ let existing = false;
205
+ try {
206
+ const descriptor = openSync(target, constants.O_RDONLY | constants.O_NOFOLLOW);
207
+ try {
208
+ const info = fstatSync(descriptor);
209
+ if (!info.isFile() || info.size > jobStillByteLimit || jobHash(readFileSync(descriptor)) !== act.still.sha256) {
210
+ throw new JobError('JOB_STILL_OUTPUT_FAILED');
211
+ }
212
+ existing = true;
213
+ } finally { closeSync(descriptor); }
214
+ } catch (error) {
215
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
216
+ }
217
+ if (!existing) {
218
+ temporary = join(directory, '.rig-review-still-' + randomUUID() + '.tmp');
219
+ const descriptor = openSync(temporary, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
220
+ // Pin this inode through output and ownership cleanup, even if its path is replaced.
221
+ pngDescriptor = descriptor;
222
+ const owned = fstatSync(descriptor);
223
+ temporaryIdentity = {dev: owned.dev, ino: owned.ino};
224
+ let offset = 0;
225
+ while (offset < png.byteLength) {
226
+ const written = writeSync(descriptor, png, offset, png.byteLength - offset);
227
+ if (written <= 0) throw new JobError('JOB_STILL_OUTPUT_FAILED');
228
+ offset += written;
229
+ }
230
+ fsyncSync(descriptor);
231
+ const info = fstatSync(descriptor);
232
+ installedIdentity = {dev: info.dev, ino: info.ino};
233
+ renameSync(temporary, target);
234
+ temporary = undefined;
235
+ installed = target;
236
+ }
237
+ const currentDirectory = lstatSync(directory);
238
+ if (currentDirectory.dev !== directoryIdentity.dev || currentDirectory.ino !== directoryIdentity.ino) {
239
+ throw new JobError('JOB_STILL_OUTPUT_FAILED');
240
+ }
241
+ fsyncSync(directoryDescriptor);
242
+ } finally { closeSync(directoryDescriptor); }
243
+ }
244
+ if (options.write && !options.writeBytes) {
245
+ // A legacy callback cannot report partial progress, so preserve an installed PNG on a thrown write.
246
+ emitted = actBytes.byteLength;
247
+ options.write(actBytes.toString('utf8'));
248
+ } else {
249
+ const write = options.writeBytes ?? (bytes => writeSync(1, bytes));
250
+ while (emitted < actBytes.byteLength) {
251
+ const written = write(actBytes.subarray(emitted));
252
+ if (!Number.isSafeInteger(written) || written <= 0 || written > actBytes.byteLength - emitted) throw new JobError('JOB_STILL_OUTPUT_FAILED');
253
+ emitted += written;
254
+ }
255
+ }
256
+ } catch (error) {
257
+ if (emitted === 0 && installed && installedIdentity) {
258
+ unlinkOwned(installed, installedIdentity);
259
+ }
260
+ throw error instanceof JobError ? error : new JobError('JOB_STILL_OUTPUT_FAILED');
261
+ } finally {
262
+ try {
263
+ try {
264
+ if (temporary && temporaryIdentity) unlinkOwned(temporary, temporaryIdentity);
265
+ } finally {
266
+ if (lockDescriptor !== undefined) {
267
+ try { unlinkOwned(lock!, fstatSync(lockDescriptor)); }
268
+ finally { closeSync(lockDescriptor); }
269
+ }
270
+ }
271
+ } finally {
272
+ if (pngDescriptor !== undefined) closeSync(pngDescriptor);
273
+ }
274
+ }
275
+ }
276
+
277
+ async function fetchActCommand(args: readonly string[], options: JobCLIOptions): Promise<void> {
278
+ const {url, job} = jobLocator(args[1]);
279
+ const rest = args.slice(2);
280
+ const stdinFlags = rest.filter(value => value === '--consumer-capability-stdin').length;
281
+ if (stdinFlags > 1 || (stdinFlags === 0 && !options.consumerCapability) || (stdinFlags && options.consumerCapability)) throw new JobError('JOB_REQUEST_INVALID');
282
+ const values = flags(rest.filter(value => value !== '--consumer-capability-stdin'), ['act', 'still-out', 'request-id']);
283
+ const actId = jobId(required(values, 'act'));
284
+ const input = options.consumerCapability ?? (await consumerBytes(options.consumerInput ?? Bun.stdin.stream(), 4096, options.signal)).toString('utf8');
285
+ const capability = input.replace(/\r?\n$/, '');
286
+ if (!/^[a-f0-9]{64}$/.test(capability)) throw new JobError('JOB_CAPABILITY_REQUIRED');
287
+ const request = {schema: JOB_API_SCHEMA, verb: 'fetch-act', jobId: job, actId, requestId: values.get('request-id') ?? randomUUID()};
288
+ async function read(accept: string, maximum: number): Promise<Buffer> {
289
+ const response = await (options.fetch ?? fetch)(`${url.origin}/jobs/${job}/api`, {
290
+ method: 'POST', redirect: 'error', signal: options.signal,
291
+ headers: {'Content-Type': 'application/json', Authorization: 'Bearer ' + capability, Accept: accept},
292
+ body: JSON.stringify(request),
293
+ });
294
+ const bytes = await consumerBytes(response.body, maximum, options.signal);
295
+ if (!response.ok) {
296
+ let failure: unknown;
297
+ try { failure = JSON.parse(bytes.toString('utf8')); } catch {}
298
+ const code = (failure as {error?: {code?: unknown}})?.error?.code;
299
+ throw new JobError('JOB_REQUEST_INVALID', typeof code === 'string' && /^JOB_[A-Z_]+$/.test(code) ? code : 'JOB_REQUEST_INVALID');
300
+ }
301
+ if (response.headers.get('content-type')?.split(';')[0] !== accept) throw new JobError('JOB_REQUEST_INVALID');
302
+ return bytes;
303
+ }
304
+ const bytes = await read(jobRawActMediaType, 512 * 1024);
305
+ const act = parseConsumerAct(bytes, job, actId);
306
+ const destination = values.get('still-out');
307
+ if (act.schema === JOB_RIG_REVIEW_ACT_SCHEMA && destination === undefined) throw new JobError('JOB_STILL_OUTPUT_FAILED');
308
+ let png: Buffer | undefined;
309
+ if (destination !== undefined) {
310
+ if (act.schema !== JOB_RIG_REVIEW_ACT_SCHEMA) throw new JobError('JOB_STILL_UNAVAILABLE');
311
+ png = await read('image/png', jobStillByteLimit);
312
+ try {
313
+ if (png.length < 33 || jobHash(png) !== act.still.sha256) throw new Error('hash');
314
+ validatePngBytes(png, png.readUInt32BE(16), png.readUInt32BE(20));
315
+ } catch { throw new JobError('JOB_STILL_CAPTURE_FAILED'); }
316
+ }
317
+ outputConsumerAct(bytes, png, act, destination, options);
318
+ }
319
+
320
+ async function readJobResponse(response: Response, interrupted?: Promise<never>): Promise<unknown> {
106
321
  const reader = response.body?.getReader();
107
322
  if (!reader) throw new JobError('JOB_REQUEST_INVALID');
108
323
  const chunks: Uint8Array[] = [];
109
324
  let size = 0;
110
325
  try {
111
326
  for (;;) {
112
- const { done, value } = await reader.read();
327
+ const { done, value } = await (interrupted ? Promise.race([reader.read(), interrupted]) : reader.read());
113
328
  if (done) break;
114
329
  size += value.byteLength;
115
330
  if (size > 1024 * 1024) {
@@ -118,6 +333,11 @@ export async function jobCommand(args: readonly string[], options: JobCLIOptions
118
333
  }
119
334
  chunks.push(value);
120
335
  }
336
+ } catch (error) {
337
+ if (interrupted) {
338
+ try { void reader.cancel().catch(() => {}); } catch {}
339
+ }
340
+ throw error;
121
341
  } finally {
122
342
  reader.releaseLock();
123
343
  }
@@ -125,6 +345,149 @@ export async function jobCommand(args: readonly string[], options: JobCLIOptions
125
345
  try { value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks, size))); }
126
346
  catch { throw new JobError('JOB_REQUEST_INVALID'); }
127
347
  assertJobApiSchema(value !== null && typeof value === 'object' ? (value as { schema?: unknown }).schema : undefined);
348
+ return value;
349
+ }
350
+
351
+ /** Check the complete existing next batch before accepting its read cursor. */
352
+ function nextValue(value: unknown, request: JobNextRequest): JobNextValue {
353
+ const result = jobObject(value, ['schema', 'verb', 'jobId', 'requestId', 'generation', 'ok', 'value']);
354
+ if (result.ok !== true || result.verb !== 'next' || result.jobId !== request.jobId) throw new JobError('JOB_REQUEST_INVALID');
355
+ jobInteger(result.generation);
356
+ const batch = jobObject(result.value, ['capabilities', 'events', 'cursor', 'status']);
357
+ if (!Array.isArray(batch.events) || !['events', 'timeout', 'closed'].includes(batch.status as string)) throw new JobError('JOB_REQUEST_INVALID');
358
+ if (batch.cursor !== null) jobId(batch.cursor);
359
+ for (const raw of batch.events) {
360
+ const event = jobObject(raw, ['cursor', 'jobId', 'generation', 'type', 'publication', 'ask', 'act', 'reason']);
361
+ jobId(event.cursor);
362
+ jobInteger(event.generation);
363
+ if (event.jobId !== request.jobId) throw new JobError('JOB_REQUEST_INVALID');
364
+ switch (event.type) {
365
+ case 'act': {
366
+ const actId = jobId((event.act as {actId?: unknown} | null)?.actId);
367
+ const act = parseConsumerAct(Buffer.from(JSON.stringify(event.act)), request.jobId, actId);
368
+ if (!(JOB_ENABLED_ACT_KINDS as readonly string[]).includes(act.kind)) throw new JobError('JOB_ACT_INVALID');
369
+ break;
370
+ }
371
+ case 'published':
372
+ case 'pending': {
373
+ const payload = event.type === 'published' ? event.publication : event.ask;
374
+ if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) throw new JobError('JOB_REQUEST_INVALID');
375
+ break;
376
+ }
377
+ case 'closed':
378
+ if (typeof event.reason !== 'string') throw new JobError('JOB_REQUEST_INVALID');
379
+ break;
380
+ default: throw new JobError('JOB_REQUEST_INVALID');
381
+ }
382
+ }
383
+ const last = batch.events.at(-1);
384
+ if (batch.cursor !== (last?.cursor ?? request.after) || (batch.status === 'events') !== (batch.events.length > 0)) {
385
+ throw new JobError('JOB_REQUEST_INVALID');
386
+ }
387
+ return batch as unknown as JobNextValue;
388
+ }
389
+
390
+ async function waitForAct(endpoint: string, initial: JobNextRequest, waitMs: number, capability: string,
391
+ write: (text: string) => void, options: JobCLIOptions): Promise<void> {
392
+ const controller = new AbortController();
393
+ const timeout = new Error('JOB_NEXT_TIMEOUT');
394
+ const cancel = () => controller.abort(options.signal?.reason);
395
+ options.signal?.addEventListener('abort', cancel, {once: true});
396
+ if (options.signal?.aborted) cancel();
397
+ const deadline = performance.now() + waitMs;
398
+ let timer: ReturnType<typeof setTimeout> | undefined;
399
+ const expire = () => {
400
+ if (controller.signal.aborted) return;
401
+ const budget = deadline - performance.now();
402
+ if (budget <= 0) controller.abort(timeout);
403
+ else timer = setTimeout(expire, Math.ceil(budget));
404
+ };
405
+ timer = setTimeout(expire, waitMs);
406
+ const interrupted = new Promise<never>((_resolve, reject) => {
407
+ controller.signal.addEventListener('abort', () => reject(controller.signal.reason), {once: true});
408
+ if (controller.signal.aborted) reject(controller.signal.reason);
409
+ });
410
+ // Pre-cancellation can reject before the first network race is installed.
411
+ void interrupted.catch(() => {});
412
+ function remaining(): number {
413
+ const budget = deadline - performance.now();
414
+ if (!controller.signal.aborted && budget <= 0) controller.abort(timeout);
415
+ controller.signal.throwIfAborted();
416
+ return budget;
417
+ }
418
+ let after = initial.after;
419
+ let lastResponse: unknown;
420
+ try {
421
+ for (;;) {
422
+ const budget = remaining();
423
+ const request = {...initial, after, waitMs: Math.max(0, Math.floor(Math.min(budget, jobWaitLimitMs)))};
424
+ // A delayed transport must also dispose its body if cancellation won the race.
425
+ const pending = (options.fetch ?? fetch)(endpoint, {
426
+ method: 'POST', redirect: 'error', signal: controller.signal,
427
+ headers: {'Content-Type': 'application/json', Authorization: 'Bearer ' + capability},
428
+ body: JSON.stringify(request),
429
+ }).then(response => {
430
+ if (controller.signal.aborted) {
431
+ try { void response.body?.cancel().catch(() => {}); } catch {}
432
+ controller.signal.throwIfAborted();
433
+ }
434
+ return response;
435
+ });
436
+ const response = await Promise.race([pending, interrupted]);
437
+ const value = await readJobResponse(response, interrupted);
438
+ remaining();
439
+ if (!response.ok || (value as {ok?: unknown}).ok === false) {
440
+ write(JSON.stringify(value));
441
+ process.exitCode = 1;
442
+ return;
443
+ }
444
+ const batch = nextValue(value, request);
445
+ remaining();
446
+ if (batch.events.some(event => event.type === 'act')) {
447
+ write(JSON.stringify(value));
448
+ return;
449
+ }
450
+ if (batch.status === 'closed' || batch.events.some(event => event.type === 'closed')) {
451
+ write(JSON.stringify(value));
452
+ console.error('JOB_CLOSED');
453
+ process.exitCode = 1;
454
+ return;
455
+ }
456
+ lastResponse = value;
457
+ after = batch.cursor;
458
+ }
459
+ } catch (error) {
460
+ if (!controller.signal.aborted && performance.now() >= deadline) controller.abort(timeout);
461
+ if (controller.signal.reason !== timeout) throw error;
462
+ if (lastResponse !== undefined) write(JSON.stringify(lastResponse));
463
+ console.error('JOB_NEXT_TIMEOUT');
464
+ process.exitCode = 3;
465
+ } finally {
466
+ clearTimeout(timer);
467
+ options.signal?.removeEventListener('abort', cancel);
468
+ }
469
+ }
470
+
471
+ export async function jobCommand(args: readonly string[], options: JobCLIOptions = {}): Promise<void> {
472
+ if (args[0] === 'fetch-act') return fetchActCommand(args, options);
473
+ const write = options.write ?? (text => console.log(text));
474
+ if (args[0] === 'open') {
475
+ if (args.length !== 2 || !options.open) throw new JobError('JOB_AUTHORITY_REFUSED', 'Managed job opening requires the Review host');
476
+ write((await options.open(args[1])).ownerUrl);
477
+ return;
478
+ }
479
+ const input = parseJobCLI(args);
480
+ const capability = options.agentCapability ?? process.env.RIG_REVIEW_JOB_AGENT_CAPABILITY;
481
+ if (!capability) throw new JobError('JOB_CAPABILITY_REQUIRED');
482
+ if (input.waitUntilActMs !== undefined && input.request.verb === 'next') {
483
+ return waitForAct(input.endpoint, input.request, input.waitUntilActMs, capability, write, options);
484
+ }
485
+ const response = await (options.fetch ?? fetch)(input.endpoint, {
486
+ method: 'POST', redirect: 'error', signal: options.signal,
487
+ headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + capability },
488
+ body: JSON.stringify(input.request),
489
+ });
490
+ const value = await readJobResponse(response);
128
491
  write(JSON.stringify(value));
129
492
  if (!response.ok) process.exitCode = 1;
130
493
  }
@@ -13,6 +13,11 @@
13
13
 
14
14
  export const JOB_API_SCHEMA = 'rig-review/job-api@2' as const;
15
15
  export const JOB_ACT_SCHEMA = 'rig-review/act@2' as const;
16
+ /** New rig verdicts only. Store/reuse markers and all other acts retain @2. */
17
+ export const JOB_RIG_REVIEW_ACT_SCHEMA = 'rig-review/act@3' as const;
18
+ export const jobStillByteLimit = 8 * 1024 * 1024;
19
+ export const jobCaptureBodyLimit = 12 * 1024 * 1024;
20
+ export const jobRawActMediaType = 'application/vnd.rig-review.act+json';
16
21
  export const JOB_PARTS_ENUMERATOR_RANGE = '>=2.25.0 <3.0.0' as const;
17
22
 
18
23
  export const JOB_ENABLED_ACT_KINDS = [
@@ -284,7 +289,7 @@ export interface JobActSources {
284
289
  * Checkpoint stage is derived by Create. Plan-bound signoff requirements apply
285
290
  * to every stage in JOB_PLAN_BOUND_SIGNOFF_STAGES before act creation.
286
291
  */
287
- export type JobAct = {
292
+ export type JobLegacyAct = {
288
293
  [Kind in JobEnabledActKind]: {
289
294
  readonly schema: typeof JOB_ACT_SCHEMA;
290
295
  readonly actId: JobActId;
@@ -300,6 +305,50 @@ export type JobAct = {
300
305
  ) : {readonly source: JobActSources[Kind]; readonly value: JobActValues[Kind]});
301
306
  }[JobEnabledActKind];
302
307
 
308
+ export type JobRigStill = {
309
+ readonly path: string;
310
+ readonly sha256: JobSha256;
311
+ readonly camera: 'fixed';
312
+ } & (
313
+ | {readonly frame: 'setup'; readonly animation?: never}
314
+ | {readonly frame: number; readonly animation: string}
315
+ );
316
+
317
+ export type JobRigReviewAct = Omit<Extract<JobLegacyAct, {kind: 'review-verdict'}>, 'schema' | 'source' | 'value'> & {
318
+ readonly schema: typeof JOB_RIG_REVIEW_ACT_SCHEMA;
319
+ readonly source: JobModelSourceBinding & {
320
+ readonly selector: Extract<JobSelector, {kind: 'rig'}>;
321
+ readonly model: JobFileIdentity;
322
+ };
323
+ readonly value: JobModelReviewValue & {readonly stage: 'rig-review'};
324
+ readonly still: JobRigStill;
325
+ };
326
+
327
+ /** Historical @2 rig acts remain readable without being backfilled or relabelled. */
328
+ export type JobAct = JobLegacyAct | JobRigReviewAct;
329
+
330
+ /** Authenticated browser provenance. The daemon validates identity and hashes PNG bytes. */
331
+ export interface JobRigCapture {
332
+ readonly png: string;
333
+ readonly width: number;
334
+ readonly height: number;
335
+ readonly camera: 'fixed';
336
+ readonly framing: 'default';
337
+ readonly view: 'whole-rig';
338
+ readonly frame: 'setup' | number;
339
+ readonly animation?: string;
340
+ readonly playing: boolean;
341
+ readonly binding: {
342
+ readonly publicationId: JobPublicationId;
343
+ readonly instanceKey: string;
344
+ readonly sourceHash: JobSha256;
345
+ readonly pageId: string;
346
+ readonly askId: JobAskId;
347
+ readonly drawGeneration: number;
348
+ readonly playerGeneration: number;
349
+ };
350
+ }
351
+
303
352
  export type JobSubject =
304
353
  | { readonly kind: 'interview-picks'; readonly questionId: string; readonly setId: string }
305
354
  | {
@@ -435,6 +484,12 @@ export const JOB_ERROR_CODES = [
435
484
  'JOB_ACT_KIND_DISABLED',
436
485
  'JOB_ACT_SOURCE_STALE',
437
486
  'JOB_DISPLAY_MISMATCH',
487
+ 'JOB_STILL_CAPTURE_FAILED',
488
+ 'JOB_STILL_CAMERA_NOT_FIXED',
489
+ 'JOB_STILL_VIEW_UNSUPPORTED',
490
+ 'JOB_STILL_BINDING_MISMATCH',
491
+ 'JOB_STILL_UNAVAILABLE',
492
+ 'JOB_STILL_OUTPUT_FAILED',
438
493
  'JOB_CURSOR_INVALID',
439
494
  'JOB_STORAGE_FAILED',
440
495
  'JOB_AGENT_ISOLATION_HOLE',
@@ -502,6 +557,7 @@ export type JobUISubmission = {
502
557
  readonly submissionId: string;
503
558
  readonly kind: Kind;
504
559
  readonly value: JobUIActValues[Kind];
560
+ readonly capture?: Kind extends 'review-verdict' ? JobRigCapture : never;
505
561
  };
506
562
  }[JobEnabledActKind];
507
563
 
package/src/job-host.ts CHANGED
@@ -47,6 +47,10 @@ export type {
47
47
  JobUIActValues,
48
48
  JobActSources,
49
49
  JobAct,
50
+ JobLegacyAct,
51
+ JobRigReviewAct,
52
+ JobRigStill,
53
+ JobRigCapture,
50
54
  JobSubject,
51
55
  JobPendingAsk,
52
56
  JobPublication,
@@ -1,11 +1,11 @@
1
1
  import { randomBytes, randomUUID } from 'node:crypto';
2
2
  import { isAbsolute, relative, sep } from 'node:path';
3
3
  import {
4
- JOB_API_SCHEMA, JOB_ACT_SCHEMA, JOB_CAPABILITIES, JOB_ENABLED_ACT_KINDS, type JobPartsEnumerator, type JobAct, type JobAgentRequest, type JobDisplayAcknowledgment,
4
+ JOB_API_SCHEMA, JOB_ACT_SCHEMA, JOB_RIG_REVIEW_ACT_SCHEMA, jobStillByteLimit, JOB_CAPABILITIES, JOB_ENABLED_ACT_KINDS, type JobPartsEnumerator, type JobAct, type JobAgentRequest, type JobDisplayAcknowledgment,
5
5
  type JobDisplayPublication, type JobDisplayReceipt, type JobEvent, type JobFetchActRequest,
6
6
  type JobNextValue, type JobPendingAsk, type JobPublication, type JobReviewerBinding, type JobStatus,
7
7
  } from './job-contract.ts';
8
- import { bindJobAsk, finalizeJobAct, parseUISubmission } from './job-act.ts';
8
+ import { bindJobAsk, finalizeJobAct, parseUISubmission, prepareJobStill } from './job-act.ts';
9
9
  import { jobHash, jobPartsEnumeratorVersion, jobWaitLimitMs, requestDigest, sameCapability } from './job-api.ts';
10
10
  import {
11
11
  assertJobRoot, assertJobSourceCurrent, captureJobRoot, prepareJobSource, jobSnapshotHash, removeOwnedJobSnapshot,
@@ -397,6 +397,26 @@ export class JobSession {
397
397
  }
398
398
  }
399
399
 
400
+ /** Bounded immutable bytes selected only through the authenticated consumer port. */
401
+ readActExport(actId: string, png: boolean): Buffer {
402
+ const current = this.current();
403
+ if (!current.active) throw new JobError('JOB_CLOSED');
404
+ const act = current.data.acts[actId];
405
+ if (!act) throw new JobError('JOB_ACT_UNKNOWN');
406
+ if (act.schema !== JOB_RIG_REVIEW_ACT_SCHEMA) {
407
+ if (png) throw new JobError('JOB_STILL_UNAVAILABLE');
408
+ return Buffer.from(JSON.stringify(act));
409
+ }
410
+ const stored = this.store.readStill(this.jobId, actId);
411
+ if (!stored || stored.png.byteLength > jobStillByteLimit || stored.actBytes.byteLength > maximumEventBytes ||
412
+ stored.sha256 !== act.still.sha256 || jobHash(stored.png) !== act.still.sha256 ||
413
+ act.still.path !== act.still.sha256 + '.png' ||
414
+ !Buffer.from(stored.actBytes).equals(Buffer.from(JSON.stringify(act)))) {
415
+ throw new JobError('JOB_STILL_CAPTURE_FAILED');
416
+ }
417
+ return Buffer.from(png ? stored.png : stored.actBytes);
418
+ }
419
+
400
420
  ackDisplayed(input: JobDisplayAcknowledgment): JobDisplayReceipt {
401
421
  const current = this.current();
402
422
  let receipt: JobDisplayReceipt;
@@ -434,13 +454,20 @@ export class JobSession {
434
454
  if (!ask) throw new JobError('JOB_ASK_INVALID');
435
455
  const retained = fresh.data.publications[input.publicationId].retained;
436
456
  assertJobSourceCurrent(retained);
437
- act = finalizeJobAct({ jobId: this.jobId, submission: input, ask, retained, reviewer: fresh.data.reviewer });
457
+ const captured = ask.subject.kind === 'review-verdict' && ask.subject.stage === 'rig-review' ?
458
+ prepareJobStill(input, ask, retained) : undefined;
459
+ act = finalizeJobAct({ jobId: this.jobId, submission: input, ask, retained, reviewer: fresh.data.reviewer,
460
+ still: captured?.still });
438
461
  fresh.data.generation++;
439
462
  fresh.data.acts[act.actId] = act;
440
463
  fresh.data.asks[ask.askId] = { ...ask, status: 'answered' };
441
464
  fresh.data.replays[key] = { digest, value: act };
442
465
  this.event(fresh.data, { type: 'act', act } as Omit<JobEvent, 'cursor' | 'jobId' | 'generation'>);
443
- return { data: fresh.data };
466
+ return { data: fresh.data, ...(captured ? {still: {
467
+ actId: act.actId, pageId: input.pageId, submissionId: input.submissionId,
468
+ sha256: captured.still.sha256, binding: JSON.stringify(captured.binding),
469
+ png: captured.bytes, actBytes: Buffer.from(JSON.stringify(act)),
470
+ }} : {}) };
444
471
  }, fresh => {
445
472
  const raced = this.replay(fresh.data, key, digest);
446
473
  if (!raced) return false;