reifyui 0.13.3 → 0.13.5

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/dist/harness.cjs CHANGED
@@ -311,17 +311,22 @@ async function streamTurn({ sessionId, harnessId, input, instructions, handlers
311
311
  hid = h.id;
312
312
  }
313
313
  const existing = sessionId ? String(sessionId) : "";
314
- const res = await fetch(`${CONFIG.base}/responses`, {
315
- method: "POST",
316
- cache: "no-store",
317
- headers: { "content-type": "application/json", accept: "text/event-stream" },
318
- body: JSON.stringify({
319
- input,
320
- ...instructions ? { instructions } : {},
321
- metadata: { harness_id: hid, ...existing ? { session_id: existing } : {} },
322
- stream: true
323
- })
324
- });
314
+ let res;
315
+ try {
316
+ res = await fetch(`${CONFIG.base}/responses`, {
317
+ method: "POST",
318
+ cache: "no-store",
319
+ headers: { "content-type": "application/json", accept: "text/event-stream" },
320
+ body: JSON.stringify({
321
+ input,
322
+ ...instructions ? { instructions } : {},
323
+ metadata: { harness_id: hid, ...existing ? { session_id: existing } : {} },
324
+ stream: true
325
+ })
326
+ });
327
+ } catch {
328
+ return { connecting: true };
329
+ }
325
330
  if (res.status === 503) return { connecting: true };
326
331
  if (!res.ok || !res.body) {
327
332
  const t = await res.text().catch(() => "");
@@ -336,20 +341,24 @@ async function streamTurn({ sessionId, harnessId, input, instructions, handlers
336
341
  handlers.onError?.(msg);
337
342
  }
338
343
  });
339
- await readSSEStream(res.body, (data) => {
340
- let evt;
341
- try {
342
- evt = JSON.parse(data);
343
- } catch {
344
- return;
345
- }
346
- const found = sessionIdOf(evt);
347
- if (found && found !== sid) {
348
- sid = found;
349
- handlers.onSession?.(found);
350
- }
351
- d.dispatch(evt);
352
- });
344
+ try {
345
+ await readSSEStream(res.body, (data) => {
346
+ let evt;
347
+ try {
348
+ evt = JSON.parse(data);
349
+ } catch {
350
+ return;
351
+ }
352
+ const found = sessionIdOf(evt);
353
+ if (found && found !== sid) {
354
+ sid = found;
355
+ handlers.onSession?.(found);
356
+ }
357
+ d.dispatch(evt);
358
+ });
359
+ } catch {
360
+ return { ok: false, dropped: true, sessionId: sid };
361
+ }
353
362
  return { ok: !sawError, sessionId: sid };
354
363
  }
355
364
  function lastAssistantText(turns) {
@@ -1 +1 @@
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,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;AACjC,oBAAQ,GAAG,YAAY,IAAI,EAAE,MAAM,KAAK,QAAQ,QAAQ,QAAQ,KAAK,WAAW,GAAG;AAAA,UACrF,WAAW,KAAK,SAAS,wBAAwB;AAC/C,cAAE,eAAe,KAAK,WAAW,IAAI,OAAO,KAAK,UAAU,EAAE,CAAC;AAAA,UAChE;AACA;AAAA,QACF;AAAA,Q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I,eAAe,EAAE,aAAa,IAAI,CAAC;AAAA,MACvC,UAAU,EAAE,YAAY,KAAK,GAAI,WAAW,EAAE,YAAY,SAAS,IAAI,CAAC,EAAG;AAAA,MAC3E,QAAQ;AAAA,IACV,CAAC;AAAA,EACH,CAAC;AACD,MAAI,IAAI,WAAW,IAAK,QAAO,EAAE,YAAY,KAAK;AAClD,MAAI,CAAC,IAAI,MAAM,CAAC,IAAI,MAAM;AACxB,UAAM,IAAI,MAAM,IAAI,KAAK,EAAE,MAAM,MAAM,EAAE;AACzC,UAAM,IAAI,MAAM,gBAAgB,IAAI,MAAM,IAAI,EAAE,MAAM,GAAG,GAAG,CAAC,EAAE;AAAA,EACjE;AAEA,MAAI,WAAW;AACf,MAAI,MAAM;AACV,QAAM,IAAI,0BAA0B;AAAA,IAClC,GAAG;AAAA,IACH,SAAS,CAAC,QAAQ;AAAE,iBAAW;AAAM,eAAS,UAAU,GAAG;AAAA,IAAG;AAAA,EAChE,CAAC;AACD,QAAM,cAAc,IAAI,MAAM,CAAC,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":[]}
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 let res;\n try {\n 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 } catch {\n return { connecting: true }; // nothing reached the gateway (down, or restarting): safe to send again\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 try {\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 } catch {\n // The gateway ACCEPTED the turn (200) and the stream broke afterwards: a console rollout\n // that stopped the old slot, a proxy timeout, a network blink. The turn is running without\n // this stream, so sending the message again would start a second one; the caller attaches\n // to the one that exists instead (its history, polled until it settles).\n return { ok: false, dropped: true, sessionId: sid };\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,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;AACjC,oBAAQ,GAAG,YAAY,IAAI,EAAE,MAAM,KAAK,QAAQ,QAAQ,QAAQ,KAAK,WAAW,GAAG;AAAA,UACrF,WAAW,KAAK,SAAS,wBAAwB;AAC/C,cAAE,eAAe,KAAK,WAAW,IAAI,OAAO,KAAK,UAAU,EAAE,CAAC;AAAA,UAChE;AACA;AAAA,QACF;AAAA,QACA,KAA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AG,UAAW,QAAO,OAAO,MAAM,CAAC,EAAE,SAAS;AAAA,EAC3D;AACA,SAAO;AACT;","names":[]}
package/dist/harness.js CHANGED
@@ -165,17 +165,22 @@ async function streamTurn({ sessionId, harnessId, input, instructions, handlers
165
165
  hid = h.id;
166
166
  }
167
167
  const existing = sessionId ? String(sessionId) : "";
168
- const res = await fetch(`${CONFIG.base}/responses`, {
169
- method: "POST",
170
- cache: "no-store",
171
- headers: { "content-type": "application/json", accept: "text/event-stream" },
172
- body: JSON.stringify({
173
- input,
174
- ...instructions ? { instructions } : {},
175
- metadata: { harness_id: hid, ...existing ? { session_id: existing } : {} },
176
- stream: true
177
- })
178
- });
168
+ let res;
169
+ try {
170
+ res = await fetch(`${CONFIG.base}/responses`, {
171
+ method: "POST",
172
+ cache: "no-store",
173
+ headers: { "content-type": "application/json", accept: "text/event-stream" },
174
+ body: JSON.stringify({
175
+ input,
176
+ ...instructions ? { instructions } : {},
177
+ metadata: { harness_id: hid, ...existing ? { session_id: existing } : {} },
178
+ stream: true
179
+ })
180
+ });
181
+ } catch {
182
+ return { connecting: true };
183
+ }
179
184
  if (res.status === 503) return { connecting: true };
180
185
  if (!res.ok || !res.body) {
181
186
  const t = await res.text().catch(() => "");
@@ -190,20 +195,24 @@ async function streamTurn({ sessionId, harnessId, input, instructions, handlers
190
195
  handlers.onError?.(msg);
191
196
  }
192
197
  });
193
- await readSSEStream(res.body, (data) => {
194
- let evt;
195
- try {
196
- evt = JSON.parse(data);
197
- } catch {
198
- return;
199
- }
200
- const found = sessionIdOf(evt);
201
- if (found && found !== sid) {
202
- sid = found;
203
- handlers.onSession?.(found);
204
- }
205
- d.dispatch(evt);
206
- });
198
+ try {
199
+ await readSSEStream(res.body, (data) => {
200
+ let evt;
201
+ try {
202
+ evt = JSON.parse(data);
203
+ } catch {
204
+ return;
205
+ }
206
+ const found = sessionIdOf(evt);
207
+ if (found && found !== sid) {
208
+ sid = found;
209
+ handlers.onSession?.(found);
210
+ }
211
+ d.dispatch(evt);
212
+ });
213
+ } catch {
214
+ return { ok: false, dropped: true, sessionId: sid };
215
+ }
207
216
  return { ok: !sawError, sessionId: sid };
208
217
  }
209
218
  function lastAssistantText(turns) {
@@ -1 +1 @@
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,IAAI;AAAA,EAAiB,IAAI;AAAA,EAC9E,KAAK;AAAA,EAAa,KAAK;AAAA,EAAc,MAAM;AAAA,EAAc,KAAK;AAAA,EAAa,KAAK;AAAA,EAChF,KAAK;AAAA,EAAmB,MAAM;AAAA,EAC9B,MAAM;AACR;AAEO,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AAK,GAAI,WAAW,EAAE,YAAY,SAAS,IAAI,CAAC,EAAG;AAAA,MAC3E,QAAQ;AAAA,IACV,CAAC;AAAA,EACH,CAAC;AACD,MAAI,IAAI,WAAW,IAAK,QAAO,EAAE,YAAY,KAAK;AAClD,MAAI,CAAC,IAAI,MAAM,CAAC,IAAI,MAAM;AACxB,UAAM,IAAI,MAAM,IAAI,KAAK,EAAE,MAAM,MAAM,EAAE;AACzC,UAAM,IAAI,MAAM,gBAAgB,IAAI,MAAM,IAAI,EAAE,MAAM,GAAG,GAAG,CAAC,EAAE;AAAA,EACjE;AAEA,MAAI,WAAW;AACf,MAAI,MAAM;AACV,QAAM,IAAI,0BAA0B;AAAA,IAClC,GAAG;AAAA,IACH,SAAS,CAAC,QAAQ;AAAE,iBAAW;AAAM,eAAS,UAAU,GAAG;AAAA,IAAG;AAAA,EAChE,CAAC;AACD,QAAM,cAAc,IAAI,MAAM,CAAC,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":[]}
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 let res;\n try {\n 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 } catch {\n return { connecting: true }; // nothing reached the gateway (down, or restarting): safe to send again\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 try {\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 } catch {\n // The gateway ACCEPTED the turn (200) and the stream broke afterwards: a console rollout\n // that stopped the old slot, a proxy timeout, a network blink. The turn is running without\n // this stream, so sending the message again would start a second one; the caller attaches\n // to the one that exists instead (its history, polled until it settles).\n return { ok: false, dropped: true, sessionId: sid };\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,IAAI;AAAA,EAAiB,IAAI;AAAA,EAC9E,KAAK;AAAA,EAAa,KAAK;AAAA,EAAc,MAAM;AAAA,EAAc,KAAK;AAAA,EAAa,KAAK;AAAA,EAChF,KAAK;AAAA,EAAmB,MAAM;AAAA,EAC9B,MAAM;AACR;AAEO,IAAM,SAAS,CAAC,MAAM,WAAW,+BACtC,KAAK,OA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@@ -1066,6 +1066,7 @@ function ChatPanel(props) {
1066
1066
  const [draft, setDraft] = (0, import_react7.useState)("");
1067
1067
  const [busy, setBusy] = (0, import_react7.useState)(false);
1068
1068
  const [connecting, setConnecting] = (0, import_react7.useState)(false);
1069
+ const [dropped, setDropped] = (0, import_react7.useState)(false);
1069
1070
  const [histLoading, setHistLoading] = (0, import_react7.useState)(true);
1070
1071
  const [staged, setStaged] = (0, import_react7.useState)([]);
1071
1072
  const [attachErr, setAttachErr] = (0, import_react7.useState)("");
@@ -1137,12 +1138,18 @@ function ChatPanel(props) {
1137
1138
  }
1138
1139
  pendingRef.current = null;
1139
1140
  setConnecting(false);
1141
+ if (out.dropped) {
1142
+ setDropped(true);
1143
+ return;
1144
+ }
1140
1145
  updateLastAsst((a) => a.status === "running" ? { ...a, status: "done" } : a);
1141
1146
  api.current.onChanged?.();
1142
- } catch {
1143
- dropRunningAsst();
1144
- pendingRef.current = { text, files };
1145
- setConnecting(true);
1147
+ } catch (e) {
1148
+ updateLastAsst((a) => ({
1149
+ ...a,
1150
+ blocks: a.blocks.length ? a.blocks : withText([], e && e.message || "The turn could not be started."),
1151
+ status: "failed"
1152
+ }));
1146
1153
  } finally {
1147
1154
  setBusy(false);
1148
1155
  }
@@ -1204,6 +1211,26 @@ function ChatPanel(props) {
1204
1211
  }, RETRY_MS);
1205
1212
  return () => window.clearInterval(iv);
1206
1213
  }, [connecting, busy, deliver]);
1214
+ (0, import_react7.useEffect)(() => {
1215
+ if (!dropped) return void 0;
1216
+ let dead = false;
1217
+ const tick = () => Promise.resolve(api.current.loadHistory(sessionId)).then((hist) => {
1218
+ if (dead || !hist?.length) return;
1219
+ const last = hist[hist.length - 1];
1220
+ const settled = !(last.role === "assistant" && last.status === "running") && !externalBusy;
1221
+ setMessages(hist);
1222
+ if (settled) {
1223
+ setDropped(false);
1224
+ api.current.onChanged?.();
1225
+ }
1226
+ }).catch(() => {
1227
+ });
1228
+ const iv = window.setInterval(tick, POLL_MS);
1229
+ return () => {
1230
+ dead = true;
1231
+ window.clearInterval(iv);
1232
+ };
1233
+ }, [dropped, externalBusy, sessionId]);
1207
1234
  (0, import_react7.useEffect)(() => {
1208
1235
  let dead = false;
1209
1236
  let poll;
@@ -1315,7 +1342,8 @@ function ChatPanel(props) {
1315
1342
  toggle,
1316
1343
  title ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: "uic-chat-title", title, children: title }) : null,
1317
1344
  headerRight,
1318
- connecting ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: "uic-chat-conn", children: connectingLabel }) : null
1345
+ connecting ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: "uic-chat-conn", children: connectingLabel }) : null,
1346
+ dropped ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("span", { className: "uic-chat-conn", children: workingLabel }) : null
1319
1347
  ] }),
1320
1348
  /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("div", { className: "uic-chat-body", ref: bodyRef, onScroll: onBodyScroll, role: "log", "aria-live": "polite", children: [
1321
1349
  histLoading ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(ChatMessagesSkeleton, {}) : empty && externalBusy ? busyState === void 0 ? defaultBusyState : busyState : empty ? emptyState : /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
@@ -4400,6 +4428,7 @@ function kindOf(name, mime = "") {
4400
4428
  if (mime.startsWith("audio/") || ["mp3", "wav", "ogg", "m4a", "flac"].includes(e)) return "audio";
4401
4429
  if (e === "csv" || e === "tsv") return "csv";
4402
4430
  if (e === "md" || e === "markdown") return "markdown";
4431
+ if (e === "html" || e === "htm") return "html";
4403
4432
  if (SHEET.has(e)) return "sheet";
4404
4433
  if (OFFICE.has(e)) return "office";
4405
4434
  if (mime.startsWith("text/") || LANG[e] || /^(txt|log|env|conf|cfg|gitignore)$/.test(e)) return "code";
@@ -4451,12 +4480,14 @@ function FilePreview({
4451
4480
  const { url, name } = file || {};
4452
4481
  const [st, setSt] = (0, import_react19.useState)({ kind: "loading" });
4453
4482
  const [tab, setTab] = (0, import_react19.useState)(0);
4483
+ const [view, setView] = (0, import_react19.useState)("preview");
4454
4484
  (0, import_react19.useEffect)(() => {
4455
4485
  if (!url) return void 0;
4456
4486
  let alive = true;
4457
4487
  let obj;
4458
4488
  setSt({ kind: "loading" });
4459
4489
  setTab(0);
4490
+ setView("preview");
4460
4491
  const get = fetchFile || ((u) => fetch(u, { cache: "no-store" }));
4461
4492
  (async () => {
4462
4493
  const res = await get(url);
@@ -4491,7 +4522,7 @@ function FilePreview({
4491
4522
  }
4492
4523
  return;
4493
4524
  }
4494
- if (kind === "csv" || kind === "markdown" || kind === "code") {
4525
+ if (kind === "csv" || kind === "markdown" || kind === "code" || kind === "html") {
4495
4526
  const text = await res.text();
4496
4527
  if (!alive) return;
4497
4528
  if (kind === "csv") setSt({ kind: "csv", rows: delimitedToRows(text, extOf(name) === "tsv" ? " " : ",") });
@@ -4517,6 +4548,18 @@ function FilePreview({
4517
4548
  /* @__PURE__ */ (0, import_jsx_runtime18.jsxs)("header", { className: "uic-fp-head", children: [
4518
4549
  /* @__PURE__ */ (0, import_jsx_runtime18.jsx)("span", { className: "uic-fp-ic", children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(FileTypeIcon, { name, size: 20 }) }),
4519
4550
  /* @__PURE__ */ (0, import_jsx_runtime18.jsx)("span", { className: "uic-fp-name", title: name, children: name }),
4551
+ st.kind === "html" && /* @__PURE__ */ (0, import_jsx_runtime18.jsx)("div", { className: "uic-fp-seg", role: "tablist", "aria-label": "Show the page or its source", children: [["preview", "Preview"], ["source", "Source"]].map(([id, label]) => /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
4552
+ "button",
4553
+ {
4554
+ type: "button",
4555
+ role: "tab",
4556
+ "aria-selected": view === id,
4557
+ className: "uic-fp-seg-btn" + (view === id ? " is-on" : ""),
4558
+ onClick: () => setView(id),
4559
+ children: label
4560
+ },
4561
+ id
4562
+ )) }),
4520
4563
  /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(
4521
4564
  "button",
4522
4565
  {
@@ -4548,6 +4591,10 @@ function FilePreview({
4548
4591
  st.kind === "audio" && st.objUrl && /* @__PURE__ */ (0, import_jsx_runtime18.jsx)("div", { className: "uic-fp-center", children: /* @__PURE__ */ (0, import_jsx_runtime18.jsx)("audio", { src: st.objUrl, controls: true }) }),
4549
4592
  st.kind === "markdown" && /* @__PURE__ */ (0, import_jsx_runtime18.jsx)("div", { className: "uic-fp-doc", children: renderMarkdown ? renderMarkdown(st.text || "") : /* @__PURE__ */ (0, import_jsx_runtime18.jsx)("pre", { className: "uic-fp-pre", children: st.text }) }),
4550
4593
  st.kind === "code" && /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(CodeBlock, { code: st.text || "", lang: LANG[extOf(name)] || "plaintext" }),
4594
+ st.kind === "html" && view === "source" && /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(CodeBlock, { code: st.text || "", lang: "xml" }),
4595
+ st.kind === "html" && view === "preview" && // The page runs in its own origin with scripts only: a mockup's own script and styles
4596
+ // work, and nothing in it can read the host page, its cookies or its storage.
4597
+ /* @__PURE__ */ (0, import_jsx_runtime18.jsx)("iframe", { className: "uic-fp-frame", title: name, sandbox: "allow-scripts", srcDoc: st.text || "" }),
4551
4598
  st.kind === "csv" && /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Grid, { rows: st.rows }),
4552
4599
  st.kind === "sheet" && st.sheets && /* @__PURE__ */ (0, import_jsx_runtime18.jsxs)("div", { className: "uic-fp-xlsx", children: [
4553
4600
  st.sheets[tab]?.filled ? /* @__PURE__ */ (0, import_jsx_runtime18.jsx)(Grid, { rows: st.sheets[tab].rows }) : /* @__PURE__ */ (0, import_jsx_runtime18.jsx)("div", { className: "uic-fp-empty", children: "This sheet is empty." }),