@promptdriven/runtime-client 1.1.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/index.mjs +9 -0
- package/src/runtime/run-program.mjs +3 -2
- package/src/runtime/runtime-bindings.mjs +7 -7
- package/src/runtime/runtime-check-plan.mjs +19 -27
- package/src/runtime/runtime-check-reconcile.mjs +328 -0
- package/src/runtime/runtime-client.mjs +804 -143
- package/src/runtime/runtime-outcome.mjs +3 -0
- package/src/runtime/runtime-output.mjs +156 -7
- package/src/runtime/runtime-preflight.mjs +205 -12
- package/src/runtime/runtime-stream.mjs +125 -0
- package/src/runtime/try-doors.mjs +1 -0
- package/src/runtime/try-http.mjs +11 -3
|
@@ -10,6 +10,7 @@ import { compileLocalManifest, validateLocalManifest } from './live-local.mjs';
|
|
|
10
10
|
import { rememberSecrets as fallbackRememberSecrets } from './secret-redaction.mjs';
|
|
11
11
|
import { bindingPlanLines, bindingRefusals } from './runtime-binding-plan.mjs';
|
|
12
12
|
import { buildCheckPlan, checkPlanResults, checkPlanLines, checkPlanResultLines, selectCheckTests, baselineReport, evaluateCheckBudget } from './runtime-check-plan.mjs';
|
|
13
|
+
import { projectCheckReconciliation } from './runtime-check-reconcile.mjs';
|
|
13
14
|
import {loadRuntimeWorkspace,allowsRuntimePath,requireRuntimePath,RuntimeWorkspaceError} from './runtime-workspace.mjs';
|
|
14
15
|
import { failedCheckCount, hasProgress, outcomeDone, outcomeFor, outcomeOverall, outcomeText, progressText, resultOutcome, resultOverall } from './runtime-outcome.mjs';
|
|
15
16
|
import { acquireRuntimeSlot, recordRuntimeRequest, releaseRuntimeSlot, listRuntimeJobs } from './runtime-slots.mjs';
|
|
@@ -27,6 +28,7 @@ import { catalogRecords, compareCopies } from './contract-refs.mjs';
|
|
|
27
28
|
import { jsonSafe, parseScenarioJson } from './scenario-json.mjs';
|
|
28
29
|
import { scenarioDerivationRefusal } from './runtime-preflight.mjs';
|
|
29
30
|
import { OPEN_STATES, causeText, cleanText, progressTicker, projectAnswer, refusalView, renderJson, renderText, summaryLine, stepTimeLimit, tokenUsageOf, tryUsage, validLink, coverageText } from './runtime-output.mjs';
|
|
31
|
+
import { adaptivePollMs, isSseContentType, parseSseStream, preferWaitHeaders, SSE_IDLE_MS, WAIT_PREFER_CALL_SECONDS, WAIT_PREFER_RUN_SECONDS } from './runtime-stream.mjs';
|
|
30
32
|
|
|
31
33
|
const localInterfaceProblem = problem => ['interface-missing','interface-kind-invalid','native-reason-missing','interface-draft-incomplete','duplicate-selector-word'].includes(problem.code);
|
|
32
34
|
const unboundPortError = message => Object.assign(new Error(message), { unboundPort: true });
|
|
@@ -229,7 +231,7 @@ function withDefaults(ports) {
|
|
|
229
231
|
return executable ? spawnSync(executable, args, { encoding: 'utf8', env, stdio: ['ignore', 'pipe', 'pipe'], timeout: 60_000 })
|
|
230
232
|
: { status: null, error: { code: 'ENOENT' } };
|
|
231
233
|
}),
|
|
232
|
-
now: ports.now ?? Date.now, randomUUID: ports.randomUUID ?? randomUUID, pollMs: ports.pollMs ?? 2000, postMs: ports.postMs ?? POST_MS,
|
|
234
|
+
now: ports.now ?? Date.now, randomUUID: ports.randomUUID ?? randomUUID, pollMs: ports.pollMs ?? 2000, pollMsExplicit: ports.pollMs !== undefined, pollDelay: elapsedMs => adaptivePollMs(elapsedMs, ports.pollMs), postMs: ports.postMs ?? POST_MS,
|
|
233
235
|
interactive: ports.interactive ?? (!!process.stdout.isTTY && !!process.stdin.isTTY), watchMs: ports.watchMs ?? 5000, stdin: ports.stdin ?? process.stdin,
|
|
234
236
|
sleep: ports.sleep ?? ((ms, signal) => new Promise(done => {
|
|
235
237
|
if (signal?.aborted) { done(); return; }
|
|
@@ -555,6 +557,37 @@ async function readBaselineReport(context, plan, identity) {
|
|
|
555
557
|
return project(partial ? 'partial' : 'available');
|
|
556
558
|
}
|
|
557
559
|
|
|
560
|
+
const snapshotReferenceMap = references => new Map(references.map(ref => [`${ref.kind}:${ref.target}`, ref.value_json]));
|
|
561
|
+
|
|
562
|
+
function validStorySnapshot(snapshot, story, tests) {
|
|
563
|
+
return isObject(snapshot) && snapshot.story_path === story
|
|
564
|
+
&& !(Array.isArray(snapshot.unavailable) && snapshot.unavailable.length > 0)
|
|
565
|
+
&& Array.isArray(snapshot.tests) && tests.every(test => snapshot.tests.includes(test))
|
|
566
|
+
&& Array.isArray(snapshot.files) && snapshot.files.length > 0
|
|
567
|
+
&& snapshot.files.every(file => isObject(file) && typeof file.path === 'string' && /^[a-f0-9]{64}$/.test(file.sha256 ?? ''))
|
|
568
|
+
&& Array.isArray(snapshot.references)
|
|
569
|
+
&& snapshot.references.every(ref => isObject(ref) && typeof ref.kind === 'string' && typeof ref.target === 'string');
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function sameStoryFootprint(saved, live) {
|
|
573
|
+
if (!isObject(saved) || !isObject(live) || saved.unavailable?.length || live.unavailable?.length) return false;
|
|
574
|
+
if (!Array.isArray(saved.files) || !Array.isArray(live.files) || !Array.isArray(saved.references) || !Array.isArray(live.references)) return false;
|
|
575
|
+
if (!isDeepStrictEqual(saved.files, live.files)) return false;
|
|
576
|
+
const before = snapshotReferenceMap(saved.references), now = snapshotReferenceMap(live.references);
|
|
577
|
+
if (before.size !== now.size) return false;
|
|
578
|
+
for (const [key, value] of before) if (!now.has(key) || now.get(key) !== value) return false;
|
|
579
|
+
return true;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
function unsavedPostOutcome(row) {
|
|
583
|
+
return ['not_run', 'busy', 'stop', 'refused'].includes(row.post_verdict)
|
|
584
|
+
|| row.recovery_state === 'not_run'
|
|
585
|
+
|| row.state === 'not_run'
|
|
586
|
+
|| row.state === 'not run'
|
|
587
|
+
|| (!row.post_verdict && row.busy === true && (row.recovery_state === 'waiting' || row.state === 'waiting'))
|
|
588
|
+
|| (!row.post_verdict && row.recovery_state === 'refused' && Array.isArray(row.refusals) && row.refusals.length > 0);
|
|
589
|
+
}
|
|
590
|
+
|
|
558
591
|
// Read receipts without StateStore.folder: status must never allocate or mutate runtime state.
|
|
559
592
|
export async function savedStoryEvidence(input, ports = {}) {
|
|
560
593
|
return createSavedStoryEvidenceReader(ports)(input);
|
|
@@ -602,33 +635,75 @@ async function readSavedStoryEvidence({ root, comparisonRoot = root, withTests =
|
|
|
602
635
|
// Older batches saved the display basename; only a unique captured path can recover its identity.
|
|
603
636
|
const rows = batch.rows.map(row => {
|
|
604
637
|
if (row.story.endsWith('.md')) return row;
|
|
638
|
+
if (relativeFile(row.story_path) && row.story_path.endsWith('.md') && basename(row.story_path, '.md') === row.story) {
|
|
639
|
+
return { ...row, story: row.story_path };
|
|
640
|
+
}
|
|
605
641
|
const candidates = [...new Set((Array.isArray(batch.files) ? batch.files : []).filter(file => relativeFile(file)
|
|
606
642
|
&& file.endsWith('.md') && basename(file, '.md') === row.story))];
|
|
607
643
|
return candidates.length === 1 ? { ...row, story: candidates[0] } : null;
|
|
608
644
|
});
|
|
609
645
|
if (rows.some(row => row === null)) { warning(path, Error('missing or ambiguous Story identity')); continue; }
|
|
610
|
-
|
|
646
|
+
const selected = new Map(), sent = new Map(), grouped = new Map(), extra = new Map();
|
|
647
|
+
for (const row of rows) {
|
|
648
|
+
if (!selected.has(row.story)) selected.set(row.story, new Set());
|
|
649
|
+
selected.get(row.story).add(row.test);
|
|
650
|
+
}
|
|
651
|
+
const storyCurrent = new Map();
|
|
611
652
|
if (comparisonRoot !== null && /^[a-f0-9]{64}$/.test(batch.source_sha256 ?? '')) {
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
653
|
+
const compareFolder = await real(comparisonRoot);
|
|
654
|
+
const excludeFixtureProjects = batch.exclude_fixture_projects === true;
|
|
655
|
+
const allowMissingInterfaces = batch.lazy_interfaces === true;
|
|
656
|
+
const captureMemo = tests => {
|
|
657
|
+
const key = JSON.stringify([compareFolder, tests, excludeFixtureProjects, ...(allowMissingInterfaces ? [true] : [])]);
|
|
658
|
+
if (!captures.has(key)) captures.set(key, Promise.resolve()
|
|
659
|
+
.then(() => capture(compareFolder, { tests, appMap: null, ...(excludeFixtureProjects ? { excludeFixtureProjects: true } : {}), ...(allowMissingInterfaces ? { allowMissingInterfaces: true } : {}) }))
|
|
660
|
+
.then(source => ({ sha256: source?.sha256, stories: Array.isArray(source?.stories) ? source.stories : null }))
|
|
661
|
+
.catch(error => ({ error })));
|
|
662
|
+
return captures.get(key);
|
|
663
|
+
};
|
|
664
|
+
let batchCurrentPromise = null;
|
|
665
|
+
const getBatchCurrent = () => {
|
|
666
|
+
if (!batchCurrentPromise) batchCurrentPromise = (async () => {
|
|
667
|
+
try {
|
|
668
|
+
const tests = [...new Set(rows.map(row => row.test))].sort();
|
|
669
|
+
const source = await captureMemo(tests);
|
|
670
|
+
if (source.error) throw source.error;
|
|
671
|
+
return source.sha256 === batch.source_sha256;
|
|
672
|
+
} catch (error) {
|
|
673
|
+
if (error?.unboundPort) throw error;
|
|
674
|
+
warning(path, error);
|
|
675
|
+
return false;
|
|
676
|
+
}
|
|
677
|
+
})();
|
|
678
|
+
return batchCurrentPromise;
|
|
679
|
+
};
|
|
680
|
+
const snapshots = Array.isArray(batch.contract_snapshots) ? batch.contract_snapshots : [];
|
|
681
|
+
for (const [story, testSet] of selected) {
|
|
682
|
+
const storyTests = [...testSet].sort();
|
|
683
|
+
const snapshot = snapshots.find(item => validStorySnapshot(item, story, storyTests));
|
|
684
|
+
if (snapshot) {
|
|
685
|
+
try {
|
|
686
|
+
const source = await captureMemo(storyTests);
|
|
687
|
+
if (source.error) throw source.error;
|
|
688
|
+
if (Array.isArray(source.stories)) {
|
|
689
|
+
const live = source.stories.find(item => item?.story_path === story);
|
|
690
|
+
storyCurrent.set(story, sameStoryFootprint(snapshot, live));
|
|
691
|
+
continue;
|
|
692
|
+
}
|
|
693
|
+
} catch (error) {
|
|
694
|
+
if (error?.unboundPort) throw error;
|
|
695
|
+
warning(path, error);
|
|
696
|
+
storyCurrent.set(story, false);
|
|
697
|
+
continue;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
storyCurrent.set(story, await getBatchCurrent());
|
|
701
|
+
}
|
|
622
702
|
}
|
|
623
|
-
const selected = new Map(), sent = new Map(), grouped = new Map(), extra = new Map();
|
|
624
703
|
// withTests: the failed checks, refusals and states of each Story's rows, and the rows that were never sent.
|
|
625
704
|
const note = (story, add) => { const was = extra.get(story) ?? { failed: 0, failedSteps: [], refusals: [], states: [], codes: [], fixes: [], sent: false }; extra.set(story, add(was)); };
|
|
626
705
|
const codesOf = list => Array.isArray(list) ? list.map(item => item?.code).filter(code => typeof code === 'string') : [];
|
|
627
706
|
const fixesOf = list => Array.isArray(list) ? list.map(item => item?.fix).filter(fix => typeof fix === 'string' && fix.trim()) : [];
|
|
628
|
-
for (const row of rows) {
|
|
629
|
-
if (!selected.has(row.story)) selected.set(row.story, new Set());
|
|
630
|
-
selected.get(row.story).add(row.test);
|
|
631
|
-
}
|
|
632
707
|
for (const row of rows) {
|
|
633
708
|
note(row.story, was => ({ ...was, refusals: [...new Set([...was.refusals, ...codesOf(row.refusals)])], fixes: [...new Set([...was.fixes, ...fixesOf(row.refusals)])],
|
|
634
709
|
states: [...new Set([...was.states, ...(typeof row.recovery_state === 'string' ? [row.recovery_state] : [])])],
|
|
@@ -663,10 +738,13 @@ async function readSavedStoryEvidence({ root, comparisonRoot = root, withTests =
|
|
|
663
738
|
&& Array.isArray(criteria) && new Set(criteria.map(item => item?.criterion_id)).size === row.criteria_total
|
|
664
739
|
&& criteria.every(item => authored.includes(item?.criterion_id) && item.status === 'passed');
|
|
665
740
|
}
|
|
666
|
-
} catch (error) {
|
|
741
|
+
} catch (error) {
|
|
742
|
+
if (!(error?.code === 'ENOENT' && unsavedPostOutcome(row))) warning(receiptPath, error);
|
|
743
|
+
}
|
|
667
744
|
}
|
|
668
745
|
const at = Number.isFinite(row.ended_at) ? row.ended_at : Date.parse(batch.created_at) || 0;
|
|
669
746
|
const previous = grouped.get(row.story);
|
|
747
|
+
const current = storyCurrent.get(row.story) ?? false;
|
|
670
748
|
grouped.set(row.story, { story: row.story, pass: pass && (previous?.pass ?? true), current, result: 'no verdict', at: Math.max(previous?.at ?? at, at) });
|
|
671
749
|
}
|
|
672
750
|
// withTests: pdd's own fix texts of a Story's refusals (its saved warnings, then each refusal's fix).
|
|
@@ -684,7 +762,7 @@ async function readSavedStoryEvidence({ root, comparisonRoot = root, withTests =
|
|
|
684
762
|
// withTests: a Story whose tests were never sent (refused before execution, interrupted) is listed too.
|
|
685
763
|
if (withTests) for (const story of extra.keys()) if (!grouped.has(story)) {
|
|
686
764
|
const at = Math.max(0, ...rows.filter(row => row.story === story).map(row => Number.isFinite(row.ended_at) ? row.ended_at : Date.parse(batch.created_at) || 0));
|
|
687
|
-
stories.push({ story, pass: false, current, result: 'not sent', at, tests: [...selected.get(story)].sort(), ...advised(story), sent: false });
|
|
765
|
+
stories.push({ story, pass: false, current: storyCurrent.get(story) ?? false, result: 'not sent', at, tests: [...selected.get(story)].sort(), ...advised(story), sent: false });
|
|
688
766
|
}
|
|
689
767
|
}
|
|
690
768
|
return { stories, warnings: [...new Set(warnings)] };
|
|
@@ -941,6 +1019,60 @@ class StateStore {
|
|
|
941
1019
|
unlinkSync(join(this.dir, 'github-user.json'));
|
|
942
1020
|
} catch { /* ignore absent or unremovable cache file */ }
|
|
943
1021
|
}
|
|
1022
|
+
originKey(origin) { return createHash('sha256').update(String(origin)).digest('hex').slice(0, 16); }
|
|
1023
|
+
readOriginCapabilities(origin, now = Date.now()) {
|
|
1024
|
+
try {
|
|
1025
|
+
if (typeof origin !== 'string' || !origin || statOrNull(this.dir)?.isSymbolicLink()) return null;
|
|
1026
|
+
const dir = join(this.dir, 'origin-capabilities');
|
|
1027
|
+
if (statOrNull(dir)?.isSymbolicLink()) return null;
|
|
1028
|
+
const path = join(dir, `${this.originKey(origin)}.json`), stat = statOrNull(path);
|
|
1029
|
+
if (!stat?.isFile() || stat.isSymbolicLink()) return null;
|
|
1030
|
+
const record = JSON.parse(readFileSync(path, 'utf8'));
|
|
1031
|
+
if (!isObject(record) || record.origin !== origin || record.lazy_interfaces !== true) return null;
|
|
1032
|
+
if (!Array.isArray(record.features) || !record.features.every(item => typeof item === 'string') || !record.features.includes('lazy-interfaces')) return null;
|
|
1033
|
+
const observedAt = Date.parse(record.observed_at);
|
|
1034
|
+
if (!Number.isFinite(observedAt) || now - observedAt > CAPABILITY_CACHE_TTL_MS) return null;
|
|
1035
|
+
return { origin, lazy_interfaces: true, features: record.features, engine_sha: typeof record.engine_sha === 'string' ? record.engine_sha : null, observed_at: record.observed_at };
|
|
1036
|
+
} catch { return null; }
|
|
1037
|
+
}
|
|
1038
|
+
writeOriginCapabilities(origin, { features, engine_sha = null } = {}, now = Date.now()) {
|
|
1039
|
+
if (typeof origin !== 'string' || !origin) return false;
|
|
1040
|
+
if (!Array.isArray(features) || !features.every(item => typeof item === 'string') || !features.includes('lazy-interfaces')) {
|
|
1041
|
+
this.deleteOriginCapabilities(origin);
|
|
1042
|
+
return false;
|
|
1043
|
+
}
|
|
1044
|
+
let folder;
|
|
1045
|
+
try {
|
|
1046
|
+
if (statOrNull(this.dir)?.isSymbolicLink()) return false;
|
|
1047
|
+
const dir = join(this.dir, 'origin-capabilities');
|
|
1048
|
+
if (statOrNull(dir)?.isSymbolicLink()) return false;
|
|
1049
|
+
folder = this.folder('origin-capabilities');
|
|
1050
|
+
} catch { return false; }
|
|
1051
|
+
const path = join(folder, `${this.originKey(origin)}.json`);
|
|
1052
|
+
if (statOrNull(path)?.isSymbolicLink()) return false;
|
|
1053
|
+
const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
1054
|
+
let text = `${JSON.stringify({ origin, lazy_interfaces: true, features, engine_sha: typeof engine_sha === 'string' ? engine_sha : null, observed_at: new Date(now).toISOString() }, null, 2)}\n`;
|
|
1055
|
+
for (const secret of this.secrets) if (secret) text = text.split(secret).join('[secret]');
|
|
1056
|
+
try {
|
|
1057
|
+
const fd = openSync(temporary, 'wx', 0o600);
|
|
1058
|
+
try { chmodSync(temporary, 0o600); writeSync(fd, text); } finally { closeSync(fd); }
|
|
1059
|
+
renameSync(temporary, path);
|
|
1060
|
+
return true;
|
|
1061
|
+
} catch {
|
|
1062
|
+
try { unlinkSync(temporary); } catch { /* ignore temp cleanup failure */ }
|
|
1063
|
+
return false;
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
deleteOriginCapabilities(origin) {
|
|
1067
|
+
try {
|
|
1068
|
+
if (typeof origin !== 'string' || !origin || statOrNull(this.dir)?.isSymbolicLink()) return;
|
|
1069
|
+
const dir = join(this.dir, 'origin-capabilities');
|
|
1070
|
+
if (statOrNull(dir)?.isSymbolicLink()) return;
|
|
1071
|
+
const path = join(dir, `${this.originKey(origin)}.json`);
|
|
1072
|
+
if (statOrNull(path)?.isSymbolicLink()) return;
|
|
1073
|
+
unlinkSync(path);
|
|
1074
|
+
} catch { /* ignore absent or unremovable cache file */ }
|
|
1075
|
+
}
|
|
944
1076
|
// Exclusive create: a second POST with the same request ID is impossible.
|
|
945
1077
|
posted(folder, id) {
|
|
946
1078
|
const fd = openSync(join(folder, `${id}.posted`), 'wx', 0o600);
|
|
@@ -1209,9 +1341,10 @@ class Runtime {
|
|
|
1209
1341
|
} catch (error) { return lostReply(error, this.origin); } finally { clearTimeout(timer); this.signal?.removeEventListener('abort', stop); readSignal?.removeEventListener('abort', stop); }
|
|
1210
1342
|
}
|
|
1211
1343
|
async send(path, init, ms) {
|
|
1344
|
+
const pathname = path.split('?')[0];
|
|
1212
1345
|
const previousToken = this.auth?.identity.token ?? this.token;
|
|
1213
1346
|
const first = await this.sendOnce(path, init, ms);
|
|
1214
|
-
if (this.auth &&
|
|
1347
|
+
if (this.auth && pathname !== '/v1/capacity' && [200, 202].includes(first.status)) this.auth.verifiedByServer = true;
|
|
1215
1348
|
if (first.status !== 401 || !this.auth) return first;
|
|
1216
1349
|
this.auth.store?.deleteGithubUser();
|
|
1217
1350
|
if (!this.auth.identity.fromCache || this.auth.identity.refreshedAfter401) return first;
|
|
@@ -1227,11 +1360,11 @@ class Runtime {
|
|
|
1227
1360
|
} catch (error) {
|
|
1228
1361
|
if (error instanceof Stop) { this.auth.store?.deleteGithubUser(); return first; }
|
|
1229
1362
|
// The initial 401 refused execution, and refresh failed before a retry.
|
|
1230
|
-
if (init?.method === 'POST' && (
|
|
1363
|
+
if (init?.method === 'POST' && (pathname === '/v1/try' || /^\/v1\/try\/[^/]+\/call$/.test(pathname) || /\/screen\/api\/(act|app\/open)$/.test(pathname))) {
|
|
1231
1364
|
if (error === null || !['object', 'function'].includes(typeof error)) error = new Error(String(error));
|
|
1232
|
-
if (
|
|
1233
|
-
if (/\/screen\/api\/(act|app\/open)$/.test(
|
|
1234
|
-
if (/^\/v1\/try\/[^/]+\/call$/.test(
|
|
1365
|
+
if (pathname === '/v1/try') unadmittedTryErrors.add(error);
|
|
1366
|
+
if (/\/screen\/api\/(act|app\/open)$/.test(pathname)) unadmittedScreenErrors.add(error);
|
|
1367
|
+
if (/^\/v1\/try\/[^/]+\/call$/.test(pathname)) unadmittedCallErrors.set(this, error);
|
|
1235
1368
|
}
|
|
1236
1369
|
throw error;
|
|
1237
1370
|
}
|
|
@@ -1242,8 +1375,8 @@ class Runtime {
|
|
|
1242
1375
|
const expectedOwner = typeof this.auth.expectedOwnerLogin === 'function' ? this.auth.expectedOwnerLogin() : this.auth.expectedOwnerLogin;
|
|
1243
1376
|
if (expectedOwner && refreshed.login !== expectedOwner) {
|
|
1244
1377
|
const error = this.auth.ownerMismatchError(expectedOwner);
|
|
1245
|
-
if (
|
|
1246
|
-
if (init?.method === 'POST' && /\/screen\/api\/(act|app\/open)$/.test(
|
|
1378
|
+
if (pathname === '/v1/try' && init?.method === 'POST') unadmittedTryErrors.add(error);
|
|
1379
|
+
if (init?.method === 'POST' && /\/screen\/api\/(act|app\/open)$/.test(pathname)) unadmittedScreenErrors.add(error);
|
|
1247
1380
|
throw error;
|
|
1248
1381
|
}
|
|
1249
1382
|
if (this.auth.verifiedByServer && refreshed.token === previousToken) {
|
|
@@ -1252,7 +1385,69 @@ class Runtime {
|
|
|
1252
1385
|
}
|
|
1253
1386
|
const retry = await this.sendOnce(path, init, ms);
|
|
1254
1387
|
if (retry.status === 401) this.auth.store?.deleteGithubUser();
|
|
1255
|
-
else if (
|
|
1388
|
+
else if (pathname !== '/v1/capacity' && [200, 202].includes(retry.status)) this.auth.verifiedByServer = true;
|
|
1389
|
+
return retry;
|
|
1390
|
+
}
|
|
1391
|
+
async streamOnce(path, init, { timeoutMs = GET_MS, idleMs = SSE_IDLE_MS, onEvent, signal } = {}) {
|
|
1392
|
+
const readSignal = signal ?? (init?.method === 'GET' ? init.signal : null);
|
|
1393
|
+
if (this.signal?.aborted || readSignal?.aborted) return { streamed: false, lost: true };
|
|
1394
|
+
const controller = new AbortController(), stop = () => controller.abort();
|
|
1395
|
+
const headerTimer = setTimeout(stop, Math.min(GET_MS, Number.isFinite(timeoutMs) ? Math.max(1, timeoutMs) : GET_MS));
|
|
1396
|
+
const overallTimer = Number.isFinite(timeoutMs) && timeoutMs > 0 ? setTimeout(stop, timeoutMs) : null;
|
|
1397
|
+
this.signal?.addEventListener('abort', stop, { once: true });
|
|
1398
|
+
readSignal?.addEventListener('abort', stop, { once: true });
|
|
1399
|
+
const bearer = this.auth?.identity.token ?? this.token;
|
|
1400
|
+
const resolved = typeof init?.body === 'function' ? { ...init, body: init.body() } : init;
|
|
1401
|
+
try {
|
|
1402
|
+
const response = await this.ports.fetch(new URL(path, this.origin), { ...resolved, redirect: 'manual', signal: controller.signal,
|
|
1403
|
+
headers: { Accept: 'text/event-stream, application/json', ...resolved?.headers, Authorization: `Bearer ${bearer}` } });
|
|
1404
|
+
clearTimeout(headerTimer);
|
|
1405
|
+
if (response.status === 200 && isSseContentType(response.headers) && typeof response.body?.getReader === 'function') {
|
|
1406
|
+
const parseJson = this.programJson ? parseProgramJson : JSON.parse;
|
|
1407
|
+
const result = await parseSseStream(response.body, { onEvent, signal: controller.signal, idleMs, parseJson });
|
|
1408
|
+
return { streamed: true, status: response.status, headers: response.headers, ...result };
|
|
1409
|
+
}
|
|
1410
|
+
const text = await response.text();
|
|
1411
|
+
let json = null;
|
|
1412
|
+
try { json = this.programJson ? parseProgramJson(text) : JSON.parse(text); } catch { json = null; }
|
|
1413
|
+
return { streamed: false, status: response.status, headers: response.headers, text, json };
|
|
1414
|
+
} catch (error) { return { streamed: false, ...lostReply(error, this.origin) }; }
|
|
1415
|
+
finally { clearTimeout(headerTimer); if (overallTimer) clearTimeout(overallTimer); this.signal?.removeEventListener('abort', stop); readSignal?.removeEventListener('abort', stop); }
|
|
1416
|
+
}
|
|
1417
|
+
async stream(path, init = {}, options = {}) {
|
|
1418
|
+
const pathname = path.split('?')[0];
|
|
1419
|
+
const previousToken = this.auth?.identity.token ?? this.token;
|
|
1420
|
+
const first = await this.streamOnce(path, init, options);
|
|
1421
|
+
if (this.auth && pathname !== '/v1/capacity' && [200, 202].includes(first.status)) this.auth.verifiedByServer = true;
|
|
1422
|
+
if (first.streamed || first.status !== 401 || !this.auth) return first;
|
|
1423
|
+
this.auth.store?.deleteGithubUser();
|
|
1424
|
+
if (!this.auth.identity.fromCache || this.auth.identity.refreshedAfter401) return first;
|
|
1425
|
+
this.auth.identity.fromCache = false;
|
|
1426
|
+
this.auth.identity.refreshedAfter401 = true;
|
|
1427
|
+
let refreshed;
|
|
1428
|
+
try {
|
|
1429
|
+
refreshed = signIn(this.ports.gh, this.auth.store, this.ports, {
|
|
1430
|
+
forceRefresh: true,
|
|
1431
|
+
afterHttp401: true,
|
|
1432
|
+
exitCode: this.auth.signInExitCode,
|
|
1433
|
+
});
|
|
1434
|
+
} catch (error) {
|
|
1435
|
+
if (error instanceof Stop) { this.auth.store?.deleteGithubUser(); return first; }
|
|
1436
|
+
throw error;
|
|
1437
|
+
}
|
|
1438
|
+
Object.assign(this.auth.identity, refreshed, { fromCache: false, refreshedAfter401: true });
|
|
1439
|
+
this.token = refreshed.token;
|
|
1440
|
+
if (Array.isArray(this.auth.secrets) && !this.auth.secrets.includes(refreshed.token)) this.auth.secrets.push(refreshed.token);
|
|
1441
|
+
await this.auth.onRefresh?.(this.auth.identity);
|
|
1442
|
+
const expectedOwner = typeof this.auth.expectedOwnerLogin === 'function' ? this.auth.expectedOwnerLogin() : this.auth.expectedOwnerLogin;
|
|
1443
|
+
if (expectedOwner && refreshed.login !== expectedOwner) throw this.auth.ownerMismatchError(expectedOwner);
|
|
1444
|
+
if (this.auth.verifiedByServer && refreshed.token === previousToken) {
|
|
1445
|
+
this.auth.store?.deleteGithubUser();
|
|
1446
|
+
return first;
|
|
1447
|
+
}
|
|
1448
|
+
const retry = await this.streamOnce(path, init, options);
|
|
1449
|
+
if (retry.status === 401) this.auth.store?.deleteGithubUser();
|
|
1450
|
+
else if (pathname !== '/v1/capacity' && [200, 202].includes(retry.status)) this.auth.verifiedByServer = true;
|
|
1256
1451
|
return retry;
|
|
1257
1452
|
}
|
|
1258
1453
|
post(path, request, tar, timeoutMs = this.ports.postMs) {
|
|
@@ -1266,7 +1461,15 @@ class Runtime {
|
|
|
1266
1461
|
};
|
|
1267
1462
|
return this.send(path, { method: 'POST', body: makeForm }, timeoutMs);
|
|
1268
1463
|
}
|
|
1269
|
-
get(id, timeoutMs = GET_MS
|
|
1464
|
+
get(id, timeoutMs = GET_MS, { waitSeconds = 0 } = {}) {
|
|
1465
|
+
const headers = waitSeconds > 0 ? preferWaitHeaders(waitSeconds) : undefined;
|
|
1466
|
+
const ms = waitSeconds > 0 ? Math.max(timeoutMs, waitSeconds * 1000 + 10_000) : timeoutMs;
|
|
1467
|
+
return this.send(`/v1/runs/${id}`, { method: 'GET', ...(headers ? { headers } : {}) }, ms);
|
|
1468
|
+
}
|
|
1469
|
+
streamRun(id, options = {}) {
|
|
1470
|
+
const path = options.useEventsPath ? `/v1/runs/${id}/events` : `/v1/runs/${id}`;
|
|
1471
|
+
return this.stream(path, { method: 'GET' }, options);
|
|
1472
|
+
}
|
|
1270
1473
|
reopen(id) { return this.send(`/v1/try/${id}/reopen`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' }, this.ports.postMs); }
|
|
1271
1474
|
stop(tryId, requestId) { return this.send(`/v1/try/${tryId}`, { method: 'DELETE', headers: { 'X-Request-Id': requestId } }, this.ports.postMs); }
|
|
1272
1475
|
}
|
|
@@ -1335,12 +1538,22 @@ export async function checkRuntimeHealth({ env = process.env } = {}, givenPorts
|
|
|
1335
1538
|
// Only capacity refusals that prove no execution can authorize a fresh check ID.
|
|
1336
1539
|
function capacityDelay(refusal, headers) {
|
|
1337
1540
|
const code = refusal?.code ?? '';
|
|
1338
|
-
const capacity = /(?:^|-)(?:queue|capacity|busy)(?:-|$)|^server-full$/.test(code);
|
|
1339
|
-
if (!capacity
|
|
1541
|
+
const capacity = /(?:^|-)(?:queue|capacity|busy)(?:-|$)|^(?:server-full|rate-limited)$/.test(code);
|
|
1542
|
+
if (!capacity) return null;
|
|
1543
|
+
const retryable = code === 'check-queue-timeout' || code === 'server-full' || refusal?.details?.retryable === true
|
|
1544
|
+
|| (code === 'rate-limited' && refusal?.details?.retryable !== false && (Boolean(headers?.get?.('retry-after')) || typeof refusal?.details?.retry_after === 'number'));
|
|
1545
|
+
if (!retryable) return null;
|
|
1340
1546
|
if (headers?.get?.('retry-after')) return retryAfter(headers);
|
|
1341
|
-
const seconds = refusal
|
|
1547
|
+
const seconds = refusal?.details?.retry_after;
|
|
1342
1548
|
return (typeof seconds === 'number' && Number.isFinite(seconds) && seconds > 0 ? Math.min(300, Math.max(1, seconds)) : 5) * 1000;
|
|
1343
1549
|
}
|
|
1550
|
+
function preAdmissionRateLimited(record) {
|
|
1551
|
+
if (!isObject(record) || record.error?.code !== 'rate-limited') return false;
|
|
1552
|
+
if (record.dispatch !== 'not_started' || record.job_created !== false || record.state !== 'refused') return false;
|
|
1553
|
+
if (record.error?.details?.retryable === false) return false;
|
|
1554
|
+
return ['usage', 'report', 'result', 'provider_calls', 'accounting_complete', 'calls', 'known_calls', 'unknown_calls', 'checks']
|
|
1555
|
+
.every(key => !Object.hasOwn(record, key));
|
|
1556
|
+
}
|
|
1344
1557
|
function safeAdmission(reply) {
|
|
1345
1558
|
const json = reply.json, report = json?.result?.report;
|
|
1346
1559
|
return !(json?.usage && Object.hasOwn(json.usage, 'calls') && json.usage.calls !== 0)
|
|
@@ -1348,6 +1561,7 @@ function safeAdmission(reply) {
|
|
|
1348
1561
|
&& !(report && Object.hasOwn(report, 'provider_calls') && report.provider_calls !== 0) && !report?.samples?.some(sample => sample?.steps?.some(step => step?.checks?.length));
|
|
1349
1562
|
}
|
|
1350
1563
|
function accountingProof(record) {
|
|
1564
|
+
if (preAdmissionRateLimited(record)) return true;
|
|
1351
1565
|
const usage = record?.usage, result = record?.result, reports = [record?.report, result?.report].filter(isObject);
|
|
1352
1566
|
if (!isObject(usage)) return false;
|
|
1353
1567
|
const supplied = (object, key) => isObject(object) && Object.hasOwn(object, key);
|
|
@@ -1393,7 +1607,8 @@ function checkCapacity(answer, headers) {
|
|
|
1393
1607
|
return capacityRefusal([answer.result?.report?.refusal, ...(Array.isArray(answer.result?.refusals) ? answer.result.refusals : [])], headers);
|
|
1394
1608
|
}
|
|
1395
1609
|
function admissionCapacityCandidate(record, headers) {
|
|
1396
|
-
return capacityDelay(record?.error, headers) !== null || record?.error?.code === 'maintenance'
|
|
1610
|
+
return capacityDelay(record?.error, headers) !== null || record?.error?.code === 'maintenance'
|
|
1611
|
+
|| (record?.error?.code === 'rate-limited' && record?.dispatch === 'not_started' && record?.error?.details?.retryable !== false);
|
|
1397
1612
|
}
|
|
1398
1613
|
function isAdmissionCapacityRecord(record) {
|
|
1399
1614
|
return isObject(record) && isObject(record.error);
|
|
@@ -1401,8 +1616,8 @@ function isAdmissionCapacityRecord(record) {
|
|
|
1401
1616
|
function admissionMatches(record, id) {
|
|
1402
1617
|
if (!isObject(record)) return false;
|
|
1403
1618
|
for (const surface of [record, record.result].filter(isObject)) {
|
|
1404
|
-
for (const key of ['requestId', 'id']) if (
|
|
1405
|
-
if (
|
|
1619
|
+
for (const key of ['requestId', 'id']) if (surface[key] != null && surface[key] !== id) return false;
|
|
1620
|
+
if (surface.command != null && surface.command !== 'check') return false;
|
|
1406
1621
|
}
|
|
1407
1622
|
return true;
|
|
1408
1623
|
}
|
|
@@ -1484,6 +1699,9 @@ function capacityRetryAllowed(context, row) {
|
|
|
1484
1699
|
return terminal.length > 0 && terminal.every(answer => checkCapacityCandidate(answer) && accountingProof(answer));
|
|
1485
1700
|
}
|
|
1486
1701
|
function usagePart(record) {
|
|
1702
|
+
if (preAdmissionRateLimited(record)) {
|
|
1703
|
+
return { known: 0, unknown: 0, complete: true, total: 0, zeroWork: true, tokens: tokenUsageOf(record, { incomplete: false }) };
|
|
1704
|
+
}
|
|
1487
1705
|
const usage = isObject(record?.usage) ? record.usage : {}, result = isObject(record?.result) ? record.result : {}, reports = [record?.report, result?.report].filter(isObject);
|
|
1488
1706
|
const counter = value => Number.isSafeInteger(value) && value >= 0 ? value : undefined;
|
|
1489
1707
|
const surfaces = [record, usage, result, ...reports];
|
|
@@ -1816,38 +2034,125 @@ async function readCapacity(context, deadline, refresh) {
|
|
|
1816
2034
|
}
|
|
1817
2035
|
}
|
|
1818
2036
|
}
|
|
2037
|
+
const CAPABILITY_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
|
2038
|
+
const CAPACITY_PROBE_ATTEMPTS = 3;
|
|
2039
|
+
const CAPACITY_PROBE_ATTEMPT_MS = 10_000;
|
|
2040
|
+
const CAPACITY_PROBE_BACKOFF_MS = [250, 750];
|
|
2041
|
+
|
|
2042
|
+
function capacityStopMessage(reply) {
|
|
2043
|
+
if (!reply || reply.lost) return null;
|
|
2044
|
+
const blocked = blockingAnswer(reply);
|
|
2045
|
+
return blocked || (reply.status === 401 ? AUTH_TEXT : gateText(reply) ? 'The runtime opens soon.' : null);
|
|
2046
|
+
}
|
|
2047
|
+
function isDefinitiveCapacityReply(reply) {
|
|
2048
|
+
if (!reply || reply.lost) return false;
|
|
2049
|
+
if (reply.status === 200 && isObject(reply.json) && (Array.isArray(reply.json.features) || Object.hasOwn(reply.json, 'maintenance'))) return true;
|
|
2050
|
+
return reply.status === 404 && isObject(reply.json);
|
|
2051
|
+
}
|
|
2052
|
+
function isRetryableCapacityFailure(reply) {
|
|
2053
|
+
if (reply === null) return true;
|
|
2054
|
+
if (reply.lost) return !reply.unreachable;
|
|
2055
|
+
return reply.status === 408 || reply.status === 429 || reply.status >= 500;
|
|
2056
|
+
}
|
|
2057
|
+
function capacityProbeDelay(reply, attempt) {
|
|
2058
|
+
const fallback = CAPACITY_PROBE_BACKOFF_MS[Math.min(attempt, CAPACITY_PROBE_BACKOFF_MS.length - 1)];
|
|
2059
|
+
if (!reply || reply.lost || ![429, 503].includes(reply.status)) return fallback;
|
|
2060
|
+
const raw = reply.headers?.get?.('retry-after'), seconds = Number(raw);
|
|
2061
|
+
if (raw && /^\d+$/.test(raw.trim()) && Number.isFinite(seconds) && seconds > 0) {
|
|
2062
|
+
return Math.min(2_000, Math.max(200, seconds * 1000));
|
|
2063
|
+
}
|
|
2064
|
+
return fallback;
|
|
2065
|
+
}
|
|
2066
|
+
function shouldSendLazyInterfaces(context) {
|
|
2067
|
+
if (context.serverFeatures?.includes('lazy-interfaces')) return true;
|
|
2068
|
+
return context.allowMissingInterfaces === true && context.capacityDefinitive !== true;
|
|
2069
|
+
}
|
|
1819
2070
|
async function probeLazyInterfaces(context, origin, store) {
|
|
1820
2071
|
if (context.lazyInterfacesProbed) return !!context.allowMissingInterfaces;
|
|
1821
2072
|
context.lazyInterfacesProbed = true;
|
|
1822
|
-
let identity;
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
2073
|
+
let identity = context.identity ?? null;
|
|
2074
|
+
if (!identity) {
|
|
2075
|
+
try { identity = signIn(context.ports.gh, store, context.ports, { exitCode: context.doorMode ? 125 : 5 }); }
|
|
2076
|
+
catch (error) { if (error instanceof Stop) return false; throw error; }
|
|
2077
|
+
}
|
|
2078
|
+
if (context.liveLocal) context.localOwner ??= identity.login;
|
|
2079
|
+
const auth = context.auth ?? authSession({ identity, store, ports: context.ports, signInExitCode: context.doorMode ? 125 : 5, ...(context.liveLocal ? { expectedOwnerLogin: context.localOwner, ownerMismatchError: () => new Stop(5, 'live-local-owner-changed') } : {}) });
|
|
1827
2080
|
const probe = { origin, identity, ports: context.ports, signal: context.signal, interrupted: context.interrupted, auth };
|
|
1828
|
-
const
|
|
1829
|
-
|
|
2081
|
+
const probeDeadline = context.ports.now() + GET_MS;
|
|
2082
|
+
let reply = null;
|
|
2083
|
+
for (let attempt = 0; attempt < CAPACITY_PROBE_ATTEMPTS; attempt++) {
|
|
2084
|
+
if (context.interrupted || context.signal?.aborted) break;
|
|
2085
|
+
const remaining = probeDeadline - context.ports.now();
|
|
2086
|
+
if (remaining <= 0) break;
|
|
2087
|
+
const attemptDeadline = context.ports.now() + Math.min(CAPACITY_PROBE_ATTEMPT_MS, remaining);
|
|
2088
|
+
reply = await readCapacity(probe, attemptDeadline, attempt > 0);
|
|
2089
|
+
const stop = capacityStopMessage(reply);
|
|
2090
|
+
if (stop) throw new Stop(context.doorMode ? 125 : 5, stop);
|
|
2091
|
+
if (isDefinitiveCapacityReply(reply)) {
|
|
2092
|
+
const features = reply.status === 200 && Array.isArray(reply.json?.features) ? reply.json.features : [];
|
|
2093
|
+
const engineSha = reply.status === 200 ? reply.json?.engine_sha ?? null : null;
|
|
2094
|
+
const supportsLazy = features.includes('lazy-interfaces');
|
|
2095
|
+
if (supportsLazy) store?.writeOriginCapabilities(origin, { features, engine_sha: engineSha }, context.ports.now());
|
|
2096
|
+
else store?.deleteOriginCapabilities(origin);
|
|
2097
|
+
context.probedIdentity = identity;
|
|
2098
|
+
context.serverFeatures = features;
|
|
2099
|
+
context.serverEngineSha = engineSha;
|
|
2100
|
+
context.allowMissingInterfaces = supportsLazy;
|
|
2101
|
+
context.capacityDefinitive = true;
|
|
2102
|
+
return supportsLazy;
|
|
2103
|
+
}
|
|
2104
|
+
if (!isRetryableCapacityFailure(reply) || attempt + 1 >= CAPACITY_PROBE_ATTEMPTS) break;
|
|
2105
|
+
const delay = Math.min(capacityProbeDelay(reply, attempt), Math.max(0, probeDeadline - context.ports.now()));
|
|
2106
|
+
if (delay <= 0) break;
|
|
2107
|
+
await context.ports.sleep(delay, context.signal);
|
|
2108
|
+
}
|
|
2109
|
+
if (context.interrupted || context.signal?.aborted) throw new Stop(context.doorMode ? 125 : 3, 'Stopped before sending.');
|
|
2110
|
+
const cached = store?.readOriginCapabilities(origin, context.ports.now()) ?? null;
|
|
1830
2111
|
context.probedIdentity = identity;
|
|
1831
|
-
context.
|
|
1832
|
-
context.
|
|
1833
|
-
|
|
1834
|
-
|
|
2112
|
+
context.allowMissingInterfaces = true;
|
|
2113
|
+
context.capacityDefinitive = false;
|
|
2114
|
+
if (cached) {
|
|
2115
|
+
context.serverFeatures = cached.features;
|
|
2116
|
+
context.serverEngineSha = cached.engine_sha ?? null;
|
|
2117
|
+
if (!context.capacityWarning) {
|
|
2118
|
+
context.capacityWarning = true;
|
|
2119
|
+
line(context.ports.stderr, 'Warning: interpreter capacity could not be read; using cached lazy-interfaces capability for this interpreter.');
|
|
2120
|
+
}
|
|
2121
|
+
} else if (!context.capacityWarning) {
|
|
2122
|
+
context.capacityWarning = true;
|
|
2123
|
+
line(context.ports.stderr, 'Warning: interpreter capacity could not be read; continuing with ordinary interpreter admission.');
|
|
2124
|
+
}
|
|
2125
|
+
return true;
|
|
1835
2126
|
}
|
|
1836
2127
|
async function capacityReady(context, deadline, busyRow = null) {
|
|
1837
2128
|
let refresh = !!context.admissionMaintenance;
|
|
1838
2129
|
while (!context.interrupted && !context.stopped && !context.sendError && context.ports.now() < deadline) {
|
|
1839
2130
|
const reply = await readCapacity(context, deadline, refresh);
|
|
1840
2131
|
if (reply === null || context.interrupted || context.signal?.aborted || context.ports.now() >= deadline) return false;
|
|
1841
|
-
const
|
|
1842
|
-
const stop = blocked || (reply.status === 401 ? AUTH_TEXT : gateText(reply) ? 'The runtime opens soon.' : null);
|
|
2132
|
+
const stop = capacityStopMessage(reply);
|
|
1843
2133
|
if (stop) { context.stopped = { code: 'blocked', message: stop }; throw new Stop(5, stop); }
|
|
1844
|
-
const understood = reply.status === 404 || reply.status === 200 && isObject(reply.json) && Object.hasOwn(reply.json, 'maintenance');
|
|
2134
|
+
const understood = reply.status === 404 || reply.status === 200 && isObject(reply.json) && (Object.hasOwn(reply.json, 'maintenance') || Array.isArray(reply.json.features));
|
|
1845
2135
|
// The interpreter declares what it supports; pdd names the tests to lint only when it says so.
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
context.
|
|
1850
|
-
|
|
2136
|
+
if (understood) {
|
|
2137
|
+
context.serverFeatures = reply.status === 200 && Array.isArray(reply.json?.features) ? reply.json.features : [];
|
|
2138
|
+
context.serverEngineSha = reply.status === 200 ? reply.json?.engine_sha ?? null : null;
|
|
2139
|
+
context.capacityDefinitive = true;
|
|
2140
|
+
if (reply.status === 200 && context.serverFeatures.includes('lazy-interfaces')) {
|
|
2141
|
+
context.store?.writeOriginCapabilities(context.origin, { features: context.serverFeatures, engine_sha: context.serverEngineSha }, context.ports.now());
|
|
2142
|
+
} else if (reply.status === 200 || isObject(reply.json)) {
|
|
2143
|
+
context.store?.deleteOriginCapabilities(context.origin);
|
|
2144
|
+
}
|
|
2145
|
+
} else {
|
|
2146
|
+
if (!context.serverFeatures?.length) {
|
|
2147
|
+
const cached = context.store?.readOriginCapabilities(context.origin, context.ports.now()) ?? null;
|
|
2148
|
+
context.serverFeatures = cached ? cached.features : (context.serverFeatures ?? []);
|
|
2149
|
+
if (cached && context.serverEngineSha == null) context.serverEngineSha = cached.engine_sha ?? null;
|
|
2150
|
+
}
|
|
2151
|
+
if (context.serverEngineSha === undefined) context.serverEngineSha = null;
|
|
2152
|
+
if (!context.capacityWarning) {
|
|
2153
|
+
context.capacityWarning = true;
|
|
2154
|
+
line(context.ports.stderr, 'Warning: interpreter capacity could not be read; continuing with ordinary interpreter admission.');
|
|
2155
|
+
}
|
|
1851
2156
|
}
|
|
1852
2157
|
const now = context.ports.now();
|
|
1853
2158
|
const maintenance = reply.status === 200 ? reply.json?.maintenance : null, until = Date.parse(maintenance?.until);
|
|
@@ -1928,7 +2233,14 @@ function judgePost(reply, id, command, secrets) {
|
|
|
1928
2233
|
return sameJob(reply.json, id, command) ? { kind: 'accepted', answer: reply.json, wait: checkCapacity(reply.json, reply.headers) } : { kind: 'unknown', why: 'The interpreter answered with another request ID or command.' };
|
|
1929
2234
|
}
|
|
1930
2235
|
if (reply.status === 429) {
|
|
1931
|
-
|
|
2236
|
+
const retryable429 = (error?.code === 'server-full' || (error?.code === 'rate-limited' && error?.details?.retryable !== false))
|
|
2237
|
+
&& reply.json?.dispatch === 'not_started' && safeAdmission(reply);
|
|
2238
|
+
if (retryable429 && command === 'check') {
|
|
2239
|
+
if (!admissionMatches(reply.json, id) || !accountingProof(reply.json))
|
|
2240
|
+
return { kind: 'unknown', why: 'Check capacity accounting is incomplete or conflicting.', admission: reply.json, capacity_uncertain: true };
|
|
2241
|
+
return { kind: 'busy', wait: retryAfter(reply.headers), admission: reply.json };
|
|
2242
|
+
}
|
|
2243
|
+
return retryable429 ? { kind: 'busy', wait: retryAfter(reply.headers), admission: reply.json }
|
|
1932
2244
|
: { kind: 'not_run', note: note('The interpreter is busy. Try again later.') };
|
|
1933
2245
|
}
|
|
1934
2246
|
if (gateText(reply)) return { kind: 'stop', note: { code: null, message: 'The runtime opens soon.' } };
|
|
@@ -1986,6 +2298,22 @@ function localSetup(cwd, words, ports) {
|
|
|
1986
2298
|
const sentTests = rows => rows.filter(row => !row.unsent && !row.native_only?.length).map(row => row.test);
|
|
1987
2299
|
const unmatchedLines = found => (found.orphans ?? []).map(item => `Warning: ${item.line}`);
|
|
1988
2300
|
|
|
2301
|
+
function untestedMatchesWords(item, words) {
|
|
2302
|
+
return words.some(raw => {
|
|
2303
|
+
const word = String(raw ?? '').replace(/^\.\//, '');
|
|
2304
|
+
if (!word) return false;
|
|
2305
|
+
return item.storyPath === word || item.story === word || word === '.'
|
|
2306
|
+
|| (!word.startsWith('../') && word !== '..' && item.storyPath?.startsWith(`${word.replace(/\/$/, '')}/`));
|
|
2307
|
+
});
|
|
2308
|
+
}
|
|
2309
|
+
|
|
2310
|
+
function scopedDiscoveryWarnings(found, words = []) {
|
|
2311
|
+
const warnings = found?.warnings ?? [];
|
|
2312
|
+
if (!words.length || !(found?.untested?.length)) return [...warnings];
|
|
2313
|
+
const hidden = new Set(found.untested.filter(item => !untestedMatchesWords(item, words)).map(item => `Warning: ${item.line}`));
|
|
2314
|
+
return hidden.size ? warnings.filter(text => !hidden.has(text)) : [...warnings];
|
|
2315
|
+
}
|
|
2316
|
+
|
|
1989
2317
|
function storyList(found, ports) {
|
|
1990
2318
|
return [...found.tests.map(test => ` ${test.story} ${test.path}${test.title && test.title !== test.story ? ` (${test.title})` : ''}`),
|
|
1991
2319
|
...(found.untested ?? []).map(item => ` ${item.story} no test (expected ${ports.expectedTestPath(item.storyPath)})`)];
|
|
@@ -2254,6 +2582,8 @@ function applyAnswer(row, answer, context, observedWait = null, observedAt = con
|
|
|
2254
2582
|
if (capacityUncertain) row.capacity_uncertain = true;
|
|
2255
2583
|
else if (capacitySafe) row.capacity_uncertain = false;
|
|
2256
2584
|
row.cache_identity = answerCacheIdentity(answer);
|
|
2585
|
+
const savedOriginalCalls = answer?.result?.report?.saved_answer?.original_provider_calls;
|
|
2586
|
+
row.saved_answer_original_calls = Number.isSafeInteger(savedOriginalCalls) && savedOriginalCalls >= 0 ? savedOriginalCalls : null;
|
|
2257
2587
|
// Evidence is no newer than its original batch, even when read much later.
|
|
2258
2588
|
const times = [context.startedAt, ...[answer?.finished_at, answer?.completed_at, answer?.ended_at].map(value => typeof value === 'number' ? value : Date.parse(value))].filter(Number.isFinite);
|
|
2259
2589
|
row.cache_sample_at = times.length ? Math.min(...times) : null;
|
|
@@ -2270,6 +2600,8 @@ function applyAnswer(row, answer, context, observedWait = null, observedAt = con
|
|
|
2270
2600
|
const advice = noVerdictAdvice(answer, view);
|
|
2271
2601
|
const firstDiagnosis = view.failed_checks.find(check => check.diagnosis) ?? null, failed = view.state === 'failed';
|
|
2272
2602
|
Object.assign(row, { state: view.state, checks: view.checks, criteria: view.criteria, failed_checks: view.failed_checks, all_checks: view.all_checks,
|
|
2603
|
+
...(view.step_details?.length ? { step_details: view.step_details } : {}),
|
|
2604
|
+
...(view.draft_interfaces?.length ? { draft_interfaces: view.draft_interfaces } : {}),
|
|
2273
2605
|
...(Object.hasOwn(view, 'field_agreement') ? { field_agreement: view.field_agreement } : {}),
|
|
2274
2606
|
...(view.sample_divergence ? { sample_divergence: view.sample_divergence } : {}),
|
|
2275
2607
|
refusals: view.refusals.map((item, index) => interfaceDiagnostic(item,
|
|
@@ -2804,7 +3136,7 @@ async function sendCheckAttempt(context, row) {
|
|
|
2804
3136
|
...(context.freshChecks || context.checkOptions?.fresh ? { fresh: true } : {}),
|
|
2805
3137
|
...(context.checkOptions ? { samples: context.checkOptions.samples,
|
|
2806
3138
|
...(context.checkOptions.step_ids ? { step_ids: context.checkOptions.step_ids } : {}) } : {}),
|
|
2807
|
-
...(context
|
|
3139
|
+
...(shouldSendLazyInterfaces(context) ? { lazy_interfaces: true } : {}),
|
|
2808
3140
|
...sourceProvenance(context) };
|
|
2809
3141
|
let verdict;
|
|
2810
3142
|
try { verdict = await context.postCheck(request, row, Math.max(1, Math.min(context.ports.postMs, context.deadline - context.ports.now()))); }
|
|
@@ -3029,7 +3361,7 @@ async function runLint(context) {
|
|
|
3029
3361
|
const request = { requestId: context.ports.randomUUID(), source_sha256: context.capture.sha256, complete: true, ...named,
|
|
3030
3362
|
...sourceProvenance(context),
|
|
3031
3363
|
...(selectedCap != null ? { max_calls: selectedCap } : {}),
|
|
3032
|
-
...(context
|
|
3364
|
+
...(shouldSendLazyInterfaces(context) ? { lazy_interfaces: true } : {}) };
|
|
3033
3365
|
context.lint.request_ids.push(request.requestId);
|
|
3034
3366
|
const verdict = await postJob(context, '/v1/lint', 'lint', request, null, Math.max(1, Math.min(context.ports.postMs, lintEnd - context.ports.now())), lintEnd);
|
|
3035
3367
|
if (verdict.kind === 'busy') { if (await pause(verdict.wait, verdict.maintenance)) continue; return busy(); }
|
|
@@ -3040,10 +3372,17 @@ async function runLint(context) {
|
|
|
3040
3372
|
let readEnd = verdict.kind === 'unknown' && !Number.isFinite(lintEnd)
|
|
3041
3373
|
? context.ports.now() + LOST_READ_MS : lintEnd;
|
|
3042
3374
|
let answer = verdict.answer ?? null, id = request.requestId, lost = false;
|
|
3375
|
+
const lintPollStart = context.ports.now();
|
|
3376
|
+
const lintLongPoll = !context.ports.pollMsExplicit && context.serverFeatures?.includes('wait-prefer-v1');
|
|
3043
3377
|
while (!['passed', 'failed', 'refused', 'unknown'].includes(answer?.state) && context.ports.now() < readEnd && !context.interrupted) {
|
|
3044
|
-
|
|
3045
|
-
|
|
3046
|
-
|
|
3378
|
+
if (!lintLongPoll) {
|
|
3379
|
+
const delay = context.ports.pollDelay(context.ports.now() - lintPollStart);
|
|
3380
|
+
await context.ports.sleep(Math.min(delay, Math.max(0, readEnd - context.ports.now())), context.signal);
|
|
3381
|
+
if (context.interrupted || context.ports.now() >= readEnd) break;
|
|
3382
|
+
}
|
|
3383
|
+
const remainingMs = Math.max(1, readEnd - context.ports.now());
|
|
3384
|
+
const waitSeconds = lintLongPoll ? Math.min(WAIT_PREFER_RUN_SECONDS, Math.max(1, Math.floor(remainingMs / 1000))) : 0;
|
|
3385
|
+
const read = judgeGet(await context.runtime.get(id, Math.max(1, Math.min(GET_MS, remainingMs)), { waitSeconds }), id, 'lint');
|
|
3047
3386
|
if (read.kind === 'state') {
|
|
3048
3387
|
answer = read.answer;
|
|
3049
3388
|
if (['queued', 'running'].includes(answer.state)) readEnd = lintEnd;
|
|
@@ -3052,7 +3391,13 @@ async function runLint(context) {
|
|
|
3052
3391
|
else if (read.kind === 'unknown') { lost = true; break; }
|
|
3053
3392
|
else if (read.kind === 'blocked') throw new Stop(5, read.message);
|
|
3054
3393
|
else if (read.kind === 'auth' || read.kind === 'gate') return { kind: 'stop', note: { code: null, message: read.kind === 'auth' ? AUTH_TEXT : 'The runtime opens soon.' } };
|
|
3055
|
-
if (!['passed', 'failed', 'refused', 'unknown'].includes(answer?.state))
|
|
3394
|
+
if (!['passed', 'failed', 'refused', 'unknown'].includes(answer?.state)) {
|
|
3395
|
+
tick(`Still checking the files: ${waitWord(answer, read)}`);
|
|
3396
|
+
if (lintLongPoll) {
|
|
3397
|
+
const delay = context.ports.pollDelay(context.ports.now() - lintPollStart);
|
|
3398
|
+
await context.ports.sleep(Math.min(delay, Math.max(0, readEnd - context.ports.now())), context.signal);
|
|
3399
|
+
}
|
|
3400
|
+
}
|
|
3056
3401
|
}
|
|
3057
3402
|
if (!lost && answer?.state === 'refused' && safeAdmission({ json: answer })) {
|
|
3058
3403
|
const refusals = [answer.result?.report?.refusal, ...(Array.isArray(answer.result?.refusals) ? answer.result.refusals : [])];
|
|
@@ -3158,7 +3503,76 @@ async function runScheduledChecks(context, rows, toSend) {
|
|
|
3158
3503
|
};
|
|
3159
3504
|
let waitingShown = -1;
|
|
3160
3505
|
const progress = context.checkProgress ??= { startedAt: ports.now(), shownAt: ports.now() };
|
|
3506
|
+
const pollStartedAt = ports.now();
|
|
3161
3507
|
const readable = row => isOpen(row) && ports.now() < Math.min(context.deadline, row.lost ? row.read_until ?? context.deadline : context.deadline);
|
|
3508
|
+
const sseEnabled = !ports.pollMsExplicit && Boolean(context.serverFeatures?.includes('sse-stream-v1'));
|
|
3509
|
+
const activeStreams = new Map();
|
|
3510
|
+
let wakeResolve = null;
|
|
3511
|
+
const notifyWake = () => { if (wakeResolve) { const fn = wakeResolve; wakeResolve = null; fn(); } };
|
|
3512
|
+
const formatStageEvent = (row, json) => {
|
|
3513
|
+
const p = isObject(json.progress) ? json.progress : {};
|
|
3514
|
+
const stage = typeof json.stage === 'string' && json.stage ? json.stage : (typeof p.stage === 'string' ? p.stage : json.state);
|
|
3515
|
+
const stepPart = typeof p.steps_done === 'number' && typeof p.steps_total === 'number' && p.steps_total > 0
|
|
3516
|
+
? `step ${Math.min(p.steps_done + 1, p.steps_total)}/${p.steps_total}${typeof p.step === 'string' && p.step ? ` (${p.step})` : ''}`
|
|
3517
|
+
: typeof p.step === 'string' && p.step ? p.step : stage;
|
|
3518
|
+
return `${row.test}: ${stepPart}`;
|
|
3519
|
+
};
|
|
3520
|
+
const syncRowStreams = () => {
|
|
3521
|
+
if (!sseEnabled || context.interrupted || context.readStop) return;
|
|
3522
|
+
for (const row of rows.filter(readable)) {
|
|
3523
|
+
const id = row.request_ids.at(-1);
|
|
3524
|
+
if (!id) continue;
|
|
3525
|
+
const existing = activeStreams.get(row);
|
|
3526
|
+
if (existing && existing.id === id) continue;
|
|
3527
|
+
if (existing) { existing.controller.abort(); activeStreams.delete(row); }
|
|
3528
|
+
if (activeStreams.size >= MAX_READS) break;
|
|
3529
|
+
const controller = new AbortController();
|
|
3530
|
+
const onSignal = () => controller.abort();
|
|
3531
|
+
context.signal?.addEventListener('abort', onSignal, { once: true });
|
|
3532
|
+
const end = Math.min(context.deadline, row.lost ? row.read_until ?? context.deadline : context.deadline);
|
|
3533
|
+
let lastStageKey = '';
|
|
3534
|
+
const entry = { id, controller };
|
|
3535
|
+
activeStreams.set(row, entry);
|
|
3536
|
+
entry.promise = context.runtime.streamRun(id, {
|
|
3537
|
+
useEventsPath: true,
|
|
3538
|
+
signal: controller.signal,
|
|
3539
|
+
timeoutMs: Math.max(1, end - ports.now()),
|
|
3540
|
+
onEvent: ({ event, json }) => {
|
|
3541
|
+
if (!isObject(json) || !sameJob(json, id, 'check')) return false;
|
|
3542
|
+
const enriched = (typeof json.stage === 'string' && json.stage && json.state === 'running')
|
|
3543
|
+
? { ...json, progress: { ...(isObject(json.progress) ? json.progress : {}), stage: json.stage } }
|
|
3544
|
+
: json;
|
|
3545
|
+
if (event === 'done' || ENDED.has(enriched.state)) {
|
|
3546
|
+
saveAnswer(context, id, enriched);
|
|
3547
|
+
queueProgress(context, enriched);
|
|
3548
|
+
applyAnswer(row, enriched, context, null, ports.now());
|
|
3549
|
+
row.lost = false;
|
|
3550
|
+
finishReservation(context, row, enriched).finally(notifyWake);
|
|
3551
|
+
return true;
|
|
3552
|
+
}
|
|
3553
|
+
if (event === 'accepted' || event === 'progress') {
|
|
3554
|
+
saveAnswer(context, id, enriched);
|
|
3555
|
+
queueProgress(context, enriched);
|
|
3556
|
+
applyAnswer(row, enriched, context, null, ports.now());
|
|
3557
|
+
row.lost = false;
|
|
3558
|
+
if (event === 'progress') {
|
|
3559
|
+
const key = `${enriched.state}|${enriched.stage ?? ''}|${enriched.progress?.steps_done ?? ''}|${enriched.progress?.step ?? ''}`;
|
|
3560
|
+
if (key !== lastStageKey) {
|
|
3561
|
+
lastStageKey = key;
|
|
3562
|
+
progress.shownAt = ports.now();
|
|
3563
|
+
line(ports.stderr, `Progress: ${formatStageEvent(row, enriched)}`);
|
|
3564
|
+
}
|
|
3565
|
+
}
|
|
3566
|
+
}
|
|
3567
|
+
return false;
|
|
3568
|
+
},
|
|
3569
|
+
}).catch(() => null).finally(() => {
|
|
3570
|
+
context.signal?.removeEventListener('abort', onSignal);
|
|
3571
|
+
if (activeStreams.get(row) === entry) activeStreams.delete(row);
|
|
3572
|
+
notifyWake();
|
|
3573
|
+
});
|
|
3574
|
+
}
|
|
3575
|
+
};
|
|
3162
3576
|
try {
|
|
3163
3577
|
while (!context.interrupted && !context.readStop) {
|
|
3164
3578
|
// Never count an uncertain dispatched job as a free slot, even if it cannot currently be read.
|
|
@@ -3184,17 +3598,30 @@ async function runScheduledChecks(context, rows, toSend) {
|
|
|
3184
3598
|
if (pending && active >= context.checkWindow && !rows.some(readable)) break;
|
|
3185
3599
|
if ((!pending || context.stopped || ports.now() >= context.deadline) && !rows.some(readable) && !pendingSends.size) break;
|
|
3186
3600
|
if (ports.now() - progress.shownAt >= PROGRESS_MS) { progress.shownAt = ports.now(); line(ports.stderr, progressLine(rows, progress.shownAt - progress.startedAt)); }
|
|
3601
|
+
syncRowStreams();
|
|
3187
3602
|
const end = context.deadline;
|
|
3188
|
-
|
|
3603
|
+
const delay = ports.pollDelay(ports.now() - pollStartedAt);
|
|
3604
|
+
const waitMs = Math.max(0, Math.min(activeStreams.size ? PROGRESS_MS : delay, end - ports.now()));
|
|
3605
|
+
if (activeStreams.size) {
|
|
3606
|
+
const wake = new Promise(resolve => { wakeResolve = resolve; });
|
|
3607
|
+
await Promise.race([ports.sleep(waitMs, context.signal), wake]);
|
|
3608
|
+
wakeResolve = null;
|
|
3609
|
+
} else {
|
|
3610
|
+
await ports.sleep(waitMs, context.signal);
|
|
3611
|
+
}
|
|
3189
3612
|
if (context.interrupted) break;
|
|
3190
|
-
|
|
3613
|
+
const unstreamed = rows.filter(row => readable(row) && !activeStreams.has(row));
|
|
3614
|
+
if (unstreamed.length) await eachLimited(unstreamed, MAX_READS, row => readRow(context, row));
|
|
3191
3615
|
for (const item of toSend) item.awaiting_budget = false;
|
|
3192
3616
|
await recoverRestarts(context);
|
|
3193
3617
|
if (!context.liveLocalSaved) for (const row of rows.filter(row => row.state === 'ready' && (row.restart_used || row.restart_pending))) if (!toSend.includes(row)) toSend.push(row);
|
|
3194
3618
|
saveBatch(context);
|
|
3195
3619
|
}
|
|
3196
3620
|
} catch (error) { context.sendError ??= error; throw error; }
|
|
3197
|
-
finally {
|
|
3621
|
+
finally {
|
|
3622
|
+
for (const entry of activeStreams.values()) entry.controller.abort();
|
|
3623
|
+
await Promise.all([...pendingSends.values(), ...[...activeStreams.values()].map(entry => entry.promise)]);
|
|
3624
|
+
}
|
|
3198
3625
|
if (context.sendError) throw context.sendError;
|
|
3199
3626
|
const stoppedEarly = context.interrupted || !!context.readStop;
|
|
3200
3627
|
context.timedOut ||= !stoppedEarly && ports.now() >= context.deadline && rows.some(isOpen);
|
|
@@ -3233,7 +3660,7 @@ function printResult(context, rows, extra = {}) {
|
|
|
3233
3660
|
const warnings = [...(context.warnings ?? []), ...engines.map(sha => `Warning: the interpreter engine is ${cleanText(sha).slice(0, 12)}, but pdd's local checks copy engine ${ENGINE_SHA.slice(0, 12)}. The engine stays the judge.`)];
|
|
3234
3661
|
const coverage = exitCode === 5 && context.coverage?.runtime?.native_only === 0
|
|
3235
3662
|
? Object.fromEntries(Object.entries(context.coverage).filter(([key])=>key !== 'runtime')) : context.coverage;
|
|
3236
|
-
const summary = renderJson({ batch: context.batch ?? null, repo: context.root, sourceSha256: context.capture?.sha256 ?? null, coverage, rows, exitCode, summaryLine: context.noFailed ? 'No failed Stories. 0 AI calls.' : summaryLine(rows, null, ports),
|
|
3663
|
+
const summary = renderJson({ batch: context.batch ?? null, repo: context.root, sourceSha256: context.capture?.sha256 ?? null, coverage, rows, exitCode, details: Boolean(context.details), summaryLine: context.noFailed ? 'No failed Stories. 0 AI calls.' : summaryLine(rows, null, ports),
|
|
3237
3664
|
warnings: [...new Set([...warnings, ...(context.unmatched ?? [])]), ...rows.flatMap(row => (row.warnings ?? []).map(text => `${row.test}: ${text}`))] }, ports);
|
|
3238
3665
|
if (context.intent === 'lint-only') {
|
|
3239
3666
|
const id = context.lint?.request_ids?.at(-1), answer = id && context.store.read(join(context.folder, `${id}.json`));
|
|
@@ -3328,6 +3755,7 @@ function runFiles(cwd, words, options, ports) {
|
|
|
3328
3755
|
// Locally the selected prompts' limits and interface format gates, SVG advice and privacy/capture checks run.
|
|
3329
3756
|
async function runLintOnly(context, cwd, words, options, setRelease) {
|
|
3330
3757
|
const { ports } = context, origin = runtimeOrigin(ports.env), { root, found, normalized } = localSetup(cwd, words, ports);
|
|
3758
|
+
found.warnings = scopedDiscoveryWarnings(found, normalized);
|
|
3331
3759
|
context.excludeFixtureProjects = words.length === 0;
|
|
3332
3760
|
const promptArgs = words.length > 0 && normalized.every(word => word.endsWith('.prompt.md') && found.visible.has(word));
|
|
3333
3761
|
const paths = promptArgs ? normalized : (words.length ? undefined : [...found.discoveryVisible].filter(path => path.endsWith('.prompt.md')));
|
|
@@ -3906,7 +4334,8 @@ async function runRead(context, batchWord, quiet = false, options = {}, retry =
|
|
|
3906
4334
|
if (admission?.error?.code === 'maintenance') {
|
|
3907
4335
|
context.maintenance ??= normalizeMaintenance(admission.maintenance ?? admission.error.details, ports.now(), context.secrets);
|
|
3908
4336
|
}
|
|
3909
|
-
const wait = capacityDelay(admission.error) ?? maintenanceDelay(admission, ports.now())
|
|
4337
|
+
const wait = capacityDelay(admission.error) ?? maintenanceDelay(admission, ports.now())
|
|
4338
|
+
?? (admission?.error?.code === 'rate-limited' && admission?.dispatch === 'not_started' && admission?.error?.details?.retryable !== false ? 5000 : null);
|
|
3910
4339
|
if (wait !== null && accountingProof(admission) && capacityRetryAllowed(context, row)) { markBusy(context, row, wait); return; }
|
|
3911
4340
|
markCapacityUnknown(context, row);
|
|
3912
4341
|
}
|
|
@@ -3946,12 +4375,14 @@ async function runRead(context, batchWord, quiet = false, options = {}, retry =
|
|
|
3946
4375
|
await readRow(context, row, context.deadline);
|
|
3947
4376
|
if (row.state === 'unknown' && row.lost) row.why ??= 'pdd could not read this run yet.';
|
|
3948
4377
|
});
|
|
4378
|
+
const lintPendingStart = ports.now();
|
|
3949
4379
|
while (context.lintPending && !context.interrupted && !context.readStop && ports.now() < context.deadline) {
|
|
3950
4380
|
if (ports.now() - progress.shownAt >= PROGRESS_MS) {
|
|
3951
4381
|
progress.shownAt = ports.now();
|
|
3952
4382
|
line(ports.stderr, progressLine(rows, progress.shownAt - progress.startedAt));
|
|
3953
4383
|
}
|
|
3954
|
-
|
|
4384
|
+
const delay = ports.pollDelay(ports.now() - lintPendingStart);
|
|
4385
|
+
await ports.sleep(Math.max(0, Math.min(delay, context.deadline - ports.now())), context.signal);
|
|
3955
4386
|
if (context.interrupted || ports.now() >= context.deadline) break;
|
|
3956
4387
|
await readUnsentLint(context, rows);
|
|
3957
4388
|
await eachLimited(rows.filter(isOpen), MAX_READS, row => readRow(context, row));
|
|
@@ -4543,7 +4974,7 @@ export async function runCheck({ words = [], options = {}, cwd = process.cwd(),
|
|
|
4543
4974
|
} catch (error) { if (error?.unboundPort) throw error; throw new Stop(2, error.message); }
|
|
4544
4975
|
}
|
|
4545
4976
|
const modes = ['--read', '--retry', '--files', '--explain-bindings', '--request', '--lint'].filter(name => options[name] !== undefined);
|
|
4546
|
-
const others = Object.keys(options).filter(name => !modes.includes(name) && !(
|
|
4977
|
+
const others = Object.keys(options).filter(name => !modes.includes(name) && !(['--retry', '--read'].includes(modes[0]) && ['--json', '--details', '--timeout'].includes(name)) && !(name === '--json' && ['--request', '--lint', '--files', '--explain-bindings'].includes(modes[0])) && !(name === '--timeout' && ['--lint'].includes(modes[0])) && !(name === '--max-calls' && modes[0] === '--lint') && !(name === '--app-map' && modes[0] === '--files'));
|
|
4547
4978
|
if (modes.length > 1 || (modes.length && others.length) || (['--request', '--retry'].includes(modes[0]) && words.length)
|
|
4548
4979
|
|| (modes[0] === '--read' && words.length > 1) || (!modes.length && options['--app-map'] !== undefined)) throw new Stop(2, 'This mix of options does not work together. Run pdd test --help.');
|
|
4549
4980
|
if (modes[0] === '--request') { release = interruptible(context); return await runRequest(context, options['--request'], cwd); }
|
|
@@ -4626,7 +5057,11 @@ function safeCachePath(fs, path, { directory = false, create = false } = {}) {
|
|
|
4626
5057
|
at = join(at, parts[index]);
|
|
4627
5058
|
const isDir = index < parts.length - 1 || directory;
|
|
4628
5059
|
let stat = cacheStat(fs, at);
|
|
4629
|
-
if (!stat && create && isDir) {
|
|
5060
|
+
if (!stat && create && isDir) {
|
|
5061
|
+
try { fs.mkdir(at, { mode: 0o700 }); }
|
|
5062
|
+
catch (error) { if (error?.code !== 'EEXIST') throw error; }
|
|
5063
|
+
stat = fs.lstat(at);
|
|
5064
|
+
}
|
|
4630
5065
|
if (!stat) { if (index < parts.length - 1) throw new Error('missing cache parent'); continue; }
|
|
4631
5066
|
if (stat.isSymbolicLink() || (isDir ? !stat.isDirectory() : !stat.isFile())) throw new Error('unsafe cache path');
|
|
4632
5067
|
}
|
|
@@ -4637,8 +5072,10 @@ function validTestCache(value) {
|
|
|
4637
5072
|
const path = text => typeof text === 'string' && text.length > 0 && text.length <= 4096 && !text.startsWith('/') && !text.split('/').some(part => !part || part === '.' || part === '..');
|
|
4638
5073
|
const hash = text => typeof text === 'string' && /^[a-f0-9]{64}$/.test(text);
|
|
4639
5074
|
const counts = value => value == null || keys(value, ['passed', 'total']) && ['passed', 'total'].every(key => Number.isSafeInteger(value[key]) && value[key] >= 0) && value.passed <= value.total;
|
|
4640
|
-
const evidence = row => keys(row, ['checks', 'criteria', 'criteria_total', 'draft']) && counts(row.checks) && counts(row.criteria)
|
|
4641
|
-
&& (row.criteria_total === undefined || Number.isSafeInteger(row.criteria_total) && row.criteria_total >= 0) && typeof row.draft === 'boolean'
|
|
5075
|
+
const evidence = row => keys(row, ['checks', 'criteria', 'criteria_total', 'draft', 'calls', 'max_calls']) && counts(row.checks) && counts(row.criteria)
|
|
5076
|
+
&& (row.criteria_total === undefined || Number.isSafeInteger(row.criteria_total) && row.criteria_total >= 0) && typeof row.draft === 'boolean'
|
|
5077
|
+
&& (row.calls === undefined || Number.isSafeInteger(row.calls) && row.calls >= 0)
|
|
5078
|
+
&& (row.max_calls === undefined || Number.isSafeInteger(row.max_calls) && row.max_calls >= 1);
|
|
4642
5079
|
if (!keys(value, ['schema_version', 'generation', 'epoch', 'stories', 'latest_identity']) || typeof value.epoch !== 'string' || !UUID.test(value.epoch) || value.schema_version !== 1 || !Number.isSafeInteger(value.generation) || value.generation < 0 || !isObject(value.stories) || Object.keys(value.stories).length > 10000) return false;
|
|
4643
5080
|
const latest = value.latest_identity;
|
|
4644
5081
|
if (latest !== undefined && (!keys(latest, ['engine_sha', 'models', 'observed_at', 'sampled_at', 'engine_shas', 'conflict', 'clean', 'written_at', 'in_progress', 'cohort'])
|
|
@@ -4656,13 +5093,26 @@ function validTestCache(value) {
|
|
|
4656
5093
|
|| ![latest.observed_at, latest.sampled_at].every(at => typeof at === 'string' && Number.isFinite(Date.parse(at)) && new Date(at).toISOString() === at))) return false;
|
|
4657
5094
|
return Object.entries(value.stories).every(([name, row]) => path(name) && keys(row, ['generation', 'outcome', 'pass']) && Number.isSafeInteger(row.generation) && row.generation >= 0 && row.generation <= value.generation
|
|
4658
5095
|
&& ['passed', 'failed', 'refused', 'not_run', 'unknown'].includes(row.outcome)
|
|
4659
|
-
&& (row.pass === undefined || (row.outcome === 'passed' && keys(row.pass, ['fingerprint', 'passed_at', 'tests', 'rows', 'engine_sha', 'requested_model']) && hash(row.pass.fingerprint)
|
|
5096
|
+
&& (row.pass === undefined || (row.outcome === 'passed' && keys(row.pass, ['fingerprint', 'passed_at', 'tests', 'rows', 'engine_sha', 'requested_model', 'calls_used', 'max_calls']) && hash(row.pass.fingerprint)
|
|
5097
|
+
&& (row.pass.calls_used === undefined || Number.isSafeInteger(row.pass.calls_used) && row.pass.calls_used >= 0)
|
|
5098
|
+
&& (row.pass.max_calls === undefined || row.pass.max_calls === null || Number.isSafeInteger(row.pass.max_calls) && row.pass.max_calls >= 1)
|
|
4660
5099
|
&& typeof row.pass.passed_at === 'string' && Number.isFinite(Date.parse(row.pass.passed_at)) && new Date(row.pass.passed_at).toISOString() === row.pass.passed_at
|
|
4661
5100
|
&& Array.isArray(row.pass.tests) && row.pass.tests.length > 0 && row.pass.tests.every(path) && new Set(row.pass.tests).size === row.pass.tests.length
|
|
4662
5101
|
&& keys(row.pass.rows, row.pass.tests) && Object.keys(row.pass.rows).length === row.pass.tests.length && row.pass.tests.every(test => evidence(row.pass.rows[test])))));
|
|
4663
5102
|
}
|
|
4664
|
-
function
|
|
4665
|
-
|
|
5103
|
+
function summarizeCacheError(cache, error) {
|
|
5104
|
+
if (!error) return null;
|
|
5105
|
+
const secrets = cache?.context?.secrets ?? [];
|
|
5106
|
+
const code = typeof error?.code === 'string' && error.code.trim() ? cleanText(error.code, secrets).slice(0, 40) : '';
|
|
5107
|
+
const msg = typeof error?.message === 'string' && error.message.trim() ? cleanText(error.message, secrets).slice(0, 140) : '';
|
|
5108
|
+
if (code && msg) return msg.startsWith(code) ? msg : `${code}: ${msg}`;
|
|
5109
|
+
return code || msg || null;
|
|
5110
|
+
}
|
|
5111
|
+
function cacheWarning(cache, recovered = false, error = null) {
|
|
5112
|
+
const detail = summarizeCacheError(cache, error);
|
|
5113
|
+
const message = detail
|
|
5114
|
+
? `Warning: test cache unavailable or damaged (${detail}); running selected Stories without reuse. To reset, run pdd test --cache-clear.`
|
|
5115
|
+
: 'Warning: test cache unavailable or damaged; running selected Stories without reuse. To reset, run pdd test --cache-clear.';
|
|
4666
5116
|
if (!cache.warned) cache.warningIndex = cache.context.warnings.push(message) - 1;
|
|
4667
5117
|
else if (cache.recoveredWarning) cache.context.warnings[cache.warningIndex] = message;
|
|
4668
5118
|
cache.recoveredWarning = false;
|
|
@@ -4783,7 +5233,7 @@ async function acquireCacheGuard(cache) {
|
|
|
4783
5233
|
if (!Number.isSafeInteger(ticket)) throw new Error('cache ticket overflow');
|
|
4784
5234
|
fs.write(join(own, 'ticket.tmp'), JSON.stringify(ticket), { flag: 'wx', mode: 0o600 });
|
|
4785
5235
|
fs.rename(join(own, 'ticket.tmp'), join(own, 'ticket.json'));
|
|
4786
|
-
for (let attempt = 0; attempt <
|
|
5236
|
+
for (let attempt = 0; attempt < 100; attempt++) {
|
|
4787
5237
|
if (!peers().some(peer => peer.ticket === null || peer.ticket < ticket || peer.ticket === ticket && peer.name < name)) return () => remove(own);
|
|
4788
5238
|
await cache.context.ports.sleep(10);
|
|
4789
5239
|
}
|
|
@@ -4796,7 +5246,7 @@ async function cacheTransaction(cache, operation, clear = false) {
|
|
|
4796
5246
|
try {
|
|
4797
5247
|
safeCachePath(cache.fs, cache.dir, { directory: true });
|
|
4798
5248
|
releaseGuard = await acquireCacheGuard(cache);
|
|
4799
|
-
for (let attempt = 0; attempt <
|
|
5249
|
+
for (let attempt = 0; attempt < 100; attempt++) {
|
|
4800
5250
|
try {
|
|
4801
5251
|
cache.fs.mkdir(cache.lock); locked = true;
|
|
4802
5252
|
owner = { pid: process.pid, token: cache.fs.nonce() };
|
|
@@ -4836,7 +5286,7 @@ async function cacheTransaction(cache, operation, clear = false) {
|
|
|
4836
5286
|
try { snapshot = readTestCache(cache); }
|
|
4837
5287
|
catch (error) {
|
|
4838
5288
|
safeCachePath(cache.fs, cache.path);
|
|
4839
|
-
cacheWarning(cache, true);
|
|
5289
|
+
cacheWarning(cache, true, error);
|
|
4840
5290
|
// A new namespace prevents an earlier in-flight generation from matching.
|
|
4841
5291
|
snapshot = { data: freshTestCache(cache), history: false };
|
|
4842
5292
|
}
|
|
@@ -4861,16 +5311,16 @@ async function cacheTransaction(cache, operation, clear = false) {
|
|
|
4861
5311
|
try { cache.fs.unlink(path); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
4862
5312
|
}
|
|
4863
5313
|
return result;
|
|
4864
|
-
} catch { cacheWarning(cache); return null; }
|
|
5314
|
+
} catch (error) { cacheWarning(cache, false, error); return null; }
|
|
4865
5315
|
finally {
|
|
4866
5316
|
if (locked) try {
|
|
4867
5317
|
const path = join(cache.lock, 'owner.json');
|
|
4868
5318
|
safeCachePath(cache.fs, path);
|
|
4869
5319
|
if (owner && isDeepStrictEqual(JSON.parse(cache.fs.read(path, 'utf8', 128)), owner)) {
|
|
4870
5320
|
cache.fs.unlink(path); cache.fs.rmdir(cache.lock);
|
|
4871
|
-
} else cacheWarning(cache);
|
|
4872
|
-
} catch { cacheWarning(cache); }
|
|
4873
|
-
if (releaseGuard) try { releaseGuard(); } catch { cacheWarning(cache); }
|
|
5321
|
+
} else cacheWarning(cache, false, new Error('cache lock ownership changed'));
|
|
5322
|
+
} catch (error) { cacheWarning(cache, false, error); }
|
|
5323
|
+
if (releaseGuard) try { releaseGuard(); } catch (error) { cacheWarning(cache, false, error); }
|
|
4874
5324
|
}
|
|
4875
5325
|
}
|
|
4876
5326
|
async function openTestCache(context, root, clear, visible) {
|
|
@@ -4918,7 +5368,7 @@ async function openTestCache(context, root, clear, visible) {
|
|
|
4918
5368
|
cache.history = false;
|
|
4919
5369
|
}
|
|
4920
5370
|
}, clear);
|
|
4921
|
-
} catch { cacheWarning(cache); }
|
|
5371
|
+
} catch (error) { cacheWarning(cache, false, error); }
|
|
4922
5372
|
return cache;
|
|
4923
5373
|
}
|
|
4924
5374
|
function storyFingerprint(cache, capture, story, options, origin) {
|
|
@@ -4927,7 +5377,7 @@ function storyFingerprint(cache, capture, story, options, origin) {
|
|
|
4927
5377
|
const rawPaths = [...new Set([story, ...footprint.tests, ...footprint.files.filter(file => file.path.endsWith('.prompt.md')).map(file => file.path)])].sort();
|
|
4928
5378
|
const raw = rawPaths.map(path => [path, capture.raw_file_hashes?.[path] ?? (path.endsWith('.prompt.md') ? capture.raw_prompt_hashes?.[path] : undefined)]);
|
|
4929
5379
|
if (raw.some(([, hash]) => !hash)) return null;
|
|
4930
|
-
return cache.context.ports.cacheHash(Buffer.from(JSON.stringify({ footprint, raw, origin,
|
|
5380
|
+
return cache.context.ports.cacheHash(Buffer.from(JSON.stringify({ footprint, raw, origin, pdd_version: cache.context.clientVersion ?? null })));
|
|
4931
5381
|
}
|
|
4932
5382
|
// The captured footprint owns reachability; inspect its captured declarations without
|
|
4933
5383
|
// inventing another dependency graph or reading a later version of a source file.
|
|
@@ -4998,6 +5448,46 @@ function eligibleCachePass(pass, now) {
|
|
|
4998
5448
|
function identityFingerprint(cache, fingerprint, identity) {
|
|
4999
5449
|
return cache.context.ports.cacheHash(Buffer.from(JSON.stringify({ fingerprint, engine_sha: identity?.engine_sha ?? null, requested_model: identity?.requested_model ?? null })));
|
|
5000
5450
|
}
|
|
5451
|
+
function liveInProgressMarks(cache, marks) {
|
|
5452
|
+
const isAlive = cache.context.ports.isAlive ?? (pid => { try { process.kill(pid, 0); return true; } catch (error) { return error.code !== 'ESRCH'; } });
|
|
5453
|
+
return (marks ?? []).filter(mark => isAlive(mark.pid));
|
|
5454
|
+
}
|
|
5455
|
+
function hasVerifiedIdentityRecord(record) {
|
|
5456
|
+
return !!record && record.conflict === false
|
|
5457
|
+
&& typeof record.engine_sha === 'string' && record.engine_sha.trim() && record.engine_sha.trim().toLowerCase() !== 'unknown'
|
|
5458
|
+
&& Array.isArray(record.models) && record.models.length === 1
|
|
5459
|
+
&& typeof record.models[0] === 'string' && record.models[0].trim() && record.models[0].trim().toLowerCase() !== 'unknown'
|
|
5460
|
+
&& (record.engine_shas ?? [record.engine_sha]).every(value => value === record.engine_sha);
|
|
5461
|
+
}
|
|
5462
|
+
function verifiedIdentityMatchesPass(cache, record, pass, story) {
|
|
5463
|
+
if (!record || !pass) return false;
|
|
5464
|
+
if (cleanRecordMatches(record, pass)) return true;
|
|
5465
|
+
if (!hasVerifiedIdentityRecord(record)) return false;
|
|
5466
|
+
if (!observedIdentityMatches(record, pass)) return false;
|
|
5467
|
+
const live = liveInProgressMarks(cache, record.in_progress);
|
|
5468
|
+
if (!live.length) return record.clean === true || record.conflict === false;
|
|
5469
|
+
const cohort = record.cohort;
|
|
5470
|
+
if (!cohort || cohort.valid === false) return false;
|
|
5471
|
+
if (cohort.engine_sha !== null && cohort.engine_sha !== pass.engine_sha) return false;
|
|
5472
|
+
if (cohort.requested_model !== null && cohort.requested_model !== pass.requested_model) return false;
|
|
5473
|
+
const liveTokens = new Set(live.map(mark => mark.token));
|
|
5474
|
+
for (const member of cohort.members ?? []) {
|
|
5475
|
+
if (liveTokens.has(member.token) && member.stories.includes(story)) return false;
|
|
5476
|
+
}
|
|
5477
|
+
return live.every(mark => (cohort.members ?? []).some(member => member.token === mark.token));
|
|
5478
|
+
}
|
|
5479
|
+
function passSatisfiesMaxCalls(pass, own) {
|
|
5480
|
+
for (const row of own) {
|
|
5481
|
+
if (!Number.isSafeInteger(row.max_calls) || row.max_calls < 1) continue;
|
|
5482
|
+
const savedRow = pass?.rows?.[row.test];
|
|
5483
|
+
const required = Number.isSafeInteger(savedRow?.calls) ? savedRow.calls
|
|
5484
|
+
: Number.isSafeInteger(pass?.calls_used) ? pass.calls_used
|
|
5485
|
+
: Number.isSafeInteger(savedRow?.max_calls) ? savedRow.max_calls
|
|
5486
|
+
: Number.isSafeInteger(pass?.max_calls) ? pass.max_calls : 0;
|
|
5487
|
+
if (row.max_calls < required) return false;
|
|
5488
|
+
}
|
|
5489
|
+
return true;
|
|
5490
|
+
}
|
|
5001
5491
|
// Call only while holding the cache transaction; normal and saved-read sends
|
|
5002
5492
|
// share ownership so another invocation cannot reuse evidence while either runs.
|
|
5003
5493
|
function markTestAttempt(cache, data) {
|
|
@@ -5015,15 +5505,17 @@ function markTestAttempt(cache, data) {
|
|
|
5015
5505
|
cache.mark = { token: cache.fs.nonce(), pid: cache.context.ports.pid ?? process.pid, started_at: cache.context.ports.now() };
|
|
5016
5506
|
const latest = data.latest_identity ?? { engine_sha: null, models: [], clean: false, conflict: true,
|
|
5017
5507
|
sampled_at: new Date(0).toISOString(), observed_at: new Date(cache.context.ports.now()).toISOString() };
|
|
5018
|
-
const isAlive = cache.context.ports.isAlive ?? (pid => { try { process.kill(pid, 0); return true; } catch (error) { return error.code !== 'ESRCH'; } });
|
|
5019
5508
|
// Eligibility already saw every mark, including dead owners. Only now retire
|
|
5020
5509
|
// dead marks; live owners must survive another invocation's finish.
|
|
5021
5510
|
const oldMarks = latest.in_progress ?? [];
|
|
5022
|
-
const live =
|
|
5511
|
+
const live = liveInProgressMarks(cache, oldMarks);
|
|
5023
5512
|
const stories = [...cache.tokens.keys()];
|
|
5024
|
-
|
|
5025
|
-
|
|
5026
|
-
|
|
5513
|
+
const verifiedBase = hasVerifiedIdentityRecord(latest);
|
|
5514
|
+
if (!live.length) {
|
|
5515
|
+
latest.cohort = { members: [], valid: true, engine_sha: verifiedBase ? latest.engine_sha : null, requested_model: verifiedBase ? latest.models[0] : null, floor: Date.parse(latest.sampled_at) };
|
|
5516
|
+
} else if (!latest.cohort || !live.every(mark => latest.cohort.members.some(member => member.token === mark.token))) {
|
|
5517
|
+
latest.cohort = { members: [], valid: false, engine_sha: null, requested_model: null, floor: Date.parse(latest.sampled_at) };
|
|
5518
|
+
}
|
|
5027
5519
|
if (latest.cohort.members.some(member => member.stories.some(story => stories.includes(story)))) latest.cohort.valid = false;
|
|
5028
5520
|
latest.cohort.members.push({ token: cache.mark.token, stories });
|
|
5029
5521
|
latest.in_progress = [...live, cache.mark];
|
|
@@ -5041,14 +5533,19 @@ async function beginTestAttempts(cache, rows, capture, options, origin, force =
|
|
|
5041
5533
|
const fingerprint = capture ? storyFingerprint(cache, capture, story, options, origin) : null;
|
|
5042
5534
|
const pass = data.stories[story]?.pass;
|
|
5043
5535
|
const eligible = eligibleCachePass(pass, cache.context.ports.now()) && fingerprint && pass.fingerprint === identityFingerprint(cache, fingerprint, pass) && own.every(row => row.state === 'ready' && pass.tests.includes(row.test));
|
|
5536
|
+
const budgetAllows = !eligible || passSatisfiesMaxCalls(pass, own);
|
|
5044
5537
|
const identity = data.latest_identity;
|
|
5045
|
-
const knownDrift =
|
|
5538
|
+
const knownDrift = hasVerifiedIdentityRecord(identity) && ((identity.engine_sha && identity.engine_sha !== pass?.engine_sha) || (identity.models?.length === 1 && identity.models[0] !== pass?.requested_model));
|
|
5046
5539
|
const reason = capture && declarationCacheReason(capture, story, own.map(row => row.test))
|
|
5047
5540
|
|| (Number.isFinite(Date.parse(pass?.passed_at)) && cache.context.ports.now() - Date.parse(pass.passed_at) > 7 * 86400000 ? 'runs again: saved pass is older than seven days' : null)
|
|
5048
|
-
|| (eligible && !
|
|
5541
|
+
|| (eligible && !budgetAllows ? 'runs again: --max-calls is lower than the saved pass call count' : null)
|
|
5542
|
+
|| (eligible && !verifiedIdentityMatchesPass(cache, identity, pass, story) ? (knownDrift ? 'runs again: interpreter build or model changed' : 'runs again: cache identity is unverified') : null);
|
|
5049
5543
|
if (reason) for (const row of own) row.cache_reason ??= reason;
|
|
5050
|
-
if (!force && !reason && [undefined, '', '0', 'false'].includes(cache.context.ports.env.CI) &&
|
|
5051
|
-
for (const row of own)
|
|
5544
|
+
if (!force && !reason && [undefined, '', '0', 'false'].includes(cache.context.ports.env.CI) && eligible && budgetAllows) {
|
|
5545
|
+
for (const row of own) {
|
|
5546
|
+
const { checks, criteria, criteria_total, draft } = pass.rows[row.test];
|
|
5547
|
+
Object.assign(row, { checks, criteria, criteria_total, draft, state: 'passed', cached: true, cache_identity: { engine_sha: pass.engine_sha, requested_model: pass.requested_model }, passed_at: pass.passed_at, phase: 'cache', calls: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, cached_input_share: null, seconds: 0, request_ids: [], report_url: null });
|
|
5548
|
+
}
|
|
5052
5549
|
continue;
|
|
5053
5550
|
}
|
|
5054
5551
|
const generation = ++data.generation;
|
|
@@ -5066,42 +5563,100 @@ async function finishTestAttempts(cache, rows, capture) {
|
|
|
5066
5563
|
await cacheTransaction(cache, data => {
|
|
5067
5564
|
const observations = cache.context.observedTestIdentities ?? [];
|
|
5068
5565
|
const previous = data.latest_identity;
|
|
5069
|
-
const
|
|
5070
|
-
|
|
5566
|
+
const observedEngines = [...new Set(observations.map(item => item.engine_sha).filter(Boolean))];
|
|
5567
|
+
const observedModels = [...new Set(observations.flatMap(item => item.models).filter(Boolean))];
|
|
5568
|
+
const hasObservedConflict = observedEngines.length > 1 || observedModels.length > 1 || observations.some(item => item.conflict);
|
|
5569
|
+
const identity = {
|
|
5570
|
+
engine_sha: observedEngines.length === 1 ? observedEngines[0] : null,
|
|
5571
|
+
requested_model: observedModels.length === 1 ? observedModels[0] : null,
|
|
5572
|
+
};
|
|
5071
5573
|
const terminalObservations = observations.filter(item => item.terminal);
|
|
5072
|
-
const
|
|
5073
|
-
&& observations.every(item => observedIdentityMatches(item, identity));
|
|
5574
|
+
const identityVerified = !hasObservedConflict && !!identity.engine_sha && !!identity.requested_model && terminalObservations.length > 0;
|
|
5074
5575
|
const marks = previous?.in_progress ?? [];
|
|
5075
5576
|
const ownMark = mark => !!cache.mark && mark.token === cache.mark.token;
|
|
5076
|
-
const
|
|
5077
|
-
const unchanged = cache.identitySnapshot === JSON.stringify(previous ?? null);
|
|
5577
|
+
const liveRemaining = liveInProgressMarks(cache, marks.filter(mark => !ownMark(mark)));
|
|
5078
5578
|
const cohort = previous?.cohort;
|
|
5079
|
-
const
|
|
5080
|
-
|
|
5081
|
-
|
|
5082
|
-
|
|
5083
|
-
|
|
5084
|
-
|
|
5085
|
-
|
|
5086
|
-
|
|
5087
|
-
|
|
5088
|
-
|
|
5089
|
-
|
|
5090
|
-
|
|
5579
|
+
const nowIso = new Date(cache.context.ports.now()).toISOString();
|
|
5580
|
+
if (cache.context.cacheReadInvocation) {
|
|
5581
|
+
if (previous && marks.some(ownMark)) {
|
|
5582
|
+
data.latest_identity = { ...previous, in_progress: liveRemaining, ...(liveRemaining.length && cohort ? { cohort } : {}) };
|
|
5583
|
+
if (!liveRemaining.length) delete data.latest_identity.cohort;
|
|
5584
|
+
}
|
|
5585
|
+
} else if (!observations.length) {
|
|
5586
|
+
// No server response was observed (e.g., local error/interrupt before HTTP settlement).
|
|
5587
|
+
// Retire our in-progress mark without erasing a previously verified identity.
|
|
5588
|
+
if (previous) {
|
|
5589
|
+
const preservedClean = !liveRemaining.length && hasVerifiedIdentityRecord(previous);
|
|
5590
|
+
const next = { ...previous, in_progress: liveRemaining, clean: preservedClean, conflict: !hasVerifiedIdentityRecord(previous), written_at: nowIso, observed_at: nowIso };
|
|
5591
|
+
if (liveRemaining.length && cohort) next.cohort = cohort;
|
|
5592
|
+
else delete next.cohort;
|
|
5593
|
+
data.latest_identity = next;
|
|
5594
|
+
}
|
|
5595
|
+
} else {
|
|
5596
|
+
let cohortConflict = false;
|
|
5597
|
+
if (cohort) {
|
|
5598
|
+
if (!identityVerified) {
|
|
5599
|
+
cohort.valid = false;
|
|
5600
|
+
cohortConflict = true;
|
|
5601
|
+
} else {
|
|
5602
|
+
if ((cohort.engine_sha !== null && cohort.engine_sha !== identity.engine_sha)
|
|
5603
|
+
|| (cohort.requested_model !== null && cohort.requested_model !== identity.requested_model)) {
|
|
5604
|
+
cohort.valid = false;
|
|
5605
|
+
cohortConflict = true;
|
|
5606
|
+
}
|
|
5607
|
+
if (cohort.engine_sha === null) cohort.engine_sha = identity.engine_sha;
|
|
5608
|
+
if (cohort.requested_model === null) cohort.requested_model = identity.requested_model;
|
|
5609
|
+
if (cohort.valid === false) cohortConflict = true;
|
|
5610
|
+
}
|
|
5611
|
+
}
|
|
5612
|
+
const clean = !liveRemaining.length && identityVerified && !cohortConflict;
|
|
5613
|
+
const conflict = hasObservedConflict || cohortConflict || !identityVerified;
|
|
5614
|
+
data.latest_identity = {
|
|
5615
|
+
engine_sha: identity.engine_sha,
|
|
5616
|
+
models: identity.requested_model ? [identity.requested_model] : [],
|
|
5617
|
+
in_progress: liveRemaining,
|
|
5618
|
+
...(liveRemaining.length && cohort ? { cohort } : {}),
|
|
5619
|
+
clean,
|
|
5620
|
+
conflict,
|
|
5621
|
+
sampled_at: new Date(Number.isFinite(cache.context.startedAt) ? cache.context.startedAt : 0).toISOString(),
|
|
5622
|
+
written_at: nowIso,
|
|
5623
|
+
observed_at: nowIso,
|
|
5624
|
+
};
|
|
5625
|
+
}
|
|
5091
5626
|
for (const [story, token] of cache.tokens) {
|
|
5092
5627
|
if (data.epoch !== token.epoch || data.stories[story]?.generation !== token.generation) continue;
|
|
5093
5628
|
const own = rows.filter(row => row.story_path === story && !row.cached), footprint = capture.stories?.find(item => item.story_path === story);
|
|
5094
5629
|
const complete = footprint?.tests.length === own.length && footprint.tests.every(test => own.some(row => row.test === test));
|
|
5095
5630
|
const outcome = own.some(row => row.state === 'failed') ? 'failed' : own.some(row => row.state === 'refused') ? 'refused' : own.some(row => row.state === 'not_run') ? 'not_run' : complete && own.length && own.every(row => row.state === 'passed' && typeof row.calls === 'number' && row.accounting_complete === true) && !cache.context.interrupted && !cache.context.lintUnknown ? 'passed' : 'unknown';
|
|
5096
5631
|
const record = data.stories[story] = { generation: token.generation, outcome: outcome !== 'passed' && data.stories[story]?.outcome === 'failed' ? 'failed' : outcome };
|
|
5097
|
-
const
|
|
5098
|
-
const consistent =
|
|
5099
|
-
&& rows.filter(row => !row.cached && row.cache_identity).every(row => sameCacheIdentity(
|
|
5100
|
-
&& observations.every(observed => observedIdentityMatches(observed,
|
|
5632
|
+
const rowIdentity = own[0]?.cache_identity;
|
|
5633
|
+
const consistent = rowIdentity && own.every(row => sameCacheIdentity(rowIdentity, row.cache_identity))
|
|
5634
|
+
&& rows.filter(row => !row.cached && row.cache_identity).every(row => sameCacheIdentity(rowIdentity, row.cache_identity))
|
|
5635
|
+
&& observations.every(observed => observedIdentityMatches(observed, rowIdentity));
|
|
5101
5636
|
const sampledAt = Math.min(cache.context.startedAt, ...own.map(row => row.cache_sample_at).filter(Number.isFinite));
|
|
5102
5637
|
if (outcome === 'passed' && token.fingerprint && consistent && Number.isFinite(sampledAt)) {
|
|
5103
|
-
|
|
5104
|
-
|
|
5638
|
+
const effectiveCalls = row => Math.max(
|
|
5639
|
+
typeof row.calls === 'number' ? row.calls : 0,
|
|
5640
|
+
Number.isSafeInteger(row.saved_answer_original_calls) && row.saved_answer_original_calls >= 0 ? row.saved_answer_original_calls : 0,
|
|
5641
|
+
);
|
|
5642
|
+
const callsUsed = Math.max(0, ...own.map(effectiveCalls));
|
|
5643
|
+
const maxCallsValues = own.map(row => row.max_calls).filter(value => Number.isSafeInteger(value) && value >= 1);
|
|
5644
|
+
record.pass = {
|
|
5645
|
+
...rowIdentity,
|
|
5646
|
+
fingerprint: identityFingerprint(cache, token.fingerprint, rowIdentity),
|
|
5647
|
+
tests: footprint.tests,
|
|
5648
|
+
passed_at: new Date(sampledAt).toISOString(),
|
|
5649
|
+
calls_used: callsUsed,
|
|
5650
|
+
max_calls: maxCallsValues.length ? Math.max(...maxCallsValues) : null,
|
|
5651
|
+
rows: Object.fromEntries(own.map(row => [row.test, {
|
|
5652
|
+
checks: row.checks,
|
|
5653
|
+
criteria: row.criteria,
|
|
5654
|
+
criteria_total: row.criteria_total,
|
|
5655
|
+
draft: !!row.draft,
|
|
5656
|
+
calls: effectiveCalls(row),
|
|
5657
|
+
...(Number.isSafeInteger(row.max_calls) && row.max_calls >= 1 ? { max_calls: row.max_calls } : {}),
|
|
5658
|
+
}])),
|
|
5659
|
+
};
|
|
5105
5660
|
}
|
|
5106
5661
|
}
|
|
5107
5662
|
});
|
|
@@ -5213,9 +5768,13 @@ async function runBatch(context, cwd, words, options, setRelease) {
|
|
|
5213
5768
|
// only this attempt's mark, leaving its invalidations and other owners intact.
|
|
5214
5769
|
if (cache?.mark) await cacheTransaction(cache, data => {
|
|
5215
5770
|
if (data.latest_identity?.in_progress) {
|
|
5216
|
-
|
|
5217
|
-
|
|
5218
|
-
if (
|
|
5771
|
+
const remaining = liveInProgressMarks(cache, data.latest_identity.in_progress.filter(mark=>mark.token!==cache.mark.token));
|
|
5772
|
+
data.latest_identity.in_progress = remaining;
|
|
5773
|
+
if (!remaining.length) {
|
|
5774
|
+
delete data.latest_identity.cohort;
|
|
5775
|
+
const preserved = hasVerifiedIdentityRecord(data.latest_identity);
|
|
5776
|
+
Object.assign(data.latest_identity, { clean: preserved, conflict: !preserved });
|
|
5777
|
+
}
|
|
5219
5778
|
}
|
|
5220
5779
|
});
|
|
5221
5780
|
if (context.testCache === cache) context.testCache = null;
|
|
@@ -5291,7 +5850,7 @@ async function runBatch(context, cwd, words, options, setRelease) {
|
|
|
5291
5850
|
}
|
|
5292
5851
|
|
|
5293
5852
|
const scopedOwnership = words.length > 0 || affected || selected.length < found.tests.length;
|
|
5294
|
-
context.warnings.push(...found
|
|
5853
|
+
context.warnings.push(...scopedDiscoveryWarnings(found, normalized), ...checked.warnings, ...sharedSourceFiles(root, found.discoveryVisible ?? found.visible, { ...(scopedOwnership ? { tests: selected } : {}), workspace: found.workspace }, ports));
|
|
5295
5854
|
context.unmatched = unmatchedLines(found);
|
|
5296
5855
|
if (cache) await beginTestAttempts(cache, rows.filter(row => row.state !== 'ready'), null, options, origin);
|
|
5297
5856
|
if (!rows.some(row => row.state === 'ready')) { if (rows.some(row => row.native_only?.length)) await saveLocalNativeResult(context, rows, 'check'); return printResult(context, rows); }
|
|
@@ -5325,9 +5884,13 @@ async function runBatch(context, cwd, words, options, setRelease) {
|
|
|
5325
5884
|
catch (error) {
|
|
5326
5885
|
if (cache?.mark) await cacheTransaction(cache, data => {
|
|
5327
5886
|
if (data.latest_identity?.in_progress) {
|
|
5328
|
-
|
|
5329
|
-
|
|
5330
|
-
if (
|
|
5887
|
+
const remaining = liveInProgressMarks(cache, data.latest_identity.in_progress.filter(mark => mark.token !== cache.mark.token));
|
|
5888
|
+
data.latest_identity.in_progress = remaining;
|
|
5889
|
+
if (!remaining.length) {
|
|
5890
|
+
delete data.latest_identity.cohort;
|
|
5891
|
+
const preserved = hasVerifiedIdentityRecord(data.latest_identity);
|
|
5892
|
+
Object.assign(data.latest_identity, { clean: preserved, conflict: !preserved });
|
|
5893
|
+
}
|
|
5331
5894
|
}
|
|
5332
5895
|
});
|
|
5333
5896
|
throw error;
|
|
@@ -5384,13 +5947,21 @@ async function runBatch(context, cwd, words, options, setRelease) {
|
|
|
5384
5947
|
// ---- pdd simulate ----
|
|
5385
5948
|
|
|
5386
5949
|
// The app map for the Screen tab: --app-map, else app-map.json at the root, else app/app-map.json.
|
|
5387
|
-
// An app map is a Git-visible JSON object with
|
|
5950
|
+
// An app map is a Git-visible JSON object with screens and optional compact fields (v1 or v2).
|
|
5388
5951
|
const APP_MAP_VERSION = 'prompt-runtime.app-map.v1';
|
|
5952
|
+
const APP_MAP_VERSIONS = new Set(['prompt-runtime.app-map.v1', 'prompt-runtime.app-map.v2']);
|
|
5389
5953
|
function appMapProblem(root, path) {
|
|
5390
5954
|
let doc;
|
|
5391
5955
|
try { doc = JSON.parse(readFileSync(join(root, path), 'utf8')); } catch { return 'it is not JSON'; }
|
|
5392
|
-
if (!isObject(doc)
|
|
5393
|
-
if (
|
|
5956
|
+
if (!isObject(doc)) return 'it is not a JSON object';
|
|
5957
|
+
if (Object.hasOwn(doc, 'schema_version') && !APP_MAP_VERSIONS.has(doc.schema_version)) return `its schema_version is not "${APP_MAP_VERSION}"`;
|
|
5958
|
+
if (Object.hasOwn(doc, 'name') && (typeof doc.name !== 'string' || !doc.name)) return 'its "name" must be a nonempty string';
|
|
5959
|
+
const hasScreens = Array.isArray(doc.screens) && doc.screens.length > 0;
|
|
5960
|
+
const hasV1Name = doc.schema_version === APP_MAP_VERSION && typeof doc.name === 'string' && doc.name.length > 0;
|
|
5961
|
+
if (!hasScreens && !hasV1Name) {
|
|
5962
|
+
if (doc.schema_version === APP_MAP_VERSION && !Object.hasOwn(doc, 'screens')) return 'it has no "name"';
|
|
5963
|
+
return 'it has no "screens"';
|
|
5964
|
+
}
|
|
5394
5965
|
return null;
|
|
5395
5966
|
}
|
|
5396
5967
|
|
|
@@ -5513,11 +6084,40 @@ function simulationSelection(root, found, words, appMap, options, ports) {
|
|
|
5513
6084
|
}
|
|
5514
6085
|
|
|
5515
6086
|
async function readUntil(context, id, command, isDone, ms, label, acceptAnswer = null) {
|
|
5516
|
-
const end = Math.min(context.deadline ?? Infinity,
|
|
5517
|
-
let last = null;
|
|
6087
|
+
const startedAt = context.ports.now(), end = Math.min(context.deadline ?? Infinity, startedAt + ms), tick = progressTicker(context.ports.stderr, context.ports.now);
|
|
6088
|
+
let last = null, serverSupportsSse = false;
|
|
5518
6089
|
for (;;) {
|
|
5519
6090
|
if (context.interrupted || context.ports.now() >= end) return { answer: last, open: true };
|
|
5520
|
-
const
|
|
6091
|
+
const remainingMs = Math.max(1, end - context.ports.now());
|
|
6092
|
+
let read;
|
|
6093
|
+
if (!context.ports.pollMsExplicit) {
|
|
6094
|
+
let streamUnknownWhy = null;
|
|
6095
|
+
const streamReply = await context.runtime.streamRun(id, {
|
|
6096
|
+
useEventsPath: serverSupportsSse,
|
|
6097
|
+
timeoutMs: remainingMs,
|
|
6098
|
+
onEvent: ({ event, json }) => {
|
|
6099
|
+
if (!isObject(json) || !sameJob(json, id, command)) return false;
|
|
6100
|
+
if (acceptAnswer && !acceptAnswer(json)) { streamUnknownWhy = 'The receipt could not be verified.'; return true; }
|
|
6101
|
+
last = json;
|
|
6102
|
+
queueProgress(context, last);
|
|
6103
|
+
context.store.write(join(context.store.folder('tries'), `${id}.json`), last);
|
|
6104
|
+
if (isDone(last)) return true;
|
|
6105
|
+
if (label && event === 'progress') tick(`${label}: ${waitWord(last, null)}`);
|
|
6106
|
+
return false;
|
|
6107
|
+
},
|
|
6108
|
+
});
|
|
6109
|
+
if (streamReply.streamed) {
|
|
6110
|
+
serverSupportsSse = true;
|
|
6111
|
+
if (streamUnknownWhy) return { unknownWhy: streamUnknownWhy };
|
|
6112
|
+
if (last && isDone(last)) return { answer: last };
|
|
6113
|
+
if (context.interrupted || context.ports.now() >= end) return { answer: last, open: true };
|
|
6114
|
+
await context.ports.sleep(context.ports.pollDelay(context.ports.now() - startedAt), context.signal);
|
|
6115
|
+
continue;
|
|
6116
|
+
}
|
|
6117
|
+
read = judgeGet(streamReply, id, command);
|
|
6118
|
+
} else {
|
|
6119
|
+
read = judgeGet(await context.runtime.get(id, Math.max(1, Math.min(GET_MS, remainingMs))), id, command);
|
|
6120
|
+
}
|
|
5521
6121
|
if (read.kind === 'state' && acceptAnswer && !acceptAnswer(read.answer)) return { unknownWhy: 'The receipt could not be verified.' };
|
|
5522
6122
|
if (read.kind === 'state') { last = read.answer; queueProgress(context, last); context.store.write(join(context.store.folder('tries'), `${id}.json`), last); if (isDone(last)) return { answer: last }; }
|
|
5523
6123
|
else if (read.kind === 'unknown') return { unknownWhy: read.why };
|
|
@@ -5525,7 +6125,8 @@ async function readUntil(context, id, command, isDone, ms, label, acceptAnswer =
|
|
|
5525
6125
|
else if (read.kind === 'blocked') throw new Stop(5, read.message);
|
|
5526
6126
|
if (label) tick(`${label}: ${waitWord(last, read)}`);
|
|
5527
6127
|
if (context.interrupted || context.ports.now() >= end) return { answer: last, open: true };
|
|
5528
|
-
|
|
6128
|
+
const delay = context.ports.pollDelay(context.ports.now() - startedAt);
|
|
6129
|
+
await context.ports.sleep(Math.min(delay, Math.max(0, end - context.ports.now())), context.signal);
|
|
5529
6130
|
}
|
|
5530
6131
|
}
|
|
5531
6132
|
|
|
@@ -5798,9 +6399,9 @@ function programSelection(cwd, word, ports, givenMap) {
|
|
|
5798
6399
|
let map;
|
|
5799
6400
|
try { map = JSON.parse(sourceFilePort(root, visible).read({ path }).content); }
|
|
5800
6401
|
catch (error) { if (error instanceof RuntimeWorkspaceError) throw error; throw new Stop(2, 'Select a readable app map containing valid JSON.'); }
|
|
5801
|
-
if (!isObject(map) || map
|
|
5802
|
-
if (explicit && (typeof map.name !== 'string' || !map.name)) throw new Stop(2, 'The selected app map has
|
|
5803
|
-
const initial = map.screens.find(screen => screen.id === map.initial_screen), first = initial?.source === 'operation' ? initial : map.screens.find(screen => screen.source === 'operation');
|
|
6402
|
+
if (!isObject(map) || (Object.hasOwn(map, 'schema_version') && !APP_MAP_VERSIONS.has(map.schema_version)) || !Array.isArray(map.screens) || !map.screens.length) throw new Stop(2, 'Select a valid app map with executable screens.');
|
|
6403
|
+
if (explicit && Object.hasOwn(map, 'name') && (typeof map.name !== 'string' || !map.name)) throw new Stop(2, 'The selected app map has an invalid name. See RUNBOOK.md §13.');
|
|
6404
|
+
const initial = map.screens.find(screen => screen.id === (map.initial_screen ?? map.screens[0]?.id)), first = (initial?.source ?? 'operation') === 'operation' ? initial : map.screens.find(screen => (screen.source ?? 'operation') === 'operation');
|
|
5804
6405
|
if (!first || typeof first.prompt_path !== 'string' || !first.prompt_path.endsWith('.prompt.md') || !visible.has(first.prompt_path)) throw new Stop(2, 'This app map has no executable prompt.');
|
|
5805
6406
|
return first.prompt_path;
|
|
5806
6407
|
};
|
|
@@ -5879,6 +6480,7 @@ async function runProgramTry({ cwd, word, options, context, requestedBudget }) {
|
|
|
5879
6480
|
if (!await admission(context, 'try', setup)) throw new Stop(5, 'The program setup wait ended before sending.');
|
|
5880
6481
|
const request = { requestId: ports.randomUUID(), source_sha256: capture.sha256, entry,
|
|
5881
6482
|
initial_world: seeded?.initial_world ?? (options['--fresh'] ? {} : files.read()), ...(seeded?.simulation ? { simulation: seeded.simulation } : {}),
|
|
6483
|
+
...(options['--fresh'] === true ? { fresh: true } : {}),
|
|
5882
6484
|
...(appMap ? { app_map: appMap } : {}), tab: selected.screen ? 'screen' : 'call', max_calls: requestedBudget ?? 300, ...sourceProvenance(context, capture) };
|
|
5883
6485
|
setup.request_ids.push(request.requestId);
|
|
5884
6486
|
if (await recordRuntimeRequest(setup.reservation, request.requestId, slotPorts(context)) === false || context.interrupted) throw new Stop(3, 'Stopped before sending the program.');
|
|
@@ -6220,7 +6822,7 @@ async function runDirectProgram({words,options,cwd}, ports) {
|
|
|
6220
6822
|
if (row.state !== 'ready') throw Object.assign(new Stop(125,row.refusals?.map(item=>item.message||item.code).join('; ')||'The interpreter refused this program.'),{fix:row.raw_refusals?.find(item=>item.fix)?.fix});
|
|
6221
6823
|
const setup = {request_ids:[],reservation:null};
|
|
6222
6824
|
if (!await admission(context,'try',setup)) throw new Stop(125,'The interpreter could not admit this program.');
|
|
6223
|
-
const lazyInterfaces=context
|
|
6825
|
+
const lazyInterfaces=shouldSendLazyInterfaces(context);
|
|
6224
6826
|
const id=ports.randomUUID(), request={requestId:id,source_sha256:context.capture.sha256,seed:test.path,max_calls:400,tab:'terminal',...(lazyInterfaces?{lazy_interfaces:true}:{})};
|
|
6225
6827
|
await recordRuntimeRequest(setup.reservation,id,slotPorts(context));
|
|
6226
6828
|
descriptor={version:1,directProgram:true,root,prompt:promptPath,operation,login:identity.login,origin,sessionId:id,sourceHash,setupPending:true,
|
|
@@ -6251,7 +6853,7 @@ async function runDirectProgram({words,options,cwd}, ports) {
|
|
|
6251
6853
|
const inputProblems=checkInput(input,selected.entry.input_schema,0).refusals;
|
|
6252
6854
|
if(inputProblems.length)throw new Stop(125,inputProblems.map(problem=>problem.message).join('; '));
|
|
6253
6855
|
descriptor={...descriptor,operation:selected.entry.operation,inputSchema:selected.entry.input_schema,draft:context.draft,
|
|
6254
|
-
lazyInterfaces:context.serverFeatures
|
|
6856
|
+
lazyInterfaces:context.serverFeatures||context.allowMissingInterfaces?shouldSendLazyInterfaces(context):descriptor.lazyInterfaces===true};
|
|
6255
6857
|
directPrivate(descriptorPath,descriptor);
|
|
6256
6858
|
if (context.interrupted) throw new Stop(130,'Stopped before the command was sent.');
|
|
6257
6859
|
return await doors.openCli({root,visible,ports:{...ports,signal:context.signal},store,identity,origin,runtime:context.runtime,
|
|
@@ -6454,7 +7056,8 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
|
|
|
6454
7056
|
const identity = signIn(ports.gh, store, ports);
|
|
6455
7057
|
return await (await import('./try-doors.mjs')).saveLast({ root, store, identity, ports, test });
|
|
6456
7058
|
}
|
|
6457
|
-
if (options['--
|
|
7059
|
+
if (options['--fresh'] !== undefined && options['--fresh'] !== true) throw new Stop(2, '--fresh takes no value.');
|
|
7060
|
+
if (options['--stop'] && (options['--tab'] || options['--new'] || options['--fresh'] || options['--no-open'] || options['--no-wait'] || options['--app-map'] !== undefined || productMode || requestedBudget !== null)) throw new Stop(2, 'pdd simulate --stop takes only a STORY. Run pdd simulate --help.');
|
|
6458
7061
|
if (words.length > 1) throw new Stop(2, 'pdd simulate takes one STORY.');
|
|
6459
7062
|
const origin = runtimeOrigin(ports.env);
|
|
6460
7063
|
if (options['--stop']) return await stopByName(context, cwd, words, origin);
|
|
@@ -6632,7 +7235,8 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
|
|
|
6632
7235
|
for (;;) {
|
|
6633
7236
|
if (!await admission(context, 'try', setup)) throw new Stop(context.interrupted ? 3 : 5, context.interrupted ? 'Stopped before sending.' : 'The interpreter stayed busy until the Try setup wait ended. No new Try was sent.');
|
|
6634
7237
|
request = { requestId: ports.randomUUID(), source_sha256: capture.sha256, seed: test.path, max_calls: requestedBudget ?? 400, ...(appMap ? { app_map: appMap } : {}), ...(prepared ? {product_parts:prepared.composition.product_parts} : {}),
|
|
6635
|
-
...(
|
|
7238
|
+
...(options['--fresh'] === true ? { fresh: true } : {}),
|
|
7239
|
+
...(shouldSendLazyInterfaces(context) ? { lazy_interfaces: true } : {}),
|
|
6636
7240
|
...sourceProvenance(context, capture),
|
|
6637
7241
|
tab };
|
|
6638
7242
|
let localBridge;
|
|
@@ -7581,8 +8185,9 @@ async function executeDoorCall(descriptor, input, givenPorts = {}, execution = {
|
|
|
7581
8185
|
const runtime = new Runtime({ origin, token: identity.token, ports, signal: ports.signal, auth, programJson: Boolean(descriptor.programEntry) });
|
|
7582
8186
|
try {
|
|
7583
8187
|
descriptor.beforeProgramDispatch?.(id);
|
|
8188
|
+
const callWaitSeconds = Math.min(WAIT_PREFER_CALL_SECONDS, Math.max(0, Math.floor((ports.postMs - 5_000) / 1000)));
|
|
7584
8189
|
const reply = descriptor.directProgram && descriptor.recoverRequestId ? { status: 202 } : await runtime.send(`/v1/try/${sessionId}/call`, { method: 'POST',
|
|
7585
|
-
headers: { 'Content-Type': 'application/json' }, body: runBody }, ports.postMs);
|
|
8190
|
+
headers: preferWaitHeaders(callWaitSeconds, { 'Content-Type': 'application/json' }), body: runBody }, ports.postMs);
|
|
7586
8191
|
if (reply.status && ![200, 202].includes(reply.status)) {
|
|
7587
8192
|
knownOutcome = isPreExecutionRefusal(reply);
|
|
7588
8193
|
preExecutionRefusal = knownOutcome;
|
|
@@ -7597,8 +8202,9 @@ async function executeDoorCall(descriptor, input, givenPorts = {}, execution = {
|
|
|
7597
8202
|
&& (!Object.hasOwn(reply.json, 'session_id') || reply.json.session_id === sessionId)
|
|
7598
8203
|
&& (!Object.hasOwn(reply.json.result?.session ?? {}, 'id') || reply.json.result.session.id === sessionId);
|
|
7599
8204
|
if ([200, 202].includes(reply.status) && reply.json && !pendingExistingCall && !programReceiptMatches(reply.json, id, 'call', sessionId)) throw new Stop(125, 'The interpreter returned a different command.' + recovery);
|
|
7600
|
-
const
|
|
7601
|
-
let answer = null;
|
|
8205
|
+
const pollStartedAt = ports.now(), end = pollStartedAt + 900_000;
|
|
8206
|
+
let answer = reply.status === 200 && reply.json && ENDED.has(reply.json.state) ? reply.json : null;
|
|
8207
|
+
let serverSupportsSse = false;
|
|
7602
8208
|
for (;;) {
|
|
7603
8209
|
if (ports.signal?.aborted) throw new Stop(125, 'The local server stopped; this command result is unknown. Do not repeat it automatically.' + recovery);
|
|
7604
8210
|
if (answer && !programReceiptMatches(answer, id, 'call', sessionId)) throw new Stop(125, 'The interpreter returned a different command.' + recovery);
|
|
@@ -7631,7 +8237,9 @@ async function executeDoorCall(descriptor, input, givenPorts = {}, execution = {
|
|
|
7631
8237
|
throw Object.assign(new Stop(125, cleanText(why?.engine_message || why?.message || why?.code || 'The command result is unknown. Do not repeat it automatically.', secrets) + (['failed', 'refused'].includes(answer.state) ? '' : recovery)), { tryUsage: usage,fix:why?.fix });
|
|
7632
8238
|
}
|
|
7633
8239
|
knownOutcome = true;
|
|
7634
|
-
const
|
|
8240
|
+
const hasEmbeddedWorld = Object.hasOwn(answer.result ?? {}, 'world');
|
|
8241
|
+
const hasEmbeddedInputWorld = Object.hasOwn(answer.result ?? {}, 'input_world') || Object.hasOwn(rawReport ?? {}, 'input_world');
|
|
8242
|
+
const observation = !(hasEmbeddedWorld && hasEmbeddedInputWorld) && (typeof projected.action_id === 'string' || descriptor.directProgram)
|
|
7635
8243
|
? await doorWorldObservation(runtime,sessionId,rawReport,projected.action_id) : rawReport ?? {};
|
|
7636
8244
|
const confirmed = {
|
|
7637
8245
|
id,
|
|
@@ -7641,8 +8249,8 @@ async function executeDoorCall(descriptor, input, givenPorts = {}, execution = {
|
|
|
7641
8249
|
error: projected.outcome === 'program_error' ? reportError : null,
|
|
7642
8250
|
usage,
|
|
7643
8251
|
callChain: rawReport?.call_chain,
|
|
7644
|
-
inputWorld: observation.input_world,
|
|
7645
|
-
world:
|
|
8252
|
+
inputWorld: Object.hasOwn(answer.result ?? {}, 'input_world') ? answer.result.input_world : observation.input_world,
|
|
8253
|
+
world: hasEmbeddedWorld ? answer.result.world : observation.world,
|
|
7646
8254
|
};
|
|
7647
8255
|
if (sourcePins && projected.outcome === 'result') await store.updateLastRun(root, current => current?.id !== id ? undefined : ({state:'confirmed',
|
|
7648
8256
|
descriptor:{root,sessionId,origin,login,prompt,operation,...sourcePins},
|
|
@@ -7668,7 +8276,33 @@ async function executeDoorCall(descriptor, input, givenPorts = {}, execution = {
|
|
|
7668
8276
|
if (!answer || !ENDED.has(answer.state)) throw new Stop(125, 'The command result is unknown. Do not repeat it automatically.' + recovery);
|
|
7669
8277
|
continue;
|
|
7670
8278
|
}
|
|
7671
|
-
await ports.sleep(ports.
|
|
8279
|
+
await ports.sleep(ports.pollDelay(ports.now() - pollStartedAt), ports.signal);
|
|
8280
|
+
continue;
|
|
8281
|
+
}
|
|
8282
|
+
if (!ports.pollMsExplicit) {
|
|
8283
|
+
let streamedDone = null;
|
|
8284
|
+
const streamReply = await runtime.streamRun(id, {
|
|
8285
|
+
useEventsPath: serverSupportsSse,
|
|
8286
|
+
timeoutMs: Math.max(1, end - ports.now()),
|
|
8287
|
+
onEvent: ({ event, json }) => {
|
|
8288
|
+
if (isObject(json) && (event === 'done' || ENDED.has(json.state))) {
|
|
8289
|
+
streamedDone = json;
|
|
8290
|
+
return true;
|
|
8291
|
+
}
|
|
8292
|
+
return false;
|
|
8293
|
+
},
|
|
8294
|
+
});
|
|
8295
|
+
if (streamReply.streamed) {
|
|
8296
|
+
serverSupportsSse = true;
|
|
8297
|
+
if (streamedDone) { answer = streamedDone; continue; }
|
|
8298
|
+
if (ports.signal?.aborted) throw new Stop(125, 'The local server stopped; this command result is unknown. Do not repeat it automatically.' + recovery);
|
|
8299
|
+
await ports.sleep(ports.pollDelay(ports.now() - pollStartedAt), ports.signal);
|
|
8300
|
+
continue;
|
|
8301
|
+
}
|
|
8302
|
+
if ([401, 403, 410].includes(streamReply.status)) throw new Stop(125, cleanText(streamReply.json?.error?.message || (streamReply.status === 401 ? AUTH_TEXT : 'The command could not be read. Do not repeat it automatically.'), secrets) + recovery);
|
|
8303
|
+
answer = [200, 202].includes(streamReply.status) ? streamReply.json : null;
|
|
8304
|
+
if (answer && ENDED.has(answer.state)) continue;
|
|
8305
|
+
await ports.sleep(ports.pollDelay(ports.now() - pollStartedAt), ports.signal);
|
|
7672
8306
|
continue;
|
|
7673
8307
|
}
|
|
7674
8308
|
await ports.sleep(ports.pollMs, ports.signal);
|
|
@@ -7761,6 +8395,33 @@ export async function observeTryCall({ cwd = process.cwd(), story, tryId, runId
|
|
|
7761
8395
|
});
|
|
7762
8396
|
}
|
|
7763
8397
|
|
|
8398
|
+
export async function reconcileCheckReceipt({ cwd = process.cwd(), requestId, origin: explicitOrigin } = {}, givenPorts = {}) {
|
|
8399
|
+
const targetRequestId = String(requestId ?? '');
|
|
8400
|
+
if (!UUID.test(targetRequestId)) {
|
|
8401
|
+
throw Object.assign(new Error(`Invalid CHECK request UUID "${cleanText(targetRequestId)}". Pass the original external request UUID.`), { code: 'invalid-request-id' });
|
|
8402
|
+
}
|
|
8403
|
+
const ports = withDefaults(givenPorts);
|
|
8404
|
+
let store;
|
|
8405
|
+
try {
|
|
8406
|
+
const root = repoRoot(cwd);
|
|
8407
|
+
store = stateFor(ports.env, root);
|
|
8408
|
+
} catch (error) {
|
|
8409
|
+
if (error instanceof Stop && error.exitCode === 2 && error.message.includes('PDD_STATE_DIR')) throw error;
|
|
8410
|
+
store = new StateStore(resolve(ports.env.PDD_STATE_DIR || join(ports.env.HOME || homedir(), '.pdd', 'runtime')));
|
|
8411
|
+
}
|
|
8412
|
+
const origin = runtimeOrigin(explicitOrigin ? { PDD_RUNTIME_URL: explicitOrigin } : ports.env);
|
|
8413
|
+
const identity = signIn(ports.gh, store, ports);
|
|
8414
|
+
const secrets = [identity.token];
|
|
8415
|
+
const auth = authSession({ identity, store, ports, secrets });
|
|
8416
|
+
const runtime = new Runtime({ origin, token: identity.token, ports, signal: ports.signal, auth });
|
|
8417
|
+
const reply = await runtime.send(`/v1/runs/${encodeURIComponent(targetRequestId)}/reconciliation`, { method: 'GET' }, GET_MS);
|
|
8418
|
+
return projectCheckReconciliation({
|
|
8419
|
+
request_id: targetRequestId,
|
|
8420
|
+
status: reply.status ?? 0,
|
|
8421
|
+
body: reply.json,
|
|
8422
|
+
});
|
|
8423
|
+
}
|
|
8424
|
+
|
|
7764
8425
|
export async function readTryOwner({ cwd = process.cwd(), story, tryId } = {}, givenPorts = {}) {
|
|
7765
8426
|
const ports = withDefaults(givenPorts), root = repoRoot(cwd), found = ports.findTests({ root }), store = stateFor(ports.env, root);
|
|
7766
8427
|
const repo = store.repo(root);
|