reifyui 0.15.0 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +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) and onEvent(event), every event whole as it arrives.\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 // every event, whole, as it arrives (reifyui/agent-chat folds these into the turn's clock)\n try { handlers.onEvent?.(evt); } catch { /* a view's clock must never break the stream */ }\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,8BA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AK;AAAA,MAAG;AAExE,UAAI;AAAE,iBAAS,UAAU,GAAG;AAAA,MAAG,QAAQ;AAAA,MAAmD;AAC1F,QAAE,SAAS,GAAG;AAAA,IAChB,CAAC;AAAA,EACH,QAAQ;AAKN,WAAO,EAAE,IAAI,OAAO,SAAS,MAAM,WAAW,IAAI;AAAA,EACpD;AACA,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) and onEvent(event), every event whole as it arrives.\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 // every event, whole, as it arrives (reifyui/agent-chat folds these into the turn's clock)\n try { handlers.onEvent?.(evt); } catch { /* a view's clock must never break the stream */ }\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, isError) function_call_output items; isError is true only when\n// the item says the tool failed (`is_error: true`)\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 ?? ''), item.is_error === true);\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 // the record names a result `output` (`result` is the older name); is_error marks a call the tool said failed\n const steps = (t.tools || []).map((x) => ({ name: x.name, args: x.arguments, result: x.result ?? x.output,\n ...(x.is_error ? { isError: true } : {}) }));\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;;;ACyBO,SAAS,0BA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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,MAAI;AACF,UAAM,cAAc,IAAI,MAAM,CAAC,SAAS;AACtC,UAAI;AACJ,UAAI;AAAE,cAAM,KAAK,MAAM,IAAI;AAAA,MAAG,QAAQ;AAAE;AAAA,MAAQ;AAChD,YAAM,QAAQ,YAAY,GAAG;AAC7B,UAAI,SAAS,UAAU,KAAK;AAAE,cAAM;AAAO,iBAAS,YAAY,KAAK;AAAA,MAAG;AAExE,UAAI;AAAE,iBAAS,UAAU,GAAG;AAAA,MAAG,QAAQ;AAAA,MAAmD;AAC1F,QAAE,SAAS,GAAG;AAAA,IAChB,CAAC;AAAA,EACH,QAAQ;AAKN,WAAO,EAAE,IAAI,OAAO,SAAS,MAAM,WAAW,IAAI;AAAA,EACpD;AACA,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.js CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  createResponsesDispatcher,
3
3
  readSSEStream,
4
4
  turnsToMessages
5
- } from "./chunk-NTIWFHR4.js";
5
+ } from "./chunk-KJY3FVGZ.js";
6
6
  import "./chunk-PZ5AY32C.js";
7
7
 
8
8
  // src/harness/attach.js
package/dist/index.cjs CHANGED
@@ -170,7 +170,7 @@ function createResponsesDispatcher(h) {
170
170
  if (item.type === "function_call") {
171
171
  fnByIdx[ev.output_index] = { name: item.name || "tool", callId: item.call_id || "" };
172
172
  } else if (item.type === "function_call_output") {
173
- h.onToolResult?.(item.call_id || "", String(item.output ?? ""));
173
+ h.onToolResult?.(item.call_id || "", String(item.output ?? ""), item.is_error === true);
174
174
  }
175
175
  break;
176
176
  }
@@ -259,8 +259,8 @@ function withStep(blocks, step) {
259
259
  else out.push({ kind: "tools", reasoning: "", steps: [step] });
260
260
  return out;
261
261
  }
262
- function withResult(blocks, callId, output) {
263
- return blocks.map((b) => b.kind !== "tools" ? b : { ...b, steps: b.steps.map((t) => t.callId && t.callId === callId && t.result === void 0 ? { ...t, result: output } : t) });
262
+ function withResult(blocks, callId, output, isError = false) {
263
+ return blocks.map((b) => b.kind !== "tools" ? b : { ...b, steps: b.steps.map((t) => t.callId && t.callId === callId && t.result === void 0 ? { ...t, result: output, ...isError ? { isError: true } : {} } : t) });
264
264
  }
265
265
  function asstText(a) {
266
266
  return a.blocks.filter((b) => b.kind === "text").map((b) => b.text).join("\n\n");
@@ -337,7 +337,12 @@ function turnsToMessages(turns) {
337
337
  const out = [];
338
338
  for (const t of turns || []) {
339
339
  if (t.user) out.push({ role: "user", text: t.user });
340
- const steps = (t.tools || []).map((x) => ({ name: x.name, args: x.arguments, result: x.result }));
340
+ const steps = (t.tools || []).map((x) => ({
341
+ name: x.name,
342
+ args: x.arguments,
343
+ result: x.result ?? x.output,
344
+ ...x.is_error ? { isError: true } : {}
345
+ }));
341
346
  const blocks = [];
342
347
  if (steps.length) blocks.push({ kind: "tools", reasoning: "", steps });
343
348
  if (t.assistant) blocks.push({ kind: "text", text: t.assistant });
@@ -634,17 +639,18 @@ function ToolGroup(props) {
634
639
  ] });
635
640
  }
636
641
  function ToolRow(props) {
637
- const { step, requestLabel = "Request", resultLabel = "Result" } = props;
642
+ const { step, requestLabel = "Request", resultLabel = "Result", failedLabel = "Failed" } = props;
638
643
  const [open, setOpen] = (0, import_react3.useState)(false);
639
644
  const meta = toolMeta(step.name, step.args);
640
645
  const Icon = meta.Icon;
641
646
  const hasDetail = !!(step.args && step.args !== "{}") || step.result !== void 0;
642
- return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "wbx-act", children: [
647
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "wbx-act" + (step.isError ? " is-failed" : ""), children: [
643
648
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "wbx-act-ic-t", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Icon, {}) }),
644
649
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "wbx-act-main", children: [
645
650
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("button", { className: "wbx-act-row" + (open ? " open" : ""), disabled: !hasDetail, onClick: () => setOpen((v) => !v), children: [
646
651
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "wbx-act-k", children: meta.label }),
647
652
  meta.chip && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "wbx-act-chip", children: meta.chip }),
653
+ step.isError && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "wbx-act-failed", children: failedLabel }),
648
654
  hasDetail && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "wbx-act-exp", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Chevron, { dir: open ? "down" : "right", size: 12 }) })
649
655
  ] }),
650
656
  open && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "wbx-act-detail", children: [
@@ -1200,7 +1206,10 @@ function commandText(a) {
1200
1206
  if (c.length >= 3 && /(^|\/)(ba|z)?sh$/.test(String(c[0])) && /^-\w*c$/.test(String(c[1]))) c = c.slice(2).join(" ");
1201
1207
  else c = c.join(" ");
1202
1208
  }
1203
- return str(c).trim();
1209
+ let t = str(c).trim();
1210
+ const m = t.match(/^(?:\/(?:usr\/)?bin\/)?(?:ba|z)?sh\s+-\w*c\s+(['"])([\s\S]*)\1$/);
1211
+ if (m) t = m[2].replace(m[1] === "'" ? /'\\''/g : /\\"/g, m[1]);
1212
+ return t;
1204
1213
  }
1205
1214
  function lineCount(s) {
1206
1215
  const t = str(s);
@@ -1845,7 +1854,8 @@ function turnFromMessage(msg, clock = null, user = null) {
1845
1854
  const c = s.callId ? byCall[s.callId] : null;
1846
1855
  const answered = s.result !== void 0;
1847
1856
  let st = c ? c.status : answered ? "done" : status === "running" ? "running" : status === "done" ? "done" : "stopped";
1848
- if (answered && st === "running") st = "done";
1857
+ if (s.isError || s.is_error) st = "failed";
1858
+ if (answered && st === "running") st = s.isError || s.is_error ? "failed" : "done";
1849
1859
  if (st === "running" && status !== "running") st = status === "done" ? "done" : "stopped";
1850
1860
  items.push({
1851
1861
  kind: "tool",
@@ -2641,7 +2651,7 @@ function ChatPanel(props) {
2641
2651
  },
2642
2652
  onReasoningDelta: (d) => updateLastAsst((a) => ({ ...a, blocks: withReasoning(a.blocks, d) })),
2643
2653
  onToolCall: (name, args, callId) => updateLastAsst((a) => ({ ...a, blocks: withStep(a.blocks, { name, args, callId }) })),
2644
- onToolResult: (callId, output) => updateLastAsst((a) => ({ ...a, blocks: withResult(a.blocks, callId, output) })),
2654
+ onToolResult: (callId, output, isError) => updateLastAsst((a) => ({ ...a, blocks: withResult(a.blocks, callId, output, isError) })),
2645
2655
  onTextDelta: (d) => updateLastAsst((a) => ({ ...a, blocks: withText(a.blocks, d) })),
2646
2656
  onDone: (status) => updateLastAsst((a) => ({ ...a, status: status === "completed" ? "done" : status })),
2647
2657
  onError: () => updateLastAsst((a) => ({