reifyui 0.13.9 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -0
- package/dist/agent-chat.cjs +2046 -0
- package/dist/agent-chat.cjs.map +1 -0
- package/dist/agent-chat.d.ts +190 -0
- package/dist/agent-chat.js +157 -0
- package/dist/agent-chat.js.map +1 -0
- package/dist/chunk-6CJPYMR2.js +1892 -0
- package/dist/chunk-6CJPYMR2.js.map +1 -0
- package/dist/chunk-AGSX5YKH.js +177 -0
- package/dist/chunk-AGSX5YKH.js.map +1 -0
- package/dist/chunk-WAND7AYD.js +124 -0
- package/dist/chunk-WAND7AYD.js.map +1 -0
- package/dist/graph.js +2 -1
- package/dist/graph.js.map +1 -1
- package/dist/harness.cjs +4 -0
- package/dist/harness.cjs.map +1 -1
- package/dist/harness.js +4 -0
- package/dist/harness.js.map +1 -1
- package/dist/index.cjs +2269 -741
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +11 -0
- package/dist/index.js +50 -6
- package/dist/index.js.map +1 -1
- package/package.json +11 -2
- package/src/agent-chat/components.jsx +777 -0
- package/src/agent-chat/index.d.ts +190 -0
- package/src/agent-chat/index.js +24 -0
- package/src/agent-chat/marks.js +51 -0
- package/src/agent-chat/time.js +55 -0
- package/src/agent-chat/tools.js +357 -0
- package/src/agent-chat/turn.js +476 -0
- package/src/components/ChatPanel.jsx +37 -1
- package/src/harness/index.js +3 -1
- package/src/index.d.ts +11 -0
- package/styles/agent-chat.css +306 -0
- package/styles/chat.css +5 -0
- package/dist/chunk-J7SECRIG.js +0 -295
- package/dist/chunk-J7SECRIG.js.map +0 -1
package/dist/harness.cjs
CHANGED
package/dist/harness.cjs.map
CHANGED
|
@@ -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 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,KAAK,yCAAyC;AAC5C,gBAAM,KAAK,QAA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AAE,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) 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,SA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,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
package/dist/harness.js.map
CHANGED
|
@@ -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 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,OAAO,IAAI,EAAE,MAAM,GAAG,EAAE,IAAI,EAAE,YAAY,CAAC,KAAK;AAIhD,SAAS,gBAAgB,KAAK,UAAU,MAAM;AACnD,MAAI,MAAM;AACV,QAAM,QAAQ,IAAI,WAAW,GAAG;AAChC,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,OAAQ;AAC7C,WAAO,OAAO,aAAa,MAAM,MAAM,MAAM,SAAS,GAAG,IAAI,KAAM,CAAC;AAAA,EACtE;AACA,SAAO,QAAQ,QAAQ,OAAO,QAAQ,CAAC,WAAW,KAAK,GAAG,CAAC;AAC7D;AAUA,eAAsB,iBAAiB,MAAM,EAAE,WAAW,SAAS,IAAI,CAAC,GAAG;AACzE,MAAI,KAAK,OAAO,UAAU;AACxB,UAAM,IAAI,MAAM,GAAG,KAAK,IAAI,OAAO,KAAK,MAAM,KAAK,OAAO,OAAO,CAAC,2BAC3C,KAAK,MAAM,WAAW,OAAO,CAAC,MAAM;AAAA,EAC7D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AAM,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;AACxE,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/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) 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"],"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,OAAO,IAAI,EAAE,MAAM,GAAG,EAAE,IAAI,EAAE,YAAY,CAAC,KAAK;AAIhD,SAAS,gBAAgB,KAAK,UAAU,MAAM;AACnD,MAAI,MAAM;AACV,QAAM,QAAQ,IAAI,WAAW,GAAG;AAChC,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,OAAQ;AAC7C,WAAO,OAAO,aAAa,MAAM,MAAM,MAAM,SAAS,GAAG,IAAI,KAAM,CAAC;AAAA,EACtE;AACA,SAAO,QAAQ,QAAQ,OAAO,QAAQ,CAAC,WAAW,KAAK,GAAG,C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