@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptdriven/runtime-client",
3
- "version": "1.1.2",
3
+ "version": "1.1.4",
4
4
  "description": "PDD Runtime Client (@promptdriven/runtime-client)",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -296,12 +296,16 @@ function expand({ path: consumer, text, format }, files, documents) {
296
296
  }
297
297
  let document, block;
298
298
  if (format === 'prompt') {
299
+ if (!text.includes('$contract') && !text.includes('\\u')) return { text, references: [] };
299
300
  const blocks = [...text.matchAll(INTERFACE)];
300
301
  if (blocks.length !== 1) return { text, references: [] };
301
302
  block = blocks[0];
303
+ if (!block[1].includes('$contract') && !block[1].includes('\\u')) return { text, references: [] };
302
304
  try { document = clone(parse(block[1])); } catch { return { text, references: [] }; }
303
305
  schemaSlots(document, (value,pointer) => schema(value,pointer));
304
306
  } else {
307
+ if (format === 'json-schema' && !text.includes('$contract') && !text.includes('\\u')) return { text, references: [] };
308
+ if (format === 'scenario' && !text.includes('$simulation') && !text.includes('$seed') && !text.includes('\\u')) return { text, references: [] };
305
309
  try { document = clone(parse(text)); } catch { return { text, references: [] }; }
306
310
  if (format === 'json-schema') document = schema(document, '');
307
311
  else if (format === 'scenario' && object(document)) {
@@ -50,6 +50,27 @@ export function runtimePreflightSlice() {
50
50
  return (preflightModule ??= req('./runtime-preflight.mjs'));
51
51
  }
52
52
 
53
+ let promptClausesModule = null;
54
+ export function runtimePromptClausesSlice() {
55
+ return (promptClausesModule ??= req('./prompt-clauses.mjs'));
56
+ }
57
+
58
+ export function extractPromptClauses(...args) {
59
+ return runtimePromptClausesSlice().extractPromptClauses(...args);
60
+ }
61
+
62
+ export function buildClauseTable(...args) {
63
+ return runtimePromptClausesSlice().buildClauseTable(...args);
64
+ }
65
+
66
+ export function indexClauseTable(...args) {
67
+ return runtimePromptClausesSlice().indexClauseTable(...args);
68
+ }
69
+
70
+ export function validateStepClauses(...args) {
71
+ return runtimePromptClausesSlice().validateStepClauses(...args);
72
+ }
73
+
53
74
  let agentPacketModule = null;
54
75
  export function runtimeAgentPacketSlice() {
55
76
  return (agentPacketModule ??= req('./agent-packet.mjs'));
@@ -708,6 +729,12 @@ export async function simulate(input = {}, ports) {
708
729
  else if (input?.mode === 'serve' && options['--serve'] === undefined) options['--serve'] = input?.port ?? true;
709
730
  else if (input?.mode === 'save-last') options['--save-last'] = true;
710
731
  else if (input?.mode === 'stop') options['--stop'] = true;
732
+ if (input?.allowOrigins !== undefined && options['--allow-origins'] === undefined) {
733
+ options['--allow-origins'] = Array.isArray(input.allowOrigins) ? input.allowOrigins.join(',') : input.allowOrigins;
734
+ }
735
+ if (input?.trustProxy === true && options['--trust-proxy'] === undefined) options['--trust-proxy'] = true;
736
+ if (input?.serveToken !== undefined && options['--serve-token'] === undefined) options['--serve-token'] = input.serveToken;
737
+ if (input?.serveHeader !== undefined && options['--serve-header'] === undefined) options['--serve-header'] = input.serveHeader;
711
738
  const testWord =
712
739
  typeof input?.test === 'string' && input.test.length > 0
713
740
  ? input.test
@@ -0,0 +1,290 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ const sha256 = value => createHash('sha256').update(value).digest('hex');
4
+
5
+ const ATX_HEADING_RE = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?[ \t]*#*[ \t]*$/;
6
+ const SETEXT_UNDERLINE_RE = /^ {0,3}(=+|-+)[ \t]*$/;
7
+ const FENCE_OPEN_RE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
8
+ const FENCE_CLOSE_RE = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
9
+ const THEMATIC_BREAK_RE = /^ {0,3}(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,})$/;
10
+ const LIST_ITEM_RE = /^([ \t]*)(?:[-+*]|[0-9]{1,9}[.)])[ \t]+(.*)$/;
11
+ const BLOCKQUOTE_RE = /^ {0,3}(?:>[ \t]?)+/;
12
+ const TABLE_DELIM_RE = /^\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*$|^\s*\|\s*:?-{3,}:?\s*\|\s*$/;
13
+ const LINK_DEF_RE = /^ {0,3}\[[^\]]+\]:[ \t]*\S/;
14
+ const BARE_HTML_TAG_RE = /^ {0,3}<\/?(?:details|summary|div|section|br|hr)\b[^>]*>[ \t]*$/i;
15
+
16
+ function normalizeProse(text) {
17
+ return String(text ?? '').replace(/\s+/g, ' ').trim();
18
+ }
19
+
20
+ function splitTableCells(line) {
21
+ let trimmed = line.trim();
22
+ if (trimmed.startsWith('|')) trimmed = trimmed.slice(1);
23
+ if (trimmed.endsWith('|') && !trimmed.endsWith('\\|')) trimmed = trimmed.slice(0, -1);
24
+ const cells = [];
25
+ let current = '';
26
+ for (let i = 0; i < trimmed.length; i++) {
27
+ const ch = trimmed[i];
28
+ if (ch === '\\' && i + 1 < trimmed.length && trimmed[i + 1] === '|') {
29
+ current += '|';
30
+ i++;
31
+ continue;
32
+ }
33
+ if (ch === '|') {
34
+ cells.push(normalizeProse(current));
35
+ current = '';
36
+ continue;
37
+ }
38
+ current += ch;
39
+ }
40
+ cells.push(normalizeProse(current));
41
+ return cells;
42
+ }
43
+
44
+ function isTableRowCandidate(line) {
45
+ const trimmed = line.trim();
46
+ if (!trimmed || !trimmed.includes('|')) return false;
47
+ if (ATX_HEADING_RE.test(line) || FENCE_OPEN_RE.test(line) || THEMATIC_BREAK_RE.test(line)) return false;
48
+ return true;
49
+ }
50
+
51
+ function formatTableRow(line) {
52
+ const cells = splitTableCells(line);
53
+ if (cells.every(cell => !cell)) return '';
54
+ return cells.join(' | ');
55
+ }
56
+
57
+ function frontmatterEndIndex(lines) {
58
+ if (lines.length < 2 || !/^---[ \t]*$/.test(lines[0])) return -1;
59
+ for (let i = 1; i < lines.length; i++) {
60
+ if (/^(?:---|\.\.\.)[ \t]*$/.test(lines[i])) return i;
61
+ }
62
+ return -1;
63
+ }
64
+
65
+ /**
66
+ * Deterministically split one Markdown prompt's prose into clauses
67
+ * (paragraphs, list items, table rows, anchored by heading path)
68
+ * with stable `cl-sha256-<hex>` IDs and 1-based line numbers.
69
+ */
70
+ export function extractPromptClauses(path, text) {
71
+ if (typeof path !== 'string' || !path || typeof text !== 'string') return [];
72
+ const lines = text.split(/\r?\n/);
73
+ const clauses = [];
74
+ const usedIds = new Set();
75
+ const headingStack = [];
76
+
77
+ const headingPath = () => headingStack.map(h => h.title).join(' > ');
78
+
79
+ const pushHeading = (level, rawTitle) => {
80
+ const title = normalizeProse(rawTitle);
81
+ while (headingStack.length && headingStack[headingStack.length - 1].level >= level) {
82
+ headingStack.pop();
83
+ }
84
+ if (title) headingStack.push({ level, title });
85
+ };
86
+
87
+ const emitClause = (lineNumber, rawText) => {
88
+ const normalized = normalizeProse(rawText);
89
+ if (!normalized) return;
90
+ const anchor = headingPath();
91
+ const base = `cl-sha256-${sha256(Buffer.from(`${path}\0${anchor}\0${normalized}`, 'utf8')).slice(0, 16)}`;
92
+ let id = base;
93
+ for (let n = 2; usedIds.has(id); n++) id = `${base}-${n}`;
94
+ usedIds.add(id);
95
+ clauses.push({ id, path, line: lineNumber, text: normalized });
96
+ };
97
+
98
+ let block = null; // { kind: 'paragraph' | 'list', line: number, parts: string[], inQuote: boolean }
99
+ const flushBlock = () => {
100
+ if (!block) return;
101
+ emitClause(block.line, block.parts.join(' '));
102
+ block = null;
103
+ };
104
+
105
+ let i = 0;
106
+ const fmEnd = frontmatterEndIndex(lines);
107
+ if (fmEnd >= 0) i = fmEnd + 1;
108
+
109
+ let fence = null; // { char: string, len: number }
110
+ let inComment = false;
111
+
112
+ for (; i < lines.length; i++) {
113
+ const rawLine = lines[i];
114
+ const lineNumber = i + 1;
115
+
116
+ if (fence) {
117
+ const close = FENCE_CLOSE_RE.exec(rawLine);
118
+ if (close && close[1][0] === fence.char && close[1].length >= fence.len) {
119
+ fence = null;
120
+ }
121
+ continue;
122
+ }
123
+
124
+ if (inComment) {
125
+ const closeIdx = rawLine.indexOf('-->');
126
+ if (closeIdx >= 0) {
127
+ inComment = false;
128
+ }
129
+ continue;
130
+ }
131
+
132
+ const trimmedRaw = rawLine.trim();
133
+ if (!trimmedRaw) {
134
+ flushBlock();
135
+ continue;
136
+ }
137
+
138
+ if (/^ {0,3}<!--/.test(rawLine)) {
139
+ flushBlock();
140
+ const closeIdx = rawLine.indexOf('-->', rawLine.indexOf('<!--') + 4);
141
+ if (closeIdx < 0) inComment = true;
142
+ continue;
143
+ }
144
+
145
+ const fenceOpen = FENCE_OPEN_RE.exec(rawLine);
146
+ if (fenceOpen && !(fenceOpen[1][0] === '`' && fenceOpen[2].includes('`'))) {
147
+ flushBlock();
148
+ fence = { char: fenceOpen[1][0], len: fenceOpen[1].length };
149
+ continue;
150
+ }
151
+
152
+ // Setext heading underline turns an open plain paragraph into a heading.
153
+ if (block && block.kind === 'paragraph' && !block.inQuote && SETEXT_UNDERLINE_RE.test(rawLine)) {
154
+ const level = rawLine.trim()[0] === '=' ? 1 : 2;
155
+ pushHeading(level, block.parts.join(' '));
156
+ block = null;
157
+ continue;
158
+ }
159
+
160
+ if (THEMATIC_BREAK_RE.test(rawLine)) {
161
+ flushBlock();
162
+ continue;
163
+ }
164
+
165
+ const atx = ATX_HEADING_RE.exec(rawLine);
166
+ if (atx) {
167
+ flushBlock();
168
+ pushHeading(atx[1].length, atx[2] ?? '');
169
+ continue;
170
+ }
171
+
172
+ if (BARE_HTML_TAG_RE.test(rawLine) || (!block && LINK_DEF_RE.test(rawLine))) {
173
+ flushBlock();
174
+ continue;
175
+ }
176
+
177
+ // GFM pipe table: header line followed immediately by delimiter row.
178
+ if (isTableRowCandidate(rawLine) && i + 1 < lines.length && TABLE_DELIM_RE.test(lines[i + 1])) {
179
+ flushBlock();
180
+ i += 2; // Skip header row and delimiter row.
181
+ while (i < lines.length) {
182
+ const rowLine = lines[i];
183
+ if (!isTableRowCandidate(rowLine) || TABLE_DELIM_RE.test(rowLine)) break;
184
+ const formatted = formatTableRow(rowLine);
185
+ if (formatted) emitClause(i + 1, formatted);
186
+ i++;
187
+ }
188
+ i--; // Outer loop will increment.
189
+ continue;
190
+ }
191
+
192
+ const quoteMatch = BLOCKQUOTE_RE.exec(rawLine);
193
+ const inQuote = Boolean(quoteMatch);
194
+ const line = inQuote ? rawLine.slice(quoteMatch[0].length) : rawLine;
195
+
196
+ if (!line.trim()) {
197
+ flushBlock();
198
+ continue;
199
+ }
200
+
201
+ const quoteAtx = inQuote ? ATX_HEADING_RE.exec(line) : null;
202
+ if (quoteAtx) {
203
+ flushBlock();
204
+ pushHeading(quoteAtx[1].length, quoteAtx[2] ?? '');
205
+ continue;
206
+ }
207
+
208
+ const listMatch = LIST_ITEM_RE.exec(line);
209
+ if (listMatch) {
210
+ flushBlock();
211
+ block = { kind: 'list', line: lineNumber, parts: [listMatch[2]], inQuote };
212
+ continue;
213
+ }
214
+
215
+ if (block) {
216
+ if (block.inQuote !== inQuote) {
217
+ flushBlock();
218
+ block = { kind: 'paragraph', line: lineNumber, parts: [line], inQuote };
219
+ } else {
220
+ block.parts.push(line);
221
+ }
222
+ } else {
223
+ block = { kind: 'paragraph', line: lineNumber, parts: [line], inQuote };
224
+ }
225
+ }
226
+
227
+ flushBlock();
228
+ return clauses;
229
+ }
230
+
231
+ /**
232
+ * Build a deterministic flat clause table across all uploaded prompt sources.
233
+ * Entries are ordered by prompt path then 1-based line number.
234
+ */
235
+ export function buildClauseTable(promptSources) {
236
+ if (!Array.isArray(promptSources)) return [];
237
+ const sorted = [...promptSources]
238
+ .filter(item => item && typeof item.path === 'string' && item.path.endsWith('.prompt.md') && typeof item.text === 'string')
239
+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
240
+ const out = [];
241
+ for (const item of sorted) {
242
+ out.push(...extractPromptClauses(item.path, item.text));
243
+ }
244
+ return out;
245
+ }
246
+
247
+ /**
248
+ * Index a clause table (Array or Map) by clause ID for O(1) validation.
249
+ */
250
+ export function indexClauseTable(clauseTable) {
251
+ const index = new Map();
252
+ if (!clauseTable) return index;
253
+ const entries = clauseTable instanceof Map ? clauseTable.values() : Array.isArray(clauseTable) ? clauseTable : [];
254
+ for (const entry of entries) {
255
+ if (
256
+ entry && typeof entry === 'object'
257
+ && typeof entry.id === 'string' && entry.id
258
+ && typeof entry.path === 'string' && entry.path
259
+ && Number.isSafeInteger(entry.line) && entry.line >= 1
260
+ && typeof entry.text === 'string' && entry.text
261
+ ) {
262
+ if (!index.has(entry.id)) {
263
+ index.set(entry.id, { id: entry.id, path: entry.path, line: entry.line, text: entry.text });
264
+ }
265
+ }
266
+ }
267
+ return index;
268
+ }
269
+
270
+ /**
271
+ * Validate raw step-level clause IDs returned by the interpreter against the uploaded clause table.
272
+ * Keeps only IDs present in `clauseIndex` (deduplicated, preserving order) and counts dropped unknown IDs.
273
+ */
274
+ export function validateStepClauses(rawClauses, clauseIndex) {
275
+ if (!Array.isArray(rawClauses)) return { present: false, valid: [], dropped: 0 };
276
+ const valid = [];
277
+ const seen = new Set();
278
+ let dropped = 0;
279
+ for (const item of rawClauses) {
280
+ if (typeof item === 'string' && clauseIndex.has(item)) {
281
+ if (!seen.has(item)) {
282
+ seen.add(item);
283
+ valid.push(clauseIndex.get(item));
284
+ }
285
+ } else {
286
+ dropped++;
287
+ }
288
+ }
289
+ return { present: true, valid, dropped };
290
+ }
@@ -8,7 +8,7 @@ import { isatty } from 'node:tty';
8
8
  import { fileURLToPath, pathToFileURL } from 'node:url';
9
9
  import { captureSource, gitFiles, interfaceBlocks, sourceFilePort, findTests } from './runtime-preflight.mjs';
10
10
  import { createProgramContext, admitProgram, runDoorCall, withRepositoryRunLock, saveDoorCaseResult, acquireCaseWriteOwnership } from './runtime-client.mjs';
11
- import { openServe } from './try-http.mjs';
11
+ import { openServe, parseServeOptions, SERVE_OPTION_KEYS } from './try-http.mjs';
12
12
  import { projectTryCall } from './try-session.mjs';
13
13
 
14
14
  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
@@ -67,7 +67,7 @@ function excludeRuns(root) {
67
67
  if (!text.split('\n').includes('/.pdd/run/')) writeFileSync(path, `${text}${text && !text.endsWith('\n') ? '\n' : ''}/.pdd/run/\n`);
68
68
  }
69
69
  function checkedOptions(options) {
70
- const allowed = new Set(['--data', '--fresh', '--show-data', '--serve', '--max-calls', '-q', '--no-open', '--read', '--save-last']);
70
+ const allowed = new Set(['--data', '--fresh', '--show-data', '--serve', ...SERVE_OPTION_KEYS, '--max-calls', '-q', '--no-open', '--read', '--save-last']);
71
71
  if (!object(options)) throw failure('Program options must be an object.');
72
72
  for (const [key, value] of Object.entries(options)) {
73
73
  if (!allowed.has(key)) throw failure(`Unknown PDD option ${key}.`);
@@ -76,6 +76,11 @@ function checkedOptions(options) {
76
76
  if (key === '--max-calls' && (!Number.isInteger(value) || value < 1 || value > 1000)) throw failure('--max-calls must be an integer from 1 to 1000.');
77
77
  if (key === '--serve' && value !== true && (!Number.isInteger(value) || value < 0 || value > 65535)) throw failure('--serve requires a port from 0 to 65535.');
78
78
  }
79
+ const hasServeExtras = SERVE_OPTION_KEYS.some(key => options[key] !== undefined);
80
+ if (hasServeExtras && options['--serve'] === undefined) throw failure('--allow-origins, --trust-proxy, --serve-token and --serve-header require --serve.');
81
+ if (hasServeExtras) {
82
+ try { parseServeOptions(options); } catch (error) { throw failure(error.message, 2); }
83
+ }
79
84
  }
80
85
  function promptInterface(text) {
81
86
  const blocks = interfaceBlocks(text);
@@ -212,7 +217,7 @@ async function saveProgramCase(context, folder, story, ports, discoveryPorts) {
212
217
  } finally { lease?.release(); }
213
218
  }
214
219
 
215
- export async function runProgram({ file, argv = [], options = {}, cwd = process.cwd() } = {}, givenPorts = {}) {
220
+ export async function runProgram({ file, argv = [], options = {}, cwd = process.cwd(), directInvoke = false } = {}, givenPorts = {}) {
216
221
  const ports = { ...givenPorts, env: givenPorts.env ?? process.env, stdin: givenPorts.stdin ?? process.stdin, stdout: givenPorts.stdout ?? process.stdout, stderr: givenPorts.stderr ?? process.stderr };
217
222
  const started = Date.now(), controller = new AbortController();
218
223
  let context, unsubscribe, lastId = '', calls = 0, accountingKnown = true, draft = false, interrupted = false;
@@ -251,12 +256,12 @@ export async function runProgram({ file, argv = [], options = {}, cwd = process.
251
256
  const hasCli = contract.entries?.some((_, index) => ['input_schema', 'result_schema'].every(key => contract.conventions?.some(row => row.path === `/entries/${index}/${key}` && row.convention === 'cli')));
252
257
  const inputIndex = argv.indexOf('--input');
253
258
  if (!hasCli && inputIndex >= 0 && argv[inputIndex + 1]?.startsWith('@')) inputFile = files.read({ path: localPath(root, cwd, argv[inputIndex + 1].slice(1)) }).content;
254
- let invocation = prepareProgramInvocation({ file: selected, argv, interface_json: JSON.stringify(contract), stdin_tty: ports.stdin.isTTY === true, serve: options['--serve'] !== undefined, input_file_json: inputFile });
259
+ let invocation = prepareProgramInvocation({ file: selected, argv, interface_json: JSON.stringify(contract), stdin_tty: ports.stdin.isTTY === true, serve: options['--serve'] !== undefined, input_file_json: inputFile, direct_invoke: directInvoke === true });
255
260
  const cliIndex = contract.entries?.findIndex((_, index) => ['input_schema', 'result_schema'].every(key => contract.conventions?.some(row => row.path === `/entries/${index}/${key}` && row.convention === 'cli'))) ?? -1;
256
261
  const typedEntries = contract.entries?.filter(row => !programHttpEntry(row)) ?? [];
257
262
  const typedWords = typedEntries.length > 1 ? argv.slice(1) : argv;
258
- const needsStdin = !appMap && !options['--read'] && !options['--save-last'] && !options['--show-data'] && !ports.stdin.isTTY && (cliIndex >= 0 ? !!contract.entries[cliIndex].input_schema?.properties?.stdin && argv.length > 0 : !['http', 'screen'].includes(invocation.door) && typedEntries.length > 0 && !typedWords.length);
259
- if (needsStdin) invocation = prepareProgramInvocation({ file: selected, argv, interface_json: JSON.stringify(contract), stdin: await stdinText(ports.stdin), stdin_tty: false, serve: options['--serve'] !== undefined, input_file_json: inputFile });
263
+ const needsStdin = !appMap && !options['--read'] && !options['--save-last'] && !options['--show-data'] && !ports.stdin.isTTY && (cliIndex >= 0 ? !!contract.entries[cliIndex].input_schema?.properties?.stdin && (argv.length > 0 || directInvoke === true) : !['http', 'screen'].includes(invocation.door) && typedEntries.length > 0 && !typedWords.length);
264
+ if (needsStdin) invocation = prepareProgramInvocation({ file: selected, argv, interface_json: JSON.stringify(contract), stdin: await stdinText(ports.stdin), stdin_tty: false, serve: options['--serve'] !== undefined, input_file_json: inputFile, direct_invoke: directInvoke === true });
260
265
  return invocation;
261
266
  };
262
267
  let invocation = iface ? await selectInvocation(iface) : { door: appMap ? 'screen' : 'deferred', operation: '', input_json: '' };
@@ -551,7 +556,7 @@ async function programShell({ file, entry, iface, folder, root, cwd, ports }) {
551
556
  const bin = privateFolder(folder, ['bin']), shim = join(bin, name);
552
557
  if (existsSync(shim)) { regular(shim); if (!readFileSync(shim, 'utf8').startsWith('#!/bin/sh\n# PDD program launcher v1\n')) throw failure('Refusing to replace a non-PDD shell command.'); }
553
558
  const module = pathToFileURL(fileURLToPath(import.meta.url)).href;
554
- const script = 'import(process.argv[1]).then(async m => { process.exitCode = await m.runProgram({file:process.argv[2],cwd:process.argv[3],argv:process.argv.slice(4)}); }).catch(e=>{process.stderr.write(String(e.message)+"\\n");process.exitCode=125;});';
559
+ const script = 'import(process.argv[1]).then(async m => { process.exitCode = await m.runProgram({file:process.argv[2],cwd:process.argv[3],argv:process.argv.slice(4),directInvoke:true}); }).catch(e=>{process.stderr.write(String(e.message)+"\\n");process.exitCode=125;});';
555
560
  const code = `#!/bin/sh\n# PDD program launcher v1\nexec ${quote(process.execPath)} --input-type=commonjs -e ${quote(script)} -- ${quote(module)} ${quote(entry)} ${quote(root)} "$@"\n`;
556
561
  const fd = openSync(shim, constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW, 0o700); try { writeFileSync(fd, code); fsyncSync(fd); } finally { closeSync(fd); }
557
562
  const env = { ...ports.env, PATH: `${bin}:${ports.env.PATH ?? process.env.PATH ?? ''}` }, chosen = ports.env.SHELL ?? '/bin/sh';
@@ -724,7 +729,7 @@ export function prepareProgramInvocation(input = {}) {
724
729
  if (Object.hasOwn(entry.input_schema.properties ?? {}, 'stdin') && (!tty || entry.input_schema.required?.includes('stdin'))) value.stdin = tty ? '' : input.stdin ?? '';
725
730
  const problem = programSchemaProblem(value, entry.input_schema);
726
731
  if (problem) return usage(problem);
727
- return selected(argv.length ? 'cli' : 'shell', entry.operation, value);
732
+ return selected(argv.length || input.direct_invoke === true ? 'cli' : 'shell', entry.operation, value);
728
733
  }
729
734
  const typedEntries = entries.filter(entry => !isHttp(entry));
730
735
  if (!typedEntries.length) return usage('This prompt exposes named HTTP routes; start its HTTP server.');
@@ -1,7 +1,20 @@
1
- // Generated from prompts/cli/runtime-binding-plan.prompt.md (sha256: 667d9ad0ad59e95258aac6c32665398d28642416fc95d7132d7349eba65abd60).
1
+ // Generated from prompts/cli/runtime-binding-plan.prompt.md (sha256: f198da66d04fa0e22f48fdd4d438ed5a6349bd6a63121fcb0e6d785adddec6c2).
2
2
 
3
3
  const rows = value => Array.isArray(value) ? value : [];
4
- const stepSimulation = (base, overrides) => {
4
+ const PROMPT_SIM_ACTIONS = new Set(['fake.prompt', 'http.prompt', 'port.prompt']);
5
+ const normalizePortName = name => typeof name === 'string' ? name.replaceAll('-', '_') : '';
6
+ const promptStem = path => {
7
+ if (typeof path !== 'string') return '';
8
+ const base = path.slice(path.lastIndexOf('/') + 1);
9
+ return base.endsWith('.prompt.md') ? base.slice(0, -'.prompt.md'.length) : base;
10
+ };
11
+ const promptTargetOf = binding => {
12
+ if (!binding || typeof binding !== 'object' || Array.isArray(binding)) return null;
13
+ if (typeof binding.target === 'string' && binding.target.endsWith('.prompt.md')) return binding.target;
14
+ if (typeof binding.prompt_path === 'string' && binding.prompt_path.endsWith('.prompt.md')) return binding.prompt_path;
15
+ return null;
16
+ };
17
+ export function stepSimulation(base, overrides) {
5
18
  const result = { ...(base ?? {}) };
6
19
  if (Array.isArray(overrides)) {
7
20
  for (const row of overrides) {
@@ -13,6 +26,63 @@ const stepSimulation = (base, overrides) => {
13
26
  Object.assign(result, overrides);
14
27
  }
15
28
  return result;
29
+ }
30
+ export function simulationGraph(simulation) {
31
+ const promptTargets = [];
32
+ const promptTargetSet = new Set();
33
+ const mockedKeys = new Set();
34
+ const normalizedMockedKeys = new Set();
35
+ const mockedResources = new Set();
36
+ const normalizedMockedResources = new Set();
37
+ for (const [key, binding] of Object.entries(simulation ?? {})) {
38
+ if (!binding || typeof binding !== 'object' || Array.isArray(binding)) continue;
39
+ const target = promptTargetOf(binding);
40
+ const dot = key.lastIndexOf('.');
41
+ const resource = dot > 0 ? key.slice(0, dot) : '';
42
+ const op = dot > 0 ? key.slice(dot + 1) : '';
43
+ if (target || PROMPT_SIM_ACTIONS.has(binding.action)) {
44
+ if (target && !promptTargetSet.has(target)) {
45
+ promptTargetSet.add(target);
46
+ promptTargets.push(target);
47
+ }
48
+ }
49
+ mockedKeys.add(key);
50
+ if (resource) {
51
+ normalizedMockedKeys.add(`${normalizePortName(resource)}.${op}`);
52
+ mockedResources.add(resource);
53
+ normalizedMockedResources.add(normalizePortName(resource));
54
+ }
55
+ }
56
+ return { promptTargets, promptTargetSet, mockedKeys, normalizedMockedKeys, mockedResources, normalizedMockedResources };
57
+ }
58
+ export function isMockedPortCall(call, sim) {
59
+ if (!call || typeof call.target !== 'string' || !sim) return false;
60
+ if (sim.promptTargetSet?.has(call.target)) return false;
61
+ const op = typeof call.operation === 'string' ? call.operation : '';
62
+ const targetOp = typeof call.target_operation === 'string' ? call.target_operation : '';
63
+ const stem = promptStem(call.target);
64
+ const normOp = normalizePortName(op);
65
+ const normStem = normalizePortName(stem);
66
+ if (op && sim.mockedKeys.has(op)) return true;
67
+ if (op && targetOp && (sim.mockedKeys.has(`${op}.${targetOp}`) || sim.normalizedMockedKeys.has(`${normOp}.${targetOp}`))) return true;
68
+ if (stem && targetOp && (sim.mockedKeys.has(`${stem}.${targetOp}`) || sim.normalizedMockedKeys.has(`${normStem}.${targetOp}`))) return true;
69
+ if (!targetOp) {
70
+ if (op && (sim.mockedResources.has(op) || sim.normalizedMockedResources.has(normOp))) return true;
71
+ if (stem && (sim.mockedResources.has(stem) || sim.normalizedMockedResources.has(normStem))) return true;
72
+ }
73
+ return false;
74
+ }
75
+ const isPlainProsePlan = (test, prompts, dependencyPaths, plainProse) => {
76
+ if (typeof plainProse === 'boolean') return plainProse;
77
+ const relevant = new Set(rows(dependencyPaths).filter(path => typeof path === 'string'));
78
+ for (const step of rows(test?.doc?.steps)) {
79
+ if (typeof step?.entry_path === 'string') relevant.add(step.entry_path);
80
+ const sim = simulationGraph(stepSimulation(test?.doc?.simulation, step?.simulation_overrides));
81
+ for (const target of sim.promptTargets) relevant.add(target);
82
+ }
83
+ const candidates = relevant.size ? [...relevant].map(path => prompts.get(path)).filter(Boolean) : [...prompts.values()];
84
+ const executable = candidates.filter(iface => iface?.kind !== 'native-only');
85
+ return executable.length > 0 && executable.every(iface => iface?.plain_prose === true);
16
86
  };
17
87
  const selectedResources = (iface, operation) => {
18
88
  const entries = rows(iface?.entries), selected = entries.filter(entry => entry?.operation === operation);
@@ -32,7 +102,7 @@ const boundaryNote = (notes, reason) => {
32
102
  : `boundary not applied: ${reason === 'unsupported-line-ends' ? 'unsupported line ends' : reason}; full dependency closure is required`});
33
103
  return null;
34
104
  };
35
- export function runtimeBoundary(storyPath, text, {notes=[]}={}) {
105
+ export function runtimeBoundary(storyPath, text, {notes=[], plainProse=false}={}) {
36
106
  // Scope removal needs unambiguous line boundaries throughout the Story.
37
107
  // Do not normalize unsupported separators into apparent top-level authority.
38
108
  if (/\r(?!\n)|[\v\f\u001c-\u001e\u0085\u2028\u2029]/u.test(text)) {
@@ -42,7 +112,11 @@ export function runtimeBoundary(storyPath, text, {notes=[]}={}) {
42
112
  // Admission is deliberately stricter than Markdown discovery. Count even
43
113
  // unsupported/example markers so uncertain declarations never yield a subset.
44
114
  const markers = lines.flatMap((line,index)=>/[`~]{3,}[ \t]*pdd-boundary\b/.test(line) ? [index] : []);
45
- if (!markers.length) return boundaryNote(notes,/runtime boundary/i.test(text) ? 'legacy-syntax' : 'missing-block');
115
+ if (!markers.length) {
116
+ if (/runtime boundary/i.test(text)) return boundaryNote(notes,'legacy-syntax');
117
+ if (plainProse) return null;
118
+ return boundaryNote(notes,'missing-block');
119
+ }
46
120
  if (markers.length !== 1) return boundaryNote(notes,'duplicate-blocks');
47
121
  const start = markers[0];
48
122
  let fence = null, uncertain = false;
@@ -67,15 +141,38 @@ export function runtimeBoundary(storyPath, text, {notes=[]}={}) {
67
141
  return [...new Set(paths)].sort();
68
142
  }
69
143
 
70
- export function buildBindingPlan({test, storyText, prompts, dependencyPaths=[], boundaryState}) {
144
+ export function buildBindingPlan({test, storyText, prompts, dependencyPaths=[], boundaryState, plainProse}) {
145
+ const isPlainProse = isPlainProsePlan(test, prompts, dependencyPaths, plainProse);
71
146
  const notes=[];
72
- const boundary = boundaryState ? boundaryState.boundary : runtimeBoundary(test.storyPath,storyText,{notes});
73
- if (boundaryState) notes.push(...boundaryState.notes);
147
+ const boundary = boundaryState ? boundaryState.boundary : runtimeBoundary(test.storyPath,storyText,{notes, plainProse: isPlainProse});
148
+ if (boundaryState) {
149
+ for (const note of rows(boundaryState.notes)) {
150
+ if (boundary === null && isPlainProse && note?.code === 'boundary-not-applied' && note?.reason === 'missing-block') continue;
151
+ notes.push(note);
152
+ }
153
+ }
154
+ const useStepMinimal = boundary === null && isPlainProse && !notes.some(note => note.code === 'boundary-not-applied');
74
155
  const steps = [], edges = [], problems = [];
75
156
  const allowed = path => boundary === null || boundary.includes(path);
157
+ const entriesByOp = new Map();
158
+ for (const [candidate, iface] of prompts) {
159
+ for (const entry of rows(iface?.entries)) {
160
+ if (!entry || typeof entry.operation !== 'string') continue;
161
+ let list = entriesByOp.get(entry.operation);
162
+ if (!list) { list = []; entriesByOp.set(entry.operation, list); }
163
+ list.push(candidate);
164
+ }
165
+ }
76
166
  for (const step of rows(test.doc?.steps)) {
77
167
  if (!step || typeof step.entry_path !== 'string') continue;
78
- const closure = new Set(), pending = [step.entry_path, ...(boundary ?? dependencyPaths)];
168
+ const simulation = stepSimulation(test.doc.simulation, step.simulation_overrides);
169
+ const sim = useStepMinimal ? simulationGraph(simulation) : null;
170
+ const closure = new Set();
171
+ const pending = boundary !== null
172
+ ? [step.entry_path, ...boundary]
173
+ : useStepMinimal
174
+ ? [step.entry_path, ...sim.promptTargets]
175
+ : [step.entry_path, ...dependencyPaths];
79
176
  for (let index = 0; index < pending.length; index++) {
80
177
  const path = pending[index];
81
178
  if (closure.has(path)) continue;
@@ -83,10 +180,14 @@ export function buildBindingPlan({test, storyText, prompts, dependencyPaths=[],
83
180
  if (!allowed(path)) { problems.push({step_id:step.step_id,prompt_path:path,code:'out-of-boundary'}); continue; }
84
181
  const iface = prompts.get(path);
85
182
  if (!iface) { problems.push({step_id:step.step_id,prompt_path:path,code:'interface-unavailable'}); continue; }
86
- for (const call of rows(iface.calls)) if (typeof call?.target==='string') pending.push(call.target);
183
+ for (const call of rows(iface.calls)) {
184
+ if (typeof call?.target !== 'string') continue;
185
+ if (boundary !== null && call.from_dependencies === true) continue;
186
+ if (useStepMinimal && call.target !== step.entry_path && isMockedPortCall(call, sim)) continue;
187
+ pending.push(call.target);
188
+ }
87
189
  }
88
190
  steps.push({step_id:step.step_id,closure:[...closure].sort()});
89
- const simulation = stepSimulation(test.doc.simulation, step.simulation_overrides);
90
191
  const otherEntryCall = [...closure].some(path => rows(prompts.get(path)?.calls).some(call =>
91
192
  call?.target === step.entry_path && call.target_operation !== step.operation));
92
193
  const active = otherEntryCall ? null : selectedResources(prompts.get(step.entry_path), step.operation);
@@ -102,10 +203,8 @@ export function buildBindingPlan({test, storyText, prompts, dependencyPaths=[],
102
203
  : !binding || typeof binding !== 'object' || binding.action === 'fixture.lookup' && (!Array.isArray(binding.cases) || !binding.cases.length) ? 'invalid-fixture' : 'selected';
103
204
  candidates.push({kind:'simulation',name,cause});
104
205
  }
105
- for (const [candidate,iface] of prompts) for (const entry of rows(iface?.entries)) {
106
- if (!entry) continue;
107
- if (entry.operation !== operation.name) continue;
108
- candidates.push({kind:'prompt',name:`${candidate}#${entry.operation}`,
206
+ for (const candidate of entriesByOp.get(operation.name) ?? []) {
207
+ candidates.push({kind:'prompt',name:`${candidate}#${operation.name}`,
109
208
  cause:!allowed(candidate)?'out-of-boundary':!closure.has(candidate)?'not-in-dependency-closure':'wrong-name'});
110
209
  }
111
210
  const internal = ['key-value','collection','blob','sql','compute'].includes(resource.kind);
@@ -122,7 +221,9 @@ export function buildBindingPlan({test, storyText, prompts, dependencyPaths=[],
122
221
  }
123
222
 
124
223
  export function bindingPlanLines(plan) {
125
- return [`Bindings: ${plan.test}; boundary: ${plan.boundary?.join(', ') ?? 'full dependency closure'}`,
224
+ const scope = plan.boundary?.join(', ')
225
+ ?? (plan.notes?.some(note => note.code === 'boundary-not-applied') ? 'full dependency closure' : 'step-minimal closure');
226
+ return [`Bindings: ${plan.test}; boundary: ${scope}`,
126
227
  ...plan.edges.map(edge=>`${edge.step_id}: ${edge.prompt_path}: ${edge.key}: ${edge.state}; considered: ${edge.candidates.map(candidate=>`${candidate.kind} ${candidate.name} (${candidate.cause})`).join(', ') || 'none'}${edge.repair ? `; repair: ${edge.repair}` : ''}`),
127
228
  ...(plan.notes ?? []).map(note=>`${note.code}: ${note.message}`),
128
229
  ...plan.problems.map(problem=>`${problem.step_id}: ${problem.prompt_path}: ${problem.code}; repair: correct the declared boundary or Runtime call target.`)];