@promptdriven/runtime-client 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +7 -0
- package/README.md +42 -2
- package/package.json +28 -4
- package/src/index.mjs +1 -0
- package/src/runtime/agent-ask.mjs +187 -0
- package/src/runtime/agent-chat.mjs +152 -0
- package/src/runtime/agent-coverage.mjs +97 -0
- package/src/runtime/agent-guide.mjs +152 -0
- package/src/runtime/agent-judge.mjs +71 -0
- package/src/runtime/agent-packet.mjs +62 -0
- package/src/runtime/agent-project.mjs +93 -0
- package/src/runtime/contract-refs.mjs +519 -0
- package/src/runtime/contracts.mjs +138 -0
- package/src/runtime/index.mjs +974 -0
- package/src/runtime/lint-call-preflight.mjs +19 -0
- package/src/runtime/lint-compatibility-display.mjs +62 -0
- package/src/runtime/live-local-bridge.mjs +178 -0
- package/src/runtime/live-local.mjs +181 -0
- package/src/runtime/product-composition.mjs +384 -0
- package/src/runtime/run-program.mjs +797 -0
- package/src/runtime/runtime-binding-plan.mjs +145 -0
- package/src/runtime/runtime-bindings.mjs +81 -0
- package/src/runtime/runtime-check-plan.mjs +411 -0
- package/src/runtime/runtime-client.mjs +8114 -0
- package/src/runtime/runtime-lint-receipt.mjs +25 -0
- package/src/runtime/runtime-markdown.mjs +215 -0
- package/src/runtime/runtime-outcome.mjs +468 -0
- package/src/runtime/runtime-output.mjs +752 -0
- package/src/runtime/runtime-preflight.mjs +3832 -0
- package/src/runtime/runtime-slots.mjs +462 -0
- package/src/runtime/runtime-workspace-migration.mjs +70 -0
- package/src/runtime/runtime-workspace.mjs +52 -0
- package/src/runtime/scenario-json.mjs +257 -0
- package/src/runtime/secret-redaction.mjs +54 -0
- package/src/runtime/try-doors.mjs +597 -0
- package/src/runtime/try-http.mjs +285 -0
- package/src/runtime/try-mcp.mjs +223 -0
- package/src/runtime/try-session.mjs +95 -0
- package/src/runtime/try-update-policy.mjs +43 -0
|
@@ -0,0 +1,797 @@
|
|
|
1
|
+
// Generated from prompts/cli/run-program.prompt.md (sha256: 5c39429d25d202d2c26262ef68f8482cd3f1002e0cfe3de7a61fe6d6710feac2).
|
|
2
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
import { closeSync, constants, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
|
|
6
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
7
|
+
import { isatty } from 'node:tty';
|
|
8
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
9
|
+
import { captureSource, gitFiles, interfaceBlocks, sourceFilePort, findTests } from './runtime-preflight.mjs';
|
|
10
|
+
import { createProgramContext, admitProgram, runDoorCall, withRepositoryRunLock, saveDoorCaseResult, acquireCaseWriteOwnership } from './runtime-client.mjs';
|
|
11
|
+
import { openServe } from './try-http.mjs';
|
|
12
|
+
import { projectTryCall } from './try-session.mjs';
|
|
13
|
+
|
|
14
|
+
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
15
|
+
const digest = value => createHash('sha256').update(value).digest('hex');
|
|
16
|
+
const quote = word => `'${String(word).replaceAll("'", "'\\''")}'`;
|
|
17
|
+
const failure = (message, exitCode = 2) => Object.assign(new Error(message), { exitCode });
|
|
18
|
+
function regular(path) {
|
|
19
|
+
const stat = lstatSync(path);
|
|
20
|
+
if (realpathSync(dirname(path)) !== dirname(path)) throw failure('Refusing a linked run directory.');
|
|
21
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) throw failure(`Refusing unsafe run file ${basename(path)}.`);
|
|
22
|
+
return stat;
|
|
23
|
+
}
|
|
24
|
+
function privateFolder(root, parts) {
|
|
25
|
+
let path = root;
|
|
26
|
+
for (const part of parts) {
|
|
27
|
+
path = join(path, part);
|
|
28
|
+
try { mkdirSync(path, { mode: 0o700 }); } catch (e) { if (e.code !== 'EEXIST') throw e; }
|
|
29
|
+
const stat = lstatSync(path);
|
|
30
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw failure('Run data must use real private directories.');
|
|
31
|
+
}
|
|
32
|
+
return path;
|
|
33
|
+
}
|
|
34
|
+
function readPrivate(path, fallback = null) {
|
|
35
|
+
try {
|
|
36
|
+
const before = regular(path), fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
37
|
+
try { const stat = fstatSync(fd); if (stat.ino !== before.ino || stat.dev !== before.dev || stat.size > 10_485_760) throw failure('Run file changed or is too large.'); return JSON.parse(readFileSync(fd, 'utf8')); } finally { closeSync(fd); }
|
|
38
|
+
} catch (e) { if (e.code === 'ENOENT') return fallback; throw e; }
|
|
39
|
+
}
|
|
40
|
+
function writePrivate(path, value) {
|
|
41
|
+
if (realpathSync(dirname(path)) !== dirname(path)) throw failure('Refusing a linked run directory.');
|
|
42
|
+
if (existsSync(path)) regular(path);
|
|
43
|
+
const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
44
|
+
const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
45
|
+
try { writeFileSync(fd, `${JSON.stringify(value, null, 2)}\n`); fsyncSync(fd); } finally { closeSync(fd); }
|
|
46
|
+
try { if (existsSync(path)) regular(path); renameSync(temporary, path); const directory = openSync(dirname(path), constants.O_RDONLY | constants.O_DIRECTORY); try { fsyncSync(directory); } finally { closeSync(directory); } } finally { try { unlinkSync(temporary); } catch {} }
|
|
47
|
+
}
|
|
48
|
+
function localRoot(cwd) {
|
|
49
|
+
const git = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8' });
|
|
50
|
+
if (git.status !== 0) throw failure('Run a prompt program inside its Git repository.');
|
|
51
|
+
return realpathSync(git.stdout.trim());
|
|
52
|
+
}
|
|
53
|
+
function localPath(root, cwd, path) {
|
|
54
|
+
if (typeof path !== 'string' || !path) throw failure('Choose a prompt file or app-map.json.');
|
|
55
|
+
const normalized = relative(root, resolve(cwd, path)).split(sep).join('/');
|
|
56
|
+
if (!normalized || normalized === '..' || normalized.startsWith('../')) throw failure('Program inputs must remain inside this repository.');
|
|
57
|
+
return normalized;
|
|
58
|
+
}
|
|
59
|
+
function excludeRuns(root) {
|
|
60
|
+
const git = spawnSync('git', ['rev-parse', '--git-path', 'info/exclude'], { cwd: root, encoding: 'utf8' });
|
|
61
|
+
if (git.status !== 0) throw failure('Could not locate the local Git exclude file.');
|
|
62
|
+
const path = resolve(root, git.stdout.trim());
|
|
63
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
64
|
+
if (realpathSync(dirname(path)) !== dirname(path)) throw failure('Refusing a linked Git exclude folder.');
|
|
65
|
+
if (existsSync(path)) regular(path);
|
|
66
|
+
const text = existsSync(path) ? readFileSync(path, 'utf8') : '';
|
|
67
|
+
if (!text.split('\n').includes('/.pdd/run/')) writeFileSync(path, `${text}${text && !text.endsWith('\n') ? '\n' : ''}/.pdd/run/\n`);
|
|
68
|
+
}
|
|
69
|
+
function checkedOptions(options) {
|
|
70
|
+
const allowed = new Set(['--data', '--fresh', '--show-data', '--serve', '--max-calls', '-q', '--no-open', '--read', '--save-last']);
|
|
71
|
+
if (!object(options)) throw failure('Program options must be an object.');
|
|
72
|
+
for (const [key, value] of Object.entries(options)) {
|
|
73
|
+
if (!allowed.has(key)) throw failure(`Unknown PDD option ${key}.`);
|
|
74
|
+
if (['--fresh', '--show-data', '-q', '--no-open'].includes(key) && typeof value !== 'boolean') throw failure(`${key} must be Boolean.`);
|
|
75
|
+
if (['--data', '--read', '--save-last'].includes(key) && (typeof value !== 'string' || !value.trim())) throw failure(`${key} requires a value.`);
|
|
76
|
+
if (key === '--max-calls' && (!Number.isInteger(value) || value < 1 || value > 1000)) throw failure('--max-calls must be an integer from 1 to 1000.');
|
|
77
|
+
if (key === '--serve' && value !== true && (!Number.isInteger(value) || value < 0 || value > 65535)) throw failure('--serve requires a port from 0 to 65535.');
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function promptInterface(text) {
|
|
81
|
+
const blocks = interfaceBlocks(text);
|
|
82
|
+
if (!blocks.length) return null;
|
|
83
|
+
if (blocks.length !== 1) throw failure('The entry needs one valid Runtime interface.');
|
|
84
|
+
try { return JSON.parse(blocks[0][1]); } catch { throw failure('The entry Runtime interface must be valid JSON.'); }
|
|
85
|
+
}
|
|
86
|
+
function appEntry(map) {
|
|
87
|
+
const screen = map?.screens?.find(row => row?.source === 'operation' && typeof row.prompt_path === 'string');
|
|
88
|
+
if (screen) return screen.prompt_path;
|
|
89
|
+
const paths = [];
|
|
90
|
+
const visit = (node, inHandlers = false) => {
|
|
91
|
+
if (Array.isArray(node)) for (const value of node) visit(value, inHandlers);
|
|
92
|
+
else if (object(node)) for (const [key, value] of Object.entries(node)) {
|
|
93
|
+
if (key === 'prompt_path' && inHandlers && typeof value === 'string') paths.push(value);
|
|
94
|
+
else visit(value, inHandlers || key === 'actions' || key === 'handlers');
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
visit(map);
|
|
98
|
+
if (paths.length) return paths.sort()[0];
|
|
99
|
+
throw failure('Add an operation screen or handler with a prompt_path to this app map.');
|
|
100
|
+
}
|
|
101
|
+
async function stdinText(stdin) {
|
|
102
|
+
const parts = []; let size = 0;
|
|
103
|
+
for await (const part of stdin) { const bytes = Buffer.from(part); size += bytes.length; if (size > 1_048_576) throw failure('Piped input exceeds 1 MiB.'); parts.push(bytes); }
|
|
104
|
+
try { return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(parts)); } catch { throw failure('Piped input must be UTF-8.'); }
|
|
105
|
+
}
|
|
106
|
+
function outputAnswer(answer, door, ports) {
|
|
107
|
+
if (answer.error) {
|
|
108
|
+
ports.stderr.write('Traceback (prompt calls, most recent last):\n');
|
|
109
|
+
for (const frame of answer.callChain ?? []) ports.stderr.write(` ${frame.prompt} ${frame.operation} (call ${frame.call_index}/${frame.max_calls})\n`);
|
|
110
|
+
ports.stderr.write(`${answer.error.code}: ${answer.error.message ?? ''}\n`);
|
|
111
|
+
return 1;
|
|
112
|
+
}
|
|
113
|
+
if (door === 'cli' || door === 'shell') {
|
|
114
|
+
const result = answer.result;
|
|
115
|
+
if (!object(result) || typeof result.stdout !== 'string' || typeof result.stderr !== 'string' || !Number.isInteger(result.exit_code) || result.exit_code < 0 || result.exit_code > 255 || result.exit_code === 125) throw failure('The CLI result needs stdout, stderr and exit_code 0..255 except 125.', 125);
|
|
116
|
+
ports.stdout.write(result.stdout); ports.stderr.write(result.stderr); ports.summaryBreak = Boolean(result.stderr && !result.stderr.endsWith('\n')); return result.exit_code;
|
|
117
|
+
}
|
|
118
|
+
ports.stdout.write(`${JSON.stringify(answer.result, null, ports.stdout.isTTY ? 2 : undefined)}\n`);
|
|
119
|
+
return 0;
|
|
120
|
+
}
|
|
121
|
+
async function terminalAnswer(ports, question) {
|
|
122
|
+
ports.stderr.write(question);
|
|
123
|
+
const { createInterface } = await import('node:readline');
|
|
124
|
+
const reader = createInterface({ input: process.stdin, output: process.stderr });
|
|
125
|
+
try { return await new Promise(done => reader.question('', done)); } finally { reader.close(); }
|
|
126
|
+
}
|
|
127
|
+
function checkSessionOwner(session, context) {
|
|
128
|
+
if (session?.id && (session.login !== context.identity.login || session.origin !== context.origin)) throw failure('This program session belongs to another Runtime owner or origin.', 125);
|
|
129
|
+
}
|
|
130
|
+
function receiptIdentity(job, id, command, sessionId) {
|
|
131
|
+
return job?.id === id && job.requestId === id && job.command === command
|
|
132
|
+
&& (!Object.hasOwn(job, 'session_id') || job.session_id === sessionId)
|
|
133
|
+
&& (!Object.hasOwn(job.result?.session ?? {}, 'id') || job.result.session.id === sessionId);
|
|
134
|
+
}
|
|
135
|
+
function checkRunOwner(last, session, context) {
|
|
136
|
+
let owner;
|
|
137
|
+
try {
|
|
138
|
+
if (/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(last.id)) owner = readPrivate(join(context.store.dir, 'calls', `${last.id}.meta.json`));
|
|
139
|
+
} catch { throw failure('The saved run owner identity is unavailable.', 125); }
|
|
140
|
+
if (owner?.id === last.id && owner.root === context.root && typeof owner.session_id === 'string' && owner.session_id && owner.session_id === last.sessionId) {
|
|
141
|
+
checkSessionOwner({ id: owner.session_id, login: owner.login, origin: owner.origin }, context);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (!session?.id || last.sessionId !== session.id) throw failure('The saved run session identity is unavailable or superseded.', 125);
|
|
145
|
+
checkSessionOwner(session, context);
|
|
146
|
+
}
|
|
147
|
+
async function saveProgramCase(context, folder, story, ports, discoveryPorts) {
|
|
148
|
+
const lastPath = join(folder, 'last.json'), sessionPath = join(folder, 'session.json'), { root, store } = context;
|
|
149
|
+
const locked = action => withRepositoryRunLock(root, store, action);
|
|
150
|
+
const snapshot = locked(() => ({ last: readPrivate(lastPath), session: readPrivate(sessionPath), selected: store.repo(root).last_run }));
|
|
151
|
+
checkSessionOwner(snapshot.session, context);
|
|
152
|
+
const last = snapshot.last;
|
|
153
|
+
const latestId = selected => selected?.run_id ?? selected?.id ?? '';
|
|
154
|
+
if (!last || !snapshot.session?.id || last.sessionId !== snapshot.session.id || !planProgramCase({ state: last.state, expected_run_id: last.id ?? '', current_run_id: latestId(snapshot.selected), terminal: true, answer: 'y' }).write) throw failure('The last run is unconfirmed or superseded; read its saved run ID first.', 125);
|
|
155
|
+
if (last.saved) { ports.stdout.write('The last run is already saved.\n'); return 0; }
|
|
156
|
+
const requireSource = () => {
|
|
157
|
+
let current;
|
|
158
|
+
try { current = context.ports.captureSource(root, { tests: [context.programEntry], appMap: context.appMap }); }
|
|
159
|
+
catch { throw failure('The reached prompt source changed or could not be confirmed. Run the program again before saving its answer.', 125); }
|
|
160
|
+
if (last.source !== current?.sha256) throw failure('The reached prompt source changed since this result. Run the program again before saving its answer.', 125);
|
|
161
|
+
};
|
|
162
|
+
requireSource();
|
|
163
|
+
ports.stderr.write(`${JSON.stringify({ input: last.input, initial_world: last.inputWorld, output: last.result, simulation: last.simulation ?? {}, context: last.context ?? [] }, null, 2)}\n`);
|
|
164
|
+
const terminal = ports.stdin === process.stdin && isatty(0) && isatty(1);
|
|
165
|
+
const answer = terminal ? await terminalAnswer(ports, 'Is this answer right? [y/N] ') : '';
|
|
166
|
+
const valid = () => {
|
|
167
|
+
requireSource();
|
|
168
|
+
const current = readPrivate(lastPath), session = readPrivate(sessionPath), selected = store.repo(root).last_run;
|
|
169
|
+
checkSessionOwner(session, context);
|
|
170
|
+
return session?.id === snapshot.session.id && current?.sessionId === session.id && planProgramCase({ state: current?.state ?? 'missing', expected_run_id: last.id, current_run_id: latestId(selected), terminal, answer }).write && current?.id === last.id;
|
|
171
|
+
};
|
|
172
|
+
const decline = () => { ports.stderr.write('No test written. Set the expected value by hand in the Story test.\n'); return 0; };
|
|
173
|
+
if (!locked(valid)) return decline();
|
|
174
|
+
const chosen = discoveryPorts.findTests ? discoveryPorts.findTests({ root }) : findTests({ root }, discoveryPorts);
|
|
175
|
+
const candidates = chosen.tests.filter(test => test.story === story || test.storyPath === story || test.path === story);
|
|
176
|
+
if (candidates.length !== 1) throw failure('Choose one discovered Story for --save-last.');
|
|
177
|
+
const test = candidates[0], criteria = test.doc.criteria;
|
|
178
|
+
if (!isDeepStrictEqual(last.simulation ?? {}, test.doc.simulation ?? {}) || !isDeepStrictEqual(last.context ?? [], test.doc.context ?? [])) throw failure('Recorded simulation bindings or context differ from this Story. No test written. Set matching bindings and the expected value by hand in an isolated Story test.', 125);
|
|
179
|
+
const criterion = criteria?.[0]?.id;
|
|
180
|
+
if (!criterion) throw failure('The Story needs a discovered acceptance criterion.');
|
|
181
|
+
if (!object(last.inputWorld) || last.error || last.answer?.error) throw failure('Exact starting data or result is unavailable; set the expected value by hand.', 125);
|
|
182
|
+
const tail = test.doc.steps?.at(-1);
|
|
183
|
+
const endWorld = !tail ? test.doc.initial_world : tail.checks?.find(check => check.target === 'world' && check.path === '' && check.op === 'equals')?.value;
|
|
184
|
+
const isolated = !isDeepStrictEqual(endWorld, last.inputWorld);
|
|
185
|
+
const saved = { id: last.actionId ?? last.id, name: 'Confirmed program run', story_path: test.storyPath, original_path: test.path, test: {
|
|
186
|
+
schema_version: 'prompt-runtime.program-scenario.v1', story_path: test.storyPath, criteria, initial_world: last.inputWorld,
|
|
187
|
+
...(test.doc.simulation ? { simulation: test.doc.simulation } : {}), ...(test.doc.context ? { context: test.doc.context } : {}),
|
|
188
|
+
steps: [{ step_id: `run-${last.id}`, entry_path: last.prompt, operation: last.operation, input: last.input, checks: [{ criterion_id: criterion, target: 'result', path: '', op: 'equals', value: last.result }] }],
|
|
189
|
+
} };
|
|
190
|
+
const transactionPorts = { ...ports, ...discoveryPorts };
|
|
191
|
+
let outcome = locked(() => valid() ? saveDoorCaseResult(root, saved, { isolated, env: ports.env, ports: transactionPorts }) : null);
|
|
192
|
+
if (!outcome) return decline();
|
|
193
|
+
if (outcome.kind === 'failure') throw failure(outcome.message, 125);
|
|
194
|
+
let lease;
|
|
195
|
+
try {
|
|
196
|
+
if (outcome.result.state !== 'committed') {
|
|
197
|
+
let handoff;
|
|
198
|
+
if (ports.caseHandoff) handoff = await ports.caseHandoff({ root, testPath: test.path, signal: ports.signal });
|
|
199
|
+
else {
|
|
200
|
+
const custody = await terminalAnswer(ports, `Close the editor for ${test.path}. Hand over this closed file for the pending case apply? y/N\n`);
|
|
201
|
+
if (/^y(?:es)?$/i.test(custody.trim())) handoff = { kind: 'closed-editor', testPath: test.path };
|
|
202
|
+
}
|
|
203
|
+
if (!locked(valid)) return decline();
|
|
204
|
+
if (handoff) lease = await acquireCaseWriteOwnership({ root, testPath: test.path, handoff, signal: ports.signal }, transactionPorts);
|
|
205
|
+
if (lease) outcome = locked(() => valid() ? saveDoorCaseResult(root, saved, { isolated, writeOwnership: lease, env: ports.env, ports: transactionPorts }) : null);
|
|
206
|
+
if (!outcome) return decline();
|
|
207
|
+
}
|
|
208
|
+
if (outcome.kind === 'failure') throw failure(outcome.message, 125);
|
|
209
|
+
if (outcome.result.state === 'committed') locked(() => { if (valid()) writePrivate(lastPath, { ...readPrivate(lastPath), saved: true }); });
|
|
210
|
+
ports.stderr.write(`${outcome.message}\nOnly the first criterion is recorded; review partial criterion coverage.\n`);
|
|
211
|
+
return outcome.result.state === 'committed' ? 0 : 125;
|
|
212
|
+
} finally { lease?.release(); }
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export async function runProgram({ file, argv = [], options = {}, cwd = process.cwd() } = {}, givenPorts = {}) {
|
|
216
|
+
const ports = { ...givenPorts, env: givenPorts.env ?? process.env, stdin: givenPorts.stdin ?? process.stdin, stdout: givenPorts.stdout ?? process.stdout, stderr: givenPorts.stderr ?? process.stderr };
|
|
217
|
+
const started = Date.now(), controller = new AbortController();
|
|
218
|
+
let context, unsubscribe, lastId = '', calls = 0, accountingKnown = true, draft = false, interrupted = false;
|
|
219
|
+
const interrupt = () => { interrupted = true; controller.abort(); };
|
|
220
|
+
try {
|
|
221
|
+
checkedOptions(options);
|
|
222
|
+
if (!Array.isArray(argv) || !argv.every(word => typeof word === 'string')) throw failure('Program argv must contain strings.');
|
|
223
|
+
const root = localRoot(cwd), selected = localPath(root, cwd, file), visible = new Set(gitFiles(root));
|
|
224
|
+
const files = sourceFilePort(root, visible), appMap = selected.endsWith('.prompt.md') ? null : selected;
|
|
225
|
+
let entry = selected;
|
|
226
|
+
if (appMap) { let map; try { map = JSON.parse(files.read({ path: appMap }).content); } catch (error) { if (error instanceof SyntaxError) throw failure('The app map must contain valid JSON.'); throw error; } entry = appEntry(map); }
|
|
227
|
+
const capturePorts = { ...ports, isStoryPath: () => false, hasAcceptance: () => false, matchTests: () => ({ tests: [], untested: [], orphans: [] }), orphanSummary: () => '' };
|
|
228
|
+
const captureProgram = ports.captureSource ?? ((r, selection) => captureSource(r, selection, capturePorts));
|
|
229
|
+
const capture = captureProgram(root, { tests: [entry], appMap });
|
|
230
|
+
const reached = capture.sources.filter(source => source.path.endsWith('.prompt.md'));
|
|
231
|
+
const authored = reached.find(source => source.path === entry);
|
|
232
|
+
if (!authored) throw failure('The app entry is not captured.');
|
|
233
|
+
let iface = promptInterface(authored.bytes.toString('utf8'));
|
|
234
|
+
const reachedInterfaces = reached.map(source => promptInterface(source.bytes.toString('utf8')));
|
|
235
|
+
const lazyRequired = reachedInterfaces.some(contract => contract === null);
|
|
236
|
+
draft = reached.some(source => { try { return promptInterface(source.bytes.toString('utf8')).status === 'draft'; } catch { return false; } });
|
|
237
|
+
let declaredErrors = [...new Set(reached.flatMap(source => { try { return promptInterface(source.bytes.toString('utf8')).entries?.flatMap(row => row.errors ?? []) ?? []; } catch { return []; } }))];
|
|
238
|
+
let data = null, inputFile = null;
|
|
239
|
+
if (options['--data']) data = files.read({ path: localPath(root, cwd, options['--data']) }).content;
|
|
240
|
+
const selectInvocation = async (contract, modelEntries = null) => {
|
|
241
|
+
if (!appMap && options['--serve'] !== undefined) {
|
|
242
|
+
const known = modelEntries ? [contract] : reachedInterfaces.filter(Boolean);
|
|
243
|
+
for (const candidate of known) if (!programInterfaceShape(candidate)) return prepareProgramInvocation({ file: selected, argv, interface_json: JSON.stringify(candidate), serve: true });
|
|
244
|
+
const entries = modelEntries ?? known.flatMap(candidate => candidate.entries);
|
|
245
|
+
// Local closure metadata can reject an invalid selection. Only the pinned
|
|
246
|
+
// owner model will authorize actual routes when the listener opens.
|
|
247
|
+
if (entries.some(row => /^HTTP (?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS) \/\S*$/.test(row.input_schema?.title ?? '') || row.http)) return { door: 'http', operation: '', input_json: '', exit_code: 0, message: '' };
|
|
248
|
+
if (!modelEntries && lazyRequired) return { door: 'deferred', operation: '', input_json: '', exit_code: 0, message: '' };
|
|
249
|
+
return prepareProgramInvocation({ file: selected, argv, interface_json: JSON.stringify(contract), serve: true });
|
|
250
|
+
}
|
|
251
|
+
const hasCli = contract.entries?.some((_, index) => ['input_schema', 'result_schema'].every(key => contract.conventions?.some(row => row.path === `/entries/${index}/${key}` && row.convention === 'cli')));
|
|
252
|
+
const inputIndex = argv.indexOf('--input');
|
|
253
|
+
if (!hasCli && inputIndex >= 0 && argv[inputIndex + 1]?.startsWith('@')) inputFile = files.read({ path: localPath(root, cwd, argv[inputIndex + 1].slice(1)) }).content;
|
|
254
|
+
let invocation = prepareProgramInvocation({ file: selected, argv, interface_json: JSON.stringify(contract), stdin_tty: ports.stdin.isTTY === true, serve: options['--serve'] !== undefined, input_file_json: inputFile });
|
|
255
|
+
const cliIndex = contract.entries?.findIndex((_, index) => ['input_schema', 'result_schema'].every(key => contract.conventions?.some(row => row.path === `/entries/${index}/${key}` && row.convention === 'cli'))) ?? -1;
|
|
256
|
+
const typedEntries = contract.entries?.filter(row => !programHttpEntry(row)) ?? [];
|
|
257
|
+
const typedWords = typedEntries.length > 1 ? argv.slice(1) : argv;
|
|
258
|
+
const needsStdin = !appMap && !options['--read'] && !options['--save-last'] && !options['--show-data'] && !ports.stdin.isTTY && (cliIndex >= 0 ? !!contract.entries[cliIndex].input_schema?.properties?.stdin && argv.length > 0 : !['http', 'screen'].includes(invocation.door) && typedEntries.length > 0 && !typedWords.length);
|
|
259
|
+
if (needsStdin) invocation = prepareProgramInvocation({ file: selected, argv, interface_json: JSON.stringify(contract), stdin: await stdinText(ports.stdin), stdin_tty: false, serve: options['--serve'] !== undefined, input_file_json: inputFile });
|
|
260
|
+
return invocation;
|
|
261
|
+
};
|
|
262
|
+
let invocation = iface ? await selectInvocation(iface) : { door: appMap ? 'screen' : 'deferred', operation: '', input_json: '' };
|
|
263
|
+
if (invocation.door === 'usage' && !options['--read'] && !options['--save-last'] && !options['--show-data']) { ports.stderr.write(`${invocation.message}\n`); return 2; }
|
|
264
|
+
// Validate starting data before authentication or Runtime work.
|
|
265
|
+
const validation = planProgramSession({ data_json: data, fresh: options['--fresh'] === true });
|
|
266
|
+
if (validation.action === 'refuse') throw failure(validation.message);
|
|
267
|
+
excludeRuns(root);
|
|
268
|
+
const folder = privateFolder(root, ['.pdd', 'run', `${basename(entry, '.prompt.md').replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 40)}-${digest(entry).slice(0, 24)}`]);
|
|
269
|
+
const sessionPath = join(folder, 'session.json'), dataPath = join(folder, 'data.json'), lastPath = join(folder, 'last.json');
|
|
270
|
+
const programSignal = controller.signal;
|
|
271
|
+
if (ports.signal) { if (ports.signal.aborted) interrupt(); else ports.signal.addEventListener('abort', interrupt, { once: true }); }
|
|
272
|
+
if (ports.onInterrupt) unsubscribe = ports.onInterrupt(interrupt);
|
|
273
|
+
else { process.on('SIGINT', interrupt); unsubscribe = () => process.off('SIGINT', interrupt); }
|
|
274
|
+
context = await createProgramContext({ cwd, options }, { ...ports, captureSource: captureProgram, signal: programSignal });
|
|
275
|
+
Object.assign(context, { freeProgram: true, programEntry: entry, appMap, capture, signal: programSignal, allowMissingInterfaces: lazyRequired });
|
|
276
|
+
let session, last;
|
|
277
|
+
const locked = action => withRepositoryRunLock(root, context.store, action);
|
|
278
|
+
locked(() => { session = readPrivate(sessionPath); last = readPrivate(lastPath); });
|
|
279
|
+
checkSessionOwner(session, context);
|
|
280
|
+
const recovery = id => `pdd run ${quote(file)} --read ${id}`;
|
|
281
|
+
const snapshot = () => ({ session: readPrivate(sessionPath), last: readPrivate(lastPath), world: readPrivate(dataPath) });
|
|
282
|
+
const changedData = current => {
|
|
283
|
+
const pendingId = current.session?.stop_id ?? (current.session?.state === 'unknown' ? current.session.id : current.last?.state === 'unknown' ? current.last.id : null);
|
|
284
|
+
return failure(`Program data changed before it could be used; saved data was retained.${pendingId ? ` Read: ${recovery(pendingId)}` : ' Run again.'}`, 125);
|
|
285
|
+
};
|
|
286
|
+
const requireSnapshot = expected => {
|
|
287
|
+
const current = snapshot();
|
|
288
|
+
if (!isDeepStrictEqual(current, expected)) throw changedData(current);
|
|
289
|
+
};
|
|
290
|
+
const persist = async (answer = null, ownerId = null, retainSnapshot = false) => {
|
|
291
|
+
const before = locked(snapshot);
|
|
292
|
+
const reply = object(answer?.world) ? { status: 200, json: { world: answer.world } } : programSignal.aborted ? await context.readState(session.id) : await context.runtime.send(`/v1/try/${session.id}/state`, { method: 'GET' }, 30_000);
|
|
293
|
+
if (reply.status !== 200 || !object(reply.json?.world)) throw failure('Current data could not be confirmed; saved data was retained.', 125);
|
|
294
|
+
const confirmed = locked(() => {
|
|
295
|
+
const current = snapshot(), latest = current.last;
|
|
296
|
+
if (!isDeepStrictEqual(current.session, session) || !isDeepStrictEqual(current, before)
|
|
297
|
+
|| (ownerId ? latest?.id !== ownerId : latest?.state === 'unknown')) {
|
|
298
|
+
// Historical receipts can still be displayed, but their world cannot
|
|
299
|
+
// become starting data after another invocation took ownership.
|
|
300
|
+
if (ownerId) return null;
|
|
301
|
+
throw changedData(current);
|
|
302
|
+
}
|
|
303
|
+
writePrivate(dataPath, reply.json.world);
|
|
304
|
+
return { ...current, world: reply.json.world };
|
|
305
|
+
});
|
|
306
|
+
return retainSnapshot ? confirmed : reply.json.world;
|
|
307
|
+
};
|
|
308
|
+
if (options['--save-last']) return await saveProgramCase(context, folder, options['--save-last'], ports, givenPorts);
|
|
309
|
+
if (options['--read']) {
|
|
310
|
+
const id = options['--read'];
|
|
311
|
+
if (session?.state === 'unknown' && session.stop_id === id) {
|
|
312
|
+
lastId = id;
|
|
313
|
+
const read = await context.runtime.get(id), job = read.json;
|
|
314
|
+
if (read.status !== 200 || !receiptIdentity(job, id, 'stop', session.id)
|
|
315
|
+
|| !['passed', 'failed', 'refused', 'not_run'].includes(job.state)
|
|
316
|
+
|| job.state === 'passed' && (job.result?.session?.id !== session.id || job.result.session.state !== 'stopped')) throw failure(`The stop outcome remains unknown. Read: ${recovery(id)}`, 125);
|
|
317
|
+
const stopped = job.state === 'passed';
|
|
318
|
+
locked(() => {
|
|
319
|
+
const latest = readPrivate(sessionPath);
|
|
320
|
+
if (latest?.id !== session.id || latest.state !== 'unknown' || latest.stop_id !== id) throw failure('This stop was superseded.', 125);
|
|
321
|
+
const { stop_id, ...retained } = latest;
|
|
322
|
+
session = { ...retained, state: stopped ? 'stopped' : 'running' };
|
|
323
|
+
context.store.write(join(context.folder, `${id}.json`), job);
|
|
324
|
+
writePrivate(sessionPath, session);
|
|
325
|
+
});
|
|
326
|
+
if (!stopped) throw failure(`${job.result?.refusals?.[0]?.message ?? 'The interpreter did not confirm that the old program stopped.'} Run the program again when ready.`, 125);
|
|
327
|
+
return 0;
|
|
328
|
+
}
|
|
329
|
+
if (session?.state === 'unknown' && session.id === id && (!last || last.id !== id)) {
|
|
330
|
+
lastId = id;
|
|
331
|
+
const receipt = await context.runtime.get(id);
|
|
332
|
+
const job = receipt.json;
|
|
333
|
+
if (receipt.status !== 200 || !receiptIdentity(job, id, 'try', session.id)) throw failure(`Program setup remains unknown. Read: ${recovery(id)}`, 125);
|
|
334
|
+
if (['failed', 'refused', 'not_run'].includes(job.state)) {
|
|
335
|
+
locked(() => {
|
|
336
|
+
const latest = readPrivate(sessionPath);
|
|
337
|
+
if (latest?.id !== id || latest.state !== 'unknown' || latest.stop_id) throw failure('This setup was superseded.', 125);
|
|
338
|
+
session = { ...latest, state: 'stopped' }; writePrivate(sessionPath, session);
|
|
339
|
+
});
|
|
340
|
+
throw failure(`${job.result?.refusals?.[0]?.message ?? 'The interpreter did not open the program session.'} Run the program again when ready.`, 125);
|
|
341
|
+
}
|
|
342
|
+
if (job.state !== 'passed' || job.result?.session?.id !== id || job.result.session.state !== 'running' || typeof job.result.url !== 'string') throw failure(`Program setup remains unknown. Read: ${recovery(id)}`, 125);
|
|
343
|
+
const link = new URL(job.result.url);
|
|
344
|
+
if (link.origin !== context.origin || !/^\/s\/[A-Za-z0-9_-]+\/$/.test(link.pathname) || link.username || link.password) throw failure('The saved program link is unsafe.', 125);
|
|
345
|
+
const confirmed = await context.readState(id);
|
|
346
|
+
if (confirmed.status !== 200 || !object(confirmed.json?.world)) throw failure('Current data could not be confirmed; saved data was retained.', 125);
|
|
347
|
+
locked(() => {
|
|
348
|
+
const latest = readPrivate(sessionPath);
|
|
349
|
+
if (!isDeepStrictEqual(latest, session) || latest?.state !== 'unknown' || latest.stop_id) throw failure('This setup was superseded.', 125);
|
|
350
|
+
session = { ...latest, state: 'running', url: link.href };
|
|
351
|
+
writePrivate(sessionPath, session); writePrivate(dataPath, confirmed.json.world);
|
|
352
|
+
});
|
|
353
|
+
return 0;
|
|
354
|
+
}
|
|
355
|
+
if (!last || last.id !== id) throw failure('That run is not this program’s saved latest run.', 125);
|
|
356
|
+
lastId = id;
|
|
357
|
+
if (last.state === 'confirmed') {
|
|
358
|
+
checkRunOwner(last, session, context);
|
|
359
|
+
return outputAnswer(last.answer ?? last, last.door, ports);
|
|
360
|
+
}
|
|
361
|
+
if (!session?.id) throw failure(`The session is unavailable. Read: ${recovery(id)}`, 125);
|
|
362
|
+
const observed = await context.runtime.send(`/v1/try/${session.id}/calls/${id}/observation`, { method: 'GET' }, 30_000);
|
|
363
|
+
if (observed.status !== 200 || !['passed', 'failed', 'refused'].includes(observed.json?.state)) throw failure(`Run outcome remains unknown. Read: ${recovery(id)}`, 125);
|
|
364
|
+
const read = await context.runtime.get(id);
|
|
365
|
+
if (read.status !== 200 || !receiptIdentity(read.json, id, 'call', session.id)
|
|
366
|
+
|| !['passed', 'failed', 'refused', 'not_run'].includes(read.json.state)) throw failure(`Run outcome remains unknown. Read: ${recovery(id)}`, 125);
|
|
367
|
+
const report = object(read.json.result?.report) ? read.json.result.report : null;
|
|
368
|
+
const receiptState = read.json.state === 'not_run' ? 'refused' : read.json.state;
|
|
369
|
+
let recoveryDeclaredErrors = [];
|
|
370
|
+
if (['failed', 'refused'].includes(receiptState) && report?.verdict === 'failed' && typeof report.error?.code === 'string') {
|
|
371
|
+
const model = await context.runtime.send(`/v1/try/${session.id}/model`, { method: 'GET' }, 30_000);
|
|
372
|
+
if (model.status !== 200 || !Array.isArray(model.json?.entries) || !model.json.entries.every(row => object(row) && Array.isArray(row.errors ?? []) && (row.errors ?? []).every(code => typeof code === 'string'))) throw failure(`The admitted program interface could not be read. Read: ${recovery(id)}`, 125);
|
|
373
|
+
// The accepted session owns this historic call's declarations. Current
|
|
374
|
+
// authored interfaces can have changed while its outcome was unknown.
|
|
375
|
+
recoveryDeclaredErrors = [...new Set(model.json.entries.flatMap(row => row.errors ?? []))];
|
|
376
|
+
}
|
|
377
|
+
let projected;
|
|
378
|
+
try {
|
|
379
|
+
projected = projectTryCall({
|
|
380
|
+
request_id: id, declared_errors: recoveryDeclaredErrors,
|
|
381
|
+
state: receiptState,
|
|
382
|
+
has_program_result: Object.hasOwn(read.json.result ?? {}, 'program_result'), usage_calls: 0,
|
|
383
|
+
report: report ? {
|
|
384
|
+
action_id: typeof report.action_id === 'string' ? report.action_id : null,
|
|
385
|
+
verdict: typeof report.verdict === 'string' ? report.verdict : null,
|
|
386
|
+
error_code: typeof report.error?.code === 'string' ? report.error.code : null,
|
|
387
|
+
replayed: Boolean(report.replayed), remaining_calls: Number.isSafeInteger(report.remaining_calls) ? report.remaining_calls : null,
|
|
388
|
+
} : null,
|
|
389
|
+
});
|
|
390
|
+
} catch (error) { throw failure(`${error.message} Read: ${recovery(id)}`, 125); }
|
|
391
|
+
const result = projected.outcome === 'result' ? read.json.result.program_result : null;
|
|
392
|
+
const state = await context.readState(session.id);
|
|
393
|
+
const action = state.status === 200 && Array.isArray(state.json?.actions) ? state.json.actions.find(row => row.action_id === report?.action_id) : null;
|
|
394
|
+
const answer = { id, actionId: projected.action_id, replayed: projected.replayed, result, error: projected.outcome === 'program_error' ? report.error : null, callChain: report?.call_chain ?? [], inputWorld: action?.input_world ?? report?.input_world, world: action?.world ?? report?.world, usage: { calls: 0 } };
|
|
395
|
+
await persist(answer, id);
|
|
396
|
+
locked(() => { if (readPrivate(lastPath)?.id === id) { last = { ...last, ...answer, state: 'confirmed', answer, inputWorld: answer.inputWorld }; writePrivate(lastPath, last); const repo = context.store.repo(root); if ((repo.last_run?.run_id ?? repo.last_run?.id) === id) context.store.saveRepo(root, { ...repo, last_run: { ...repo.last_run, state: 'confirmed' } }); } });
|
|
397
|
+
return outputAnswer(answer, last.door, ports);
|
|
398
|
+
}
|
|
399
|
+
if (last?.state === 'unknown' || session?.state === 'unknown') throw failure(`A saved run outcome is unknown. Read: ${recovery(session?.stop_id ?? (last?.state === 'unknown' ? last.id : session?.id))}`, 125);
|
|
400
|
+
let savedWorld = readPrivate(dataPath), status = session?.state === 'stopped' ? 'stopped' : session ? 'running' : 'missing';
|
|
401
|
+
if (session?.id) {
|
|
402
|
+
const model = status === 'stopped' ? { status: 410 } : await context.runtime.send(`/v1/try/${session.id}/model`, { method: 'GET' }, 30_000);
|
|
403
|
+
if ([404, 410].includes(model.status)) status = 'missing';
|
|
404
|
+
else if (model.status === 409) {
|
|
405
|
+
const old = await context.runtime.get(session.id);
|
|
406
|
+
if (old.status !== 200 || !receiptIdentity(old.json, session.id, 'try', session.id)
|
|
407
|
+
|| old.json.state !== 'passed' || old.json.result?.session?.id !== session.id
|
|
408
|
+
|| !['paused', 'stopped'].includes(old.json.result.session.state)) throw failure(`Program session state remains unknown for ${session.id}. Run the program again when its owner receipt is available.`, 125);
|
|
409
|
+
status = old.json.result.session.state;
|
|
410
|
+
} else if (model.status !== 200) status = 'unknown';
|
|
411
|
+
}
|
|
412
|
+
let plan = planProgramSession({ fresh: options['--fresh'] === true, data_json: data, saved_data_json: savedWorld === null ? null : JSON.stringify(savedWorld), saved_simulation_json: JSON.stringify(session?.simulation ?? {}), saved_source: session?.source ?? '', current_source: capture.sha256, session_id: session?.id ?? '', session_state: status });
|
|
413
|
+
if (plan.action === 'refuse') throw failure(plan.message, 125);
|
|
414
|
+
if (plan.action === 'replace') {
|
|
415
|
+
const confirmed = await persist(null, null, true);
|
|
416
|
+
savedWorld = confirmed.world;
|
|
417
|
+
plan = planProgramSession({ fresh: options['--fresh'] === true, data_json: data, saved_data_json: JSON.stringify(savedWorld), saved_simulation_json: JSON.stringify(session.simulation ?? {}), saved_source: session.source, current_source: capture.sha256, session_id: session.id, session_state: status });
|
|
418
|
+
const previous = session, stopId = randomUUID(); lastId = stopId;
|
|
419
|
+
locked(() => { requireSnapshot(confirmed); session = { ...previous, state: 'unknown', stop_id: stopId }; writePrivate(sessionPath, session); });
|
|
420
|
+
try { await context.stopSession(previous.id, stopId); }
|
|
421
|
+
catch (error) { if (!error.unknownOutcome) locked(() => { if (readPrivate(sessionPath)?.stop_id === stopId) { session = previous; writePrivate(sessionPath, previous); } }); throw error; }
|
|
422
|
+
locked(() => { if (readPrivate(sessionPath)?.stop_id !== stopId) throw failure('This replacement stop was superseded.', 125); session = { ...previous, state: 'stopped' }; writePrivate(sessionPath, session); });
|
|
423
|
+
}
|
|
424
|
+
if (plan.action === 'reopen') {
|
|
425
|
+
const previous = session;
|
|
426
|
+
locked(() => { const current = readPrivate(sessionPath); if (current?.id !== previous.id || current.state === 'unknown') throw failure('This session changed before reopening.', 125); session = { ...previous, state: 'unknown' }; writePrivate(sessionPath, session); });
|
|
427
|
+
const pending = structuredClone(session);
|
|
428
|
+
lastId = session.id;
|
|
429
|
+
let reopened = await context.runtime.reopen(session.id);
|
|
430
|
+
const deadline = Date.now() + 300_000;
|
|
431
|
+
for (;;) {
|
|
432
|
+
const job = reopened.json;
|
|
433
|
+
if ([200, 202].includes(reopened.status)) {
|
|
434
|
+
if (!receiptIdentity(job, session.id, 'try', session.id)
|
|
435
|
+
|| job.state === 'passed' && (job.result?.session?.id !== session.id || job.result.session.state !== 'running')) throw failure(`Reopening the program was not confirmed. Read: ${recovery(session.id)}`, 125);
|
|
436
|
+
if (reopened.status === 200 && job.state === 'passed') break;
|
|
437
|
+
}
|
|
438
|
+
if (programSignal.aborted || Date.now() >= deadline || reopened.status && ![200, 202].includes(reopened.status)) throw failure(`Reopening the program was not confirmed. Read: ${recovery(session.id)}`, 125);
|
|
439
|
+
await context.ports.sleep(context.ports.pollMs, programSignal);
|
|
440
|
+
reopened = await context.runtime.get(session.id);
|
|
441
|
+
}
|
|
442
|
+
locked(() => { const latest = readPrivate(sessionPath); if (!isDeepStrictEqual(latest, pending) || latest?.state !== 'unknown' || latest.stop_id) throw failure('This session was superseded.', 125); session = { ...previous, state: 'running' }; writePrivate(sessionPath, session); });
|
|
443
|
+
}
|
|
444
|
+
if (['create', 'replace'].includes(plan.action)) {
|
|
445
|
+
const id = randomUUID(), previous = session; lastId = id;
|
|
446
|
+
session = { id, state: 'unknown', source: capture.sha256, entry, login: context.identity.login, origin: context.origin, simulation: JSON.parse(plan.simulation_json) };
|
|
447
|
+
locked(() => { const latest = readPrivate(sessionPath); if (latest?.id !== previous?.id) throw failure('Another process changed this program session; run again.', 125); writePrivate(sessionPath, session); });
|
|
448
|
+
const pending = structuredClone(session);
|
|
449
|
+
let opened;
|
|
450
|
+
try { opened = await admitProgram(context, capture, { requestId: id, entry, appMap, initial_world: JSON.parse(plan.initial_world_json), simulation: JSON.parse(plan.simulation_json), max_calls: options['--max-calls'] ?? 400, tab: invocation.door === 'screen' ? 'screen' : ['cli', 'shell'].includes(invocation.door) ? 'terminal' : 'call' }); }
|
|
451
|
+
catch (error) { if (!error.unknownOutcome) locked(() => { if (readPrivate(sessionPath)?.id === id) { if (previous) writePrivate(sessionPath, previous); else unlinkSync(sessionPath); } }); throw error; }
|
|
452
|
+
locked(() => { const latest = readPrivate(sessionPath); if (!isDeepStrictEqual(latest, pending) || latest?.state !== 'unknown' || latest.stop_id) throw failure('Program session was superseded.', 125); session = { ...pending, id: opened.id, url: opened.url, state: 'running' }; writePrivate(sessionPath, session); writePrivate(dataPath, JSON.parse(plan.initial_world_json)); });
|
|
453
|
+
}
|
|
454
|
+
if (options['--show-data']) { await persist(); ports.stdout.write(`${JSON.stringify(readPrivate(dataPath), null, ports.stdout.isTTY ? 2 : undefined)}\n`); return 0; }
|
|
455
|
+
const call = async (selectedEntry, input, door = invocation.door) => {
|
|
456
|
+
const id = randomUUID(); lastId = id;
|
|
457
|
+
let inputWorld;
|
|
458
|
+
// Refresh confirmed starting data before selecting the next run owner.
|
|
459
|
+
const confirmed = await persist(null, null, true);
|
|
460
|
+
inputWorld = confirmed.world;
|
|
461
|
+
const pending = { id, state: 'unknown', sessionId: session.id, prompt: selectedEntry.entry_path ?? entry, operation: selectedEntry.operation, input, source: session.source, startingSnapshot: inputWorld, simulation: session.simulation ?? {}, context: [], door };
|
|
462
|
+
locked(() => {
|
|
463
|
+
requireSnapshot(confirmed);
|
|
464
|
+
const current = readPrivate(sessionPath), latest = readPrivate(lastPath);
|
|
465
|
+
if (current?.id !== session.id) throw failure('Another process changed this program session; run again.', 125);
|
|
466
|
+
if (current.state !== 'running') {
|
|
467
|
+
const pendingId = current.stop_id ?? (current.state === 'unknown' ? current.id : null);
|
|
468
|
+
throw failure(`This program session is not running.${pendingId ? ` Read: ${recovery(pendingId)}` : ' Run again.'}`, 125);
|
|
469
|
+
}
|
|
470
|
+
if (latest?.state === 'unknown') throw failure(`Another program call is pending. Read: ${recovery(latest.id)}`, 125);
|
|
471
|
+
writePrivate(lastPath, pending);
|
|
472
|
+
const repo = context.store.repo(root);
|
|
473
|
+
context.store.saveRepo(root, { ...repo, last_run: { id, run_id: id, state: 'unknown', program: entry, session_id: session.id } });
|
|
474
|
+
});
|
|
475
|
+
let answer;
|
|
476
|
+
try { answer = await runDoorCall({ root, origin: context.origin, login: context.identity.login, sessionId: session.id, prompt: pending.prompt, operation: selectedEntry.operation, declaredErrors, freeProgram: true, runId: id, maxCalls: options['--max-calls'], fresh: options['--fresh'] === true }, input, { ...ports, captureSource: captureProgram, signal: programSignal }); }
|
|
477
|
+
catch (error) {
|
|
478
|
+
if (Number.isInteger(error.tryUsage?.calls)) calls += error.tryUsage.calls;
|
|
479
|
+
else if (error.unknownOutcome) accountingKnown = false;
|
|
480
|
+
if (error.unknownOutcome !== true) locked(() => {
|
|
481
|
+
if (readPrivate(lastPath)?.id === id) writePrivate(lastPath, { ...pending, state: 'missing' });
|
|
482
|
+
const repo = context.store.repo(root);
|
|
483
|
+
if (repo.last_run?.id === id) context.store.saveRepo(root, { ...repo, last_run: { ...repo.last_run, state: 'missing' } });
|
|
484
|
+
});
|
|
485
|
+
if (error.unknownOutcome !== true) { lastId = ''; throw error; }
|
|
486
|
+
throw Object.assign(error, { message: `${error.message}\nRead: ${recovery(id)}` });
|
|
487
|
+
}
|
|
488
|
+
if (Number.isInteger(answer.usage?.calls)) calls += answer.usage.calls; else accountingKnown = false;
|
|
489
|
+
await persist(answer, id);
|
|
490
|
+
locked(() => {
|
|
491
|
+
if (readPrivate(lastPath)?.id !== id) return;
|
|
492
|
+
writePrivate(lastPath, { ...pending, ...answer, state: 'confirmed', answer, inputWorld: answer.inputWorld });
|
|
493
|
+
const repo = context.store.repo(root);
|
|
494
|
+
if ((repo.last_run?.run_id ?? repo.last_run?.id) === id) context.store.saveRepo(root, { ...repo, last_run: { ...repo.last_run, state: 'confirmed' } });
|
|
495
|
+
});
|
|
496
|
+
return answer;
|
|
497
|
+
};
|
|
498
|
+
if (lazyRequired) {
|
|
499
|
+
const model = await context.runtime.send(`/v1/try/${session.id}/model`, { method: 'GET' }, 30_000);
|
|
500
|
+
if (model.status !== 200 || !Array.isArray(model.json?.entries)) throw failure('The admitted program interface could not be read. No program call was sent; read this session again.', 125);
|
|
501
|
+
declaredErrors = [...new Set([...declaredErrors, ...model.json.entries.flatMap(row => row.errors ?? [])])];
|
|
502
|
+
const admitted = context.programLintAnswer?.result?.report?.program?.prompts;
|
|
503
|
+
draft ||= !Array.isArray(admitted) || reached.some(source => !admitted.some(row => row.path === source.path && (row.state === 'approved' || row.admission_state === 'approved')));
|
|
504
|
+
if (!iface || !appMap && options['--serve'] !== undefined) {
|
|
505
|
+
const entries = model.json.entries.filter(row => row.entry_path === entry);
|
|
506
|
+
if (!entries.length) throw failure('The pinned model has no admitted operation for this entry. No program call was sent.', 125);
|
|
507
|
+
iface = { entries: entries.map(row => ({ operation: row.operation, input_schema: row.input_schema, result_schema: row.result_schema, errors: row.errors ?? [], http: row.http })), conventions: entries.flatMap((row, index) => row.cli === true ? ['input_schema', 'result_schema'].map(key => ({ path: `/entries/${index}/${key}`, convention: 'cli' })) : []) };
|
|
508
|
+
invocation = await selectInvocation(iface, model.json.entries);
|
|
509
|
+
if (invocation.door === 'usage') { ports.stderr.write(`${invocation.message}\n`); return 2; }
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
context.callProgram = (selectedEntry, input) => call(selectedEntry, input, 'typed');
|
|
513
|
+
context.persistProgram = () => persist();
|
|
514
|
+
if (invocation.door === 'http') {
|
|
515
|
+
const code = await openServe(context, null, session.id, { ...options, '--serve': options['--serve'] === true || options['--serve'] === undefined ? 8080 : options['--serve'] });
|
|
516
|
+
if (interrupted) throw failure('Program interrupted.', 130);
|
|
517
|
+
return code;
|
|
518
|
+
}
|
|
519
|
+
if (invocation.door === 'screen') {
|
|
520
|
+
const url = session.url;
|
|
521
|
+
if (!url) throw failure('The interpreter returned no Screen link.', 125);
|
|
522
|
+
const screenUrl = new URL(url); screenUrl.searchParams.set('tab', 'screen');
|
|
523
|
+
ports.stdout.write(`${screenUrl.href}\n`);
|
|
524
|
+
if (!options['--no-open']) await context.ports.openUrl(screenUrl.href);
|
|
525
|
+
if (ports.serve) await ports.serve(null);
|
|
526
|
+
else while (!programSignal.aborted) { await context.ports.sleep(context.ports.watchMs, programSignal); if (!programSignal.aborted) await persist(); }
|
|
527
|
+
await persist();
|
|
528
|
+
if (interrupted) throw failure('Program interrupted.', 130);
|
|
529
|
+
return 0;
|
|
530
|
+
}
|
|
531
|
+
if (invocation.door === 'shell') return await programShell({ file, entry, iface, folder, root, cwd, ports });
|
|
532
|
+
const answer = await call({ entry_path: entry, operation: invocation.operation }, JSON.parse(invocation.input_json));
|
|
533
|
+
return outputAnswer(answer, invocation.door, ports);
|
|
534
|
+
} catch (error) {
|
|
535
|
+
if (error?.unboundPort) throw error;
|
|
536
|
+
ports.stderr.write(`pdd: ${error.message ?? 'The program could not run.'}\n`);
|
|
537
|
+
if (interrupted) { if (lastId) ports.stderr.write(`Read: pdd run ${quote(file)} --read ${lastId}\n`); return 130; }
|
|
538
|
+
return error.exitCode === 2 || error.exitCode === 4 ? 2 : 125;
|
|
539
|
+
} finally {
|
|
540
|
+
unsubscribe?.(); ports.signal?.removeEventListener('abort', interrupt);
|
|
541
|
+
await context?.dispose?.();
|
|
542
|
+
if (!options?.['-q']) ports.stderr.write(`${ports.summaryBreak ? '\n' : ''}pdd: ${accountingKnown ? calls : 'unknown'} AI calls; ${((Date.now() - started) / 1000).toFixed(2)} s; prompt behavior; not tested native code${draft ? '; DRAFT' : ''}\n`);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
async function programShell({ file, entry, iface, folder, root, cwd, ports }) {
|
|
547
|
+
const text = sourceFilePort(root).read({ path: entry }).content;
|
|
548
|
+
const name = text.match(/^#\s+`?([A-Za-z][A-Za-z0-9._-]{0,63})`?\s*$/m)?.[1];
|
|
549
|
+
if (!name || ['pdd', 'node', 'gh', 'git'].includes(name.toLowerCase())) throw failure('Name the CLI prompt with a safe program heading, such as # tasks.');
|
|
550
|
+
const bin = privateFolder(folder, ['bin']), shim = join(bin, name);
|
|
551
|
+
if (existsSync(shim)) { regular(shim); if (!readFileSync(shim, 'utf8').startsWith('#!/bin/sh\n# PDD program launcher v1\n')) throw failure('Refusing to replace a non-PDD shell command.'); }
|
|
552
|
+
const module = pathToFileURL(fileURLToPath(import.meta.url)).href;
|
|
553
|
+
const script = 'import(process.argv[1]).then(async m => { process.exitCode = await m.runProgram({file:process.argv[2],cwd:process.argv[3],argv:process.argv.slice(4)}); }).catch(e=>{process.stderr.write(String(e.message)+"\\n");process.exitCode=125;});';
|
|
554
|
+
const code = `#!/bin/sh\n# PDD program launcher v1\nexec ${quote(process.execPath)} --input-type=commonjs -e ${quote(script)} -- ${quote(module)} ${quote(entry)} ${quote(root)} "$@"\n`;
|
|
555
|
+
const fd = openSync(shim, constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW, 0o700); try { writeFileSync(fd, code); fsyncSync(fd); } finally { closeSync(fd); }
|
|
556
|
+
const env = { ...ports.env, PATH: `${bin}:${ports.env.PATH ?? process.env.PATH ?? ''}` }, chosen = ports.env.SHELL ?? '/bin/sh';
|
|
557
|
+
const shell = ['bash', 'sh', 'zsh'].includes(basename(chosen)) ? chosen : '/bin/sh';
|
|
558
|
+
if (ports.shell) return await ports.shell(shell, env);
|
|
559
|
+
return await new Promise((done, reject) => { const child = spawn(shell, ['-i'], { cwd, env, stdio: 'inherit' }); child.on('error', reject); child.on('exit', (code, signal) => done(code ?? (signal ? 130 : 0))); });
|
|
560
|
+
}
|
|
561
|
+
// Deterministic policy owned by prompts/cli/run-program.prompt.md.
|
|
562
|
+
const programObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
563
|
+
const programHttpRoute = /^HTTP (?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS) \/\S*$/;
|
|
564
|
+
const programHttpEntry = entry => programHttpRoute.test(entry.input_schema?.title ?? '') || programObject(entry.http) && programHttpRoute.test(`HTTP ${entry.http.method} ${entry.http.path}`);
|
|
565
|
+
const programEqual = (left, right) => {
|
|
566
|
+
if (left === right) return true;
|
|
567
|
+
if (!left || !right || typeof left !== 'object' || typeof right !== 'object' || Array.isArray(left) !== Array.isArray(right)) return false;
|
|
568
|
+
const keys = Object.keys(left);
|
|
569
|
+
return keys.length === Object.keys(right).length && keys.every(key => Object.hasOwn(right, key) && programEqual(left[key], right[key]));
|
|
570
|
+
};
|
|
571
|
+
function programNumberIdentity(text) {
|
|
572
|
+
const match = /^(-?)([0-9]+)(?:\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?$/.exec(text);
|
|
573
|
+
if (!match) return text;
|
|
574
|
+
let digits = (match[2] + (match[3] ?? '')).replace(/^0+/, '');
|
|
575
|
+
if (!digits) return '0';
|
|
576
|
+
const zeros = /0*$/.exec(digits)[0].length;
|
|
577
|
+
return match[1] + digits.slice(0, digits.length - zeros) + 'e' + (BigInt(match[4] ?? 0) - BigInt((match[3] ?? '').length) + BigInt(zeros));
|
|
578
|
+
}
|
|
579
|
+
function programMultiple(value, divisor) {
|
|
580
|
+
if (!(divisor > 0)) return false;
|
|
581
|
+
const [top, topExponent] = programNumberIdentity(String(value)).split('e');
|
|
582
|
+
if (top === '0') return true;
|
|
583
|
+
const [bottom, bottomExponent] = programNumberIdentity(String(divisor)).split('e');
|
|
584
|
+
let numerator = BigInt(top), denominator = BigInt(bottom);
|
|
585
|
+
const exponent = BigInt(topExponent) - BigInt(bottomExponent);
|
|
586
|
+
if (exponent >= 0n) numerator *= 10n ** exponent;
|
|
587
|
+
else denominator *= 10n ** -exponent;
|
|
588
|
+
return numerator % denominator === 0n;
|
|
589
|
+
}
|
|
590
|
+
function programParse(text) {
|
|
591
|
+
return JSON.parse(text, (key, value, context) => {
|
|
592
|
+
if (typeof value === 'number' && (!Number.isFinite(value) || context?.source && programNumberIdentity(context.source) !== programNumberIdentity(String(value)))) throw new Error('JSON numbers must be finite and representable without truncation.');
|
|
593
|
+
return value;
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
function programSchemaProblem(value, schema, path = 'input', root = schema, seen = new Set()) {
|
|
597
|
+
if (schema === true) return '';
|
|
598
|
+
if (schema === false) return `${path} is not allowed.`;
|
|
599
|
+
if (!programObject(schema)) return `${path} has a malformed schema.`;
|
|
600
|
+
if (schema.$ref !== undefined) {
|
|
601
|
+
if (typeof schema.$ref !== 'string' || !schema.$ref.startsWith('#/')) return `${path} has an unsupported schema reference.`;
|
|
602
|
+
let target = root;
|
|
603
|
+
for (const key of schema.$ref.slice(2).split('/')) target = target?.[key.replace(/~1/g, '/').replace(/~0/g, '~')];
|
|
604
|
+
if (!target || seen.has(target)) return `${path} has an unresolved schema reference.`;
|
|
605
|
+
const refs = new Set(seen); refs.add(target);
|
|
606
|
+
const problem = programSchemaProblem(value, target, path, root, refs);
|
|
607
|
+
if (problem) return problem;
|
|
608
|
+
}
|
|
609
|
+
if (Array.isArray(schema.oneOf) && schema.oneOf.filter(variant => !programSchemaProblem(value, variant, path, root, seen)).length !== 1) return `${path} must match exactly one allowed shape.`;
|
|
610
|
+
if (Array.isArray(schema.anyOf) && !schema.anyOf.some(variant => !programSchemaProblem(value, variant, path, root, seen))) return `${path} does not match an allowed shape.`;
|
|
611
|
+
if (Array.isArray(schema.allOf)) for (const variant of schema.allOf) { const problem = programSchemaProblem(value, variant, path, root, seen); if (problem) return problem; }
|
|
612
|
+
if (schema.not && !programSchemaProblem(value, schema.not, path, root, seen)) return `${path} matches a forbidden shape.`;
|
|
613
|
+
if (schema.if) {
|
|
614
|
+
const branch = programSchemaProblem(value, schema.if, path, root, seen) ? schema.else : schema.then;
|
|
615
|
+
if (branch !== undefined) { const problem = programSchemaProblem(value, branch, path, root, seen); if (problem) return problem; }
|
|
616
|
+
}
|
|
617
|
+
const matchesType = type => type === 'object' ? programObject(value) : type === 'array' ? Array.isArray(value)
|
|
618
|
+
: type === 'null' ? value === null : type === 'integer' ? typeof value === 'number' && Number.isFinite(value) && Number.isInteger(value)
|
|
619
|
+
: type === 'number' ? typeof value === 'number' && Number.isFinite(value) : typeof value === type;
|
|
620
|
+
if (schema.type !== undefined && !(Array.isArray(schema.type) ? schema.type : [schema.type]).some(matchesType)) return `${path} must be ${Array.isArray(schema.type) ? schema.type.join(' or ') : schema.type}.`;
|
|
621
|
+
if (Object.hasOwn(schema, 'const') && !programEqual(value, schema.const)) return `${path} must equal ${JSON.stringify(schema.const)}.`;
|
|
622
|
+
if (Array.isArray(schema.enum) && !schema.enum.some(item => programEqual(item, value))) return `${path} must be one of ${JSON.stringify(schema.enum)}.`;
|
|
623
|
+
if (typeof value === 'number') {
|
|
624
|
+
if (!Number.isFinite(value)) return `${path} must be finite.`;
|
|
625
|
+
if (schema.minimum !== undefined && value < schema.minimum || schema.maximum !== undefined && value > schema.maximum) return `${path} is outside the allowed numeric range.`;
|
|
626
|
+
if (typeof schema.exclusiveMinimum === 'number' && value <= schema.exclusiveMinimum || typeof schema.exclusiveMaximum === 'number' && value >= schema.exclusiveMaximum) return `${path} is outside the allowed exclusive numeric range.`;
|
|
627
|
+
if (schema.multipleOf !== undefined && !programMultiple(value, schema.multipleOf)) return `${path} must be a multiple of ${schema.multipleOf}.`;
|
|
628
|
+
}
|
|
629
|
+
if (typeof value === 'string') {
|
|
630
|
+
const length = [...value].length;
|
|
631
|
+
if (schema.minLength !== undefined && length < schema.minLength || schema.maxLength !== undefined && length > schema.maxLength) return `${path} has an invalid length.`;
|
|
632
|
+
if (schema.pattern !== undefined) { try { if (!new RegExp(schema.pattern, 'u').test(value)) return `${path} does not match ${schema.pattern}.`; } catch { return `${path} has an invalid schema pattern.`; } }
|
|
633
|
+
}
|
|
634
|
+
if (Array.isArray(value)) {
|
|
635
|
+
if (schema.minItems !== undefined && value.length < schema.minItems || schema.maxItems !== undefined && value.length > schema.maxItems) return `${path} has an invalid number of items.`;
|
|
636
|
+
if (schema.uniqueItems && value.some((item, index) => value.slice(0, index).some(previous => programEqual(previous, item)))) return `${path} requires unique items.`;
|
|
637
|
+
for (const [index, item] of value.entries()) {
|
|
638
|
+
const child = Array.isArray(schema.prefixItems) && index < schema.prefixItems.length ? schema.prefixItems[index] : schema.items;
|
|
639
|
+
if (child !== undefined) { const problem = programSchemaProblem(item, child, `${path}[${index}]`, root, seen); if (problem) return problem; }
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
if (programObject(value)) {
|
|
643
|
+
const keys = Object.keys(value), properties = programObject(schema.properties) ? schema.properties : {};
|
|
644
|
+
if (schema.minProperties !== undefined && keys.length < schema.minProperties || schema.maxProperties !== undefined && keys.length > schema.maxProperties) return `${path} has an invalid number of properties.`;
|
|
645
|
+
for (const name of schema.required ?? []) if (!Object.hasOwn(value, name)) return `${path} requires ${name}.`;
|
|
646
|
+
for (const key of keys) {
|
|
647
|
+
let child;
|
|
648
|
+
if (Object.hasOwn(properties, key)) child = properties[key];
|
|
649
|
+
else if (schema.additionalProperties === false) return `${path} does not allow ${key}.`;
|
|
650
|
+
else child = schema.additionalProperties;
|
|
651
|
+
if (child !== undefined) { const problem = programSchemaProblem(value[key], child, `${path}.${key}`, root, seen); if (problem) return problem; }
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
return '';
|
|
655
|
+
}
|
|
656
|
+
function programSchemaShape(schema) {
|
|
657
|
+
if (!programObject(schema) || !Object.keys(schema).length) return false;
|
|
658
|
+
if (schema.type !== undefined && (typeof schema.type !== 'string' || !['object', 'array', 'string', 'number', 'integer', 'boolean', 'null'].includes(schema.type))) return false;
|
|
659
|
+
if (schema.type === undefined && !['oneOf', 'anyOf', 'allOf', '$ref'].some(key => Object.hasOwn(schema, key))) return false;
|
|
660
|
+
if (schema.type === 'object' && (!programObject(schema.properties) || !Array.isArray(schema.required) || schema.additionalProperties !== false)) return false;
|
|
661
|
+
if (schema.required !== undefined && (!Array.isArray(schema.required) || schema.required.some(key => typeof key !== 'string') || new Set(schema.required).size !== schema.required.length)) return false;
|
|
662
|
+
if (schema.properties !== undefined && (!programObject(schema.properties) || !Object.values(schema.properties).every(programSchemaShape))) return false;
|
|
663
|
+
if (schema.type === 'object' && schema.required?.some(key => !Object.hasOwn(schema.properties ?? {}, key))) return false;
|
|
664
|
+
if (schema.type === 'array' && !programSchemaShape(schema.items)) return false;
|
|
665
|
+
for (const key of ['oneOf', 'anyOf', 'allOf']) if (schema[key] !== undefined && (!Array.isArray(schema[key]) || !schema[key].length || !schema[key].every(programSchemaShape))) return false;
|
|
666
|
+
for (const key of ['minLength', 'maxLength', 'minItems', 'maxItems', 'minProperties', 'maxProperties']) if (schema[key] !== undefined && (!Number.isInteger(schema[key]) || schema[key] < 0)) return false;
|
|
667
|
+
for (const key of ['minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf']) if (schema[key] !== undefined && (typeof schema[key] !== 'number' || !Number.isFinite(schema[key]))) return false;
|
|
668
|
+
if (schema.multipleOf !== undefined && schema.multipleOf <= 0) return false;
|
|
669
|
+
if (schema.pattern !== undefined) { try { if (typeof schema.pattern !== 'string') return false; new RegExp(schema.pattern, 'u'); } catch { return false; } }
|
|
670
|
+
return true;
|
|
671
|
+
}
|
|
672
|
+
function programUsage(file, entries, reason = '') {
|
|
673
|
+
const operations = entries.map(entry => {
|
|
674
|
+
const properties = programObject(entry.input_schema?.properties) ? entry.input_schema.properties : {};
|
|
675
|
+
const required = new Set(entry.input_schema?.required ?? []);
|
|
676
|
+
const fields = Object.entries(properties).map(([name, schema]) => `${required.has(name) ? '' : '['}--${name} <${schema.type ?? 'JSON'}>${required.has(name) ? '' : ']'}`).join(' ');
|
|
677
|
+
return ` ${file || '<prompt>'} ${entry.operation}${fields ? ` ${fields}` : ''} | --input JSON | --input @file`;
|
|
678
|
+
});
|
|
679
|
+
return { door: 'usage', operation: '', input_json: '', exit_code: 2, message: `${reason ? `${reason}\n` : ''}Usage:\n${operations.length ? operations.join('\n') : ` ${file || '<prompt>'} <operation> [arguments]`}` };
|
|
680
|
+
}
|
|
681
|
+
function programInterfaceShape(contract) {
|
|
682
|
+
return programObject(contract) && Array.isArray(contract.entries) && contract.entries.length > 0 && Array.isArray(contract.conventions ?? []) &&
|
|
683
|
+
contract.entries.every(entry => programObject(entry) && typeof entry.operation === 'string' && entry.operation && programSchemaShape(entry.input_schema) && programSchemaShape(entry.result_schema)) &&
|
|
684
|
+
new Set(contract.entries.map(entry => entry.operation)).size === contract.entries.length;
|
|
685
|
+
}
|
|
686
|
+
function programFlagValue(text, schema) {
|
|
687
|
+
if (schema?.type === 'string') return text;
|
|
688
|
+
if (schema?.type === 'boolean') { if (!['true', 'false'].includes(text)) throw new Error('Expected true or false.'); return text === 'true'; }
|
|
689
|
+
if (schema?.type === 'number' || schema?.type === 'integer') {
|
|
690
|
+
if (!/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(text)) throw new Error(`Expected a JSON ${schema.type}.`);
|
|
691
|
+
const value = programParse(text);
|
|
692
|
+
if (!Number.isFinite(value) || schema.type === 'integer' && !Number.isInteger(value)) throw new Error(`Expected a finite ${schema.type}.`);
|
|
693
|
+
return value;
|
|
694
|
+
}
|
|
695
|
+
if (schema?.oneOf?.some(variant => variant.type === 'string')) {
|
|
696
|
+
try { const value = programParse(text); if (!programSchemaProblem(value, schema)) return value; } catch { /* A string need not be JSON encoded. */ }
|
|
697
|
+
return text;
|
|
698
|
+
}
|
|
699
|
+
return programParse(text);
|
|
700
|
+
}
|
|
701
|
+
export function prepareProgramInvocation(input = {}) {
|
|
702
|
+
let entries = [];
|
|
703
|
+
const file = typeof input?.file === 'string' ? input.file : '';
|
|
704
|
+
const usage = reason => programUsage(file, entries, reason);
|
|
705
|
+
const selected = (door, operation = '', value) => ({ door, operation, input_json: value === undefined ? '' : JSON.stringify(value), exit_code: 0, message: '' });
|
|
706
|
+
try {
|
|
707
|
+
if (!programObject(input) || !file || !Array.isArray(input.argv ?? []) || (input.argv ?? []).some(word => typeof word !== 'string')) return usage('Expected a prompt path and string arguments.');
|
|
708
|
+
if (input.stdin !== undefined && typeof input.stdin !== 'string' || input.stdin_tty !== undefined && typeof input.stdin_tty !== 'boolean' || input.serve !== undefined && typeof input.serve !== 'boolean') return usage('Malformed input stream or serve option.');
|
|
709
|
+
const argv = [...(input.argv ?? [])], tty = input.stdin_tty ?? true;
|
|
710
|
+
if (/\.json$/i.test(file) && !/\.prompt\.md$/i.test(file)) return selected('screen');
|
|
711
|
+
const contract = programParse(input.interface_json);
|
|
712
|
+
if (!programObject(contract) || !Array.isArray(contract.entries) || !contract.entries.length || !Array.isArray(contract.conventions ?? [])) return usage('The prompt interface has no valid entries.');
|
|
713
|
+
entries = contract.entries;
|
|
714
|
+
if (!programInterfaceShape(contract)) return usage('The prompt interface is malformed.');
|
|
715
|
+
const isHttp = programHttpEntry;
|
|
716
|
+
const httpEntries = entries.filter(isHttp);
|
|
717
|
+
if (input.serve === true) return httpEntries.length ? selected('http') : usage('The prompt has no named HTTP route.');
|
|
718
|
+
if (httpEntries.length === entries.length && !argv.length) return selected('http');
|
|
719
|
+
const cliEntries = entries.filter((entry, index) => ['input_schema', 'result_schema'].every(kind => (contract.conventions ?? []).some(row => row?.convention === 'cli' && row.path === `/entries/${index}/${kind}`)));
|
|
720
|
+
if (cliEntries.length > 1) return usage('The prompt has more than one CLI entry.');
|
|
721
|
+
if (cliEntries.length === 1) {
|
|
722
|
+
const entry = cliEntries[0], value = { argv };
|
|
723
|
+
if (Object.hasOwn(entry.input_schema.properties ?? {}, 'stdin') && (!tty || entry.input_schema.required?.includes('stdin'))) value.stdin = tty ? '' : input.stdin ?? '';
|
|
724
|
+
const problem = programSchemaProblem(value, entry.input_schema);
|
|
725
|
+
if (problem) return usage(problem);
|
|
726
|
+
return selected(argv.length ? 'cli' : 'shell', entry.operation, value);
|
|
727
|
+
}
|
|
728
|
+
const typedEntries = entries.filter(entry => !isHttp(entry));
|
|
729
|
+
if (!typedEntries.length) return usage('This prompt exposes named HTTP routes; start its HTTP server.');
|
|
730
|
+
let entry = typedEntries[0];
|
|
731
|
+
if (typedEntries.length > 1) {
|
|
732
|
+
const operation = argv.shift();
|
|
733
|
+
entry = typedEntries.find(candidate => candidate.operation === operation);
|
|
734
|
+
if (!entry) return usage(`Choose an operation: ${typedEntries.map(candidate => candidate.operation).join(', ')}.`);
|
|
735
|
+
}
|
|
736
|
+
if (argv.includes('--help')) return usage();
|
|
737
|
+
let value;
|
|
738
|
+
if (!argv.length) value = tty ? {} : programParse(input.stdin ?? '');
|
|
739
|
+
else if (argv[0] === '--input') {
|
|
740
|
+
if (argv.length !== 2) return usage('Whole JSON input cannot be combined with field flags.');
|
|
741
|
+
const text = argv[1];
|
|
742
|
+
if (text.startsWith('@') && (typeof input.input_file_json !== 'string' || text.length === 1)) return usage('The requested input file is unavailable.');
|
|
743
|
+
value = programParse(text.startsWith('@') ? input.input_file_json : text);
|
|
744
|
+
} else {
|
|
745
|
+
value = Object.create(null);
|
|
746
|
+
const properties = entry.input_schema.properties ?? {};
|
|
747
|
+
for (let index = 0; index < argv.length; index += 2) {
|
|
748
|
+
const flag = argv[index], text = argv[index + 1];
|
|
749
|
+
if (!flag.startsWith('--') || flag.length === 2 || text === undefined) return usage(`Each field flag needs a value: ${flag}.`);
|
|
750
|
+
const name = flag.slice(2);
|
|
751
|
+
if (!Object.hasOwn(properties, name)) return usage(`Unknown field: ${flag}.`);
|
|
752
|
+
const schema = properties[name];
|
|
753
|
+
if (schema.type === 'array') {
|
|
754
|
+
if (!Object.hasOwn(value, name)) value[name] = [];
|
|
755
|
+
value[name].push(programFlagValue(text, schema.items));
|
|
756
|
+
} else {
|
|
757
|
+
if (Object.hasOwn(value, name)) return usage(`Duplicate field: ${flag}.`);
|
|
758
|
+
value[name] = programFlagValue(text, schema);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
const problem = programSchemaProblem(value, entry.input_schema);
|
|
763
|
+
return problem ? usage(problem) : selected('typed', entry.operation, value);
|
|
764
|
+
} catch (error) { return usage(`Invalid input: ${error?.message ?? 'malformed JSON or interface'}`); }
|
|
765
|
+
}
|
|
766
|
+
export function planProgramSession(input = {}) {
|
|
767
|
+
const refusal = message => ({ action: 'refuse', initial_world_json: '{}', simulation_json: '{}', message });
|
|
768
|
+
if (input.session_state === 'unknown') return refusal('Read the pending result before reusing or replacing this program session.');
|
|
769
|
+
try {
|
|
770
|
+
let world = {}, simulation = {};
|
|
771
|
+
const explicit = input.data_json !== undefined && input.data_json !== null;
|
|
772
|
+
if (explicit) {
|
|
773
|
+
const data = programParse(input.data_json);
|
|
774
|
+
if (!programObject(data)) return refusal('Starting data must be a JSON object.');
|
|
775
|
+
if (Object.hasOwn(data, 'initial_world')) { world = data.initial_world; simulation = Object.hasOwn(data, 'simulation') ? data.simulation : {}; }
|
|
776
|
+
else world = data;
|
|
777
|
+
} else if (input.fresh !== true) {
|
|
778
|
+
if (input.saved_data_json !== undefined && input.saved_data_json !== null) world = programParse(input.saved_data_json);
|
|
779
|
+
simulation = programParse(input.saved_simulation_json ?? '{}');
|
|
780
|
+
}
|
|
781
|
+
if (!programObject(world) || !programObject(simulation)) return refusal('Program world and simulation must both be JSON objects.');
|
|
782
|
+
let action;
|
|
783
|
+
if (!input.session_id || ['missing', 'stopped'].includes(input.session_state)) action = 'create';
|
|
784
|
+
else if (input.fresh === true || explicit || input.saved_source !== input.current_source) action = 'replace';
|
|
785
|
+
else if (input.session_state === 'running') action = 'reuse';
|
|
786
|
+
else if (input.session_state === 'paused') action = 'reopen';
|
|
787
|
+
else return refusal('The program session state is not confirmed. Read its pending result first.');
|
|
788
|
+
return { action, initial_world_json: JSON.stringify(world), simulation_json: JSON.stringify(simulation), message: '' };
|
|
789
|
+
} catch { return refusal('Program data and simulation must contain valid JSON objects.'); }
|
|
790
|
+
}
|
|
791
|
+
export function planProgramCase(input = {}) {
|
|
792
|
+
if (input.state !== 'confirmed') return { write: false, reason: 'unconfirmed' };
|
|
793
|
+
if (input.expected_run_id !== input.current_run_id) return { write: false, reason: 'superseded' };
|
|
794
|
+
if (input.terminal !== true) return { write: false, reason: 'non-terminal' };
|
|
795
|
+
if (typeof input.answer !== 'string' || input.answer.trim().toLowerCase() !== 'y') return { write: false, reason: 'declined' };
|
|
796
|
+
return { write: true, reason: 'confirmed' };
|
|
797
|
+
}
|