reifyui 0.4.2 → 0.5.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.
package/README.md CHANGED
@@ -56,7 +56,8 @@ A production-grade surface for rendering and interacting with a live agent turn:
56
56
  | **Task list** | `TaskList`, `taskStatusGroup` — the master list beside a conversation: live status, filtering, cursor pagination. Transport-agnostic: you supply `fetchPage(cursor)` |
57
57
  | **Dialogs** | `DialogHost`, `useDialog` — awaited in-app `alert` / `confirm` / `prompt`, so a destructive tool call or a "name this" step never falls back to a browser popup |
58
58
  | **Slides** (`reifyui/slides`) | `SlideView`, `SlideStage`, `EditorCanvas`, `Presentation`, `ElementView`, `themeVars` — render a JSON deck, edit it by direct manipulation, present it |
59
- | **Spreadsheet** | `SheetGrid`, `sheetToDelimited`, `sheetToAoA` — an AI-editable grid |
59
+ | **Spreadsheet** | `SheetGrid`, `sheetToDelimited`, `sheetToAoA` — an AI-editable grid, extensible with your own column types |
60
+ | **HarnessRouter** (`reifyui/harness`) | `configureKit`, `kitHarness`, `listSessions`, `readFile`, `writeFile`, `createResponse`, `streamTurn`, `turnsToMessages` — the transport for apps served by a HarnessRouter console |
60
61
  | **Icons / tool meta** | `Ic*` icon set, `toolMeta`, `humanize`, `summarizeSteps` |
61
62
  | **Auth (optional)** | `configureAuth`, `login`, `AuthForm`, `GoogleButton` — a thin JWT client for products with a `/v1/auth`-style backend; wired to nothing by default |
62
63
 
@@ -186,6 +187,42 @@ belong — with the host. Pass `peers` to draw other people's selections and liv
186
187
  `onDragState` to broadcast your own. `resolveSrc` rewrites element `src` values on the way out, so
187
188
  workspace-relative image paths can point at your own file API.
188
189
 
190
+ ## Spreadsheet
191
+
192
+ `SheetGrid` renders a sheet JSON and calls back for edits. Its column vocabulary is a prop, so a
193
+ host adds a column kind without forking the component:
194
+
195
+ ```jsx
196
+ import { SheetGrid } from 'reifyui';
197
+ import 'reifyui/styles/sheet.css';
198
+
199
+ const COLUMN_TYPES = [
200
+ { type: 'text', label: 'Text' },
201
+ { type: 'number', label: 'Number' },
202
+ // `computed` means the app fills these cells: status dot, tint, run affordances.
203
+ { type: 'agent', label: 'Agent', computed: true, configKey: 'agent',
204
+ badge: (col) => col.agent?.name },
205
+ ];
206
+
207
+ <SheetGrid
208
+ sheet={sheet}
209
+ onChange={setSheet}
210
+ columnTypes={COLUMN_TYPES}
211
+ // Own a cell's body. Return undefined to fall through to the built-in rendering.
212
+ renderCell={({ column, cell, runCell }) =>
213
+ (column.type === 'agent' ? <AgentCell cell={cell} onRun={runCell} /> : undefined)}
214
+ // Own the column popover's body, below the Type select. applyPatch commits and closes.
215
+ renderColumnConfig={({ type, column, columns, applyPatch }) =>
216
+ (type === 'agent' ? <AgentConfig column={column} columns={columns} onApply={applyPatch} /> : undefined)}
217
+ />
218
+ ```
219
+
220
+ `sheetToDelimited(sheet, sep, { cellText })` and `sheetToAoA(sheet, { cellText })` export the grid;
221
+ pass `cellText` so a custom column exports as something a person wants rather than as raw JSON.
222
+
223
+ All colours come from `--uic-*` tokens — apply `styles/themes/light.css` or `dark.css`, or set the
224
+ same tokens in your own layer.
225
+
189
226
  ## Optional: auth client
190
227
 
191
228
  ReifyUI includes a small, framework-agnostic auth client for products whose backend exposes a JSON
@@ -0,0 +1,97 @@
1
+ // src/stream/responses.js
2
+ function createResponsesDispatcher(h) {
3
+ const fnByIdx = {};
4
+ const self = {
5
+ responseId: null,
6
+ dispatch(ev) {
7
+ const t = ev.type;
8
+ switch (t) {
9
+ case "response.created": {
10
+ const resp = ev.response || {};
11
+ self.responseId = resp.id || self.responseId;
12
+ if (self.responseId) h.onCreated?.(self.responseId);
13
+ const sid = resp.metadata && resp.metadata.session_id || "";
14
+ if (sid) h.onSession?.(sid);
15
+ break;
16
+ }
17
+ case "response.reasoning_summary_text.delta":
18
+ h.onReasoningDelta?.(ev.delta || "");
19
+ break;
20
+ case "response.output_item.added": {
21
+ const item = ev.item || {};
22
+ if (item.type === "function_call") {
23
+ fnByIdx[ev.output_index] = { name: item.name || "tool", callId: item.call_id || "" };
24
+ } else if (item.type === "function_call_output") {
25
+ h.onToolResult?.(item.call_id || "", String(item.output ?? ""));
26
+ }
27
+ break;
28
+ }
29
+ case "response.function_call_arguments.done": {
30
+ const fn = fnByIdx[ev.output_index] || { name: "tool", callId: "" };
31
+ h.onToolCall?.(fn.name, ev.arguments || "", fn.callId);
32
+ break;
33
+ }
34
+ case "response.output_text.delta":
35
+ h.onTextDelta?.(ev.delta || "");
36
+ break;
37
+ case "response.output_text.annotation.added": {
38
+ const a = ev.annotation || {};
39
+ if (a.type === "container_file_citation") {
40
+ h.onFile?.({ container_id: a.container_id, file_id: a.file_id, filename: a.filename });
41
+ }
42
+ break;
43
+ }
44
+ case "response.completed":
45
+ h.onDone?.("completed", ev.response);
46
+ break;
47
+ case "response.incomplete":
48
+ h.onDone?.("incomplete", ev.response);
49
+ break;
50
+ case "response.failed":
51
+ h.onDone?.(ev.response && ev.response.status || "failed", ev.response);
52
+ break;
53
+ case "error":
54
+ h.onError?.(ev.message || "stream error");
55
+ break;
56
+ default:
57
+ break;
58
+ }
59
+ }
60
+ };
61
+ return self;
62
+ }
63
+ async function readSSEStream(body, onData) {
64
+ const reader = body.getReader();
65
+ const decoder = new TextDecoder();
66
+ let buf = "";
67
+ for (; ; ) {
68
+ const { value, done } = await reader.read();
69
+ if (done) break;
70
+ buf += decoder.decode(value, { stream: true });
71
+ let nl;
72
+ while ((nl = buf.indexOf("\n\n")) !== -1) {
73
+ const frame = buf.slice(0, nl);
74
+ buf = buf.slice(nl + 2);
75
+ const data = frame.split("\n").filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trim()).join("");
76
+ if (!data) continue;
77
+ onData(data);
78
+ }
79
+ }
80
+ }
81
+ async function pumpResponsesStream(body, handlers) {
82
+ const d = createResponsesDispatcher(handlers);
83
+ await readSSEStream(body, (data) => {
84
+ try {
85
+ d.dispatch(JSON.parse(data));
86
+ } catch {
87
+ }
88
+ });
89
+ return d.responseId;
90
+ }
91
+
92
+ export {
93
+ createResponsesDispatcher,
94
+ readSSEStream,
95
+ pumpResponsesStream
96
+ };
97
+ //# sourceMappingURL=chunk-2LYV4PIX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/stream/responses.js"],"sourcesContent":["// OpenAI Responses SSE event parsing — extracted from HarnessRouter's chat client\n// (harnessrouter/src/lib/chat.ts streamResponse). Transport-agnostic: the caller does the\n// fetch/POST however it likes (BFF, broker, direct) and hands the response body (a\n// ReadableStream) plus a handlers object here.\n//\n// Two layers:\n// readSSEStream(body, onData) — raw SSE framing (blank-line separated, data: lines)\n// createResponsesDispatcher(handlers) — native Responses event -> handler dispatch\n// pumpResponsesStream(body, handlers) — both together; resolves to the response id\n//\n// Handlers (all optional):\n// onCreated(responseId) response.created\n// onSession(sessionId) response.created metadata.session_id (continuation)\n// onReasoningDelta(text) response.reasoning_summary_text.delta\n// onToolCall(name, args, callId) response.function_call_arguments.done (name + call_id\n// captured from the matching output_item.added, keyed by\n// output_index — the same pairing HR ships)\n// onToolResult(callId, output) function_call_output items\n// onTextDelta(text) response.output_text.delta\n// onFile({container_id,file_id,filename}) container_file_citation annotations\n// onDone(status, response) response.completed / .incomplete / .failed (a failed\n// response's own status distinguishes user cancels)\n// onError(message) error events\n\nexport function createResponsesDispatcher(h) {\n // function_call name + call_id live on output_item.added; arguments finalize on .done — key by\n // output_index. function_call_output (the tool result) carries the same call_id → pair them.\n const fnByIdx = {};\n const self = {\n responseId: null,\n dispatch(ev) {\n const t = ev.type;\n switch (t) {\n case 'response.created': {\n const resp = ev.response || {};\n self.responseId = resp.id || self.responseId;\n if (self.responseId) h.onCreated?.(self.responseId);\n const sid = (resp.metadata && resp.metadata.session_id) || '';\n if (sid) h.onSession?.(sid);\n break;\n }\n case 'response.reasoning_summary_text.delta':\n h.onReasoningDelta?.(ev.delta || '');\n break;\n case 'response.output_item.added': {\n const item = ev.item || {};\n if (item.type === 'function_call') {\n fnByIdx[ev.output_index] = { name: item.name || 'tool', callId: item.call_id || '' };\n } else if (item.type === 'function_call_output') {\n h.onToolResult?.(item.call_id || '', String(item.output ?? ''));\n }\n break;\n }\n case 'response.function_call_arguments.done': {\n const fn = fnByIdx[ev.output_index] || { name: 'tool', callId: '' };\n h.onToolCall?.(fn.name, ev.arguments || '', fn.callId);\n break;\n }\n case 'response.output_text.delta':\n h.onTextDelta?.(ev.delta || '');\n break;\n case 'response.output_text.annotation.added': {\n const a = ev.annotation || {};\n if (a.type === 'container_file_citation') {\n h.onFile?.({ container_id: a.container_id, file_id: a.file_id, filename: a.filename });\n }\n break;\n }\n case 'response.completed':\n h.onDone?.('completed', ev.response);\n break;\n case 'response.incomplete':\n h.onDone?.('incomplete', ev.response);\n break;\n case 'response.failed':\n // the response object's own status distinguishes a user cancel ('cancelled')\n // from a real failure — surface it so the UI can badge them differently\n h.onDone?.((ev.response && ev.response.status) || 'failed', ev.response);\n break;\n case 'error':\n h.onError?.(ev.message || 'stream error');\n break;\n default:\n break;\n }\n },\n };\n return self;\n}\n\n/** Read an SSE body stream, calling onData(dataString) per frame (data: lines joined). */\nexport async function readSSEStream(body, onData) {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buf = '';\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n buf += decoder.decode(value, { stream: true });\n let nl;\n // SSE frames are separated by a blank line; each frame has one or more `data:` lines.\n while ((nl = buf.indexOf('\\n\\n')) !== -1) {\n const frame = buf.slice(0, nl);\n buf = buf.slice(nl + 2);\n const data = frame.split('\\n').filter((l) => l.startsWith('data:')).map((l) => l.slice(5).trim()).join('');\n if (!data) continue;\n onData(data);\n }\n }\n}\n\n/**\n * Convenience: parse a Responses SSE body end-to-end, dispatching to handlers.\n * Resolves to the response id (for previous_response_id chaining), or null.\n */\nexport async function pumpResponsesStream(body, handlers) {\n const d = createResponsesDispatcher(handlers);\n await readSSEStream(body, (data) => {\n try { d.dispatch(JSON.parse(data)); } catch { /* ignore malformed frame */ }\n });\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0 +1,310 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/harness/index.js
20
+ var harness_exports = {};
21
+ __export(harness_exports, {
22
+ cancelResponse: () => cancelResponse,
23
+ cancelSession: () => cancelSession,
24
+ configureKit: () => configureKit,
25
+ containerFileUrl: () => containerFileUrl,
26
+ createResponse: () => createResponse,
27
+ deleteSession: () => deleteSession,
28
+ getResponse: () => getResponse,
29
+ hr: () => hr,
30
+ kitConfig: () => kitConfig,
31
+ kitHarness: () => kitHarness,
32
+ lastAssistantText: () => lastAssistantText,
33
+ listHarnesses: () => listHarnesses,
34
+ listSessions: () => listSessions,
35
+ patchSession: () => patchSession,
36
+ readFile: () => readFile,
37
+ readJsonFile: () => readJsonFile,
38
+ sessionDetail: () => sessionDetail,
39
+ sessionTurns: () => sessionTurns,
40
+ streamTurn: () => streamTurn,
41
+ turnsToMessages: () => turnsToMessages,
42
+ writeFile: () => writeFile
43
+ });
44
+ module.exports = __toCommonJS(harness_exports);
45
+
46
+ // src/stream/responses.js
47
+ function createResponsesDispatcher(h) {
48
+ const fnByIdx = {};
49
+ const self = {
50
+ responseId: null,
51
+ dispatch(ev) {
52
+ const t = ev.type;
53
+ switch (t) {
54
+ case "response.created": {
55
+ const resp = ev.response || {};
56
+ self.responseId = resp.id || self.responseId;
57
+ if (self.responseId) h.onCreated?.(self.responseId);
58
+ const sid = resp.metadata && resp.metadata.session_id || "";
59
+ if (sid) h.onSession?.(sid);
60
+ break;
61
+ }
62
+ case "response.reasoning_summary_text.delta":
63
+ h.onReasoningDelta?.(ev.delta || "");
64
+ break;
65
+ case "response.output_item.added": {
66
+ const item = ev.item || {};
67
+ if (item.type === "function_call") {
68
+ fnByIdx[ev.output_index] = { name: item.name || "tool", callId: item.call_id || "" };
69
+ } else if (item.type === "function_call_output") {
70
+ h.onToolResult?.(item.call_id || "", String(item.output ?? ""));
71
+ }
72
+ break;
73
+ }
74
+ case "response.function_call_arguments.done": {
75
+ const fn = fnByIdx[ev.output_index] || { name: "tool", callId: "" };
76
+ h.onToolCall?.(fn.name, ev.arguments || "", fn.callId);
77
+ break;
78
+ }
79
+ case "response.output_text.delta":
80
+ h.onTextDelta?.(ev.delta || "");
81
+ break;
82
+ case "response.output_text.annotation.added": {
83
+ const a = ev.annotation || {};
84
+ if (a.type === "container_file_citation") {
85
+ h.onFile?.({ container_id: a.container_id, file_id: a.file_id, filename: a.filename });
86
+ }
87
+ break;
88
+ }
89
+ case "response.completed":
90
+ h.onDone?.("completed", ev.response);
91
+ break;
92
+ case "response.incomplete":
93
+ h.onDone?.("incomplete", ev.response);
94
+ break;
95
+ case "response.failed":
96
+ h.onDone?.(ev.response && ev.response.status || "failed", ev.response);
97
+ break;
98
+ case "error":
99
+ h.onError?.(ev.message || "stream error");
100
+ break;
101
+ default:
102
+ break;
103
+ }
104
+ }
105
+ };
106
+ return self;
107
+ }
108
+ async function readSSEStream(body, onData) {
109
+ const reader = body.getReader();
110
+ const decoder = new TextDecoder();
111
+ let buf = "";
112
+ for (; ; ) {
113
+ const { value, done } = await reader.read();
114
+ if (done) break;
115
+ buf += decoder.decode(value, { stream: true });
116
+ let nl;
117
+ while ((nl = buf.indexOf("\n\n")) !== -1) {
118
+ const frame = buf.slice(0, nl);
119
+ buf = buf.slice(nl + 2);
120
+ const data = frame.split("\n").filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trim()).join("");
121
+ if (!data) continue;
122
+ onData(data);
123
+ }
124
+ }
125
+ }
126
+
127
+ // src/harness/index.js
128
+ var CONFIG = { kitId: "", base: "/api/harness/v1" };
129
+ function configureKit({ kitId, base } = {}) {
130
+ CONFIG = { kitId: kitId || CONFIG.kitId, base: base || CONFIG.base };
131
+ _harness = null;
132
+ return CONFIG;
133
+ }
134
+ function kitConfig() {
135
+ return { ...CONFIG };
136
+ }
137
+ async function readError(res) {
138
+ try {
139
+ const body = await res.json();
140
+ const d = body?.error?.message ?? body?.detail;
141
+ return typeof d === "string" ? d : `request failed (${res.status})`;
142
+ } catch {
143
+ return `request failed (${res.status})`;
144
+ }
145
+ }
146
+ async function hr(path, init = {}) {
147
+ const res = await fetch(`${CONFIG.base}${path}`, { cache: "no-store", ...init });
148
+ if (!res.ok) {
149
+ const err = new Error(await readError(res));
150
+ err.status = res.status;
151
+ throw err;
152
+ }
153
+ return res.status === 204 ? null : res.json();
154
+ }
155
+ function jsonInit(method, body, headers) {
156
+ return {
157
+ method,
158
+ headers: { "content-type": "application/json", ...headers || {} },
159
+ body: JSON.stringify(body)
160
+ };
161
+ }
162
+ async function listHarnesses() {
163
+ const { harnesses = [] } = await hr("/harnesses");
164
+ return harnesses;
165
+ }
166
+ var _harness = null;
167
+ async function kitHarness() {
168
+ if (_harness) return _harness;
169
+ const harnesses = await listHarnesses();
170
+ _harness = harnesses.find((h) => h.kit === CONFIG.kitId) || null;
171
+ return _harness;
172
+ }
173
+ async function listSessions({ limit = 100 } = {}) {
174
+ const h = await kitHarness();
175
+ if (!h) return { sessions: [], cursor: null };
176
+ const body = await hr(`/sessions?harness=${encodeURIComponent(h.id)}&limit=${limit}`);
177
+ return { sessions: body?.sessions ?? body?.data ?? [], cursor: body?.cursor ?? null };
178
+ }
179
+ function sessionDetail(sid) {
180
+ return hr(`/sessions/${encodeURIComponent(sid)}`);
181
+ }
182
+ function patchSession(sid, { title }) {
183
+ return hr(`/sessions/${encodeURIComponent(sid)}`, jsonInit("PATCH", { title }));
184
+ }
185
+ function deleteSession(sid) {
186
+ return hr(`/traces/${encodeURIComponent(sid)}`, { method: "DELETE" });
187
+ }
188
+ async function readFile(sid, path) {
189
+ const r = await fetch(
190
+ `${CONFIG.base}/sessions/${encodeURIComponent(sid)}/files/${path}`,
191
+ { cache: "no-store" }
192
+ );
193
+ if (!r.ok) return null;
194
+ return r.text();
195
+ }
196
+ async function readJsonFile(sid, path) {
197
+ const text = await readFile(sid, path);
198
+ if (text == null) return null;
199
+ try {
200
+ return JSON.parse(text);
201
+ } catch {
202
+ return null;
203
+ }
204
+ }
205
+ function writeFile(sid, path, content) {
206
+ return hr(`/sessions/${encodeURIComponent(sid)}/files/${path}`, jsonInit("PUT", { content }));
207
+ }
208
+ function containerFileUrl(containerId, fileId) {
209
+ return `${CONFIG.base}/containers/${encodeURIComponent(containerId)}/files/${encodeURIComponent(fileId)}/content`;
210
+ }
211
+ async function sessionTurns(sid, { limit } = {}) {
212
+ const q = limit ? `?limit=${limit}` : "";
213
+ const body = await hr(`/sessions/${encodeURIComponent(sid)}/turns${q}`).catch(() => null);
214
+ return body?.turns ?? [];
215
+ }
216
+ function getResponse(rid) {
217
+ return hr(`/responses/${encodeURIComponent(rid)}`);
218
+ }
219
+ function createResponse(body, { idempotencyKey, stream } = {}) {
220
+ const headers = {};
221
+ if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
222
+ if (stream) headers.accept = "text/event-stream";
223
+ return hr("/responses", jsonInit("POST", body, headers));
224
+ }
225
+ function cancelResponse(rid) {
226
+ return hr(`/responses/${encodeURIComponent(rid)}/cancel`, { method: "POST" });
227
+ }
228
+ function cancelSession(sid) {
229
+ return hr(`/sessions/${encodeURIComponent(sid)}/cancel`, { method: "POST" });
230
+ }
231
+ function sessionIdOf(evt) {
232
+ return evt?.metadata?.session_id || evt?.response?.metadata?.session_id || evt?.session_id || evt?.response?.session_id || null;
233
+ }
234
+ async function streamTurn({ sessionId, harnessId, input, instructions, handlers = {} }) {
235
+ let hid = harnessId;
236
+ if (!hid) {
237
+ const h = await kitHarness();
238
+ if (!h) throw new Error("This kit has not been launched yet.");
239
+ hid = h.id;
240
+ }
241
+ const existing = sessionId ? String(sessionId) : "";
242
+ const res = await fetch(`${CONFIG.base}/responses`, {
243
+ method: "POST",
244
+ cache: "no-store",
245
+ headers: { "content-type": "application/json", accept: "text/event-stream" },
246
+ body: JSON.stringify({
247
+ input,
248
+ ...instructions ? { instructions } : {},
249
+ metadata: { harness_id: hid, ...existing ? { session_id: existing } : {} },
250
+ stream: true
251
+ })
252
+ });
253
+ if (res.status === 503) return { connecting: true };
254
+ if (!res.ok || !res.body) {
255
+ const t = await res.text().catch(() => "");
256
+ throw new Error(`turn failed: ${res.status} ${t.slice(0, 160)}`);
257
+ }
258
+ let sawError = false;
259
+ let sid = existing;
260
+ const d = createResponsesDispatcher({
261
+ ...handlers,
262
+ onError: (msg) => {
263
+ sawError = true;
264
+ handlers.onError?.(msg);
265
+ }
266
+ });
267
+ await readSSEStream(res.body, (data) => {
268
+ let evt;
269
+ try {
270
+ evt = JSON.parse(data);
271
+ } catch {
272
+ return;
273
+ }
274
+ const found = sessionIdOf(evt);
275
+ if (found && found !== sid) {
276
+ sid = found;
277
+ handlers.onSession?.(found);
278
+ }
279
+ d.dispatch(evt);
280
+ });
281
+ return { ok: !sawError, sessionId: sid };
282
+ }
283
+ var TURN_STATUS = {
284
+ failed: "failed",
285
+ error: "failed",
286
+ cancelled: "cancelled",
287
+ incomplete: "incomplete",
288
+ max_turns: "incomplete",
289
+ timeout: "incomplete"
290
+ };
291
+ function turnsToMessages(turns) {
292
+ const out = [];
293
+ for (const t of turns || []) {
294
+ if (t.user) out.push({ role: "user", text: t.user });
295
+ const steps = (t.tools || []).map((x) => ({ name: x.name, args: x.arguments, result: x.result }));
296
+ const blocks = [];
297
+ if (steps.length) blocks.push({ kind: "tools", reasoning: "", steps });
298
+ if (t.assistant) blocks.push({ kind: "text", text: t.assistant });
299
+ const status = TURN_STATUS[t.status] || "done";
300
+ if (blocks.length || status !== "done") out.push({ role: "assistant", blocks, status });
301
+ }
302
+ return out;
303
+ }
304
+ function lastAssistantText(turns) {
305
+ for (let i = (turns || []).length - 1; i >= 0; i--) {
306
+ if (turns[i]?.assistant) return String(turns[i].assistant);
307
+ }
308
+ return "";
309
+ }
310
+ //# sourceMappingURL=harness.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/harness/index.js","../src/stream/responses.js"],"sourcesContent":["// The HarnessRouter transport, for apps served by the HarnessRouter console.\n//\n// A \"kit\" is a single-page app the console serves at /kits/<id>, same-origin with its API proxy.\n// That origin is the whole authentication story: the console already signed the person in, the\n// browser carries that session on every request, and the proxy attaches the internal key\n// server-side. There is no token here, no login screen, and nothing to refresh.\n//\n// The model these functions speak:\n//\n// a document = a session on the kit's Harness (the session list IS the document list)\n// its content = a file in that session's workspace\n// talking to it= POST /responses with that session id\n//\n// Every route below is one the gateway actually implements. Keeping them in one file is the\n// point: the first kit shipped five separate bugs that were all the same bug — a call carried\n// over from a hosted product to an endpoint that does not exist here. A second kit copying this\n// file would inherit the next five. Functions only, no hooks: a hook encodes page structure, and\n// that genuinely differs per kit.\nimport { createResponsesDispatcher, readSSEStream } from '../stream/responses.js';\n\nlet CONFIG = { kitId: '', base: '/api/harness/v1' };\n\n/** Call once at boot. kitId is what /v1/harnesses reports in `kit` for the harness this kit launched. */\nexport function configureKit({ kitId, base } = {}) {\n CONFIG = { kitId: kitId || CONFIG.kitId, base: base || CONFIG.base };\n _harness = null;\n return CONFIG;\n}\n\nexport function kitConfig() { return { ...CONFIG }; }\n\nasync function readError(res) {\n try {\n const body = await res.json();\n const d = body?.error?.message ?? body?.detail;\n return typeof d === 'string' ? d : `request failed (${res.status})`;\n } catch {\n return `request failed (${res.status})`;\n }\n}\n\n/** One request. Throws an Error carrying `.status` so callers can branch on 409 / 404. */\nexport async function hr(path, init = {}) {\n const res = await fetch(`${CONFIG.base}${path}`, { cache: 'no-store', ...init });\n if (!res.ok) {\n const err = new Error(await readError(res));\n err.status = res.status;\n throw err;\n }\n return res.status === 204 ? null : res.json();\n}\n\nfunction jsonInit(method, body, headers) {\n return {\n method,\n headers: { 'content-type': 'application/json', ...(headers || {}) },\n body: JSON.stringify(body),\n };\n}\n\n// ── harnesses ──────────────────────────────────────────────────────────────\nexport async function listHarnesses() {\n const { harnesses = [] } = await hr('/harnesses');\n return harnesses;\n}\n\nlet _harness = null;\n\n/** The Harness this kit launched, or null when the kit was never launched.\n *\n * Null is a real answer and callers must render it. Swallowing it into an empty list shows an\n * empty \"no documents yet\" screen to someone whose actual problem is that nothing is running. */\nexport async function kitHarness() {\n if (_harness) return _harness;\n const harnesses = await listHarnesses();\n _harness = harnesses.find((h) => h.kit === CONFIG.kitId) || null;\n return _harness;\n}\n\n// ── sessions (= documents) ─────────────────────────────────────────────────\n/** The kit's documents, newest first. The filter is `harness` — an unknown query param is\n * ignored rather than refused, so the wrong name silently returns every session in the org. */\nexport async function listSessions({ limit = 100 } = {}) {\n const h = await kitHarness();\n if (!h) return { sessions: [], cursor: null };\n const body = await hr(`/sessions?harness=${encodeURIComponent(h.id)}&limit=${limit}`);\n return { sessions: body?.sessions ?? body?.data ?? [], cursor: body?.cursor ?? null };\n}\n\nexport function sessionDetail(sid) {\n return hr(`/sessions/${encodeURIComponent(sid)}`);\n}\n\n/** Rename. This also rewrites the trace manifest the session LIST renders from, and marks the\n * title as chosen so the next turn stops regenerating it from the latest user message. */\nexport function patchSession(sid, { title }) {\n return hr(`/sessions/${encodeURIComponent(sid)}`, jsonInit('PATCH', { title }));\n}\n\n/** Delete a document and the conversation underneath it. The route is /traces/{id}: there is no\n * DELETE on the session path, and this one removes the trace, the durable workspace tarball and\n * tombstones the session. */\nexport function deleteSession(sid) {\n return hr(`/traces/${encodeURIComponent(sid)}`, { method: 'DELETE' });\n}\n\n// ── workspace files ────────────────────────────────────────────────────────\n/** Read one file by path, from the LIVE workspace — so a file appears the moment the agent\n * writes it, mid-turn. Returns null when it does not exist yet.\n *\n * Do not reach for the file LISTING to detect a file: that answers from the end-of-turn\n * checkpoint tarball and shows a spinner over a file already on disk. */\nexport async function readFile(sid, path) {\n const r = await fetch(`${CONFIG.base}/sessions/${encodeURIComponent(sid)}/files/${path}`,\n { cache: 'no-store' });\n if (!r.ok) return null;\n return r.text();\n}\n\nexport async function readJsonFile(sid, path) {\n const text = await readFile(sid, path);\n if (text == null) return null;\n try { return JSON.parse(text); } catch { return null; }\n}\n\n/** Write a workspace file. Refused 409 `session_busy` while that session has a turn running —\n * the agent owns its workspace until it finishes. Blocking is honest; both sides silently\n * racing is not. Callers must re-arm rather than drop the write. */\nexport function writeFile(sid, path, content) {\n return hr(`/sessions/${encodeURIComponent(sid)}/files/${path}`, jsonInit('PUT', { content }));\n}\n\n/** A URL that serves one artifact's bytes. Same-origin, so it works in <img src> directly. */\nexport function containerFileUrl(containerId, fileId) {\n return `${CONFIG.base}/containers/${encodeURIComponent(containerId)}`\n + `/files/${encodeURIComponent(fileId)}/content`;\n}\n\n// ── turns and responses ────────────────────────────────────────────────────\n/** The conversation so far, oldest first. Replays from the trace WHILE a turn is in flight, so\n * it is also how a reopened tab watches a running turn without a stream. */\nexport async function sessionTurns(sid, { limit } = {}) {\n const q = limit ? `?limit=${limit}` : '';\n const body = await hr(`/sessions/${encodeURIComponent(sid)}/turns${q}`).catch(() => null);\n return body?.turns ?? [];\n}\n\nexport function getResponse(rid) {\n return hr(`/responses/${encodeURIComponent(rid)}`);\n}\n\n/** Start a turn.\n *\n * idempotencyKey is not optional decoration for a background dispatch: without it a retry after\n * a flaky reply starts a SECOND turn on a session that may already be running one, and two\n * concurrent turns on one session destroy that session's workspace (each turn wipes and\n * restores it, so the last writer wins with an empty tree). With the key, a duplicate replays\n * the first response instead of running again. */\nexport function createResponse(body, { idempotencyKey, stream } = {}) {\n const headers = {};\n if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey;\n if (stream) headers.accept = 'text/event-stream';\n return hr('/responses', jsonInit('POST', body, headers));\n}\n\n/** Cancel one turn. Preferred over cancelling the session: it only kills the sandbox when it can\n * prove this response owns the live turn, and otherwise lets the turn self-terminate. */\nexport function cancelResponse(rid) {\n return hr(`/responses/${encodeURIComponent(rid)}/cancel`, { method: 'POST' });\n}\n\nexport function cancelSession(sid) {\n return hr(`/sessions/${encodeURIComponent(sid)}/cancel`, { method: 'POST' });\n}\n\n// ── streaming one turn ─────────────────────────────────────────────────────\n/** Pull a session id out of whatever frame carries it, without caring which one that is. */\nfunction sessionIdOf(evt) {\n return evt?.metadata?.session_id || evt?.response?.metadata?.session_id\n || evt?.session_id || evt?.response?.session_id || null;\n}\n\n/** Run one streaming turn against the kit's own harness.\n *\n * `sessionId` may be empty for a brand-new document: nothing but a turn creates a session, so\n * the id arrives in the stream and is reported through onSession before the frame is dispatched.\n *\n * Framing belongs in `instructions`, never in `input`. The gateway captures the user text before\n * it prepends instructions, so the transcript, the console task list and the trace all show the\n * person's own sentence instead of our scaffolding.\n *\n * handlers: the ReifyUI dispatcher's (onTextDelta, onReasoningDelta, onToolCall, onToolResult,\n * onDone, onError) plus onSession(sessionId).\n *\n * Returns {ok, sessionId}, or {connecting:true} when the gateway is still coming up (503).\n */\nexport async function streamTurn({ sessionId, harnessId, input, instructions, handlers = {} }) {\n let hid = harnessId;\n if (!hid) {\n const h = await kitHarness();\n if (!h) throw new Error('This kit has not been launched yet.');\n hid = h.id;\n }\n const existing = sessionId ? String(sessionId) : '';\n const res = await fetch(`${CONFIG.base}/responses`, {\n method: 'POST',\n cache: 'no-store',\n headers: { 'content-type': 'application/json', accept: 'text/event-stream' },\n body: JSON.stringify({\n input,\n ...(instructions ? { instructions } : {}),\n metadata: { harness_id: hid, ...(existing ? { session_id: existing } : {}) },\n stream: true,\n }),\n });\n if (res.status === 503) return { connecting: true };\n if (!res.ok || !res.body) {\n const t = await res.text().catch(() => '');\n throw new Error(`turn failed: ${res.status} ${t.slice(0, 160)}`);\n }\n\n let sawError = false;\n let sid = existing;\n const d = createResponsesDispatcher({\n ...handlers,\n onError: (msg) => { sawError = true; handlers.onError?.(msg); },\n });\n await readSSEStream(res.body, (data) => {\n let evt;\n try { evt = JSON.parse(data); } catch { return; } // malformed frame\n const found = sessionIdOf(evt);\n if (found && found !== sid) { sid = found; handlers.onSession?.(found); }\n d.dispatch(evt);\n });\n return { ok: !sawError, sessionId: sid };\n}\n\n// ── replaying history ──────────────────────────────────────────────────────\nconst TURN_STATUS = {\n failed: 'failed', error: 'failed', cancelled: 'cancelled',\n incomplete: 'incomplete', max_turns: 'incomplete', timeout: 'incomplete',\n};\n\n/** Gateway turns -> ChatMessages' message shape. */\nexport function turnsToMessages(turns) {\n const out = [];\n for (const t of turns || []) {\n if (t.user) out.push({ role: 'user', text: t.user });\n const steps = (t.tools || []).map((x) => ({ name: x.name, args: x.arguments, result: x.result }));\n const blocks = [];\n if (steps.length) blocks.push({ kind: 'tools', reasoning: '', steps });\n if (t.assistant) blocks.push({ kind: 'text', text: t.assistant });\n const status = TURN_STATUS[t.status] || 'done';\n if (blocks.length || status !== 'done') out.push({ role: 'assistant', blocks, status });\n }\n return out;\n}\n\n/** The assistant text of a session's last turn — what a document page shows when there is no\n * document yet and the agent has stopped. The real explanation is usually in there. */\nexport function lastAssistantText(turns) {\n for (let i = (turns || []).length - 1; i >= 0; i--) {\n if (turns[i]?.assistant) return String(turns[i].assistant);\n }\n return '';\n}\n","// OpenAI Responses SSE event parsing — extracted from HarnessRouter's chat client\n// (harnessrouter/src/lib/chat.ts streamResponse). Transport-agnostic: the caller does the\n// fetch/POST however it likes (BFF, broker, direct) and hands the response body (a\n// ReadableStream) plus a handlers object here.\n//\n// Two layers:\n// readSSEStream(body, onData) — raw SSE framing (blank-line separated, data: lines)\n// createResponsesDispatcher(handlers) — native Responses event -> handler dispatch\n// pumpResponsesStream(body, handlers) — both together; resolves to the response id\n//\n// Handlers (all optional):\n// onCreated(responseId) response.created\n// onSession(sessionId) response.created metadata.session_id (continuation)\n// onReasoningDelta(text) response.reasoning_summary_text.delta\n// onToolCall(name, args, callId) response.function_call_arguments.done (name + call_id\n// captured from the matching output_item.added, keyed by\n// output_index — the same pairing HR ships)\n// onToolResult(callId, output) function_call_output items\n// onTextDelta(text) response.output_text.delta\n// onFile({container_id,file_id,filename}) container_file_citation annotations\n// onDone(status, response) response.completed / .incomplete / .failed (a failed\n// response's own status distinguishes user cancels)\n// onError(message) error events\n\nexport function createResponsesDispatcher(h) {\n // function_call name + call_id live on output_item.added; arguments finalize on .done — key by\n // output_index. function_call_output (the tool result) carries the same call_id → pair them.\n const fnByIdx = {};\n const self = {\n responseId: null,\n dispatch(ev) {\n const t = ev.type;\n switch (t) {\n case 'response.created': {\n const resp = ev.response || {};\n self.responseId = resp.id || self.responseId;\n if (self.responseId) h.onCreated?.(self.responseId);\n const sid = (resp.metadata && resp.metadata.session_id) || '';\n if (sid) h.onSession?.(sid);\n break;\n }\n case 'response.reasoning_summary_text.delta':\n h.onReasoningDelta?.(ev.delta || '');\n break;\n case 'response.output_item.added': {\n const item = ev.item || {};\n if (item.type === 'function_call') {\n fnByIdx[ev.output_index] = { name: item.name || 'tool', callId: item.call_id || '' };\n } else if (item.type === 'function_call_output') {\n h.onToolResult?.(item.call_id || '', String(item.output ?? ''));\n }\n break;\n }\n case 'response.function_call_arguments.done': {\n const fn = fnByIdx[ev.output_index] || { name: 'tool', callId: '' };\n h.onToolCall?.(fn.name, ev.arguments || '', fn.callId);\n break;\n }\n case 'response.output_text.delta':\n h.onTextDelta?.(ev.delta || '');\n break;\n case 'response.output_text.annotation.added': {\n const a = ev.annotation || {};\n if (a.type === 'container_file_citation') {\n h.onFile?.({ container_id: a.container_id, file_id: a.file_id, filename: a.filename });\n }\n break;\n }\n case 'response.completed':\n h.onDone?.('completed', ev.response);\n break;\n case 'response.incomplete':\n h.onDone?.('incomplete', ev.response);\n break;\n case 'response.failed':\n // the response object's own status distinguishes a user cancel ('cancelled')\n // from a real failure — surface it so the UI can badge them differently\n h.onDone?.((ev.response && ev.response.status) || 'failed', ev.response);\n break;\n case 'error':\n h.onError?.(ev.message || 'stream error');\n break;\n default:\n break;\n }\n },\n };\n return self;\n}\n\n/** Read an SSE body stream, calling onData(dataString) per frame (data: lines joined). */\nexport async function readSSEStream(body, onData) {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buf = '';\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n buf += decoder.decode(value, { stream: true });\n let nl;\n // SSE frames are separated by a blank line; each frame has one or more `data:` lines.\n while ((nl = buf.indexOf('\\n\\n')) !== -1) {\n const frame = buf.slice(0, nl);\n buf = buf.slice(nl + 2);\n const data = frame.split('\\n').filter((l) => l.startsWith('data:')).map((l) => l.slice(5).trim()).join('');\n if (!data) continue;\n onData(data);\n }\n }\n}\n\n/**\n * Convenience: parse a Responses SSE body end-to-end, dispatching to handlers.\n * Resolves to the response id (for previous_response_id chaining), or null.\n */\nexport async function pumpResponsesStream(body, handlers) {\n const d = createResponsesDispatcher(handlers);\n await readSSEStream(body, (data) => {\n try { d.dispatch(JSON.parse(data)); } catch { /* ignore malformed frame */ }\n });\n return d.responseId;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACwBO,SAAS,0BAA0B,GAAG;AAG3C,QAAM,UAAU,CAAC;AACjB,QAAM,OAAO;AAAA,IACX,YAAY;AAAA,IACZ,SAAS,IAAI;AACX,YAAM,IAAI,GAAG;AACb,cAAQ,GAAG;AAAA,QACT,KAAK,oBAAoB;AACvB,gBAAM,OAAO,GAAG,YAAY,CAAC;AAC7B,eAAK,aAAa,KAAK,MAAM,KAAK;AAClC,cAAI,KAA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E,UAAW,QAAO,KAAK,EAAE,MAAM,QAAQ,MAAM,EAAE,UAAU,CAAC;AAChE,UAAM,SAAS,YAAY,EAAE,MAAM,KAAK;AACxC,QAAI,OAAO,UAAU,WAAW,OAAQ,KAAI,KAAK,EAAE,MAAM,aAAa,QAAQ,OAAO,CAAC;AAAA,EACxF;AACA,SAAO;AACT;AAIO,SAAS,kBAAkB,OAAO;AACvC,WAAS,KAAK,SAAS,CAAC,GAAG,SAAS,GAAG,KAAK,GAAG,KAAK;AAClD,QAAI,MAAM,CAAC,GAAG,UAAW,QAAO,OAAO,MAAM,CAAC,EAAE,SAAS;AAAA,EAC3D;AACA,SAAO;AACT;","names":[]}
@@ -0,0 +1,88 @@
1
+ // reifyui/harness — the HarnessRouter transport for apps served by the HarnessRouter console.
2
+ //
3
+ // Hand-authored, like the rest of this package's types: the implementation is plain ESM.
4
+ import type { ResponseHandlers } from '../index';
5
+
6
+ export interface KitConfig {
7
+ /** What GET /v1/harnesses reports in `kit` for the harness this kit launched. */
8
+ kitId: string;
9
+ /** The console's API proxy. Same-origin, so the console session authenticates every call. */
10
+ base: string;
11
+ }
12
+ export function configureKit(config: Partial<KitConfig>): KitConfig;
13
+ export function kitConfig(): KitConfig;
14
+
15
+ /** An Error from `hr` carries the HTTP status, so callers can branch on 409 / 404. */
16
+ export interface HarnessError extends Error { status?: number }
17
+ export function hr(path: string, init?: RequestInit): Promise<any>;
18
+
19
+ export interface Harness {
20
+ id: string;
21
+ name: string;
22
+ base?: string;
23
+ defaultModel?: string;
24
+ /** The starter kit that launched this harness, or null for a hand-made one. */
25
+ kit?: string | null;
26
+ additionalHeaders?: Record<string, string>;
27
+ [key: string]: unknown;
28
+ }
29
+ export function listHarnesses(): Promise<Harness[]>;
30
+ /** Null when the kit was never launched — a real answer the caller must render. */
31
+ export function kitHarness(): Promise<Harness | null>;
32
+
33
+ export interface Session {
34
+ id: string;
35
+ title?: string;
36
+ status?: string;
37
+ turn_status?: string;
38
+ created_at?: string | number;
39
+ updated_at?: string | number;
40
+ [key: string]: unknown;
41
+ }
42
+ export function listSessions(opts?: { limit?: number }): Promise<{ sessions: Session[]; cursor: string | null }>;
43
+ export function sessionDetail(sid: string): Promise<Session>;
44
+ export function patchSession(sid: string, patch: { title: string }): Promise<unknown>;
45
+ export function deleteSession(sid: string): Promise<unknown>;
46
+
47
+ /** Reads the LIVE workspace, so a file appears the moment the agent writes it. Null if absent. */
48
+ export function readFile(sid: string, path: string): Promise<string | null>;
49
+ export function readJsonFile<T = unknown>(sid: string, path: string): Promise<T | null>;
50
+ /** Refused 409 `session_busy` while that session has a turn running. Re-arm; never drop. */
51
+ export function writeFile(sid: string, path: string, content: string): Promise<unknown>;
52
+ export function containerFileUrl(containerId: string, fileId: string): string;
53
+
54
+ export interface Turn {
55
+ user?: string;
56
+ assistant?: string;
57
+ status?: string;
58
+ tools?: Array<{ name: string; arguments?: unknown; result?: unknown }>;
59
+ [key: string]: unknown;
60
+ }
61
+ export function sessionTurns(sid: string, opts?: { limit?: number }): Promise<Turn[]>;
62
+ export function getResponse(rid: string): Promise<any>;
63
+ export function createResponse(
64
+ body: Record<string, unknown>,
65
+ opts?: { idempotencyKey?: string; stream?: boolean },
66
+ ): Promise<any>;
67
+ export function cancelResponse(rid: string): Promise<unknown>;
68
+ export function cancelSession(sid: string): Promise<unknown>;
69
+
70
+ /** ResponseHandlers already carries onSession — a brand-new document learns its own id there. */
71
+ export type StreamTurnHandlers = ResponseHandlers;
72
+ export function streamTurn(args: {
73
+ sessionId?: string;
74
+ harnessId?: string;
75
+ input: unknown;
76
+ /** Framing goes here, never in `input`: the transcript must show the person's own words. */
77
+ instructions?: string;
78
+ handlers?: StreamTurnHandlers;
79
+ }): Promise<{ ok?: boolean; sessionId?: string; connecting?: boolean }>;
80
+
81
+ export interface ChatMessage {
82
+ role: 'user' | 'assistant';
83
+ text?: string;
84
+ blocks?: Array<Record<string, unknown>>;
85
+ status?: string;
86
+ }
87
+ export function turnsToMessages(turns: Turn[]): ChatMessage[];
88
+ export function lastAssistantText(turns: Turn[]): string;