@promptdriven/runtime-client 1.0.0 → 1.1.1
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/package.json +1 -1
- package/src/runtime/agent-chat.mjs +55 -8
- package/src/runtime/index.mjs +41 -1
- package/src/runtime/live-local-bridge.mjs +178 -0
- package/src/runtime/live-local.mjs +181 -0
- package/src/runtime/run-program.mjs +798 -0
- package/src/runtime/runtime-bindings.mjs +28 -18
- package/src/runtime/runtime-check-plan.mjs +19 -27
- package/src/runtime/runtime-check-reconcile.mjs +328 -0
- package/src/runtime/runtime-client.mjs +2797 -345
- package/src/runtime/runtime-outcome.mjs +66 -2
- package/src/runtime/runtime-output.mjs +202 -15
- package/src/runtime/runtime-preflight.mjs +994 -87
- package/src/runtime/runtime-slots.mjs +75 -4
- package/src/runtime/runtime-stream.mjs +125 -0
- package/src/runtime/scenario-json.mjs +167 -1
- package/src/runtime/secret-redaction.mjs +3 -2
- package/src/runtime/try-doors.mjs +426 -59
- package/src/runtime/try-http.mjs +49 -15
- package/src/runtime/try-update-policy.mjs +43 -0
|
@@ -12,6 +12,7 @@ const order = (a, b) => a.started_at - b.started_at || (a.id < b.id ? -1 : a.id
|
|
|
12
12
|
const snapshotKey = row => JSON.stringify([row.id, row.pid, row.state, row.kind, row.started_at, row.request_ids]);
|
|
13
13
|
const nativeSnapshotKey = row => row.state === undefined ? JSON.stringify([row.id, row.pid, row.choosing, row.number]) : snapshotKey(row);
|
|
14
14
|
const rememberNativeOwnership = Symbol('rememberNativeOwnership');
|
|
15
|
+
const commitCheckRegistration = Symbol('commitCheckRegistration');
|
|
15
16
|
const directoryFor = ({ stateDir, origin }) => join(stateDir, 'slots', encodeURIComponent(new URL(origin).host));
|
|
16
17
|
const nativeInterrupt = handler => {
|
|
17
18
|
const signals = ['SIGINT', 'SIGHUP', 'SIGTERM'];
|
|
@@ -84,6 +85,37 @@ function nativeFilePort(ports) {
|
|
|
84
85
|
try { writeFileSync(fd, `${JSON.stringify(record)}\n`); fsyncSync(fd); } finally { closeSync(fd); }
|
|
85
86
|
renameSync(temporary, path); remember(path, record); files.touch(path);
|
|
86
87
|
},
|
|
88
|
+
readCheckStart({ directory }) {
|
|
89
|
+
try {
|
|
90
|
+
const at = readRecord(join(directory, '.check-start')).at;
|
|
91
|
+
if (!Number.isFinite(at) || at < 0) throw new Error('Invalid check pacing state');
|
|
92
|
+
return at;
|
|
93
|
+
}
|
|
94
|
+
catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
95
|
+
},
|
|
96
|
+
writeCheckStart({ directory, at }) { files.writeAtomic(join(directory, '.check-start'), { at }); },
|
|
97
|
+
[commitCheckRegistration]({ path, previous, next, at }) {
|
|
98
|
+
const pacing = join(resolve(path, '..'), '.check-start');
|
|
99
|
+
let staged = false;
|
|
100
|
+
try {
|
|
101
|
+
// A partial native commit must remain unavailable after process death,
|
|
102
|
+
// rather than leave a recorded ID with an absent or stale start time.
|
|
103
|
+
files.writeAtomic(pacing, { at: null }); staged = true;
|
|
104
|
+
files.writeAtomic(path, next);
|
|
105
|
+
files.writeAtomic(pacing, { at: ports.now() });
|
|
106
|
+
} catch (error) {
|
|
107
|
+
if (staged) {
|
|
108
|
+
try {
|
|
109
|
+
const current = readRecord(path);
|
|
110
|
+
if (snapshotKey(current) === snapshotKey(next)) files.writeAtomic(path, previous);
|
|
111
|
+
else if (snapshotKey(current) !== snapshotKey(previous)) throw new Error('Runtime reservation ownership changed');
|
|
112
|
+
if (at === null) files.unlink(pacing);
|
|
113
|
+
else files.writeAtomic(pacing, { at });
|
|
114
|
+
} catch { /* Retain unavailable timing when exact rollback cannot complete. */ }
|
|
115
|
+
}
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
},
|
|
87
119
|
modifiedAt(path) {
|
|
88
120
|
const claim = path.endsWith('/claim.json');
|
|
89
121
|
path = actual(path); if (!path) return null;
|
|
@@ -120,7 +152,7 @@ function defaults(given = {}) {
|
|
|
120
152
|
return ports;
|
|
121
153
|
}
|
|
122
154
|
const nativeFiles = nativeFilePort({ now: Date.now, randomUUID, isAlive: alive });
|
|
123
|
-
const owners = new Map(), reservationOwners = new WeakMap(), probes = new Map();
|
|
155
|
+
const owners = new Map(), reservationOwners = new WeakMap(), probes = new Map(), incompleteCheckStarts = new Map();
|
|
124
156
|
let claimSections = 0;
|
|
125
157
|
const claimWaiters = new Set();
|
|
126
158
|
function leaveClaim() { if (--claimSections === 0) { for (const done of claimWaiters) done(); claimWaiters.clear(); } }
|
|
@@ -344,16 +376,54 @@ export async function recordRuntimeRequest(reservation, requestId, given = {}) {
|
|
|
344
376
|
throw unavailable(new Error('Runtime reservation ownership changed'));
|
|
345
377
|
}
|
|
346
378
|
if (!row || row.state !== 'active') throw unavailable(new Error('Missing runtime reservation'));
|
|
379
|
+
const readStart = ports.files.readCheckStart, writeStart = ports.files.writeCheckStart;
|
|
380
|
+
const paced = row.kind === 'check' && (readStart !== undefined || writeStart !== undefined);
|
|
381
|
+
let at;
|
|
382
|
+
if (paced) {
|
|
383
|
+
if (incompleteCheckStarts.has(reservation.directory)) throw unavailable(new Error('Incomplete check pacing commit'));
|
|
384
|
+
if (typeof readStart !== 'function' || typeof writeStart !== 'function') throw unavailable(new Error('Incomplete check pacing storage'));
|
|
385
|
+
try { at = await readStart.call(ports.files, { directory: reservation.directory }); }
|
|
386
|
+
catch (error) { throw unavailable(error); }
|
|
387
|
+
if (at !== null && (!Number.isFinite(at) || at < 0)) throw unavailable(new Error('Invalid check pacing state'));
|
|
388
|
+
}
|
|
347
389
|
if (!row.request_ids.includes(requestId)) {
|
|
390
|
+
if (paced) {
|
|
391
|
+
const wait = at === null ? 0 : Math.max(0, at + 1000 - ports.now());
|
|
392
|
+
if (wait > 0) return { wait };
|
|
393
|
+
}
|
|
394
|
+
if (ended() || !await ownsClaim()) return false;
|
|
348
395
|
const next = { ...row, request_ids: [...row.request_ids, requestId] };
|
|
349
|
-
|
|
396
|
+
if (paced && ports.files[commitCheckRegistration]) {
|
|
397
|
+
try { await ports.files[commitCheckRegistration]({ path, previous: row, next, at }); }
|
|
398
|
+
catch (error) { throw unavailable(error); }
|
|
399
|
+
} else {
|
|
400
|
+
await ports.files.writeAtomic(path, next);
|
|
401
|
+
if (owner) { owner.snapshot = snapshotKey(next); owner[rememberNativeOwnership]?.(path, next); }
|
|
402
|
+
if (paced) {
|
|
403
|
+
try { await writeStart.call(ports.files, { directory: reservation.directory, at: ports.now() }); }
|
|
404
|
+
catch (error) {
|
|
405
|
+
incompleteCheckStarts.set(reservation.directory, path);
|
|
406
|
+
try {
|
|
407
|
+
const current = (await rows(ports.files, reservation.directory)).find(item => item.id === row.id);
|
|
408
|
+
if (snapshotKey(current) === snapshotKey(next) && await ownsClaim()) {
|
|
409
|
+
await ports.files.writeAtomic(path, row);
|
|
410
|
+
incompleteCheckStarts.delete(reservation.directory);
|
|
411
|
+
}
|
|
412
|
+
} catch { /* An uncertain predecessor must not become accepted ownership. */
|
|
413
|
+
} finally {
|
|
414
|
+
if (owner) { owner.snapshot = snapshotKey(row); owner[rememberNativeOwnership]?.(path, row); }
|
|
415
|
+
}
|
|
416
|
+
throw unavailable(error);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
350
420
|
if (owner) { owner.snapshot = snapshotKey(next); owner[rememberNativeOwnership]?.(path, next); }
|
|
351
421
|
}
|
|
352
422
|
if (owner) owner.posted = true;
|
|
353
423
|
});
|
|
354
|
-
if (result.claimed) return result.value !== false;
|
|
424
|
+
if (result.claimed && !result.value?.wait) return result.value !== false;
|
|
355
425
|
const remaining = ports.deadline === undefined ? Infinity : Math.max(0, ports.deadline - ports.now());
|
|
356
|
-
await ports.sleep(Math.min(remaining, Math.max(10, retryDelay(ports, ++failures, false, remaining))));
|
|
426
|
+
await ports.sleep(Math.min(remaining, result.value?.wait ?? Math.max(10, retryDelay(ports, ++failures, false, remaining))));
|
|
357
427
|
}
|
|
358
428
|
} finally { off(); }
|
|
359
429
|
}
|
|
@@ -368,6 +438,7 @@ export async function releaseRuntimeSlot(reservation, { ended }, given = {}) {
|
|
|
368
438
|
if (!row || snapshotKey(row) !== owner.snapshot) return;
|
|
369
439
|
}
|
|
370
440
|
await ports.files.unlink(path);
|
|
441
|
+
if (incompleteCheckStarts.get(reservation.directory) === path) incompleteCheckStarts.delete(reservation.directory);
|
|
371
442
|
}
|
|
372
443
|
}
|
|
373
444
|
export async function listRuntimeJobs(options, ports = {}) {
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// Adaptive polling schedule, Wait-Prefer headers, and Codex-style SSE stream parsing.
|
|
2
|
+
export const WAIT_PREFER_CALL_SECONDS = 15;
|
|
3
|
+
export const WAIT_PREFER_RUN_SECONDS = 25;
|
|
4
|
+
export const SSE_IDLE_MS = 45_000;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Adaptive polling cadence when no explicit pollMs override is injected by callers/tests:
|
|
8
|
+
* 250ms for the first 2000ms -> 500ms for the next 4000ms -> 1000ms cap.
|
|
9
|
+
*/
|
|
10
|
+
export function adaptivePollMs(elapsedMs, explicitPollMs) {
|
|
11
|
+
if (explicitPollMs !== undefined) return explicitPollMs;
|
|
12
|
+
const elapsed = Number.isFinite(elapsedMs) && elapsedMs > 0 ? elapsedMs : 0;
|
|
13
|
+
if (elapsed < 2000) return 250;
|
|
14
|
+
if (elapsed < 6000) return 500;
|
|
15
|
+
return 1000;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function preferWaitHeaders(seconds, extra = {}) {
|
|
19
|
+
const wait = Number.isFinite(seconds) && seconds > 0 ? Math.max(1, Math.min(25, Math.floor(seconds))) : 0;
|
|
20
|
+
return wait > 0 ? { ...extra, Prefer: `respond-async, wait=${wait}` } : { ...extra };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function isSseContentType(headers) {
|
|
24
|
+
const raw = typeof headers?.get === 'function' ? headers.get('content-type') : headers?.['content-type'];
|
|
25
|
+
if (typeof raw !== 'string') return false;
|
|
26
|
+
return raw.split(';', 1)[0].trim().toLowerCase() === 'text/event-stream';
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Incrementally parse an HTTP response body formatted as text/event-stream.
|
|
31
|
+
* Resets the idle timer on every received chunk (including `: keepalive` comments).
|
|
32
|
+
*/
|
|
33
|
+
export async function parseSseStream(body, { onEvent, signal, idleMs = SSE_IDLE_MS, parseJson = JSON.parse } = {}) {
|
|
34
|
+
if (!body || typeof body.getReader !== 'function') {
|
|
35
|
+
return { completed: false, events: 0, error: new Error('SSE body is not readable.') };
|
|
36
|
+
}
|
|
37
|
+
const reader = body.getReader();
|
|
38
|
+
const decoder = new TextDecoder('utf-8');
|
|
39
|
+
let buffer = '';
|
|
40
|
+
let eventName = 'message';
|
|
41
|
+
let dataLines = [];
|
|
42
|
+
let events = 0;
|
|
43
|
+
let idleTimer = null;
|
|
44
|
+
let idleTimedOut = false;
|
|
45
|
+
|
|
46
|
+
const armIdle = () => {
|
|
47
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
48
|
+
if (Number.isFinite(idleMs) && idleMs > 0) {
|
|
49
|
+
idleTimer = setTimeout(() => {
|
|
50
|
+
idleTimedOut = true;
|
|
51
|
+
reader.cancel().catch(() => {});
|
|
52
|
+
}, idleMs);
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
const onAbort = () => { reader.cancel().catch(() => {}); };
|
|
56
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
57
|
+
|
|
58
|
+
const dispatch = () => {
|
|
59
|
+
if (!dataLines.length) {
|
|
60
|
+
eventName = 'message';
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
const raw = dataLines.join('\n');
|
|
64
|
+
const name = eventName || 'message';
|
|
65
|
+
eventName = 'message';
|
|
66
|
+
dataLines = [];
|
|
67
|
+
let json = null;
|
|
68
|
+
try { json = parseJson(raw); } catch { json = null; }
|
|
69
|
+
events++;
|
|
70
|
+
return onEvent?.({ event: name, data: raw, json }) === true;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
try {
|
|
74
|
+
armIdle();
|
|
75
|
+
for (;;) {
|
|
76
|
+
if (signal?.aborted) break;
|
|
77
|
+
const { value, done } = await reader.read();
|
|
78
|
+
if (done) {
|
|
79
|
+
buffer += decoder.decode();
|
|
80
|
+
break;
|
|
81
|
+
}
|
|
82
|
+
armIdle();
|
|
83
|
+
buffer += decoder.decode(value, { stream: true });
|
|
84
|
+
let newlineIndex;
|
|
85
|
+
while ((newlineIndex = buffer.indexOf('\n')) !== -1) {
|
|
86
|
+
let line = buffer.slice(0, newlineIndex);
|
|
87
|
+
buffer = buffer.slice(newlineIndex + 1);
|
|
88
|
+
if (line.endsWith('\r')) line = line.slice(0, -1);
|
|
89
|
+
if (line === '') {
|
|
90
|
+
if (dispatch()) {
|
|
91
|
+
reader.cancel().catch(() => {});
|
|
92
|
+
return { completed: true, events, idleTimedOut: false };
|
|
93
|
+
}
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (line.startsWith(':')) continue; // Keepalive comment
|
|
97
|
+
const colon = line.indexOf(':');
|
|
98
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
99
|
+
let fieldValue = colon === -1 ? '' : line.slice(colon + 1);
|
|
100
|
+
if (fieldValue.startsWith(' ')) fieldValue = fieldValue.slice(1);
|
|
101
|
+
if (field === 'event') eventName = fieldValue || 'message';
|
|
102
|
+
else if (field === 'data') dataLines.push(fieldValue);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
if (buffer.length) {
|
|
106
|
+
const trailing = buffer.endsWith('\r') ? buffer.slice(0, -1) : buffer;
|
|
107
|
+
if (trailing && !trailing.startsWith(':')) {
|
|
108
|
+
const colon = trailing.indexOf(':');
|
|
109
|
+
const field = colon === -1 ? trailing : trailing.slice(0, colon);
|
|
110
|
+
let fieldValue = colon === -1 ? '' : trailing.slice(colon + 1);
|
|
111
|
+
if (fieldValue.startsWith(' ')) fieldValue = fieldValue.slice(1);
|
|
112
|
+
if (field === 'event') eventName = fieldValue || 'message';
|
|
113
|
+
else if (field === 'data') dataLines.push(fieldValue);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (dataLines.length) dispatch();
|
|
117
|
+
return { completed: !idleTimedOut && !signal?.aborted, events, idleTimedOut };
|
|
118
|
+
} catch (error) {
|
|
119
|
+
return { completed: false, events, idleTimedOut, error };
|
|
120
|
+
} finally {
|
|
121
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
122
|
+
signal?.removeEventListener('abort', onAbort);
|
|
123
|
+
try { reader.releaseLock(); } catch {}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Generated from prompts/cli/scenario-json.prompt.md (sha256:
|
|
1
|
+
// Generated from prompts/cli/scenario-json.prompt.md (sha256: 5b6173d4ec1a476063de34a456a6e29ccabeb5d3c2e3fd3500e0593d81fbab1e).
|
|
2
2
|
// Exact whole numbers in Runtime scenario files: read, write and compare without rounding.
|
|
3
3
|
|
|
4
4
|
const EXACT_INTEGER = /^-?(?:0|[1-9][0-9]*)$/;
|
|
@@ -89,3 +89,169 @@ export function withExactIntegers(value, leaves) {
|
|
|
89
89
|
}
|
|
90
90
|
return copy;
|
|
91
91
|
}
|
|
92
|
+
|
|
93
|
+
const derivationError = message => Object.assign(new SyntaxError(message), { code: 'scenario-derivation-invalid' });
|
|
94
|
+
const absInteger = value => value < 0n ? -value : value;
|
|
95
|
+
const DERIVATION_COMPONENT_LIMIT = 10n ** 10001n;
|
|
96
|
+
function gcdInteger(left, right) {
|
|
97
|
+
left = absInteger(left); right = absInteger(right);
|
|
98
|
+
while (right) [left, right] = [right, left % right];
|
|
99
|
+
return left;
|
|
100
|
+
}
|
|
101
|
+
function rational(numerator, denominator = 1n) {
|
|
102
|
+
if (!denominator) throw derivationError('Division by zero.');
|
|
103
|
+
if (denominator < 0n) { numerator = -numerator; denominator = -denominator; }
|
|
104
|
+
const divisor = gcdInteger(numerator, denominator);
|
|
105
|
+
const n = numerator / divisor, d = denominator / divisor;
|
|
106
|
+
if (absInteger(n) >= DERIVATION_COMPONENT_LIMIT || d >= DERIVATION_COMPONENT_LIMIT)
|
|
107
|
+
throw derivationError('Exact component exceeds 10,001 decimal digits.');
|
|
108
|
+
return { n, d };
|
|
109
|
+
}
|
|
110
|
+
function decimalRational(token) {
|
|
111
|
+
const match = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(token);
|
|
112
|
+
const exponent = BigInt(match[4] ?? '0');
|
|
113
|
+
if (absInteger(exponent) > 10000n) throw derivationError('Decimal exponent exceeds 10,000.');
|
|
114
|
+
const digits = (match[2] + (match[3] ?? '')) || '0';
|
|
115
|
+
const n = BigInt(digits) * (match[1] === '-' ? -1n : 1n);
|
|
116
|
+
const scale = BigInt((match[3] ?? '').length) - exponent;
|
|
117
|
+
return scale < 0n ? rational(n * 10n ** -scale) : rational(n, 10n ** scale);
|
|
118
|
+
}
|
|
119
|
+
const addRational = (a, b) => rational(a.n * b.d + b.n * a.d, a.d * b.d);
|
|
120
|
+
const subtractRational = (a, b) => rational(a.n * b.d - b.n * a.d, a.d * b.d);
|
|
121
|
+
const multiplyRational = (a, b) => rational(a.n * b.n, a.d * b.d);
|
|
122
|
+
const divideRational = (a, b) => rational(a.n * b.d, a.d * b.n);
|
|
123
|
+
function roundRational(value, mode) {
|
|
124
|
+
const q = value.n / value.d, r = value.n % value.d;
|
|
125
|
+
if (mode === 'trunc' || !r) return rational(q);
|
|
126
|
+
if (mode === 'floor') return rational(q - (r < 0n ? 1n : 0n));
|
|
127
|
+
if (mode === 'ceil') return rational(q + (r > 0n ? 1n : 0n));
|
|
128
|
+
const comparison = absInteger(r) * 2n - value.d;
|
|
129
|
+
const advance = comparison > 0n || comparison === 0n && (mode === 'round_half_up' || q % 2n !== 0n);
|
|
130
|
+
return rational(q + (advance ? (value.n < 0n ? -1n : 1n) : 0n));
|
|
131
|
+
}
|
|
132
|
+
function factorMultiplicity(value, factor) {
|
|
133
|
+
const powers = [];
|
|
134
|
+
for (let power = factor, count = 1; power <= value; power *= power, count *= 2)
|
|
135
|
+
powers.push({ power, count });
|
|
136
|
+
let count = 0;
|
|
137
|
+
for (let index = powers.length - 1; index >= 0; index--) {
|
|
138
|
+
const candidate = powers[index];
|
|
139
|
+
if (value % candidate.power === 0n) { value /= candidate.power; count += candidate.count; }
|
|
140
|
+
}
|
|
141
|
+
return { rest: value, count };
|
|
142
|
+
}
|
|
143
|
+
function canonicalDerivation(text) {
|
|
144
|
+
if (text.length > 20004) throw derivationError('Canonical result exceeds 20,004 characters.');
|
|
145
|
+
return text;
|
|
146
|
+
}
|
|
147
|
+
function formatRational(value) {
|
|
148
|
+
if (value.d === 1n) return String(value.n);
|
|
149
|
+
const two = factorMultiplicity(value.d, 2n), five = factorMultiplicity(two.rest, 5n);
|
|
150
|
+
if (five.rest !== 1n) return canonicalDerivation(`${value.n}/${value.d}`);
|
|
151
|
+
const twos = two.count, fives = five.count;
|
|
152
|
+
const scale = Math.max(twos, fives);
|
|
153
|
+
if (scale > 10000) throw derivationError('Terminating result exceeds 10,000 fractional decimal places.');
|
|
154
|
+
const digits = String(absInteger(value.n) * 2n ** BigInt(scale - twos) * 5n ** BigInt(scale - fives)).padStart(scale + 1, '0');
|
|
155
|
+
const decimal = `${digits.slice(0, -scale)}.${digits.slice(-scale)}`.replace(/0+$/, '');
|
|
156
|
+
return canonicalDerivation(`${value.n < 0n ? '-' : ''}${decimal}`);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// This parser only recognizes the exact-math grammar. Authored text never runs as JavaScript.
|
|
160
|
+
function derivationRational(expression) {
|
|
161
|
+
if (typeof expression !== 'string') throw derivationError('derivation must be a string.');
|
|
162
|
+
if (expression.length > 10000) throw derivationError('Expression exceeds 10,000 characters.');
|
|
163
|
+
let offset = 0, token = '', depth = 0;
|
|
164
|
+
const next = () => {
|
|
165
|
+
const whitespace = /^\s*/.exec(expression.slice(offset))[0]; offset += whitespace.length;
|
|
166
|
+
if (offset === expression.length) { token = ''; return; }
|
|
167
|
+
const match = /^(?:(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|[A-Za-z_][A-Za-z_0-9]*|[+*/(),-])/.exec(expression.slice(offset));
|
|
168
|
+
if (!match) throw derivationError(`Unexpected character at position ${offset + 1}.`);
|
|
169
|
+
token = match[0]; offset += token.length;
|
|
170
|
+
};
|
|
171
|
+
const nested = action => {
|
|
172
|
+
if (++depth > 128) throw derivationError('Expression nesting exceeds 128 levels.');
|
|
173
|
+
try { return action(); } finally { depth--; }
|
|
174
|
+
};
|
|
175
|
+
const requireToken = wanted => {
|
|
176
|
+
if (token !== wanted) throw derivationError(`Expected ${wanted} at position ${offset + 1}.`);
|
|
177
|
+
next();
|
|
178
|
+
};
|
|
179
|
+
const primary = () => {
|
|
180
|
+
if (token === '+' || token === '-') {
|
|
181
|
+
const sign = token; next();
|
|
182
|
+
const value = nested(primary);
|
|
183
|
+
return sign === '-' ? rational(-value.n, value.d) : value;
|
|
184
|
+
}
|
|
185
|
+
if (token === '(') {
|
|
186
|
+
next(); const value = nested(sum); requireToken(')'); return value;
|
|
187
|
+
}
|
|
188
|
+
if (/^[\d.]/.test(token)) { const value = decimalRational(token); next(); return value; }
|
|
189
|
+
const name = token;
|
|
190
|
+
if (!['min', 'max', 'floor', 'ceil', 'trunc', 'round_half_up', 'round_half_even'].includes(name))
|
|
191
|
+
throw derivationError(`Expected a number or an allowed function at position ${offset + 1}.`);
|
|
192
|
+
next(); requireToken('(');
|
|
193
|
+
const args = nested(() => {
|
|
194
|
+
const values = [];
|
|
195
|
+
if (token !== ')') {
|
|
196
|
+
values.push(sum());
|
|
197
|
+
while (token === ',') { next(); values.push(sum()); }
|
|
198
|
+
}
|
|
199
|
+
return values;
|
|
200
|
+
});
|
|
201
|
+
requireToken(')');
|
|
202
|
+
if (name === 'min' || name === 'max') {
|
|
203
|
+
if (!args.length) throw derivationError(`${name} needs at least one argument.`);
|
|
204
|
+
return args.reduce((selected, value) => {
|
|
205
|
+
const difference = value.n * selected.d - selected.n * value.d;
|
|
206
|
+
return (name === 'min' ? difference < 0n : difference > 0n) ? value : selected;
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
if (args.length !== 1) throw derivationError(`${name} needs one argument.`);
|
|
210
|
+
return roundRational(args[0], name);
|
|
211
|
+
};
|
|
212
|
+
const product = () => {
|
|
213
|
+
let left = primary();
|
|
214
|
+
while (['*', '/', 'div', 'mod'].includes(token)) {
|
|
215
|
+
const op = token; next(); const right = primary();
|
|
216
|
+
if (op === '*') left = multiplyRational(left, right);
|
|
217
|
+
else if (op === '/') left = divideRational(left, right);
|
|
218
|
+
else {
|
|
219
|
+
const quotient = divideRational(left, right), whole = rational(quotient.n / quotient.d);
|
|
220
|
+
left = op === 'div' ? whole : subtractRational(left, multiplyRational(whole, right));
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return left;
|
|
224
|
+
};
|
|
225
|
+
const sum = () => {
|
|
226
|
+
let left = product();
|
|
227
|
+
while (token === '+' || token === '-') {
|
|
228
|
+
const op = token; next(); const right = product();
|
|
229
|
+
left = op === '+' ? addRational(left, right) : subtractRational(left, right);
|
|
230
|
+
}
|
|
231
|
+
return left;
|
|
232
|
+
};
|
|
233
|
+
next(); const value = sum();
|
|
234
|
+
if (token !== '') throw derivationError(`Unexpected token ${token}.`);
|
|
235
|
+
return value;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export function evaluateDerivation(expression) {
|
|
239
|
+
return formatRational(derivationRational(expression));
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export function checkDerivation(check) {
|
|
243
|
+
if (!check || !Object.hasOwn(check, 'derivation')) return null;
|
|
244
|
+
try {
|
|
245
|
+
if (typeof check.value !== 'bigint' && (typeof check.value !== 'number' || !Number.isFinite(check.value)))
|
|
246
|
+
throw derivationError('A derivation needs a finite numeric scalar value.');
|
|
247
|
+
const computed = derivationRational(check.derivation);
|
|
248
|
+
const expected = typeof check.value === 'bigint' || Number.isInteger(check.value)
|
|
249
|
+
? rational(BigInt(check.value)) : decimalRational(String(check.value));
|
|
250
|
+
return computed.n === expected.n && computed.d === expected.d ? null : {
|
|
251
|
+
code: 'scenario-derivation-mismatch',
|
|
252
|
+
message: `Derivation evaluates to ${formatRational(computed)}; expected value is ${formatRational(expected)}.`,
|
|
253
|
+
};
|
|
254
|
+
} catch (error) {
|
|
255
|
+
return { code: 'scenario-derivation-invalid', message: error.message };
|
|
256
|
+
}
|
|
257
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Generated from prompts/cli/secret-redaction.prompt.md (sha256:
|
|
1
|
+
// Generated from prompts/cli/secret-redaction.prompt.md (sha256: ce9cfca0e024e8b39785b35a44e9e287012cbdcc399cec52fc77afe866bdacfe).
|
|
2
2
|
// Owned by prompts/cli/secret-redaction.prompt.md.
|
|
3
3
|
const SECRET = /token|password|secret|api[_-]?key|authorization|cookie|credential/i;
|
|
4
4
|
const remembered = new Set();
|
|
@@ -48,6 +48,7 @@ export function redactSecrets(value, secrets = []) {
|
|
|
48
48
|
value = redacted;
|
|
49
49
|
value=value.replace(/https?:\/\/[^\s"'<>]+/g,text=>{try{const url=new URL(text);let changed=false;if(url.username||url.password){url.username='';url.password='';changed=true;}for(const key of [...url.searchParams.keys()])if(SECRET.test(key)||/^(?:key|auth|signature)$/i.test(key)){url.searchParams.set(key,'[redacted]');changed=true;}return changed?url.href:text;}catch{return text.replace(/(https?:\/\/)[^\s/@]+(?::[^\s/@]*)?@/gi,'$1[redacted]@');}});
|
|
50
50
|
value = value.replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?(?:-----END [^-]*PRIVATE KEY-----|$)/g,'[redacted]');
|
|
51
|
-
value = value.replace(/\b(authorization)["']?\s*[:=]\s*[^\r\n]+/gi, '$1=[redacted]');
|
|
51
|
+
value = value.replace(/\b(authorization|cookie|set-cookie)["']?\s*[:=]\s*[^\r\n]+/gi, '$1=[redacted]');
|
|
52
|
+
value = value.replace(/\bAKIA[A-Z0-9]{16}\b/g,'[redacted]').replace(/\beyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,'[redacted]');
|
|
52
53
|
return value.replace(/\b(?:gh[pousr]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]{12,}|AIza[A-Za-z0-9_-]+|ya29\.[A-Za-z0-9_.-]+)\b/g,'[redacted]').replace(/\b(?:Bearer|Basic)\s+\S+/gi,'[redacted]').replace(/\b(key|token|password|secret|api[_-]?key|authorization|cookie|credential)["']?\s*[:=]\s*(?:"(?:\\.|[^"\\])*(?:"|$)|'(?:\\.|[^'\\])*(?:'|$)|[^\s,;]+)/gi,'$1=[redacted]').replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,'');
|
|
53
54
|
}
|