@promptdriven/runtime-client 1.0.0 → 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.
- package/package.json +1 -1
- package/src/runtime/agent-chat.mjs +55 -8
- package/src/runtime/index.mjs +32 -1
- package/src/runtime/live-local-bridge.mjs +178 -0
- package/src/runtime/live-local.mjs +181 -0
- package/src/runtime/run-program.mjs +797 -0
- package/src/runtime/runtime-bindings.mjs +22 -12
- package/src/runtime/runtime-check-plan.mjs +1 -1
- package/src/runtime/runtime-client.mjs +2009 -218
- package/src/runtime/runtime-outcome.mjs +63 -2
- package/src/runtime/runtime-output.mjs +46 -8
- package/src/runtime/runtime-preflight.mjs +793 -79
- package/src/runtime/runtime-slots.mjs +75 -4
- package/src/runtime/scenario-json.mjs +167 -1
- package/src/runtime/secret-redaction.mjs +3 -2
- package/src/runtime/try-doors.mjs +425 -59
- package/src/runtime/try-http.mjs +40 -14
- package/src/runtime/try-update-policy.mjs +43 -0
package/src/runtime/try-http.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Generated from prompts/cli/try-http.prompt.md (sha256:
|
|
1
|
+
// Generated from prompts/cli/try-http.prompt.md (sha256: 31a599108c95b490698b28941fda14ecf6405a8e4a5a00bd9539c8c351c4d3b7).
|
|
2
2
|
import { createServer, validateHeaderName, validateHeaderValue } from 'node:http';
|
|
3
3
|
import { join, relative } from 'node:path';
|
|
4
4
|
import {loadRuntimeWorkspace} from './runtime-workspace.mjs';
|
|
@@ -119,7 +119,7 @@ async function requestText(req) {
|
|
|
119
119
|
|
|
120
120
|
// Build a request only from authored input; missing values remain visible placeholders.
|
|
121
121
|
function requestExample(entry, tests, port) {
|
|
122
|
-
const step = tests.flatMap(test => test
|
|
122
|
+
const step = tests.flatMap(test => test?.doc?.steps ?? []).find(step => step.entry_path === entry.entry_path && step.operation === entry.operation);
|
|
123
123
|
const input = step?.input ?? {}, props = propertiesOf(entry.input_schema);
|
|
124
124
|
const missing = name => `<required:${name}>`;
|
|
125
125
|
const path = entry.route.path.replace(/:([A-Za-z][A-Za-z0-9_]*)/g, (_, name) => {
|
|
@@ -150,17 +150,33 @@ function requestExample(entry, tests, port) {
|
|
|
150
150
|
return args.map(shellWord).join(' ');
|
|
151
151
|
}
|
|
152
152
|
|
|
153
|
-
export async function openServe(context, test, sessionId, options) {
|
|
153
|
+
export async function openServe(context, test, sessionId, options = {}) {
|
|
154
154
|
const { ports, root, origin, identity } = context;
|
|
155
|
-
|
|
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});
|
|
156
171
|
const model = await context.runtime.send(`/v1/try/${sessionId}/model`, { method: 'GET' }, 30_000);
|
|
157
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.'));
|
|
158
|
-
const routes = model.json.entries.filter(e => e.http).map(entry => ({ ...entry, route: entry.http }));
|
|
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 }));
|
|
159
174
|
const hasScreen = model.json.app_map === true;
|
|
160
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.');
|
|
161
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)}`);
|
|
162
178
|
if (context.appMap) {
|
|
163
|
-
const command =
|
|
179
|
+
const command = serveCommand(options['--serve'] ?? 8080, true);
|
|
164
180
|
throw problem(502, `This saved Try has no Screen app map. Start a new Try with the selected app map: ${command}`);
|
|
165
181
|
}
|
|
166
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).');
|
|
@@ -192,11 +208,15 @@ export async function openServe(context, test, sessionId, options) {
|
|
|
192
208
|
const body = await requestText(req);
|
|
193
209
|
if (req.method === 'POST' && req.headers['content-type']?.split(';')[0] !== 'application/json') throw problem(415, 'Screen actions require application/json.');
|
|
194
210
|
if (stopped || context.signal?.aborted) throw problem(503, 'The local Try is stopped.');
|
|
195
|
-
const
|
|
196
|
-
...(req.method === 'POST' ? { headers: { 'Content-Type': 'application/json' }, body } : {}) }
|
|
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);
|
|
197
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.');
|
|
198
217
|
const text = upstream.text ?? JSON.stringify(upstream.json);
|
|
199
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();
|
|
200
220
|
res.writeHead(upstream.status, { 'content-type': upstream.headers?.get('content-type') || 'application/json; charset=utf-8',
|
|
201
221
|
'content-length': Buffer.byteLength(text), 'cache-control': 'no-store', 'content-security-policy': SCREEN_CSP,
|
|
202
222
|
'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff' });
|
|
@@ -219,7 +239,9 @@ export async function openServe(context, test, sessionId, options) {
|
|
|
219
239
|
ports.stderr?.write(`${label}: running on the Try…\n`);
|
|
220
240
|
const work = tail.then(async () => {
|
|
221
241
|
if (stopped || context.signal?.aborted) throw problem(503, 'The local Try is stopped.');
|
|
222
|
-
|
|
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,
|
|
223
245
|
{ ...ports, signal: context.signal });
|
|
224
246
|
});
|
|
225
247
|
tail = work.catch(() => {});
|
|
@@ -239,21 +261,25 @@ export async function openServe(context, test, sessionId, options) {
|
|
|
239
261
|
finally { if (counted) pending--; }
|
|
240
262
|
});
|
|
241
263
|
server.requestTimeout = 30_000; server.headersTimeout = 15_000;
|
|
242
|
-
const wanted = Number(options['--serve'] ?? 8080);
|
|
264
|
+
const wanted = Number(options['--serve'] === true ? 8080 : options['--serve'] ?? 8080);
|
|
243
265
|
await new Promise((done, reject) => { server.once('error', reject); server.listen(wanted, '127.0.0.1', done); }).catch(error => {
|
|
244
|
-
|
|
245
|
-
if (error.code === '
|
|
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)}.`);
|
|
246
269
|
throw error;
|
|
247
270
|
});
|
|
248
271
|
const stop = () => { stopped = true; server.close(); server.closeIdleConnections(); server.closeAllConnections(); };
|
|
249
272
|
context.signal?.addEventListener('abort', stop, { once: true });
|
|
250
273
|
const port = server.address().port;
|
|
251
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`);
|
|
252
|
-
if (routes.length) ports.stdout.write(`Example: ${requestExample(routes[0], context.simulationTests ?? [test], port)}\n`);
|
|
275
|
+
if (routes.length) ports.stdout.write(`Example: ${requestExample(routes[0], context.simulationTests ?? (test ? [test] : []), port)}\n`);
|
|
253
276
|
if (hasScreen) ports.stdout.write(`Screen: http://127.0.0.1:${port}/\n`);
|
|
254
277
|
try {
|
|
255
278
|
if (ports.serve) { await ports.serve(server); return 0; }
|
|
256
279
|
await new Promise(done => { server.once('close', done); if (context.signal?.aborted) stop(); });
|
|
257
280
|
return 0;
|
|
258
|
-
} finally {
|
|
281
|
+
} finally {
|
|
282
|
+
stop(); context.signal?.removeEventListener('abort', stop);
|
|
283
|
+
if (free) { await tail; await context.persistProgram(); }
|
|
284
|
+
}
|
|
259
285
|
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Generated from prompts/cli/try-update-policy.prompt.md.
|
|
2
|
+
const categories = ['tests', 'approvals'];
|
|
3
|
+
const validRevisions = value => value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
4
|
+
&& categories.every(key => Number.isSafeInteger(value[key]) && value[key] >= 0);
|
|
5
|
+
const deadline = (now, delay) => Math.min(Number.MAX_SAFE_INTEGER, now + delay);
|
|
6
|
+
|
|
7
|
+
export function advanceTryUpdates({ state, event, now, watchMs }) {
|
|
8
|
+
const fresh = desired => ({ desired, acknowledged: -1, target: null, retryAt: 0, nextAt: 0, missing: false });
|
|
9
|
+
let next = state === null ? null : { ...state, tests: { ...state.tests }, approvals: { ...state.approvals } };
|
|
10
|
+
let error = null, read = [], postApprovals = false;
|
|
11
|
+
const end = () => { next.mode = 'ended'; for (const category of categories) next[category].target = null; next.deliveryInFlight = false; };
|
|
12
|
+
if (event.kind === 'connect' && next === null) {
|
|
13
|
+
const valid = !event.advertised || validRevisions(event.revisions);
|
|
14
|
+
next = { mode: event.advertised ? 'notifications' : 'legacy', tests: fresh(valid && event.advertised ? event.revisions.tests : 0), approvals: fresh(valid && event.advertised ? event.revisions.approvals : 0), deliveryPending: false, deliveryInFlight: false, deliveryRetryAt: 0 };
|
|
15
|
+
if (!valid) { error = 'invalid-update-revisions'; end(); }
|
|
16
|
+
} else if (next.mode !== 'ended') {
|
|
17
|
+
if (event.kind === 'notice' && next.mode === 'notifications') {
|
|
18
|
+
if (!validRevisions(event.revisions) || categories.some(key => event.revisions[key] < next[key].desired)) { error = 'invalid-update-revisions'; end(); }
|
|
19
|
+
else for (const category of categories) next[category].desired = event.revisions[category];
|
|
20
|
+
} else if (event.kind === 'plan') {
|
|
21
|
+
for (const category of categories) {
|
|
22
|
+
const item = next[category];
|
|
23
|
+
if (!item.missing && item.target === null && now >= item.retryAt && (next.mode === 'notifications' ? item.desired > item.acknowledged : now >= item.nextAt)) {
|
|
24
|
+
item.target = item.desired; read.push(category);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
if (next.deliveryPending && !next.deliveryInFlight && now >= next.deliveryRetryAt) { next.deliveryInFlight = true; postApprovals = true; }
|
|
28
|
+
} else if (event.kind === 'complete') {
|
|
29
|
+
const item = next[event.category];
|
|
30
|
+
if (item.target !== null) {
|
|
31
|
+
if (event.outcome === 'success') { item.acknowledged = item.target; item.retryAt = 0; item.nextAt = deadline(now, watchMs); }
|
|
32
|
+
else if (event.outcome === 'retry') item.retryAt = deadline(now, event.retryMs);
|
|
33
|
+
else if (event.outcome === 'missing') item.missing = true;
|
|
34
|
+
else if (event.outcome === 'ended') end();
|
|
35
|
+
item.target = null;
|
|
36
|
+
}
|
|
37
|
+
} else if (event.kind === 'delivery') {
|
|
38
|
+
next.deliveryPending = event.pending; next.deliveryInFlight = false;
|
|
39
|
+
next.deliveryRetryAt = event.pending ? deadline(now, event.retryMs) : 0;
|
|
40
|
+
} else if (event.kind === 'end') end();
|
|
41
|
+
}
|
|
42
|
+
return { state: next, read, postApprovals, pollRevisions: next.mode === 'notifications' ? Object.fromEntries(categories.map(key => [key, next[key].missing ? null : next[key].acknowledged])) : null, error };
|
|
43
|
+
}
|