@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.
Files changed (39) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +42 -2
  3. package/package.json +28 -4
  4. package/src/index.mjs +1 -0
  5. package/src/runtime/agent-ask.mjs +187 -0
  6. package/src/runtime/agent-chat.mjs +152 -0
  7. package/src/runtime/agent-coverage.mjs +97 -0
  8. package/src/runtime/agent-guide.mjs +152 -0
  9. package/src/runtime/agent-judge.mjs +71 -0
  10. package/src/runtime/agent-packet.mjs +62 -0
  11. package/src/runtime/agent-project.mjs +93 -0
  12. package/src/runtime/contract-refs.mjs +519 -0
  13. package/src/runtime/contracts.mjs +138 -0
  14. package/src/runtime/index.mjs +974 -0
  15. package/src/runtime/lint-call-preflight.mjs +19 -0
  16. package/src/runtime/lint-compatibility-display.mjs +62 -0
  17. package/src/runtime/live-local-bridge.mjs +178 -0
  18. package/src/runtime/live-local.mjs +181 -0
  19. package/src/runtime/product-composition.mjs +384 -0
  20. package/src/runtime/run-program.mjs +797 -0
  21. package/src/runtime/runtime-binding-plan.mjs +145 -0
  22. package/src/runtime/runtime-bindings.mjs +81 -0
  23. package/src/runtime/runtime-check-plan.mjs +411 -0
  24. package/src/runtime/runtime-client.mjs +8114 -0
  25. package/src/runtime/runtime-lint-receipt.mjs +25 -0
  26. package/src/runtime/runtime-markdown.mjs +215 -0
  27. package/src/runtime/runtime-outcome.mjs +468 -0
  28. package/src/runtime/runtime-output.mjs +752 -0
  29. package/src/runtime/runtime-preflight.mjs +3832 -0
  30. package/src/runtime/runtime-slots.mjs +462 -0
  31. package/src/runtime/runtime-workspace-migration.mjs +70 -0
  32. package/src/runtime/runtime-workspace.mjs +52 -0
  33. package/src/runtime/scenario-json.mjs +257 -0
  34. package/src/runtime/secret-redaction.mjs +54 -0
  35. package/src/runtime/try-doors.mjs +597 -0
  36. package/src/runtime/try-http.mjs +285 -0
  37. package/src/runtime/try-mcp.mjs +223 -0
  38. package/src/runtime/try-session.mjs +95 -0
  39. package/src/runtime/try-update-policy.mjs +43 -0
@@ -0,0 +1,597 @@
1
+ // Generated from prompts/cli/try-doors.prompt.md (sha256: 5bd90da988b27996d32579172073ba42f9a320968d451592be1456dec50449cb).
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import { createHash, randomUUID } 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, interfaceSchemaProblems, readAppMapScreens, analyzePromptSelectorWords } from './runtime-preflight.mjs';
8
+ import { loadRuntimeWorkspace, requireRuntimePath } from './runtime-workspace.mjs';
9
+ import { cleanText, causeText, tryUsage, tryUsageLine } from './runtime-output.mjs';
10
+ import { runDoorCall, saveDoorCaseResult, acquireCaseWriteOwnership, withRepositoryRunLockAsync, defaultLineReader } from './runtime-client.mjs';
11
+
12
+ const WRAPPER_EXIT = 125;
13
+ const hash = text => createHash('sha256').update(text).digest('hex');
14
+ const quote = word => /^[A-Za-z0-9_./:@%+=,-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`;
15
+ const read = path => JSON.parse(readFileSync(path, 'utf8'));
16
+ const fail = message => { const e = new Error(message); e.exitCode = WRAPPER_EXIT; throw e; };
17
+ function checkEffectivePrompts(root, rawHashes, effectiveHashes) {
18
+ const visible=new Set(gitFiles(root));
19
+ for (const path of Object.keys(rawHashes ?? {})) {
20
+ const prompt=readPrompt(root,visible,path);
21
+ if (!prompt.text) fail('A prompt is unavailable. Run pdd simulate STORY --cli --new.');
22
+ if (effectiveHashes?.[path]) {
23
+ if (hash(executableInterfaceText(prompt.text))!==effectiveHashes[path]) fail('A prompt or shared contract changed since this Try. Run pdd simulate STORY --cli --new.');
24
+ } else if (prompt.references?.length) fail('This Try reference baseline is unavailable. Run pdd simulate STORY --cli --new.');
25
+ }
26
+ }
27
+ function regular(path) {
28
+ const stat = lstatSync(path);
29
+ if (stat.isSymbolicLink()) fail('Refusing a symbolic link in Try files.');
30
+ if (!stat.isFile() || stat.nlink !== 1) fail('A Try file must be a regular file with one link.');
31
+ }
32
+ function writePrivate(path, value) {
33
+ if (existsSync(path)) regular(path);
34
+ const temp = `${path}.${process.pid}.tmp`;
35
+ const fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
36
+ try { writeFileSync(fd, JSON.stringify(value, null, 2) + '\n'); } finally { closeSync(fd); }
37
+ renameSync(temp, path);
38
+ }
39
+ function safeBin(root) {
40
+ let path = root;
41
+ for (const part of ['.pdd', 'try', 'bin']) {
42
+ path = join(path, part);
43
+ try { mkdirSync(path, { mode: 0o700 }); } catch (e) { if (e.code !== 'EEXIST') throw e; }
44
+ const stat = lstatSync(path);
45
+ if (stat.isSymbolicLink()) fail(`Refusing a symbolic link at ${part}.`);
46
+ if (!stat.isDirectory()) fail(`${part} is not a folder.`);
47
+ }
48
+ return path;
49
+ }
50
+
51
+ function excludeLaunchers(root) {
52
+ const git = spawnSync('git', ['rev-parse', '--git-path', 'info/exclude'], { cwd: root, encoding: 'utf8' });
53
+ if (git.status !== 0) fail('Could not locate the repository’s local Git exclude file.');
54
+ const exclude = resolve(root, git.stdout.trim());
55
+ if (existsSync(exclude)) regular(exclude);
56
+ mkdirSync(dirname(exclude), { recursive: true });
57
+ if (realpathSync(dirname(exclude)) !== dirname(exclude)) fail('Refusing a symbolic link in the Git exclude path.');
58
+ const ignored = existsSync(exclude) ? readFileSync(exclude, 'utf8') : '';
59
+ if (!ignored.split('\n').includes('/.pdd/try/')) writeFileSync(exclude, `${ignored}${ignored.endsWith('\n') || !ignored ? '' : '\n'}/.pdd/try/\n`);
60
+ }
61
+
62
+ function cliEntries(context, test) {
63
+ const entries = new Map();
64
+ for (const step of Array.isArray(test.doc?.steps) ? test.doc.steps : []) {
65
+ if (!step || typeof step.entry_path !== 'string' || typeof step.operation !== 'string') continue;
66
+ const prompt = readPrompt(context.root, context.visible, step.entry_path);
67
+ const authoredEntries = Array.isArray(prompt.interface?.entries) ? prompt.interface.entries : [];
68
+ const index = authoredEntries.findIndex(e => e?.operation === step.operation);
69
+ if (!(index >= 0)) continue;
70
+ const conventions = Array.isArray(prompt.interface.conventions) ? prompt.interface.conventions : [];
71
+ if (!['input_schema', 'result_schema'].every(key => conventions.some(c => c?.path === `/entries/${index}/${key}` && c.convention === 'cli'))) continue;
72
+ entries.set(`${step.entry_path}#${step.operation}`, { step, prompt, entry: authoredEntries[index] });
73
+ }
74
+ return entries;
75
+ }
76
+
77
+ function typedUnmappedStory(context, test) {
78
+ const steps = (Array.isArray(test.doc?.steps) ? test.doc.steps : []).filter(step => step && typeof step.entry_path === 'string' && typeof step.operation === 'string');
79
+ for (const step of steps) {
80
+ const prompt = readPrompt(context.root, context.visible, step.entry_path);
81
+ const entry = (Array.isArray(prompt.interface?.entries) ? prompt.interface.entries : []).find(entry => entry?.operation === step.operation);
82
+ if (typeof entry?.input_schema?.title === 'string' && /^HTTP (GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) \/\S*$/.test(entry.input_schema.title)) return false;
83
+ }
84
+ const mapPath = context.appMap === undefined ? ['app-map.json', 'app/app-map.json'].find(path => context.visible.has(path)) : context.appMap;
85
+ if (mapPath) {
86
+ let screens;
87
+ try { screens = read(join(context.root, mapPath)).screens; } catch { return false; }
88
+ 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;
89
+ }
90
+ return true;
91
+ }
92
+
93
+ function cliEntry(context, test) {
94
+ let entries;
95
+ if (context.directProgram) {
96
+ if(context.directProgram.selected)return context.directProgram.selected;
97
+ const path=context.directProgram.prompt??context.directProgram.descriptor?.prompt;
98
+ const source=readPrompt(context.root,context.visible,path);
99
+ const prompt=context.directProgram.interface?{...source,interface:context.directProgram.interface,error:null}:source;
100
+ if(prompt.error==='interface-missing'&&context.directProgram.allowMissingInterfaces){
101
+ // A cold declaration prepares transport only. The client must obtain the admitted schema before calling.
102
+ const operations=[...new Set([...prompt.text.matchAll(/\b(?:export|operation)\s+`?([A-Za-z_$][\w$]*)`?/gi)].map(match=>match[1]))];
103
+ const stdin=/\bstdin\s*(\?)?\s*:\s*string\b/.exec(prompt.text);
104
+ const entry={operation:operations.length===1?operations[0]:null,input_schema:{type:'object',properties:{argv:{type:'array',items:{type:'string'}},...(stdin?{stdin:{type:'string'}}:{})},required:['argv',...(stdin&&!stdin[1]?['stdin']:[])],additionalProperties:false}};
105
+ entries=new Map([[path,{step:{entry_path:path,operation:entry.operation},prompt,entry,unadmitted:true}]]);
106
+ }else{
107
+ const candidates=Array.isArray(prompt.interface?.entries)?prompt.interface.entries:[];
108
+ const conventions=Array.isArray(prompt.interface?.conventions)?prompt.interface.conventions:[];
109
+ entries=new Map(candidates.flatMap((entry,index)=>['input_schema','result_schema'].every(key=>conventions.some(c=>c?.path===`/entries/${index}/${key}`&&c.convention==='cli'))
110
+ ? [[`${path}#${entry.operation}`,{step:{entry_path:path,operation:entry.operation},prompt,entry}]]:[]));
111
+ if(entries.size!==1)fail('The entry prompt must declare exactly one command-line program.');
112
+ }
113
+ } else entries = cliEntries(context, test);
114
+ if (entries.size !== 1) {
115
+ if (entries.size) fail('This Story uses more than one command-line program. Choose a Story with one command-line program.');
116
+ 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));
117
+ const names = [...new Set(found.tests.filter(candidate => {
118
+ // Other Stories supply advice only; their missing context is independent.
119
+ try { return cliEntries(context, candidate).size === 1; } catch { return false; }
120
+ }).map(candidate => candidate.story))].sort();
121
+ 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.` : ''}`);
122
+ }
123
+ const value = [...entries.values()][0];
124
+ const heading = value.prompt.text.match(/^#\s+(.+?)\s*$/m)?.[1]?.replace(/^`([^`]+)`$/, '$1');
125
+ 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).');
126
+ return { ...value, name: heading };
127
+ }
128
+
129
+ async function directProgramInput(inputSchema,argv,ports){
130
+ const input={argv};
131
+ try{
132
+ if(inputSchema.properties?.stdin&&!ports.stdin.isTTY){
133
+ const chunks=[];let bytes=0;
134
+ const collect=async()=>{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.');chunks.push(part);}};
135
+ let abort;
136
+ try{
137
+ if(ports.signal?.aborted)fail('Stopped before the command was sent.');
138
+ const interrupted=ports.signal?new Promise((done,reject)=>{abort=()=>{ports.stdin.destroy?.();reject(new Error('Stopped while reading stdin; no command was sent.'));};ports.signal.addEventListener('abort',abort,{once:true});}):null;
139
+ if(interrupted)await Promise.race([collect(),interrupted]);else await collect();
140
+ }finally{if(abort)ports.signal.removeEventListener('abort',abort);}
141
+ input.stdin=new TextDecoder('utf-8',{fatal:true}).decode(Buffer.concat(chunks));
142
+ }else if(inputSchema.required?.includes('stdin'))input.stdin='';
143
+
144
+ return input;
145
+ }catch(error){
146
+ if(error instanceof TypeError&&/encoded data/.test(error.message))fail('Piped stdin must be UTF-8 text.');
147
+ throw error;
148
+ }
149
+ }
150
+
151
+ async function openDirectCli(context, test, selected) {
152
+ const direct=context.directProgram;
153
+ if (direct.prepareOnly) return direct.prepareInput?{...selected,input:await directProgramInput(selected.entry.input_schema,direct.argv,context.ports)}:selected;
154
+ const {descriptorPath,argv,quiet,recoverRequestId}=direct, d=direct.descriptor;
155
+ if (argv.length || recoverRequestId || direct.invoke) return runShim(descriptorPath,argv,{...context.ports,directPrepared:true,directInput:direct.input,directQuiet:quiet,directStartedAt:direct.startedAt,directSetupCalls:direct.setupCalls,directRecoveryId:recoverRequestId});
156
+ excludeLaunchers(context.root);
157
+ const bin=safeBin(context.root),shim=join(bin,d.name);
158
+ if(existsSync(shim)){regular(shim);if(!readFileSync(shim,'utf8').startsWith('#!/bin/sh\n# PDD Try launcher v1\n'))fail('Refusing to overwrite a non-PDD launcher.');}
159
+ const moduleUrl=context.ports.tryLauncherUrl??pathToFileURL(join(dirname(fileURLToPath(import.meta.url)),'try-doors.mjs')).href;
160
+ 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 program adapter could not load.\\nFix: Reinstall PDD and open the program again.\\n");process.exitCode=125;});';
161
+ const fd=openSync(shim,constants.O_WRONLY|constants.O_CREAT|constants.O_TRUNC|constants.O_NOFOLLOW,0o700);
162
+ try{writeFileSync(fd,`#!/bin/sh\n# PDD Try launcher v1\nexec ${quote(process.execPath)} --input-type=commonjs -e ${quote(script)} -- ${quote(moduleUrl)} ${quote(descriptorPath)} "$@"\n`);}finally{closeSync(fd);}
163
+ chmodSync(shim,0o700);
164
+ context.ports.stdout.write(`Try is ready: ${d.name}\n${shim}\nexport PATH=${quote(bin)}:"$PATH"\n`);
165
+ if(typeof context.ports.shell!=='function')fail('The shell host capability is unavailable.');
166
+ const chosen=context.ports.env.SHELL||'/bin/sh',shell=['bash','zsh','sh'].includes(basename(chosen))?chosen:'/bin/sh';
167
+ return context.ports.shell(shell,{...context.ports.env,PATH:`${bin}:${context.ports.env.PATH||process.env.PATH||''}`},context.root);
168
+ }
169
+ function directSummary(d,usage,elapsed,replayed=false,setupCalls=0){
170
+ const ownerCalls=replayed?0:usage?.calls;
171
+ const total=Number.isSafeInteger(setupCalls)&&Number.isSafeInteger(ownerCalls)?setupCalls+ownerCalls:null;
172
+ const calls=Number.isSafeInteger(total)?total:'unknown';
173
+ return `pdd: ${calls} AI calls · ${Math.max(0,elapsed)/1000}s${d.draft?' · DRAFT':''}\n`;
174
+ }
175
+ async function runDirectShim(d,descriptorPath,argv,ports){
176
+ if(!ports.directPrepared)return (await import('./runtime-client.mjs')).runTry({cwd:d.root,words:[d.prompt,...argv],options:{}},{...ports,directInvoke:true});
177
+ const now=ports.now??Date.now,started=ports.directStartedAt??now(),last=join(d.programDir,'last.json'),data=join(d.programDir,'data.json');
178
+ let input=ports.directInput??{argv},requestId=ports.directRecoveryId??null,accounting,replayed=false;
179
+ const quiet=ports.directQuiet===true;
180
+ try{
181
+ if(ports.directRecoveryId){regular(last);Object.assign(input,read(last).input);}
182
+ else{
183
+ writePrivate(last,{state:'unknown',id:null,input});
184
+ if(!ports.directInput)input=await directProgramInput(d.inputSchema,argv,ports);
185
+ }
186
+ const answer=await runDoorCall({...d,recoverRequestId:ports.directRecoveryId},input,{...ports,env:{...ports.env,PDD_STATE_DIR:d.stateDir},
187
+ onDoorRequest:id=>{requestId=id;writePrivate(last,{state:'unknown',id,input});}});
188
+ accounting=answer.usage;replayed=answer.replayed;
189
+ const result=answer.result;
190
+ 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)
191
+ fail('The prompt must return stdout, stderr and an exit_code from 0–255 except reserved code 125.');
192
+ if(answer.world!==undefined){if(answer.world===null||typeof answer.world!=='object'||Array.isArray(answer.world))fail('The interpreter returned invalid program data.');writePrivate(data,answer.world);}
193
+ writePrivate(last,{state:'confirmed',id:answer.id,input,result,inputWorld:answer.inputWorld,world:answer.world});
194
+ ports.stdout.write(result.stdout);ports.stderr.write(result.stderr);
195
+ if(!quiet)ports.stderr.write(`${result.stderr&&!result.stderr.endsWith('\n')?'\n':''}${directSummary(d,answer.usage,now()-started,answer.replayed,ports.directSetupCalls)}`);
196
+ if(ports.signal?.aborted){ports.stderr.write(`${quiet&&result.stderr&&!result.stderr.endsWith('\n')?'\n':''}pdd: Stopped. Read the result with: pdd test --read ${answer.id}\n`);return 130;}
197
+ return result.exit_code;
198
+ }catch(error){
199
+ if(error?.unboundPort)throw error;
200
+ try{writePrivate(last,{state:error.unknownOutcome?'unknown':'refused',id:requestId,input});}catch(persistenceError){error=persistenceError;}
201
+ const reason=error instanceof TypeError&&/encoded data/.test(error.message)?'Piped stdin must be UTF-8 text.':cleanText(error.message||'The command could not run.');
202
+ ports.stderr.write(`pdd: ${reason}\nFix: ${cleanText(error.fix|| (requestId&&error.unknownOutcome?`Read pdd test --read ${requestId}; do not repeat the command automatically.`:'Check the prompt, data and interpreter connection, then run the command again.'))}\n`);
203
+ if(!quiet)ports.stderr.write(directSummary(d,error.tryUsage??accounting,now()-started,replayed,ports.directSetupCalls));
204
+ return ports.signal?.aborted?130:WRAPPER_EXIT;
205
+ }
206
+ }
207
+
208
+ export async function openCli(context, test, sessionId, options) {
209
+ if(context.directProgram)return openDirectCli(context,test,cliEntry(context,test));
210
+ const { root, ports, store, identity, origin } = context;
211
+ const { step, prompt, entry, name } = cliEntry(context, test);
212
+ const record = store.repo(root).tries?.[test.path];
213
+ 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.');
214
+ 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.');
215
+ checkEffectivePrompts(root,record.prompt_hashes,record.effective_prompt_hashes);
216
+ const bin = safeBin(root), shim = join(bin, name);
217
+ if (existsSync(shim)) {
218
+ regular(shim);
219
+ 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.`);
220
+ } else { try { lstatSync(shim); fail('Refusing a symbolic link in Try files.'); } catch (e) { if (e.code !== 'ENOENT') throw e; } }
221
+ excludeLaunchers(root);
222
+ const descriptorPath = join(store.folder('tries'), `${sessionId}.door.json`);
223
+ if (existsSync(descriptorPath) && read(descriptorPath).promptHash !== hash(prompt.text)) fail('The CLI prompt changed since this Try. Run pdd simulate STORY --cli --new.');
224
+ 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; } });
225
+ let metadata;
226
+ 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. */ }
227
+ const usage = tryUsage(metadata);
228
+ ports.stderr.write(`${tryUsageLine(usage)}\n`);
229
+ const descriptor = { callCap: usage.cap, version: 1, root, sessionId, origin, login: identity.login, prompt: step.entry_path, operation: step.operation,
230
+ 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,
231
+ criterion: step.checks[0]?.criterion_id, storyHash: hash(readFileSync(join(root, test.doc.story_path))),
232
+ promptHash: hash(prompt.text), stateDir: store.dir, repoState: join(store.folder('repos'), `${store.repoKey(root)}.json`) };
233
+ writePrivate(descriptorPath, descriptor);
234
+ const moduleUrl = ports.tryLauncherUrl ?? pathToFileURL(join(dirname(fileURLToPath(import.meta.url)), 'try-doors.mjs')).href;
235
+ 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; });`;
236
+ const code = `#!/bin/sh\n# PDD Try launcher v1\nexec ${quote(process.execPath)} --input-type=commonjs -e ${quote(script)} -- ${quote(moduleUrl)} ${quote(descriptorPath)} \"$@\"\n`;
237
+ const fd = openSync(shim, constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW, 0o700);
238
+ try { writeFileSync(fd, code); } finally { closeSync(fd); }
239
+ chmodSync(shim, 0o700);
240
+ ports.stdout.write(`Try is ready: ${name}\n${shim}\nexport PATH=${quote(bin)}:"$PATH"\n`);
241
+ const examples = [...new Set(test.doc.steps.filter(s => s.entry_path === step.entry_path && s.operation === step.operation && Array.isArray(s.input?.argv))
242
+ .map(s => [name, ...s.input.argv].map(quote).join(' ')))];
243
+ if (examples.length) ports.stdout.write(`Examples from this Story:\n${examples.map(s => ` ${s}`).join('\n')}\n`);
244
+ if (options['--shell']) {
245
+ const chosen = ports.env.SHELL || '/bin/sh', shell = ['bash', 'zsh', 'sh'].includes(basename(chosen)) ? chosen : '/bin/sh';
246
+ const env = { ...ports.env, PATH: `${bin}:${ports.env.PATH || process.env.PATH || ''}` };
247
+ if (ports.shell) return ports.shell(shell, env, root);
248
+ 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))); });
249
+ }
250
+ return 0;
251
+ }
252
+
253
+ async function invalidate(descriptor, path) {
254
+ const last = join(dirname(path), `${descriptor.sessionId}.last.json`), invocationId = randomUUID();
255
+ await withRepositoryRunLockAsync(descriptor.repoState, () => {
256
+ regular(descriptor.repoState);
257
+ writePrivate(last, {state:'unknown',invocationId});
258
+ writePrivate(descriptor.repoState, {...read(descriptor.repoState),last_door:{descriptor:path,last}});
259
+ });
260
+ return {last,invocationId};
261
+ }
262
+ export async function runShim(descriptorPath, argv, givenPorts = {}) {
263
+ const ports = {
264
+ ...givenPorts,
265
+ env: givenPorts.env ?? process.env,
266
+ stdout: givenPorts.stdout ?? process.stdout,
267
+ stderr: givenPorts.stderr ?? process.stderr,
268
+ stdin: givenPorts.stdin ?? process.stdin,
269
+ };
270
+ try {
271
+ regular(descriptorPath);
272
+ const d = read(descriptorPath);
273
+ if(d.directProgram){
274
+ if(d.version!==1||(!d.sessionId&&!d.shellBootstrap)||!d.root||realpathSync(d.root)!==d.root||d.programDir!==dirname(descriptorPath))fail('The direct program record is invalid.');
275
+ return await runDirectShim(d,descriptorPath,argv,ports);
276
+ }
277
+ 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.');
278
+ const {last,invocationId} = await invalidate(d, descriptorPath), input = { argv: [...argv] };
279
+ 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.');
280
+ checkEffectivePrompts(d.root,d.promptHashes ?? {[d.prompt]:d.promptHash},d.effectivePromptHashes);
281
+ if (d.inputSchema.properties?.stdin && !ports.stdin.isTTY) {
282
+ const parts = []; let bytes = 0;
283
+ 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); }
284
+ const value = new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(parts));
285
+ input.stdin = value;
286
+ } else if (d.inputSchema.required?.includes('stdin')) input.stdin = '';
287
+ // A person at a terminal sees that a slow command still runs; a pipe or an agent gets only the program's output.
288
+ const note = ports.stderr.isTTY ? setTimeout(() => ports.stderr.write(`pdd: running ${d.name ?? 'the command'} on the Try…\n`), 2000) : null;
289
+ let answer;
290
+ try { answer = await runDoorCall(d, input, { ...ports, ghPath: d.ghPath, env: { ...ports.env, PDD_STATE_DIR: d.stateDir } }); } finally { clearTimeout(note); }
291
+ const result = answer.result;
292
+ 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.');
293
+ await withRepositoryRunLockAsync(d.repoState, () => {
294
+ regular(last);
295
+ if (read(last).invocationId === invocationId) writePrivate(last, {state:'confirmed',invocationId,id:answer.id,input,result,inputWorld:answer.inputWorld,world:answer.world});
296
+ });
297
+ ports.stdout.write(result.stdout); ports.stderr.write(result.stderr);
298
+ ports.stderr.write(`${result.stderr && !result.stderr.endsWith('\n') ? '\n' : ''}${tryUsageLine(answer.usage, { command: true })}\n`);
299
+ return result.exit_code;
300
+ } catch (e) {
301
+ if (e?.unboundPort) throw e;
302
+ const reason = e.code === 'ENOENT' ? 'No Try session is available. Run pdd simulate STORY --cli again.'
303
+ : e instanceof TypeError && /encoded data/.test(e.message) ? 'Piped stdin must be UTF-8 text.' : cleanText(e.message || 'The command could not run.');
304
+ ports.stderr.write(`pdd: ${reason}\n${tryUsageLine(e.tryUsage ?? tryUsage({}), { command: true })}\n`); return WRAPPER_EXIT;
305
+ }
306
+ }
307
+
308
+ export async function saveLast({ root, store, identity, ports, test }) {
309
+ const repo = store.repo(root), pointer = test ? null : repo.last_door;
310
+ if (!test && !pointer) fail('No last command is available. Run a command through the Try command first.');
311
+ if (pointer) { regular(pointer.descriptor); regular(pointer.last); }
312
+ const last = test ? repo.last_run : read(pointer.last), d = test ? repo.last_run?.descriptor : read(pointer.descriptor);
313
+ if (last?.state !== 'confirmed') fail('The last command result is unknown; there is no confirmed output to save.');
314
+ if (!d || d.root !== root || identity.login !== d.login) fail(`This Try belongs to ${d?.login ?? 'another owner'}. Run: gh auth switch -u ${d?.login ?? 'OWNER'}`);
315
+ if (!test && (d.programEntry || !d.originalPath || !d.storyPath)) fail('This program run has no selected Story. Its observed result cannot be appended as a Story case.');
316
+ const originalPath = test?.path ?? d.originalPath, storyPath = test?.doc.story_path ?? d.storyPath;
317
+ if (test ? last.saved?.includes(originalPath) : last.saved) { ports.stdout.write('The last command is already saved.\n'); return 0; }
318
+ const capture = ports.captureSource ?? ((r,o)=>captureSource(r,o,ports));
319
+ const authority = () => {
320
+ const policy = loadRuntimeWorkspace({root});
321
+ requireRuntimePath(policy,{path:originalPath,role:'original test'});
322
+ requireRuntimePath(policy,{path:storyPath,role:'original Story'});
323
+ for (const path of new Set([d.prompt,...Object.keys(d.promptHashes??{}),...Object.keys(d.effectivePromptHashes??{})].filter(Boolean))) requireRuntimePath(policy,{path,role:'recorded prompt'});
324
+ };
325
+ authority();
326
+ const storyHash = test ? hash(readFileSync(join(root,storyPath))) : d.storyHash;
327
+ const checkFresh = () => {
328
+ authority();
329
+ capture(root,{tests:[d.prompt]});
330
+ if (hash(readFileSync(join(root,storyPath))) !== 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.');
331
+ checkEffectivePrompts(root,d.promptHashes??{[d.prompt]:d.promptHash},d.effectivePromptHashes);
332
+ if (read(join(root,originalPath)).story_path !== storyPath) fail('The original Story test identity changed. Add the input and the right expected value by hand.');
333
+ };
334
+ checkFresh();
335
+ const original = read(join(root,originalPath));
336
+ const tied = test ? [...new Set(original.steps.filter(step=>step.entry_path===d.prompt&&step.operation===d.operation).flatMap(step=>(step.checks??[]).map(check=>check.criterion_id)))] : [d.criterion];
337
+ if (tied.length !== 1 || !original.criteria.some(item=>item.id===tied[0])) fail('The Story must associate exactly one criterion with this run entry. Add the case and the right expected value by hand.');
338
+ if (!last.inputWorld || typeof last.inputWorld !== 'object' || Array.isArray(last.inputWorld)) fail('The interpreter did not provide confirmed data before this run. Add the input and the right expected value by hand.');
339
+ const manual = `Nothing added. To write the right expected value by hand, edit ${originalPath}: add the input to steps and the expected value to checks (target: "result", op: "equals", value: your correct answer).\n`;
340
+ ports.stdout.write(`Input:\n${JSON.stringify(last.input,null,2)}\nData before:\n${JSON.stringify(last.inputWorld,null,2)}\nOutput:\n${JSON.stringify(last.result,null,2)}\n`);
341
+ if (!ports.stdin?.isTTY || !ports.stdout?.isTTY) {
342
+ ports.stderr.write('A person must answer "Is this answer right? [y/N]" in a terminal. '+manual);
343
+ return WRAPPER_EXIT;
344
+ }
345
+ const checkCurrent = () => {
346
+ const current = store.repo(root);
347
+ if (test) {
348
+ if (current.last_run?.state !== 'confirmed' || current.last_run.id !== last.id) fail('The last command was superseded or is unknown. Run the command again before saving.');
349
+ return current;
350
+ }
351
+ if (current.last_door?.descriptor !== pointer.descriptor || current.last_door?.last !== pointer.last) fail('The last command was superseded. Run the command again before saving.');
352
+ regular(pointer.last);
353
+ const latest = read(pointer.last);
354
+ if (latest.state !== 'confirmed' || latest.id !== last.id || latest.invocationId !== last.invocationId) fail('The last command was superseded or is unknown. Run the command again before saving.');
355
+ return current;
356
+ };
357
+ const repoState = test ? join(store.folder('repos'), `${store.repoKey(root)}.json`) : d.repoState;
358
+ const locked = action => store.withRepoLock ? store.withRepoLock(root,action) : withRepositoryRunLockAsync(repoState,action);
359
+ const answers = (ports.lineReader ?? defaultLineReader)(ports.stdin);
360
+ try {
361
+ ports.stdout.write('Is this answer right? [y/N]\n');
362
+ if (!/^y$/i.test((await answers.ask()).trim())) { ports.stdout.write(manual); return 0; }
363
+ const step = {step_id:`try-${last.id}`,entry_path:d.prompt,operation:d.operation,input:last.input,
364
+ checks:[{criterion_id:tied[0],target:'result',path:'',op:'equals',value:last.result}]};
365
+ const saved = {id:last.id,name:'Recorded terminal command',story_path:storyPath,original_path:originalPath,
366
+ test:{schema_version:'prompt-runtime.program-scenario.v1',story_path:storyPath,criteria:original.criteria,
367
+ initial_world:last.inputWorld,...(Object.keys(original.simulation??{}).length?{simulation:original.simulation}:{}),...(original.context?.length?{context:original.context}:{}),steps:[step]}};
368
+ const publish = writeOwnership => locked(() => {
369
+ const current = checkCurrent(); checkFresh(); capture(root,{tests:[originalPath]});
370
+ const outcome = saveDoorCaseResult(root,saved,{writeOwnership,signal:ports.signal,env:ports.env,ports,publicationGuard:()=>{checkCurrent();checkFresh();}});
371
+ if (outcome.kind === 'case' && outcome.result.state === 'committed') {
372
+ if (test) store.write(repoState,{...current,last_run:{...current.last_run,saved:[...new Set([...(current.last_run.saved??[]),originalPath])]}});
373
+ else writePrivate(pointer.last,{...read(pointer.last),saved:true});
374
+ }
375
+ return outcome;
376
+ });
377
+ let outcome = await publish();
378
+ if (outcome.kind === 'failure') fail(outcome.message);
379
+ const refuse = (result,error) => { ports.stderr.write(`pdd: ${error?cleanText(error)+'. ':''}${result.message}\n`); return WRAPPER_EXIT; };
380
+ if (outcome.result.state === 'pending') {
381
+ let lease;
382
+ try {
383
+ if (ports.caseHandoff) {
384
+ const handoff = await ports.caseHandoff({root,testPath:originalPath,signal:ports.signal});
385
+ if (handoff) lease = await acquireCaseWriteOwnership({root,testPath:originalPath,handoff,signal:ports.signal},{...ports,env:ports.env});
386
+ } else {
387
+ ports.stdout.write(`Close the editor for ${originalPath}. Hand over this closed file for the pending case apply? y/N\n`);
388
+ if (/^y(?:es)?$/i.test((await answers.ask()).trim())) lease = await acquireCaseWriteOwnership({root,testPath:originalPath,handoff:{kind:'closed-editor',testPath:originalPath},signal:ports.signal},{...ports,env:ports.env});
389
+ }
390
+ if (lease) outcome = await publish(lease);
391
+ } catch (error) { if(error?.unboundPort)throw error; return refuse(outcome,error.message??error); }
392
+ finally { lease?.release(); }
393
+ }
394
+ if (outcome.kind === 'failure') fail(outcome.message);
395
+ if (outcome.result.state !== 'committed') return refuse(outcome);
396
+ const actualStep = outcome.result.steps?.[0] ?? step.step_id;
397
+ ports.stdout.write(`Added to ${originalPath} as step ${actualStep}. Review the data before this step, then run: pdd test ${test?.story ?? basename(storyPath,'.md')}\n`);
398
+ return 0;
399
+ } finally { answers.close(); }
400
+ }
401
+
402
+ // Direct typed commands share the executable schema subset, but never defer input
403
+ // validation to a model. In particular, unsupported schemas cannot skip checks.
404
+ const typedObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
405
+ function typedEqual(left,right) {
406
+ // Native numeric equality gives JSON's single zero value. Recurse without
407
+ // coercing scalar types, object members or array positions.
408
+ if(left===right)return true;
409
+ if(Array.isArray(left))return Array.isArray(right)&&left.length===right.length&&left.every((value,index)=>typedEqual(value,right[index]));
410
+ if(!typedObject(left)||!typedObject(right))return false;
411
+ const names=Object.keys(left);
412
+ return names.length===Object.keys(right).length&&names.every(name=>Object.hasOwn(right,name)&&typedEqual(left[name],right[name]));
413
+ }
414
+ const typedJson = text => JSON.parse(text,(key,value)=>{
415
+ if (typeof value==='number' && !Number.isFinite(value)) throw Error('JSON numbers must be finite.');
416
+ return value;
417
+ });
418
+ function typedMultipleOf(value, step) {
419
+ // Compare exact decimal Number spellings, including scientific notation.
420
+ const decimal = number => {
421
+ const [mantissa, exponent='0'] = String(number).split('e');
422
+ const [whole, fraction=''] = mantissa.split('.');
423
+ return {coefficient:BigInt(whole+fraction), exponent:Number(exponent)-fraction.length};
424
+ };
425
+ const valueParts=decimal(value), stepParts=decimal(step);
426
+ const difference=valueParts.exponent-stepParts.exponent;
427
+ return difference>=0
428
+ ? (valueParts.coefficient*10n**BigInt(difference))%stepParts.coefficient===0n
429
+ : valueParts.coefficient%(stepParts.coefficient*10n**BigInt(-difference))===0n;
430
+ }
431
+ class UnsupportedTypedPattern extends Error {
432
+ constructor() { super('Unsupported input pattern: local validation requires portable syntax and printable ASCII input.'); }
433
+ }
434
+ function typedPattern(source) {
435
+ // Keep membership evidence within the common JavaScript/Python domain.
436
+ // Outside printable ASCII, classes, dot and end anchors can disagree.
437
+ if (/[^\x20-\x7e]/u.test(source) || /\[\^?\]/u.test(source)
438
+ || /\\(?:[1-9bBAZzGkpPuU]|x|c)|\(\?/u.test(source)
439
+ // Python refuses overflowing repetition counts that JavaScript can compile.
440
+ || /\{(?:\d{10,}(?:,\d*)?|\d*,\d{10,})\}/u.test(source)) throw new UnsupportedTypedPattern();
441
+ try { return new RegExp(source,'u'); } catch { throw new UnsupportedTypedPattern(); }
442
+ }
443
+ function typedValidation(value, schema) {
444
+ const issues = interfaceSchemaProblems({entries:[{input_schema:schema}],limits:{max_steps:1,max_model_calls:1}});
445
+ if (issues.length) throw Error(`Unsupported input schema: ${issues[0].pointer} ${issues[0].rule}`);
446
+ // Unsupported pattern syntax refuses even on omitted or unused branches.
447
+ const patterns=new Map();
448
+ const compile=shape=>{
449
+ if(typeof shape.pattern==='string') patterns.set(shape,typedPattern(shape.pattern));
450
+ if(Array.isArray(shape.oneOf)) shape.oneOf.forEach(compile);
451
+ if(shape.type==='object') Object.values(shape.properties).forEach(compile);
452
+ if(shape.type==='array') compile(shape.items);
453
+ };
454
+ compile(schema);
455
+ const visit = (item, shape) => {
456
+ if (Array.isArray(shape.oneOf)) {
457
+ const matches = shape.oneOf.filter(part => {
458
+ try { visit(item,part); return true; }
459
+ catch (error) { if(error instanceof UnsupportedTypedPattern) throw error; return false; }
460
+ });
461
+ if (matches.length !== 1) throw Error('Input must match exactly one allowed shape.');
462
+ return;
463
+ }
464
+ const invalid = reason => {throw Error(`Input ${reason}`);};
465
+ const type=item===null?'null':Array.isArray(item)?'array':typeof item;
466
+ if(shape.type==='integer'? !Number.isInteger(item) : shape.type==='object'? !typedObject(item) : shape.type!==type) invalid(`must be ${shape.type}.`);
467
+ if (shape.enum && !shape.enum.some(choice=>typedEqual(item,choice))) invalid('is not an allowed enum value.');
468
+ if (Object.hasOwn(shape,'const') && !typedEqual(item,shape.const)) invalid('does not match its const value.');
469
+ if (typeof item==='number') {
470
+ if(!Number.isFinite(item)) invalid('numbers must be finite.');
471
+ if(shape.minimum!==undefined && item<shape.minimum || shape.maximum!==undefined && item>shape.maximum
472
+ || shape.exclusiveMinimum!==undefined && item<=shape.exclusiveMinimum || shape.exclusiveMaximum!==undefined && item>=shape.exclusiveMaximum) invalid('is outside its numeric bounds.');
473
+ if(shape.multipleOf!==undefined && !typedMultipleOf(item,shape.multipleOf)) invalid('must be a multiple of its declared step.');
474
+ }
475
+ if (typeof item==='string') {
476
+ const length=[...item].length;
477
+ if(shape.minLength!==undefined && length<shape.minLength || shape.maxLength!==undefined && length>shape.maxLength) invalid('is outside its string length bounds.');
478
+ if(patterns.has(shape)) {
479
+ if(/[^\x20-\x7e]/u.test(item)) throw new UnsupportedTypedPattern();
480
+ if(!patterns.get(shape).test(item)) invalid('does not match its pattern.');
481
+ }
482
+ }
483
+ if (Array.isArray(item)) {
484
+ if(shape.minItems!==undefined && item.length<shape.minItems || shape.maxItems!==undefined && item.length>shape.maxItems) invalid('is outside its array length bounds.');
485
+ if(shape.uniqueItems && item.some((child,index)=>item.slice(0,index).some(other=>typedEqual(child,other)))) invalid('requires unique array items.');
486
+ item.forEach(child=>visit(child,shape.items));
487
+ }
488
+ if (typedObject(item)) {
489
+ const count=Object.keys(item).length;
490
+ if(shape.minProperties!==undefined && count<shape.minProperties || shape.maxProperties!==undefined && count>shape.maxProperties) invalid('is outside its field count bounds.');
491
+ for(const name of shape.required) if(!Object.hasOwn(item,name)) invalid(`requires field ${name}.`);
492
+ for(const [name,child] of Object.entries(item)) {
493
+ if(!Object.hasOwn(shape.properties,name)) invalid(`has unknown field ${name}.`);
494
+ visit(child,shape.properties[name]);
495
+ }
496
+ }
497
+ };
498
+ visit(value,schema);
499
+ }
500
+
501
+ function typedInputJson(value) {
502
+ if (Array.isArray(value)) return '['+value.map(typedInputJson).join(',')+']';
503
+ if (typedObject(value)) return '{'+Object.keys(value).sort().map(name=>JSON.stringify(name)+':'+typedInputJson(value[name])).join(',')+'}';
504
+ return JSON.stringify(value);
505
+ }
506
+
507
+ export function prepareTypedInvocation({prompt_path,argv,interface_json,stdin_json,input_file_json}) {
508
+ let entries = [], selected;
509
+ const usage = () => {
510
+ const properties=typedObject(selected?.input_schema?.properties)?selected.input_schema.properties:{};
511
+ const required=Array.isArray(selected?.input_schema?.required)?selected.input_schema.required:[];
512
+ const fields=Object.entries(properties).filter(([,schema])=>typedObject(schema) && (typeof schema.type==='string' || Array.isArray(schema.oneOf)));
513
+ return `Usage: pdd ${prompt_path} [OPERATION] [--field value ... | --input JSON|@file]\nOperations: ${entries.map(entry=>entry.operation).join(', ')}\n`
514
+ + (selected ? 'Fields:\n'+fields.map(([name,schema])=>` --${name} <${typeof schema.type==='string'?schema.type:'oneOf'}> (${required.includes(name)?'required':'optional'})\n`).join('') : '');
515
+ };
516
+ const local = (kind,reason='') => ({kind,operation:null,input_json:null,stdout:'',stderr:(reason?reason+'\n':'')+usage(),exit_code:2});
517
+ try {
518
+ const iface=typedJson(interface_json);
519
+ if (!Array.isArray(iface?.entries) || !iface.entries.length || iface.entries.some(entry=>typeof entry?.operation!=='string')) throw Error('The typed interface is unavailable.');
520
+ entries=iface.entries;
521
+ const args=[...argv];
522
+ const word=args[0] && !args[0].startsWith('-') ? args.shift() : undefined;
523
+ const matches=word===undefined ? entries.length===1?entries:[] : entries.filter(entry=>entry.operation===word);
524
+ if (matches.length===1) selected=matches[0];
525
+ if (args.includes('--help')) return local('help');
526
+ if (!selected) throw Error(word===undefined?'Choose an operation.':'Unknown or ambiguous operation.');
527
+ const schema=selected.input_schema;
528
+ // Validate the schema even when all fields are optional.
529
+ const schemaIssues=interfaceSchemaProblems({entries:[{input_schema:schema}],limits:{max_steps:1,max_model_calls:1}});
530
+ if (schemaIssues.length) throw Error(`Unsupported input schema: ${schemaIssues[0].pointer} ${schemaIssues[0].rule}`);
531
+ let input={}, whole, fields=0, wholeCount=0;
532
+ const scalar=(token,shape)=>{
533
+ if (shape?.type==='string') return token;
534
+ if (shape?.type==='boolean' && ['true','false'].includes(token)) return token==='true';
535
+ if (['integer','number'].includes(shape?.type) && /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(token)) {
536
+ const value=Number(token);
537
+ if (Number.isFinite(value) && (shape.type!=='integer' || Number.isInteger(value))) return value;
538
+ }
539
+ throw Error('Invalid scalar value or unsupported flag shape. Use --input for objects and non-scalar arrays.');
540
+ };
541
+ for (let index=0;index<args.length;index++) {
542
+ const flag=args[index], token=args[++index];
543
+ if (!/^--[^=]+$/.test(flag) || token===undefined || token.startsWith('--')) throw Error('Each field flag needs a value.');
544
+ const name=flag.slice(2);
545
+ if (name==='input') { wholeCount++; whole=token; continue; }
546
+ if (schema.type!=='object') throw Error('Field flags require top-level schema properties. Use --input for this input shape.');
547
+ if (!Object.hasOwn(schema.properties,name)) throw Error(`Unknown field: ${flag}.`);
548
+ fields++;
549
+ const shape=schema.properties[name];
550
+ if (shape.type==='array') {
551
+ if (!Object.hasOwn(input,name)) Object.defineProperty(input,name,{value:[],enumerable:true,writable:true,configurable:true});
552
+ input[name].push(scalar(token,shape.items));
553
+ } else {
554
+ if (Object.hasOwn(input,name)) throw Error(`Repeated field: ${flag}.`);
555
+ Object.defineProperty(input,name,{value:scalar(token,shape),enumerable:true,writable:true,configurable:true});
556
+ }
557
+ }
558
+ if (wholeCount>1 || wholeCount && fields) throw Error('Use one --input or field flags.');
559
+ if (wholeCount) input=typedJson(whole.startsWith('@') ? input_file_json : whole);
560
+ else if (!fields && stdin_json!==undefined) input=typedJson(stdin_json);
561
+ if (!typedObject(input)) throw Error('Input must be a JSON object.');
562
+ typedValidation(input,schema);
563
+ return {kind:'call',operation:selected.operation,input_json:typedInputJson(input),stdout:'',stderr:'',exit_code:0};
564
+ } catch (error) { return local('usage',error instanceof SyntaxError?'Input must be valid JSON.':error.message); }
565
+ }
566
+
567
+ export function formatTypedOutcome({outcome,result_json,error_json}) {
568
+ try {
569
+ if (outcome==='result') return {stdout:JSON.stringify(typedJson(result_json))+'\n',stderr:'',exit_code:0};
570
+ const error=typedJson(error_json ?? '{}');
571
+ if (outcome==='program_error' && typeof error?.code==='string' && typeof error?.message==='string'
572
+ && (error.call_chain===undefined || Array.isArray(error.call_chain) && error.call_chain.every(row=>typeof row?.prompt==='string' && typeof row?.operation==='string'))) {
573
+ const chain=error.call_chain?.length ? 'Traceback (prompt calls):\n'+error.call_chain.map(row=>` ${row.prompt}: ${row.operation}\n`).join('') : '';
574
+ return {stdout:'',stderr:chain+`pdd: ${error.code}: ${error.message}\n`,exit_code:1};
575
+ }
576
+ return {stdout:'',stderr:`pdd: ${causeText(error?.message).replace(/https?:\/\/[^\s]+/gi,'<service>') || 'The PDD interpreter returned an incompatible outcome.'}\n`,exit_code:125};
577
+ } catch { return {stdout:'',stderr:'pdd: The PDD interpreter returned an incompatible outcome.\n',exit_code:125}; }
578
+ }
579
+
580
+ export { analyzePromptSelectorWords };
581
+
582
+ export function selectorLintForPrompts({ root, visible, paths, workspace }) {
583
+ const appMapScreens = readAppMapScreens(root, visible, workspace);
584
+ const warnings = [];
585
+ const tableLines = [];
586
+ const seen = new Set();
587
+ for (const path of paths ?? []) {
588
+ if (typeof path !== 'string' || seen.has(path)) continue;
589
+ seen.add(path);
590
+ let prompt;
591
+ try { prompt = readPrompt(root, visible, path, workspace); } catch { continue; }
592
+ const info = analyzePromptSelectorWords(prompt, { appMapScreens });
593
+ for (const warning of info.warnings) if (!warnings.includes(warning)) warnings.push(warning);
594
+ if (info.tableLines.length) tableLines.push(...info.tableLines);
595
+ }
596
+ return { warnings, tableLines };
597
+ }