@surfaces-ui/agent-loom 0.6.0 → 0.8.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/NOTICE +50 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/package.json +7 -4
package/NOTICE
CHANGED
|
@@ -2,3 +2,53 @@ Surfaces UI
|
|
|
2
2
|
Copyright 2026 Josh Schoen
|
|
3
3
|
|
|
4
4
|
This product is licensed under the Apache License, Version 2.0 (see LICENSE).
|
|
5
|
+
|
|
6
|
+
--------------------------------------------------------------------------------
|
|
7
|
+
|
|
8
|
+
@surfaces-ui/icons includes drawings from Lucide (https://lucide.dev), taken
|
|
9
|
+
from lucide-static 1.84.0. Other packages include some of them by depending on
|
|
10
|
+
it or by bundling it. They are used under this license:
|
|
11
|
+
|
|
12
|
+
ISC License
|
|
13
|
+
|
|
14
|
+
Copyright (c) 2026 Lucide Icons and Contributors
|
|
15
|
+
|
|
16
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
17
|
+
purpose with or without fee is hereby granted, provided that the above
|
|
18
|
+
copyright notice and this permission notice appear in all copies.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
|
21
|
+
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
|
22
|
+
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
|
23
|
+
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
|
24
|
+
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
|
25
|
+
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
|
26
|
+
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
The following Lucide icons are derived from the Feather project:
|
|
31
|
+
|
|
32
|
+
airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out
|
|
33
|
+
|
|
34
|
+
The MIT License (MIT) (for the icons listed above)
|
|
35
|
+
|
|
36
|
+
Copyright (c) 2013-present Cole Bemis
|
|
37
|
+
|
|
38
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
39
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
40
|
+
in the Software without restriction, including without limitation the rights
|
|
41
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
42
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
43
|
+
furnished to do so, subject to the following conditions:
|
|
44
|
+
|
|
45
|
+
The above copyright notice and this permission notice shall be included in all
|
|
46
|
+
copies or substantial portions of the Software.
|
|
47
|
+
|
|
48
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
49
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
50
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
51
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
52
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
53
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
54
|
+
SOFTWARE.
|
package/dist/index.js
CHANGED
|
@@ -220,6 +220,11 @@ export function loomAgent(options) {
|
|
|
220
220
|
},
|
|
221
221
|
async *send(request, callOptions) {
|
|
222
222
|
const signal = callOptions?.signal;
|
|
223
|
+
// A listener added to a signal that has already fired never runs, so a turn stopped before it began is caught here.
|
|
224
|
+
if (signal?.aborted) {
|
|
225
|
+
yield agentEvent.error("CANCELLED", "Stopped.");
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
223
228
|
try {
|
|
224
229
|
const input = request.input;
|
|
225
230
|
const sessionId = request.sessionId || (await createSession(request.agentId ?? "", signal));
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmB,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAA4D,UAAU,EAAE,UAAU,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AACjJ,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,4BAA4B,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAuC7G,MAAM,SAAS,GAAG,CAAC,CAAC;AACpB,MAAM,MAAM,GAAG,CAAC,CAAC;AACjB,6FAA6F;AAC7F,MAAM,aAAa,GAAG,IAAI,GAA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EAAE,SAAS;wBACrB,QAAQ,EAAE,OAAO,CAAC,OAAO,IAAI,EAAE;wBAC/B,OAAO,EAAE,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,eAAe,EAAE,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC,CAAC,SAAS;qBACxF,CAAC;oBACF,MAAM,EAAE,UAAU,CAAC,MAAM;iBAC1B,CAAC,CAAC;gBACH,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI;oBAAE,MAAM,IAAI,KAAK,CAAC,iBAAiB,QAAQ,CAAC,MAAM,GAAG,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;gBAChJ,MAAM,IAAI,GAAa,EAAE,MAAM,EAAE,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,UAAU,CAAC,KAAK,EAAE,EAAE,CAAC;gBAChH,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;gBAC1B,KAAK,CAAC,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC;YAChD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;YACxF,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { type JsonObject, create } from \"@bufbuild/protobuf\";\nimport { type AgentBackend, type AgentEvent, type DescribesAgents, agentEvent, errorEvent, extractSurfaces, turnText } from \"@surfaces-ui/agent\";\nimport { AgentInfoSchema, ApprovalKind, DescribeAgentsResponseSchema, StepStatus } from \"@surfaces-ui/proto\";\n\n/**\n * One event from Loom's `POST /v1/weave:stream`, as its HTTP gateway writes\n * it: the `WeaveProgress` message in JSON with snake_case names and numeric\n * enums. Only the fields this adapter reads are listed. Nothing from Loom is\n * vendored; this describes its public wire format.\n */\nexport interface LoomProgress {\n /** 7 is completed, 8 is failed. An error frame carries the text \"EXECUTION_STAGE_FAILED\". */\n stage?: number | string;\n message?: string;\n /** Set on a frame the gateway writes when the call itself fails. */\n error?: string;\n /** The reply so far (accumulated, not a delta) while `is_token_stream` is set. */\n partial_content?: string;\n is_token_stream?: boolean;\n tool_name?: string;\n tool_call_id?: string;\n is_tool_started?: boolean;\n is_tool_completed?: boolean;\n tool_input?: Record<string, unknown>;\n tool_error?: string;\n tool_success?: boolean;\n tool_duration_ms?: number | string;\n hitl_request?: {\n request_id?: string;\n question_id?: string;\n question?: string;\n request_type?: string;\n kind?: string;\n summary?: string;\n options?: string[];\n params_json?: string;\n };\n cost?: { total_cost_usd?: number; llm_cost?: { input_tokens?: number; output_tokens?: number; model?: string } };\n context_state?: { context_tokens_used?: number | string; context_tokens_max?: number | string };\n}\n\nconst COMPLETED = 7;\nconst FAILED = 8;\n/** Tools whose input is a list of A2UI messages to draw, not something to show as a step. */\nconst SURFACE_TOOLS = new Set([\"render_surface\"]);\n\nexport interface LoomTurnState {\n /** Reply text already passed on, to turn Loom's accumulated text into deltas. */\n text: string;\n model: string;\n /** Maps a Loom question to the tool step numbering, so repeated frames are not repeated here. */\n asked: Set<string>;\n steps: number;\n}\n\nexport const newLoomTurn = (): LoomTurnState => ({ text: \"\", model: \"\", asked: new Set(), steps: 0 });\n\nconst words = (tool: string) => tool.replace(/[_-]+/g, \" \").replace(/^./, (c) => c.toUpperCase());\nconst clip = (text: string, max = 4000) => (text.length > max ? `${text.slice(0, max)}…` : text);\n\n/**\n * Turns one Loom progress event into the events a chat shows. Pure: the\n * turn's running state is passed in and updated, so a recorded stream can be\n * replayed in tests.\n */\nexport function mapLoomProgress(frame: LoomProgress, state: LoomTurnState, sessionId: string): AgentEvent[] {\n const out: AgentEvent[] = [];\n if (frame.error) return [agentEvent.error(\"FAILED\", frame.error)];\n\n if (typeof frame.partial_content === \"string\" && frame.partial_content !== \"\" && (frame.is_token_stream || frame.stage === COMPLETED)) {\n const all = frame.partial_content;\n // Loom sends the whole reply so far each time; only what is new is passed on.\n const delta = all.startsWith(state.text) ? all.slice(state.text.length) : all;\n if (delta) out.push(agentEvent.text(delta));\n state.text = all;\n }\n\n const tool = frame.tool_name ?? \"\";\n const stepId = frame.tool_call_id || (tool ? `${tool}#${state.steps}` : \"\");\n if (frame.is_tool_started && tool) {\n const messages = SURFACE_TOOLS.has(tool) ? frame.tool_input?.messages : undefined;\n if (Array.isArray(messages)) {\n for (const message of messages) if (message && typeof message === \"object\") out.push(agentEvent.surface(message as JsonObject));\n } else {\n const sql = typeof frame.tool_input?.sql === \"string\" ? frame.tool_input.sql : undefined;\n out.push(agentEvent.step({ id: stepId, title: words(tool), status: StepStatus.RUNNING, tool, detail: clip(sql ?? (frame.tool_input ? JSON.stringify(frame.tool_input, null, 2) : \"\")) }));\n }\n }\n if (frame.is_tool_completed && tool && !SURFACE_TOOLS.has(tool)) {\n const failed = Boolean(frame.tool_error) || frame.tool_success === false;\n out.push(\n agentEvent.step({\n id: stepId,\n title: words(tool),\n status: failed ? StepStatus.FAILED : StepStatus.DONE,\n tool,\n detail: frame.tool_error ? clip(frame.tool_error) : \"\",\n durationMs: BigInt(Math.max(0, Math.round(Number(frame.tool_duration_ms ?? 0)))),\n }),\n );\n if (!frame.tool_call_id) state.steps++;\n }\n\n const ask = frame.hitl_request;\n // An empty request_id is only a hint that a question is coming; the one that can be answered follows.\n const askId = ask?.question_id || ask?.request_id || \"\";\n if (ask && ask.request_id && !state.asked.has(askId)) {\n state.asked.add(askId);\n const options = ask.options ?? [];\n const kind = options.length > 0 ? ApprovalKind.CHOICE : /approv|permission|confirm/i.test(`${ask.request_type ?? \"\"} ${ask.kind ?? \"\"}`) ? ApprovalKind.PERMISSION : ApprovalKind.INPUT;\n let sql = \"\";\n try {\n const params = ask.params_json ? (JSON.parse(ask.params_json) as Record<string, unknown>) : {};\n if (typeof params.sql === \"string\") sql = params.sql;\n } catch {\n // Parameters are optional context; a question without them is still a question.\n }\n out.push(agentEvent.approval({ id: askId, kind, title: ask.question ?? \"The agent has a question.\", detail: ask.summary ?? \"\", sql, options }));\n }\n\n if (frame.cost?.llm_cost?.model) state.model = frame.cost.llm_cost.model;\n if (frame.cost || frame.context_state) {\n out.push(\n agentEvent.usage({\n inputTokens: BigInt(frame.cost?.llm_cost?.input_tokens ?? 0),\n outputTokens: BigInt(frame.cost?.llm_cost?.output_tokens ?? 0),\n contextTokens: BigInt(Number(frame.context_state?.context_tokens_used ?? 0)),\n contextLimit: BigInt(Number(frame.context_state?.context_tokens_max ?? 0)),\n costUsd: frame.cost?.total_cost_usd,\n }),\n );\n }\n\n if (frame.stage === FAILED || frame.stage === \"EXECUTION_STAGE_FAILED\") out.push(agentEvent.error(\"FAILED\", frame.message || \"The agent could not finish.\"));\n if (frame.stage === COMPLETED) out.push(agentEvent.done(sessionId, state.model ? `Loom · ${state.model}` : \"Loom\"));\n return out;\n}\n\n/** Reads `data:` lines from a server-sent event stream as JSON. Comment lines (heartbeats) are skipped. */\nexport async function* readSse(body: ReadableStream<Uint8Array>): AsyncGenerator<LoomProgress> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let pending = \"\";\n try {\n for (;;) {\n const { done, value } = await reader.read();\n pending += done ? decoder.decode() : decoder.decode(value, { stream: true });\n const lines = pending.split(/\\r?\\n/);\n pending = done ? \"\" : (lines.pop() ?? \"\");\n for (const line of lines) {\n if (!line.startsWith(\"data:\")) continue;\n const payload = line.slice(5).trim();\n if (!payload) continue;\n try {\n yield JSON.parse(payload) as LoomProgress;\n } catch {\n // A frame that is not JSON is skipped; the stream carries on.\n }\n }\n if (done) return;\n }\n } finally {\n await reader.cancel().catch(() => {});\n }\n}\n\nexport interface LoomAgentOptions {\n /** Where the Loom server's HTTP gateway is, e.g. http://localhost:5006. */\n baseUrl: string;\n /** Supplies a bearer token per request. The token is the host's to manage; it is never stored here. */\n token?(): string | Promise<string>;\n /** Extra headers, e.g. for a proxy. */\n headers?: Record<string, string>;\n /** Uses this instead of the global `fetch`. */\n fetch?: typeof fetch;\n}\n\n/**\n * A Loom model as a chat names it: `provider/model` (`anthropic/claude-opus-5-5`,\n * `ollama/qwen3:8b`), since Loom switches a session by both. The provider\n * part never holds a slash.\n */\nexport const loomModelId = (provider: string, model: string) => (provider ? `${provider}/${model}` : model);\nexport function splitLoomModel(id: string): { provider: string; model: string } {\n const at = id.indexOf(\"/\");\n return at < 0 ? { provider: \"\", model: id } : { provider: id.slice(0, at), model: id.slice(at + 1) };\n}\n\ninterface OpenTurn {\n frames: AsyncGenerator<LoomProgress>;\n state: LoomTurnState;\n stop(): void;\n}\n\n/**\n * An AgentBackend that talks to a Loom server. Loom stays a separate\n * program: this adapter only calls its HTTP gateway, so nothing from Loom is\n * built into or shipped with this library.\n *\n * - A turn is `POST /v1/weave:stream`; replies, tool calls, questions and\n * usage are mapped to chat events.\n * - When Loom asks the person something, the turn pauses. Answering posts to\n * `/v1/clarifications/{session}/answer` and carries on reading the same\n * stream.\n * - A Loom agent draws UI by calling a `render_surface` tool (as the\n * Surfaces MCP server provides) or by writing an `a2ui` fenced block.\n */\nexport function loomAgent(options: LoomAgentOptions): AgentBackend & DescribesAgents {\n const call = options.fetch ?? fetch;\n const base = options.baseUrl.replace(/\\/+$/, \"\");\n const open = new Map<string, OpenTurn>();\n // The model each session was last switched to here, so a turn switches only when the choice changed.\n const switched = new Map<string, string>();\n\n const headers = async (accept: string) => {\n const token = await options.token?.();\n return {\n \"Content-Type\": \"application/json\",\n Accept: accept,\n // Marks the turn as started by a person, so Loom does not treat a retry as a duplicate background run.\n \"X-Loom-Slot-Origin\": \"interactive\",\n ...(token ? { Authorization: `Bearer ${token}` } : {}),\n ...options.headers,\n };\n };\n\n const createSession = async (agentId: string, signal?: AbortSignal): Promise<string> => {\n try {\n const response = await call(`${base}/v1/sessions`, { method: \"POST\", headers: await headers(\"application/json\"), body: JSON.stringify({ agent_id: agentId }), signal });\n if (response.ok) {\n const session = (await response.json()) as { id?: string };\n if (session.id) return session.id;\n }\n } catch {\n // Fall through: Loom also accepts an ID chosen by the client.\n }\n return crypto.randomUUID();\n };\n\n async function* pump(turn: OpenTurn, sessionId: string): AsyncGenerator<AgentEvent> {\n for (;;) {\n const next = await turn.frames.next();\n if (next.done) {\n open.delete(sessionId);\n // The stream ended without a completed stage: still tell the chat the turn is over.\n yield agentEvent.done(sessionId, turn.state.model ? `Loom · ${turn.state.model}` : \"Loom\");\n return;\n }\n const events = mapLoomProgress(next.value, turn.state, sessionId);\n yield* events;\n const last = events.at(-1)?.event.case;\n if (last === \"done\" || last === \"error\") {\n open.delete(sessionId);\n // The reply is complete: close the reader. Aborting a finished request would raise in callers that share its body.\n await turn.frames.return(undefined);\n return;\n }\n // The agent is waiting for an answer: this turn pauses with the stream left open.\n if (events.some((e) => e.event.case === \"approval\")) return;\n }\n }\n\n const getJson = async (path: string) => {\n const response = await call(`${base}${path}`, { headers: await headers(\"application/json\") });\n if (!response.ok) throw new Error(`Loom answered ${response.status} for ${path}.`);\n return (await response.json()) as unknown;\n };\n\n return {\n /**\n * Loom's agents, each offering the models Loom can run (`GET /v1/agents`,\n * `GET /v1/models`). A server that does not list models offers none, and a\n * turn then runs on the agent's own.\n */\n async describeAgents() {\n const [agents, models] = await Promise.all([\n getJson(\"/v1/agents\").then((body) => (body as { agents?: { id?: string; name?: string; metadata?: { description?: string } }[] }).agents ?? []),\n getJson(\"/v1/models\").then(\n (body) => (body as { models?: { id?: string; name?: string; provider?: string }[] }).models ?? [],\n () => [],\n ),\n ]);\n const options = models.filter((m) => m.id).map((m) => ({ id: loomModelId(m.provider ?? \"\", m.id!), label: m.name || m.id!, description: m.provider ?? \"\" }));\n return create(DescribeAgentsResponseSchema, {\n agents: agents.map((a, i) =>\n create(AgentInfoSchema, { id: a.name || a.id || \"\", name: a.name || a.id || \"\", description: a.metadata?.description ?? \"\", isDefault: i === 0, models: options }),\n ),\n });\n },\n async *send(request, callOptions) {\n const signal = callOptions?.signal;\n try {\n const input = request.input;\n const sessionId = request.sessionId || (await createSession(request.agentId ?? \"\", signal));\n const waiting = open.get(sessionId);\n\n if (input?.case === \"approval\" && waiting) {\n const answer = input.value.answer || (input.value.allow ? \"approved\" : \"denied\");\n const response = await call(`${base}/v1/clarifications/${encodeURIComponent(sessionId)}/answer`, {\n method: \"POST\",\n headers: await headers(\"application/json\"),\n body: JSON.stringify({ session_id: sessionId, question_id: input.value.id, answer, agent_id: request.agentId ?? \"\" }),\n signal,\n });\n if (!response.ok) throw new Error(`Loom did not accept the answer (${response.status}).`);\n signal?.addEventListener(\"abort\", () => (open.delete(sessionId), waiting.stop()), { once: true });\n yield* extractSurfaces(pump(waiting, sessionId));\n return;\n }\n // Anything else starts a new turn; a paused one is dropped.\n if (waiting) {\n open.delete(sessionId);\n waiting.stop();\n }\n\n // A model the person picked: Loom switches the session to it, keeping the conversation, before this turn.\n const model = request.model ?? \"\";\n if (model && switched.get(sessionId) !== model) {\n const { provider, model: name } = splitLoomModel(model);\n const switching = await call(`${base}/v1/sessions/${encodeURIComponent(sessionId)}:switch-model`, {\n method: \"POST\",\n headers: await headers(\"application/json\"),\n body: JSON.stringify({ session_id: sessionId, agent_id: request.agentId ?? \"\", provider, model: name, preserve_context: true }),\n signal,\n });\n if (!switching.ok) throw new Error(`Loom could not switch to ${model} (${switching.status}).`);\n switched.set(sessionId, model);\n }\n\n // The event, the page's state, the agent's own contracts and any problems, as text Loom passes to the model.\n const query = turnText(request);\n const controller = new AbortController();\n signal?.addEventListener(\"abort\", () => controller.abort(), { once: true });\n const response = await call(`${base}/v1/weave:stream`, {\n method: \"POST\",\n headers: await headers(\"text/event-stream\"),\n body: JSON.stringify({\n query,\n session_id: sessionId,\n agent_id: request.agentId ?? \"\",\n context: request.contextPackId ? { context_pack_id: request.contextPackId } : undefined,\n }),\n signal: controller.signal,\n });\n if (!response.ok || !response.body) throw new Error(`Loom answered ${response.status}${response.statusText ? ` ${response.statusText}` : \"\"}.`);\n const turn: OpenTurn = { frames: readSse(response.body), state: newLoomTurn(), stop: () => controller.abort() };\n open.set(sessionId, turn);\n yield* extractSurfaces(pump(turn, sessionId));\n } catch (error) {\n yield signal?.aborted ? agentEvent.error(\"CANCELLED\", \"Stopped.\") : errorEvent(error);\n }\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmB,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAA4D,UAAU,EAAE,UAAU,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AACjJ,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,4BAA4B,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAuC7G,MAAM,SAAS,GAAG,CAAC,CAAC;AACpB,MAAM,MAAM,GAAG,CAAC,CAAC;AACjB,6FAA6F;AAC7F,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC;AAWlD,MAAM,CAAC,MAAM,WAAW,GAAG,GAAkB,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,IAAI,GAAG,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC;AAEtG,MAAM,KAAK,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;AAClG,MAAM,IAAI,GAAG,CAAC,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AC,IAAI;oBAAE,MAAM,IAAI,KAAK,CAAC,iBAAiB,QAAQ,CAAC,MAAM,GAAG,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;gBAChJ,MAAM,IAAI,GAAa,EAAE,MAAM,EAAE,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,UAAU,CAAC,KAAK,EAAE,EAAE,CAAC;gBAChH,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;gBAC1B,KAAK,CAAC,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC;YAChD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;YACxF,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { type JsonObject, create } from \"@bufbuild/protobuf\";\nimport { type AgentBackend, type AgentEvent, type DescribesAgents, agentEvent, errorEvent, extractSurfaces, turnText } from \"@surfaces-ui/agent\";\nimport { AgentInfoSchema, ApprovalKind, DescribeAgentsResponseSchema, StepStatus } from \"@surfaces-ui/proto\";\n\n/**\n * One event from Loom's `POST /v1/weave:stream`, as its HTTP gateway writes\n * it: the `WeaveProgress` message in JSON with snake_case names and numeric\n * enums. Only the fields this adapter reads are listed. Nothing from Loom is\n * vendored; this describes its public wire format.\n */\nexport interface LoomProgress {\n /** 7 is completed, 8 is failed. An error frame carries the text \"EXECUTION_STAGE_FAILED\". */\n stage?: number | string;\n message?: string;\n /** Set on a frame the gateway writes when the call itself fails. */\n error?: string;\n /** The reply so far (accumulated, not a delta) while `is_token_stream` is set. */\n partial_content?: string;\n is_token_stream?: boolean;\n tool_name?: string;\n tool_call_id?: string;\n is_tool_started?: boolean;\n is_tool_completed?: boolean;\n tool_input?: Record<string, unknown>;\n tool_error?: string;\n tool_success?: boolean;\n tool_duration_ms?: number | string;\n hitl_request?: {\n request_id?: string;\n question_id?: string;\n question?: string;\n request_type?: string;\n kind?: string;\n summary?: string;\n options?: string[];\n params_json?: string;\n };\n cost?: { total_cost_usd?: number; llm_cost?: { input_tokens?: number; output_tokens?: number; model?: string } };\n context_state?: { context_tokens_used?: number | string; context_tokens_max?: number | string };\n}\n\nconst COMPLETED = 7;\nconst FAILED = 8;\n/** Tools whose input is a list of A2UI messages to draw, not something to show as a step. */\nconst SURFACE_TOOLS = new Set([\"render_surface\"]);\n\nexport interface LoomTurnState {\n /** Reply text already passed on, to turn Loom's accumulated text into deltas. */\n text: string;\n model: string;\n /** Maps a Loom question to the tool step numbering, so repeated frames are not repeated here. */\n asked: Set<string>;\n steps: number;\n}\n\nexport const newLoomTurn = (): LoomTurnState => ({ text: \"\", model: \"\", asked: new Set(), steps: 0 });\n\nconst words = (tool: string) => tool.replace(/[_-]+/g, \" \").replace(/^./, (c) => c.toUpperCase());\nconst clip = (text: string, max = 4000) => (text.length > max ? `${text.slice(0, max)}…` : text);\n\n/**\n * Turns one Loom progress event into the events a chat shows. Pure: the\n * turn's running state is passed in and updated, so a recorded stream can be\n * replayed in tests.\n */\nexport function mapLoomProgress(frame: LoomProgress, state: LoomTurnState, sessionId: string): AgentEvent[] {\n const out: AgentEvent[] = [];\n if (frame.error) return [agentEvent.error(\"FAILED\", frame.error)];\n\n if (typeof frame.partial_content === \"string\" && frame.partial_content !== \"\" && (frame.is_token_stream || frame.stage === COMPLETED)) {\n const all = frame.partial_content;\n // Loom sends the whole reply so far each time; only what is new is passed on.\n const delta = all.startsWith(state.text) ? all.slice(state.text.length) : all;\n if (delta) out.push(agentEvent.text(delta));\n state.text = all;\n }\n\n const tool = frame.tool_name ?? \"\";\n const stepId = frame.tool_call_id || (tool ? `${tool}#${state.steps}` : \"\");\n if (frame.is_tool_started && tool) {\n const messages = SURFACE_TOOLS.has(tool) ? frame.tool_input?.messages : undefined;\n if (Array.isArray(messages)) {\n for (const message of messages) if (message && typeof message === \"object\") out.push(agentEvent.surface(message as JsonObject));\n } else {\n const sql = typeof frame.tool_input?.sql === \"string\" ? frame.tool_input.sql : undefined;\n out.push(agentEvent.step({ id: stepId, title: words(tool), status: StepStatus.RUNNING, tool, detail: clip(sql ?? (frame.tool_input ? JSON.stringify(frame.tool_input, null, 2) : \"\")) }));\n }\n }\n if (frame.is_tool_completed && tool && !SURFACE_TOOLS.has(tool)) {\n const failed = Boolean(frame.tool_error) || frame.tool_success === false;\n out.push(\n agentEvent.step({\n id: stepId,\n title: words(tool),\n status: failed ? StepStatus.FAILED : StepStatus.DONE,\n tool,\n detail: frame.tool_error ? clip(frame.tool_error) : \"\",\n durationMs: BigInt(Math.max(0, Math.round(Number(frame.tool_duration_ms ?? 0)))),\n }),\n );\n if (!frame.tool_call_id) state.steps++;\n }\n\n const ask = frame.hitl_request;\n // An empty request_id is only a hint that a question is coming; the one that can be answered follows.\n const askId = ask?.question_id || ask?.request_id || \"\";\n if (ask && ask.request_id && !state.asked.has(askId)) {\n state.asked.add(askId);\n const options = ask.options ?? [];\n const kind = options.length > 0 ? ApprovalKind.CHOICE : /approv|permission|confirm/i.test(`${ask.request_type ?? \"\"} ${ask.kind ?? \"\"}`) ? ApprovalKind.PERMISSION : ApprovalKind.INPUT;\n let sql = \"\";\n try {\n const params = ask.params_json ? (JSON.parse(ask.params_json) as Record<string, unknown>) : {};\n if (typeof params.sql === \"string\") sql = params.sql;\n } catch {\n // Parameters are optional context; a question without them is still a question.\n }\n out.push(agentEvent.approval({ id: askId, kind, title: ask.question ?? \"The agent has a question.\", detail: ask.summary ?? \"\", sql, options }));\n }\n\n if (frame.cost?.llm_cost?.model) state.model = frame.cost.llm_cost.model;\n if (frame.cost || frame.context_state) {\n out.push(\n agentEvent.usage({\n inputTokens: BigInt(frame.cost?.llm_cost?.input_tokens ?? 0),\n outputTokens: BigInt(frame.cost?.llm_cost?.output_tokens ?? 0),\n contextTokens: BigInt(Number(frame.context_state?.context_tokens_used ?? 0)),\n contextLimit: BigInt(Number(frame.context_state?.context_tokens_max ?? 0)),\n costUsd: frame.cost?.total_cost_usd,\n }),\n );\n }\n\n if (frame.stage === FAILED || frame.stage === \"EXECUTION_STAGE_FAILED\") out.push(agentEvent.error(\"FAILED\", frame.message || \"The agent could not finish.\"));\n if (frame.stage === COMPLETED) out.push(agentEvent.done(sessionId, state.model ? `Loom · ${state.model}` : \"Loom\"));\n return out;\n}\n\n/** Reads `data:` lines from a server-sent event stream as JSON. Comment lines (heartbeats) are skipped. */\nexport async function* readSse(body: ReadableStream<Uint8Array>): AsyncGenerator<LoomProgress> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let pending = \"\";\n try {\n for (;;) {\n const { done, value } = await reader.read();\n pending += done ? decoder.decode() : decoder.decode(value, { stream: true });\n const lines = pending.split(/\\r?\\n/);\n pending = done ? \"\" : (lines.pop() ?? \"\");\n for (const line of lines) {\n if (!line.startsWith(\"data:\")) continue;\n const payload = line.slice(5).trim();\n if (!payload) continue;\n try {\n yield JSON.parse(payload) as LoomProgress;\n } catch {\n // A frame that is not JSON is skipped; the stream carries on.\n }\n }\n if (done) return;\n }\n } finally {\n await reader.cancel().catch(() => {});\n }\n}\n\nexport interface LoomAgentOptions {\n /** Where the Loom server's HTTP gateway is, e.g. http://localhost:5006. */\n baseUrl: string;\n /** Supplies a bearer token per request. The token is the host's to manage; it is never stored here. */\n token?(): string | Promise<string>;\n /** Extra headers, e.g. for a proxy. */\n headers?: Record<string, string>;\n /** Uses this instead of the global `fetch`. */\n fetch?: typeof fetch;\n}\n\n/**\n * A Loom model as a chat names it: `provider/model` (`anthropic/claude-opus-5-5`,\n * `ollama/qwen3:8b`), since Loom switches a session by both. The provider\n * part never holds a slash.\n */\nexport const loomModelId = (provider: string, model: string) => (provider ? `${provider}/${model}` : model);\nexport function splitLoomModel(id: string): { provider: string; model: string } {\n const at = id.indexOf(\"/\");\n return at < 0 ? { provider: \"\", model: id } : { provider: id.slice(0, at), model: id.slice(at + 1) };\n}\n\ninterface OpenTurn {\n frames: AsyncGenerator<LoomProgress>;\n state: LoomTurnState;\n stop(): void;\n}\n\n/**\n * An AgentBackend that talks to a Loom server. Loom stays a separate\n * program: this adapter only calls its HTTP gateway, so nothing from Loom is\n * built into or shipped with this library.\n *\n * - A turn is `POST /v1/weave:stream`; replies, tool calls, questions and\n * usage are mapped to chat events.\n * - When Loom asks the person something, the turn pauses. Answering posts to\n * `/v1/clarifications/{session}/answer` and carries on reading the same\n * stream.\n * - A Loom agent draws UI by calling a `render_surface` tool (as the\n * Surfaces MCP server provides) or by writing an `a2ui` fenced block.\n */\nexport function loomAgent(options: LoomAgentOptions): AgentBackend & DescribesAgents {\n const call = options.fetch ?? fetch;\n const base = options.baseUrl.replace(/\\/+$/, \"\");\n const open = new Map<string, OpenTurn>();\n // The model each session was last switched to here, so a turn switches only when the choice changed.\n const switched = new Map<string, string>();\n\n const headers = async (accept: string) => {\n const token = await options.token?.();\n return {\n \"Content-Type\": \"application/json\",\n Accept: accept,\n // Marks the turn as started by a person, so Loom does not treat a retry as a duplicate background run.\n \"X-Loom-Slot-Origin\": \"interactive\",\n ...(token ? { Authorization: `Bearer ${token}` } : {}),\n ...options.headers,\n };\n };\n\n const createSession = async (agentId: string, signal?: AbortSignal): Promise<string> => {\n try {\n const response = await call(`${base}/v1/sessions`, { method: \"POST\", headers: await headers(\"application/json\"), body: JSON.stringify({ agent_id: agentId }), signal });\n if (response.ok) {\n const session = (await response.json()) as { id?: string };\n if (session.id) return session.id;\n }\n } catch {\n // Fall through: Loom also accepts an ID chosen by the client.\n }\n return crypto.randomUUID();\n };\n\n async function* pump(turn: OpenTurn, sessionId: string): AsyncGenerator<AgentEvent> {\n for (;;) {\n const next = await turn.frames.next();\n if (next.done) {\n open.delete(sessionId);\n // The stream ended without a completed stage: still tell the chat the turn is over.\n yield agentEvent.done(sessionId, turn.state.model ? `Loom · ${turn.state.model}` : \"Loom\");\n return;\n }\n const events = mapLoomProgress(next.value, turn.state, sessionId);\n yield* events;\n const last = events.at(-1)?.event.case;\n if (last === \"done\" || last === \"error\") {\n open.delete(sessionId);\n // The reply is complete: close the reader. Aborting a finished request would raise in callers that share its body.\n await turn.frames.return(undefined);\n return;\n }\n // The agent is waiting for an answer: this turn pauses with the stream left open.\n if (events.some((e) => e.event.case === \"approval\")) return;\n }\n }\n\n const getJson = async (path: string) => {\n const response = await call(`${base}${path}`, { headers: await headers(\"application/json\") });\n if (!response.ok) throw new Error(`Loom answered ${response.status} for ${path}.`);\n return (await response.json()) as unknown;\n };\n\n return {\n /**\n * Loom's agents, each offering the models Loom can run (`GET /v1/agents`,\n * `GET /v1/models`). A server that does not list models offers none, and a\n * turn then runs on the agent's own.\n */\n async describeAgents() {\n const [agents, models] = await Promise.all([\n getJson(\"/v1/agents\").then((body) => (body as { agents?: { id?: string; name?: string; metadata?: { description?: string } }[] }).agents ?? []),\n getJson(\"/v1/models\").then(\n (body) => (body as { models?: { id?: string; name?: string; provider?: string }[] }).models ?? [],\n () => [],\n ),\n ]);\n const options = models.filter((m) => m.id).map((m) => ({ id: loomModelId(m.provider ?? \"\", m.id!), label: m.name || m.id!, description: m.provider ?? \"\" }));\n return create(DescribeAgentsResponseSchema, {\n agents: agents.map((a, i) =>\n create(AgentInfoSchema, { id: a.name || a.id || \"\", name: a.name || a.id || \"\", description: a.metadata?.description ?? \"\", isDefault: i === 0, models: options }),\n ),\n });\n },\n async *send(request, callOptions) {\n const signal = callOptions?.signal;\n // A listener added to a signal that has already fired never runs, so a turn stopped before it began is caught here.\n if (signal?.aborted) {\n yield agentEvent.error(\"CANCELLED\", \"Stopped.\");\n return;\n }\n try {\n const input = request.input;\n const sessionId = request.sessionId || (await createSession(request.agentId ?? \"\", signal));\n const waiting = open.get(sessionId);\n\n if (input?.case === \"approval\" && waiting) {\n const answer = input.value.answer || (input.value.allow ? \"approved\" : \"denied\");\n const response = await call(`${base}/v1/clarifications/${encodeURIComponent(sessionId)}/answer`, {\n method: \"POST\",\n headers: await headers(\"application/json\"),\n body: JSON.stringify({ session_id: sessionId, question_id: input.value.id, answer, agent_id: request.agentId ?? \"\" }),\n signal,\n });\n if (!response.ok) throw new Error(`Loom did not accept the answer (${response.status}).`);\n signal?.addEventListener(\"abort\", () => (open.delete(sessionId), waiting.stop()), { once: true });\n yield* extractSurfaces(pump(waiting, sessionId));\n return;\n }\n // Anything else starts a new turn; a paused one is dropped.\n if (waiting) {\n open.delete(sessionId);\n waiting.stop();\n }\n\n // A model the person picked: Loom switches the session to it, keeping the conversation, before this turn.\n const model = request.model ?? \"\";\n if (model && switched.get(sessionId) !== model) {\n const { provider, model: name } = splitLoomModel(model);\n const switching = await call(`${base}/v1/sessions/${encodeURIComponent(sessionId)}:switch-model`, {\n method: \"POST\",\n headers: await headers(\"application/json\"),\n body: JSON.stringify({ session_id: sessionId, agent_id: request.agentId ?? \"\", provider, model: name, preserve_context: true }),\n signal,\n });\n if (!switching.ok) throw new Error(`Loom could not switch to ${model} (${switching.status}).`);\n switched.set(sessionId, model);\n }\n\n // The event, the page's state, the agent's own contracts and any problems, as text Loom passes to the model.\n const query = turnText(request);\n const controller = new AbortController();\n signal?.addEventListener(\"abort\", () => controller.abort(), { once: true });\n const response = await call(`${base}/v1/weave:stream`, {\n method: \"POST\",\n headers: await headers(\"text/event-stream\"),\n body: JSON.stringify({\n query,\n session_id: sessionId,\n agent_id: request.agentId ?? \"\",\n context: request.contextPackId ? { context_pack_id: request.contextPackId } : undefined,\n }),\n signal: controller.signal,\n });\n if (!response.ok || !response.body) throw new Error(`Loom answered ${response.status}${response.statusText ? ` ${response.statusText}` : \"\"}.`);\n const turn: OpenTurn = { frames: readSse(response.body), state: newLoomTurn(), stop: () => controller.abort() };\n open.set(sessionId, turn);\n yield* extractSurfaces(pump(turn, sessionId));\n } catch (error) {\n yield signal?.aborted ? agentEvent.error(\"CANCELLED\", \"Stopped.\") : errorEvent(error);\n }\n },\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@surfaces-ui/agent-loom",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "Loom adapter for Surfaces UI chat: talks to a Loom server over its HTTP gateway",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"surfaces-ui",
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"url": "git+https://github.com/teradata-labs/surfaces-ui.git",
|
|
16
16
|
"directory": "packages/agent-loom"
|
|
17
17
|
},
|
|
18
|
-
"homepage": "https://
|
|
18
|
+
"homepage": "https://surfaces-ui.com",
|
|
19
19
|
"bugs": {
|
|
20
20
|
"url": "https://github.com/teradata-labs/surfaces-ui/issues"
|
|
21
21
|
},
|
|
@@ -35,13 +35,16 @@
|
|
|
35
35
|
],
|
|
36
36
|
"dependencies": {
|
|
37
37
|
"@bufbuild/protobuf": "^2.17.0",
|
|
38
|
-
"@surfaces-ui/agent": "0.
|
|
39
|
-
"@surfaces-ui/proto": "0.
|
|
38
|
+
"@surfaces-ui/agent": "0.8.0",
|
|
39
|
+
"@surfaces-ui/proto": "0.8.0"
|
|
40
40
|
},
|
|
41
41
|
"publishConfig": {
|
|
42
42
|
"access": "public",
|
|
43
43
|
"provenance": true
|
|
44
44
|
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@surfaces-ui/data": "0.8.0"
|
|
47
|
+
},
|
|
45
48
|
"scripts": {
|
|
46
49
|
"build": "tsc -p tsconfig.build.json",
|
|
47
50
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|