@promptdriven/runtime-client 1.1.2 → 1.1.4

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.
@@ -4,7 +4,7 @@ import { createHash, randomUUID } from 'node:crypto';
4
4
  import { accessSync, chmodSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
5
5
  import { basename, dirname, join, resolve } from 'node:path';
6
6
  import { fileURLToPath, pathToFileURL } from 'node:url';
7
- import { findTests, gitFiles, readPrompt, captureSource, executableInterfaceText, interfaceSchemaProblems, readAppMapScreens, analyzePromptSelectorWords } from './runtime-preflight.mjs';
7
+ import { findTests, gitFiles, readPrompt, captureSource, executableInterfaceText, interfaceSchemaProblems, readAppMapScreens, analyzePromptSelectorWords, parsePlainMarkdownOperations } from './runtime-preflight.mjs';
8
8
  import { loadRuntimeWorkspace, requireRuntimePath } from './runtime-workspace.mjs';
9
9
  import { cleanText, causeText, tryUsage, tryUsageLine } from './runtime-output.mjs';
10
10
  import { runDoorCall, saveDoorCaseResult, acquireCaseWriteOwnership, withRepositoryRunLockAsync, defaultLineReader } from './runtime-client.mjs';
@@ -59,6 +59,35 @@ function excludeLaunchers(root) {
59
59
  if (!ignored.split('\n').includes('/.pdd/try/')) writeFileSync(exclude, `${ignored}${ignored.endsWith('\n') || !ignored ? '' : '\n'}/.pdd/try/\n`);
60
60
  }
61
61
 
62
+ export function plainCliEntry(prompt, step) {
63
+ if (!prompt || prompt.error !== 'interface-missing' || typeof prompt.text !== 'string') return null;
64
+ if (!step || typeof step.entry_path !== 'string' || typeof step.operation !== 'string') return null;
65
+ const stepInput = step.input;
66
+ const hasArgv = stepInput !== null && typeof stepInput === 'object' && !Array.isArray(stepInput)
67
+ && Array.isArray(stepInput.argv) && stepInput.argv.every(word => typeof word === 'string');
68
+ if (!hasArgv) return null;
69
+ const cliCue = /\b(?:cli|argv|stdout|stderr|exit_code|command-line)\b/i.test(prompt.text)
70
+ || (Array.isArray(step.checks) && step.checks.some(c => c?.target === 'result' && ['/stdout', '/stderr', '/exit_code'].includes(c?.path)));
71
+ if (!cliCue) return null;
72
+ const stdin = /\bstdin\s*(\?)?\s*:\s*string\b/.exec(prompt.text);
73
+ const stepHasStdin = Object.hasOwn(stepInput, 'stdin') && typeof stepInput.stdin === 'string';
74
+ const hasStdin = Boolean(stdin || stepHasStdin);
75
+ const requiredStdin = Boolean(stdin && !stdin[1]);
76
+ return {
77
+ operation: step.operation,
78
+ input_schema: {
79
+ type: 'object',
80
+ properties: {
81
+ argv: { type: 'array', items: { type: 'string' } },
82
+ ...(hasStdin ? { stdin: { type: 'string' } } : {}),
83
+ },
84
+ required: ['argv', ...(requiredStdin ? ['stdin'] : [])],
85
+ additionalProperties: false,
86
+ },
87
+ errors: [],
88
+ };
89
+ }
90
+
62
91
  function cliEntries(context, test) {
63
92
  const entries = new Map();
64
93
  for (const step of Array.isArray(test.doc?.steps) ? test.doc.steps : []) {
@@ -66,10 +95,14 @@ function cliEntries(context, test) {
66
95
  const prompt = readPrompt(context.root, context.visible, step.entry_path);
67
96
  const authoredEntries = Array.isArray(prompt.interface?.entries) ? prompt.interface.entries : [];
68
97
  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] });
98
+ if (index >= 0) {
99
+ const conventions = Array.isArray(prompt.interface.conventions) ? prompt.interface.conventions : [];
100
+ if (!['input_schema', 'result_schema'].every(key => conventions.some(c => c?.path === `/entries/${index}/${key}` && c.convention === 'cli'))) continue;
101
+ entries.set(`${step.entry_path}#${step.operation}`, { step, prompt, entry: authoredEntries[index] });
102
+ } else if (context.allowMissingInterfaces) {
103
+ const synthesized = plainCliEntry(prompt, step);
104
+ if (synthesized) entries.set(`${step.entry_path}#${step.operation}`, { step, prompt, entry: synthesized });
105
+ }
73
106
  }
74
107
  return entries;
75
108
  }
@@ -99,7 +132,8 @@ function cliEntry(context, test) {
99
132
  const prompt=context.directProgram.interface?{...source,interface:context.directProgram.interface,error:null}:source;
100
133
  if(prompt.error==='interface-missing'&&context.directProgram.allowMissingInterfaces){
101
134
  // 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]))];
135
+ const explicitOps=[...new Set([...prompt.text.matchAll(/\b(?:export|operation)\s+`?([A-Za-z_$][\w$]*)`?/gi)].map(match=>match[1]))];
136
+ const operations=explicitOps.length?explicitOps:[...parsePlainMarkdownOperations(prompt.text)];
103
137
  const stdin=/\bstdin\s*(\?)?\s*:\s*string\b/.exec(prompt.text);
104
138
  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
139
  entries=new Map([[path,{step:{entry_path:path,operation:entry.operation},prompt,entry,unadmitted:true}]]);
@@ -110,6 +144,32 @@ function cliEntry(context, test) {
110
144
  ? [[`${path}#${entry.operation}`,{step:{entry_path:path,operation:entry.operation},prompt,entry}]]:[]));
111
145
  if(entries.size!==1)fail('The entry prompt must declare exactly one command-line program.');
112
146
  }
147
+ } else if (context.programRecord && context.programEntry) {
148
+ const path = context.programEntry;
149
+ const prompt = readPrompt(context.root, context.visible, path);
150
+ if (prompt.error === 'interface-missing' && context.allowMissingInterfaces) {
151
+ const explicitOps = [...new Set([...prompt.text.matchAll(/\b(?:export|operation)\s+`?([A-Za-z_$][\w$]*)`?/gi)].map(match => match[1]))];
152
+ const operations = explicitOps.length ? explicitOps : [...parsePlainMarkdownOperations(prompt.text)];
153
+ const operation = operations.length === 1 ? operations[0] : 'main';
154
+ const stdin = /\bstdin\s*(\?)?\s*:\s*string\b/.exec(prompt.text);
155
+ const entry = {
156
+ operation,
157
+ input_schema: {
158
+ type: 'object',
159
+ properties: { argv: { type: 'array', items: { type: 'string' } }, ...(stdin ? { stdin: { type: 'string' } } : {}) },
160
+ required: ['argv', ...(stdin && !stdin[1] ? ['stdin'] : [])],
161
+ additionalProperties: false,
162
+ },
163
+ errors: [],
164
+ };
165
+ entries = new Map([[`${path}#${operation}`, { step: { entry_path: path, operation, checks: [] }, prompt, entry }]]);
166
+ } else {
167
+ const candidates = Array.isArray(prompt.interface?.entries) ? prompt.interface.entries : [];
168
+ const conventions = Array.isArray(prompt.interface?.conventions) ? prompt.interface.conventions : [];
169
+ entries = new Map(candidates.flatMap((entry, index) => ['input_schema', 'result_schema'].every(key => conventions.some(c => c?.path === `/entries/${index}/${key}` && c.convention === 'cli'))
170
+ ? [[`${path}#${entry.operation}`, { step: { entry_path: path, operation: entry.operation, checks: [] }, prompt, entry }]] : []));
171
+ if (entries.size !== 1) fail('The entry prompt must declare exactly one command-line program.');
172
+ }
113
173
  } else entries = cliEntries(context, test);
114
174
  if (entries.size !== 1) {
115
175
  if (entries.size) fail('This Story uses more than one command-line program. Choose a Story with one command-line program.');
@@ -122,14 +182,14 @@ function cliEntry(context, test) {
122
182
  }
123
183
  const value = [...entries.values()][0];
124
184
  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).');
185
+ 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 (see the pdd skill reference ports-and-cli.md, or run pdd help prompting).');
126
186
  return { ...value, name: heading };
127
187
  }
128
188
 
129
189
  async function directProgramInput(inputSchema,argv,ports){
130
- const input={argv};
190
+ const input={argv:Array.isArray(argv)?[...argv]:[]};
131
191
  try{
132
- if(inputSchema.properties?.stdin&&!ports.stdin.isTTY){
192
+ if(inputSchema?.properties?.stdin&&!ports.stdin.isTTY){
133
193
  const chunks=[];let bytes=0;
134
194
  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
195
  let abort;
@@ -139,7 +199,7 @@ async function directProgramInput(inputSchema,argv,ports){
139
199
  if(interrupted)await Promise.race([collect(),interrupted]);else await collect();
140
200
  }finally{if(abort)ports.signal.removeEventListener('abort',abort);}
141
201
  input.stdin=new TextDecoder('utf-8',{fatal:true}).decode(Buffer.concat(chunks));
142
- }else if(inputSchema.required?.includes('stdin'))input.stdin='';
202
+ }else if(inputSchema?.required?.includes('stdin'))input.stdin='';
143
203
 
144
204
  return input;
145
205
  }catch(error){
@@ -209,7 +269,7 @@ export async function openCli(context, test, sessionId, options) {
209
269
  if(context.directProgram)return openDirectCli(context,test,cliEntry(context,test));
210
270
  const { root, ports, store, identity, origin } = context;
211
271
  const { step, prompt, entry, name } = cliEntry(context, test);
212
- const record = store.repo(root).tries?.[test.path];
272
+ const record = context.programRecord ?? store.repo(root).tries?.[test.path];
213
273
  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
274
  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
275
  checkEffectivePrompts(root,record.prompt_hashes,record.effective_prompt_hashes);
@@ -226,10 +286,20 @@ export async function openCli(context, test, sessionId, options) {
226
286
  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
287
  const usage = tryUsage(metadata);
228
288
  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,
289
+ const modelEntries = Array.isArray(metadata?.entries) ? metadata.entries : [];
290
+ const modelEntry = modelEntries.find(e => e?.entry_path === step.entry_path && e?.operation === step.operation)
291
+ ?? (context.programRecord ? modelEntries.find(e => e?.entry_path === step.entry_path && e?.cli === true) ?? modelEntries.find(e => e?.entry_path === step.entry_path) : null);
292
+ const resolvedOperation = modelEntry?.operation ?? step.operation;
293
+ const resolvedInputSchema = (entry?.input_schema && typeof entry.input_schema === 'object' ? entry.input_schema : null)
294
+ ?? (modelEntry?.input_schema && typeof modelEntry.input_schema === 'object' ? modelEntry.input_schema : null)
295
+ ?? { type: 'object', properties: { argv: { type: 'array', items: { type: 'string' } } }, required: ['argv'], additionalProperties: false };
296
+ const declaredErrors = [...new Set([...(Array.isArray(entry?.errors) ? entry.errors : []), ...(Array.isArray(modelEntry?.errors) ? modelEntry.errors : [])].filter(e => typeof e === 'string'))];
297
+ const hasStoryDoc = typeof test?.doc?.story_path === 'string' && test.doc.story_path.length > 0;
298
+ const descriptor = { callCap: usage.cap, version: 1, root, sessionId, origin, login: identity.login, prompt: step.entry_path, operation: resolvedOperation,
230
299
  ...(options?.['--fresh'] === true ? { fresh: true } : {}),
231
- 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,
232
- criterion: step.checks[0]?.criterion_id, storyHash: hash(readFileSync(join(root, test.doc.story_path))),
300
+ ...(declaredErrors.length ? { declaredErrors } : {}),
301
+ ghPath: ghPath ? resolve(ghPath) : null, promptHashes: record.prompt_hashes, effectivePromptHashes:record.effective_prompt_hashes, name, inputSchema: resolvedInputSchema,
302
+ ...(hasStoryDoc ? { originalPath: test.path, storyPath: test.doc.story_path, criteria: test.doc.criteria, criterion: step.checks?.[0]?.criterion_id, storyHash: hash(readFileSync(join(root, test.doc.story_path))) } : { programEntry: step.entry_path }),
233
303
  promptHash: hash(prompt.text), stateDir: store.dir, repoState: join(store.folder('repos'), `${store.repoKey(root)}.json`) };
234
304
  writePrivate(descriptorPath, descriptor);
235
305
  const moduleUrl = ports.tryLauncherUrl ?? pathToFileURL(join(dirname(fileURLToPath(import.meta.url)), 'try-doors.mjs')).href;
@@ -239,7 +309,7 @@ export async function openCli(context, test, sessionId, options) {
239
309
  try { writeFileSync(fd, code); } finally { closeSync(fd); }
240
310
  chmodSync(shim, 0o700);
241
311
  ports.stdout.write(`Try is ready: ${name}\n${shim}\nexport PATH=${quote(bin)}:"$PATH"\n`);
242
- const examples = [...new Set(test.doc.steps.filter(s => s.entry_path === step.entry_path && s.operation === step.operation && Array.isArray(s.input?.argv))
312
+ const examples = [...new Set((Array.isArray(test?.doc?.steps) ? test.doc.steps : []).filter(s => s.entry_path === step.entry_path && s.operation === step.operation && Array.isArray(s.input?.argv))
243
313
  .map(s => [name, ...s.input.argv].map(quote).join(' ')))];
244
314
  if (examples.length) ports.stdout.write(`Examples from this Story:\n${examples.map(s => ` ${s}`).join('\n')}\n`);
245
315
  if (options['--shell']) {
@@ -254,9 +324,15 @@ export async function openCli(context, test, sessionId, options) {
254
324
  async function invalidate(descriptor, path) {
255
325
  const last = join(dirname(path), `${descriptor.sessionId}.last.json`), invocationId = randomUUID();
256
326
  await withRepositoryRunLockAsync(descriptor.repoState, () => {
257
- regular(descriptor.repoState);
258
- writePrivate(last, {state:'unknown',invocationId});
259
- writePrivate(descriptor.repoState, {...read(descriptor.repoState),last_door:{descriptor:path,last}});
327
+ if (existsSync(descriptor.repoState)) {
328
+ regular(descriptor.repoState);
329
+ writePrivate(last, {state:'unknown',invocationId});
330
+ writePrivate(descriptor.repoState, {...read(descriptor.repoState),last_door:{descriptor:path,last}});
331
+ } else {
332
+ mkdirSync(dirname(descriptor.repoState), { recursive: true, mode: 0o700 });
333
+ writePrivate(last, {state:'unknown',invocationId});
334
+ writePrivate(descriptor.repoState, {last_door:{descriptor:path,last}});
335
+ }
260
336
  });
261
337
  return {last,invocationId};
262
338
  }
@@ -271,26 +347,32 @@ export async function runShim(descriptorPath, argv, givenPorts = {}) {
271
347
  try {
272
348
  regular(descriptorPath);
273
349
  const d = read(descriptorPath);
350
+ const args = Array.isArray(argv) ? [...argv] : [];
274
351
  if(d.directProgram){
275
352
  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.');
276
- return await runDirectShim(d,descriptorPath,argv,ports);
353
+ return await runDirectShim(d,descriptorPath,args,ports);
277
354
  }
278
355
  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.');
279
- const {last,invocationId} = await invalidate(d, descriptorPath), input = { argv: [...argv] };
356
+ const {last,invocationId} = await invalidate(d, descriptorPath), input = { argv: args };
280
357
  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.');
281
358
  checkEffectivePrompts(d.root,d.promptHashes ?? {[d.prompt]:d.promptHash},d.effectivePromptHashes);
282
- if (d.inputSchema.properties?.stdin && !ports.stdin.isTTY) {
359
+ if (d.inputSchema?.properties?.stdin && !ports.stdin.isTTY) {
283
360
  const parts = []; let bytes = 0;
284
361
  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); }
285
362
  const value = new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(parts));
286
363
  input.stdin = value;
287
- } else if (d.inputSchema.required?.includes('stdin')) input.stdin = '';
364
+ } else if (d.inputSchema?.required?.includes('stdin')) input.stdin = '';
288
365
  // A person at a terminal sees that a slow command still runs; a pipe or an agent gets only the program's output.
289
366
  const note = ports.stderr.isTTY ? setTimeout(() => ports.stderr.write(`pdd: running ${d.name ?? 'the command'} on the Try…\n`), 2000) : null;
290
367
  let answer;
291
368
  try { answer = await runDoorCall(d, input, { ...ports, ghPath: d.ghPath, env: { ...ports.env, PDD_STATE_DIR: d.stateDir } }); } finally { clearTimeout(note); }
369
+ if (answer.error) {
370
+ const errText = `${answer.error.code ? `${answer.error.code}: ` : ''}${answer.error.message || ''}`.trim() || 'The command returned an error.';
371
+ ports.stderr.write(`${errText}\n${tryUsageLine(answer.usage, { command: true })}\n`);
372
+ return 1;
373
+ }
292
374
  const result = answer.result;
293
- 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.');
375
+ if (!result || typeof result.stdout !== 'string' || typeof result.stderr !== 'string' || !Number.isInteger(result.exit_code) || result.exit_code < 0 || result.exit_code > 255 || result.exit_code === WRAPPER_EXIT) fail('The prompt must return stdout, stderr and an exit_code from 0–255 except reserved code 125.');
294
376
  await withRepositoryRunLockAsync(d.repoState, () => {
295
377
  regular(last);
296
378
  if (read(last).invocationId === invocationId) writePrivate(last, {state:'confirmed',invocationId,id:answer.id,input,result,inputWorld:answer.inputWorld,world:answer.world});
@@ -1,4 +1,5 @@
1
- // Generated from prompts/cli/try-http.prompt.md (sha256: 31a599108c95b490698b28941fda14ecf6405a8e4a5a00bd9539c8c351c4d3b7).
1
+ // Generated from prompts/cli/try-http.prompt.md (sha256: ad6dc1066b8cae67789281372bba11a2ec570e083e139e8f23e8bd55136a9a76).
2
+ import { timingSafeEqual } from 'node:crypto';
2
3
  import { createServer, validateHeaderName, validateHeaderValue } from 'node:http';
3
4
  import { join, relative } from 'node:path';
4
5
  import {loadRuntimeWorkspace} from './runtime-workspace.mjs';
@@ -8,10 +9,128 @@ import { runDoorCall } from './runtime-client.mjs';
8
9
  import { preferWaitHeaders, WAIT_PREFER_CALL_SECONDS } from './runtime-stream.mjs';
9
10
 
10
11
  const problem = (status, message) => Object.assign(new Error(message), { httpStatus: status });
12
+ const invalidOption = message => Object.assign(new Error(message), { exitCode: 2, httpStatus: 400 });
11
13
  const shellWord = word => /^[A-Za-z0-9_./:@%+=,-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`;
12
14
  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
13
15
  const HOP = new Set(['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'content-length']);
14
16
  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']);
17
+ const EXPOSED_USAGE_HEADERS = [...RESERVED_USAGE].join(', ');
18
+ const FORBIDDEN_GATE_HEADERS = new Set([...HOP, ...RESERVED_USAGE, 'host', 'origin', 'content-type', 'cookie', 'sec-fetch-site', 'sec-fetch-dest', 'sec-fetch-mode', 'x-forwarded-host', 'x-forwarded-proto', 'x-forwarded-for']);
19
+ export const SERVE_OPTION_KEYS = Object.freeze(['--allow-origins', '--trust-proxy', '--serve-token', '--serve-header']);
20
+
21
+ function parseAllowedOrigin(raw) {
22
+ if (typeof raw !== 'string') return null;
23
+ const trimmed = raw.trim();
24
+ if (!trimmed || trimmed.includes('*') || /\s/.test(trimmed)) return null;
25
+ let parsed;
26
+ try { parsed = new URL(trimmed); } catch { return null; }
27
+ if (!['http:', 'https:'].includes(parsed.protocol)) return null;
28
+ if (parsed.username || parsed.password || parsed.search || parsed.hash || parsed.pathname !== '/') return null;
29
+ if (!parsed.hostname || parsed.origin === 'null') return null;
30
+ const bare = trimmed.endsWith('/') && !trimmed.endsWith('//') ? trimmed.slice(0, -1) : trimmed;
31
+ if (/[?#]/.test(bare) || bare.slice(parsed.protocol.length + 2).includes('/')) return null;
32
+ return parsed.origin;
33
+ }
34
+
35
+ function parseHostHeader(raw) {
36
+ if (typeof raw !== 'string') return null;
37
+ const trimmed = raw.trim();
38
+ if (!trimmed || /[\s/@\\?#\r\n\0]/.test(trimmed)) return null;
39
+ let parsed;
40
+ try { parsed = new URL(`http://${trimmed}`); } catch { return null; }
41
+ if (parsed.username || parsed.password || parsed.pathname !== '/' || parsed.search || parsed.hash || !parsed.hostname) return null;
42
+ if (trimmed.startsWith('[')) {
43
+ const close = trimmed.indexOf(']');
44
+ if (close === -1) return null;
45
+ const rest = trimmed.slice(close + 1);
46
+ if (rest && !/^:[1-9][0-9]{0,4}$/.test(rest)) return null;
47
+ if (rest && Number(rest.slice(1)) > 65535) return null;
48
+ } else {
49
+ const colon = trimmed.indexOf(':');
50
+ if (colon !== -1) {
51
+ const portText = trimmed.slice(colon + 1);
52
+ if (!/^[1-9][0-9]{0,4}$/.test(portText) || Number(portText) > 65535) return null;
53
+ }
54
+ }
55
+ return trimmed.toLowerCase();
56
+ }
57
+
58
+ function originFromHost(proto, host) {
59
+ try { return new URL(`${proto}://${host}`).origin; } catch { return null; }
60
+ }
61
+
62
+ function safeEqual(a, b) {
63
+ if (typeof a !== 'string' || typeof b !== 'string') return false;
64
+ const left = Buffer.from(a, 'utf8'), right = Buffer.from(b, 'utf8');
65
+ return left.length === right.length && timingSafeEqual(left, right);
66
+ }
67
+
68
+ export function parseServeOptions(options = {}) {
69
+ if (!object(options)) throw invalidOption('Serve options must be an object.');
70
+ if (options['--trust-proxy'] !== undefined && typeof options['--trust-proxy'] !== 'boolean') {
71
+ throw invalidOption('--trust-proxy takes no value.');
72
+ }
73
+ const trustProxy = options['--trust-proxy'] === true;
74
+ const allowOrigins = new Set();
75
+ if (options['--allow-origins'] !== undefined) {
76
+ const raw = options['--allow-origins'];
77
+ const items = typeof raw === 'string' ? raw.split(',') : Array.isArray(raw) && raw.every(v => typeof v === 'string') ? raw : null;
78
+ if (!items || !items.length) throw invalidOption('--allow-origins requires a comma-separated list of http:// or https:// origins.');
79
+ for (const item of items) {
80
+ const origin = parseAllowedOrigin(item);
81
+ if (!origin) throw invalidOption(`Invalid origin in --allow-origins: ${cleanText(item)}. Use exact http:// or https:// origins without paths or wildcards.`);
82
+ allowOrigins.add(origin);
83
+ }
84
+ if (!allowOrigins.size) throw invalidOption('--allow-origins requires at least one http:// or https:// origin.');
85
+ }
86
+ let serveToken = null;
87
+ if (options['--serve-token'] !== undefined) {
88
+ const raw = options['--serve-token'];
89
+ if (typeof raw !== 'string' || !raw || raw.trim() !== raw || /[\r\n\0]/.test(raw)) {
90
+ throw invalidOption('--serve-token must be a non-empty token with no leading/trailing spaces or line breaks.');
91
+ }
92
+ serveToken = raw;
93
+ }
94
+ let serveHeader = null, serveHeaderDisplay = null;
95
+ if (options['--serve-header'] !== undefined) {
96
+ if (!serveToken) throw invalidOption('--serve-header requires --serve-token.');
97
+ const raw = options['--serve-header'];
98
+ if (typeof raw !== 'string' || !raw.trim()) throw invalidOption('--serve-header requires an HTTP header name.');
99
+ const trimmed = raw.trim();
100
+ try { validateHeaderName(trimmed); } catch { throw invalidOption(`Invalid HTTP header name for --serve-header: ${cleanText(trimmed)}.`); }
101
+ const lower = trimmed.toLowerCase();
102
+ if (FORBIDDEN_GATE_HEADERS.has(lower)) throw invalidOption(`--serve-header cannot use reserved header ${cleanText(trimmed)}.`);
103
+ serveHeader = lower;
104
+ serveHeaderDisplay = trimmed;
105
+ }
106
+ return { allowOrigins, trustProxy, serveToken, serveHeader, serveHeaderDisplay };
107
+ }
108
+
109
+ function matchesServeToken(req, config) {
110
+ if (!config.serveToken) return true;
111
+ if (config.serveHeader) {
112
+ const value = req.headers[config.serveHeader];
113
+ return typeof value === 'string' && safeEqual(value.trim(), config.serveToken);
114
+ }
115
+ const auth = req.headers.authorization;
116
+ if (typeof auth === 'string') {
117
+ const match = auth.match(/^Bearer\s+(.+)$/i);
118
+ if (match && safeEqual(match[1].trim(), config.serveToken)) return true;
119
+ }
120
+ const header = req.headers['x-pdd-serve-token'];
121
+ return typeof header === 'string' && safeEqual(header.trim(), config.serveToken);
122
+ }
123
+
124
+ function mergeVary(existing, added) {
125
+ const seen = new Set(), items = [];
126
+ for (const part of [...(Array.isArray(existing) ? existing : existing ? [existing] : []), ...added].flatMap(v => String(v).split(','))) {
127
+ const trimmed = part.trim();
128
+ if (!trimmed) continue;
129
+ const key = trimmed.toLowerCase();
130
+ if (!seen.has(key)) { seen.add(key); items.push(trimmed); }
131
+ }
132
+ return items.join(', ');
133
+ }
15
134
  function primitive(values, schema) {
16
135
  if (schema?.type === 'array') return values.map(v => primitive([v], schema.items));
17
136
  if (values.length !== 1) throw problem(400, 'A query field was repeated; declare an array to accept repeated values.');
@@ -119,7 +238,7 @@ async function requestText(req) {
119
238
  }
120
239
 
121
240
  // Build a request only from authored input; missing values remain visible placeholders.
122
- function requestExample(entry, tests, port) {
241
+ function requestExample(entry, tests, port, serveConfig = null) {
123
242
  const step = tests.flatMap(test => test?.doc?.steps ?? []).find(step => step.entry_path === entry.entry_path && step.operation === entry.operation);
124
243
  const input = step?.input ?? {}, props = propertiesOf(entry.input_schema);
125
244
  const missing = name => `<required:${name}>`;
@@ -139,6 +258,9 @@ function requestExample(entry, tests, port) {
139
258
  }
140
259
  const url = `http://127.0.0.1:${port}${path}${query.size ? `?${query}` : ''}`;
141
260
  const args = ['curl', '-X', entry.route.method, url];
261
+ if (serveConfig?.serveToken) {
262
+ args.push('-H', serveConfig.serveHeaderDisplay ? `${serveConfig.serveHeaderDisplay}: <serve-token>` : 'Authorization: Bearer <serve-token>');
263
+ }
142
264
  for (const name of Object.keys(propertiesOf(props.headers))) {
143
265
  const value = input.headers?.[name];
144
266
  if (value !== undefined || props.headers.required?.includes(name)) args.push('-H', `${name}: ${value ?? missing(name)}`);
@@ -152,19 +274,31 @@ function requestExample(entry, tests, port) {
152
274
  }
153
275
 
154
276
  export async function openServe(context, test, sessionId, options = {}) {
277
+ const serveConfig = parseServeOptions(options);
278
+ if (serveConfig.serveToken) {
279
+ context.secrets = [...new Set([...(context.secrets ?? []), serveConfig.serveToken])];
280
+ }
155
281
  const { ports, root, origin, identity } = context;
156
282
  const free = context.freeProgram === true;
283
+ const serveExtraArgs = () => {
284
+ const extra = [];
285
+ if (serveConfig.allowOrigins.size) extra.push('--allow-origins', [...serveConfig.allowOrigins].join(','));
286
+ if (serveConfig.trustProxy) extra.push('--trust-proxy');
287
+ if (serveConfig.serveToken) extra.push('--serve-token', '<token>');
288
+ if (serveConfig.serveHeaderDisplay) extra.push('--serve-header', serveConfig.serveHeaderDisplay);
289
+ return extra;
290
+ };
157
291
  const serveCommand = (port, fresh = false) => {
158
292
  if (free) {
159
293
  const programFile = relative(context.cwd ?? root, join(root, context.appMap ?? context.programEntry));
160
- return ['pdd', 'run', programFile, '--serve', String(port)].map(shellWord).join(' ');
294
+ return ['pdd', 'run', programFile, '--serve', String(port), ...serveExtraArgs()].map(shellWord).join(' ');
161
295
  }
162
296
  const target = context.programEntry
163
297
  ? [relative(context.cwd ?? root, join(root, context.programTarget ?? context.programEntry))]
164
298
  : ['simulate', test.story];
165
299
  const map = context.appMap && (context.programEntry || fresh)
166
300
  ? ['--app-map', relative(context.cwd ?? root, join(root, context.appMap))] : [];
167
- return ['pdd', ...target, '--serve', String(port), ...(fresh ? ['--new'] : []), ...map].map(shellWord).join(' ');
301
+ return ['pdd', ...target, '--serve', String(port), ...(fresh ? ['--new'] : []), ...map, ...serveExtraArgs()].map(shellWord).join(' ');
168
302
  };
169
303
  const recovery = port => serveCommand(port);
170
304
  if (free && (typeof context.programEntry !== 'string' || typeof context.callProgram !== 'function' || typeof context.persistProgram !== 'function')) throw problem(502, 'The free program server context is incomplete.');
@@ -180,7 +314,7 @@ export async function openServe(context, test, sessionId, options = {}) {
180
314
  const command = serveCommand(options['--serve'] ?? 8080, true);
181
315
  throw problem(502, `This saved Try has no Screen app map. Start a new Try with the selected app map: ${command}`);
182
316
  }
183
- 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).');
317
+ throw problem(502, 'This Story has neither a Screen app map nor named HTTP routes. Add an app map (see the pdd skill reference ui-and-screens.md), or name an HTTP route such as HTTP GET /api/books in input_schema.title (see ports-and-cli.md, or run pdd help prompting).');
184
318
  }
185
319
  const keys = new Set();
186
320
  for (const entry of routes) {
@@ -194,14 +328,92 @@ export async function openServe(context, test, sessionId, options = {}) {
194
328
  let tail = Promise.resolve(), pending = 0, stopped = false;
195
329
  const server = createServer(async (req, res) => {
196
330
  let counted = false, usage = { ...latestUsage, calls: 0, input_tokens: 'unknown', cached_input_tokens: 'unknown', output_tokens: 'unknown', cached_input_share: null }, usageSource = 'last-known';
197
- 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(); };
331
+ let corsOrigin = null;
332
+ const reply = (status, message) => {
333
+ if (!res.headersSent) {
334
+ const extra = {
335
+ ...(status === 401 && serveConfig.serveToken && !serveConfig.serveHeader ? { 'www-authenticate': 'Bearer realm="pdd-serve"' } : {}),
336
+ ...(corsOrigin ? { 'access-control-allow-origin': corsOrigin, 'access-control-expose-headers': EXPOSED_USAGE_HEADERS, vary: 'Origin' } : {}),
337
+ };
338
+ res.writeHead(status, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', ...extra, ...tryUsageHeaders(usage), 'x-pdd-usage-source': usageSource });
339
+ res.end(`pdd: ${cleanText(message, context.secrets ?? [])}\n`);
340
+ } else res.destroy();
341
+ };
198
342
  try {
199
343
  const port = server.address()?.port, acceptedHost = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
200
344
  if (port === 80) { acceptedHost.add('127.0.0.1'); acceptedHost.add('localhost'); }
201
- const acceptedOrigin = new Set([...acceptedHost].map(host => `http://${host}`));
202
- 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.');
345
+ const sameOrigins = new Set([...acceptedHost].map(host => `http://${host}`));
346
+ if (serveConfig.trustProxy) {
347
+ const host = parseHostHeader(req.headers.host);
348
+ if (!host) throw problem(403, 'Invalid or missing Host header.');
349
+ const xfhRaw = req.headers['x-forwarded-host'];
350
+ let forwardedHost = null;
351
+ if (xfhRaw !== undefined) {
352
+ const first = (Array.isArray(xfhRaw) ? xfhRaw[0] : String(xfhRaw)).split(',')[0];
353
+ forwardedHost = parseHostHeader(first);
354
+ if (!forwardedHost) throw problem(403, 'Invalid X-Forwarded-Host header.');
355
+ }
356
+ const xfpRaw = req.headers['x-forwarded-proto'];
357
+ let protos = ['https', 'http'];
358
+ if (xfpRaw !== undefined) {
359
+ const firstProto = (Array.isArray(xfpRaw) ? xfpRaw[0] : String(xfpRaw)).split(',')[0].trim().toLowerCase();
360
+ if (firstProto !== 'http' && firstProto !== 'https') throw problem(403, 'Invalid X-Forwarded-Proto header.');
361
+ protos = [firstProto];
362
+ }
363
+ for (const candidateHost of forwardedHost ? [host, forwardedHost] : [host]) {
364
+ for (const proto of protos) {
365
+ const built = originFromHost(proto, candidateHost);
366
+ if (built) sameOrigins.add(built);
367
+ }
368
+ }
369
+ } else if (!acceptedHost.has(req.headers.host)) {
370
+ throw problem(403, 'This local Try accepts requests only from its own origin.');
371
+ }
203
372
  if (!req.url.startsWith('/') || req.url.startsWith('//') || req.url.includes('\\')) throw problem(400, 'Use a local absolute request path.');
204
373
  const url = new URL(req.url, `http://127.0.0.1:${port}`);
374
+ const isScreenPath = hasScreen && (url.pathname === '/' || url.pathname.startsWith(SCREEN_PREFIX));
375
+ const reqOrigin = typeof req.headers.origin === 'string' ? req.headers.origin : '';
376
+ const isExplicitOrigin = !isScreenPath && reqOrigin !== '' && serveConfig.allowOrigins.has(reqOrigin);
377
+ const originAccepted = !reqOrigin || sameOrigins.has(reqOrigin) || isExplicitOrigin;
378
+ const crossSite = req.headers['sec-fetch-site'] === 'cross-site';
379
+ if (!originAccepted || (crossSite && !isExplicitOrigin)) {
380
+ throw problem(403, 'This local Try accepts requests only from its own origin.');
381
+ }
382
+ if (isExplicitOrigin) corsOrigin = reqOrigin;
383
+ if (isExplicitOrigin && req.method === 'OPTIONS' && typeof req.headers['access-control-request-method'] === 'string'
384
+ && !routes.some(e => e.route.method === 'OPTIONS' && pathParams(e.route, url.pathname))) {
385
+ const matching = routes.filter(e => pathParams(e.route, url.pathname));
386
+ req.resume();
387
+ if (!matching.length) { reply(404, 'No prompt names this HTTP route.'); return; }
388
+ const methods = [...new Set([...matching.map(e => e.route.method), ...(matching.some(e => e.route.method === 'GET') ? ['HEAD'] : []), 'OPTIONS'])];
389
+ const allowHeaderSet = new Map([['authorization', 'Authorization'], ['content-type', 'Content-Type'], ['x-pdd-serve-token', 'X-PDD-Serve-Token']]);
390
+ if (serveConfig.serveHeader) allowHeaderSet.set(serveConfig.serveHeader, serveConfig.serveHeaderDisplay);
391
+ const requestedHeaders = req.headers['access-control-request-headers'];
392
+ if (typeof requestedHeaders === 'string') {
393
+ for (const rawName of requestedHeaders.split(',')) {
394
+ const trimmed = rawName.trim();
395
+ if (!trimmed) continue;
396
+ try { validateHeaderName(trimmed); allowHeaderSet.set(trimmed.toLowerCase(), trimmed); } catch { /* Ignore invalid requested header names. */ }
397
+ }
398
+ }
399
+ res.writeHead(204, {
400
+ 'access-control-allow-origin': corsOrigin,
401
+ 'access-control-allow-methods': methods.join(', '),
402
+ 'access-control-allow-headers': [...allowHeaderSet.values()].join(', '),
403
+ 'access-control-max-age': '600',
404
+ vary: 'Origin, Access-Control-Request-Method, Access-Control-Request-Headers',
405
+ 'cache-control': 'no-store',
406
+ ...tryUsageHeaders(usage),
407
+ 'x-pdd-usage-source': usageSource,
408
+ });
409
+ res.end();
410
+ return;
411
+ }
412
+ if (!matchesServeToken(req, serveConfig)) {
413
+ throw problem(401, serveConfig.serveHeaderDisplay
414
+ ? `Missing or invalid ${serveConfig.serveHeaderDisplay} token.`
415
+ : 'Missing or invalid serve token. Send Authorization: Bearer <token> or X-PDD-Serve-Token.');
416
+ }
205
417
  const resource = hasScreen ? screenResource(url, req.method) : null;
206
418
  if (resource) {
207
419
  if (pending >= 32 || stopped || context.signal?.aborted) throw problem(503, 'The local Try is busy or stopped.');
@@ -259,12 +471,17 @@ export async function openServe(context, test, sessionId, options = {}) {
259
471
  const result = responseFor(answer.result);
260
472
  const body = req.method === 'HEAD' || [204, 304].includes(result.status) ? '' : result.body;
261
473
  const headers = { ...result.headers, ...(![204, 304].includes(result.status) ? { 'content-length': Buffer.byteLength(req.method === 'HEAD' ? result.body : body) } : {}) };
474
+ if (corsOrigin) {
475
+ headers['access-control-allow-origin'] = corsOrigin;
476
+ headers['access-control-expose-headers'] = EXPOSED_USAGE_HEADERS;
477
+ headers.vary = mergeVary(headers.vary, ['Origin']);
478
+ }
262
479
  res.writeHead(result.status, { ...headers, ...tryUsageHeaders(usage), 'x-pdd-usage-source': usageSource }); res.end(body);
263
480
  ports.stderr?.write(`${label}: ${result.status} in ${Math.round((Date.now() - sentAt) / 1000)} s\n`);
264
481
  } catch (error) {
265
482
  if (error.tryUsage) { usage = error.tryUsage; latestUsage = usage; usageSource = 'runtime'; }
266
483
  req.resume(); reply(error.httpStatus || 502, error.message || 'The interpreter could not confirm this request.');
267
- ports.stderr?.write(`${req.method} ${req.url.split('?')[0]}: ${error.httpStatus || 502} ${cleanText(error.message || 'The interpreter could not confirm this request.')}\n`);
484
+ ports.stderr?.write(`${req.method} ${req.url.split('?')[0]}: ${error.httpStatus || 502} ${cleanText(error.message || 'The interpreter could not confirm this request.', context.secrets ?? [])}\n`);
268
485
  }
269
486
  finally { if (counted) pending--; }
270
487
  });
@@ -280,7 +497,12 @@ export async function openServe(context, test, sessionId, options = {}) {
280
497
  context.signal?.addEventListener('abort', stop, { once: true });
281
498
  const port = server.address().port;
282
499
  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`);
283
- if (routes.length) ports.stdout.write(`Example: ${requestExample(routes[0], context.simulationTests ?? (test ? [test] : []), port)}\n`);
500
+ ports.stdout.write('Limits: named route calls serialize on a single queue (up to 32 pending); HTTP request timeout is 30 s.\n');
501
+ if (serveConfig.trustProxy) ports.stdout.write('Proxy: trusting forwarded Host / X-Forwarded-Host (still bound to 127.0.0.1).\n');
502
+ if (serveConfig.allowOrigins.size) ports.stdout.write(`Allowed origins: ${[...serveConfig.allowOrigins].join(', ')}\n`);
503
+ if (serveConfig.serveToken) ports.stdout.write(`Auth gate: enabled (${serveConfig.serveHeaderDisplay ? `header ${serveConfig.serveHeaderDisplay}` : 'Authorization: Bearer <token> or X-PDD-Serve-Token'}).\n`);
504
+ else if (serveConfig.trustProxy || serveConfig.allowOrigins.size) ports.stdout.write('Auth gate: none (add --serve-token <token> to require a bearer/header token on tunneled requests).\n');
505
+ if (routes.length) ports.stdout.write(`Example: ${requestExample(routes[0], context.simulationTests ?? (test ? [test] : []), port, serveConfig)}\n`);
284
506
  if (hasScreen) ports.stdout.write(`Screen: http://127.0.0.1:${port}/\n`);
285
507
  try {
286
508
  if (ports.serve) { await ports.serve(server); return 0; }
@@ -100,7 +100,13 @@ export function createTryTools({ cwd = process.cwd(), words = [], env } = {}, po
100
100
  if (session.unknown) throw new Error('A prior run has an unknown outcome. Inspect the Try page before starting another run; do not repeat it automatically.');
101
101
  let entry, input;
102
102
  if (Object.hasOwn(args, 'argv')) {
103
- const cli = owner.model.entries.filter(e => e.cli === true);
103
+ let cli = owner.model.entries.filter(e => e.cli === true);
104
+ if (cli.length === 0 && owner.model.entries.length === 1) {
105
+ const single = owner.model.entries[0];
106
+ const hasCliStep = Array.isArray(owner.test?.doc?.steps) && owner.test.doc.steps.some(step =>
107
+ step?.entry_path === single.entry_path && step?.operation === single.operation && Array.isArray(step?.input?.argv));
108
+ if (hasCliStep || Object.hasOwn(single?.input_schema?.properties ?? {}, 'argv')) cli = [single];
109
+ }
104
110
  if (cli.length !== 1) throw new Error('This Try needs exactly one CLI entry for argv. Choose an explicit entry and input from try_state.');
105
111
  entry = cli[0]; input = { argv: args.argv };
106
112
  } else {