@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,285 @@
1
+ // Generated from prompts/cli/try-http.prompt.md (sha256: 31a599108c95b490698b28941fda14ecf6405a8e4a5a00bd9539c8c351c4d3b7).
2
+ import { createServer, validateHeaderName, validateHeaderValue } from 'node:http';
3
+ import { join, relative } from 'node:path';
4
+ import {loadRuntimeWorkspace} from './runtime-workspace.mjs';
5
+ import { checkInput,captureSource } from './runtime-preflight.mjs';
6
+ import { cleanText, tryUsage, tryUsageHeaders, tryUsageLine } from './runtime-output.mjs';
7
+ import { runDoorCall } from './runtime-client.mjs';
8
+
9
+ const problem = (status, message) => Object.assign(new Error(message), { httpStatus: status });
10
+ const shellWord = word => /^[A-Za-z0-9_./:@%+=,-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`;
11
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
12
+ const HOP = new Set(['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'content-length']);
13
+ const RESERVED_USAGE = new Set(['x-pdd-ai-calls', 'x-pdd-try-used', 'x-pdd-try-remaining', 'x-pdd-try-cap', 'x-pdd-input-tokens', 'x-pdd-cached-input-tokens', 'x-pdd-usage-source']);
14
+ function primitive(values, schema) {
15
+ if (schema?.type === 'array') return values.map(v => primitive([v], schema.items));
16
+ if (values.length !== 1) throw problem(400, 'A query field was repeated; declare an array to accept repeated values.');
17
+ const value = values[0];
18
+ if (schema?.type === 'string') return value;
19
+ if (schema?.type === 'boolean' && /^(true|false)$/.test(value)) return value === 'true';
20
+ if (['integer', 'number'].includes(schema?.type) && /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(value)) {
21
+ const number = Number(value);
22
+ if (Number.isFinite(number) && (schema.type === 'number' || Number.isInteger(number))) return number;
23
+ }
24
+ throw problem(400, 'A query or path value does not match the prompt’s input type.');
25
+ }
26
+ function pathParams(route, pathname) {
27
+ const wanted = route.path.split('/'), got = pathname.split('/');
28
+ if (wanted.length !== got.length) return null;
29
+ const params = Object.create(null);
30
+ for (let i = 0; i < wanted.length; i++) {
31
+ if (wanted[i].startsWith(':')) {
32
+ try { params[wanted[i].slice(1)] = decodeURIComponent(got[i]); } catch { throw problem(400, 'A path parameter has invalid UTF-8 or escaping.'); }
33
+ } else if (wanted[i] !== got[i]) return null;
34
+ }
35
+ return params;
36
+ }
37
+ function propertiesOf(schema) { return object(schema?.properties) ? schema.properties : {}; }
38
+ function inputFor(entry, req, url, params, text, method) {
39
+ const props = propertiesOf(entry.input_schema), querySchema = propertiesOf(props.query), input = Object.create(null);
40
+ const query = Object.create(null), paramValues = Object.create(null), bodyProps = Object.create(null);
41
+ for (const key of new Set(url.searchParams.keys())) {
42
+ const schema = props.query ? querySchema[key] : props[key];
43
+ if (!schema || ['method', 'path', 'headers', 'body', 'params'].includes(key)) throw problem(400, `The route does not declare query field ${cleanText(key)}.`);
44
+ query[key] = primitive(url.searchParams.getAll(key), schema);
45
+ }
46
+ for (const [key, value] of Object.entries(params)) {
47
+ const schema = props.params ? propertiesOf(props.params)[key] : props[key];
48
+ if (!schema) throw problem(400, 'The prompt does not declare this route parameter.');
49
+ paramValues[key] = primitive([value], schema);
50
+ }
51
+ let body;
52
+ if (text.length) {
53
+ if (props.body?.type === 'string') body = text;
54
+ else {
55
+ try { body = JSON.parse(text); } catch { throw problem(400, 'The request body is not valid JSON.'); }
56
+ if (object(body)) for (const [key, value] of Object.entries(body)) bodyProps[key] = value;
57
+ }
58
+ }
59
+ for (const [key, schema] of Object.entries(props)) {
60
+ if (key === 'method') input[key] = method;
61
+ else if (key === 'path') input[key] = url.pathname;
62
+ else if (key === 'query') input[key] = query;
63
+ else if (key === 'params') input[key] = paramValues;
64
+ else if (key === 'headers') {
65
+ const headers = Object.create(null);
66
+ for (const [name, headerSchema] of Object.entries(propertiesOf(schema))) {
67
+ const value = req.headers[name.toLowerCase()];
68
+ if (value !== undefined) headers[name] = primitive(Array.isArray(value) ? value : [value], headerSchema);
69
+ }
70
+ input[key] = headers;
71
+ } else if (key === 'body') { if (body !== undefined) input[key] = body; }
72
+ else if (Object.hasOwn(paramValues, key)) input[key] = paramValues[key];
73
+ else if (Object.hasOwn(query, key)) input[key] = query[key];
74
+ else if (Object.hasOwn(bodyProps, key)) input[key] = bodyProps[key];
75
+ }
76
+ const errors = checkInput(input, entry.input_schema, 0).refusals;
77
+ if (errors.length) throw problem(400, errors[0].message || 'The request does not match the prompt’s input schema.');
78
+ return input;
79
+ }
80
+ function responseFor(result) {
81
+ if (!object(result) || !Number.isInteger(result.status) || result.status < 200 || result.status > 599) throw problem(502, 'The prompt must return an HTTP status from 200 to 599.');
82
+ if (result.headers !== undefined && !object(result.headers)) throw problem(502, 'The prompt must return an object of HTTP headers.');
83
+ const headers = Object.create(null), nominated = new Set(String(result.headers?.connection ?? result.headers?.Connection ?? '').toLowerCase().split(',').map(s => s.trim()));
84
+ for (const [name, value] of Object.entries(result.headers ?? {})) {
85
+ const lower = name.toLowerCase();
86
+ if (HOP.has(lower) || nominated.has(lower) || RESERVED_USAGE.has(lower)) continue;
87
+ if (!(typeof value === 'string' || Array.isArray(value) && value.every(v => typeof v === 'string'))) throw problem(502, 'The prompt returned an invalid HTTP header value.');
88
+ try { validateHeaderName(name); for (const item of Array.isArray(value) ? value : [value]) validateHeaderValue(name, item); } catch { throw problem(502, 'The prompt returned an invalid HTTP header.'); }
89
+ headers[name.toLowerCase()] = value;
90
+ }
91
+ const value = Object.hasOwn(result, 'body') ? result.body : Object.fromEntries(Object.entries(result).filter(([key]) => !['status', 'headers'].includes(key)));
92
+ const body = typeof value === 'string' ? value : JSON.stringify(value);
93
+ if (body === undefined) throw problem(502, 'The prompt returned no HTTP response body.');
94
+ if (!headers['content-type']) headers['content-type'] = typeof value === 'string' ? 'text/plain; charset=utf-8' : 'application/json; charset=utf-8';
95
+ return { status: result.status, headers, body };
96
+ }
97
+
98
+ const SCREEN_PREFIX = '/__pdd/screen/';
99
+ const SCREEN_CSP = "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src data:; connect-src 'self'; frame-src 'self'; base-uri 'self'; form-action 'none'; frame-ancestors 'none'; object-src 'none'";
100
+ function screenResource(url, method) {
101
+ if (url.pathname === '/' && ['GET', 'HEAD'].includes(method) && !url.search) return 'index.html';
102
+ if (!url.pathname.startsWith(SCREEN_PREFIX)) return null;
103
+ const path = url.pathname.slice(SCREEN_PREFIX.length);
104
+ if (['GET', 'HEAD'].includes(method)) {
105
+ if (!url.search && (['index.html', 'door-screen.js', 'door-screen.css', 'try-frame.js', 'api/state'].includes(path) || /^app-asset\/[0-9]+$/.test(path))) return path;
106
+ if (path === 'api/action' && [...url.searchParams.keys()].length === 1 && url.searchParams.has('id') && /^[A-Za-z0-9_-]{1,128}$/.test(url.searchParams.get('id'))) return path + url.search;
107
+ }
108
+ if (method === 'POST' && !url.search && ['api/app/open', 'api/act'].includes(path)) return path;
109
+ return null;
110
+ }
111
+ async function requestText(req) {
112
+ const chunks = []; let size = 0;
113
+ const timeout = setTimeout(() => req.destroy(), 30_000);
114
+ try {
115
+ for await (const chunk of req) { size += chunk.length; if (size > 1024 * 1024) throw problem(413, 'The request body exceeds 1 MiB.'); chunks.push(chunk); }
116
+ } finally { clearTimeout(timeout); }
117
+ try { return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)); } catch { throw problem(400, 'The request body must be UTF-8.'); }
118
+ }
119
+
120
+ // Build a request only from authored input; missing values remain visible placeholders.
121
+ function requestExample(entry, tests, port) {
122
+ const step = tests.flatMap(test => test?.doc?.steps ?? []).find(step => step.entry_path === entry.entry_path && step.operation === entry.operation);
123
+ const input = step?.input ?? {}, props = propertiesOf(entry.input_schema);
124
+ const missing = name => `<required:${name}>`;
125
+ const path = entry.route.path.replace(/:([A-Za-z][A-Za-z0-9_]*)/g, (_, name) => {
126
+ const value = (input.params ?? input)[name];
127
+ return value === undefined ? missing(name) : encodeURIComponent(String(value));
128
+ });
129
+ const query = new URLSearchParams();
130
+ const queryProps = props.query ? propertiesOf(props.query) : props;
131
+ const required = props.query?.required ?? entry.input_schema?.required ?? [];
132
+ const parameters = new Set([...entry.route.path.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(match => match[1]));
133
+ for (const name of Object.keys(queryProps)) {
134
+ if (!props.query && (parameters.has(name) || ['body', 'headers', 'method', 'path', 'params'].includes(name))) continue;
135
+ const value = (props.query ? input.query : input)?.[name];
136
+ if (value !== undefined) for (const item of Array.isArray(value) ? value : [value]) query.append(name, String(item));
137
+ else if (required.includes(name)) query.append(name, missing(name));
138
+ }
139
+ const url = `http://127.0.0.1:${port}${path}${query.size ? `?${query}` : ''}`;
140
+ const args = ['curl', '-X', entry.route.method, url];
141
+ for (const name of Object.keys(propertiesOf(props.headers))) {
142
+ const value = input.headers?.[name];
143
+ if (value !== undefined || props.headers.required?.includes(name)) args.push('-H', `${name}: ${value ?? missing(name)}`);
144
+ }
145
+ if (props.body && (input.body !== undefined || entry.input_schema.required?.includes('body'))) {
146
+ const body = input.body === undefined ? missing('body') : typeof input.body === 'string' ? input.body : JSON.stringify(input.body);
147
+ if (props.body.type !== 'string') args.push('-H', 'Content-Type: application/json');
148
+ args.push('--data', body);
149
+ }
150
+ return args.map(shellWord).join(' ');
151
+ }
152
+
153
+ export async function openServe(context, test, sessionId, options = {}) {
154
+ const { ports, root, origin, identity } = context;
155
+ const free = context.freeProgram === true;
156
+ const serveCommand = (port, fresh = false) => {
157
+ if (free) {
158
+ const programFile = relative(context.cwd ?? root, join(root, context.appMap ?? context.programEntry));
159
+ return ['pdd', 'run', programFile, '--serve', String(port)].map(shellWord).join(' ');
160
+ }
161
+ const target = context.programEntry
162
+ ? [relative(context.cwd ?? root, join(root, context.programTarget ?? context.programEntry))]
163
+ : ['simulate', test.story];
164
+ const map = context.appMap && (context.programEntry || fresh)
165
+ ? ['--app-map', relative(context.cwd ?? root, join(root, context.appMap))] : [];
166
+ return ['pdd', ...target, '--serve', String(port), ...(fresh ? ['--new'] : []), ...map].map(shellWord).join(' ');
167
+ };
168
+ const recovery = port => serveCommand(port);
169
+ if (free && (typeof context.programEntry !== 'string' || typeof context.callProgram !== 'function' || typeof context.persistProgram !== 'function')) throw problem(502, 'The free program server context is incomplete.');
170
+ if(loadRuntimeWorkspace({root}).configured)(ports?.captureSource??((r,o)=>captureSource(r,o,ports)))(root,{tests:[free ? context.programEntry : (context.programEntry ?? test.path)],appMap:context.appMap??null});
171
+ const model = await context.runtime.send(`/v1/try/${sessionId}/model`, { method: 'GET' }, 30_000);
172
+ if (model.status !== 200 || !Array.isArray(model.json?.entries)) throw problem(502, cleanText(model.json?.error?.message || 'The interpreter could not read this Try’s routes. It needs the Try doors server branch.'));
173
+ const routes = model.json.entries.filter(e => e.http && (!context.programEntry || !context.capture?.raw_prompt_hashes || Object.hasOwn(context.capture.raw_prompt_hashes, e.entry_path))).map(entry => ({ ...entry, route: entry.http }));
174
+ const hasScreen = model.json.app_map === true;
175
+ if (hasScreen && routes.some(e => ['GET', 'HEAD'].includes(e.route.method) && e.route.path === '/' || e.route.path.startsWith(SCREEN_PREFIX))) throw problem(502, 'This app map reserves GET/HEAD / and /__pdd/screen/; its HTTP routes conflict with the Screen.');
176
+ if (!routes.length && !hasScreen) {
177
+ if (free) throw problem(502, `This program has neither an admitted Screen app map nor named HTTP routes. Name an HTTP route such as HTTP GET /api/books in input_schema.title, then run: ${recovery(options['--serve'] === true ? 8080 : options['--serve'] ?? 8080)}`);
178
+ if (context.appMap) {
179
+ const command = serveCommand(options['--serve'] ?? 8080, true);
180
+ throw problem(502, `This saved Try has no Screen app map. Start a new Try with the selected app map: ${command}`);
181
+ }
182
+ throw problem(502, 'This Story has neither a Screen app map nor named HTTP routes. Add an app map (RUNBOOK §13), or name an HTTP route such as HTTP GET /api/books in input_schema.title (RUNBOOK §19).');
183
+ }
184
+ const keys = new Set();
185
+ for (const entry of routes) {
186
+ const key = `${entry.route.method} ${entry.route.path.replace(/:[A-Za-z][A-Za-z0-9_]*/g, ':param')}`;
187
+ if (keys.has(key)) throw problem(502, 'This Try has overlapping HTTP route labels; name each method/path once.');
188
+ keys.add(key);
189
+ }
190
+ let latestUsage = tryUsage(model.json);
191
+ const callCap = latestUsage.cap;
192
+ (ports.stderr ?? process.stderr).write(`${tryUsageLine(latestUsage)}\n`);
193
+ let tail = Promise.resolve(), pending = 0, stopped = false;
194
+ const server = createServer(async (req, res) => {
195
+ let counted = false, usage = { ...latestUsage, calls: 0, input_tokens: 'unknown', cached_input_tokens: 'unknown', output_tokens: 'unknown', cached_input_share: null }, usageSource = 'last-known';
196
+ const reply = (status, message) => { if (!res.headersSent) { res.writeHead(status, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', ...tryUsageHeaders(usage), 'x-pdd-usage-source': usageSource }); res.end(`pdd: ${cleanText(message)}\n`); } else res.destroy(); };
197
+ try {
198
+ const port = server.address()?.port, acceptedHost = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
199
+ if (port === 80) { acceptedHost.add('127.0.0.1'); acceptedHost.add('localhost'); }
200
+ const acceptedOrigin = new Set([...acceptedHost].map(host => `http://${host}`));
201
+ if (!acceptedHost.has(req.headers.host) || (req.headers.origin && !acceptedOrigin.has(req.headers.origin)) || req.headers['sec-fetch-site'] === 'cross-site') throw problem(403, 'This local Try accepts requests only from its own origin.');
202
+ if (!req.url.startsWith('/') || req.url.startsWith('//') || req.url.includes('\\')) throw problem(400, 'Use a local absolute request path.');
203
+ const url = new URL(req.url, `http://127.0.0.1:${port}`);
204
+ const resource = hasScreen ? screenResource(url, req.method) : null;
205
+ if (resource) {
206
+ if (pending >= 32 || stopped || context.signal?.aborted) throw problem(503, 'The local Try is busy or stopped.');
207
+ pending++; counted = true;
208
+ const body = await requestText(req);
209
+ if (req.method === 'POST' && req.headers['content-type']?.split(';')[0] !== 'application/json') throw problem(415, 'Screen actions require application/json.');
210
+ if (stopped || context.signal?.aborted) throw problem(503, 'The local Try is stopped.');
211
+ const init = { method: req.method === 'HEAD' ? 'GET' : req.method,
212
+ ...(req.method === 'POST' ? { headers: { 'Content-Type': 'application/json' }, body } : {}) };
213
+ const upstream = context.programScreen && (req.method === 'POST' || resource.startsWith('api/action?'))
214
+ ? await context.programScreen(resource, init)
215
+ : await context.runtime.send(`/v1/try/${sessionId}/screen/${resource}`, init, 90_000);
216
+ if (upstream.lost || !Number.isInteger(upstream.status) || upstream.status < 200 || upstream.status > 599) throw problem(502, 'The Screen request result is unknown. Read its action ID; do not resubmit.');
217
+ const text = upstream.text ?? JSON.stringify(upstream.json);
218
+ if (typeof text !== 'string' || Buffer.byteLength(text) > 16 * 1024 * 1024) throw problem(502, 'The Screen response is unavailable or too large.');
219
+ if (free && upstream.status >= 200 && upstream.status < 300) await context.persistProgram();
220
+ res.writeHead(upstream.status, { 'content-type': upstream.headers?.get('content-type') || 'application/json; charset=utf-8',
221
+ 'content-length': Buffer.byteLength(text), 'cache-control': 'no-store', 'content-security-policy': SCREEN_CSP,
222
+ 'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff' });
223
+ res.end(req.method === 'HEAD' ? '' : text); return;
224
+ }
225
+ if (hasScreen && url.pathname.startsWith(SCREEN_PREFIX)) { req.resume(); reply(404, 'This Screen resource is not available.'); return; }
226
+ let selected, params;
227
+ // A literal route wins over a parameter route; HEAD has its own entry before GET fallback.
228
+ const candidates = routes.filter(e => e.route.method === req.method || req.method === 'HEAD' && e.route.method === 'GET')
229
+ .sort((a, b) => Number(a.route.method !== req.method) - Number(b.route.method !== req.method) || (a.route.path.match(/:/g)?.length ?? 0) - (b.route.path.match(/:/g)?.length ?? 0));
230
+ for (const entry of candidates) { const found = pathParams(entry.route, url.pathname); if (found) { selected = entry; params = found; break; } }
231
+ if (!selected) { req.resume(); reply(404, 'No prompt names this HTTP route.'); return; }
232
+ if (req.headers['sec-fetch-dest'] && req.headers['sec-fetch-dest'] !== 'empty') throw problem(403, 'Use curl or fetch for this API route; embedded resources and page navigations cannot spend AI calls.');
233
+ if (pending >= 32 || stopped) throw problem(503, 'The local Try is busy or stopped.');
234
+ pending++; counted = true;
235
+ const text = await requestText(req);
236
+ const input = inputFor(selected, req, url, params, text, selected.route.method);
237
+ // One line per request in the pdd window, like a local server log: the call can take many seconds.
238
+ const label = `${req.method} ${url.pathname}`, sentAt = Date.now();
239
+ ports.stderr?.write(`${label}: running on the Try…\n`);
240
+ const work = tail.then(async () => {
241
+ if (stopped || context.signal?.aborted) throw problem(503, 'The local Try is stopped.');
242
+ if (free) return context.callProgram(selected, input);
243
+ 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,
245
+ { ...ports, signal: context.signal });
246
+ });
247
+ tail = work.catch(() => {});
248
+ usage = tryUsage({}, { cap: callCap }); usageSource = 'runtime';
249
+ const answer = await work;
250
+ usage = answer.usage; latestUsage = usage;
251
+ const result = responseFor(answer.result);
252
+ const body = req.method === 'HEAD' || [204, 304].includes(result.status) ? '' : result.body;
253
+ const headers = { ...result.headers, ...(![204, 304].includes(result.status) ? { 'content-length': Buffer.byteLength(req.method === 'HEAD' ? result.body : body) } : {}) };
254
+ res.writeHead(result.status, { ...headers, ...tryUsageHeaders(usage), 'x-pdd-usage-source': usageSource }); res.end(body);
255
+ ports.stderr?.write(`${label}: ${result.status} in ${Math.round((Date.now() - sentAt) / 1000)} s\n`);
256
+ } catch (error) {
257
+ if (error.tryUsage) { usage = error.tryUsage; latestUsage = usage; usageSource = 'runtime'; }
258
+ req.resume(); reply(error.httpStatus || 502, error.message || 'The interpreter could not confirm this request.');
259
+ ports.stderr?.write(`${req.method} ${req.url.split('?')[0]}: ${error.httpStatus || 502} ${cleanText(error.message || 'The interpreter could not confirm this request.')}\n`);
260
+ }
261
+ finally { if (counted) pending--; }
262
+ });
263
+ server.requestTimeout = 30_000; server.headersTimeout = 15_000;
264
+ const wanted = Number(options['--serve'] === true ? 8080 : options['--serve'] ?? 8080);
265
+ await new Promise((done, reject) => { server.once('error', reject); server.listen(wanted, '127.0.0.1', done); }).catch(error => {
266
+ const command = serveCommand(wanted === 65535 ? wanted - 1 : wanted + 1);
267
+ if (error.code === 'EADDRINUSE') throw problem(502, `port ${wanted} is in use by another program. Stop it, or run ${command}.`);
268
+ if (error.code === 'EACCES') throw problem(502, `port ${wanted} needs extra rights on this computer. Run ${serveCommand(8080)}.`);
269
+ throw error;
270
+ });
271
+ const stop = () => { stopped = true; server.close(); server.closeIdleConnections(); server.closeAllConnections(); };
272
+ context.signal?.addEventListener('abort', stop, { once: true });
273
+ const port = server.address().port;
274
+ ports.stdout.write(`Try is serving at http://127.0.0.1:${port}\n${routes.length ? routes.map(e => ` ${e.route.method} ${e.route.path}`).join('\n') : ' Screen only (no named HTTP routes).'}\nCtrl-C closes this server. The Try session keeps its saved data.\n`);
275
+ if (routes.length) ports.stdout.write(`Example: ${requestExample(routes[0], context.simulationTests ?? (test ? [test] : []), port)}\n`);
276
+ if (hasScreen) ports.stdout.write(`Screen: http://127.0.0.1:${port}/\n`);
277
+ try {
278
+ if (ports.serve) { await ports.serve(server); return 0; }
279
+ await new Promise(done => { server.once('close', done); if (context.signal?.aborted) stop(); });
280
+ return 0;
281
+ } finally {
282
+ stop(); context.signal?.removeEventListener('abort', stop);
283
+ if (free) { await tail; await context.persistProgram(); }
284
+ }
285
+ }
@@ -0,0 +1,223 @@
1
+ // Generated from prompts/cli/try-mcp.prompt.md (sha256: f005492d96bf72699f50571513cd90416a70c422a79c079a79bb54e3ce7471f9).
2
+ import { createInterface } from 'node:readline';
3
+ import { readTryOwner, observeTryCall, runDoorCall, saveDoorCase, applyPendingCaseWithHandoff } from './runtime-client.mjs';
4
+ import { createRunJudge } from './agent-judge.mjs';
5
+
6
+ const object = x => x !== null && typeof x === 'object' && !Array.isArray(x);
7
+ const text = x => typeof x === 'string' && x.length > 0;
8
+ const validSha256 = x => typeof x === 'string' && /^[0-9a-f]{64}$/i.test(x) ? x.toLowerCase() : null;
9
+ const validEngineSha = x => typeof x === 'string' && /^[0-9a-f]{8,40}$/i.test(x) ? x.toLowerCase() : null;
10
+ const validCommit = x => typeof x === 'string' && x.length > 0 ? x : null;
11
+ const schema = (properties, required = []) => ({
12
+ type: 'object',
13
+ properties: { story: { type: 'string' }, ...properties },
14
+ ...(required.length ? { required } : {}),
15
+ additionalProperties: false,
16
+ });
17
+ const tools = [
18
+ ['try_open', 'Open or reuse the current repo and Story Try, or pass try_id to bind only an existing running simulation without opening or reopening one. Returns its entries, data and budget. No prompt approval.', { try_id: { type: 'string' } }, false],
19
+ ['try_state', 'Read current Try data, entries and schemas, Story criteria, test inputs, runs, budget and progress. Opens a missing Try only when try_id is omitted.', { try_id: { type: 'string' } }, false],
20
+ ['try_run', 'Run one action on the Try, spending its existing AI call budget. Pass try_id to require that exact running Try without opening or reopening one. Use entry and input, or exact CLI argv. Declared entry errors return structured error outcomes; every run appears on the Try page.', { try_id: { type: 'string' }, entry: { type: 'string' }, input: { type: 'object', additionalProperties: true }, argv: { type: 'array', items: { type: 'string' } } }, false],
21
+ ['try_observe', 'Read call state and session state for run_id on try_id without opening, reopening, recovering or replaying a run. Works while the session is running, paused or stopped.', { try_id: { type: 'string' }, run_id: { type: 'string' } }, true, ['try_id', 'run_id']],
22
+ ['try_check', 'Compare a confirmed run with the Story tests, with honest limits and first differences. No AI calls.', { try_id: { type: 'string' }, run_id: { type: 'string' } }, true],
23
+ ['try_save_case', 'Save a confirmed run as an exact observed-result case. Or apply a retained pending_id with closed_editor_for: obtain the person’s actual confirmation that this exact original test is closed and handed over until apply finishes; generic tool approval is insufficient. Review its expectation and starting data; saving does not approve correctness.', { try_id: { type: 'string' }, run_id: { type: 'string' }, criterion_id: { type: 'string' }, name: { type: 'string' }, pending_id: { type: 'string', pattern: '^[0-9a-f]{64}\\.[0-9a-f]{64}$' }, closed_editor_for: { type: 'string', minLength: 1 } }, false],
24
+ ].map(([name, description, properties, readOnlyHint, required]) => ({ name, description, inputSchema: schema(properties, required), annotations: { readOnlyHint, destructiveHint: false, idempotentHint: name !== 'try_run', openWorldHint: false } }));
25
+
26
+ function validate(name, args) {
27
+ const tool = tools.find(tool => tool.name === name);
28
+ if (!tool) throw new Error(`Unknown tool ${name}.`);
29
+ if (!object(args)) throw new Error('Tool arguments must be an object.');
30
+ for (const key of tool.inputSchema.required ?? []) {
31
+ if (!Object.hasOwn(args, key)) throw new Error(`Missing required argument ${key}.`);
32
+ }
33
+ for (const [key, value] of Object.entries(args)) {
34
+ const property = tool.inputSchema.properties[key];
35
+ if (!property) throw new Error(`Unknown argument ${key}.`);
36
+ if (property.type === 'string' && !text(value) || property.type === 'object' && !object(value)
37
+ || property.type === 'array' && (!Array.isArray(value) || !value.every(x => typeof x === 'string'))) throw new Error(`Invalid ${key}.`);
38
+ }
39
+ if (name === 'try_run') {
40
+ if (Object.hasOwn(args, 'argv')) {
41
+ if (Object.hasOwn(args, 'entry') || Object.hasOwn(args, 'input')) throw new Error('Choose argv, or entry and input.');
42
+ } else if (!text(args.entry) || !object(args.input)) throw new Error('Give entry and input, or argv.');
43
+ }
44
+ if(name==='try_save_case'&&(Object.hasOwn(args,'pending_id')||Object.hasOwn(args,'closed_editor_for'))){
45
+ if(!text(args.pending_id)||!text(args.closed_editor_for))throw new Error('Give both pending_id and closed_editor_for for retained-case application.');
46
+ if(!/^[a-f0-9]{64}\.[a-f0-9]{64}$/.test(args.pending_id))throw new Error('Invalid pending_id.');
47
+ if(['story','try_id','run_id','criterion_id','name'].some(key=>Object.hasOwn(args,key)))throw new Error('Pending application accepts only pending_id and closed_editor_for.');
48
+ }
49
+ }
50
+
51
+ function recordedCaseNote({scope,covered,total}){
52
+ const prefix=scope==='original-story'?`Recorded case; covers ${covered} of ${total} Story criteria.${total>1?' Complete coverage before pdd test.':''}`
53
+ :scope==='retained-scenario'?`Recorded case; references ${covered} of ${total} retained scenario criteria. Whole-Story coverage is unavailable. Complete coverage before pdd test.`
54
+ :'Recorded case; criterion coverage is unavailable. Complete coverage before pdd test.';
55
+ return prefix+' This records observed output; review its expectation and saved-data setup before replaying.';
56
+ }
57
+
58
+ export function createTryTools({ cwd = process.cwd(), words = [], env } = {}, ports = {}) {
59
+ const dependencies = {
60
+ ...ports,
61
+ readTryOwner: ports.readTryOwner ?? readTryOwner,
62
+ observeTryCall: ports.observeTryCall ?? observeTryCall,
63
+ runDoorCall: ports.runDoorCall ?? runDoorCall,
64
+ saveDoorCase: ports.saveDoorCase ?? saveDoorCase,
65
+ applyPendingCaseWithHandoff: ports.applyPendingCaseWithHandoff ?? applyPendingCaseWithHandoff,
66
+ };
67
+ const runtimePorts = { ...ports, env: env ?? ports.env ?? process.env, stdout: ports.stderr ?? process.stderr, stderr: ports.stderr ?? process.stderr };
68
+ const sessions = new Map();
69
+ let queue = Promise.resolve();
70
+ async function invoke(name, args) {
71
+ validate(name, args);
72
+ if(name==='try_save_case'&&Object.hasOwn(args,'pending_id')){
73
+ const outcome=await dependencies.applyPendingCaseWithHandoff({cwd,pendingId:args.pending_id,handoff:{kind:'closed-editor',testPath:args.closed_editor_for},signal:runtimePorts.signal},runtimePorts);
74
+ if(outcome.kind!=='case'||outcome.result.state!=='committed')throw new Error(outcome.message);
75
+ return{pending_id:args.pending_id,result:outcome.message,note:recordedCaseNote(outcome.coverage)};
76
+ }
77
+ if (name === 'try_observe') {
78
+ return await dependencies.observeTryCall({ cwd, story: args.story ?? words[0], tryId: args.try_id, runId: args.run_id }, runtimePorts);
79
+ }
80
+ const owner = await dependencies.readTryOwner({ cwd, story: args.story ?? words[0], ...(args.try_id ? { tryId: args.try_id } : {}) }, runtimePorts);
81
+ const key = `${owner.root}:${owner.record.id}`;
82
+ let session = sessions.get(key);
83
+ if (!session) {
84
+ session = { judge: createRunJudge({ scenario: owner.test.doc }), runs: [], unknown: false };
85
+ sessions.set(key, session);
86
+ }
87
+ const { judge, runs } = session;
88
+ if (name === 'try_open' || name === 'try_state') return {
89
+ story: owner.test.title, story_path: owner.test.storyPath, try_id: owner.record.id,
90
+ source_sha256: validSha256(owner.model?.source_sha256) ?? validSha256(owner.source_sha256) ?? validSha256(owner.record?.source_sha256) ?? null,
91
+ engine_sha: validEngineSha(owner.model?.engine_sha) ?? validEngineSha(owner.engine_sha) ?? validEngineSha(owner.record?.engine_sha) ?? null,
92
+ server_commit: validCommit(owner.model?.server_commit) ?? validCommit(owner.server_commit) ?? validCommit(owner.record?.server_commit) ?? null,
93
+ criteria: owner.test.doc.criteria, test_inputs: judge.bindings(),
94
+ entries: owner.model.entries.map(e => ({ ...e, entry: `${e.entry_path}#${e.operation}` })),
95
+ data_now: owner.data ?? null, ...(owner.data_error ? { data_error: owner.data_error } : {}),
96
+ runs: runs.map(({ saved, ...run }) => run), calls: owner.model.calls ?? null, actions: owner.actions ?? null,
97
+ progress: judge.snapshot(), ...(session.unknown ? { warning: 'A run has an unknown outcome. Do not repeat it automatically.' } : {}),
98
+ };
99
+ if (name === 'try_run') {
100
+ if (session.unknown) throw new Error('A prior run has an unknown outcome. Inspect the Try page before starting another run; do not repeat it automatically.');
101
+ let entry, input;
102
+ if (Object.hasOwn(args, 'argv')) {
103
+ const cli = owner.model.entries.filter(e => e.cli === true);
104
+ if (cli.length !== 1) throw new Error('This Try needs exactly one CLI entry for argv. Choose an explicit entry and input from try_state.');
105
+ entry = cli[0]; input = { argv: args.argv };
106
+ } else {
107
+ entry = owner.model.entries.find(e => `${e.entry_path}#${e.operation}` === args.entry);
108
+ input = args.input;
109
+ }
110
+ if (!entry) throw new Error('Unknown entry. Read try_state for admitted entries.');
111
+ const started = Date.now();
112
+ let answer;
113
+ try {
114
+ answer = await dependencies.runDoorCall({ root: owner.root, originalPath:owner.test.path, origin: owner.record.origin, sessionId: owner.record.id,
115
+ login: owner.record.login, prompt: entry.entry_path, operation: entry.operation, callCap: owner.model.calls?.cap ?? null,
116
+ existingOnly: Boolean(args.try_id), declaredErrors: Array.isArray(entry.errors) ? entry.errors : [] }, input, runtimePorts);
117
+ } catch (error) {
118
+ // The door owns dispatch/recovery. Conservatively block a second mutation when its outcome is unconfirmed.
119
+ if (error.unknownOutcome === true) session.unknown = true;
120
+ throw error;
121
+ }
122
+ const isProgramError = answer.error !== undefined && answer.error !== null;
123
+ const run = { id: answer.id, ...(answer.actionId !== undefined ? { action_id: answer.actionId } : {}),
124
+ ...(answer.replayed !== undefined ? { replayed: Boolean(answer.replayed) } : {}),
125
+ entry: `${entry.entry_path}#${entry.operation}`, input,
126
+ ...(answer.inputWorld !== undefined ? { world_before: answer.inputWorld } : {}),
127
+ ...(isProgramError ? { error: answer.error } : { result: answer.result, error: null }),
128
+ ...(answer.world !== undefined ? { world_after: answer.world } : {}), lossless: true };
129
+ runs.push(run);
130
+ return { run_id: run.id, action_id: answer.actionId ?? null, replayed: Boolean(answer.replayed),
131
+ result: isProgramError ? null : run.result, error: isProgramError ? run.error : null,
132
+ data_before: run.world_before ?? null, data_after: run.world_after ?? null,
133
+ ...(answer.inputWorld === undefined || answer.world === undefined ? { data_warning: 'The interpreter did not supply both run world snapshots; world checks may be unavailable.' } : {}),
134
+ usage: answer.usage ?? null, seconds: Math.round((Date.now() - started) / 100) / 10 };
135
+ }
136
+ const run = args.run_id ? runs.find(run => run.id === args.run_id) : runs.at(-1);
137
+ if (!run) throw new Error('No matching confirmed run. Use try_run first.');
138
+ if (name === 'try_check') return { run_id: run.id, verdict: judge.record(run), progress: judge.snapshot() };
139
+ if (run.saved) return { run_id: run.id, already_saved: true, result: run.saved };
140
+ const criteria = owner.test.doc.criteria ?? [];
141
+ const tied = [...new Set(owner.test.doc.steps.filter(step => `${step.entry_path}#${step.operation}` === run.entry).flatMap(step => (step.checks ?? []).map(check => check.criterion_id)))];
142
+ const criterion = args.criterion_id ?? (tied.length === 1 ? tied[0] : undefined);
143
+ if (!criteria.some(item => item.id === criterion)) throw new Error(`Choose criterion_id from: ${criteria.map(item => item.id).join(', ')}.`);
144
+ if (!object(run.world_before)) throw new Error('The interpreter did not provide a confirmed starting world. This run cannot be saved safely.');
145
+ const separator = run.entry.lastIndexOf('#');
146
+ const step = run.error && typeof run.error.code === 'string'
147
+ ? { step_id: `try-${run.id}`, entry_path: run.entry.slice(0, separator), operation: run.entry.slice(separator + 1), input: run.input,
148
+ expected_error: run.error.code, checks: [{ criterion_id: criterion, target: 'error', path: '/code', op: 'equals', value: run.error.code }] }
149
+ : { step_id: `try-${run.id}`, entry_path: run.entry.slice(0, separator), operation: run.entry.slice(separator + 1), input: run.input,
150
+ checks: [{ criterion_id: criterion, target: 'result', path: '', op: 'equals', value: run.result }] };
151
+ const result = dependencies.saveDoorCase(owner.root, { id: run.id, name: args.name ?? 'Recorded Try tool run', story_path: owner.test.storyPath, original_path: owner.test.path,
152
+ test: { schema_version: 'prompt-runtime.program-scenario.v1', story_path: owner.test.storyPath, criteria, initial_world: run.world_before, simulation: owner.test.doc.simulation ?? {}, context: owner.test.doc.context ?? [],
153
+ steps: [step] } }, { ...runtimePorts, ports: runtimePorts, isolated: true });
154
+ if (!result.startsWith('added ') && !result.startsWith('already saved ')) throw new Error(result);
155
+ run.saved = result;
156
+ return { run_id: run.id, result, note: recordedCaseNote({scope:'original-story',covered:1,total:criteria.length}) };
157
+ }
158
+ return { call(name, args = {}) { const result = queue.then(() => invoke(name, args)); queue = result.catch(() => {}); return result; } };
159
+ }
160
+
161
+ export async function runMcp({ cwd = process.cwd(), words = [], env, client } = {}, ports = {}) {
162
+ const serverVersion = typeof client?.version === 'string' && client.version ? client.version : typeof ports.clientVersion === 'string' && ports.clientVersion ? ports.clientVersion : '0.0.0';
163
+ const stdin = ports.stdin ?? process.stdin, stdout = ports.stdout ?? process.stdout, stderr = ports.stderr ?? process.stderr;
164
+ const service = createTryTools({ cwd, words, env }, ports), replay = new Map();
165
+ const send = message => stdout.write(`${JSON.stringify(message)}\n`);
166
+ const error = (id, code, message) => ({ jsonrpc: '2.0', id, error: { code, message } });
167
+ const validId = id => id === null || typeof id === 'string' || typeof id === 'number' && Number.isFinite(id);
168
+ async function respond(msg) {
169
+ const id = msg.id;
170
+ if (msg.method === 'initialize') {
171
+ if (!object(msg.params) || typeof msg.params.protocolVersion !== 'string' || !object(msg.params.capabilities) || !object(msg.params.clientInfo)) return error(id, -32602, 'Invalid initialize parameters');
172
+ const versions = ['2025-06-18', '2025-03-26', '2024-11-05'];
173
+ return { jsonrpc: '2.0', id, result: { protocolVersion: versions.includes(msg.params.protocolVersion) ? msg.params.protocolVersion : versions[0], capabilities: { tools: {} }, serverInfo: { name: 'pdd-try', version: serverVersion } } };
174
+ }
175
+ if (msg.method === 'ping' || msg.method === 'tools/list') {
176
+ if (msg.params !== undefined && !object(msg.params)) return error(id, -32602, 'Parameters must be an object');
177
+ return { jsonrpc: '2.0', id, result: msg.method === 'ping' ? {} : { tools } };
178
+ }
179
+ if (msg.method !== 'tools/call') return error(id, -32601, 'Method not found');
180
+ if (!object(msg.params) || !text(msg.params.name) || msg.params.arguments !== undefined && !object(msg.params.arguments)) return error(id, -32602, 'Invalid tools/call parameters');
181
+ const token = msg.params._meta?.progressToken;
182
+ let progress = 0;
183
+ const tick = () => {
184
+ stderr.write(`pdd mcp: ${msg.params.name} is still working…\n`);
185
+ if (typeof token === 'string' || typeof token === 'number') send({ jsonrpc: '2.0', method: 'notifications/progress', params: { progressToken: token, progress: ++progress, message: `${msg.params.name} is still working` } });
186
+ };
187
+ const timer = setInterval(tick, ports.progressMs ?? 10_000);
188
+ timer.unref?.();
189
+ try {
190
+ const value = await service.call(msg.params.name, msg.params.arguments ?? {});
191
+ return { jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: JSON.stringify(value) }], structuredContent: value } };
192
+ } catch (e) {
193
+ return { jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: String(e.message || 'The Try tool failed.') }], isError: true } };
194
+ } finally { clearInterval(timer); }
195
+ }
196
+ const pending = new Set();
197
+ const input = createInterface({ input: stdin, crlfDelay: Infinity });
198
+ for await (const line of input) {
199
+ if (Buffer.byteLength(line) > 1_048_576) { send(error(null, -32600, 'Request exceeds 1 MiB')); continue; }
200
+ let msg;
201
+ try { msg = JSON.parse(line); } catch { send(error(null, -32700, 'Parse error')); continue; }
202
+ if (!object(msg) || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string' || Object.hasOwn(msg, 'id') && !validId(msg.id)) { send(error(null, -32600, 'Invalid Request')); continue; }
203
+ if (!Object.hasOwn(msg, 'id')) continue;
204
+ const key = `${typeof msg.id}:${msg.id}`, signature = JSON.stringify(msg);
205
+ const prior = replay.get(key);
206
+ if (prior) {
207
+ if (prior.signature !== signature) send(error(msg.id, -32600, 'Request ID already used for a different request'));
208
+ else { const task = prior.answer.then(send); pending.add(task); task.finally(() => pending.delete(task)); }
209
+ continue;
210
+ }
211
+ const answer = respond(msg).catch(() => error(msg.id, -32603, 'Internal error'));
212
+ const record = { signature, answer, settled: false };
213
+ replay.set(key, record);
214
+ // Keep pending IDs until completion and a bounded recent replay window afterwards.
215
+ const task = answer.then(send).finally(() => {
216
+ pending.delete(task); record.settled = true;
217
+ if (replay.size > 1024) for (const [old, cached] of replay) { if (old !== key && cached.settled) { replay.delete(old); break; } }
218
+ });
219
+ pending.add(task);
220
+ }
221
+ await Promise.all(pending);
222
+ return 0;
223
+ }
@@ -0,0 +1,95 @@
1
+ // Generated from prompts/cli/try-session.prompt.md (sha256: 0201646679c184b9c28af44b93264b1602c8ab0a700e7ad394f3fdd362edae57).
2
+
3
+ function fail(code, message = code) {
4
+ const error = new Error(message);
5
+ error.code = code;
6
+ throw error;
7
+ }
8
+
9
+ export function bindExistingTry({ try_id, story, records, drift, model }) {
10
+ const hits = records.filter(record => record.id === try_id);
11
+ if (hits.length !== 1) fail('try-not-found', `No open Try with ID "${try_id}". No new Try was opened.`);
12
+ const record = hits[0];
13
+ if (story !== undefined && story !== '' && ![record.story, record.story_path, record.test_path, record.test_name].includes(story)) {
14
+ fail('story-mismatch', `Try "${try_id}" belongs to "${record.story_path}", not "${story}".`);
15
+ }
16
+ if (drift !== null) fail('source-drift', drift || 'The Story or prompt changed since this Try started.');
17
+ if (model.status !== 200) {
18
+ fail('session-not-running', `Try "${try_id}" is not running (HTTP ${model.status}${model.error_code ? `: ${model.error_code}` : ''}). No new Try or reopen was sent.`);
19
+ }
20
+ if (record.max_calls !== null && model.cap !== null && record.max_calls !== model.cap) {
21
+ fail('cap-mismatch', `Try "${try_id}" reported call cap ${model.cap} instead of pinned cap ${record.max_calls}.`);
22
+ }
23
+ return {
24
+ try_id: record.id,
25
+ test_path: record.test_path,
26
+ story_path: record.story_path,
27
+ source_sha256: record.source_sha256,
28
+ engine_sha: record.engine_sha,
29
+ server_commit: record.server_commit,
30
+ cap: model.cap !== null ? model.cap : record.max_calls,
31
+ remaining: model.remaining,
32
+ };
33
+ }
34
+
35
+ export function projectTryCall({ request_id, declared_errors, state, has_program_result, usage_calls, report }) {
36
+ if (state === 'queued' || state === 'running' || state === 'unknown') {
37
+ fail('unknown-outcome', 'The command result is unknown. Do not repeat it automatically.');
38
+ }
39
+ if (state === 'passed') {
40
+ if (!has_program_result) fail('unknown-outcome', 'The command result is unknown. Do not repeat it automatically.');
41
+ return {
42
+ outcome: 'result',
43
+ run_id: request_id,
44
+ action_id: report !== null ? report.action_id : null,
45
+ error_code: null,
46
+ replayed: report !== null ? Boolean(report.replayed) : false,
47
+ calls: usage_calls,
48
+ remaining_calls: report !== null ? report.remaining_calls : null,
49
+ };
50
+ }
51
+ if ((state === 'failed' || state === 'refused') && report !== null && report.verdict === 'failed' && report.error_code !== null && declared_errors.includes(report.error_code)) {
52
+ return {
53
+ outcome: 'program_error',
54
+ run_id: request_id,
55
+ action_id: report.action_id,
56
+ error_code: report.error_code,
57
+ replayed: Boolean(report.replayed),
58
+ calls: usage_calls,
59
+ remaining_calls: report.remaining_calls,
60
+ };
61
+ }
62
+ fail('call-refused', 'The interpreter refused the command.');
63
+ }
64
+
65
+ export function projectTryObservation({ try_id, run_id, status, body }) {
66
+ if (status === 404) fail('run-not-found', `No call "${run_id}" was found on Try "${try_id}".`);
67
+ if (status === 410) fail('result-expired', `Call "${run_id}" on Try "${try_id}" has expired.`);
68
+ if (status !== 200 || body === null || body.session_id !== try_id || body.request_id !== run_id) {
69
+ fail('observation-unavailable', `Observation for call "${run_id}" on Try "${try_id}" is unavailable${status ? ` (HTTP ${status})` : ''}.`);
70
+ }
71
+ return {
72
+ try_id: body.session_id,
73
+ run_id: body.request_id,
74
+ action_id: body.action_id,
75
+ state: body.state,
76
+ session_state: body.session_state,
77
+ terminal: body.state === 'passed' || body.state === 'failed' || body.state === 'refused',
78
+ unknown_outcome: body.state === 'unknown',
79
+ source_sha256: body.source_sha256,
80
+ server_commit: body.server_commit,
81
+ engine_sha: body.engine_sha,
82
+ };
83
+ }
84
+
85
+ export function selectTryToStop({ selector, records }) {
86
+ if (selector === undefined || selector === '') {
87
+ if (records.length === 0) fail('stop-not-found', 'No open Try in this repository.');
88
+ if (records.length > 1) fail('stop-ambiguous', 'Name the Try to stop.');
89
+ return { id: records[0].id, test_path: records[0].test_path, story_path: records[0].story_path };
90
+ }
91
+ const hits = records.filter(record => [record.id, record.story_path, record.story, record.test_path, record.test_name].includes(selector));
92
+ if (hits.length === 0) fail('stop-not-found', `No open Try for "${selector}".`);
93
+ if (hits.length > 1) fail('stop-ambiguous', `More than one open Try matches "${selector}".`);
94
+ return { id: hits[0].id, test_path: hits[0].test_path, story_path: hits[0].story_path };
95
+ }