@promptdriven/runtime-client 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,11 @@
1
- // Generated from prompts/cli/try-http.prompt.md (sha256: fd02d62d3fa6e26b7f534ce806435737d2afc2a5a709c01c442e2e4e4c9592d1).
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';
5
5
  import { checkInput,captureSource } from './runtime-preflight.mjs';
6
6
  import { cleanText, tryUsage, tryUsageHeaders, tryUsageLine } from './runtime-output.mjs';
7
7
  import { runDoorCall } from './runtime-client.mjs';
8
+ import { preferWaitHeaders, WAIT_PREFER_CALL_SECONDS } from './runtime-stream.mjs';
8
9
 
9
10
  const problem = (status, message) => Object.assign(new Error(message), { httpStatus: status });
10
11
  const shellWord = word => /^[A-Za-z0-9_./:@%+=,-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`;
@@ -119,7 +120,7 @@ async function requestText(req) {
119
120
 
120
121
  // Build a request only from authored input; missing values remain visible placeholders.
121
122
  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 step = tests.flatMap(test => test?.doc?.steps ?? []).find(step => step.entry_path === entry.entry_path && step.operation === entry.operation);
123
124
  const input = step?.input ?? {}, props = propertiesOf(entry.input_schema);
124
125
  const missing = name => `<required:${name}>`;
125
126
  const path = entry.route.path.replace(/:([A-Za-z][A-Za-z0-9_]*)/g, (_, name) => {
@@ -150,17 +151,33 @@ function requestExample(entry, tests, port) {
150
151
  return args.map(shellWord).join(' ');
151
152
  }
152
153
 
153
- export async function openServe(context, test, sessionId, options) {
154
+ export async function openServe(context, test, sessionId, options = {}) {
154
155
  const { ports, root, origin, identity } = context;
155
- if(loadRuntimeWorkspace({root}).configured)(ports?.captureSource??((r,o)=>captureSource(r,o,ports)))(root,{tests:[test.path],appMap:context.appMap??null});
156
+ const free = context.freeProgram === true;
157
+ const serveCommand = (port, fresh = false) => {
158
+ if (free) {
159
+ const programFile = relative(context.cwd ?? root, join(root, context.appMap ?? context.programEntry));
160
+ return ['pdd', 'run', programFile, '--serve', String(port)].map(shellWord).join(' ');
161
+ }
162
+ const target = context.programEntry
163
+ ? [relative(context.cwd ?? root, join(root, context.programTarget ?? context.programEntry))]
164
+ : ['simulate', test.story];
165
+ const map = context.appMap && (context.programEntry || fresh)
166
+ ? ['--app-map', relative(context.cwd ?? root, join(root, context.appMap))] : [];
167
+ return ['pdd', ...target, '--serve', String(port), ...(fresh ? ['--new'] : []), ...map].map(shellWord).join(' ');
168
+ };
169
+ const recovery = port => serveCommand(port);
170
+ if (free && (typeof context.programEntry !== 'string' || typeof context.callProgram !== 'function' || typeof context.persistProgram !== 'function')) throw problem(502, 'The free program server context is incomplete.');
171
+ 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
172
  const model = await context.runtime.send(`/v1/try/${sessionId}/model`, { method: 'GET' }, 30_000);
157
173
  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 }));
174
+ 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
175
  const hasScreen = model.json.app_map === true;
160
176
  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
177
  if (!routes.length && !hasScreen) {
178
+ 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
179
  if (context.appMap) {
163
- const command = ['pdd', 'simulate', test.story, '--serve', String(options['--serve'] ?? 8080), '--new', '--app-map', relative(context.cwd ?? root, join(root, context.appMap))].map(shellWord).join(' ');
180
+ const command = serveCommand(options['--serve'] ?? 8080, true);
164
181
  throw problem(502, `This saved Try has no Screen app map. Start a new Try with the selected app map: ${command}`);
165
182
  }
166
183
  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).');
@@ -189,14 +206,25 @@ export async function openServe(context, test, sessionId, options) {
189
206
  if (resource) {
190
207
  if (pending >= 32 || stopped || context.signal?.aborted) throw problem(503, 'The local Try is busy or stopped.');
191
208
  pending++; counted = true;
192
- const body = await requestText(req);
209
+ const rawBody = await requestText(req);
193
210
  if (req.method === 'POST' && req.headers['content-type']?.split(';')[0] !== 'application/json') throw problem(415, 'Screen actions require application/json.');
194
211
  if (stopped || context.signal?.aborted) throw problem(503, 'The local Try is stopped.');
195
- const upstream = await context.runtime.send(`/v1/try/${sessionId}/screen/${resource}`, { method: req.method === 'HEAD' ? 'GET' : req.method,
196
- ...(req.method === 'POST' ? { headers: { 'Content-Type': 'application/json' }, body } : {}) }, 90_000);
212
+ let body = rawBody;
213
+ if (req.method === 'POST' && options['--fresh'] === true) {
214
+ try {
215
+ const parsed = JSON.parse(rawBody);
216
+ if (object(parsed) && parsed.fresh === undefined) body = JSON.stringify({ ...parsed, fresh: true });
217
+ } catch { /* Preserve original body for upstream validation. */ }
218
+ }
219
+ const init = { method: req.method === 'HEAD' ? 'GET' : req.method,
220
+ ...(req.method === 'POST' ? { headers: preferWaitHeaders(WAIT_PREFER_CALL_SECONDS, { 'Content-Type': 'application/json' }), body } : {}) };
221
+ const upstream = context.programScreen && (req.method === 'POST' || resource.startsWith('api/action?'))
222
+ ? await context.programScreen(resource, init)
223
+ : await context.runtime.send(`/v1/try/${sessionId}/screen/${resource}`, init, 90_000);
197
224
  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
225
  const text = upstream.text ?? JSON.stringify(upstream.json);
199
226
  if (typeof text !== 'string' || Buffer.byteLength(text) > 16 * 1024 * 1024) throw problem(502, 'The Screen response is unavailable or too large.');
227
+ if (free && upstream.status >= 200 && upstream.status < 300) await context.persistProgram();
200
228
  res.writeHead(upstream.status, { 'content-type': upstream.headers?.get('content-type') || 'application/json; charset=utf-8',
201
229
  'content-length': Buffer.byteLength(text), 'cache-control': 'no-store', 'content-security-policy': SCREEN_CSP,
202
230
  'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff' });
@@ -219,7 +247,9 @@ export async function openServe(context, test, sessionId, options) {
219
247
  ports.stderr?.write(`${label}: running on the Try…\n`);
220
248
  const work = tail.then(async () => {
221
249
  if (stopped || context.signal?.aborted) throw problem(503, 'The local Try is stopped.');
222
- return runDoorCall({ root, originalPath:test.path, origin, login: identity.login, sessionId, callCap, prompt: selected.entry_path, operation: selected.operation }, input,
250
+ if (free) return context.callProgram(selected, input);
251
+ return runDoorCall({ root, ...(context.programEntry ? { programEntry: context.programEntry,
252
+ declaredErrors: (selected.errors ?? []).map(error => typeof error === 'string' ? error : error.code).filter(value => typeof value === 'string') } : { originalPath: test.path }), ...(options['--fresh'] === true ? { fresh: true } : {}), origin, login: identity.login, sessionId, callCap, prompt: selected.entry_path, operation: selected.operation }, input,
223
253
  { ...ports, signal: context.signal });
224
254
  });
225
255
  tail = work.catch(() => {});
@@ -239,21 +269,25 @@ export async function openServe(context, test, sessionId, options) {
239
269
  finally { if (counted) pending--; }
240
270
  });
241
271
  server.requestTimeout = 30_000; server.headersTimeout = 15_000;
242
- const wanted = Number(options['--serve'] ?? 8080);
272
+ const wanted = Number(options['--serve'] === true ? 8080 : options['--serve'] ?? 8080);
243
273
  await new Promise((done, reject) => { server.once('error', reject); server.listen(wanted, '127.0.0.1', done); }).catch(error => {
244
- if (error.code === 'EADDRINUSE') throw problem(502, `port ${wanted} is in use by another program. Stop it, or run pdd simulate ${test.story} --serve ${wanted === 65535 ? wanted - 1 : wanted + 1}.`);
245
- if (error.code === 'EACCES') throw problem(502, `port ${wanted} needs extra rights on this computer. Run pdd simulate ${test.story} --serve 8080.`);
274
+ const command = serveCommand(wanted === 65535 ? wanted - 1 : wanted + 1);
275
+ if (error.code === 'EADDRINUSE') throw problem(502, `port ${wanted} is in use by another program. Stop it, or run ${command}.`);
276
+ if (error.code === 'EACCES') throw problem(502, `port ${wanted} needs extra rights on this computer. Run ${serveCommand(8080)}.`);
246
277
  throw error;
247
278
  });
248
279
  const stop = () => { stopped = true; server.close(); server.closeIdleConnections(); server.closeAllConnections(); };
249
280
  context.signal?.addEventListener('abort', stop, { once: true });
250
281
  const port = server.address().port;
251
282
  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`);
283
+ if (routes.length) ports.stdout.write(`Example: ${requestExample(routes[0], context.simulationTests ?? (test ? [test] : []), port)}\n`);
253
284
  if (hasScreen) ports.stdout.write(`Screen: http://127.0.0.1:${port}/\n`);
254
285
  try {
255
286
  if (ports.serve) { await ports.serve(server); return 0; }
256
287
  await new Promise(done => { server.once('close', done); if (context.signal?.aborted) stop(); });
257
288
  return 0;
258
- } finally { stop(); context.signal?.removeEventListener('abort', stop); }
289
+ } finally {
290
+ stop(); context.signal?.removeEventListener('abort', stop);
291
+ if (free) { await tail; await context.persistProgram(); }
292
+ }
259
293
  }
@@ -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
+ }