reifyui 0.5.1 → 0.6.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 (43) hide show
  1. package/README.md +40 -3
  2. package/dist/{chunk-2LYV4PIX.js → chunk-NTIWFHR4.js} +26 -2
  3. package/dist/chunk-NTIWFHR4.js.map +1 -0
  4. package/dist/harness.cjs +72 -21
  5. package/dist/harness.cjs.map +1 -1
  6. package/dist/harness.d.ts +23 -0
  7. package/dist/harness.js +52 -23
  8. package/dist/harness.js.map +1 -1
  9. package/dist/index.cjs +1125 -296
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.ts +260 -1
  12. package/dist/index.js +1100 -293
  13. package/dist/index.js.map +1 -1
  14. package/package.json +1 -1
  15. package/src/components/Card.jsx +49 -0
  16. package/src/components/Carousel.jsx +73 -0
  17. package/src/components/ChatPanel.jsx +461 -0
  18. package/src/components/Chip.jsx +61 -0
  19. package/src/components/Composer.jsx +20 -1
  20. package/src/components/Dialog.jsx +5 -10
  21. package/src/components/Modal.jsx +75 -0
  22. package/src/components/Popover.jsx +86 -0
  23. package/src/components/SearchField.jsx +30 -0
  24. package/src/components/icons.jsx +9 -0
  25. package/src/components/overlay.js +63 -0
  26. package/src/format.js +10 -0
  27. package/src/harness/attach.js +63 -0
  28. package/src/harness/index.d.ts +23 -0
  29. package/src/harness/index.js +6 -18
  30. package/src/hooks/useTypewriter.js +53 -0
  31. package/src/index.d.ts +260 -1
  32. package/src/index.js +27 -1
  33. package/src/input/dictate.js +60 -0
  34. package/src/state/turns.js +30 -0
  35. package/styles/chat.css +127 -1
  36. package/styles/chip.css +53 -0
  37. package/styles/dialog.css +42 -37
  38. package/styles/library.css +205 -0
  39. package/styles/preview.css +73 -0
  40. package/styles/sheet.css +16 -14
  41. package/styles/themes/dark.css +20 -0
  42. package/styles/themes/light.css +23 -0
  43. package/dist/chunk-2LYV4PIX.js.map +0 -1
package/README.md CHANGED
@@ -52,12 +52,14 @@ A production-grade surface for rendering and interacting with a live agent turn:
52
52
  | **Streaming** | `pumpResponsesStream`, `createResponsesDispatcher`, `readSSEStream` — parse the Responses SSE event shape into ordered blocks |
53
53
  | **Block state** | `withText`, `withReasoning`, `withStep`, `withResult`, `asstText`, `createConversationStore` — session-continuation state machine |
54
54
  | **Chat surface** | `ChatMessages`, `UserTurn`, `AssistantTurn`, `ToolGroup`, `ToolRow`, `Composer` — message list + a collapsible "ran 5 commands, wrote a file" tool-step timeline |
55
+ | **Chat panel** | `ChatPanel` — the whole conversation column beside a document: history replay, the live turn, connecting-and-retry, attachments, dictation, composer. You supply `runTurn` and `loadHistory`; it owns everything else. `turnsToMessages`, `createDictation`, `bytesLabel` |
56
+ | **Library page** | `Carousel`, `Card`, `Chip`, `SearchField`, `Popover`, `Modal`, `useTypewriter` — the surface a document product opens on: a prompt box, a strip of templates, the things you already made |
55
57
  | **Rich blocks** | `CodeBlock` (highlight.js + mermaid + charts), `useResizablePane`, `PaneResizer` |
56
58
  | **Task list** | `TaskList`, `taskStatusGroup` — the master list beside a conversation: live status, filtering, cursor pagination. Transport-agnostic: you supply `fetchPage(cursor)` |
57
59
  | **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
60
  | **Slides** (`reifyui/slides`) | `SlideView`, `SlideStage`, `EditorCanvas`, `Presentation`, `ElementView`, `themeVars` — render a JSON deck, edit it by direct manipulation, present it |
59
61
  | **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 |
62
+ | **HarnessRouter** (`reifyui/harness`) | `configureKit`, `kitHarness`, `listSessions`, `readFile`, `writeFile`, `createResponse`, `streamTurn`, `turnsToMessages`, `fileToInputBlock` — the transport for apps served by a HarnessRouter console |
61
63
  | **Icons / tool meta** | `Ic*` icon set, `toolMeta`, `humanize`, `summarizeSteps` |
62
64
  | **Auth (optional)** | `configureAuth`, `login`, `AuthForm`, `GoogleButton` — a thin JWT client for products with a `/v1/auth`-style backend; wired to nothing by default |
63
65
 
@@ -140,9 +142,12 @@ import a feature, it adds nothing to your bundle.
140
142
  CSS ships as plain files you import where you want them — nothing is injected for you:
141
143
 
142
144
  ```js
143
- import 'reifyui/styles/chat.css'; // chat surface + tool steps + composer
145
+ import 'reifyui/styles/chat.css'; // chat surface + tool steps + composer + ChatPanel
144
146
  import 'reifyui/styles/themes/light.css'; // light theme variables
145
147
  import 'reifyui/styles/themes/dark.css'; // dark theme variables
148
+ import 'reifyui/styles/library.css'; // shell, hero, prompt box, carousel, card, table
149
+ import 'reifyui/styles/chip.css'; // Chip + Popover
150
+ import 'reifyui/styles/preview.css'; // Modal
146
151
  import 'reifyui/styles/slides.css'; // slides
147
152
  import 'reifyui/styles/sheet.css'; // spreadsheet grid
148
153
  import 'reifyui/styles/tasks.css'; // task list
@@ -150,7 +155,39 @@ import 'reifyui/styles/dialog.css'; // alert / confirm / prompt dialogs
150
155
  ```
151
156
 
152
157
  Themes are CSS-variable files — load one, or switch at runtime by toggling which you apply. Override
153
- the variables to match your design system.
158
+ the variables to match your design system. Every stylesheet reads the same `--uic-*` set, dialogs
159
+ included, so setting `--uic-brand` once moves the conversation, the grid, the focus glow and the
160
+ dialog buttons together.
161
+
162
+ ## Chat panel
163
+
164
+ `ChatMessages` renders a conversation. `ChatPanel` is the whole column around it — the part every
165
+ product rebuilds and every rebuild gets slightly wrong. It owns the conversation's state machine;
166
+ you own the transport and the words.
167
+
168
+ ```jsx
169
+ import { ChatPanel, createDictation, turnsToMessages } from 'reifyui';
170
+ import { sessionTurns, fileToInputBlock } from 'reifyui/harness';
171
+ import 'reifyui/styles/chat.css';
172
+
173
+ <ChatPanel
174
+ sessionId={id} // opaque — never parsed, so a placeholder id is fine
175
+ loadHistory={(sid) => sessionTurns(sid).then(turnsToMessages)}
176
+ runTurn={({ sessionId, text, attachments, handlers }) =>
177
+ runMyTurn(sessionId, text, handlers, attachments.map((a) => a.payload))}
178
+ onSessionStarted={adopt} // the first turn opened a session: take its id
179
+ externalBusy={agentIsRunning} // a turn started elsewhere — poll, don't show a blank prompt
180
+ attachments={{ prepare: fileToInputBlock }}
181
+ dictation={createDictation()} // null where the browser has no recogniser -> no mic
182
+ title={doc.title}
183
+ placeholder="What should this do?"
184
+ emptyState={<YourEmptyState />}
185
+ />
186
+ ```
187
+
188
+ `runTurn` resolves `{ connecting: true }` when the backend is not up yet: the panel then holds the
189
+ message — with its files — and retries, instead of showing a turn that failed. Everything else it
190
+ learns through `handlers`, which are the streaming dispatcher's own callbacks.
154
191
 
155
192
  ## Slides
156
193
 
@@ -89,9 +89,33 @@ async function pumpResponsesStream(body, handlers) {
89
89
  return d.responseId;
90
90
  }
91
91
 
92
+ // src/state/turns.js
93
+ var TURN_STATUS = {
94
+ failed: "failed",
95
+ error: "failed",
96
+ cancelled: "cancelled",
97
+ incomplete: "incomplete",
98
+ max_turns: "incomplete",
99
+ timeout: "incomplete"
100
+ };
101
+ function turnsToMessages(turns) {
102
+ const out = [];
103
+ for (const t of turns || []) {
104
+ if (t.user) out.push({ role: "user", text: t.user });
105
+ const steps = (t.tools || []).map((x) => ({ name: x.name, args: x.arguments, result: x.result }));
106
+ const blocks = [];
107
+ if (steps.length) blocks.push({ kind: "tools", reasoning: "", steps });
108
+ if (t.assistant) blocks.push({ kind: "text", text: t.assistant });
109
+ const status = TURN_STATUS[t.status] || "done";
110
+ if (blocks.length || status !== "done") out.push({ role: "assistant", blocks, status });
111
+ }
112
+ return out;
113
+ }
114
+
92
115
  export {
93
116
  createResponsesDispatcher,
94
117
  readSSEStream,
95
- pumpResponsesStream
118
+ pumpResponsesStream,
119
+ turnsToMessages
96
120
  };
97
- //# sourceMappingURL=chunk-2LYV4PIX.js.map
121
+ //# sourceMappingURL=chunk-NTIWFHR4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/stream/responses.js","../src/state/turns.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 });\n return d.responseId;\n}\n","// Gateway turns -> the message shape ChatMessages renders.\n//\n// This lives in state/ rather than in the transport because it is a pure shape translation with\n// no network in it, and because ChatPanel (a root export) takes ChatMessage[] from its\n// loadHistory: a root consumer must be able to convert history without pulling the whole\n// HarnessRouter fetch layer into its bundle. reifyui/harness re-exports it, so the transport's\n// own callers keep importing it from where the rest of their transport lives.\n//\n// Four apps had each open-coded this function. Three of the four copies were byte-identical and\n// the fourth was the same logic with the status map inlined as a nested ternary.\n\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"],"mappings":";AAwBO,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,KAAK,WAAY,GAAE,YAAY,KAAK,UAAU;AAClD,gBAAM,MAAO,KAAK,YAAY,KAAK,SAAS,cAAe;AAC3D,cAAI,IAAK,GAAE,YAAY,GAAG;AAC1B;AAAA,QACF;AAAA,QACA,KAAK;AACH,YAAE,mBAAmB,GAAG,SAAS,EAAE;AACnC;AAAA,QACF,KAAK,8BAA8B;AACjC,gBAAM,OAAO,GAAG,QAAQ,CAAC;AACzB,cAAI,KAAK,SAAS,iBAAiB;AAC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AAU,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;","names":[]}
package/dist/harness.cjs CHANGED
@@ -19,12 +19,15 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
19
19
  // src/harness/index.js
20
20
  var harness_exports = {};
21
21
  __export(harness_exports, {
22
+ FILE_MAX: () => FILE_MAX,
23
+ bufferToDataUrl: () => bufferToDataUrl,
22
24
  cancelResponse: () => cancelResponse,
23
25
  cancelSession: () => cancelSession,
24
26
  configureKit: () => configureKit,
25
27
  containerFileUrl: () => containerFileUrl,
26
28
  createResponse: () => createResponse,
27
29
  deleteSession: () => deleteSession,
30
+ fileToInputBlock: () => fileToInputBlock,
28
31
  getResponse: () => getResponse,
29
32
  hr: () => hr,
30
33
  kitConfig: () => kitConfig,
@@ -32,6 +35,7 @@ __export(harness_exports, {
32
35
  lastAssistantText: () => lastAssistantText,
33
36
  listHarnesses: () => listHarnesses,
34
37
  listSessions: () => listSessions,
38
+ mimeOf: () => mimeOf,
35
39
  patchSession: () => patchSession,
36
40
  readFile: () => readFile,
37
41
  readJsonFile: () => readJsonFile,
@@ -124,6 +128,74 @@ async function readSSEStream(body, onData) {
124
128
  }
125
129
  }
126
130
 
131
+ // src/state/turns.js
132
+ var TURN_STATUS = {
133
+ failed: "failed",
134
+ error: "failed",
135
+ cancelled: "cancelled",
136
+ incomplete: "incomplete",
137
+ max_turns: "incomplete",
138
+ timeout: "incomplete"
139
+ };
140
+ function turnsToMessages(turns) {
141
+ const out = [];
142
+ for (const t of turns || []) {
143
+ if (t.user) out.push({ role: "user", text: t.user });
144
+ const steps = (t.tools || []).map((x) => ({ name: x.name, args: x.arguments, result: x.result }));
145
+ const blocks = [];
146
+ if (steps.length) blocks.push({ kind: "tools", reasoning: "", steps });
147
+ if (t.assistant) blocks.push({ kind: "text", text: t.assistant });
148
+ const status = TURN_STATUS[t.status] || "done";
149
+ if (blocks.length || status !== "done") out.push({ role: "assistant", blocks, status });
150
+ }
151
+ return out;
152
+ }
153
+
154
+ // src/harness/attach.js
155
+ var FILE_MAX = 25 * 1024 * 1024;
156
+ var MIME = {
157
+ md: "text/markdown",
158
+ txt: "text/plain",
159
+ json: "application/json",
160
+ csv: "text/csv",
161
+ tsv: "text/tab-separated-values",
162
+ html: "text/html",
163
+ py: "text/x-python",
164
+ js: "text/javascript",
165
+ png: "image/png",
166
+ jpg: "image/jpeg",
167
+ jpeg: "image/jpeg",
168
+ gif: "image/gif",
169
+ svg: "image/svg+xml",
170
+ pdf: "application/pdf",
171
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
172
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
173
+ };
174
+ var mimeOf = (name, fallback = "application/octet-stream") => MIME[String(name).split(".").pop().toLowerCase()] || fallback;
175
+ function bufferToDataUrl(buf, filename, type) {
176
+ let bin = "";
177
+ const bytes = new Uint8Array(buf);
178
+ for (let i = 0; i < bytes.length; i += 32768) {
179
+ bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 32768));
180
+ }
181
+ return `data:${type || mimeOf(filename)};base64,${btoa(bin)}`;
182
+ }
183
+ async function fileToInputBlock(file, { maxBytes = FILE_MAX } = {}) {
184
+ if (file.size > maxBytes) {
185
+ throw new Error(`${file.name} is ${Math.round(file.size / 1048576)} MB \u2014 the limit is ${Math.round(maxBytes / 1048576)} MB.`);
186
+ }
187
+ const buf = await file.arrayBuffer();
188
+ return {
189
+ name: file.name,
190
+ size: file.size,
191
+ payload: {
192
+ type: "input_file",
193
+ filename: file.name,
194
+ file_data: bufferToDataUrl(buf, file.name, file.type)
195
+ }
196
+ };
197
+ }
198
+
127
199
  // src/harness/index.js
128
200
  var CONFIG = { kitId: "", base: "/api/harness/v1" };
129
201
  function configureKit({ kitId, base } = {}) {
@@ -280,27 +352,6 @@ async function streamTurn({ sessionId, harnessId, input, instructions, handlers
280
352
  });
281
353
  return { ok: !sawError, sessionId: sid };
282
354
  }
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
355
  function lastAssistantText(turns) {
305
356
  for (let i = (turns || []).length - 1; i >= 0; i--) {
306
357
  if (turns[i]?.assistant) return String(turns[i].assistant);
@@ -1 +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;AAA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GAAG;AAC3B,QAAI,EAAE,KAAM,KAAI,KAAK,EAAE,MAAM,QAAQ,MAAM,EAAE,KAAK,CAAC;AACnD,UAAM,SAAS,EAAE,SAAS,CAAC,GAAG,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,MAAM,EAAE,WAAW,QAAQ,EAAE,OAAO,EAAE;AAChG,UAAM,SAAS,CAAC;AAChB,QAAI,MAAM,OAAQ,QAAO,KAAK,EAAE,MAAM,SAAS,WAAW,IAAI,MAAM,CAAC;AACrE,QAAI,EAAE,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":[]}
1
+ {"version":3,"sources":["../src/harness/index.js","../src/stream/responses.js","../src/state/turns.js","../src/harness/attach.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 ──────────────────────────────────────────────────────\n// turnsToMessages now lives in state/turns.js and is re-exported from BOTH entry points: it is a\n// pure shape translation, and ChatPanel (a root export) takes the messages it produces, so a root\n// consumer must be able to convert history without pulling this fetch layer into its bundle.\nexport { turnsToMessages } from '../state/turns.js';\n\n// Files on their way into a turn — `input_file` is this transport's block shape, so it lives here.\nexport { FILE_MAX, mimeOf, bufferToDataUrl, fileToInputBlock } from './attach.js';\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","// Gateway turns -> the message shape ChatMessages renders.\n//\n// This lives in state/ rather than in the transport because it is a pure shape translation with\n// no network in it, and because ChatPanel (a root export) takes ChatMessage[] from its\n// loadHistory: a root consumer must be able to convert history without pulling the whole\n// HarnessRouter fetch layer into its bundle. reifyui/harness re-exports it, so the transport's\n// own callers keep importing it from where the rest of their transport lives.\n//\n// Four apps had each open-coded this function. Three of the four copies were byte-identical and\n// the fourth was the same logic with the status map inlined as a nested ternary.\n\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","// Files, on their way into a turn.\n//\n// One mechanism for every place a file gets attached — the person's own attachment in the chat\n// panel, and an upstream computed cell's artifact handed to the next one. Both become an\n// `input_file` block on the turn, which the gateway writes into the working directory before the\n// agent starts.\n//\n// This lives with the transport because `input_file` is that transport's block shape, not a\n// general idea about files.\n//\n// Deliberately NOT a workspace PUT: that needs a session which a brand-new document does not have\n// yet, it is refused 409 while a turn is running, and it cannot carry bytes that are not text —\n// one kit shipped `await file.text()` here and corrupted every PDF and image it was given.\n\n/** Per-file cap the API enforces. Refuse a bigger file by name rather than truncating it. */\nexport const FILE_MAX = 25 * 1024 * 1024;\n\nconst MIME = {\n md: 'text/markdown', txt: 'text/plain', json: 'application/json', csv: 'text/csv',\n tsv: 'text/tab-separated-values', html: 'text/html', py: 'text/x-python', js: 'text/javascript',\n png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', svg: 'image/svg+xml',\n pdf: 'application/pdf', docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n};\n\nexport const mimeOf = (name, fallback = 'application/octet-stream') =>\n MIME[String(name).split('.').pop().toLowerCase()] || fallback;\n\n/** ArrayBuffer -> data: URL, chunked because a single fromCharCode over a large file overflows\n * the argument stack. */\nexport function bufferToDataUrl(buf, filename, type) {\n let bin = '';\n const bytes = new Uint8Array(buf);\n for (let i = 0; i < bytes.length; i += 0x8000) {\n bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));\n }\n return `data:${type || mimeOf(filename)};base64,${btoa(bin)}`;\n}\n\n/** A picked File -> the staged entry a chat panel hands back to its runTurn.\n *\n * The return shape is ChatPanel's StagedFile ({name, size, payload}) on purpose, so a kit's\n * whole attachment story is `attachments={{ prepare: fileToInputBlock }}` and the panel never\n * learns what a block is. `payload` is the `input_file` block; the caller puts it in `input`.\n *\n * Throws with the file's OWN name if it is too large — the message reaches the person, so it\n * names the file they picked rather than reporting a limit in the abstract. */\nexport async function fileToInputBlock(file, { maxBytes = FILE_MAX } = {}) {\n if (file.size > maxBytes) {\n throw new Error(`${file.name} is ${Math.round(file.size / 1048576)} MB`\n + ` — the limit is ${Math.round(maxBytes / 1048576)} MB.`);\n }\n const buf = await file.arrayBuffer();\n return {\n name: file.name,\n size: file.size,\n payload: {\n type: 'input_file',\n filename: file.name,\n file_data: bufferToDataUrl(buf, file.name, file.type),\n },\n };\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;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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SAAS;AACtC,QAAI;AACJ,QAAI;AAAE,YAAM,KAAK,MAAM,IAAI;AAAA,IAAG,QAAQ;AAAE;AAAA,IAAQ;AAChD,UAAM,QAAQ,YAAY,GAAG;AAC7B,QAAI,SAAS,UAAU,KAAK;AAAE,YAAM;AAAO,eAAS,YAAY,KAAK;AAAA,IAAG;AACxE,MAAE,SAAS,GAAG;AAAA,EAChB,CAAC;AACD,SAAO,EAAE,IAAI,CAAC,UAAU,WAAW,IAAI;AACzC;AAaO,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":[]}
package/dist/harness.d.ts CHANGED
@@ -84,5 +84,28 @@ export interface ChatMessage {
84
84
  blocks?: Array<Record<string, unknown>>;
85
85
  status?: string;
86
86
  }
87
+ /** Also exported from the package root — same function, one implementation (state/turns.js).
88
+ * Converting history must not require importing this fetch layer, and importing this fetch
89
+ * layer must not mean going somewhere else for the converter. */
87
90
  export function turnsToMessages(turns: Turn[]): ChatMessage[];
88
91
  export function lastAssistantText(turns: Turn[]): string;
92
+
93
+ // ── files on their way into a turn ──────────────────────────────────────────
94
+ /** Per-file cap the API enforces. A bigger file is refused by name, never truncated. */
95
+ export const FILE_MAX: number;
96
+ /** Content type from a filename's extension, for the handful the products actually send. */
97
+ export function mimeOf(name: string, fallback?: string): string;
98
+ /** ArrayBuffer -> data: URL. Chunked: one fromCharCode over a large file overflows the stack. */
99
+ export function bufferToDataUrl(buffer: ArrayBuffer, filename: string, type?: string): string;
100
+
101
+ /** A picked File -> the `input_file` block a turn takes, wrapped in ChatPanel's StagedFile shape
102
+ * so a whole attachment story is `attachments={{ prepare: fileToInputBlock }}`.
103
+ *
104
+ * Not a workspace PUT: that needs a session a brand-new document does not have, is refused 409
105
+ * while a turn runs, and cannot carry bytes that are not text.
106
+ *
107
+ * Rejects with a message naming the FILE when it is over the cap — the person reads it. */
108
+ export function fileToInputBlock(
109
+ file: File,
110
+ options?: { maxBytes?: number },
111
+ ): Promise<{ name: string; size: number; payload: { type: 'input_file'; filename: string; file_data: string } }>;
package/dist/harness.js CHANGED
@@ -1,7 +1,53 @@
1
1
  import {
2
2
  createResponsesDispatcher,
3
- readSSEStream
4
- } from "./chunk-2LYV4PIX.js";
3
+ readSSEStream,
4
+ turnsToMessages
5
+ } from "./chunk-NTIWFHR4.js";
6
+
7
+ // src/harness/attach.js
8
+ var FILE_MAX = 25 * 1024 * 1024;
9
+ var MIME = {
10
+ md: "text/markdown",
11
+ txt: "text/plain",
12
+ json: "application/json",
13
+ csv: "text/csv",
14
+ tsv: "text/tab-separated-values",
15
+ html: "text/html",
16
+ py: "text/x-python",
17
+ js: "text/javascript",
18
+ png: "image/png",
19
+ jpg: "image/jpeg",
20
+ jpeg: "image/jpeg",
21
+ gif: "image/gif",
22
+ svg: "image/svg+xml",
23
+ pdf: "application/pdf",
24
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
25
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
26
+ };
27
+ var mimeOf = (name, fallback = "application/octet-stream") => MIME[String(name).split(".").pop().toLowerCase()] || fallback;
28
+ function bufferToDataUrl(buf, filename, type) {
29
+ let bin = "";
30
+ const bytes = new Uint8Array(buf);
31
+ for (let i = 0; i < bytes.length; i += 32768) {
32
+ bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 32768));
33
+ }
34
+ return `data:${type || mimeOf(filename)};base64,${btoa(bin)}`;
35
+ }
36
+ async function fileToInputBlock(file, { maxBytes = FILE_MAX } = {}) {
37
+ if (file.size > maxBytes) {
38
+ throw new Error(`${file.name} is ${Math.round(file.size / 1048576)} MB \u2014 the limit is ${Math.round(maxBytes / 1048576)} MB.`);
39
+ }
40
+ const buf = await file.arrayBuffer();
41
+ return {
42
+ name: file.name,
43
+ size: file.size,
44
+ payload: {
45
+ type: "input_file",
46
+ filename: file.name,
47
+ file_data: bufferToDataUrl(buf, file.name, file.type)
48
+ }
49
+ };
50
+ }
5
51
 
6
52
  // src/harness/index.js
7
53
  var CONFIG = { kitId: "", base: "/api/harness/v1" };
@@ -159,27 +205,6 @@ async function streamTurn({ sessionId, harnessId, input, instructions, handlers
159
205
  });
160
206
  return { ok: !sawError, sessionId: sid };
161
207
  }
162
- var TURN_STATUS = {
163
- failed: "failed",
164
- error: "failed",
165
- cancelled: "cancelled",
166
- incomplete: "incomplete",
167
- max_turns: "incomplete",
168
- timeout: "incomplete"
169
- };
170
- function turnsToMessages(turns) {
171
- const out = [];
172
- for (const t of turns || []) {
173
- if (t.user) out.push({ role: "user", text: t.user });
174
- const steps = (t.tools || []).map((x) => ({ name: x.name, args: x.arguments, result: x.result }));
175
- const blocks = [];
176
- if (steps.length) blocks.push({ kind: "tools", reasoning: "", steps });
177
- if (t.assistant) blocks.push({ kind: "text", text: t.assistant });
178
- const status = TURN_STATUS[t.status] || "done";
179
- if (blocks.length || status !== "done") out.push({ role: "assistant", blocks, status });
180
- }
181
- return out;
182
- }
183
208
  function lastAssistantText(turns) {
184
209
  for (let i = (turns || []).length - 1; i >= 0; i--) {
185
210
  if (turns[i]?.assistant) return String(turns[i].assistant);
@@ -187,12 +212,15 @@ function lastAssistantText(turns) {
187
212
  return "";
188
213
  }
189
214
  export {
215
+ FILE_MAX,
216
+ bufferToDataUrl,
190
217
  cancelResponse,
191
218
  cancelSession,
192
219
  configureKit,
193
220
  containerFileUrl,
194
221
  createResponse,
195
222
  deleteSession,
223
+ fileToInputBlock,
196
224
  getResponse,
197
225
  hr,
198
226
  kitConfig,
@@ -200,6 +228,7 @@ export {
200
228
  lastAssistantText,
201
229
  listHarnesses,
202
230
  listSessions,
231
+ mimeOf,
203
232
  patchSession,
204
233
  readFile,
205
234
  readJsonFile,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/harness/index.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"],"mappings":";;;;;;AAoBA,IAAI,SAAS,EAAE,OAAO,IAAI,MAAM,kBAAkB;AAG3C,SAAS,aAAa,EAAE,OAAO,KAAK,IAAI,CAAC,GAAG;AACjD,WAAS,EAAE,OAAO,SAAS,OAAO,OAAO,MAAM,QAAQ,OAAO,KAAK;AACnE,aAAW;AACX,SAAO;AACT;AAEO,SAAS,YAAY;AAAE,SAAO,EAAE,GAAG,OAAO;AAAG;AAEpD,eAAe,UAAU,KAAK;AAC5B,MAAI;AACF,UAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,UAAM,IAAI,MAAM,OAAO,WAAW,MAAM;AACxC,WAAO,OAAO,MAAM,WAAW,IAAI,mBAAmB,IAAI,MAAM;AAAA,EAClE,QAAQ;AACN,WAAO,mBAAmB,IAAI,MAAM;AAAA,EACtC;AACF;AAGA,eAAsB,GAAG,MAAM,OAAO,CAAC,GAAG;AACxC,QAAM,MAAM,MAAM,MAAM,GAAG,OAAO,IAAI,GAAG,IAAI,IAAI,EAAE,OAAO,YAAY,GAAG,KAAK,C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,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":[]}
1
+ {"version":3,"sources":["../src/harness/attach.js","../src/harness/index.js"],"sourcesContent":["// Files, on their way into a turn.\n//\n// One mechanism for every place a file gets attached — the person's own attachment in the chat\n// panel, and an upstream computed cell's artifact handed to the next one. Both become an\n// `input_file` block on the turn, which the gateway writes into the working directory before the\n// agent starts.\n//\n// This lives with the transport because `input_file` is that transport's block shape, not a\n// general idea about files.\n//\n// Deliberately NOT a workspace PUT: that needs a session which a brand-new document does not have\n// yet, it is refused 409 while a turn is running, and it cannot carry bytes that are not text —\n// one kit shipped `await file.text()` here and corrupted every PDF and image it was given.\n\n/** Per-file cap the API enforces. Refuse a bigger file by name rather than truncating it. */\nexport const FILE_MAX = 25 * 1024 * 1024;\n\nconst MIME = {\n md: 'text/markdown', txt: 'text/plain', json: 'application/json', csv: 'text/csv',\n tsv: 'text/tab-separated-values', html: 'text/html', py: 'text/x-python', js: 'text/javascript',\n png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', svg: 'image/svg+xml',\n pdf: 'application/pdf', docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n};\n\nexport const mimeOf = (name, fallback = 'application/octet-stream') =>\n MIME[String(name).split('.').pop().toLowerCase()] || fallback;\n\n/** ArrayBuffer -> data: URL, chunked because a single fromCharCode over a large file overflows\n * the argument stack. */\nexport function bufferToDataUrl(buf, filename, type) {\n let bin = '';\n const bytes = new Uint8Array(buf);\n for (let i = 0; i < bytes.length; i += 0x8000) {\n bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));\n }\n return `data:${type || mimeOf(filename)};base64,${btoa(bin)}`;\n}\n\n/** A picked File -> the staged entry a chat panel hands back to its runTurn.\n *\n * The return shape is ChatPanel's StagedFile ({name, size, payload}) on purpose, so a kit's\n * whole attachment story is `attachments={{ prepare: fileToInputBlock }}` and the panel never\n * learns what a block is. `payload` is the `input_file` block; the caller puts it in `input`.\n *\n * Throws with the file's OWN name if it is too large — the message reaches the person, so it\n * names the file they picked rather than reporting a limit in the abstract. */\nexport async function fileToInputBlock(file, { maxBytes = FILE_MAX } = {}) {\n if (file.size > maxBytes) {\n throw new Error(`${file.name} is ${Math.round(file.size / 1048576)} MB`\n + ` — the limit is ${Math.round(maxBytes / 1048576)} MB.`);\n }\n const buf = await file.arrayBuffer();\n return {\n name: file.name,\n size: file.size,\n payload: {\n type: 'input_file',\n filename: file.name,\n file_data: bufferToDataUrl(buf, file.name, file.type),\n },\n };\n}\n","// 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 ──────────────────────────────────────────────────────\n// turnsToMessages now lives in state/turns.js and is re-exported from BOTH entry points: it is a\n// pure shape translation, and ChatPanel (a root export) takes the messages it produces, so a root\n// consumer must be able to convert history without pulling this fetch layer into its bundle.\nexport { turnsToMessages } from '../state/turns.js';\n\n// Files on their way into a turn — `input_file` is this transport's block shape, so it lives here.\nexport { FILE_MAX, mimeOf, bufferToDataUrl, fileToInputBlock } from './attach.js';\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"],"mappings":";;;;;;;AAeO,IAAM,WAAW,KAAK,OAAO;AAEpC,IAAM,OAAO;AAAA,EACX,IAAI;AAAA,EAAiB,KAAK;AAAA,EAAc,MAAM;AAAA,EAAoB,KAAK;AAAA,EACvE,KAAK;AAAA,EAA6B,MAAM;AAAA,EAAa,I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