@promptdriven/runtime-client 1.1.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.
@@ -0,0 +1,125 @@
1
+ // Adaptive polling schedule, Wait-Prefer headers, and Codex-style SSE stream parsing.
2
+ export const WAIT_PREFER_CALL_SECONDS = 15;
3
+ export const WAIT_PREFER_RUN_SECONDS = 25;
4
+ export const SSE_IDLE_MS = 45_000;
5
+
6
+ /**
7
+ * Adaptive polling cadence when no explicit pollMs override is injected by callers/tests:
8
+ * 250ms for the first 2000ms -> 500ms for the next 4000ms -> 1000ms cap.
9
+ */
10
+ export function adaptivePollMs(elapsedMs, explicitPollMs) {
11
+ if (explicitPollMs !== undefined) return explicitPollMs;
12
+ const elapsed = Number.isFinite(elapsedMs) && elapsedMs > 0 ? elapsedMs : 0;
13
+ if (elapsed < 2000) return 250;
14
+ if (elapsed < 6000) return 500;
15
+ return 1000;
16
+ }
17
+
18
+ export function preferWaitHeaders(seconds, extra = {}) {
19
+ const wait = Number.isFinite(seconds) && seconds > 0 ? Math.max(1, Math.min(25, Math.floor(seconds))) : 0;
20
+ return wait > 0 ? { ...extra, Prefer: `respond-async, wait=${wait}` } : { ...extra };
21
+ }
22
+
23
+ export function isSseContentType(headers) {
24
+ const raw = typeof headers?.get === 'function' ? headers.get('content-type') : headers?.['content-type'];
25
+ if (typeof raw !== 'string') return false;
26
+ return raw.split(';', 1)[0].trim().toLowerCase() === 'text/event-stream';
27
+ }
28
+
29
+ /**
30
+ * Incrementally parse an HTTP response body formatted as text/event-stream.
31
+ * Resets the idle timer on every received chunk (including `: keepalive` comments).
32
+ */
33
+ export async function parseSseStream(body, { onEvent, signal, idleMs = SSE_IDLE_MS, parseJson = JSON.parse } = {}) {
34
+ if (!body || typeof body.getReader !== 'function') {
35
+ return { completed: false, events: 0, error: new Error('SSE body is not readable.') };
36
+ }
37
+ const reader = body.getReader();
38
+ const decoder = new TextDecoder('utf-8');
39
+ let buffer = '';
40
+ let eventName = 'message';
41
+ let dataLines = [];
42
+ let events = 0;
43
+ let idleTimer = null;
44
+ let idleTimedOut = false;
45
+
46
+ const armIdle = () => {
47
+ if (idleTimer) clearTimeout(idleTimer);
48
+ if (Number.isFinite(idleMs) && idleMs > 0) {
49
+ idleTimer = setTimeout(() => {
50
+ idleTimedOut = true;
51
+ reader.cancel().catch(() => {});
52
+ }, idleMs);
53
+ }
54
+ };
55
+ const onAbort = () => { reader.cancel().catch(() => {}); };
56
+ signal?.addEventListener('abort', onAbort, { once: true });
57
+
58
+ const dispatch = () => {
59
+ if (!dataLines.length) {
60
+ eventName = 'message';
61
+ return false;
62
+ }
63
+ const raw = dataLines.join('\n');
64
+ const name = eventName || 'message';
65
+ eventName = 'message';
66
+ dataLines = [];
67
+ let json = null;
68
+ try { json = parseJson(raw); } catch { json = null; }
69
+ events++;
70
+ return onEvent?.({ event: name, data: raw, json }) === true;
71
+ };
72
+
73
+ try {
74
+ armIdle();
75
+ for (;;) {
76
+ if (signal?.aborted) break;
77
+ const { value, done } = await reader.read();
78
+ if (done) {
79
+ buffer += decoder.decode();
80
+ break;
81
+ }
82
+ armIdle();
83
+ buffer += decoder.decode(value, { stream: true });
84
+ let newlineIndex;
85
+ while ((newlineIndex = buffer.indexOf('\n')) !== -1) {
86
+ let line = buffer.slice(0, newlineIndex);
87
+ buffer = buffer.slice(newlineIndex + 1);
88
+ if (line.endsWith('\r')) line = line.slice(0, -1);
89
+ if (line === '') {
90
+ if (dispatch()) {
91
+ reader.cancel().catch(() => {});
92
+ return { completed: true, events, idleTimedOut: false };
93
+ }
94
+ continue;
95
+ }
96
+ if (line.startsWith(':')) continue; // Keepalive comment
97
+ const colon = line.indexOf(':');
98
+ const field = colon === -1 ? line : line.slice(0, colon);
99
+ let fieldValue = colon === -1 ? '' : line.slice(colon + 1);
100
+ if (fieldValue.startsWith(' ')) fieldValue = fieldValue.slice(1);
101
+ if (field === 'event') eventName = fieldValue || 'message';
102
+ else if (field === 'data') dataLines.push(fieldValue);
103
+ }
104
+ }
105
+ if (buffer.length) {
106
+ const trailing = buffer.endsWith('\r') ? buffer.slice(0, -1) : buffer;
107
+ if (trailing && !trailing.startsWith(':')) {
108
+ const colon = trailing.indexOf(':');
109
+ const field = colon === -1 ? trailing : trailing.slice(0, colon);
110
+ let fieldValue = colon === -1 ? '' : trailing.slice(colon + 1);
111
+ if (fieldValue.startsWith(' ')) fieldValue = fieldValue.slice(1);
112
+ if (field === 'event') eventName = fieldValue || 'message';
113
+ else if (field === 'data') dataLines.push(fieldValue);
114
+ }
115
+ }
116
+ if (dataLines.length) dispatch();
117
+ return { completed: !idleTimedOut && !signal?.aborted, events, idleTimedOut };
118
+ } catch (error) {
119
+ return { completed: false, events, idleTimedOut, error };
120
+ } finally {
121
+ if (idleTimer) clearTimeout(idleTimer);
122
+ signal?.removeEventListener('abort', onAbort);
123
+ try { reader.releaseLock(); } catch {}
124
+ }
125
+ }
@@ -227,6 +227,7 @@ export async function openCli(context, test, sessionId, options) {
227
227
  const usage = tryUsage(metadata);
228
228
  ports.stderr.write(`${tryUsageLine(usage)}\n`);
229
229
  const descriptor = { callCap: usage.cap, version: 1, root, sessionId, origin, login: identity.login, prompt: step.entry_path, operation: step.operation,
230
+ ...(options?.['--fresh'] === true ? { fresh: true } : {}),
230
231
  ghPath: ghPath ? resolve(ghPath) : null, promptHashes: record.prompt_hashes, effectivePromptHashes:record.effective_prompt_hashes, name, inputSchema: entry.input_schema, originalPath: test.path, storyPath: test.doc.story_path, criteria: test.doc.criteria,
231
232
  criterion: step.checks[0]?.criterion_id, storyHash: hash(readFileSync(join(root, test.doc.story_path))),
232
233
  promptHash: hash(prompt.text), stateDir: store.dir, repoState: join(store.folder('repos'), `${store.repoKey(root)}.json`) };
@@ -5,6 +5,7 @@ import {loadRuntimeWorkspace} from './runtime-workspace.mjs';
5
5
  import { checkInput,captureSource } from './runtime-preflight.mjs';
6
6
  import { cleanText, tryUsage, tryUsageHeaders, tryUsageLine } from './runtime-output.mjs';
7
7
  import { runDoorCall } from './runtime-client.mjs';
8
+ import { preferWaitHeaders, WAIT_PREFER_CALL_SECONDS } from './runtime-stream.mjs';
8
9
 
9
10
  const problem = (status, message) => Object.assign(new Error(message), { httpStatus: status });
10
11
  const shellWord = word => /^[A-Za-z0-9_./:@%+=,-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`;
@@ -205,11 +206,18 @@ export async function openServe(context, test, sessionId, options = {}) {
205
206
  if (resource) {
206
207
  if (pending >= 32 || stopped || context.signal?.aborted) throw problem(503, 'The local Try is busy or stopped.');
207
208
  pending++; counted = true;
208
- const body = await requestText(req);
209
+ const rawBody = await requestText(req);
209
210
  if (req.method === 'POST' && req.headers['content-type']?.split(';')[0] !== 'application/json') throw problem(415, 'Screen actions require application/json.');
210
211
  if (stopped || context.signal?.aborted) throw problem(503, 'The local Try is stopped.');
212
+ let body = rawBody;
213
+ if (req.method === 'POST' && options['--fresh'] === true) {
214
+ try {
215
+ const parsed = JSON.parse(rawBody);
216
+ if (object(parsed) && parsed.fresh === undefined) body = JSON.stringify({ ...parsed, fresh: true });
217
+ } catch { /* Preserve original body for upstream validation. */ }
218
+ }
211
219
  const init = { method: req.method === 'HEAD' ? 'GET' : req.method,
212
- ...(req.method === 'POST' ? { headers: { 'Content-Type': 'application/json' }, body } : {}) };
220
+ ...(req.method === 'POST' ? { headers: preferWaitHeaders(WAIT_PREFER_CALL_SECONDS, { 'Content-Type': 'application/json' }), body } : {}) };
213
221
  const upstream = context.programScreen && (req.method === 'POST' || resource.startsWith('api/action?'))
214
222
  ? await context.programScreen(resource, init)
215
223
  : await context.runtime.send(`/v1/try/${sessionId}/screen/${resource}`, init, 90_000);
@@ -241,7 +249,7 @@ export async function openServe(context, test, sessionId, options = {}) {
241
249
  if (stopped || context.signal?.aborted) throw problem(503, 'The local Try is stopped.');
242
250
  if (free) return context.callProgram(selected, input);
243
251
  return runDoorCall({ root, ...(context.programEntry ? { programEntry: context.programEntry,
244
- declaredErrors: (selected.errors ?? []).map(error => typeof error === 'string' ? error : error.code).filter(value => typeof value === 'string') } : { originalPath: test.path }), origin, login: identity.login, sessionId, callCap, prompt: selected.entry_path, operation: selected.operation }, input,
252
+ declaredErrors: (selected.errors ?? []).map(error => typeof error === 'string' ? error : error.code).filter(value => typeof value === 'string') } : { originalPath: test.path }), ...(options['--fresh'] === true ? { fresh: true } : {}), origin, login: identity.login, sessionId, callCap, prompt: selected.entry_path, operation: selected.operation }, input,
245
253
  { ...ports, signal: context.signal });
246
254
  });
247
255
  tail = work.catch(() => {});