@promptdriven/runtime-client 1.1.1 → 1.1.3

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.1",
3
+ "version": "1.1.3",
4
4
  "description": "PDD Runtime Client (@promptdriven/runtime-client)",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -0,0 +1,53 @@
1
+ // Adaptive multi-Story check concurrency pacing (AIMD).
2
+ // Bounds default batch concurrency (instead of unbounded Infinity bursts),
3
+ // backs off multiplicatively on HTTP 429 / capacity / provider contention,
4
+ // and ramps back up conservatively after consecutive clean completions.
5
+
6
+ export const DEFAULT_CHECK_CONCURRENCY = 4;
7
+ export const ADAPTIVE_RECOVERY_SUCCESSES = 2;
8
+
9
+ export function createAdaptiveConcurrency({ ceiling = DEFAULT_CHECK_CONCURRENCY, initial = ceiling } = {}) {
10
+ const maxWindow = Number.isSafeInteger(ceiling) && ceiling >= 1 ? ceiling : DEFAULT_CHECK_CONCURRENCY;
11
+ const startWindow = Math.max(1, Math.min(maxWindow, Number.isSafeInteger(initial) && initial >= 1 ? initial : maxWindow));
12
+ return {
13
+ ceiling: maxWindow,
14
+ window: startWindow,
15
+ cleanCompletions: 0,
16
+ contentionEvents: 0,
17
+ countedSignals: new Set(),
18
+ countedSuccesses: new Set(),
19
+ };
20
+ }
21
+
22
+ export function recordContention(state, signalKey = null, { reason = 'contention' } = {}) {
23
+ if (!state) return { changed: false, previous: 1, current: 1, reason };
24
+ if (signalKey != null) {
25
+ if (state.countedSignals.has(signalKey)) return { changed: false, previous: state.window, current: state.window, reason };
26
+ state.countedSignals.add(signalKey);
27
+ }
28
+ state.contentionEvents += 1;
29
+ state.cleanCompletions = 0;
30
+ const previous = state.window;
31
+ state.window = Math.max(1, Math.floor(state.window / 2));
32
+ return { changed: state.window !== previous, previous, current: state.window, reason };
33
+ }
34
+
35
+ export function recordCleanSuccess(state, successKey = null) {
36
+ if (!state) return { changed: false, previous: 1, current: 1 };
37
+ if (successKey != null) {
38
+ if (state.countedSuccesses.has(successKey)) return { changed: false, previous: state.window, current: state.window };
39
+ state.countedSuccesses.add(successKey);
40
+ }
41
+ if (state.window >= state.ceiling) {
42
+ state.cleanCompletions = 0;
43
+ return { changed: false, previous: state.window, current: state.window };
44
+ }
45
+ state.cleanCompletions += 1;
46
+ if (state.cleanCompletions >= ADAPTIVE_RECOVERY_SUCCESSES) {
47
+ const previous = state.window;
48
+ state.window = Math.min(state.ceiling, state.window + 1);
49
+ state.cleanCompletions = 0;
50
+ return { changed: state.window !== previous, previous, current: state.window };
51
+ }
52
+ return { changed: false, previous: state.window, current: state.window };
53
+ }
@@ -60,6 +60,9 @@ function observed(current){const last=current.last_answer;if(!object(last)||type
60
60
  const before=own(report,'input_world')?report.input_world:own(last,'world_before')?last.world_before:undefined;
61
61
  const after=own(report,'world')?report.world:own(last,'world_after')?last.world_after:undefined;
62
62
  if(before!==undefined)run.world_before=clone(before);if(after!==undefined)run.world_after=clone(after);
63
+ const calls=object(report.calls)?report.calls:object(last.calls)?last.calls:undefined;
64
+ const recordingAvailable=typeof report.recording_available==='boolean'?report.recording_available:typeof last.recording_available==='boolean'?last.recording_available:undefined;
65
+ if(calls!==undefined)run.calls=clone(calls);if(recordingAvailable!==undefined)run.recording_available=recordingAvailable;
63
66
  if(typeof last.screen==='string')run.screen=last.screen;if(Array.isArray(last.screens))run.screens=last.screens.filter(x=>typeof x==='string').slice(0,64);
64
67
  return run;
65
68
  }
@@ -1,11 +1,61 @@
1
- // Generated from prompts/cli/agent-judge.prompt.md (sha256: 7413bb037488fc165d9f2e799ca4b04017b326ee8acee87da119c68d7af175a5).
1
+ // Generated from prompts/cli/agent-judge.prompt.md (sha256: 2931d1ba2f74b5399eba9d5f39e72af05e00af3c469eb7bd1125e1cfd6a2b834).
2
2
  import {isDeepStrictEqual} from 'node:util';
3
3
  const clone=value=>JSON.parse(JSON.stringify(value));
4
4
  const own=(x,k)=>x!==null&&typeof x==='object'&&Object.hasOwn(x,k);
5
+ const isPlainObj=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
6
+ const isCountMap=x=>isPlainObj(x)&&Object.values(x).every(v=>Number.isSafeInteger(v)&&v>=0);
7
+ const PATH_HEX_COUNTER_RE=/^path-([0-9a-f]+)-(.+)$/;
8
+ const utf8Decoder=new TextDecoder('utf-8',{fatal:true});
5
9
  const references=x=>Array.isArray(x)?x.some(references):x!==null&&typeof x==='object'&&(own(x,'$step_result')||Object.values(x).some(references));
6
10
  const entry=s=>`${s.entry_path}#${s.operation}`;
7
11
  const validPointer=p=>typeof p==='string'&&(p===''||(p.startsWith('/')&&!/~(?:[^01]|$)/.test(p)));
8
12
  function at(value,path){if(!validPointer(path))return{invalid:true};if(value===undefined)return{missing:true};if(path==='')return{value};for(const key of path.slice(1).split('/').map(k=>k.replace(/~1/g,'/').replace(/~0/g,'~'))){if(!own(value,key))return{missing:true};value=value[key];}return{value};}
13
+ function hasRecordedCalls(run){
14
+ if(!isPlainObj(run)||run.recording_available===false)return false;
15
+ const c=run.calls;
16
+ if(!isPlainObj(c))return false;
17
+ const hasInternal=own(c,'internal'),hasResources=own(c,'resources');
18
+ if(!hasInternal&&!hasResources)return false;
19
+ if(hasInternal&&!isCountMap(c.internal))return false;
20
+ if(hasResources&&!isCountMap(c.resources))return false;
21
+ return true;
22
+ }
23
+ function promptStem(decodedPath){
24
+ const base=decodedPath.split('/').at(-1)??decodedPath;
25
+ return base.endsWith('.prompt.md')?base.slice(0,-'.prompt.md'.length):base;
26
+ }
27
+ function decodeHexUtf8(hex){
28
+ if(!hex||hex.length%2!==0||!/^[0-9a-f]+$/.test(hex))return null;
29
+ try{return utf8Decoder.decode(Buffer.from(hex,'hex'));}catch{return null;}
30
+ }
31
+ function resolveCallsPointer(calls,path){
32
+ const direct=at(calls,path);
33
+ if(!direct.missing&&!direct.invalid)return direct;
34
+ if(direct.invalid||!isPlainObj(calls))return direct;
35
+ let bucketName,rest;
36
+ if(path.startsWith('/resources/')){bucketName='resources';rest=path.slice('/resources/'.length);}
37
+ else if(path.startsWith('/internal/')){bucketName='internal';rest=path.slice('/internal/'.length);}
38
+ else return direct;
39
+ if(rest.includes('/'))return direct;
40
+ const reqKey=rest.replace(/~1/g,'/').replace(/~0/g,'~');
41
+ const bucket=own(calls,bucketName)?calls[bucketName]:null;
42
+ if(!isPlainObj(bucket))return direct;
43
+ const matches=[];
44
+ for(const [key,count] of Object.entries(bucket)){
45
+ if(bucketName==='internal'){
46
+ if(key.startsWith('path-')){
47
+ const decoded=decodeHexUtf8(key.slice('path-'.length));
48
+ if(decoded!==null&&promptStem(decoded)===reqKey)matches.push(count);
49
+ }
50
+ continue;
51
+ }
52
+ const m=PATH_HEX_COUNTER_RE.exec(key);
53
+ if(!m)continue;
54
+ const decoded=decodeHexUtf8(m[1]);
55
+ if(decoded!==null&&`${promptStem(decoded)}-${m[2]}`===reqKey)matches.push(count);
56
+ }
57
+ return matches.length===1?{value:matches[0]}:direct;
58
+ }
9
59
  function observedTarget(run,target,path){
10
60
  if(target==='world')return run.world_after===undefined?{unavailable:true}:at(run.world_after,path);
11
61
  const hasError=own(run,'error')&&run.error!==undefined&&run.error!==null,hasResult=!hasError&&own(run,'result')&&run.result!==undefined;
@@ -30,7 +80,28 @@ export function createRunJudge({scenario,checkPassed=[]}){
30
80
  for(const c of criteria){const checks=(s.checks??[]).filter(ch=>ch.criterion_id===c.id);if(!checks.length)continue;const item={id:c.id,state:'tried',compared:0,unchecked:[]};
31
81
  const skip=reason=>{if(!item.unchecked.includes(reason))item.unchecked.push(reason);};
32
82
  for(const ch of checks){
33
- if(ch.target==='calls'){skip('calls not checked here: pdd test covers them');continue;}
83
+ if(ch.target==='calls'){
84
+ if(!['equals','not_equals','one_of','count'].includes(ch.op)||!validPointer(ch.path)||!own(ch,'value')||(ch.op==='one_of'&&(!Array.isArray(ch.value)||!ch.value.length))||(ch.op==='count'&&(!Number.isSafeInteger(ch.value)||ch.value<0))){skip('unsupported check not checked here');continue;}
85
+ if(references(ch.value)){skip('step-result reference not checked here');continue;}
86
+ if(run.recording_available===false){skip('calls not checked: dispatch recording unavailable');continue;}
87
+ if(!hasRecordedCalls(run)){skip('calls not checked: dispatch recording data unavailable');continue;}
88
+ const actual=resolveCallsPointer(run.calls,ch.path);
89
+ item.compared++;
90
+ let passed=false,got=actual.missing||actual.value===undefined?null:clone(actual.value);
91
+ if(ch.op==='equals'){passed=!actual.missing&&isDeepStrictEqual(actual.value,ch.value);}
92
+ else if(ch.op==='not_equals'){passed=!actual.missing&&!isDeepStrictEqual(actual.value,ch.value);}
93
+ else if(ch.op==='one_of'){passed=!actual.missing&&ch.value.some(v=>isDeepStrictEqual(actual.value,v));}
94
+ else{
95
+ let counted;
96
+ if(!actual.missing&&isPlainObj(actual.value)&&Object.values(actual.value).every(v=>Number.isSafeInteger(v))){counted=Object.values(actual.value).filter(v=>v>0).length;}
97
+ else if(!actual.missing&&(Array.isArray(actual.value)||typeof actual.value==='string')){counted=actual.value.length;}
98
+ else if(!actual.missing&&isPlainObj(actual.value)){counted=Object.keys(actual.value).length;}
99
+ got=counted!==undefined?counted:null;
100
+ passed=counted!==undefined&&counted===ch.value;
101
+ }
102
+ if(!passed){const difference={target:ch.target,path:ch.path,...(ch.op!=='equals'?{op:ch.op}:{}),expected:clone(ch.value),got,...(actual.missing?{missing:true}:{})};item.first_difference??=difference;firstDifference??=difference;}
103
+ continue;
104
+ }
34
105
  if(ch.op!=='equals'||!['result','error','world'].includes(ch.target)||!validPointer(ch.path)||!own(ch,'value')){skip('unsupported check not checked here');continue;}
35
106
  if(references(ch.value)){skip('step-result reference not checked here');continue;}
36
107
  if(ch.target==='world'&&!same){skip('world not checked: different or unknown starting data');continue;}
@@ -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'));
@@ -573,6 +594,16 @@ export async function reconcileCheckReceipt(input, ports) {
573
594
  return reconcile(input, ports);
574
595
  }
575
596
 
597
+ export async function reconcileCheckBatch(input, ports) {
598
+ const { reconcileCheckBatch: reconcile } = await import('./runtime-client.mjs');
599
+ return reconcile(input, ports);
600
+ }
601
+
602
+ export async function reconcileStaleReservations(input, ports) {
603
+ const { reconcileStaleReservations: reconcile } = await import('./runtime-client.mjs');
604
+ return reconcile(input, ports);
605
+ }
606
+
576
607
  export async function askAgent(input, ports) {
577
608
  const { askAgent: ask } = await import('./agent-ask.mjs');
578
609
  return ask(input, ports);
@@ -698,6 +729,12 @@ export async function simulate(input = {}, ports) {
698
729
  else if (input?.mode === 'serve' && options['--serve'] === undefined) options['--serve'] = input?.port ?? true;
699
730
  else if (input?.mode === 'save-last') options['--save-last'] = true;
700
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;
701
738
  const testWord =
702
739
  typeof input?.test === 'string' && input.test.length > 0
703
740
  ? input.test
@@ -63,16 +63,18 @@ function scopedHandlers(handlers, screen, encode) {
63
63
  return output;
64
64
  }
65
65
 
66
+ const APP_MAP_VERSIONS = new Set(['prompt-runtime.app-map.v1', 'prompt-runtime.app-map.v2']);
67
+
66
68
  function validateMap(map, part) {
67
69
  const invalid = field => badMap(`app/maps/${part}.json has a missing or malformed ${field} field.`);
68
70
  const required = (value, fields, parent) => {
69
71
  if (!plain(value)) invalid(parent);
70
72
  for (const field of fields) if (!Object.hasOwn(value, field)) invalid(`${parent}.${field}`);
71
73
  };
72
- required(map, ['schema_version', 'name', 'initial_screen', 'initial_route', 'initial_state', 'state_schema', 'synthetic', 'screens', 'router', 'routes', 'handlers', 'stylesheets'], 'map');
74
+ required(map, ['name', 'initial_screen', 'initial_route', 'initial_state', 'state_schema', 'synthetic', 'screens', 'router', 'routes', 'handlers', 'stylesheets'], 'map');
73
75
  const supported=new Set(['schema_version','name','initial_screen','initial_route','initial_state','state_schema','synthetic','screens','router','routes','handlers','stylesheets']);
74
76
  for(const key of Object.keys(map))if(!supported.has(key))badMap(`app/maps/${part}.json: unsupported composition field ${key}; preserve it in a standalone Simulator.`);
75
- if (map.schema_version !== 'prompt-runtime.app-map.v1') invalid('schema_version');
77
+ if (Object.hasOwn(map, 'schema_version') && !APP_MAP_VERSIONS.has(map.schema_version)) invalid('schema_version');
76
78
  for (const field of ['name', 'initial_screen']) if (typeof map[field] !== 'string' || !map[field]) invalid(field);
77
79
  if (map.initial_route !== null && typeof map.initial_route !== 'string') invalid('initial_route');
78
80
  if (typeof map.synthetic !== 'boolean') invalid('synthetic');
@@ -129,8 +131,8 @@ function joinMaps(product, parts, maps, chain, encode, selectedParts) {
129
131
  let tapOperations = 0;
130
132
  for (const [index, map] of maps.entries()) {
131
133
  const part = parts[index], screenId = id => `${part}/${id}`;
132
- if (map.schema_version !== joined.schema_version || !Array.isArray(map.screens) || !Array.isArray(map.handlers)
133
- || !Array.isArray(map.stylesheets) || !Array.isArray(map.routes) || !Object.hasOwn(map, 'initial_state') || !plain(map.state_schema)) badMap(`app/maps/${part}.json is not a complete v1 map.`);
134
+ if ((Object.hasOwn(map, 'schema_version') && !APP_MAP_VERSIONS.has(map.schema_version)) || !Array.isArray(map.screens) || !Array.isArray(map.handlers)
135
+ || !Array.isArray(map.stylesheets) || !Array.isArray(map.routes) || !Object.hasOwn(map, 'initial_state') || !plain(map.state_schema)) badMap(`app/maps/${part}.json is not a complete v1/v2 map.`);
134
136
  const ids = new Set();
135
137
  for (const screen of map.screens) {
136
138
  if (!plain(screen) || Object.keys(screen).sort().join(',') !== 'format,id,input,operation,prompt_path,result_pointer,source'
@@ -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.');