@promptdriven/runtime-client 1.1.0 → 1.1.2

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.
@@ -1,4 +1,4 @@
1
- // Generated from prompts/cli/runtime-preflight.prompt.md (sha256: 82c0d4c07385035d6555f688ddda347268bd17777f02d8394079955bc0d7d0c9).
1
+ // Generated from prompts/cli/runtime-preflight.prompt.md (sha256: 44554fdc6a301396b96768844239cb202714e7ea65f501452c020be929df06ca).
2
2
  import { markdownLinks, markdownDefinitions, markdownSectionText } from './runtime-markdown.mjs';
3
3
  import { buildBindingPlan, runtimeBoundary } from './runtime-binding-plan.mjs';
4
4
  import { createHash } from 'node:crypto';
@@ -26,6 +26,15 @@ const OPTIONAL_STEP_KEYS = ['expected_error', 'simulation_overrides', 'model'];
26
26
  const STEP_KEYS = new Set([...REQUIRED_STEP_KEYS, ...OPTIONAL_STEP_KEYS]);
27
27
  const RULE_OPS = new Set(['at_most', 'at_least', 'lt', 'lte', 'gt', 'gte', 'not_contains', 'all_in', 'equals_ignore_case']);
28
28
  const EXACT_OPS = new Set(['equals', 'not_equals', 'one_of', 'count', 'integer_relation', ...RULE_OPS]);
29
+ const CHECK_OPS = new Set([...EXACT_OPS, 'exists', 'contains']);
30
+ const CALLS_OPS = new Set(['count', 'equals', 'not_equals', 'one_of']);
31
+ const ERROR_OPS = new Set(['count', 'equals', 'exists', 'not_equals', 'one_of']);
32
+ const CHECK_KEYS = new Set(['criterion_id', 'target', 'path', 'op', 'value', 'json_path', 'html', 'measure',
33
+ 'ref_target', 'ref_path', 'ref_json_path', 'derivation']);
34
+ const hasCheckRef = check => isObject(check) && (
35
+ Object.hasOwn(check, 'ref_target') || Object.hasOwn(check, 'ref_path') || Object.hasOwn(check, 'ref_json_path')
36
+ || (isObject(check.value) && (Object.hasOwn(check.value, 'ref_target') || Object.hasOwn(check.value, 'ref_path')))
37
+ );
29
38
  const SCHEMA_RULES = new Set(['type', 'properties', 'required', 'additionalProperties', 'items', 'enum', 'const', 'oneOf',
30
39
  'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf', 'minLength', 'maxLength', 'pattern',
31
40
  'minItems', 'maxItems', 'uniqueItems', 'minProperties', 'maxProperties']);
@@ -831,7 +840,7 @@ export function analyzePromptSelectorWords(prompt, { appMapScreens = [] } = {})
831
840
  || (Array.isArray(entry.conventions) && entry.conventions.includes('screen'))
832
841
  || conventions.some(c => isObject(c) && typeof c.path === 'string' && c.path.startsWith(`/entries/${index}/`) && c.convention === 'screen');
833
842
  const screenBoundOp = typeof entry.operation === 'string'
834
- && appMapScreens.some(screen => screen?.source === 'operation' && screen.prompt_path === prompt.path && screen.operation === entry.operation);
843
+ && appMapScreens.some(screen => (screen?.source ?? 'operation') === 'operation' && screen.prompt_path === prompt.path && (screen.operation ?? 'render') === entry.operation);
835
844
 
836
845
  if (entryIsCli) {
837
846
  kinds.add('cli');
@@ -931,7 +940,10 @@ export function runtimeCoverage({ root, paths = discoveryPromptPaths(root), allo
931
940
  for (const path of paths) {
932
941
  try {
933
942
  const prompt = readPrompt(root, visible, path);
934
- if (prompt.error === 'interface-missing') continue;
943
+ if (prompt.error === 'interface-missing') {
944
+ if (allowMissingInterfaces && typeof prompt.text === 'string' && prompt.text.trim()) checkable++;
945
+ continue;
946
+ }
935
947
  if (promptRefusal(prompt, 'interface') || interfaceSchemaProblems(prompt.interface).length) continue;
936
948
  if (prompt.interface.kind === 'native-only') native_only++;
937
949
  else if (Array.isArray(prompt.interface.entries) && prompt.interface.entries.length && prompt.interface.entries.every(entry => typeof entry?.operation === 'string' && entry.operation.trim() && entry.input_schema && entry.result_schema)) checkable++;
@@ -1033,9 +1045,91 @@ export function numberWarnings(doc, { testPath, testSha, reviews = [] } = {}) {
1033
1045
  return [...warnings];
1034
1046
  }
1035
1047
 
1048
+ export const LAZY_INTERFACE_SYNTHESIS_CALLS = 2;
1049
+ const LAZY_INTERFACE_SYNTHESIS_HEADROOM = 4;
1050
+ const CALL_GRAPH_FANOUT_PER_PROMPT = 5;
1051
+ const CALL_GRAPH_EXECUTION_HEADROOM = 1.75;
1052
+
1053
+ export const hasSimulationBindings = (doc, step = null) =>
1054
+ (typeof doc?.$simulation === 'string' && doc.$simulation.trim().length > 0)
1055
+ || (isObject(doc?.simulation) && Object.keys(doc.simulation).length > 0)
1056
+ || (isObject(step?.simulation_overrides) && Object.keys(step.simulation_overrides).length > 0);
1057
+
1058
+ export function analyzeStepCallCost(entryPath, {
1059
+ getPrompt,
1060
+ visible,
1061
+ allowMissingInterfaces = false,
1062
+ hasSimulationPorts = false,
1063
+ onProblem = null,
1064
+ missingInterfaces = null,
1065
+ reachablePrompts = null,
1066
+ }) {
1067
+ const walk = (path, stack = new Set(), proseOnly = false) => {
1068
+ if (stack.has(path)) {
1069
+ if (!proseOnly && onProblem) onProblem('recursive-call-bound', path, '/calls');
1070
+ return 0;
1071
+ }
1072
+ const prompt = getPrompt(path);
1073
+ const iface = prompt?.interface;
1074
+ if (!iface) {
1075
+ if (allowMissingInterfaces && prompt?.error === 'interface-missing') {
1076
+ missingInterfaces?.add(path);
1077
+ reachablePrompts?.add(path);
1078
+ const next = new Set([...stack, path]);
1079
+ const targets = [...new Set(promptMarkdownTargets(prompt.text, path, visible))];
1080
+ const activeChildren = [];
1081
+ for (const target of targets) {
1082
+ const nested = walk(target, next, true);
1083
+ if (nested > 0) activeChildren.push(nested);
1084
+ }
1085
+ const ownBase = hasSimulationPorts || activeChildren.length > 0 || stack.size > 0 ? 2 : 1;
1086
+ return ownBase + activeChildren.reduce((sum, nested) => sum + nested + 1, 0);
1087
+ }
1088
+ if (onProblem) onProblem(prompt?.error ?? 'interface-missing', path, '/interface');
1089
+ return 0;
1090
+ }
1091
+ if (iface.kind === 'native-only') return 0;
1092
+ reachablePrompts?.add(path);
1093
+ if ((!Number.isSafeInteger(iface.limits?.max_model_calls) || iface.limits.max_model_calls < 1) && onProblem) {
1094
+ onProblem('undefined-call-bound', path, '/limits/max_model_calls');
1095
+ }
1096
+ const next = new Set([...stack, path]);
1097
+ let count = 1 + (Array.isArray(iface.resources) ? iface.resources : []).reduce(
1098
+ (sum, resource) => sum + (Array.isArray(resource.operations) ? resource.operations.length : 0),
1099
+ 0,
1100
+ );
1101
+ for (const [index, call] of (Array.isArray(iface.calls) ? iface.calls : []).entries()) {
1102
+ if ((!Number.isSafeInteger(call?.max_calls) || call.max_calls < 1) && onProblem) {
1103
+ onProblem('undefined-call-bound', path, `/calls/${index}/max_calls`);
1104
+ }
1105
+ const nested = walk(call?.target, next, false);
1106
+ if (Number.isSafeInteger(call?.max_calls) && call.max_calls >= 1 && nested > 0) {
1107
+ count += call.max_calls * (nested + 1);
1108
+ }
1109
+ }
1110
+ return count;
1111
+ };
1112
+ return walk(entryPath, new Set(), false);
1113
+ }
1114
+
1036
1115
  const stepCount = doc => Array.isArray(doc?.steps) ? doc.steps.length : 0;
1116
+ const positiveInt = value => Number.isSafeInteger(value) && value > 0 ? value : 0;
1037
1117
  // Leave room for the whole call graph; the budget is a ceiling, not a charge.
1038
- export const defaultMaxCalls = doc => Math.min(1000, Math.max(18, stepCount(doc) * 12));
1118
+ export function defaultMaxCalls(doc, closure = null) {
1119
+ const steps = stepCount(doc);
1120
+ const baseline = Math.max(18, steps * 12);
1121
+ if (steps === 0 || !isObject(closure)) return Math.min(1000, baseline);
1122
+ const estimatedStepCalls = positiveInt(closure.estimatedStepCalls);
1123
+ const missingInterfaces = positiveInt(closure.missingInterfaceCount);
1124
+ const stepPromptCount = positiveInt(closure.stepPromptCount);
1125
+ const perStepNodes = positiveInt(closure.maxChainFanOut) || positiveInt(closure.promptCount);
1126
+ const fanOutBudget = stepPromptCount > 0
1127
+ ? stepPromptCount * CALL_GRAPH_FANOUT_PER_PROMPT
1128
+ : perStepNodes > 0 ? steps * perStepNodes * CALL_GRAPH_FANOUT_PER_PROMPT : 0;
1129
+ const graphBudget = Math.max(Math.ceil(estimatedStepCalls * CALL_GRAPH_EXECUTION_HEADROOM), fanOutBudget)
1130
+ + missingInterfaces * LAZY_INTERFACE_SYNTHESIS_HEADROOM;
1131
+ return Math.min(1000, Math.max(baseline, graphBudget));
1132
+ }
1039
1133
 
1040
1134
  function firstDifference(testTexts, storyTexts) {
1041
1135
  const left = [...storyTexts];
@@ -1050,7 +1144,7 @@ function firstDifference(testTexts, storyTexts) {
1050
1144
  // Coverage is structural. A negative assertion with an exact calls/world check is checkable.
1051
1145
  const exactCheck = check => EXACT_OPS.has(check?.op) || (isObject(check) && Object.hasOwn(check, 'html') && check.op === 'exists');
1052
1146
  const ordinaryInexactCheck = check => isObject(check) && ['exists','contains'].includes(check.op)
1053
- && ['result','world','calls','error'].includes(check.target) && typeof check.path === 'string'
1147
+ && ['result','world','calls','error','input'].includes(check.target) && typeof check.path === 'string'
1054
1148
  && (check.path === '' || check.path.startsWith('/')) && !/~(?![01])/.test(check.path)
1055
1149
  && (check.op !== 'contains' || Object.hasOwn(check,'value'));
1056
1150
  function criterionPlan(doc, story) {
@@ -1078,10 +1172,15 @@ function criterionPlan(doc, story) {
1078
1172
  const not_checked = criteria.filter(item => !exact.has(item.id)).map(item => ({criterion_id:item.id,text:item.text,
1079
1173
  reason:assigned.has(item.id) ? 'no exact check is assigned' : 'no check is assigned'}));
1080
1174
  const unmatched = [...doc.criteria.map(item => item.text)], used = new Set(criteria.map(item => item.id));
1175
+ const useContentIds = typeof doc.story_path === 'string' && doc.story_path.length > 0
1176
+ && doc.criteria.length > 0 && doc.criteria.every(item => item.id.startsWith('ac-sha256-'));
1081
1177
  for (const [index, text] of story.entries()) {
1082
1178
  const at = unmatched.indexOf(text);
1083
1179
  if (at >= 0) { unmatched.splice(at, 1); continue; }
1084
- const base = `ac-${index + 1}`; let id = base;
1180
+ const base = useContentIds
1181
+ ? `ac-sha256-${sha256(Buffer.from(`${doc.story_path}\0${text}`, 'utf8')).slice(0, 48)}`
1182
+ : `ac-${index + 1}`;
1183
+ let id = base;
1085
1184
  for (let n = 2; used.has(id); n++) id = `${base}-${n}`;
1086
1185
  used.add(id); criteria.push({id,text});
1087
1186
  not_checked.push({criterion_id:id,text,reason:'the test has no criterion for this Story item'});
@@ -1232,7 +1331,7 @@ function stepProblem(step) {
1232
1331
  return null;
1233
1332
  }
1234
1333
  const checkShape = check => isObject(check) && ['criterion_id','target','path','op'].every(key=>Object.hasOwn(check,key));
1235
- const checkTargets = new Set(['result', 'world', 'calls', 'error']);
1334
+ const checkTargets = new Set(['result', 'world', 'calls', 'error', 'input']);
1236
1335
 
1237
1336
  // Reject only paths whose absence is established by every schema alternative.
1238
1337
  function resultPathPossible(schema, path) {
@@ -1858,12 +1957,72 @@ function checkTest(root, found, test, prompts, { allowMissingInterfaces = false,
1858
1957
  return done(refusal('invalid-check', `${section}.checks[${checkIndex}]`, 'A check has criterion_id, target, path and op.', at), story);
1859
1958
  }
1860
1959
  const checkSection = `${section}.checks[${checkIndex}]`;
1861
- if (!checkTargets.has(check.target)) return done(refusal('invalid-check', checkSection, 'A check target must be "result", "world", "calls" or "error".', at), story);
1960
+ const extraKeys = Object.keys(check).filter(key => !CHECK_KEYS.has(key)).sort();
1961
+ if (extraKeys.length) {
1962
+ const isPredicate = typeof check.op === 'string' && (RULE_OPS.has(check.op) || check.op === 'integer_relation');
1963
+ return done(refusal(
1964
+ isPredicate ? 'invalid-predicate' : 'invalid-check',
1965
+ checkSection,
1966
+ isPredicate
1967
+ ? `The check predicate has unsupported keys: ${extraKeys.map(show).join(', ')}.`
1968
+ : `The check has unknown keys: ${extraKeys.map(show).join(', ')}.`,
1969
+ at,
1970
+ ), story);
1971
+ }
1972
+ if (typeof check.target !== 'string' || !checkTargets.has(check.target)) {
1973
+ const message = check.target === 'output'
1974
+ ? 'A check target must be "result", "world", "calls", "error" or "input". Use target "result" to check a step\'s returned output.'
1975
+ : 'A check target must be "result", "world", "calls", "error" or "input".';
1976
+ return done(refusal('invalid-check', checkSection, message, at), story);
1977
+ }
1978
+ if (typeof check.op !== 'string' || !CHECK_OPS.has(check.op)) {
1979
+ return done(refusal(
1980
+ 'unsupported-check',
1981
+ checkSection,
1982
+ `Unsupported check op ${show(check.op)}. Supported ops: ${[...CHECK_OPS].sort().join(', ')}.`,
1983
+ at,
1984
+ ), story);
1985
+ }
1986
+ if (check.target === 'calls' || check.target === 'error') {
1987
+ const allowed = [...(check.target === 'calls' ? CALLS_OPS : ERROR_OPS)].join(', ');
1988
+ if (hasCheckRef(check)) {
1989
+ return done(refusal(
1990
+ 'unsupported-check',
1991
+ checkSection,
1992
+ `Cross-path reference checks (ref_target/ref_path) apply only to "result", "world", and "input" targets, not "${check.target}".`,
1993
+ { ...at, hint: `Check target "result", "world", or "input", or use a literal value with an op supported for "${check.target}" (${allowed}).` },
1994
+ ), story);
1995
+ }
1996
+ if (RULE_OPS.has(check.op) || check.op === 'integer_relation') {
1997
+ return done(refusal(
1998
+ 'unsupported-check',
1999
+ checkSection,
2000
+ `Check op "${check.op}" applies only to "result", "world", and "input" targets; target "${check.target}" supports ${allowed}.`,
2001
+ { ...at, hint: `Change target to "result", "world", or "input", or use a supported op for "${check.target}" (${allowed}).` },
2002
+ ), story);
2003
+ }
2004
+ if (check.op === 'contains') {
2005
+ return done(refusal(
2006
+ 'invalid-contains',
2007
+ checkSection,
2008
+ `Check op "contains" applies only to "result", "world", and "input" targets, not "${check.target}".`,
2009
+ { ...at, hint: `Change target to "result", "world", or "input", or use a supported op for "${check.target}" (${allowed}).` },
2010
+ ), story);
2011
+ }
2012
+ if (check.target === 'calls' && check.op === 'exists') {
2013
+ return done(refusal(
2014
+ 'invalid-call-check',
2015
+ checkSection,
2016
+ 'Target "calls" does not support op "exists"; it supports count, equals, not_equals, and one_of.',
2017
+ { ...at, hint: 'Use "equals" with an integer call count (including 0) on /internal/<id> or /resources/<id>, or "count" on /internal or /resources.' },
2018
+ ), story);
2019
+ }
2020
+ }
1862
2021
  if (check.target === 'result' && errorStep) resultWithErrorRefusal ??= refusal('invalid-check', checkSection, 'A step with expected_error cannot check a successful result. Check the error instead.', at);
1863
2022
  if (check.target === 'result' && entry?.result_schema && !resultPathPossible(entry.result_schema, check.path)) {
1864
2023
  return done(refusal('invalid-check', `${checkSection}.path`, `${show(check.path)} cannot address a value in the result schema of ${step.operation} in ${step.entry_path}.`, at), story);
1865
2024
  }
1866
- if (!ids.has(check.criterion_id)) return done(refusal('unknown-criterion', `${section}.checks[${checkIndex}]`, `The check names ${show(check.criterion_id)}, which is not a criterion ID.`, at), story);
2025
+ if (typeof check.criterion_id !== 'string' || !ids.has(check.criterion_id)) return done(refusal('unknown-criterion', `${section}.checks[${checkIndex}]`, `The check names ${show(check.criterion_id)}, which is not a criterion ID.`, at), story);
1867
2026
  if (EXACT_OPS.has(check.op) || (Object.hasOwn(check, 'html') && check.op === 'exists')) exact.add(check.criterion_id);
1868
2027
  if (check.target === 'error' && check.path === '/code' && check.op === 'equals' && check.value === step.expected_error) errorChecks += 1;
1869
2028
  }
@@ -1887,6 +2046,42 @@ function checkTest(root, found, test, prompts, { allowMissingInterfaces = false,
1887
2046
  return done(null, story);
1888
2047
  }
1889
2048
 
2049
+ function summarizePromptClosure(doc, { prompts, visible, root, workspace, allowMissingInterfaces }) {
2050
+ const steps = Array.isArray(doc?.steps) ? doc.steps : [];
2051
+ if (!steps.length) return null;
2052
+ const getPrompt = path => {
2053
+ if (typeof path !== 'string' || !path) return { error: 'entry-missing' };
2054
+ if (!prompts.has(path)) {
2055
+ try { prompts.set(path, readPrompt(root, visible, path, workspace)); }
2056
+ catch { prompts.set(path, { error: 'interface-unavailable' }); }
2057
+ }
2058
+ return prompts.get(path);
2059
+ };
2060
+ const allPrompts = new Set(), missingInterfaces = new Set();
2061
+ let estimatedStepCalls = 0, stepPromptCount = 0, maxChainFanOut = 0;
2062
+ for (const step of steps) {
2063
+ const stepPrompts = new Set();
2064
+ estimatedStepCalls += analyzeStepCallCost(step?.entry_path, {
2065
+ getPrompt,
2066
+ visible,
2067
+ allowMissingInterfaces,
2068
+ hasSimulationPorts: hasSimulationBindings(doc, step),
2069
+ missingInterfaces,
2070
+ reachablePrompts: stepPrompts,
2071
+ });
2072
+ for (const path of stepPrompts) allPrompts.add(path);
2073
+ stepPromptCount += stepPrompts.size;
2074
+ if (stepPrompts.size > maxChainFanOut) maxChainFanOut = stepPrompts.size;
2075
+ }
2076
+ return {
2077
+ estimatedStepCalls,
2078
+ promptCount: allPrompts.size,
2079
+ stepPromptCount,
2080
+ maxChainFanOut,
2081
+ missingInterfaceCount: missingInterfaces.size,
2082
+ };
2083
+ }
2084
+
1890
2085
  // Rules P1-P10 for the selected tests. Returns rows and warnings; never throws for a test problem.
1891
2086
  export function preflight({ root, found, selected,workspace=found.workspace??loadRuntimeWorkspace({root}), allowMissingInterfaces = false, localLint = false, stepIds = [] }) {
1892
2087
  found={...found,workspace};for(const test of selected)requireRuntimePath(workspace,{path:test.path,from:'Selected test'});
@@ -1926,9 +2121,10 @@ export function preflight({ root, found, selected,workspace=found.workspace??loa
1926
2121
  refused = refusal(error.code ?? 'source-unavailable', 'source', error.message,
1927
2122
  {hint:'Restore the named dependency, make it readable, or correct its declared path.'});
1928
2123
  }
2124
+ const closure = summarizePromptClosure(effectiveDoc, { prompts, visible: found.visible, root, workspace, allowMissingInterfaces });
1929
2125
  const row = { test: test.path, story: test.story, title: test.title, refusals: refused ? [refused].flat() : [], warnings: numberWarnings(effectiveDoc, { testPath: test.path, testSha, reviews }),
1930
2126
  ...(stepIds.length ? {diagnostic:true,diagnostic_subset:true,selected_steps:(effectiveDoc?.steps ?? []).filter(step=>stepIds.includes(step?.step_id)).map(step=>step.step_id)} : {}),
1931
- max_calls: defaultMaxCalls(effectiveDoc), steps: Array.isArray(effectiveDoc?.steps) ? effectiveDoc.steps : [],
2127
+ max_calls: defaultMaxCalls(effectiveDoc, closure), steps: Array.isArray(effectiveDoc?.steps) ? effectiveDoc.steps : [],
1932
2128
  criteria_total: plan?.criteria.length ?? (Array.isArray(effectiveDoc?.criteria) ? effectiveDoc.criteria.length : 0),
1933
2129
  ...(plan?.not_checked.length ? {not_checked:plan.not_checked} : {}), draft: false };
1934
2130
  row.native_only = [...executablePaths].map(path => prompts.get(path)).filter(item => item?.interface?.kind === 'native-only').map(item => ({path:item.path,reason:item.interface.reason}));
@@ -2735,7 +2931,7 @@ function captureOnce(root, { tests, appMap = null, prepareSource,sourceIncludes=
2735
2931
  if (output.role !== undefined) {
2736
2932
  if (output.role !== 'app-map' || prepared.filter(file=>file.role==='app-map').length !== 1 || appMap !== null) throw new PreflightError(4,'prepareSource may mark exactly one app-map and cannot override an explicit map.');
2737
2933
  let map;try{map=JSON.parse(Buffer.from(output.bytes).toString('utf8'));}catch{throw new PreflightError(4,'Prepared app-map must be valid JSON.');}
2738
- if(!isObject(map)||map.schema_version!=='prompt-runtime.app-map.v1')throw new PreflightError(4,'Prepared app-map must be a v1 app map.');
2934
+ if(!isObject(map)||(Object.hasOwn(map,'schema_version')&&!['prompt-runtime.app-map.v1','prompt-runtime.app-map.v2'].includes(map.schema_version))||!Array.isArray(map.screens))throw new PreflightError(4,'Prepared app-map must be a valid app map.');
2739
2935
  appMap=path;
2740
2936
  }
2741
2937
  if (overlay.has(path)) throw sourceProblem('prepareSource', path, `duplicates prepared file ${path}.`);
@@ -2800,10 +2996,15 @@ function captureOnce(root, { tests, appMap = null, prepareSource,sourceIncludes=
2800
2996
  const mapRefusal=appMapsRefusal(doc);
2801
2997
  if (mapRefusal) throw Object.assign(new PreflightError(4,path+': '+mapRefusal.section+': '+mapRefusal.message),
2802
2998
  {code:mapRefusal.code,section:mapRefusal.section});
2803
- if (typeof doc.story_path === 'string') {
2804
- if (selecting) { if (!storyTests.has(doc.story_path)) storyTests.set(doc.story_path,[]); if (!storyTests.get(doc.story_path).includes(path)) storyTests.get(doc.story_path).push(path); }
2805
- add(doc.story_path, path, 'story');
2999
+ const effectiveStoryPath = typeof doc.story_path === 'string' && doc.story_path
3000
+ ? doc.story_path
3001
+ : (path.endsWith('.json') && visible.has(`user_stories/${basename(path, '.json')}.md`)
3002
+ ? `user_stories/${basename(path, '.json')}.md` : null);
3003
+ if (typeof effectiveStoryPath === 'string') {
3004
+ if (selecting) { if (!storyTests.has(effectiveStoryPath)) storyTests.set(effectiveStoryPath,[]); if (!storyTests.get(effectiveStoryPath).includes(path)) storyTests.get(effectiveStoryPath).push(path); }
3005
+ add(effectiveStoryPath, path, 'story');
2806
3006
  }
3007
+ if (typeof doc.entry_path === 'string' && doc.entry_path) add(doc.entry_path, path);
2807
3008
  addStrings(doc.entry_paths, path);
2808
3009
  addStrings(doc.app_maps, path, 'app-map');
2809
3010
  for (const step of Array.isArray(doc.steps) ? doc.steps : []) if (typeof step?.entry_path === 'string') add(step.entry_path, path);
@@ -0,0 +1,125 @@
1
+ // Adaptive polling schedule, Wait-Prefer headers, and Codex-style SSE stream parsing.
2
+ export const WAIT_PREFER_CALL_SECONDS = 15;
3
+ export const WAIT_PREFER_RUN_SECONDS = 25;
4
+ export const SSE_IDLE_MS = 45_000;
5
+
6
+ /**
7
+ * Adaptive polling cadence when no explicit pollMs override is injected by callers/tests:
8
+ * 250ms for the first 2000ms -> 500ms for the next 4000ms -> 1000ms cap.
9
+ */
10
+ export function adaptivePollMs(elapsedMs, explicitPollMs) {
11
+ if (explicitPollMs !== undefined) return explicitPollMs;
12
+ const elapsed = Number.isFinite(elapsedMs) && elapsedMs > 0 ? elapsedMs : 0;
13
+ if (elapsed < 2000) return 250;
14
+ if (elapsed < 6000) return 500;
15
+ return 1000;
16
+ }
17
+
18
+ export function preferWaitHeaders(seconds, extra = {}) {
19
+ const wait = Number.isFinite(seconds) && seconds > 0 ? Math.max(1, Math.min(25, Math.floor(seconds))) : 0;
20
+ return wait > 0 ? { ...extra, Prefer: `respond-async, wait=${wait}` } : { ...extra };
21
+ }
22
+
23
+ export function isSseContentType(headers) {
24
+ const raw = typeof headers?.get === 'function' ? headers.get('content-type') : headers?.['content-type'];
25
+ if (typeof raw !== 'string') return false;
26
+ return raw.split(';', 1)[0].trim().toLowerCase() === 'text/event-stream';
27
+ }
28
+
29
+ /**
30
+ * Incrementally parse an HTTP response body formatted as text/event-stream.
31
+ * Resets the idle timer on every received chunk (including `: keepalive` comments).
32
+ */
33
+ export async function parseSseStream(body, { onEvent, signal, idleMs = SSE_IDLE_MS, parseJson = JSON.parse } = {}) {
34
+ if (!body || typeof body.getReader !== 'function') {
35
+ return { completed: false, events: 0, error: new Error('SSE body is not readable.') };
36
+ }
37
+ const reader = body.getReader();
38
+ const decoder = new TextDecoder('utf-8');
39
+ let buffer = '';
40
+ let eventName = 'message';
41
+ let dataLines = [];
42
+ let events = 0;
43
+ let idleTimer = null;
44
+ let idleTimedOut = false;
45
+
46
+ const armIdle = () => {
47
+ if (idleTimer) clearTimeout(idleTimer);
48
+ if (Number.isFinite(idleMs) && idleMs > 0) {
49
+ idleTimer = setTimeout(() => {
50
+ idleTimedOut = true;
51
+ reader.cancel().catch(() => {});
52
+ }, idleMs);
53
+ }
54
+ };
55
+ const onAbort = () => { reader.cancel().catch(() => {}); };
56
+ signal?.addEventListener('abort', onAbort, { once: true });
57
+
58
+ const dispatch = () => {
59
+ if (!dataLines.length) {
60
+ eventName = 'message';
61
+ return false;
62
+ }
63
+ const raw = dataLines.join('\n');
64
+ const name = eventName || 'message';
65
+ eventName = 'message';
66
+ dataLines = [];
67
+ let json = null;
68
+ try { json = parseJson(raw); } catch { json = null; }
69
+ events++;
70
+ return onEvent?.({ event: name, data: raw, json }) === true;
71
+ };
72
+
73
+ try {
74
+ armIdle();
75
+ for (;;) {
76
+ if (signal?.aborted) break;
77
+ const { value, done } = await reader.read();
78
+ if (done) {
79
+ buffer += decoder.decode();
80
+ break;
81
+ }
82
+ armIdle();
83
+ buffer += decoder.decode(value, { stream: true });
84
+ let newlineIndex;
85
+ while ((newlineIndex = buffer.indexOf('\n')) !== -1) {
86
+ let line = buffer.slice(0, newlineIndex);
87
+ buffer = buffer.slice(newlineIndex + 1);
88
+ if (line.endsWith('\r')) line = line.slice(0, -1);
89
+ if (line === '') {
90
+ if (dispatch()) {
91
+ reader.cancel().catch(() => {});
92
+ return { completed: true, events, idleTimedOut: false };
93
+ }
94
+ continue;
95
+ }
96
+ if (line.startsWith(':')) continue; // Keepalive comment
97
+ const colon = line.indexOf(':');
98
+ const field = colon === -1 ? line : line.slice(0, colon);
99
+ let fieldValue = colon === -1 ? '' : line.slice(colon + 1);
100
+ if (fieldValue.startsWith(' ')) fieldValue = fieldValue.slice(1);
101
+ if (field === 'event') eventName = fieldValue || 'message';
102
+ else if (field === 'data') dataLines.push(fieldValue);
103
+ }
104
+ }
105
+ if (buffer.length) {
106
+ const trailing = buffer.endsWith('\r') ? buffer.slice(0, -1) : buffer;
107
+ if (trailing && !trailing.startsWith(':')) {
108
+ const colon = trailing.indexOf(':');
109
+ const field = colon === -1 ? trailing : trailing.slice(0, colon);
110
+ let fieldValue = colon === -1 ? '' : trailing.slice(colon + 1);
111
+ if (fieldValue.startsWith(' ')) fieldValue = fieldValue.slice(1);
112
+ if (field === 'event') eventName = fieldValue || 'message';
113
+ else if (field === 'data') dataLines.push(fieldValue);
114
+ }
115
+ }
116
+ if (dataLines.length) dispatch();
117
+ return { completed: !idleTimedOut && !signal?.aborted, events, idleTimedOut };
118
+ } catch (error) {
119
+ return { completed: false, events, idleTimedOut, error };
120
+ } finally {
121
+ if (idleTimer) clearTimeout(idleTimer);
122
+ signal?.removeEventListener('abort', onAbort);
123
+ try { reader.releaseLock(); } catch {}
124
+ }
125
+ }
@@ -227,6 +227,7 @@ export async function openCli(context, test, sessionId, options) {
227
227
  const usage = tryUsage(metadata);
228
228
  ports.stderr.write(`${tryUsageLine(usage)}\n`);
229
229
  const descriptor = { callCap: usage.cap, version: 1, root, sessionId, origin, login: identity.login, prompt: step.entry_path, operation: step.operation,
230
+ ...(options?.['--fresh'] === true ? { fresh: true } : {}),
230
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,
231
232
  criterion: step.checks[0]?.criterion_id, storyHash: hash(readFileSync(join(root, test.doc.story_path))),
232
233
  promptHash: hash(prompt.text), stateDir: store.dir, repoState: join(store.folder('repos'), `${store.repoKey(root)}.json`) };
@@ -5,6 +5,7 @@ import {loadRuntimeWorkspace} from './runtime-workspace.mjs';
5
5
  import { checkInput,captureSource } from './runtime-preflight.mjs';
6
6
  import { cleanText, tryUsage, tryUsageHeaders, tryUsageLine } from './runtime-output.mjs';
7
7
  import { runDoorCall } from './runtime-client.mjs';
8
+ import { preferWaitHeaders, WAIT_PREFER_CALL_SECONDS } from './runtime-stream.mjs';
8
9
 
9
10
  const problem = (status, message) => Object.assign(new Error(message), { httpStatus: status });
10
11
  const shellWord = word => /^[A-Za-z0-9_./:@%+=,-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`;
@@ -205,11 +206,18 @@ export async function openServe(context, test, sessionId, options = {}) {
205
206
  if (resource) {
206
207
  if (pending >= 32 || stopped || context.signal?.aborted) throw problem(503, 'The local Try is busy or stopped.');
207
208
  pending++; counted = true;
208
- const body = await requestText(req);
209
+ const rawBody = await requestText(req);
209
210
  if (req.method === 'POST' && req.headers['content-type']?.split(';')[0] !== 'application/json') throw problem(415, 'Screen actions require application/json.');
210
211
  if (stopped || context.signal?.aborted) throw problem(503, 'The local Try is stopped.');
212
+ let body = rawBody;
213
+ if (req.method === 'POST' && options['--fresh'] === true) {
214
+ try {
215
+ const parsed = JSON.parse(rawBody);
216
+ if (object(parsed) && parsed.fresh === undefined) body = JSON.stringify({ ...parsed, fresh: true });
217
+ } catch { /* Preserve original body for upstream validation. */ }
218
+ }
211
219
  const init = { method: req.method === 'HEAD' ? 'GET' : req.method,
212
- ...(req.method === 'POST' ? { headers: { 'Content-Type': 'application/json' }, body } : {}) };
220
+ ...(req.method === 'POST' ? { headers: preferWaitHeaders(WAIT_PREFER_CALL_SECONDS, { 'Content-Type': 'application/json' }), body } : {}) };
213
221
  const upstream = context.programScreen && (req.method === 'POST' || resource.startsWith('api/action?'))
214
222
  ? await context.programScreen(resource, init)
215
223
  : await context.runtime.send(`/v1/try/${sessionId}/screen/${resource}`, init, 90_000);
@@ -241,7 +249,7 @@ export async function openServe(context, test, sessionId, options = {}) {
241
249
  if (stopped || context.signal?.aborted) throw problem(503, 'The local Try is stopped.');
242
250
  if (free) return context.callProgram(selected, input);
243
251
  return runDoorCall({ root, ...(context.programEntry ? { programEntry: context.programEntry,
244
- declaredErrors: (selected.errors ?? []).map(error => typeof error === 'string' ? error : error.code).filter(value => typeof value === 'string') } : { originalPath: test.path }), origin, login: identity.login, sessionId, callCap, prompt: selected.entry_path, operation: selected.operation }, input,
252
+ declaredErrors: (selected.errors ?? []).map(error => typeof error === 'string' ? error : error.code).filter(value => typeof value === 'string') } : { originalPath: test.path }), ...(options['--fresh'] === true ? { fresh: true } : {}), origin, login: identity.login, sessionId, callCap, prompt: selected.entry_path, operation: selected.operation }, input,
245
253
  { ...ports, signal: context.signal });
246
254
  });
247
255
  tail = work.catch(() => {});
@@ -120,16 +120,23 @@ export function createTryTools({ cwd = process.cwd(), words = [], env } = {}, po
120
120
  throw error;
121
121
  }
122
122
  const isProgramError = answer.error !== undefined && answer.error !== null;
123
+ const recordingAvailable = typeof answer.recordingAvailable === 'boolean' ? answer.recordingAvailable
124
+ : typeof answer.recording_available === 'boolean' ? answer.recording_available : undefined;
123
125
  const run = { id: answer.id, ...(answer.actionId !== undefined ? { action_id: answer.actionId } : {}),
124
126
  ...(answer.replayed !== undefined ? { replayed: Boolean(answer.replayed) } : {}),
125
127
  entry: `${entry.entry_path}#${entry.operation}`, input,
126
128
  ...(answer.inputWorld !== undefined ? { world_before: answer.inputWorld } : {}),
127
129
  ...(isProgramError ? { error: answer.error } : { result: answer.result, error: null }),
128
- ...(answer.world !== undefined ? { world_after: answer.world } : {}), lossless: true };
130
+ ...(answer.world !== undefined ? { world_after: answer.world } : {}),
131
+ ...(object(answer.calls) ? { calls: answer.calls } : {}),
132
+ ...(recordingAvailable !== undefined ? { recording_available: recordingAvailable } : {}),
133
+ lossless: true };
129
134
  runs.push(run);
130
135
  return { run_id: run.id, action_id: answer.actionId ?? null, replayed: Boolean(answer.replayed),
131
136
  result: isProgramError ? null : run.result, error: isProgramError ? run.error : null,
132
137
  data_before: run.world_before ?? null, data_after: run.world_after ?? null,
138
+ ...(run.calls !== undefined ? { calls: run.calls } : {}),
139
+ ...(run.recording_available !== undefined ? { recording_available: run.recording_available } : {}),
133
140
  ...(answer.inputWorld === undefined || answer.world === undefined ? { data_warning: 'The interpreter did not supply both run world snapshots; world checks may be unavailable.' } : {}),
134
141
  usage: answer.usage ?? null, seconds: Math.round((Date.now() - started) / 100) / 10 };
135
142
  }