@promptdriven/runtime-client 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +42 -2
  3. package/package.json +28 -4
  4. package/src/index.mjs +1 -0
  5. package/src/runtime/agent-ask.mjs +187 -0
  6. package/src/runtime/agent-chat.mjs +152 -0
  7. package/src/runtime/agent-coverage.mjs +97 -0
  8. package/src/runtime/agent-guide.mjs +152 -0
  9. package/src/runtime/agent-judge.mjs +71 -0
  10. package/src/runtime/agent-packet.mjs +62 -0
  11. package/src/runtime/agent-project.mjs +93 -0
  12. package/src/runtime/contract-refs.mjs +519 -0
  13. package/src/runtime/contracts.mjs +138 -0
  14. package/src/runtime/index.mjs +974 -0
  15. package/src/runtime/lint-call-preflight.mjs +19 -0
  16. package/src/runtime/lint-compatibility-display.mjs +62 -0
  17. package/src/runtime/live-local-bridge.mjs +178 -0
  18. package/src/runtime/live-local.mjs +181 -0
  19. package/src/runtime/product-composition.mjs +384 -0
  20. package/src/runtime/run-program.mjs +797 -0
  21. package/src/runtime/runtime-binding-plan.mjs +145 -0
  22. package/src/runtime/runtime-bindings.mjs +81 -0
  23. package/src/runtime/runtime-check-plan.mjs +411 -0
  24. package/src/runtime/runtime-client.mjs +8114 -0
  25. package/src/runtime/runtime-lint-receipt.mjs +25 -0
  26. package/src/runtime/runtime-markdown.mjs +215 -0
  27. package/src/runtime/runtime-outcome.mjs +468 -0
  28. package/src/runtime/runtime-output.mjs +752 -0
  29. package/src/runtime/runtime-preflight.mjs +3832 -0
  30. package/src/runtime/runtime-slots.mjs +462 -0
  31. package/src/runtime/runtime-workspace-migration.mjs +70 -0
  32. package/src/runtime/runtime-workspace.mjs +52 -0
  33. package/src/runtime/scenario-json.mjs +257 -0
  34. package/src/runtime/secret-redaction.mjs +54 -0
  35. package/src/runtime/try-doors.mjs +597 -0
  36. package/src/runtime/try-http.mjs +285 -0
  37. package/src/runtime/try-mcp.mjs +223 -0
  38. package/src/runtime/try-session.mjs +95 -0
  39. package/src/runtime/try-update-policy.mjs +43 -0
@@ -0,0 +1,384 @@
1
+ // Generated from prompts/cli/product-composition.prompt.md (sha256: 5cce422befd0b81cf14251b2c7bed26572b988dc55a8dd5535ff6e684564cded).
2
+ import { basename, join } from 'node:path';
3
+ import { checkInput, interfaceBlocks, parsePromptFrontmatter, PreflightError, promptMarkdownTargets } from './runtime-preflight.mjs';
4
+ import { expandSource, isJsonNumber, jsonNumberIdentity, parseJsonValue, stringifyJsonValue } from './contract-refs.mjs';
5
+
6
+ const fail = (code, message) => { throw Object.assign(Error(message), { code }); };
7
+ const badMap = message => fail('invalid-product-map', message);
8
+ const escape = value => value.replace(/~/g, '~0').replace(/\//g, '~1');
9
+ const plain = value => value !== null && typeof value === 'object' && !Array.isArray(value) && !isJsonNumber(value);
10
+ const ref = path => ({ $ref: path });
11
+
12
+ function matcherEqual(a, b) {
13
+ if (a === b) return true;
14
+ const numeric = value => isJsonNumber(value) || typeof value === 'number' || typeof value === 'boolean';
15
+ if (numeric(a) && numeric(b)) return jsonNumberIdentity(typeof a === 'boolean' ? Number(a) : a) === jsonNumberIdentity(typeof b === 'boolean' ? Number(b) : b);
16
+ if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((value, index) => matcherEqual(value, b[index]));
17
+ return plain(a) && plain(b) && Object.keys(a).length === Object.keys(b).length
18
+ && Object.entries(a).every(([key, value]) => Object.hasOwn(b, key) && matcherEqual(value, b[key]));
19
+ }
20
+
21
+ function scopeTemplate(value, part) {
22
+ if (Array.isArray(value)) return value.map(item => scopeTemplate(item, part));
23
+ if (!plain(value)) return value;
24
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key,
25
+ key === '$ref' && typeof item === 'string' && /^\/state(?:\/|$)/.test(item)
26
+ ? `/state/${escape(part)}${item.slice(6)}` : scopeTemplate(item, part)]));
27
+ }
28
+
29
+ function scopedHandlers(handlers, screen, encode) {
30
+ const applicable = handlers.filter(rule => rule.screen === '*' || rule.screen === screen);
31
+ const output = [];
32
+ for (const kind of new Set(applicable.map(rule => rule.kind))) {
33
+ const rules = applicable.filter(rule => rule.kind === kind);
34
+ if (!rules.some(rule => rule.screen === '*') || !rules.some(rule => rule.screen === screen)) { output.push(...rules); continue; }
35
+ const entries = value => Object.entries(value);
36
+ const compatible = (a, b) => entries(a).every(([key, value]) => !Object.hasOwn(b, key) || matcherEqual(value, b[key]));
37
+ const covers = (a, b) => entries(a).every(([key, value]) => Object.hasOwn(b, key) && matcherEqual(value, b[key]));
38
+ const behavior = rule => encode(Object.fromEntries(entries(rule).filter(([key]) => !['screen', 'match'].includes(key))));
39
+ const conditions = [], queue = [];
40
+ const addCondition = match => { if (!conditions.some(prior => matcherEqual(prior, match))) { conditions.push(match); queue.push(match); } };
41
+ for (const rule of rules) addCondition(rule.match);
42
+ for (let index = 0; index < queue.length; index++) for (const rule of rules) {
43
+ const match = queue[index];
44
+ if (!compatible(match, rule.match)) continue;
45
+ addCondition({ ...match, ...rule.match });
46
+ }
47
+ const compiled = conditions.map(match => {
48
+ const eligible = rules.filter(rule => covers(rule.match, match));
49
+ eligible.sort((a, b) => Number(a.screen === screen) - Number(b.screen === screen) || Object.keys(a.match).length - Object.keys(b.match).length);
50
+ return { ...eligible.at(-1), match };
51
+ });
52
+ const minimal = compiled.filter(rule => !compiled.some(other => other !== rule && Object.keys(other.match).length < Object.keys(rule.match).length
53
+ && covers(other.match, rule.match) && behavior(other) === behavior(rule)
54
+ && !compiled.some(competitor => behavior(competitor) !== behavior(rule) && compatible(competitor.match, rule.match)
55
+ && Object.keys(competitor.match).length >= Object.keys(other.match).length)));
56
+ for (let index = 0; index < minimal.length; index++) for (const other of minimal.slice(index + 1)) {
57
+ if (Object.keys(minimal[index].match).length === Object.keys(other.match).length && compatible(minimal[index].match, other.match)) {
58
+ badMap(`Unsupported wildcard priority on ${screen}: overlapping ${kind} rules cannot retain their original priority after scoping.`);
59
+ }
60
+ }
61
+ output.push(...minimal);
62
+ }
63
+ return output;
64
+ }
65
+
66
+ function validateMap(map, part) {
67
+ const invalid = field => badMap(`app/maps/${part}.json has a missing or malformed ${field} field.`);
68
+ const required = (value, fields, parent) => {
69
+ if (!plain(value)) invalid(parent);
70
+ for (const field of fields) if (!Object.hasOwn(value, field)) invalid(`${parent}.${field}`);
71
+ };
72
+ required(map, ['schema_version', 'name', 'initial_screen', 'initial_route', 'initial_state', 'state_schema', 'synthetic', 'screens', 'router', 'routes', 'handlers', 'stylesheets'], 'map');
73
+ const supported=new Set(['schema_version','name','initial_screen','initial_route','initial_state','state_schema','synthetic','screens','router','routes','handlers','stylesheets']);
74
+ 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');
76
+ for (const field of ['name', 'initial_screen']) if (typeof map[field] !== 'string' || !map[field]) invalid(field);
77
+ if (map.initial_route !== null && typeof map.initial_route !== 'string') invalid('initial_route');
78
+ if (typeof map.synthetic !== 'boolean') invalid('synthetic');
79
+ for (const field of ['initial_state', 'state_schema']) if (!plain(map[field])) invalid(field);
80
+ for (const field of ['screens', 'routes', 'handlers', 'stylesheets']) if (!Array.isArray(map[field])) invalid(field);
81
+ for (const screen of map.screens) {
82
+ required(screen, ['id', 'prompt_path', 'operation', 'source', 'format', 'input', 'result_pointer'], 'screen');
83
+ if (typeof screen.prompt_path !== 'string' || !screen.prompt_path) invalid('screen.prompt_path');
84
+ if (!['operation', 'mockup'].includes(screen.source)) invalid('screen.source');
85
+ if (screen.source === 'mockup') {
86
+ if (screen.operation !== null) invalid('screen.operation');
87
+ if (screen.format !== 'svg') invalid('screen.format');
88
+ if (screen.result_pointer !== null) invalid('screen.result_pointer');
89
+ } else {
90
+ if (typeof screen.operation !== 'string' || !screen.operation) invalid('screen.operation');
91
+ if (!['html', 'text', 'grid'].includes(screen.format)) invalid('screen.format');
92
+ if (typeof screen.result_pointer !== 'string' || !/^(?:\/(?:[^~]|~[01])*)?$/.test(screen.result_pointer)) invalid('screen.result_pointer');
93
+ }
94
+ }
95
+ if (map.router !== null) required(map.router, ['handler', 'input', 'result_pointer'], 'router');
96
+ for (const route of map.routes) required(route, ['name', 'screen', 'input'], 'route');
97
+ for (const handler of map.handlers) {
98
+ required(handler, ['screen', 'kind', 'match', 'handler', 'input', 'next', 'state'], 'handler');
99
+ required(handler.next, ['kind', 'screen', 'route_pointer'], 'handler.next');
100
+ if (!plain(handler.match)) invalid('handler.match');
101
+ if (Object.hasOwn(handler, 'after') && !Array.isArray(handler.after)) invalid('handler.after');
102
+ for (const after of handler.after ?? []) required(after, ['handler', 'input', 'bind'], 'handler.after');
103
+ }
104
+ }
105
+
106
+ function joinMaps(product, parts, maps, chain, encode, selectedParts) {
107
+ maps.forEach((map, index) => validateMap(map, parts[index]));
108
+ let scratch = 'product_after';
109
+ while (selectedParts.includes(scratch)) scratch += '_';
110
+ const slots = Object.fromEntries(chain.map((operation, index) => [String(index), operation.resultSchema === null
111
+ ? {}
112
+ : checkInput(null, operation.resultSchema, 0).refusals.length
113
+ ? { oneOf: [{ type: 'null' }, operation.resultSchema] } : operation.resultSchema]));
114
+ const initial = Object.fromEntries(parts.map((part, index) => [part, maps[index].initial_state]));
115
+ const properties = Object.fromEntries(parts.map((part, index) => [part, maps[index].state_schema]));
116
+ if (chain.length) {
117
+ initial[scratch] = Object.fromEntries(chain.map((_operation, index) => [String(index), null]));
118
+ properties[scratch] = { type: 'object', properties: slots, required: Object.keys(slots), additionalProperties: false };
119
+ }
120
+ const stateKeys = Object.keys(initial);
121
+ const allScreens = maps.flatMap((map, index) => (Array.isArray(map.screens) ? map.screens : []).map(screen => `${parts[index]}/${screen.id}`));
122
+ const globalIds = new Set(allScreens);
123
+ if (globalIds.size !== allScreens.length) badMap('Selected parts produce duplicate qualified screen IDs.');
124
+ const joined = { schema_version: 'prompt-runtime.app-map.v1', name: product.name,
125
+ initial_screen: `${parts[0]}/${maps[0].initial_screen}`, initial_route: maps[0].initial_route,
126
+ initial_state: initial, state_schema: { type: 'object', properties, required: stateKeys, additionalProperties: false },
127
+ synthetic: maps.some(map => map.synthetic === true), screens: [], router: null, routes: [], handlers: [], stylesheets: [] };
128
+ const labels = [], routers = [], routes = new Map();
129
+ let tapOperations = 0;
130
+ for (const [index, map] of maps.entries()) {
131
+ 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
+ const ids = new Set();
135
+ for (const screen of map.screens) {
136
+ if (!plain(screen) || Object.keys(screen).sort().join(',') !== 'format,id,input,operation,prompt_path,result_pointer,source'
137
+ || typeof screen.id !== 'string' || !screen.id || ids.has(screen.id)) badMap(`app/maps/${part}.json has an invalid or duplicate screen ID.`);
138
+ ids.add(screen.id);
139
+ joined.screens.push({ ...screen, id: screenId(screen.id), input: scopeTemplate(screen.input, part) });
140
+ labels.push({ id: screenId(screen.id), title: `${part} · ${screen.id}` });
141
+ }
142
+ if (!ids.has(map.initial_screen)) badMap(`app/maps/${part}.json has an unknown initial screen.`);
143
+ routers.push(map.router === null ? null : scopeTemplate(map.router, part));
144
+ for (const route of map.routes) {
145
+ const scoped = { ...route, screen: screenId(route.screen), input: scopeTemplate(route.input, part) };
146
+ if (!ids.has(route.screen)) badMap(`app/maps/${part}.json has an unknown route screen.`);
147
+ if (routes.has(route.name) && encode(routes.get(route.name)) !== encode(scoped)) fail('unsupported-product-router', `Route ${route.name} selects different part screens.`);
148
+ routes.set(route.name, scoped);
149
+ }
150
+ for (const handler of map.handlers) if (handler.screen !== '*' && !ids.has(handler.screen)) badMap(`app/maps/${part}.json has an unknown handler screen.`);
151
+ for (const target of ids) {
152
+ for (const handler of scopedHandlers(map.handlers, target, encode)) {
153
+ const next = { ...handler.next };
154
+ if (next.screen !== null && next.screen !== undefined) {
155
+ if (ids.has(next.screen)) next.screen = screenId(next.screen);
156
+ else if (!globalIds.has(next.screen)) badMap(`app/maps/${part}.json: next screen ${next.screen} is neither local nor a screen in the selected product parts.`);
157
+ }
158
+ const after = (handler.after ?? []).map(operation => {
159
+ if (typeof operation.bind !== 'string' || !operation.bind.startsWith('/')) badMap(`app/maps/${part}.json has an invalid after binding.`);
160
+ return { ...operation, input: scopeTemplate(operation.input, part), bind: `/${escape(part)}${operation.bind}` };
161
+ });
162
+ if (handler.handler !== null && handler.handler !== undefined) {
163
+ for (const [offset, operation] of chain.entries()) after.push({ handler: operation.handler, input: {}, bind: `/${escape(scratch)}/${offset}` });
164
+ if (after.length > 8) badMap(`app/maps/${part}.json needs ${after.length} after operations; the PDD interpreter limit is 8 (40 total calls per tap).`);
165
+ tapOperations = Math.max(tapOperations, 1 + after.length);
166
+ }
167
+ const state = handler.state === null || handler.state === undefined ? null : Object.fromEntries(stateKeys.map(key => [key,
168
+ key === part ? scopeTemplate(handler.state, part) : ref(`/state/${escape(key)}`)]));
169
+ joined.handlers.push({ ...handler, screen: screenId(target), input: scopeTemplate(handler.input, part), next, state, ...(Object.hasOwn(handler, 'after') || after.length ? { after } : {}) });
170
+ }
171
+ }
172
+ for (const stylesheet of map.stylesheets) if (!joined.stylesheets.includes(stylesheet)) joined.stylesheets.push(stylesheet);
173
+ }
174
+ if (routers.some(router => router !== null)) {
175
+ if (routers.some(router => router === null) || routers.some(router => encode(router) !== encode(routers[0]))) fail('unsupported-product-router', 'Selected maps require incompatible routers; the PDD interpreter has one router slot.');
176
+ joined.router = routers[0];
177
+ }
178
+ joined.routes = [...routes.values()];
179
+ return { map: joined, labels, tapOperations };
180
+ }
181
+
182
+ export function selectJourneys(tests, selector, ports = {}) {
183
+ if (typeof ports?.selectTests !== 'function') {
184
+ throw Object.assign(new Error('Product composition port (selectTests) is not bound.'), { unboundPort: true });
185
+ }
186
+ const candidates = tests.filter(test => /^user_stories\/journeys\/[^/]+\.md$/.test(test.storyPath));
187
+ if (selector === undefined) return candidates.map(test => test.testPath);
188
+ const records = candidates.map(test => ({ ...test, path: test.testPath }));
189
+ const exactPaths = records.filter(test => test.testPath === selector || test.storyPath === selector).map(test => test.testPath);
190
+ const exact = exactPaths.length ? ports.selectTests({ tests: records }, exactPaths).selected : [];
191
+ const matches = exact.length ? exact : records.filter(test => {
192
+ const name = basename(test.storyPath, '.md');
193
+ return name === selector || name.startsWith(`${selector}-`) || name.startsWith(`${selector}.`);
194
+ });
195
+ if (new Set(matches.map(test => test.storyPath)).size !== 1) {
196
+ fail('invalid-journey', `${matches.length ? 'Ambiguous' : 'Unknown'} journey ${selector}. Candidates: ${[...new Set(candidates.map(test => test.storyPath))].join(', ') || 'none'}.`);
197
+ }
198
+ return matches.map(test => test.testPath);
199
+ }
200
+
201
+ export function composeProductTry({ root, parts, journey, testPath }, ports) {
202
+ if (typeof ports?.parseProductDocuments !== 'function' || typeof ports?.parseProductWorldWriters !== 'function') {
203
+ throw Object.assign(new Error('Product composition ports (parseProductDocuments, parseProductWorldWriters) are not bound.'), { unboundPort: true });
204
+ }
205
+ const cached = new Map();
206
+ const read = (path, optional = false) => {
207
+ if (cached.has(path)) return cached.get(path);
208
+ const stat = ports.statFile(join(root, path));
209
+ if (stat?.is_symlink) throw new PreflightError(4, `${path}: symbolic links are not allowed.`);
210
+ if (!stat || typeof stat.exists !== 'boolean') throw new PreflightError(4, `${path}: source file could not be inspected.`);
211
+ if (!stat.exists) { if (optional) return null; badMap(`${path}: required source file is missing.`); }
212
+ const value = ports.readFile(join(root, path));
213
+ const text = typeof value === 'string' ? value : Buffer.isBuffer(value) ? value.toString('utf8') : null;
214
+ if (text === null) badMap(`${path}: the file reader did not return UTF-8 bytes.`);
215
+ cached.set(path, text); return text;
216
+ };
217
+ const files = {
218
+ stat({ path }) { return ports.statFile(join(root, path)); },
219
+ read({ path }) { return { content: read(path) }; },
220
+ };
221
+ try {
222
+ const mapText = read('product/map.md'), planText = read('product/plan.md', true) ?? '';
223
+ const { product } = ports.parseProductDocuments({ mapText, planText });
224
+ const selected = parts === undefined ? product.parts.map(part => part.part) : [...parts];
225
+ if (!selected.length || new Set(selected).size !== selected.length || selected.some(part => !product.parts.some(row => row.part === part))) {
226
+ fail('invalid-product', `Choose distinct product parts from: ${product.parts.map(part => part.part).join(', ')}.`);
227
+ }
228
+ const writers = new Map();
229
+ for (const { key, writer } of ports.parseProductWorldWriters({ worldText: read('contracts/world.md', true) ?? '' })) {
230
+ if (writers.has(key) && writers.get(key) !== writer) fail('world-writer-conflict', `${key} is written by ${writers.get(key)} and ${writer}.`);
231
+ writers.set(key, writer);
232
+ }
233
+ const parseWorld = path => {
234
+ const expanded = expandSource({ path, text: JSON.stringify({ initial_world: { $seed: path } }), format: 'scenario' }, files);
235
+ return parseJsonValue(expanded.text).initial_world;
236
+ };
237
+ let world = read('contracts/seed-world.json', true) === null ? {} : parseWorld('contracts/seed-world.json');
238
+ const contributions = new Map();
239
+ for (const part of selected) {
240
+ const path = `prompts/${part}/seed.json`;
241
+ if (read(path, true) === null) continue;
242
+ const value = parseWorld(path);
243
+ for (const key of Object.keys(value)) {
244
+ if (contributions.has(key) && contributions.get(key) !== part) fail('world-writer-conflict', `${key} is seeded by ${contributions.get(key)} and ${part}.`);
245
+ if (writers.has(key) && writers.get(key) !== part) fail('world-writer-conflict', `${key} is written by ${writers.get(key)}, not seed part ${part}.`);
246
+ contributions.set(key, part);
247
+ }
248
+ world = Object.fromEntries([...Object.entries(world), ...Object.entries(value)]);
249
+ }
250
+ let appMapPath, seedPath;
251
+ for (let suffix = 0; ; suffix++) {
252
+ const tag = suffix ? `_${suffix}` : '';
253
+ appMapPath = `app/maps/product${tag}.json`;
254
+ seedPath = `contracts/product-seed${tag}.json`;
255
+ const mapStat = ports.statFile(join(root, appMapPath), {presenceOnly:true}), seedStat = ports.statFile(join(root, seedPath), {presenceOnly:true});
256
+ if (mapStat?.is_symlink || seedStat?.is_symlink) throw new PreflightError(4, 'Generated product paths must not be symbolic links.');
257
+ if (!mapStat || !seedStat || typeof mapStat.exists !== 'boolean' || typeof seedStat.exists !== 'boolean') throw new PreflightError(4, 'Generated product paths could not be inspected.');
258
+ if (!mapStat.exists && !seedStat.exists) break;
259
+ }
260
+ if (journey !== undefined) {
261
+ if (typeof testPath !== 'string' || !testPath) fail('invalid-journey', 'Choose one journey test path for this Try.');
262
+ const raw = read(testPath), scenario = parseJsonValue(raw);
263
+ selectJourneys([{ testPath, storyPath: scenario.story_path }], journey, ports);
264
+ if (!plain(scenario.initial_world)) fail('invalid-journey', `${testPath}: initial_world must be an object.`);
265
+ // Validate its ordinary standalone seed/reference before using only its set.
266
+ expandSource({ path: testPath, text: raw, format: 'scenario' }, files);
267
+ if (Object.hasOwn(scenario.initial_world, '$seed')) {
268
+ const base = stringifyJsonValue(world), overlay = { ...files,
269
+ stat: input => input.path === seedPath ? { exists: true, is_symlink: false, size: Buffer.byteLength(base) } : files.stat(input),
270
+ read: input => input.path === seedPath ? { content: base } : files.read(input) };
271
+ const initial_world = { $seed: seedPath, ...(Object.hasOwn(scenario.initial_world, 'set') ? { set: scenario.initial_world.set } : {}) };
272
+ world = parseJsonValue(expandSource({ path: testPath, text: stringifyJsonValue({ initial_world }), format: 'scenario' }, overlay).text).initial_world;
273
+ } else world = Object.fromEntries([...Object.entries(world), ...Object.entries(scenario.initial_world)]);
274
+ }
275
+ const afterSection = planText.split(/^##\s+/m).find(section => section.split(/\r?\n/, 1)[0].trim() === 'After every tap');
276
+ const chain = [];
277
+ for (const line of afterSection?.split(/\r?\n/).slice(1) ?? []) {
278
+ const item = /^\s*\d+[.)]\s+`?(.+?\.prompt\.md)#([^\s`#]+)`?\s*$/.exec(line);
279
+ if (!item) { if (/^\s*\d+[.)]/.test(line)) badMap(`Invalid After every tap operation: ${line.trim()}`); continue; }
280
+ const handler = { prompt_path: item[1], operation: item[2] };
281
+ const expanded = expandSource({ path: handler.prompt_path, text: read(handler.prompt_path), format: 'prompt' }, files);
282
+ const blocks = interfaceBlocks(expanded.text);
283
+ if (blocks.length > 1) badMap(`${handler.prompt_path}: expected at most one Runtime interface for ${handler.operation}.`);
284
+ if (!blocks.length) {
285
+ const fm = parsePromptFrontmatter(expanded.text);
286
+ if (fm.error) badMap(`${handler.prompt_path}: invalid prompt frontmatter (${fm.error}).`);
287
+ if (fm.kind === 'native-only') badMap(`${handler.prompt_path}: native-only prompt cannot run After every tap.`);
288
+ chain.push({ handler, resultSchema: null });
289
+ continue;
290
+ }
291
+ const entry = parseJsonValue(blocks[0][1]).entries?.find(operation => operation.operation === handler.operation);
292
+ if (!entry || !plain(entry.result_schema)) badMap(`${handler.prompt_path}: missing operation/result schema ${handler.operation}.`);
293
+ chain.push({ handler, resultSchema: entry.result_schema });
294
+ }
295
+ const mapped = selected.flatMap(part => {
296
+ const text = read(`app/maps/${part}.json`, true);
297
+ return text === null ? [] : [{ part, map: parseJsonValue(text) }];
298
+ });
299
+ if (!mapped.length) badMap('No screen is available: the selected product parts have no app map; Runtime v1 requires an initial screen.');
300
+ const joined = joinMaps(product, mapped.map(item => item.part), mapped.map(item => item.map), chain, stringifyJsonValue, selected);
301
+ const paths = [...new Set([
302
+ ...joined.map.screens.map(screen=>screen.prompt_path),
303
+ ...(joined.map.router ? [joined.map.router.handler.prompt_path] : []),
304
+ ...joined.map.handlers.flatMap(rule=>[...(rule.handler ? [rule.handler.prompt_path] : []), ...(rule.after??[]).map(step=>step.handler.prompt_path)])
305
+ ])];
306
+ const product_parts = selected.map(name=>({name,prompt_paths:[]}));
307
+ for (const path of paths) {
308
+ const owners = selected.filter(name=>{const folder=product.parts.find(part=>part.part===name).folder.replace(/\/$/,'');return path===folder || path.startsWith(folder+'/');});
309
+ if (owners.length > 1) badMap(`Ambiguous product owner for ${path}.`);
310
+ if (owners.length) product_parts.find(part=>part.name===owners[0]).prompt_paths.push(path);
311
+ }
312
+ return { appMapPath, seedPath, files: [{ path: appMapPath, content: stringifyJsonValue(joined.map) }, { path: seedPath, content: stringifyJsonValue(world) }],
313
+ product_parts, parts: selected, journey: journey ?? null, tapOperations: joined.tapOperations, labels: joined.labels };
314
+ } catch (error) {
315
+ if (error?.unboundPort) throw error;
316
+ if (error.exitCode || ['invalid-product', 'invalid-journey', 'world-writer-conflict', 'invalid-product-map', 'unsupported-product-router'].includes(error.code) || /^(?:contract-|seed-)/.test(error.code ?? '')) throw error;
317
+ badMap(`Cannot compose this product Try: ${error.message}`);
318
+ }
319
+ }
320
+
321
+ // Setup-only validation: pure assembly may inspect partial fixtures, but no upload
322
+ // is allowed until all executable source has supplied a bounded graph.
323
+ export function productTapCallBound(map, {root, readFile, statFile}) {
324
+ const read = path => {
325
+ const full=join(root,path), stat=statFile(full);
326
+ if(!stat?.exists || stat.is_symlink)badMap(`Cannot bound product operation: ${path} is unavailable.`);
327
+ return String(readFile(full));
328
+ };
329
+ const files={stat:({path})=>statFile(join(root,path)),read:({path})=>({content:read(path)})};
330
+ const visible={has:path=>{const st=statFile(join(root,path));return !!st?.exists && !st?.is_symlink;}};
331
+ // Same acyclic caller/child/resume recurrence as Runtime's declared graph bound.
332
+ const costs = new Map(), visiting = new Set();
333
+ const cost = reference => {
334
+ const key=reference.prompt_path+'#'+reference.operation;
335
+ if(costs.has(key))return costs.get(key);
336
+ if(visiting.has(key) || visiting.has(reference.prompt_path+'#*'))badMap(`Cannot bound recursive product operation ${key}.`);
337
+ const expanded=expandSource({path:reference.prompt_path,text:read(reference.prompt_path),format:'prompt'},files);
338
+ const blocks=interfaceBlocks(expanded.text);
339
+ if(blocks.length>1)badMap(`Cannot bound ${key}: at most one interface is allowed.`);
340
+ if(!blocks.length) {
341
+ const fm=parsePromptFrontmatter(expanded.text);
342
+ if(fm.error)badMap(`Cannot bound product operation ${key}: invalid prompt frontmatter (${fm.error}).`);
343
+ if(fm.kind==='native-only')badMap(`Cannot bound native-only product operation ${key}.`);
344
+ const plainKey=reference.prompt_path+'#*';
345
+ if(costs.has(plainKey))return costs.get(plainKey);
346
+ if(visiting.has(plainKey))badMap(`Cannot bound recursive product operation ${key}.`);
347
+ visiting.add(plainKey);
348
+ let bound=1;
349
+ for(const target of promptMarkdownTargets(expanded.text,reference.prompt_path,visible)) {
350
+ bound+=cost({prompt_path:target,operation:'*'})+1;
351
+ if(bound>40)break;
352
+ }
353
+ visiting.delete(plainKey);costs.set(plainKey,bound);costs.set(key,bound);return bound;
354
+ }
355
+ visiting.add(key);
356
+ const iface=parseJsonValue(blocks[0][1]);
357
+ if(reference.operation!=='*' && !iface.entries?.some(entry=>entry.operation===reference.operation))badMap(`Unknown product operation ${key}.`);
358
+ let bound=1;
359
+ for(const call of iface.calls??[]) {
360
+ const count=Number(isJsonNumber(call.max_calls)?call.max_calls.text:call.max_calls);
361
+ if(!Number.isSafeInteger(count)||count<1||typeof call.target!=='string'||typeof call.target_operation!=='string')badMap(`Cannot bound call in ${key}.`);
362
+ bound+=count*(cost({prompt_path:call.target,operation:call.target_operation})+1);
363
+ if(bound>40)break;
364
+ }
365
+ const declared=iface.limits?.max_model_calls;
366
+ if(declared!==undefined){const cap=Number(isJsonNumber(declared)?declared.text:declared);if(!Number.isSafeInteger(cap)||cap<1)badMap(`Cannot bound provider allowance for ${key}.`);bound=Math.max(bound,cap);}
367
+ else if((iface.resources??[]).length)badMap(`Cannot bound resource continuations for ${key} without a provider allowance.`);
368
+ visiting.delete(key);costs.set(key,bound);return bound;
369
+ };
370
+ let maxTapCalls=0;
371
+ for(const rule of map.handlers) {
372
+ let bound=(rule.handler?cost(rule.handler):0)+(rule.after??[]).reduce((sum,step)=>sum+cost(step.handler),0);
373
+ let destinations;
374
+ if(rule.next.kind==='screen')destinations=map.screens.filter(screen=>screen.id===rule.next.screen);
375
+ else if(rule.next.kind==='same')destinations=map.screens.filter(screen=>screen.id===rule.screen);
376
+ else destinations=map.screens;
377
+ bound+=Math.max(0,...destinations.map(screen=>screen.source==='mockup'?1:cost(screen)));
378
+ // A dynamic router also evaluates before destination drawing.
379
+ if(rule.next.kind==='route' && map.router)bound+=cost(map.router.handler);
380
+ if(bound>40)badMap(`One product tap may need ${bound} AI calls; the limit is 40. Shorten the background chain or declared calls.`);
381
+ maxTapCalls=Math.max(maxTapCalls,bound);
382
+ }
383
+ return maxTapCalls;
384
+ }