@promptdriven/runtime-client 0.0.0-stage → 1.0.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 +105 -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 +943 -0
- package/src/runtime/lint-call-preflight.mjs +19 -0
- package/src/runtime/lint-compatibility-display.mjs +62 -0
- package/src/runtime/product-composition.mjs +384 -0
- package/src/runtime/runtime-binding-plan.mjs +145 -0
- package/src/runtime/runtime-bindings.mjs +71 -0
- package/src/runtime/runtime-check-plan.mjs +411 -0
- package/src/runtime/runtime-client.mjs +6323 -0
- package/src/runtime/runtime-lint-receipt.mjs +25 -0
- package/src/runtime/runtime-markdown.mjs +215 -0
- package/src/runtime/runtime-outcome.mjs +407 -0
- package/src/runtime/runtime-output.mjs +714 -0
- package/src/runtime/runtime-preflight.mjs +3118 -0
- package/src/runtime/runtime-slots.mjs +391 -0
- package/src/runtime/runtime-workspace-migration.mjs +70 -0
- package/src/runtime/runtime-workspace.mjs +52 -0
- package/src/runtime/scenario-json.mjs +91 -0
- package/src/runtime/secret-redaction.mjs +53 -0
- package/src/runtime/try-doors.mjs +231 -0
- package/src/runtime/try-http.mjs +259 -0
- package/src/runtime/try-mcp.mjs +223 -0
- package/src/runtime/try-session.mjs +95 -0
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// Generated from prompts/cli/secret-redaction.prompt.md (sha256: eec6ecce797bc1cf5ec5231c8771b115b5a72b8d9c946e3d1dadd5c9109bbf56).
|
|
2
|
+
// Owned by prompts/cli/secret-redaction.prompt.md.
|
|
3
|
+
const SECRET = /token|password|secret|api[_-]?key|authorization|cookie|credential/i;
|
|
4
|
+
const remembered = new Set();
|
|
5
|
+
const secretName = /token|secret|password|passwd|credential|authorization|cookie|api[_-]?key|_key$/i;
|
|
6
|
+
export function rememberSecrets(...values) {
|
|
7
|
+
for (const value of values) if (typeof value === 'string' && value) remembered.add(value);
|
|
8
|
+
}
|
|
9
|
+
export function knownSecretValues(env = process.env, secrets = []) {
|
|
10
|
+
return [...new Set([...remembered, ...secrets,
|
|
11
|
+
...[process.env, env].flatMap(source => Object.entries(source ?? {})
|
|
12
|
+
.filter(([name,value]) => secretName.test(name) && typeof value === 'string' && value)
|
|
13
|
+
.map(([,value]) => value))])].filter(value => typeof value === 'string' && value);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// Keep undecided raw text only for the longest possible match. The second
|
|
17
|
+
// callback argument lets evidence consumers count original bytes and lines.
|
|
18
|
+
export function redactingValues(emit, secrets) {
|
|
19
|
+
const values = [...new Set(secrets)].filter(value => typeof value === 'string' && value);
|
|
20
|
+
const overlap = Math.max(0, ...values.map(value => value.length - 1));
|
|
21
|
+
let pending = '';
|
|
22
|
+
const drain = final => {
|
|
23
|
+
const limit = final ? pending.length : Math.max(0, pending.length - overlap);
|
|
24
|
+
let offset = 0;
|
|
25
|
+
while (offset < limit) {
|
|
26
|
+
let start = -1, matched = '';
|
|
27
|
+
for (const value of values) {
|
|
28
|
+
const index = pending.indexOf(value, offset);
|
|
29
|
+
if (index >= 0 && (start < 0 || index < start || index === start && value.length > matched.length)) {
|
|
30
|
+
start = index; matched = value;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (start < 0 || start >= limit) break;
|
|
34
|
+
if (start > offset) emit(pending.slice(offset,start), pending.slice(offset,start));
|
|
35
|
+
emit('[redacted]', matched);
|
|
36
|
+
offset = start + matched.length;
|
|
37
|
+
}
|
|
38
|
+
if (offset < limit) { emit(pending.slice(offset,limit), pending.slice(offset,limit)); offset = limit; }
|
|
39
|
+
pending = pending.slice(offset);
|
|
40
|
+
};
|
|
41
|
+
return {write(text) { pending += text; drain(false); }, end() { drain(true); }};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function redactSecrets(value, secrets = []) {
|
|
45
|
+
let redacted = '';
|
|
46
|
+
const stream = redactingValues(text => { redacted += text; }, knownSecretValues(process.env,secrets));
|
|
47
|
+
stream.write(String(value ?? '')); stream.end();
|
|
48
|
+
value = redacted;
|
|
49
|
+
value=value.replace(/https?:\/\/[^\s"'<>]+/g,text=>{try{const url=new URL(text);let changed=false;if(url.username||url.password){url.username='';url.password='';changed=true;}for(const key of [...url.searchParams.keys()])if(SECRET.test(key)||/^(?:key|auth|signature)$/i.test(key)){url.searchParams.set(key,'[redacted]');changed=true;}return changed?url.href:text;}catch{return text.replace(/(https?:\/\/)[^\s/@]+(?::[^\s/@]*)?@/gi,'$1[redacted]@');}});
|
|
50
|
+
value = value.replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?(?:-----END [^-]*PRIVATE KEY-----|$)/g,'[redacted]');
|
|
51
|
+
value = value.replace(/\b(authorization)["']?\s*[:=]\s*[^\r\n]+/gi, '$1=[redacted]');
|
|
52
|
+
return value.replace(/\b(?:gh[pousr]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]{12,}|AIza[A-Za-z0-9_-]+|ya29\.[A-Za-z0-9_.-]+)\b/g,'[redacted]').replace(/\b(?:Bearer|Basic)\s+\S+/gi,'[redacted]').replace(/\b(key|token|password|secret|api[_-]?key|authorization|cookie|credential)["']?\s*[:=]\s*(?:"(?:\\.|[^"\\])*(?:"|$)|'(?:\\.|[^'\\])*(?:'|$)|[^\s,;]+)/gi,'$1=[redacted]').replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,'');
|
|
53
|
+
}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
// Generated from prompts/cli/try-doors.prompt.md (sha256: a7f657473a8a63a20e48ec6b5e52261695af9226d6bb3290a00c23f217975763).
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { accessSync, chmodSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
6
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
7
|
+
import { findTests, gitFiles, readPrompt, captureSource, executableInterfaceText } from './runtime-preflight.mjs';
|
|
8
|
+
import { cleanText, tryUsage, tryUsageLine } from './runtime-output.mjs';
|
|
9
|
+
import { runDoorCall, saveDoorCaseResult, acquireCaseWriteOwnership, defaultLineReader } from './runtime-client.mjs';
|
|
10
|
+
|
|
11
|
+
const WRAPPER_EXIT = 125;
|
|
12
|
+
const hash = text => createHash('sha256').update(text).digest('hex');
|
|
13
|
+
const quote = word => /^[A-Za-z0-9_./:@%+=,-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`;
|
|
14
|
+
const read = path => JSON.parse(readFileSync(path, 'utf8'));
|
|
15
|
+
const fail = message => { const e = new Error(message); e.exitCode = WRAPPER_EXIT; throw e; };
|
|
16
|
+
function checkEffectivePrompts(root, rawHashes, effectiveHashes) {
|
|
17
|
+
const visible=new Set(gitFiles(root));
|
|
18
|
+
for (const path of Object.keys(rawHashes ?? {})) {
|
|
19
|
+
const prompt=readPrompt(root,visible,path);
|
|
20
|
+
if (!prompt.text) fail('A prompt is unavailable. Run pdd simulate STORY --cli --new.');
|
|
21
|
+
if (effectiveHashes?.[path]) {
|
|
22
|
+
if (hash(executableInterfaceText(prompt.text))!==effectiveHashes[path]) fail('A prompt or shared contract changed since this Try. Run pdd simulate STORY --cli --new.');
|
|
23
|
+
} else if (prompt.references?.length) fail('This Try reference baseline is unavailable. Run pdd simulate STORY --cli --new.');
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function regular(path) {
|
|
27
|
+
const stat = lstatSync(path);
|
|
28
|
+
if (stat.isSymbolicLink()) fail('Refusing a symbolic link in Try files.');
|
|
29
|
+
if (!stat.isFile() || stat.nlink !== 1) fail('A Try file must be a regular file with one link.');
|
|
30
|
+
}
|
|
31
|
+
function writePrivate(path, value) {
|
|
32
|
+
if (existsSync(path)) regular(path);
|
|
33
|
+
const temp = `${path}.${process.pid}.tmp`;
|
|
34
|
+
const fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
35
|
+
try { writeFileSync(fd, JSON.stringify(value, null, 2) + '\n'); } finally { closeSync(fd); }
|
|
36
|
+
renameSync(temp, path);
|
|
37
|
+
}
|
|
38
|
+
function safeBin(root) {
|
|
39
|
+
let path = root;
|
|
40
|
+
for (const part of ['.pdd', 'try', 'bin']) {
|
|
41
|
+
path = join(path, part);
|
|
42
|
+
try { mkdirSync(path, { mode: 0o700 }); } catch (e) { if (e.code !== 'EEXIST') throw e; }
|
|
43
|
+
const stat = lstatSync(path);
|
|
44
|
+
if (stat.isSymbolicLink()) fail(`Refusing a symbolic link at ${part}.`);
|
|
45
|
+
if (!stat.isDirectory()) fail(`${part} is not a folder.`);
|
|
46
|
+
}
|
|
47
|
+
return path;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function cliEntries(context, test) {
|
|
51
|
+
const entries = new Map();
|
|
52
|
+
for (const step of Array.isArray(test.doc?.steps) ? test.doc.steps : []) {
|
|
53
|
+
if (!step || typeof step.entry_path !== 'string' || typeof step.operation !== 'string') continue;
|
|
54
|
+
const prompt = readPrompt(context.root, context.visible, step.entry_path);
|
|
55
|
+
const authoredEntries = Array.isArray(prompt.interface?.entries) ? prompt.interface.entries : [];
|
|
56
|
+
const index = authoredEntries.findIndex(e => e?.operation === step.operation);
|
|
57
|
+
if (!(index >= 0)) continue;
|
|
58
|
+
const conventions = Array.isArray(prompt.interface.conventions) ? prompt.interface.conventions : [];
|
|
59
|
+
if (!['input_schema', 'result_schema'].every(key => conventions.some(c => c?.path === `/entries/${index}/${key}` && c.convention === 'cli'))) continue;
|
|
60
|
+
entries.set(`${step.entry_path}#${step.operation}`, { step, prompt, entry: authoredEntries[index] });
|
|
61
|
+
}
|
|
62
|
+
return entries;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function typedUnmappedStory(context, test) {
|
|
66
|
+
const steps = (Array.isArray(test.doc?.steps) ? test.doc.steps : []).filter(step => step && typeof step.entry_path === 'string' && typeof step.operation === 'string');
|
|
67
|
+
for (const step of steps) {
|
|
68
|
+
const prompt = readPrompt(context.root, context.visible, step.entry_path);
|
|
69
|
+
const entry = (Array.isArray(prompt.interface?.entries) ? prompt.interface.entries : []).find(entry => entry?.operation === step.operation);
|
|
70
|
+
if (typeof entry?.input_schema?.title === 'string' && /^HTTP (GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) \/\S*$/.test(entry.input_schema.title)) return false;
|
|
71
|
+
}
|
|
72
|
+
const mapPath = context.appMap === undefined ? ['app-map.json', 'app/app-map.json'].find(path => context.visible.has(path)) : context.appMap;
|
|
73
|
+
if (mapPath) {
|
|
74
|
+
let screens;
|
|
75
|
+
try { screens = read(join(context.root, mapPath)).screens; } catch { return false; }
|
|
76
|
+
if (Array.isArray(screens) && steps.some(step => screens.some(screen => screen?.source === 'operation' && screen.prompt_path === step.entry_path && screen.operation === step.operation))) return false;
|
|
77
|
+
}
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function cliEntry(context, test) {
|
|
82
|
+
const entries = cliEntries(context, test);
|
|
83
|
+
if (entries.size !== 1) {
|
|
84
|
+
if (entries.size) fail('This Story uses more than one command-line program. Choose a Story with one command-line program.');
|
|
85
|
+
const found = context.found ?? (context.ports?.findTests ? context.ports.findTests({ root: context.root, files: [...context.visible] }) : findTests({ root: context.root, files: [...context.visible] }, context.ports));
|
|
86
|
+
const names = [...new Set(found.tests.filter(candidate => {
|
|
87
|
+
// Other Stories supply advice only; their missing context is independent.
|
|
88
|
+
try { return cliEntries(context, candidate).size === 1; } catch { return false; }
|
|
89
|
+
}).map(candidate => candidate.story))].sort();
|
|
90
|
+
fail(`This Story is not a command-line program. ${names.length ? `These are: ${names.join(', ')}.` : 'No Stories are command-line programs.'}${typedUnmappedStory(context, test) ? `\npdd simulate ${quote(test.story)} opens its Form tab.` : ''}`);
|
|
91
|
+
}
|
|
92
|
+
const value = [...entries.values()][0];
|
|
93
|
+
const heading = value.prompt.text.match(/^#\s+(.+?)\s*$/m)?.[1]?.replace(/^`([^`]+)`$/, '$1');
|
|
94
|
+
if (!/^[A-Za-z][A-Za-z0-9._-]{0,63}$/.test(heading ?? '') || ['pdd', 'node', 'gh', 'git'].includes(heading?.toLowerCase())) fail('Name the program in the CLI prompt’s first heading, for example # tipjar; pdd, node, gh and git are reserved (RUNBOOK §6).');
|
|
95
|
+
return { ...value, name: heading };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export async function openCli(context, test, sessionId, options) {
|
|
99
|
+
const { root, ports, store, identity, origin } = context;
|
|
100
|
+
const { step, prompt, entry, name } = cliEntry(context, test);
|
|
101
|
+
const record = store.repo(root).tries?.[test.path];
|
|
102
|
+
if (record?.prompt_hashes?.[step.entry_path] !== hash(readFileSync(join(root,step.entry_path)))) fail('The CLI prompt changed or this Try has no source record. Run pdd simulate STORY --cli --new.');
|
|
103
|
+
for (const [path, expected] of Object.entries(record.prompt_hashes)) if (hash(readFileSync(join(root, path))) !== expected) fail('A prompt dependency changed since this Try. Run pdd simulate STORY --cli --new.');
|
|
104
|
+
checkEffectivePrompts(root,record.prompt_hashes,record.effective_prompt_hashes);
|
|
105
|
+
const bin = safeBin(root), shim = join(bin, name);
|
|
106
|
+
if (existsSync(shim)) {
|
|
107
|
+
regular(shim);
|
|
108
|
+
if (!readFileSync(shim, 'utf8').startsWith(`#!/bin/sh\n# PDD Try launcher v1\n`)) fail(`Refusing to overwrite ${shim}; it is not a PDD Try launcher.`);
|
|
109
|
+
} else { try { lstatSync(shim); fail('Refusing a symbolic link in Try files.'); } catch (e) { if (e.code !== 'ENOENT') throw e; } }
|
|
110
|
+
// A local exclude is preferable to changing the project's tracked .gitignore.
|
|
111
|
+
const { spawnSync } = await import('node:child_process');
|
|
112
|
+
const git = spawnSync('git', ['rev-parse', '--git-path', 'info/exclude'], { cwd: root, encoding: 'utf8' });
|
|
113
|
+
if (git.status !== 0) fail('Could not locate the repository’s local Git exclude file.');
|
|
114
|
+
const exclude = git.stdout.trim().startsWith('/') ? git.stdout.trim() : join(root, git.stdout.trim());
|
|
115
|
+
if (existsSync(exclude)) regular(exclude);
|
|
116
|
+
mkdirSync(dirname(exclude), { recursive: true });
|
|
117
|
+
if (realpathSync(dirname(exclude)) !== dirname(exclude)) fail('Refusing a symbolic link in the Git exclude path.');
|
|
118
|
+
const ignored = existsSync(exclude) ? readFileSync(exclude, 'utf8') : '';
|
|
119
|
+
if (!ignored.split('\n').includes('/.pdd/try/')) writeFileSync(exclude, `${ignored}${ignored.endsWith('\n') || !ignored ? '' : '\n'}/.pdd/try/\n`);
|
|
120
|
+
const descriptorPath = join(store.folder('tries'), `${sessionId}.door.json`);
|
|
121
|
+
if (existsSync(descriptorPath) && read(descriptorPath).promptHash !== hash(prompt.text)) fail('The CLI prompt changed since this Try. Run pdd simulate STORY --cli --new.');
|
|
122
|
+
const ghPath = (ports.env.PATH || process.env.PATH || '').split(':').map(folder => join(folder, 'gh')).find(path => { try { accessSync(path, constants.X_OK); return (lstatSync(path).isFile() || lstatSync(path).isSymbolicLink()) && !readFileSync(path).subarray(0, 64).toString().includes('PDD Try launcher v1'); } catch { return false; } });
|
|
123
|
+
let metadata;
|
|
124
|
+
try { const reply = await context.runtime.send(`/v1/try/${sessionId}/model`, { method: 'GET' }, 30_000); if (reply.status === 200) metadata = reply.json; } catch { /* Accounting cannot block an otherwise usable CLI. */ }
|
|
125
|
+
const usage = tryUsage(metadata);
|
|
126
|
+
ports.stderr.write(`${tryUsageLine(usage)}\n`);
|
|
127
|
+
const descriptor = { callCap: usage.cap, version: 1, root, sessionId, origin, login: identity.login, prompt: step.entry_path, operation: step.operation,
|
|
128
|
+
ghPath: ghPath ? resolve(ghPath) : null, promptHashes: record.prompt_hashes, effectivePromptHashes:record.effective_prompt_hashes, name, inputSchema: entry.input_schema, originalPath: test.path, storyPath: test.doc.story_path, criteria: test.doc.criteria,
|
|
129
|
+
criterion: step.checks[0]?.criterion_id, storyHash: hash(readFileSync(join(root, test.doc.story_path))),
|
|
130
|
+
promptHash: hash(prompt.text), stateDir: store.dir, repoState: join(store.folder('repos'), `${store.repoKey(root)}.json`) };
|
|
131
|
+
writePrivate(descriptorPath, descriptor);
|
|
132
|
+
const moduleUrl = ports.tryLauncherUrl ?? pathToFileURL(join(dirname(fileURLToPath(import.meta.url)), 'try-doors.mjs')).href;
|
|
133
|
+
const script = `import(process.argv[1]).then(async ({ runShim }) => { process.exitCode = await runShim(process.argv[2], process.argv.slice(3)); }).catch(() => { process.stderr.write('pdd: The installed adapter could not load. Run pdd simulate STORY --cli again.\\n'); process.exitCode = 125; });`;
|
|
134
|
+
const code = `#!/bin/sh\n# PDD Try launcher v1\nexec ${quote(process.execPath)} --input-type=commonjs -e ${quote(script)} -- ${quote(moduleUrl)} ${quote(descriptorPath)} \"$@\"\n`;
|
|
135
|
+
const fd = openSync(shim, constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW, 0o700);
|
|
136
|
+
try { writeFileSync(fd, code); } finally { closeSync(fd); }
|
|
137
|
+
chmodSync(shim, 0o700);
|
|
138
|
+
ports.stdout.write(`Try is ready: ${name}\n${shim}\nexport PATH=${quote(bin)}:"$PATH"\n`);
|
|
139
|
+
const examples = [...new Set(test.doc.steps.filter(s => s.entry_path === step.entry_path && s.operation === step.operation && Array.isArray(s.input?.argv))
|
|
140
|
+
.map(s => [name, ...s.input.argv].map(quote).join(' ')))];
|
|
141
|
+
if (examples.length) ports.stdout.write(`Examples from this Story:\n${examples.map(s => ` ${s}`).join('\n')}\n`);
|
|
142
|
+
if (options['--shell']) {
|
|
143
|
+
const chosen = ports.env.SHELL || '/bin/sh', shell = ['bash', 'zsh', 'sh'].includes(basename(chosen)) ? chosen : '/bin/sh';
|
|
144
|
+
const env = { ...ports.env, PATH: `${bin}:${ports.env.PATH || process.env.PATH || ''}` };
|
|
145
|
+
if (ports.shell) return ports.shell(shell, env);
|
|
146
|
+
return new Promise((done, reject) => { const child = spawn(shell, ['-i'], { cwd: root, env, stdio: 'inherit' }); child.on('error', reject); child.on('exit', (code, signal) => done(code ?? (signal ? 128 : 0))); });
|
|
147
|
+
}
|
|
148
|
+
return 0;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function invalidate(descriptor, path) {
|
|
152
|
+
const last = join(dirname(path), `${descriptor.sessionId}.last.json`);
|
|
153
|
+
writePrivate(last, { state: 'unknown' });
|
|
154
|
+
regular(descriptor.repoState);
|
|
155
|
+
writePrivate(descriptor.repoState, { ...read(descriptor.repoState), last_door: { descriptor: path, last } });
|
|
156
|
+
return last;
|
|
157
|
+
}
|
|
158
|
+
export async function runShim(descriptorPath, argv, givenPorts = {}) {
|
|
159
|
+
const ports = {
|
|
160
|
+
...givenPorts,
|
|
161
|
+
env: givenPorts.env ?? process.env,
|
|
162
|
+
stdout: givenPorts.stdout ?? process.stdout,
|
|
163
|
+
stderr: givenPorts.stderr ?? process.stderr,
|
|
164
|
+
stdin: givenPorts.stdin ?? process.stdin,
|
|
165
|
+
};
|
|
166
|
+
try {
|
|
167
|
+
regular(descriptorPath);
|
|
168
|
+
const d = read(descriptorPath);
|
|
169
|
+
if (d.version !== 1 || !d.sessionId || !d.root || realpathSync(d.root) !== d.root) fail('The Try session record is invalid. Run pdd simulate STORY --cli again.');
|
|
170
|
+
const last = invalidate(d, descriptorPath), input = { argv };
|
|
171
|
+
if (Object.entries(d.promptHashes ?? { [d.prompt]: d.promptHash }).some(([path, expected]) => hash(readFileSync(join(d.root, path))) !== expected)) fail('The CLI prompt changed since this Try. Run pdd simulate STORY --cli --new.');
|
|
172
|
+
checkEffectivePrompts(d.root,d.promptHashes ?? {[d.prompt]:d.promptHash},d.effectivePromptHashes);
|
|
173
|
+
if (d.inputSchema.properties?.stdin && !ports.stdin.isTTY) {
|
|
174
|
+
const parts = []; let bytes = 0;
|
|
175
|
+
for await (const chunk of ports.stdin) { const part = Buffer.from(chunk); bytes += part.length; if (bytes > 1024 * 1024) fail('Piped stdin exceeds 1 MiB.'); parts.push(part); }
|
|
176
|
+
const value = new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(parts));
|
|
177
|
+
input.stdin = value;
|
|
178
|
+
} else if (d.inputSchema.required?.includes('stdin')) input.stdin = '';
|
|
179
|
+
// A person at a terminal sees that a slow command still runs; a pipe or an agent gets only the program's output.
|
|
180
|
+
const note = ports.stderr.isTTY ? setTimeout(() => ports.stderr.write(`pdd: running ${d.name ?? 'the command'} on the Try…\n`), 2000) : null;
|
|
181
|
+
let answer;
|
|
182
|
+
try { answer = await runDoorCall(d, input, { ...ports, ghPath: d.ghPath, env: { ...ports.env, PDD_STATE_DIR: d.stateDir } }); } finally { clearTimeout(note); }
|
|
183
|
+
const result = answer.result;
|
|
184
|
+
if (typeof result.stdout !== 'string' || typeof result.stderr !== 'string' || !Number.isInteger(result.exit_code) || result.exit_code < 0 || result.exit_code > 255 || result.exit_code === WRAPPER_EXIT) fail('The prompt must return stdout, stderr and an exit_code from 0–255 except reserved code 125.');
|
|
185
|
+
writePrivate(last, { state: 'confirmed', id: answer.id, input, result, inputWorld: answer.inputWorld, world: answer.world });
|
|
186
|
+
ports.stdout.write(result.stdout); ports.stderr.write(result.stderr);
|
|
187
|
+
ports.stderr.write(`${result.stderr && !result.stderr.endsWith('\n') ? '\n' : ''}${tryUsageLine(answer.usage, { command: true })}\n`);
|
|
188
|
+
return result.exit_code;
|
|
189
|
+
} catch (e) {
|
|
190
|
+
if (e?.unboundPort) throw e;
|
|
191
|
+
const reason = e.code === 'ENOENT' ? 'No Try session is available. Run pdd simulate STORY --cli again.'
|
|
192
|
+
: e instanceof TypeError && /encoded data/.test(e.message) ? 'Piped stdin must be UTF-8 text.' : cleanText(e.message || 'The command could not run.');
|
|
193
|
+
ports.stderr.write(`pdd: ${reason}\n${tryUsageLine(e.tryUsage ?? tryUsage({}), { command: true })}\n`); return WRAPPER_EXIT;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export async function saveLast({ root, store, identity, ports }) {
|
|
198
|
+
const pointer = store.repo(root).last_door;
|
|
199
|
+
if (!pointer) fail('No last command is available. Run a command through the Try command first.');
|
|
200
|
+
regular(pointer.descriptor); regular(pointer.last);
|
|
201
|
+
const d = read(pointer.descriptor), last = read(pointer.last);
|
|
202
|
+
if (d.root !== root || identity.login !== d.login) fail(`This Try belongs to ${d.login}. Run: gh auth switch -u ${d.login}`);
|
|
203
|
+
if (last.state !== 'confirmed') fail('The last command result is unknown; there is no confirmed output to save.');
|
|
204
|
+
if (last.saved) { ports.stdout.write('The last command is already saved.\n'); return 0; }
|
|
205
|
+
if (hash(readFileSync(join(root, d.storyPath))) !== d.storyHash || Object.entries(d.promptHashes ?? { [d.prompt]: d.promptHash }).some(([path, expected]) => hash(readFileSync(join(root, path))) !== expected)) fail('The Story or prompt changed since this Try. Open a new Try and run the command again.');
|
|
206
|
+
checkEffectivePrompts(root,d.promptHashes ?? {[d.prompt]:d.promptHash},d.effectivePromptHashes);
|
|
207
|
+
const step = { step_id: `try-${last.id}`, entry_path: d.prompt, operation: d.operation, input: last.input,
|
|
208
|
+
checks: [{ criterion_id: d.criterion, target: 'result', path: '', op: 'equals', value: last.result }] };
|
|
209
|
+
(ports?.captureSource ?? ((r, o) => captureSource(r, o, ports)))(root,{tests:[d.originalPath]});
|
|
210
|
+
const saved={ id: last.id, name: 'Recorded terminal command', story_path: d.storyPath, original_path: d.originalPath,
|
|
211
|
+
test: { schema_version: 'prompt-runtime.program-scenario.v1', story_path: d.storyPath, criteria: d.criteria, ...(Object.hasOwn(last,'inputWorld')?{initial_world:last.inputWorld}:{}), steps: [step] } };
|
|
212
|
+
const retained=saveDoorCaseResult(root,saved,{signal:ports.signal,env:ports.env,ports});
|
|
213
|
+
if(retained.kind==='failure')fail(retained.message);
|
|
214
|
+
const refuse=(outcome,error)=>{ports.stderr.write(`pdd: ${error?cleanText(error)+'. ':''}${outcome.message}\n`);return WRAPPER_EXIT;};
|
|
215
|
+
let outcome=retained;
|
|
216
|
+
if(retained.result.state==='pending'){
|
|
217
|
+
let lease;
|
|
218
|
+
try{
|
|
219
|
+
if(ports.caseHandoff){const handoff=await ports.caseHandoff({root,testPath:d.originalPath,signal:ports.signal});if(handoff)lease=await acquireCaseWriteOwnership({root,testPath:d.originalPath,handoff,signal:ports.signal},{...ports,env:ports.env});}
|
|
220
|
+
else if(ports.interactive){ports.stdout.write(`Close the editor for ${d.originalPath}. Hand over this closed file for the pending case apply? y/N\n`);const answers=(ports.lineReader??defaultLineReader)(ports.stdin);try{if(/^y(?:es)?$/i.test((await answers.ask()).trim()))lease=await acquireCaseWriteOwnership({root,testPath:d.originalPath,handoff:{kind:'closed-editor',testPath:d.originalPath},signal:ports.signal},{...ports,env:ports.env});}finally{answers.close();}}
|
|
221
|
+
if(lease)outcome=saveDoorCaseResult(root,saved,{writeOwnership:lease,signal:ports.signal,env:ports.env,ports});
|
|
222
|
+
}catch(error){if(error?.unboundPort)throw error;return refuse(retained,error.message??error);}
|
|
223
|
+
finally{lease?.release();}
|
|
224
|
+
}
|
|
225
|
+
if(outcome.kind==='failure')fail(outcome.message);
|
|
226
|
+
if(outcome.result.state!=='committed')return refuse(outcome);
|
|
227
|
+
writePrivate(pointer.last, { ...last, saved: true });
|
|
228
|
+
ports.stdout.write(`${outcome.message}\n`);
|
|
229
|
+
if (last.inputWorld && Object.keys(last.inputWorld).length) ports.stdout.write('This records observed output. Review the saved-data setup before replaying this case.\n');
|
|
230
|
+
return 0;
|
|
231
|
+
}
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
// Generated from prompts/cli/try-http.prompt.md (sha256: fd02d62d3fa6e26b7f534ce806435737d2afc2a5a709c01c442e2e4e4c9592d1).
|
|
2
|
+
import { createServer, validateHeaderName, validateHeaderValue } from 'node:http';
|
|
3
|
+
import { join, relative } from 'node:path';
|
|
4
|
+
import {loadRuntimeWorkspace} from './runtime-workspace.mjs';
|
|
5
|
+
import { checkInput,captureSource } from './runtime-preflight.mjs';
|
|
6
|
+
import { cleanText, tryUsage, tryUsageHeaders, tryUsageLine } from './runtime-output.mjs';
|
|
7
|
+
import { runDoorCall } from './runtime-client.mjs';
|
|
8
|
+
|
|
9
|
+
const problem = (status, message) => Object.assign(new Error(message), { httpStatus: status });
|
|
10
|
+
const shellWord = word => /^[A-Za-z0-9_./:@%+=,-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`;
|
|
11
|
+
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
12
|
+
const HOP = new Set(['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'content-length']);
|
|
13
|
+
const RESERVED_USAGE = new Set(['x-pdd-ai-calls', 'x-pdd-try-used', 'x-pdd-try-remaining', 'x-pdd-try-cap', 'x-pdd-input-tokens', 'x-pdd-cached-input-tokens', 'x-pdd-usage-source']);
|
|
14
|
+
function primitive(values, schema) {
|
|
15
|
+
if (schema?.type === 'array') return values.map(v => primitive([v], schema.items));
|
|
16
|
+
if (values.length !== 1) throw problem(400, 'A query field was repeated; declare an array to accept repeated values.');
|
|
17
|
+
const value = values[0];
|
|
18
|
+
if (schema?.type === 'string') return value;
|
|
19
|
+
if (schema?.type === 'boolean' && /^(true|false)$/.test(value)) return value === 'true';
|
|
20
|
+
if (['integer', 'number'].includes(schema?.type) && /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(value)) {
|
|
21
|
+
const number = Number(value);
|
|
22
|
+
if (Number.isFinite(number) && (schema.type === 'number' || Number.isInteger(number))) return number;
|
|
23
|
+
}
|
|
24
|
+
throw problem(400, 'A query or path value does not match the prompt’s input type.');
|
|
25
|
+
}
|
|
26
|
+
function pathParams(route, pathname) {
|
|
27
|
+
const wanted = route.path.split('/'), got = pathname.split('/');
|
|
28
|
+
if (wanted.length !== got.length) return null;
|
|
29
|
+
const params = Object.create(null);
|
|
30
|
+
for (let i = 0; i < wanted.length; i++) {
|
|
31
|
+
if (wanted[i].startsWith(':')) {
|
|
32
|
+
try { params[wanted[i].slice(1)] = decodeURIComponent(got[i]); } catch { throw problem(400, 'A path parameter has invalid UTF-8 or escaping.'); }
|
|
33
|
+
} else if (wanted[i] !== got[i]) return null;
|
|
34
|
+
}
|
|
35
|
+
return params;
|
|
36
|
+
}
|
|
37
|
+
function propertiesOf(schema) { return object(schema?.properties) ? schema.properties : {}; }
|
|
38
|
+
function inputFor(entry, req, url, params, text, method) {
|
|
39
|
+
const props = propertiesOf(entry.input_schema), querySchema = propertiesOf(props.query), input = Object.create(null);
|
|
40
|
+
const query = Object.create(null), paramValues = Object.create(null), bodyProps = Object.create(null);
|
|
41
|
+
for (const key of new Set(url.searchParams.keys())) {
|
|
42
|
+
const schema = props.query ? querySchema[key] : props[key];
|
|
43
|
+
if (!schema || ['method', 'path', 'headers', 'body', 'params'].includes(key)) throw problem(400, `The route does not declare query field ${cleanText(key)}.`);
|
|
44
|
+
query[key] = primitive(url.searchParams.getAll(key), schema);
|
|
45
|
+
}
|
|
46
|
+
for (const [key, value] of Object.entries(params)) {
|
|
47
|
+
const schema = props.params ? propertiesOf(props.params)[key] : props[key];
|
|
48
|
+
if (!schema) throw problem(400, 'The prompt does not declare this route parameter.');
|
|
49
|
+
paramValues[key] = primitive([value], schema);
|
|
50
|
+
}
|
|
51
|
+
let body;
|
|
52
|
+
if (text.length) {
|
|
53
|
+
if (props.body?.type === 'string') body = text;
|
|
54
|
+
else {
|
|
55
|
+
try { body = JSON.parse(text); } catch { throw problem(400, 'The request body is not valid JSON.'); }
|
|
56
|
+
if (object(body)) for (const [key, value] of Object.entries(body)) bodyProps[key] = value;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
for (const [key, schema] of Object.entries(props)) {
|
|
60
|
+
if (key === 'method') input[key] = method;
|
|
61
|
+
else if (key === 'path') input[key] = url.pathname;
|
|
62
|
+
else if (key === 'query') input[key] = query;
|
|
63
|
+
else if (key === 'params') input[key] = paramValues;
|
|
64
|
+
else if (key === 'headers') {
|
|
65
|
+
const headers = Object.create(null);
|
|
66
|
+
for (const [name, headerSchema] of Object.entries(propertiesOf(schema))) {
|
|
67
|
+
const value = req.headers[name.toLowerCase()];
|
|
68
|
+
if (value !== undefined) headers[name] = primitive(Array.isArray(value) ? value : [value], headerSchema);
|
|
69
|
+
}
|
|
70
|
+
input[key] = headers;
|
|
71
|
+
} else if (key === 'body') { if (body !== undefined) input[key] = body; }
|
|
72
|
+
else if (Object.hasOwn(paramValues, key)) input[key] = paramValues[key];
|
|
73
|
+
else if (Object.hasOwn(query, key)) input[key] = query[key];
|
|
74
|
+
else if (Object.hasOwn(bodyProps, key)) input[key] = bodyProps[key];
|
|
75
|
+
}
|
|
76
|
+
const errors = checkInput(input, entry.input_schema, 0).refusals;
|
|
77
|
+
if (errors.length) throw problem(400, errors[0].message || 'The request does not match the prompt’s input schema.');
|
|
78
|
+
return input;
|
|
79
|
+
}
|
|
80
|
+
function responseFor(result) {
|
|
81
|
+
if (!object(result) || !Number.isInteger(result.status) || result.status < 200 || result.status > 599) throw problem(502, 'The prompt must return an HTTP status from 200 to 599.');
|
|
82
|
+
if (result.headers !== undefined && !object(result.headers)) throw problem(502, 'The prompt must return an object of HTTP headers.');
|
|
83
|
+
const headers = Object.create(null), nominated = new Set(String(result.headers?.connection ?? result.headers?.Connection ?? '').toLowerCase().split(',').map(s => s.trim()));
|
|
84
|
+
for (const [name, value] of Object.entries(result.headers ?? {})) {
|
|
85
|
+
const lower = name.toLowerCase();
|
|
86
|
+
if (HOP.has(lower) || nominated.has(lower) || RESERVED_USAGE.has(lower)) continue;
|
|
87
|
+
if (!(typeof value === 'string' || Array.isArray(value) && value.every(v => typeof v === 'string'))) throw problem(502, 'The prompt returned an invalid HTTP header value.');
|
|
88
|
+
try { validateHeaderName(name); for (const item of Array.isArray(value) ? value : [value]) validateHeaderValue(name, item); } catch { throw problem(502, 'The prompt returned an invalid HTTP header.'); }
|
|
89
|
+
headers[name.toLowerCase()] = value;
|
|
90
|
+
}
|
|
91
|
+
const value = Object.hasOwn(result, 'body') ? result.body : Object.fromEntries(Object.entries(result).filter(([key]) => !['status', 'headers'].includes(key)));
|
|
92
|
+
const body = typeof value === 'string' ? value : JSON.stringify(value);
|
|
93
|
+
if (body === undefined) throw problem(502, 'The prompt returned no HTTP response body.');
|
|
94
|
+
if (!headers['content-type']) headers['content-type'] = typeof value === 'string' ? 'text/plain; charset=utf-8' : 'application/json; charset=utf-8';
|
|
95
|
+
return { status: result.status, headers, body };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const SCREEN_PREFIX = '/__pdd/screen/';
|
|
99
|
+
const SCREEN_CSP = "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src data:; connect-src 'self'; frame-src 'self'; base-uri 'self'; form-action 'none'; frame-ancestors 'none'; object-src 'none'";
|
|
100
|
+
function screenResource(url, method) {
|
|
101
|
+
if (url.pathname === '/' && ['GET', 'HEAD'].includes(method) && !url.search) return 'index.html';
|
|
102
|
+
if (!url.pathname.startsWith(SCREEN_PREFIX)) return null;
|
|
103
|
+
const path = url.pathname.slice(SCREEN_PREFIX.length);
|
|
104
|
+
if (['GET', 'HEAD'].includes(method)) {
|
|
105
|
+
if (!url.search && (['index.html', 'door-screen.js', 'door-screen.css', 'try-frame.js', 'api/state'].includes(path) || /^app-asset\/[0-9]+$/.test(path))) return path;
|
|
106
|
+
if (path === 'api/action' && [...url.searchParams.keys()].length === 1 && url.searchParams.has('id') && /^[A-Za-z0-9_-]{1,128}$/.test(url.searchParams.get('id'))) return path + url.search;
|
|
107
|
+
}
|
|
108
|
+
if (method === 'POST' && !url.search && ['api/app/open', 'api/act'].includes(path)) return path;
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
async function requestText(req) {
|
|
112
|
+
const chunks = []; let size = 0;
|
|
113
|
+
const timeout = setTimeout(() => req.destroy(), 30_000);
|
|
114
|
+
try {
|
|
115
|
+
for await (const chunk of req) { size += chunk.length; if (size > 1024 * 1024) throw problem(413, 'The request body exceeds 1 MiB.'); chunks.push(chunk); }
|
|
116
|
+
} finally { clearTimeout(timeout); }
|
|
117
|
+
try { return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)); } catch { throw problem(400, 'The request body must be UTF-8.'); }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Build a request only from authored input; missing values remain visible placeholders.
|
|
121
|
+
function requestExample(entry, tests, port) {
|
|
122
|
+
const step = tests.flatMap(test => test.doc?.steps ?? []).find(step => step.entry_path === entry.entry_path && step.operation === entry.operation);
|
|
123
|
+
const input = step?.input ?? {}, props = propertiesOf(entry.input_schema);
|
|
124
|
+
const missing = name => `<required:${name}>`;
|
|
125
|
+
const path = entry.route.path.replace(/:([A-Za-z][A-Za-z0-9_]*)/g, (_, name) => {
|
|
126
|
+
const value = (input.params ?? input)[name];
|
|
127
|
+
return value === undefined ? missing(name) : encodeURIComponent(String(value));
|
|
128
|
+
});
|
|
129
|
+
const query = new URLSearchParams();
|
|
130
|
+
const queryProps = props.query ? propertiesOf(props.query) : props;
|
|
131
|
+
const required = props.query?.required ?? entry.input_schema?.required ?? [];
|
|
132
|
+
const parameters = new Set([...entry.route.path.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(match => match[1]));
|
|
133
|
+
for (const name of Object.keys(queryProps)) {
|
|
134
|
+
if (!props.query && (parameters.has(name) || ['body', 'headers', 'method', 'path', 'params'].includes(name))) continue;
|
|
135
|
+
const value = (props.query ? input.query : input)?.[name];
|
|
136
|
+
if (value !== undefined) for (const item of Array.isArray(value) ? value : [value]) query.append(name, String(item));
|
|
137
|
+
else if (required.includes(name)) query.append(name, missing(name));
|
|
138
|
+
}
|
|
139
|
+
const url = `http://127.0.0.1:${port}${path}${query.size ? `?${query}` : ''}`;
|
|
140
|
+
const args = ['curl', '-X', entry.route.method, url];
|
|
141
|
+
for (const name of Object.keys(propertiesOf(props.headers))) {
|
|
142
|
+
const value = input.headers?.[name];
|
|
143
|
+
if (value !== undefined || props.headers.required?.includes(name)) args.push('-H', `${name}: ${value ?? missing(name)}`);
|
|
144
|
+
}
|
|
145
|
+
if (props.body && (input.body !== undefined || entry.input_schema.required?.includes('body'))) {
|
|
146
|
+
const body = input.body === undefined ? missing('body') : typeof input.body === 'string' ? input.body : JSON.stringify(input.body);
|
|
147
|
+
if (props.body.type !== 'string') args.push('-H', 'Content-Type: application/json');
|
|
148
|
+
args.push('--data', body);
|
|
149
|
+
}
|
|
150
|
+
return args.map(shellWord).join(' ');
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function openServe(context, test, sessionId, options) {
|
|
154
|
+
const { ports, root, origin, identity } = context;
|
|
155
|
+
if(loadRuntimeWorkspace({root}).configured)(ports?.captureSource??((r,o)=>captureSource(r,o,ports)))(root,{tests:[test.path],appMap:context.appMap??null});
|
|
156
|
+
const model = await context.runtime.send(`/v1/try/${sessionId}/model`, { method: 'GET' }, 30_000);
|
|
157
|
+
if (model.status !== 200 || !Array.isArray(model.json?.entries)) throw problem(502, cleanText(model.json?.error?.message || 'The interpreter could not read this Try’s routes. It needs the Try doors server branch.'));
|
|
158
|
+
const routes = model.json.entries.filter(e => e.http).map(entry => ({ ...entry, route: entry.http }));
|
|
159
|
+
const hasScreen = model.json.app_map === true;
|
|
160
|
+
if (hasScreen && routes.some(e => ['GET', 'HEAD'].includes(e.route.method) && e.route.path === '/' || e.route.path.startsWith(SCREEN_PREFIX))) throw problem(502, 'This app map reserves GET/HEAD / and /__pdd/screen/; its HTTP routes conflict with the Screen.');
|
|
161
|
+
if (!routes.length && !hasScreen) {
|
|
162
|
+
if (context.appMap) {
|
|
163
|
+
const command = ['pdd', 'simulate', test.story, '--serve', String(options['--serve'] ?? 8080), '--new', '--app-map', relative(context.cwd ?? root, join(root, context.appMap))].map(shellWord).join(' ');
|
|
164
|
+
throw problem(502, `This saved Try has no Screen app map. Start a new Try with the selected app map: ${command}`);
|
|
165
|
+
}
|
|
166
|
+
throw problem(502, 'This Story has neither a Screen app map nor named HTTP routes. Add an app map (RUNBOOK §13), or name an HTTP route such as HTTP GET /api/books in input_schema.title (RUNBOOK §19).');
|
|
167
|
+
}
|
|
168
|
+
const keys = new Set();
|
|
169
|
+
for (const entry of routes) {
|
|
170
|
+
const key = `${entry.route.method} ${entry.route.path.replace(/:[A-Za-z][A-Za-z0-9_]*/g, ':param')}`;
|
|
171
|
+
if (keys.has(key)) throw problem(502, 'This Try has overlapping HTTP route labels; name each method/path once.');
|
|
172
|
+
keys.add(key);
|
|
173
|
+
}
|
|
174
|
+
let latestUsage = tryUsage(model.json);
|
|
175
|
+
const callCap = latestUsage.cap;
|
|
176
|
+
(ports.stderr ?? process.stderr).write(`${tryUsageLine(latestUsage)}\n`);
|
|
177
|
+
let tail = Promise.resolve(), pending = 0, stopped = false;
|
|
178
|
+
const server = createServer(async (req, res) => {
|
|
179
|
+
let counted = false, usage = { ...latestUsage, calls: 0, input_tokens: 'unknown', cached_input_tokens: 'unknown', output_tokens: 'unknown', cached_input_share: null }, usageSource = 'last-known';
|
|
180
|
+
const reply = (status, message) => { if (!res.headersSent) { res.writeHead(status, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', ...tryUsageHeaders(usage), 'x-pdd-usage-source': usageSource }); res.end(`pdd: ${cleanText(message)}\n`); } else res.destroy(); };
|
|
181
|
+
try {
|
|
182
|
+
const port = server.address()?.port, acceptedHost = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
|
|
183
|
+
if (port === 80) { acceptedHost.add('127.0.0.1'); acceptedHost.add('localhost'); }
|
|
184
|
+
const acceptedOrigin = new Set([...acceptedHost].map(host => `http://${host}`));
|
|
185
|
+
if (!acceptedHost.has(req.headers.host) || (req.headers.origin && !acceptedOrigin.has(req.headers.origin)) || req.headers['sec-fetch-site'] === 'cross-site') throw problem(403, 'This local Try accepts requests only from its own origin.');
|
|
186
|
+
if (!req.url.startsWith('/') || req.url.startsWith('//') || req.url.includes('\\')) throw problem(400, 'Use a local absolute request path.');
|
|
187
|
+
const url = new URL(req.url, `http://127.0.0.1:${port}`);
|
|
188
|
+
const resource = hasScreen ? screenResource(url, req.method) : null;
|
|
189
|
+
if (resource) {
|
|
190
|
+
if (pending >= 32 || stopped || context.signal?.aborted) throw problem(503, 'The local Try is busy or stopped.');
|
|
191
|
+
pending++; counted = true;
|
|
192
|
+
const body = await requestText(req);
|
|
193
|
+
if (req.method === 'POST' && req.headers['content-type']?.split(';')[0] !== 'application/json') throw problem(415, 'Screen actions require application/json.');
|
|
194
|
+
if (stopped || context.signal?.aborted) throw problem(503, 'The local Try is stopped.');
|
|
195
|
+
const upstream = await context.runtime.send(`/v1/try/${sessionId}/screen/${resource}`, { method: req.method === 'HEAD' ? 'GET' : req.method,
|
|
196
|
+
...(req.method === 'POST' ? { headers: { 'Content-Type': 'application/json' }, body } : {}) }, 90_000);
|
|
197
|
+
if (upstream.lost || !Number.isInteger(upstream.status) || upstream.status < 200 || upstream.status > 599) throw problem(502, 'The Screen request result is unknown. Read its action ID; do not resubmit.');
|
|
198
|
+
const text = upstream.text ?? JSON.stringify(upstream.json);
|
|
199
|
+
if (typeof text !== 'string' || Buffer.byteLength(text) > 16 * 1024 * 1024) throw problem(502, 'The Screen response is unavailable or too large.');
|
|
200
|
+
res.writeHead(upstream.status, { 'content-type': upstream.headers?.get('content-type') || 'application/json; charset=utf-8',
|
|
201
|
+
'content-length': Buffer.byteLength(text), 'cache-control': 'no-store', 'content-security-policy': SCREEN_CSP,
|
|
202
|
+
'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff' });
|
|
203
|
+
res.end(req.method === 'HEAD' ? '' : text); return;
|
|
204
|
+
}
|
|
205
|
+
if (hasScreen && url.pathname.startsWith(SCREEN_PREFIX)) { req.resume(); reply(404, 'This Screen resource is not available.'); return; }
|
|
206
|
+
let selected, params;
|
|
207
|
+
// A literal route wins over a parameter route; HEAD has its own entry before GET fallback.
|
|
208
|
+
const candidates = routes.filter(e => e.route.method === req.method || req.method === 'HEAD' && e.route.method === 'GET')
|
|
209
|
+
.sort((a, b) => Number(a.route.method !== req.method) - Number(b.route.method !== req.method) || (a.route.path.match(/:/g)?.length ?? 0) - (b.route.path.match(/:/g)?.length ?? 0));
|
|
210
|
+
for (const entry of candidates) { const found = pathParams(entry.route, url.pathname); if (found) { selected = entry; params = found; break; } }
|
|
211
|
+
if (!selected) { req.resume(); reply(404, 'No prompt names this HTTP route.'); return; }
|
|
212
|
+
if (req.headers['sec-fetch-dest'] && req.headers['sec-fetch-dest'] !== 'empty') throw problem(403, 'Use curl or fetch for this API route; embedded resources and page navigations cannot spend AI calls.');
|
|
213
|
+
if (pending >= 32 || stopped) throw problem(503, 'The local Try is busy or stopped.');
|
|
214
|
+
pending++; counted = true;
|
|
215
|
+
const text = await requestText(req);
|
|
216
|
+
const input = inputFor(selected, req, url, params, text, selected.route.method);
|
|
217
|
+
// One line per request in the pdd window, like a local server log: the call can take many seconds.
|
|
218
|
+
const label = `${req.method} ${url.pathname}`, sentAt = Date.now();
|
|
219
|
+
ports.stderr?.write(`${label}: running on the Try…\n`);
|
|
220
|
+
const work = tail.then(async () => {
|
|
221
|
+
if (stopped || context.signal?.aborted) throw problem(503, 'The local Try is stopped.');
|
|
222
|
+
return runDoorCall({ root, originalPath:test.path, origin, login: identity.login, sessionId, callCap, prompt: selected.entry_path, operation: selected.operation }, input,
|
|
223
|
+
{ ...ports, signal: context.signal });
|
|
224
|
+
});
|
|
225
|
+
tail = work.catch(() => {});
|
|
226
|
+
usage = tryUsage({}, { cap: callCap }); usageSource = 'runtime';
|
|
227
|
+
const answer = await work;
|
|
228
|
+
usage = answer.usage; latestUsage = usage;
|
|
229
|
+
const result = responseFor(answer.result);
|
|
230
|
+
const body = req.method === 'HEAD' || [204, 304].includes(result.status) ? '' : result.body;
|
|
231
|
+
const headers = { ...result.headers, ...(![204, 304].includes(result.status) ? { 'content-length': Buffer.byteLength(req.method === 'HEAD' ? result.body : body) } : {}) };
|
|
232
|
+
res.writeHead(result.status, { ...headers, ...tryUsageHeaders(usage), 'x-pdd-usage-source': usageSource }); res.end(body);
|
|
233
|
+
ports.stderr?.write(`${label}: ${result.status} in ${Math.round((Date.now() - sentAt) / 1000)} s\n`);
|
|
234
|
+
} catch (error) {
|
|
235
|
+
if (error.tryUsage) { usage = error.tryUsage; latestUsage = usage; usageSource = 'runtime'; }
|
|
236
|
+
req.resume(); reply(error.httpStatus || 502, error.message || 'The interpreter could not confirm this request.');
|
|
237
|
+
ports.stderr?.write(`${req.method} ${req.url.split('?')[0]}: ${error.httpStatus || 502} ${cleanText(error.message || 'The interpreter could not confirm this request.')}\n`);
|
|
238
|
+
}
|
|
239
|
+
finally { if (counted) pending--; }
|
|
240
|
+
});
|
|
241
|
+
server.requestTimeout = 30_000; server.headersTimeout = 15_000;
|
|
242
|
+
const wanted = Number(options['--serve'] ?? 8080);
|
|
243
|
+
await new Promise((done, reject) => { server.once('error', reject); server.listen(wanted, '127.0.0.1', done); }).catch(error => {
|
|
244
|
+
if (error.code === 'EADDRINUSE') throw problem(502, `port ${wanted} is in use by another program. Stop it, or run pdd simulate ${test.story} --serve ${wanted === 65535 ? wanted - 1 : wanted + 1}.`);
|
|
245
|
+
if (error.code === 'EACCES') throw problem(502, `port ${wanted} needs extra rights on this computer. Run pdd simulate ${test.story} --serve 8080.`);
|
|
246
|
+
throw error;
|
|
247
|
+
});
|
|
248
|
+
const stop = () => { stopped = true; server.close(); server.closeIdleConnections(); server.closeAllConnections(); };
|
|
249
|
+
context.signal?.addEventListener('abort', stop, { once: true });
|
|
250
|
+
const port = server.address().port;
|
|
251
|
+
ports.stdout.write(`Try is serving at http://127.0.0.1:${port}\n${routes.length ? routes.map(e => ` ${e.route.method} ${e.route.path}`).join('\n') : ' Screen only (no named HTTP routes).'}\nCtrl-C closes this server. The Try session keeps its saved data.\n`);
|
|
252
|
+
if (routes.length) ports.stdout.write(`Example: ${requestExample(routes[0], context.simulationTests ?? [test], port)}\n`);
|
|
253
|
+
if (hasScreen) ports.stdout.write(`Screen: http://127.0.0.1:${port}/\n`);
|
|
254
|
+
try {
|
|
255
|
+
if (ports.serve) { await ports.serve(server); return 0; }
|
|
256
|
+
await new Promise(done => { server.once('close', done); if (context.signal?.aborted) stop(); });
|
|
257
|
+
return 0;
|
|
258
|
+
} finally { stop(); context.signal?.removeEventListener('abort', stop); }
|
|
259
|
+
}
|