@surfaces-ui/chat 0.3.0 → 0.5.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.
@@ -1 +1 @@
1
- {"version":3,"file":"thread.js","sourceRoot":"","sources":["../src/thread.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EAAoD,YAAY,EAAE,gBAAgB,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AA+JrJ,MAAM,CAAC,MAAM,WAAW,GAAe,EAAE,QAAQ,EAAE,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE,EAAE,CAAC;AAEtH,MAAM,WAAW,GAAoD;IACnE,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,SAAS;IAC/B,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,MAAM;IACzB,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,QAAQ;CAC9B,CAAC;AACF,MAAM,aAAa,GAAwD;IACzE,CAAC,YAAY,CAAC,UAAU,CAAC,EAAE,YAAY;IACvC,CAAC,YAAY,CAAC,MAAM,CAAC,EAAE,QAAQ;IAC/B,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE,OAAO;CAC9B,CAAC;AAEF,MAAM,aAAa,GAAwD;IACzE,CAAC,YAAY,CAAC,GAAG,CAAC,EAAE,KAAK;IACzB,CAAC,YAAY,CAAC,IAAI,CAAC,EAAE,MAAM;IAC3B,CAAC,YAAY,CAAC,YAAY,CAAC,EAAE,cAAc;CAC5C,CAAC;AAEF,MAAM,KAAK,GAAG,GAAG,CAAC;AAClB,uFAAuF;AACvF,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,SAAiB,EAAE,SAAiB,EAAE,EAAE,CAAC,IAAI,SAAS,GA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AE,KAAK,EAAE,KAAK,CAAC,KAA6B,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAChF,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,EAAe,EAAE,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE;KACzH,CAAC;AACJ,CAAC","sourcesContent":["import type { AgentEvent } from \"@surfaces-ui/agent\";\nimport type { JsonObject } from \"@bufbuild/protobuf\";\nimport { ApprovalKind, ApprovalRisk, StepStatus } from \"@surfaces-ui/proto\";\nimport { type Catalog, type SurfaceMessage, type Surfaces, applyMessage, isComponentIssue, upgradeMessage, upgradeSurface } from \"@surfaces-ui/spec\";\nimport type { DataRef } from \"@surfaces-ui/components\";\n\nexport interface ChatStep {\n id: string;\n title: string;\n status: \"running\" | \"done\" | \"failed\";\n tool: string;\n /** More to show when opened: the SQL run, an error message. */\n detail: string;\n durationMs: number;\n}\n\nexport interface ChatApproval {\n id: string;\n kind: \"permission\" | \"choice\" | \"input\";\n title: string;\n detail: string;\n /** SQL the agent wants to run, when that is what needs approval. */\n sql: string;\n options: string[];\n /** What exactly is being approved, shown as JSON. */\n subject?: JsonObject;\n /** \"sha256:…\" of `{ sql, subject }`; the card refuses to offer approval when it does not match. */\n digest: string;\n /** ISO time after which it cannot be approved. Empty for no limit. */\n expiresAt: string;\n risk: \"low\" | \"high\" | \"irreversible\" | \"\";\n /** The person may change the SQL or subject before approving. */\n editable: boolean;\n reasonRequired: boolean;\n /** Different people who must allow it. */\n approvalsRequired: number;\n /** Decisions already made, when several people must decide. */\n approvals: ChatDecision[];\n /** What the request was based on, for the person to see. */\n basis: string;\n /** Set once the person has answered. */\n answer?: ChatApprovalAnswer;\n}\n\n/** Who decided, as the host identified them. */\nexport interface ChatActor {\n id: string;\n name: string;\n}\n\nexport interface ChatDecision {\n by?: ChatActor;\n /** ISO time. */\n at: string;\n allow: boolean;\n reason: string;\n}\n\nexport interface ChatApprovalAnswer extends ChatDecision {\n /** The chosen option or typed answer. */\n text: string;\n /** \"sha256:…\" of what was approved, edits included. */\n digest: string;\n editedSql?: string;\n editedSubject?: JsonObject;\n}\n\n/** One button in an actions part. What a press does is the host's to decide. */\nexport interface ChatButton {\n /** Reaches the host with the press; need only be unique within its row. */\n id: string;\n label: string;\n /** \"primary\" for the one thing most people will do; \"danger\" for what cannot be taken back. */\n variant?: \"primary\" | \"danger\";\n /** Shown but cannot be pressed. It stays reachable by keyboard so its reason can be read. */\n disabled?: boolean;\n /** Why it cannot be pressed (or, when it can, what it does). Its tooltip, and read with it. */\n reason?: string;\n /** A fuller name when the label alone is ambiguous: \"Apply “Bold” from the chat\". */\n ariaLabel?: string;\n}\n\n/** One of several alternatives in an actions part, with buttons of its own. */\nexport interface ChatChoice {\n id: string;\n title: string;\n detail?: string;\n buttons: ChatButton[];\n}\n\n/**\n * What a person can do about a reply, drawn under it: one set of buttons\n * (\"Show on the page\", \"Discard\", \"Apply\"), or several alternatives one row\n * each with buttons for the whole set after them (\"Discard all\"). Presses go\n * to `MessageList`'s `onPartAction`. Once handled, the host sets `outcome`,\n * which replaces every button.\n */\nexport interface ChatActions {\n id: string;\n title?: string;\n detail?: string;\n /** Alternatives to choose between, one row each. */\n choices?: ChatChoice[];\n /** Buttons for the whole set, after any choices. */\n buttons?: ChatButton[];\n /** What became of it (\"Applied.\", \"Discarded.\"). Replaces the buttons. */\n outcome?: string;\n}\n\n/** One piece of a reply, in the order it arrived. */\nexport type ChatPart =\n | { kind: \"text\"; text: string }\n /** Tables and columns a person attached to their message, by name. */\n | { kind: \"references\"; references: DataRef[] }\n | { kind: \"steps\"; steps: ChatStep[] }\n /** A component the agent drew. `surfaceId` is the key into `ChatThread.surfaces`. */\n | { kind: \"surface\"; surfaceId: string }\n | { kind: \"approval\"; approval: ChatApproval }\n /** Buttons the host offers under a reply. Added by the host, never by an agent's events. */\n | { kind: \"actions\"; actions: ChatActions }\n | { kind: \"error\"; code: string; message: string };\n\nexport interface ChatMessage {\n id: number;\n role: \"user\" | \"assistant\";\n parts: ChatPart[];\n /** The model or agent that answered. Always shown. */\n generatedBy: string;\n streaming: boolean;\n}\n\nexport interface ChatUsage {\n inputTokens: number;\n outputTokens: number;\n contextTokens: number;\n contextLimit: number;\n costUsd?: number;\n}\n\nexport interface ChatThread {\n messages: ChatMessage[];\n /** Agent-drawn surfaces, keyed by message and the agent's own surface ID. */\n surfaces: Surfaces;\n /** \"waiting\" means the agent paused for the person's answer. */\n status: \"idle\" | \"streaming\" | \"waiting\";\n sessionId: string;\n usage?: ChatUsage;\n /** Things the person might say next. */\n suggestions: string[];\n}\n\nexport type ChatAction =\n | { type: \"user\"; text: string; references?: DataRef[] }\n /** A turn has started; the reply is added to the latest assistant message when `resume` is set. */\n | { type: \"begin\"; resume?: boolean }\n | { type: \"event\"; event: AgentEvent }\n | { type: \"answered\"; id: string; answer: ChatApprovalAnswer }\n | { type: \"end\" }\n | { type: \"reset\" }\n /** Replaces the thread with one loaded from storage (checked with `parseThread` first). */\n | { type: \"restore\"; thread: ChatThread };\n\nexport const emptyThread: ChatThread = { messages: [], surfaces: {}, status: \"idle\", sessionId: \"\", suggestions: [] };\n\nconst STEP_STATUS: Partial<Record<StepStatus, ChatStep[\"status\"]>> = {\n [StepStatus.RUNNING]: \"running\",\n [StepStatus.DONE]: \"done\",\n [StepStatus.FAILED]: \"failed\",\n};\nconst APPROVAL_KIND: Partial<Record<ApprovalKind, ChatApproval[\"kind\"]>> = {\n [ApprovalKind.PERMISSION]: \"permission\",\n [ApprovalKind.CHOICE]: \"choice\",\n [ApprovalKind.INPUT]: \"input\",\n};\n\nconst APPROVAL_RISK: Partial<Record<ApprovalRisk, ChatApproval[\"risk\"]>> = {\n [ApprovalRisk.LOW]: \"low\",\n [ApprovalRisk.HIGH]: \"high\",\n [ApprovalRisk.IRREVERSIBLE]: \"irreversible\",\n};\n\nconst SCOPE = \":\";\n/** The key a message's surface is stored under, so two replies can both use \"main\". */\nexport const surfaceKey = (messageId: number, surfaceId: string) => `m${messageId}${SCOPE}${surfaceId}`;\n/** The agent's own ID for a stored surface, to send back with an action. */\nexport const agentSurfaceId = (key: string) => key.slice(key.indexOf(SCOPE) + 1);\n\nfunction updateLast(thread: ChatThread, change: (message: ChatMessage) => ChatMessage): ChatThread {\n const index = thread.messages.findLastIndex((m) => m.role === \"assistant\");\n if (index < 0) return thread;\n return { ...thread, messages: thread.messages.map((m, i) => (i === index ? change(m) : m)) };\n}\n\nfunction withPart(message: ChatMessage, part: ChatPart): ChatMessage {\n return { ...message, parts: [...message.parts, part] };\n}\n\nfunction applySurface(thread: ChatThread, raw: unknown, catalog: Catalog): ChatThread {\n const message = thread.messages.findLast((m) => m.role === \"assistant\");\n if (!message) return thread;\n const fail = (text: string) => updateLast(thread, (m) => withPart(m, { kind: \"error\", code: \"INVALID_SURFACE\", message: text }));\n // A malformed envelope is refused; a malformed component is applied and reported where it is drawn.\n const fatal = catalog.validateMessage(raw).filter((issue) => !isComponentIssue(issue));\n if (fatal.length > 0) return fail(`The agent sent a view this page cannot draw: ${fatal[0]!.path} ${fatal[0]!.message}`);\n // What is kept is in the current version, whichever the agent wrote.\n const record = upgradeMessage(raw) as Record<string, { surfaceId: string }>;\n const kind = ([\"createSurface\", \"updateComponents\", \"updateDataModel\", \"deleteSurface\"] as const).find((k) => record[k]);\n if (!kind) return thread;\n const key = surfaceKey(message.id, record[kind]!.surfaceId);\n const scoped = { ...record, [kind]: { ...record[kind], surfaceId: key } } as unknown as SurfaceMessage;\n try {\n const surfaces = applyMessage(thread.surfaces, scoped);\n const shown = message.parts.some((p) => p.kind === \"surface\" && p.surfaceId === key);\n const next = { ...thread, surfaces };\n return kind === \"createSurface\" && !shown ? updateLast(next, (m) => withPart(m, { kind: \"surface\", surfaceId: key })) : next;\n } catch (error) {\n return fail(error instanceof Error ? error.message : String(error));\n }\n}\n\n/**\n * Folds user input and agent events into a thread. Pure: the same actions\n * always give the same thread, so a conversation can be replayed in tests.\n */\nexport function reduceThread(thread: ChatThread, action: ChatAction, catalog: Catalog): ChatThread {\n const nextId = (thread.messages.at(-1)?.id ?? 0) + 1;\n switch (action.type) {\n case \"reset\":\n return emptyThread;\n case \"restore\":\n return action.thread;\n case \"user\":\n return {\n ...thread,\n suggestions: [],\n messages: [\n ...thread.messages,\n { id: nextId, role: \"user\", parts: [{ kind: \"text\", text: action.text }, ...(action.references?.length ? [{ kind: \"references\" as const, references: action.references }] : [])], generatedBy: \"\", streaming: false },\n ],\n };\n case \"begin\": {\n const last = thread.messages.at(-1);\n if (action.resume && last?.role === \"assistant\") {\n return { ...updateLast(thread, (m) => ({ ...m, streaming: true })), status: \"streaming\", suggestions: [] };\n }\n return {\n ...thread,\n status: \"streaming\",\n suggestions: [],\n messages: [...thread.messages, { id: nextId, role: \"assistant\", parts: [], generatedBy: \"\", streaming: true }],\n };\n }\n case \"answered\":\n return {\n ...thread,\n messages: thread.messages.map((m) => ({\n ...m,\n parts: m.parts.map((p) =>\n p.kind === \"approval\" && p.approval.id === action.id ? { ...p, approval: { ...p.approval, answer: action.answer } } : p,\n ),\n })),\n };\n case \"end\": {\n const waiting = thread.messages.at(-1)?.parts.some((p) => p.kind === \"approval\" && !p.approval.answer) ?? false;\n return { ...updateLast(thread, (m) => ({ ...m, streaming: false })), status: waiting ? \"waiting\" : \"idle\" };\n }\n case \"event\": {\n const event = action.event.event;\n switch (event.case) {\n case \"text\":\n return updateLast(thread, (m) => {\n const last = m.parts.at(-1);\n if (last?.kind === \"text\") return { ...m, parts: [...m.parts.slice(0, -1), { kind: \"text\", text: last.text + event.value.delta }] };\n return withPart(m, { kind: \"text\", text: event.value.delta });\n });\n case \"step\": {\n const step: ChatStep = {\n id: event.value.id,\n title: event.value.title,\n status: STEP_STATUS[event.value.status] ?? \"running\",\n tool: event.value.tool,\n detail: event.value.detail,\n durationMs: Number(event.value.durationMs),\n };\n return updateLast(thread, (m) => {\n // An event for a step already shown updates it in place.\n if (m.parts.some((p) => p.kind === \"steps\" && p.steps.some((s) => s.id === step.id))) {\n return {\n ...m,\n parts: m.parts.map((p) =>\n p.kind === \"steps\" ? { ...p, steps: p.steps.map((s) => (s.id === step.id ? { ...s, ...step, title: step.title || s.title, detail: step.detail || s.detail } : s)) } : p,\n ),\n };\n }\n const last = m.parts.at(-1);\n if (last?.kind === \"steps\") return { ...m, parts: [...m.parts.slice(0, -1), { kind: \"steps\", steps: [...last.steps, step] }] };\n return withPart(m, { kind: \"steps\", steps: [step] });\n });\n }\n case \"surface\":\n return applySurface(thread, event.value, catalog);\n case \"approval\": {\n const approval: ChatApproval = {\n id: event.value.id,\n kind: APPROVAL_KIND[event.value.kind] ?? \"permission\",\n title: event.value.title,\n detail: event.value.detail,\n sql: event.value.sql,\n options: event.value.options,\n ...(event.value.subject ? { subject: event.value.subject } : {}),\n digest: event.value.digest,\n expiresAt: event.value.expiresAt,\n risk: APPROVAL_RISK[event.value.risk] ?? \"\",\n editable: event.value.editable,\n reasonRequired: event.value.reasonRequired,\n approvalsRequired: Math.max(1, event.value.approvalsRequired),\n approvals: event.value.approvals.map((r) => ({\n ...(r.decidedBy ? { by: { id: r.decidedBy.id, name: r.decidedBy.name } } : {}),\n at: r.decidedAt,\n allow: r.allow,\n reason: r.reason,\n })),\n basis: event.value.basis,\n };\n return updateLast(thread, (m) => withPart(m, { kind: \"approval\", approval }));\n }\n case \"usage\":\n return {\n ...thread,\n usage: {\n inputTokens: Number(event.value.inputTokens),\n outputTokens: Number(event.value.outputTokens),\n contextTokens: Number(event.value.contextTokens),\n contextLimit: Number(event.value.contextLimit),\n costUsd: event.value.costUsd,\n },\n };\n case \"suggestions\":\n return { ...thread, suggestions: event.value.items };\n case \"error\":\n return updateLast(thread, (m) => withPart(m, { kind: \"error\", code: event.value.code, message: event.value.message }));\n case \"done\":\n return { ...updateLast(thread, (m) => ({ ...m, generatedBy: event.value.generatedBy || m.generatedBy })), sessionId: event.value.sessionId || thread.sessionId };\n default:\n return thread;\n }\n }\n }\n}\n\nconst PART_KINDS = new Set([\"text\", \"references\", \"steps\", \"surface\", \"approval\", \"actions\", \"error\"]);\nconst isRecord = (value: unknown): value is Record<string, unknown> => !!value && typeof value === \"object\" && !Array.isArray(value);\n\n/**\n * Checks a thread loaded from storage before it is used, since anyone with\n * access to the storage can edit it. Returns undefined for anything that is\n * not a thread. A reply that was still streaming when the page closed is\n * marked as cut off; an approval nobody answered is still waiting. Surfaces\n * are checked against the catalog again when they are drawn.\n */\nexport function parseThread(input: unknown): ChatThread | undefined {\n if (!isRecord(input) || !Array.isArray(input.messages) || !isRecord(input.surfaces)) return undefined;\n const messages: ChatMessage[] = [];\n for (const raw of input.messages) {\n if (!isRecord(raw) || typeof raw.id !== \"number\" || (raw.role !== \"user\" && raw.role !== \"assistant\") || !Array.isArray(raw.parts)) return undefined;\n if (!raw.parts.every((p) => isRecord(p) && PART_KINDS.has(p.kind as string))) return undefined;\n const parts = raw.parts as ChatPart[];\n const cut = raw.streaming === true;\n messages.push({\n id: raw.id,\n role: raw.role,\n parts: cut ? [...parts, { kind: \"error\", code: \"INTERRUPTED\", message: \"This reply was cut off when the page closed.\" }] : parts,\n generatedBy: typeof raw.generatedBy === \"string\" ? raw.generatedBy : \"\",\n streaming: false,\n });\n }\n const waiting = messages.at(-1)?.parts.some((p) => p.kind === \"approval\" && !p.approval.answer) ?? false;\n return {\n messages,\n // A thread kept before the move to A2UI v1.0 holds surfaces written for v0.9.\n surfaces: Object.fromEntries(Object.entries(input.surfaces as ChatThread[\"surfaces\"]).map(([key, surface]) => [key, isRecord(surface) && isRecord(surface.components) ? upgradeSurface(surface) : surface])),\n status: waiting ? \"waiting\" : \"idle\",\n sessionId: typeof input.sessionId === \"string\" ? input.sessionId : \"\",\n ...(isRecord(input.usage) ? { usage: input.usage as unknown as ChatUsage } : {}),\n suggestions: Array.isArray(input.suggestions) ? input.suggestions.filter((s): s is string => typeof s === \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C,CAAC,EAAE;QACrE,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,KAA6B,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAChF,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,EAAe,EAAE,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE;KACzH,CAAC;AACJ,CAAC","sourcesContent":["import type { AgentEvent } from \"@surfaces-ui/agent\";\nimport type { JsonObject } from \"@bufbuild/protobuf\";\nimport { ApprovalKind, ApprovalRisk, StepStatus } from \"@surfaces-ui/proto\";\nimport { type Catalog, type SurfaceMessage, type Surfaces, applyMessage, isComponentIssue, upgradeMessage, upgradeSurface } from \"@surfaces-ui/spec\";\nimport type { DataRef } from \"@surfaces-ui/components\";\n\nexport interface ChatStep {\n id: string;\n title: string;\n status: \"running\" | \"done\" | \"failed\";\n tool: string;\n /** More to show when opened: the SQL run, an error message. */\n detail: string;\n durationMs: number;\n}\n\nexport interface ChatApproval {\n id: string;\n kind: \"permission\" | \"choice\" | \"input\";\n title: string;\n detail: string;\n /** SQL the agent wants to run, when that is what needs approval. */\n sql: string;\n options: string[];\n /** What exactly is being approved, shown as JSON. */\n subject?: JsonObject;\n /** \"sha256:…\" of `{ sql, subject }`; the card refuses to offer approval when it does not match. */\n digest: string;\n /** ISO time after which it cannot be approved. Empty for no limit. */\n expiresAt: string;\n risk: \"low\" | \"high\" | \"irreversible\" | \"\";\n /** The person may change the SQL or subject before approving. */\n editable: boolean;\n reasonRequired: boolean;\n /** Different people who must allow it. */\n approvalsRequired: number;\n /** Decisions already made, when several people must decide. */\n approvals: ChatDecision[];\n /** What the request was based on, for the person to see. */\n basis: string;\n /** Set once the person has answered. */\n answer?: ChatApprovalAnswer;\n}\n\n/** Who decided, as the host identified them. */\nexport interface ChatActor {\n id: string;\n name: string;\n}\n\nexport interface ChatDecision {\n by?: ChatActor;\n /** ISO time. */\n at: string;\n allow: boolean;\n reason: string;\n}\n\nexport interface ChatApprovalAnswer extends ChatDecision {\n /** The chosen option or typed answer. */\n text: string;\n /** \"sha256:…\" of what was approved, edits included. */\n digest: string;\n editedSql?: string;\n editedSubject?: JsonObject;\n}\n\n/** One button in an actions part. What a press does is the host's to decide. */\nexport interface ChatButton {\n /** Reaches the host with the press; need only be unique within its row. */\n id: string;\n label: string;\n /** \"primary\" for the one thing most people will do; \"danger\" for what cannot be taken back. */\n variant?: \"primary\" | \"danger\";\n /** Shown but cannot be pressed. It stays reachable by keyboard so its reason can be read. */\n disabled?: boolean;\n /** Why it cannot be pressed (or, when it can, what it does). Its tooltip, and read with it. */\n reason?: string;\n /** A fuller name when the label alone is ambiguous: \"Apply “Bold” from the chat\". */\n ariaLabel?: string;\n}\n\n/** One of several alternatives in an actions part, with buttons of its own. */\nexport interface ChatChoice {\n id: string;\n title: string;\n detail?: string;\n buttons: ChatButton[];\n}\n\n/**\n * What a person can do about a reply, drawn under it: one set of buttons\n * (\"Show on the page\", \"Discard\", \"Apply\"), or several alternatives one row\n * each with buttons for the whole set after them (\"Discard all\"). Presses go\n * to `MessageList`'s `onPartAction`. Once handled, the host sets `outcome`,\n * which replaces every button.\n */\nexport interface ChatActions {\n id: string;\n title?: string;\n detail?: string;\n /** Alternatives to choose between, one row each. */\n choices?: ChatChoice[];\n /** Buttons for the whole set, after any choices. */\n buttons?: ChatButton[];\n /** What became of it (\"Applied.\", \"Discarded.\"). Replaces the buttons. */\n outcome?: string;\n}\n\n/**\n * Something a person attached to a message that is not a table or a file of data: a picture, usually. The host\n * keeps the bytes; the thread keeps this description, which is what the message list shows.\n */\nexport interface ChatAttachment {\n /** Tells it apart, and lets the host find what it kept. Default: the name. */\n id?: string;\n /** The file's name, shown under or beside the thumbnail. */\n name: string;\n /** Its media type, such as \"image/png\". A thumbnail is drawn only for an `image/*` type. */\n mediaType: string;\n /** Its size in bytes, when known. */\n size?: number;\n /**\n * An address a small picture of it can be drawn from (a `blob:` URL the host made, a raster `data:image/` URL, an\n * http(s) or same-origin address). It comes from the host, never from a model: nothing an agent wrote is put here, and\n * an address that is not one of those kinds is ignored. A blob URL does not outlive the page, so a thread kept\n * across reloads shows the name alone until the host supplies a preview again.\n */\n preview?: string;\n}\n\n/** One piece of a reply, in the order it arrived. */\nexport type ChatPart =\n | { kind: \"text\"; text: string }\n /** Tables and columns a person attached to their message, by name. */\n | { kind: \"references\"; references: DataRef[] }\n /** Pictures and other files a person attached to their message that are not data (`ChatAttachment`). */\n | { kind: \"attachments\"; attachments: ChatAttachment[] }\n | { kind: \"steps\"; steps: ChatStep[] }\n /** A component the agent drew. `surfaceId` is the key into `ChatThread.surfaces`. */\n | { kind: \"surface\"; surfaceId: string }\n | { kind: \"approval\"; approval: ChatApproval }\n /** Buttons the host offers under a reply. Added by the host, never by an agent's events. */\n | { kind: \"actions\"; actions: ChatActions }\n | { kind: \"error\"; code: string; message: string };\n\nexport interface ChatMessage {\n id: number;\n role: \"user\" | \"assistant\";\n parts: ChatPart[];\n /** The model or agent that answered. Always shown. */\n generatedBy: string;\n streaming: boolean;\n}\n\nexport interface ChatUsage {\n inputTokens: number;\n outputTokens: number;\n contextTokens: number;\n contextLimit: number;\n costUsd?: number;\n}\n\nexport interface ChatThread {\n messages: ChatMessage[];\n /** Agent-drawn surfaces, keyed by message and the agent's own surface ID. */\n surfaces: Surfaces;\n /** \"waiting\" means the agent paused for the person's answer. */\n status: \"idle\" | \"streaming\" | \"waiting\";\n sessionId: string;\n usage?: ChatUsage;\n /** Things the person might say next. */\n suggestions: string[];\n}\n\nexport type ChatAction =\n | { type: \"user\"; text: string; references?: DataRef[]; attachments?: ChatAttachment[] }\n /** A turn has started; the reply is added to the latest assistant message when `resume` is set. */\n | { type: \"begin\"; resume?: boolean }\n | { type: \"event\"; event: AgentEvent }\n | { type: \"answered\"; id: string; answer: ChatApprovalAnswer }\n | { type: \"end\" }\n | { type: \"reset\" }\n /** Replaces the thread with one loaded from storage (checked with `parseThread` first). */\n | { type: \"restore\"; thread: ChatThread };\n\nexport const emptyThread: ChatThread = { messages: [], surfaces: {}, status: \"idle\", sessionId: \"\", suggestions: [] };\n\nconst STEP_STATUS: Partial<Record<StepStatus, ChatStep[\"status\"]>> = {\n [StepStatus.RUNNING]: \"running\",\n [StepStatus.DONE]: \"done\",\n [StepStatus.FAILED]: \"failed\",\n};\nconst APPROVAL_KIND: Partial<Record<ApprovalKind, ChatApproval[\"kind\"]>> = {\n [ApprovalKind.PERMISSION]: \"permission\",\n [ApprovalKind.CHOICE]: \"choice\",\n [ApprovalKind.INPUT]: \"input\",\n};\n\nconst APPROVAL_RISK: Partial<Record<ApprovalRisk, ChatApproval[\"risk\"]>> = {\n [ApprovalRisk.LOW]: \"low\",\n [ApprovalRisk.HIGH]: \"high\",\n [ApprovalRisk.IRREVERSIBLE]: \"irreversible\",\n};\n\nconst SCOPE = \":\";\n/** The key a message's surface is stored under, so two replies can both use \"main\". */\nexport const surfaceKey = (messageId: number, surfaceId: string) => `m${messageId}${SCOPE}${surfaceId}`;\n/** The agent's own ID for a stored surface, to send back with an action. */\nexport const agentSurfaceId = (key: string) => key.slice(key.indexOf(SCOPE) + 1);\n\nfunction updateLast(thread: ChatThread, change: (message: ChatMessage) => ChatMessage): ChatThread {\n const index = thread.messages.findLastIndex((m) => m.role === \"assistant\");\n if (index < 0) return thread;\n return { ...thread, messages: thread.messages.map((m, i) => (i === index ? change(m) : m)) };\n}\n\nfunction withPart(message: ChatMessage, part: ChatPart): ChatMessage {\n return { ...message, parts: [...message.parts, part] };\n}\n\nfunction applySurface(thread: ChatThread, raw: unknown, catalog: Catalog): ChatThread {\n const message = thread.messages.findLast((m) => m.role === \"assistant\");\n if (!message) return thread;\n const fail = (text: string) => updateLast(thread, (m) => withPart(m, { kind: \"error\", code: \"INVALID_SURFACE\", message: text }));\n // A malformed envelope is refused; a malformed component is applied and reported where it is drawn.\n const fatal = catalog.validateMessage(raw).filter((issue) => !isComponentIssue(issue));\n if (fatal.length > 0) return fail(`The agent sent a view this page cannot draw: ${fatal[0]!.path} ${fatal[0]!.message}`);\n // What is kept is in the current version, whichever the agent wrote.\n const record = upgradeMessage(raw) as Record<string, { surfaceId: string }>;\n const kind = ([\"createSurface\", \"updateComponents\", \"updateDataModel\", \"deleteSurface\"] as const).find((k) => record[k]);\n if (!kind) return thread;\n const key = surfaceKey(message.id, record[kind]!.surfaceId);\n const scoped = { ...record, [kind]: { ...record[kind], surfaceId: key } } as unknown as SurfaceMessage;\n try {\n const surfaces = applyMessage(thread.surfaces, scoped);\n const shown = message.parts.some((p) => p.kind === \"surface\" && p.surfaceId === key);\n const next = { ...thread, surfaces };\n return kind === \"createSurface\" && !shown ? updateLast(next, (m) => withPart(m, { kind: \"surface\", surfaceId: key })) : next;\n } catch (error) {\n return fail(error instanceof Error ? error.message : String(error));\n }\n}\n\n/**\n * Folds user input and agent events into a thread. Pure: the same actions\n * always give the same thread, so a conversation can be replayed in tests.\n */\nexport function reduceThread(thread: ChatThread, action: ChatAction, catalog: Catalog): ChatThread {\n const nextId = (thread.messages.at(-1)?.id ?? 0) + 1;\n switch (action.type) {\n case \"reset\":\n return emptyThread;\n case \"restore\":\n return action.thread;\n case \"user\":\n return {\n ...thread,\n suggestions: [],\n messages: [\n ...thread.messages,\n { id: nextId, role: \"user\", parts: [\n { kind: \"text\", text: action.text },\n ...(action.references?.length ? [{ kind: \"references\" as const, references: action.references }] : []),\n ...(action.attachments?.length ? [{ kind: \"attachments\" as const, attachments: action.attachments }] : []),\n ], generatedBy: \"\", streaming: false },\n ],\n };\n case \"begin\": {\n const last = thread.messages.at(-1);\n if (action.resume && last?.role === \"assistant\") {\n return { ...updateLast(thread, (m) => ({ ...m, streaming: true })), status: \"streaming\", suggestions: [] };\n }\n return {\n ...thread,\n status: \"streaming\",\n suggestions: [],\n messages: [...thread.messages, { id: nextId, role: \"assistant\", parts: [], generatedBy: \"\", streaming: true }],\n };\n }\n case \"answered\":\n return {\n ...thread,\n messages: thread.messages.map((m) => ({\n ...m,\n parts: m.parts.map((p) =>\n p.kind === \"approval\" && p.approval.id === action.id ? { ...p, approval: { ...p.approval, answer: action.answer } } : p,\n ),\n })),\n };\n case \"end\": {\n const waiting = thread.messages.at(-1)?.parts.some((p) => p.kind === \"approval\" && !p.approval.answer) ?? false;\n return { ...updateLast(thread, (m) => ({ ...m, streaming: false })), status: waiting ? \"waiting\" : \"idle\" };\n }\n case \"event\": {\n const event = action.event.event;\n switch (event.case) {\n case \"text\":\n return updateLast(thread, (m) => {\n const last = m.parts.at(-1);\n if (last?.kind === \"text\") return { ...m, parts: [...m.parts.slice(0, -1), { kind: \"text\", text: last.text + event.value.delta }] };\n return withPart(m, { kind: \"text\", text: event.value.delta });\n });\n case \"step\": {\n const step: ChatStep = {\n id: event.value.id,\n title: event.value.title,\n status: STEP_STATUS[event.value.status] ?? \"running\",\n tool: event.value.tool,\n detail: event.value.detail,\n durationMs: Number(event.value.durationMs),\n };\n return updateLast(thread, (m) => {\n // An event for a step already shown updates it in place.\n if (m.parts.some((p) => p.kind === \"steps\" && p.steps.some((s) => s.id === step.id))) {\n return {\n ...m,\n parts: m.parts.map((p) =>\n p.kind === \"steps\" ? { ...p, steps: p.steps.map((s) => (s.id === step.id ? { ...s, ...step, title: step.title || s.title, detail: step.detail || s.detail } : s)) } : p,\n ),\n };\n }\n const last = m.parts.at(-1);\n if (last?.kind === \"steps\") return { ...m, parts: [...m.parts.slice(0, -1), { kind: \"steps\", steps: [...last.steps, step] }] };\n return withPart(m, { kind: \"steps\", steps: [step] });\n });\n }\n case \"surface\":\n return applySurface(thread, event.value, catalog);\n case \"approval\": {\n const approval: ChatApproval = {\n id: event.value.id,\n kind: APPROVAL_KIND[event.value.kind] ?? \"permission\",\n title: event.value.title,\n detail: event.value.detail,\n sql: event.value.sql,\n options: event.value.options,\n ...(event.value.subject ? { subject: event.value.subject } : {}),\n digest: event.value.digest,\n expiresAt: event.value.expiresAt,\n risk: APPROVAL_RISK[event.value.risk] ?? \"\",\n editable: event.value.editable,\n reasonRequired: event.value.reasonRequired,\n approvalsRequired: Math.max(1, event.value.approvalsRequired),\n approvals: event.value.approvals.map((r) => ({\n ...(r.decidedBy ? { by: { id: r.decidedBy.id, name: r.decidedBy.name } } : {}),\n at: r.decidedAt,\n allow: r.allow,\n reason: r.reason,\n })),\n basis: event.value.basis,\n };\n return updateLast(thread, (m) => withPart(m, { kind: \"approval\", approval }));\n }\n case \"usage\":\n return {\n ...thread,\n usage: {\n inputTokens: Number(event.value.inputTokens),\n outputTokens: Number(event.value.outputTokens),\n contextTokens: Number(event.value.contextTokens),\n contextLimit: Number(event.value.contextLimit),\n costUsd: event.value.costUsd,\n },\n };\n case \"suggestions\":\n return { ...thread, suggestions: event.value.items };\n case \"error\":\n return updateLast(thread, (m) => withPart(m, { kind: \"error\", code: event.value.code, message: event.value.message }));\n case \"done\":\n return { ...updateLast(thread, (m) => ({ ...m, generatedBy: event.value.generatedBy || m.generatedBy })), sessionId: event.value.sessionId || thread.sessionId };\n default:\n return thread;\n }\n }\n }\n}\n\nconst PART_KINDS = new Set([\"text\", \"references\", \"attachments\", \"steps\", \"surface\", \"approval\", \"actions\", \"error\"]);\nconst isRecord = (value: unknown): value is Record<string, unknown> => !!value && typeof value === \"object\" && !Array.isArray(value);\n\n/**\n * Checks a thread loaded from storage before it is used, since anyone with\n * access to the storage can edit it. Returns undefined for anything that is\n * not a thread. A reply that was still streaming when the page closed is\n * marked as cut off; an approval nobody answered is still waiting. Surfaces\n * are checked against the catalog again when they are drawn.\n */\nexport function parseThread(input: unknown): ChatThread | undefined {\n if (!isRecord(input) || !Array.isArray(input.messages) || !isRecord(input.surfaces)) return undefined;\n const messages: ChatMessage[] = [];\n for (const raw of input.messages) {\n if (!isRecord(raw) || typeof raw.id !== \"number\" || (raw.role !== \"user\" && raw.role !== \"assistant\") || !Array.isArray(raw.parts)) return undefined;\n if (!raw.parts.every((p) => isRecord(p) && PART_KINDS.has(p.kind as string))) return undefined;\n const parts = raw.parts as ChatPart[];\n const cut = raw.streaming === true;\n messages.push({\n id: raw.id,\n role: raw.role,\n parts: cut ? [...parts, { kind: \"error\", code: \"INTERRUPTED\", message: \"This reply was cut off when the page closed.\" }] : parts,\n generatedBy: typeof raw.generatedBy === \"string\" ? raw.generatedBy : \"\",\n streaming: false,\n });\n }\n const waiting = messages.at(-1)?.parts.some((p) => p.kind === \"approval\" && !p.approval.answer) ?? false;\n return {\n messages,\n // A thread kept before the move to A2UI v1.0 holds surfaces written for v0.9.\n surfaces: Object.fromEntries(Object.entries(input.surfaces as ChatThread[\"surfaces\"]).map(([key, surface]) => [key, isRecord(surface) && isRecord(surface.components) ? upgradeSurface(surface) : surface])),\n status: waiting ? \"waiting\" : \"idle\",\n sessionId: typeof input.sessionId === \"string\" ? input.sessionId : \"\",\n ...(isRecord(input.usage) ? { usage: input.usage as unknown as ChatUsage } : {}),\n suggestions: Array.isArray(input.suggestions) ? input.suggestions.filter((s): s is string => typeof s === \"string\") : [],\n };\n}\n"]}
package/dist/useChat.d.ts CHANGED
@@ -12,7 +12,7 @@ export interface ChatActivity {
12
12
  subject?: Record<string, unknown>;
13
13
  at: string;
14
14
  }
15
- import { type ChatActor, type ChatThread } from "./thread.js";
15
+ import { type ChatActor, type ChatAttachment, type ChatThread } from "./thread.js";
16
16
  export interface UseChatOptions {
17
17
  /** The catalog agent-drawn components are checked against. */
18
18
  catalog: Catalog;
@@ -89,7 +89,11 @@ export interface ApprovalReply {
89
89
  export interface UseChat {
90
90
  thread: ChatThread;
91
91
  /** Sends what the person typed, with any tables and columns they attached. */
92
- send(text: string, references?: DataRef[]): void;
92
+ /**
93
+ * Adds the person's message and starts a turn. `attachments` (pictures and other files that are not data) are shown with
94
+ * the message and kept in the thread; they are not sent to the agent, which takes text and data references only.
95
+ */
96
+ send(text: string, references?: DataRef[], attachments?: ChatAttachment[]): void;
93
97
  /** Answers an approval the agent is waiting on, recording who, when and why, and the digest of what was approved. */
94
98
  answer(id: string, reply: ApprovalReply): void;
95
99
  /** Sends an event from a control on an agent-drawn component. */
package/dist/useChat.js CHANGED
@@ -161,11 +161,11 @@ export function useChat(given, options) {
161
161
  })();
162
162
  }, [agent, agentId, contextPackId, dispatch]);
163
163
  useEffect(() => () => controller.current?.abort(), []);
164
- const send = useCallback((text, references = []) => {
164
+ const send = useCallback((text, references = [], attachments = []) => {
165
165
  const trimmed = text.trim();
166
166
  if (!trimmed)
167
167
  return;
168
- dispatch({ type: "user", text: trimmed, references });
168
+ dispatch({ type: "user", text: trimmed, references, attachments });
169
169
  run({ case: "text", value: trimmed }, false, references);
170
170
  }, [run, dispatch]);
171
171
  const answer = useCallback((id, reply) => {
@@ -1 +1 @@
1
- {"version":3,"file":"useChat.js","sourceRoot":"","sources":["../src/useChat.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoC,cAAc,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAElG,OAAO,EAAoC,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACrF,OAAO,EAAyC,eAAe,EAAE,MAAM,yBAAyB,CAAC;AACjG,OAAO,EAAqB,WAAW,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEjF,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,eAAe,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAkBvG,8EAA8E;AAC9E,MAAM,YAAY,GAAG,EAAE,CAAC;AAExB,8CAA8C;AAC9C,MAAM,SAAS,GAAG,CAAC,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K,CAAC,QAAQ,GAAG,EAAE,CAAC;IACrF,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,OAAO,IAAI,CAAC,CAAC,IAAI,KAAK,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAChJ,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,EAAE,SAAS,EAAE,EAAE,EAAE,IAAI,EAAE,iBAAiB,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;IACnI,UAAU,CAAC,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC;IACpC,MAAM,aAAa,GAAG,CAAC,GAAG,OAAO,CAAC,OAAO,EAAE,GAAG,KAAK,CAAC,CAAC;IACrD,OAAO,CAAC,OAAO,GAAG,EAAE,CAAC;IACrB,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,CAAC;AACrC,CAAC","sourcesContent":["import { type AgentBackend, type SendInit, approvalDigest, errorEvent } from \"@surfaces-ui/agent\";\nimport type { JsonObject } from \"@bufbuild/protobuf\";\nimport { type Catalog, type SurfaceAction, upgradeMessage } from \"@surfaces-ui/spec\";\nimport { type SurfaceNote, type SurfaceProblem, surfaceSnapshot } from \"@surfaces-ui/spec/react\";\nimport { type StateStorage, decodeState, encodeState } from \"@surfaces-ui/state\";\nimport type { DataRef } from \"@surfaces-ui/components\";\nimport { ObjectKind } from \"@surfaces-ui/proto\";\nimport { newHolder, recordMessage, traceAgent } from \"@surfaces-ui/trace\";\nimport { useRecorder } from \"@surfaces-ui/trace/react\";\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState } from \"react\";\n\n/** One thing a person did in a surface, kept until the agent's next turn. */\nexport interface ChatActivity {\n componentId: string;\n kind: string;\n summary: string;\n subject?: Record<string, unknown>;\n at: string;\n}\n\n/** Where a surface stands on this page, and what a person has done in it that the agent has not been told. */\ninterface SurfaceLocal {\n data?: unknown;\n controls: Record<string, Record<string, unknown>>;\n activity?: ChatActivity[];\n}\n\n/** The most notes kept for one surface between turns; the oldest go first. */\nconst MAX_ACTIVITY = 40;\n\n/** A reference as the contract carries it. */\nconst objectRef = (ref: DataRef) => ({\n sourceId: ref.sourceId,\n kind: ref.kind === \"file\" ? ObjectKind.FILE : ref.column ? ObjectKind.COLUMN : ObjectKind.TABLE,\n catalog: ref.catalog ?? \"\",\n schema: ref.schema ?? \"\",\n table: ref.table,\n column: ref.column ?? \"\",\n path: ref.path ?? \"\",\n});\nimport { type ChatAction, type ChatActor, type ChatApprovalAnswer, type ChatThread, agentSurfaceId, emptyThread, parseThread, reduceThread } from \"./thread.js\";\n\nexport interface UseChatOptions {\n /** The catalog agent-drawn components are checked against. */\n catalog: Catalog;\n /** Which agent to talk to, when the backend has several. */\n agentId?: string;\n /** Limit the agent to the data in this saved context pack. */\n contextPackId?: string;\n /**\n * Who is using the chat, from the host's own sign-in. Recorded on every\n * approval answer (`decided_by`). A backend must still check it against\n * its own session.\n */\n user?: ChatActor;\n /**\n * Where to keep the conversation so it survives a reload: the thread,\n * where each surface stands, and approvals still waiting. Use\n * `browserStorage()` from `@surfaces-ui/state` for this browser, or your own\n * `StateStorage` over a server so another person can pick up a waiting\n * approval. Nothing is kept without it.\n */\n storage?: StateStorage;\n /** The key the conversation is kept under. Defaults to \"surfaces.chat\". */\n storageKey?: string;\n /**\n * The thread to open with: a saved conversation (`conversationThread`) or a\n * written one (`scriptThread`). Read once; a kept conversation in `storage`\n * does not replace it.\n */\n initial?: ChatThread;\n /**\n * What the person chose for this conversation: the agent, the model, and\n * the skills and connectors that are on. Sent with every turn; the backend\n * refuses anything it does not offer. Leave it out to use the agent's defaults.\n */\n settings?: ChatSettings;\n}\n\n/** A person's choices for a conversation, as plain JSON a host or a saved conversation can hold. */\nexport interface ChatSettings {\n agentId?: string;\n /** Empty or left out: the agent's default. */\n model?: string;\n /**\n * Where the model runs, when the host offers several (`ChatProvider`): the\n * host turns it into its own backend. Neither it nor the model picked under\n * it is sent with a turn: the host passes the model to that backend.\n */\n provider?: string;\n /** Given: exactly these are on. Left out: each one's default. */\n skillIds?: string[];\n connectorIds?: string[];\n /** The data connection the person browses and attaches from. Not sent: what the agent sees is what they attach. */\n sourceId?: string;\n}\n\n/** The parts of a turn request that carry a person's choices. */\nexport function settingsRequest(settings: ChatSettings | undefined, agentId?: string) {\n const chosen = settings?.skillIds !== undefined || settings?.connectorIds !== undefined;\n return {\n agentId: settings?.agentId || agentId || \"\",\n // A model picked under a provider is the host's to hand its own backend, which is the one that knows it.\n model: settings?.provider ? \"\" : (settings?.model ?? \"\"),\n ...(chosen ? { choicesSet: true, skillIds: settings?.skillIds ?? [], connectorIds: settings?.connectorIds ?? [] } : {}),\n };\n}\n\n/** A person's answer to an approval. */\nexport interface ApprovalReply {\n allow: boolean;\n /** The chosen option or typed answer. */\n text?: string;\n /** Why, in their words. */\n reason?: string;\n /** Their version of the SQL, when the request was editable. */\n editedSql?: string;\n /** Their version of the subject, when the request was editable. */\n editedSubject?: JsonObject;\n}\n\nexport interface UseChat {\n thread: ChatThread;\n /** Sends what the person typed, with any tables and columns they attached. */\n send(text: string, references?: DataRef[]): void;\n /** Answers an approval the agent is waiting on, recording who, when and why, and the digest of what was approved. */\n answer(id: string, reply: ApprovalReply): void;\n /** Sends an event from a control on an agent-drawn component. */\n act(action: SurfaceAction): void;\n /**\n * Records where an agent-drawn surface stands: its data model after a\n * person typed, or one component's controls. Nothing is sent now; every\n * later turn carries it (`SendRequest.surfaces`).\n */\n report(surfaceKey: string, state: { data?: unknown; componentId?: string; controls?: Record<string, unknown>; note?: SurfaceNote }): void;\n /** Records a problem with an agent-drawn surface, to tell the agent on the next turn (`SendRequest.surface_errors`). */\n problem(surfaceKey: string, problem: SurfaceProblem): void;\n /** Stops the reply in progress. */\n stop(): void;\n /** Starts a new conversation, forgetting the kept one too. */\n reset(): void;\n /** False until a kept conversation has been loaded (always true without `storage`). */\n ready: boolean;\n}\n\n/**\n * Runs a conversation against any AgentBackend and keeps its thread. One\n * turn streams at a time; starting another stops the one in progress.\n */\nexport function useChat(given: AgentBackend, options: UseChatOptions): UseChat {\n const { catalog, agentId, contextPackId, user, storage, storageKey = \"surfaces.chat\" } = options;\n // Dev tools: with a recorder above, each turn is one trace and each surface message is recorded. Without one, nothing here runs.\n const recorder = useRecorder();\n const agent = useMemo(() => (recorder ? traceAgent(given, recorder) : given), [given, recorder]);\n const holder = useRef<string | undefined>(undefined);\n const [thread, send_] = useReducer((state: ChatThread, action: ChatAction) => reduceThread(state, action, catalog), options.initial ?? emptyThread);\n const controller = useRef<AbortController | undefined>(undefined);\n const sessionId = useRef(\"\");\n sessionId.current = thread.sessionId;\n const settings = useRef(options.settings);\n settings.current = options.settings;\n const latest = useRef(thread);\n latest.current = thread;\n // The thread as it stands after every action so far, kept only while tracing: what the reducer made of a\n // surface message (which surface it changed, or why it was refused) is read from it as the message arrives.\n const shadow = useRef<ChatThread | undefined>(undefined);\n const dispatch = useCallback(\n (action: ChatAction) => {\n if (recorder) {\n const before = shadow.current ?? latest.current;\n const after = reduceThread(before, action, catalog);\n shadow.current = after;\n const prefix = `${(holder.current ??= newHolder(\"c\"))}:`;\n if (action.type === \"event\" && action.event.event.case === \"surface\") {\n const raw = action.event.event.value;\n const key = Object.keys(after.surfaces).find((k) => after.surfaces[k] !== before.surfaces[k]) ?? Object.keys(before.surfaces).find((k) => !(k in after.surfaces));\n const refused = after.messages.at(-1)?.parts.at(-1);\n const error = key === undefined && refused?.kind === \"error\" && refused !== before.messages.at(-1)?.parts.at(-1) ? { code: refused.code, message: refused.message } : undefined;\n const event = recordMessage(recorder, { format: \"a2ui\", key: `${prefix}${key ?? \"\"}`, raw, message: upgradeMessage(raw), issues: catalog.validateMessage(raw), applied: key !== undefined, ...(error ? { error } : {}) });\n if (error) recorder.record({ kind: \"problem\", name: error.code, status: \"error\", surfaceId: event.surfaceId, detail: { code: error.code, path: \"/\", message: error.message } }, { traceId: event.traceId, spanId: event.spanId });\n } else if (action.type === \"reset\" || action.type === \"restore\") recorder.record({ kind: \"state\", name: \"reset\", detail: { prefix } });\n } else shadow.current = undefined;\n send_(action);\n },\n [recorder, catalog],\n );\n if (recorder) for (const [key, surface] of Object.entries(thread.surfaces)) recorder.tag(surface, `${(holder.current ??= newHolder(\"c\"))}:${key}`);\n // A surface that came with the thread (a saved or written conversation) has no recorded messages: it is recorded whole.\n useLayoutEffect(() => {\n if (!recorder) return;\n for (const [key, surface] of Object.entries(thread.surfaces)) {\n const traced = `${(holder.current ??= newHolder(\"c\"))}:${key}`;\n if (!recorder.surfaceScope(traced)) recordMessage(recorder, { format: \"surface\", key: traced, raw: surfaceSnapshot(surface), snapshot: true, name: \"surface\" });\n }\n }, [recorder, thread.surfaces]);\n // Where each surface stands on this page, and problems not yet told to the agent.\n const states = useRef(new Map<string, SurfaceLocal>());\n const pending = useRef<{ surfaceId: string; code: string; path: string; message: string }[]>([]);\n const toldErrors = useRef(0);\n const [ready, setReady] = useState(!storage);\n\n // Load a kept conversation once, then keep it after every change.\n useEffect(() => {\n if (!storage) return;\n let live = true;\n void (async () => {\n try {\n const text = await storage.load(storageKey);\n const saved = text ? (decodeState(text) as { version?: number; thread?: unknown; states?: unknown; pending?: unknown; toldErrors?: unknown }) : undefined;\n const restored = saved?.version === STORE_VERSION ? parseThread(saved.thread) : undefined;\n if (live && restored && latest.current.messages.length === 0) {\n dispatch({ type: \"restore\", thread: restored });\n if (saved?.states && typeof saved.states === \"object\") states.current = new Map(Object.entries(saved.states as Record<string, SurfaceLocal>));\n if (Array.isArray(saved?.pending)) pending.current = saved.pending as typeof pending.current;\n if (typeof saved?.toldErrors === \"number\") toldErrors.current = saved.toldErrors;\n }\n } catch {\n // A kept conversation that cannot be read is ignored, not fatal.\n } finally {\n if (live) setReady(true);\n }\n })();\n return () => {\n live = false;\n };\n }, [storage, storageKey]);\n const save = useCallback(() => {\n if (!storage) return;\n const record = { version: STORE_VERSION, thread: latest.current, states: Object.fromEntries(states.current), pending: pending.current, toldErrors: toldErrors.current };\n void storage.save(storageKey, encodeState(record));\n }, [storage, storageKey]);\n useEffect(() => {\n if (!ready || !storage) return;\n const timer = setTimeout(save, thread.status === \"streaming\" ? 500 : 0);\n return () => clearTimeout(timer);\n }, [thread, ready, storage, save]);\n\n const run = useCallback(\n (input: NonNullable<SendInit[\"input\"]>, resume = false, references: DataRef[] = []) => {\n controller.current?.abort();\n const current = new AbortController();\n controller.current = current;\n dispatch({ type: \"begin\", resume });\n void (async () => {\n try {\n const { surfaces, surfaceErrors } = takeState(latest.current, states.current, pending, toldErrors);\n for await (const event of agent.send({ sessionId: sessionId.current, ...settingsRequest(settings.current, agentId), contextPackId, input, surfaces, surfaceErrors, references: references.map(objectRef) }, { signal: current.signal })) {\n if (current.signal.aborted) break;\n dispatch({ type: \"event\", event });\n }\n } catch (error) {\n if (!current.signal.aborted) dispatch({ type: \"event\", event: errorEvent(error) });\n } finally {\n if (controller.current === current) {\n controller.current = undefined;\n dispatch({ type: \"end\" });\n }\n }\n })();\n },\n [agent, agentId, contextPackId, dispatch],\n );\n\n useEffect(() => () => controller.current?.abort(), []);\n\n const send = useCallback(\n (text: string, references: DataRef[] = []) => {\n const trimmed = text.trim();\n if (!trimmed) return;\n dispatch({ type: \"user\", text: trimmed, references });\n run({ case: \"text\", value: trimmed }, false, references);\n },\n [run, dispatch],\n );\n const answer = useCallback(\n (id: string, reply: ApprovalReply) => {\n const approval = latest.current.messages.flatMap((m) => m.parts).find((p) => p.kind === \"approval\" && p.approval.id === id);\n const request = approval?.kind === \"approval\" ? approval.approval : undefined;\n void (async () => {\n // The digest of what the person approved: their edited version when they changed it.\n const digest = await approvalDigest({ sql: reply.editedSql ?? request?.sql, subject: reply.editedSubject ?? request?.subject });\n const decided: ChatApprovalAnswer = {\n allow: reply.allow,\n text: reply.text ?? \"\",\n reason: reply.reason?.trim() ?? \"\",\n at: new Date().toISOString(),\n digest,\n ...(user ? { by: user } : {}),\n ...(reply.editedSql !== undefined ? { editedSql: reply.editedSql } : {}),\n ...(reply.editedSubject ? { editedSubject: reply.editedSubject } : {}),\n };\n dispatch({ type: \"answered\", id, answer: decided });\n run(\n {\n case: \"approval\",\n value: {\n id,\n allow: decided.allow,\n answer: decided.text,\n reason: decided.reason,\n decidedAt: decided.at,\n digest,\n ...(user ? { decidedBy: user } : {}),\n ...(decided.editedSql !== undefined ? { editedSql: decided.editedSql } : {}),\n ...(decided.editedSubject ? { editedSubject: decided.editedSubject } : {}),\n },\n },\n true,\n );\n })();\n },\n [run, user, dispatch],\n );\n const act = useCallback(\n (action: SurfaceAction) =>\n run({\n case: \"action\",\n value: {\n name: action.name,\n surfaceId: agentSurfaceId(action.surfaceId),\n sourceComponentId: action.sourceComponentId,\n timestamp: action.timestamp,\n // Values travel as JSON; anything that is not JSON (a bigint) is sent as text.\n context: asJson(action.context),\n ...(action.dataModel !== undefined ? { dataModel: asJson(action.dataModel) } : {}),\n ...(user ? { actor: user } : {}),\n },\n }),\n [run, user],\n );\n const report = useCallback<UseChat[\"report\"]>((key, state) => {\n const entry = states.current.get(key) ?? { controls: {} };\n if (state.data !== undefined) entry.data = state.data;\n if (state.componentId && state.controls) entry.controls[state.componentId] = state.controls;\n if (state.componentId && state.note) {\n // What a person did, for the agent's context on its next turn. The same thing twice in a row is told once.\n const last = entry.activity?.at(-1);\n if (!(last && last.componentId === state.componentId && last.kind === state.note.kind && last.summary === state.note.summary)) {\n entry.activity = [...(entry.activity ?? []), { componentId: state.componentId, kind: state.note.kind, summary: state.note.summary, ...(state.note.subject ? { subject: state.note.subject } : {}), at: new Date().toISOString() }].slice(-MAX_ACTIVITY);\n }\n }\n states.current.set(key, entry);\n save();\n }, [save]);\n const problem = useCallback<UseChat[\"problem\"]>((key, p) => {\n const message = { surfaceId: agentSurfaceId(key), code: p.code, path: p.path, message: p.message };\n // The same problem is reported once, however often the surface is drawn.\n if (!pending.current.some((e) => e.surfaceId === message.surfaceId && e.path === message.path && e.message === message.message)) pending.current.push(message);\n save();\n }, [save]);\n const stop = useCallback(() => {\n controller.current?.abort();\n controller.current = undefined;\n dispatch({ type: \"end\" });\n }, [dispatch]);\n const reset = useCallback(() => {\n controller.current?.abort();\n controller.current = undefined;\n states.current = new Map();\n pending.current = [];\n toldErrors.current = 0;\n dispatch({ type: \"reset\" });\n }, [dispatch]);\n\n return { thread, send, answer, act, report, problem, stop, reset, ready };\n}\n\n/** Bump when the kept shape changes; older conversations are then dropped. */\nconst STORE_VERSION = 1;\n\n/** Values travel as JSON; anything that is not JSON (a bigint) is sent as text. */\nconst asJson = (value: unknown): JsonObject => {\n const plain = JSON.parse(JSON.stringify(value ?? {}, (_, v) => (typeof v === \"bigint\" ? String(v) : v))) as unknown;\n return plain && typeof plain === \"object\" && !Array.isArray(plain) ? (plain as JsonObject) : { value: plain as JsonObject[string] };\n};\n\n/**\n * What goes with every turn: each agent surface as it now stands (the\n * latest one for each of the agent's surface IDs), and problems not yet\n * reported, including views the chat refused to draw.\n */\nfunction takeState(\n thread: ChatThread,\n states: Map<string, SurfaceLocal>,\n pending: { current: { surfaceId: string; code: string; path: string; message: string }[] },\n toldErrors: { current: number },\n): Pick<SendInit, \"surfaces\" | \"surfaceErrors\"> {\n const latestKey = new Map<string, string>();\n for (const key of Object.keys(thread.surfaces)) latestKey.set(agentSurfaceId(key), key);\n const surfaces = [...latestKey.entries()].map(([surfaceId, key]) => {\n const surface = thread.surfaces[key]!;\n const local = states.get(key);\n return {\n surfaceId,\n dataModel: asJson(local?.data ?? surface.data),\n controls: Object.fromEntries(Object.entries(local?.controls ?? {}).map(([id, c]) => [id, asJson(c)])),\n expects: Object.entries(surface.expects ?? {}).map(([event, schema]) => ({ event, schema: asJson(schema) })),\n activity: (local?.activity ?? []).map((a) => ({ componentId: a.componentId, kind: a.kind, summary: a.summary, at: a.at, ...(a.subject ? { subject: asJson(a.subject) } : {}) })),\n };\n });\n // Told once: what was done before this turn is not repeated on the next.\n for (const local of states.values()) if (local.activity?.length) local.activity = [];\n const refused = thread.messages.flatMap((m) => m.parts.flatMap((p) => (p.kind === \"error\" && p.code === \"INVALID_SURFACE\" ? [p.message] : [])));\n const fresh = refused.slice(toldErrors.current).map((message) => ({ surfaceId: \"\", code: \"INVALID_MESSAGE\", path: \"/\", message }));\n toldErrors.current = refused.length;\n const surfaceErrors = [...pending.current, ...fresh];\n pending.current = [];\n return { surfaces, surfaceErrors };\n}\n"]}
1
+ {"version":3,"file":"useChat.js","sourceRoot":"","sources":["../src/useChat.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoC,cAAc,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAElG,OAAO,EAAoC,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACrF,OAAO,EAAyC,eAAe,EAAE,MAAM,yBAAyB,CAAC;AACjG,OAAO,EAAqB,WAAW,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEjF,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAC1E,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,eAAe,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAkBvG,8EAA8E;AAC9E,MAAM,YAAY,GAAG,EAAE,CAAC;AAExB,8CAA8C;AAC9C,MAAM,SAAS,GAAG,CAAC,GAAY,EAAE,EAAE,CAAC,CAAC;IAC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,KAAK,CAAC,QAAQ,GAAG,EAAE,CAAC;IACrF,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,OAAO,IAAI,CAAC,CAAC,IAAI,KAAK,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAChJ,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,EAAE,SAAS,EAAE,EAAE,EAAE,IAAI,EAAE,iBAAiB,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;IACnI,UAAU,CAAC,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC;IACpC,MAAM,aAAa,GAAG,CAAC,GAAG,OAAO,CAAC,OAAO,EAAE,GAAG,KAAK,CAAC,CAAC;IACrD,OAAO,CAAC,OAAO,GAAG,EAAE,CAAC;IACrB,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,CAAC;AACrC,CAAC","sourcesContent":["import { type AgentBackend, type SendInit, approvalDigest, errorEvent } from \"@surfaces-ui/agent\";\nimport type { JsonObject } from \"@bufbuild/protobuf\";\nimport { type Catalog, type SurfaceAction, upgradeMessage } from \"@surfaces-ui/spec\";\nimport { type SurfaceNote, type SurfaceProblem, surfaceSnapshot } from \"@surfaces-ui/spec/react\";\nimport { type StateStorage, decodeState, encodeState } from \"@surfaces-ui/state\";\nimport type { DataRef } from \"@surfaces-ui/components\";\nimport { ObjectKind } from \"@surfaces-ui/proto\";\nimport { newHolder, recordMessage, traceAgent } from \"@surfaces-ui/trace\";\nimport { useRecorder } from \"@surfaces-ui/trace/react\";\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState } from \"react\";\n\n/** One thing a person did in a surface, kept until the agent's next turn. */\nexport interface ChatActivity {\n componentId: string;\n kind: string;\n summary: string;\n subject?: Record<string, unknown>;\n at: string;\n}\n\n/** Where a surface stands on this page, and what a person has done in it that the agent has not been told. */\ninterface SurfaceLocal {\n data?: unknown;\n controls: Record<string, Record<string, unknown>>;\n activity?: ChatActivity[];\n}\n\n/** The most notes kept for one surface between turns; the oldest go first. */\nconst MAX_ACTIVITY = 40;\n\n/** A reference as the contract carries it. */\nconst objectRef = (ref: DataRef) => ({\n sourceId: ref.sourceId,\n kind: ref.kind === \"file\" ? ObjectKind.FILE : ref.column ? ObjectKind.COLUMN : ObjectKind.TABLE,\n catalog: ref.catalog ?? \"\",\n schema: ref.schema ?? \"\",\n table: ref.table,\n column: ref.column ?? \"\",\n path: ref.path ?? \"\",\n});\nimport { type ChatAction, type ChatActor, type ChatAttachment, type ChatApprovalAnswer, type ChatThread, agentSurfaceId, emptyThread, parseThread, reduceThread } from \"./thread.js\";\n\nexport interface UseChatOptions {\n /** The catalog agent-drawn components are checked against. */\n catalog: Catalog;\n /** Which agent to talk to, when the backend has several. */\n agentId?: string;\n /** Limit the agent to the data in this saved context pack. */\n contextPackId?: string;\n /**\n * Who is using the chat, from the host's own sign-in. Recorded on every\n * approval answer (`decided_by`). A backend must still check it against\n * its own session.\n */\n user?: ChatActor;\n /**\n * Where to keep the conversation so it survives a reload: the thread,\n * where each surface stands, and approvals still waiting. Use\n * `browserStorage()` from `@surfaces-ui/state` for this browser, or your own\n * `StateStorage` over a server so another person can pick up a waiting\n * approval. Nothing is kept without it.\n */\n storage?: StateStorage;\n /** The key the conversation is kept under. Defaults to \"surfaces.chat\". */\n storageKey?: string;\n /**\n * The thread to open with: a saved conversation (`conversationThread`) or a\n * written one (`scriptThread`). Read once; a kept conversation in `storage`\n * does not replace it.\n */\n initial?: ChatThread;\n /**\n * What the person chose for this conversation: the agent, the model, and\n * the skills and connectors that are on. Sent with every turn; the backend\n * refuses anything it does not offer. Leave it out to use the agent's defaults.\n */\n settings?: ChatSettings;\n}\n\n/** A person's choices for a conversation, as plain JSON a host or a saved conversation can hold. */\nexport interface ChatSettings {\n agentId?: string;\n /** Empty or left out: the agent's default. */\n model?: string;\n /**\n * Where the model runs, when the host offers several (`ChatProvider`): the\n * host turns it into its own backend. Neither it nor the model picked under\n * it is sent with a turn: the host passes the model to that backend.\n */\n provider?: string;\n /** Given: exactly these are on. Left out: each one's default. */\n skillIds?: string[];\n connectorIds?: string[];\n /** The data connection the person browses and attaches from. Not sent: what the agent sees is what they attach. */\n sourceId?: string;\n}\n\n/** The parts of a turn request that carry a person's choices. */\nexport function settingsRequest(settings: ChatSettings | undefined, agentId?: string) {\n const chosen = settings?.skillIds !== undefined || settings?.connectorIds !== undefined;\n return {\n agentId: settings?.agentId || agentId || \"\",\n // A model picked under a provider is the host's to hand its own backend, which is the one that knows it.\n model: settings?.provider ? \"\" : (settings?.model ?? \"\"),\n ...(chosen ? { choicesSet: true, skillIds: settings?.skillIds ?? [], connectorIds: settings?.connectorIds ?? [] } : {}),\n };\n}\n\n/** A person's answer to an approval. */\nexport interface ApprovalReply {\n allow: boolean;\n /** The chosen option or typed answer. */\n text?: string;\n /** Why, in their words. */\n reason?: string;\n /** Their version of the SQL, when the request was editable. */\n editedSql?: string;\n /** Their version of the subject, when the request was editable. */\n editedSubject?: JsonObject;\n}\n\nexport interface UseChat {\n thread: ChatThread;\n /** Sends what the person typed, with any tables and columns they attached. */\n /**\n * Adds the person's message and starts a turn. `attachments` (pictures and other files that are not data) are shown with\n * the message and kept in the thread; they are not sent to the agent, which takes text and data references only.\n */\n send(text: string, references?: DataRef[], attachments?: ChatAttachment[]): void;\n /** Answers an approval the agent is waiting on, recording who, when and why, and the digest of what was approved. */\n answer(id: string, reply: ApprovalReply): void;\n /** Sends an event from a control on an agent-drawn component. */\n act(action: SurfaceAction): void;\n /**\n * Records where an agent-drawn surface stands: its data model after a\n * person typed, or one component's controls. Nothing is sent now; every\n * later turn carries it (`SendRequest.surfaces`).\n */\n report(surfaceKey: string, state: { data?: unknown; componentId?: string; controls?: Record<string, unknown>; note?: SurfaceNote }): void;\n /** Records a problem with an agent-drawn surface, to tell the agent on the next turn (`SendRequest.surface_errors`). */\n problem(surfaceKey: string, problem: SurfaceProblem): void;\n /** Stops the reply in progress. */\n stop(): void;\n /** Starts a new conversation, forgetting the kept one too. */\n reset(): void;\n /** False until a kept conversation has been loaded (always true without `storage`). */\n ready: boolean;\n}\n\n/**\n * Runs a conversation against any AgentBackend and keeps its thread. One\n * turn streams at a time; starting another stops the one in progress.\n */\nexport function useChat(given: AgentBackend, options: UseChatOptions): UseChat {\n const { catalog, agentId, contextPackId, user, storage, storageKey = \"surfaces.chat\" } = options;\n // Dev tools: with a recorder above, each turn is one trace and each surface message is recorded. Without one, nothing here runs.\n const recorder = useRecorder();\n const agent = useMemo(() => (recorder ? traceAgent(given, recorder) : given), [given, recorder]);\n const holder = useRef<string | undefined>(undefined);\n const [thread, send_] = useReducer((state: ChatThread, action: ChatAction) => reduceThread(state, action, catalog), options.initial ?? emptyThread);\n const controller = useRef<AbortController | undefined>(undefined);\n const sessionId = useRef(\"\");\n sessionId.current = thread.sessionId;\n const settings = useRef(options.settings);\n settings.current = options.settings;\n const latest = useRef(thread);\n latest.current = thread;\n // The thread as it stands after every action so far, kept only while tracing: what the reducer made of a\n // surface message (which surface it changed, or why it was refused) is read from it as the message arrives.\n const shadow = useRef<ChatThread | undefined>(undefined);\n const dispatch = useCallback(\n (action: ChatAction) => {\n if (recorder) {\n const before = shadow.current ?? latest.current;\n const after = reduceThread(before, action, catalog);\n shadow.current = after;\n const prefix = `${(holder.current ??= newHolder(\"c\"))}:`;\n if (action.type === \"event\" && action.event.event.case === \"surface\") {\n const raw = action.event.event.value;\n const key = Object.keys(after.surfaces).find((k) => after.surfaces[k] !== before.surfaces[k]) ?? Object.keys(before.surfaces).find((k) => !(k in after.surfaces));\n const refused = after.messages.at(-1)?.parts.at(-1);\n const error = key === undefined && refused?.kind === \"error\" && refused !== before.messages.at(-1)?.parts.at(-1) ? { code: refused.code, message: refused.message } : undefined;\n const event = recordMessage(recorder, { format: \"a2ui\", key: `${prefix}${key ?? \"\"}`, raw, message: upgradeMessage(raw), issues: catalog.validateMessage(raw), applied: key !== undefined, ...(error ? { error } : {}) });\n if (error) recorder.record({ kind: \"problem\", name: error.code, status: \"error\", surfaceId: event.surfaceId, detail: { code: error.code, path: \"/\", message: error.message } }, { traceId: event.traceId, spanId: event.spanId });\n } else if (action.type === \"reset\" || action.type === \"restore\") recorder.record({ kind: \"state\", name: \"reset\", detail: { prefix } });\n } else shadow.current = undefined;\n send_(action);\n },\n [recorder, catalog],\n );\n if (recorder) for (const [key, surface] of Object.entries(thread.surfaces)) recorder.tag(surface, `${(holder.current ??= newHolder(\"c\"))}:${key}`);\n // A surface that came with the thread (a saved or written conversation) has no recorded messages: it is recorded whole.\n useLayoutEffect(() => {\n if (!recorder) return;\n for (const [key, surface] of Object.entries(thread.surfaces)) {\n const traced = `${(holder.current ??= newHolder(\"c\"))}:${key}`;\n if (!recorder.surfaceScope(traced)) recordMessage(recorder, { format: \"surface\", key: traced, raw: surfaceSnapshot(surface), snapshot: true, name: \"surface\" });\n }\n }, [recorder, thread.surfaces]);\n // Where each surface stands on this page, and problems not yet told to the agent.\n const states = useRef(new Map<string, SurfaceLocal>());\n const pending = useRef<{ surfaceId: string; code: string; path: string; message: string }[]>([]);\n const toldErrors = useRef(0);\n const [ready, setReady] = useState(!storage);\n\n // Load a kept conversation once, then keep it after every change.\n useEffect(() => {\n if (!storage) return;\n let live = true;\n void (async () => {\n try {\n const text = await storage.load(storageKey);\n const saved = text ? (decodeState(text) as { version?: number; thread?: unknown; states?: unknown; pending?: unknown; toldErrors?: unknown }) : undefined;\n const restored = saved?.version === STORE_VERSION ? parseThread(saved.thread) : undefined;\n if (live && restored && latest.current.messages.length === 0) {\n dispatch({ type: \"restore\", thread: restored });\n if (saved?.states && typeof saved.states === \"object\") states.current = new Map(Object.entries(saved.states as Record<string, SurfaceLocal>));\n if (Array.isArray(saved?.pending)) pending.current = saved.pending as typeof pending.current;\n if (typeof saved?.toldErrors === \"number\") toldErrors.current = saved.toldErrors;\n }\n } catch {\n // A kept conversation that cannot be read is ignored, not fatal.\n } finally {\n if (live) setReady(true);\n }\n })();\n return () => {\n live = false;\n };\n }, [storage, storageKey]);\n const save = useCallback(() => {\n if (!storage) return;\n const record = { version: STORE_VERSION, thread: latest.current, states: Object.fromEntries(states.current), pending: pending.current, toldErrors: toldErrors.current };\n void storage.save(storageKey, encodeState(record));\n }, [storage, storageKey]);\n useEffect(() => {\n if (!ready || !storage) return;\n const timer = setTimeout(save, thread.status === \"streaming\" ? 500 : 0);\n return () => clearTimeout(timer);\n }, [thread, ready, storage, save]);\n\n const run = useCallback(\n (input: NonNullable<SendInit[\"input\"]>, resume = false, references: DataRef[] = []) => {\n controller.current?.abort();\n const current = new AbortController();\n controller.current = current;\n dispatch({ type: \"begin\", resume });\n void (async () => {\n try {\n const { surfaces, surfaceErrors } = takeState(latest.current, states.current, pending, toldErrors);\n for await (const event of agent.send({ sessionId: sessionId.current, ...settingsRequest(settings.current, agentId), contextPackId, input, surfaces, surfaceErrors, references: references.map(objectRef) }, { signal: current.signal })) {\n if (current.signal.aborted) break;\n dispatch({ type: \"event\", event });\n }\n } catch (error) {\n if (!current.signal.aborted) dispatch({ type: \"event\", event: errorEvent(error) });\n } finally {\n if (controller.current === current) {\n controller.current = undefined;\n dispatch({ type: \"end\" });\n }\n }\n })();\n },\n [agent, agentId, contextPackId, dispatch],\n );\n\n useEffect(() => () => controller.current?.abort(), []);\n\n const send = useCallback(\n (text: string, references: DataRef[] = [], attachments: ChatAttachment[] = []) => {\n const trimmed = text.trim();\n if (!trimmed) return;\n dispatch({ type: \"user\", text: trimmed, references, attachments });\n run({ case: \"text\", value: trimmed }, false, references);\n },\n [run, dispatch],\n );\n const answer = useCallback(\n (id: string, reply: ApprovalReply) => {\n const approval = latest.current.messages.flatMap((m) => m.parts).find((p) => p.kind === \"approval\" && p.approval.id === id);\n const request = approval?.kind === \"approval\" ? approval.approval : undefined;\n void (async () => {\n // The digest of what the person approved: their edited version when they changed it.\n const digest = await approvalDigest({ sql: reply.editedSql ?? request?.sql, subject: reply.editedSubject ?? request?.subject });\n const decided: ChatApprovalAnswer = {\n allow: reply.allow,\n text: reply.text ?? \"\",\n reason: reply.reason?.trim() ?? \"\",\n at: new Date().toISOString(),\n digest,\n ...(user ? { by: user } : {}),\n ...(reply.editedSql !== undefined ? { editedSql: reply.editedSql } : {}),\n ...(reply.editedSubject ? { editedSubject: reply.editedSubject } : {}),\n };\n dispatch({ type: \"answered\", id, answer: decided });\n run(\n {\n case: \"approval\",\n value: {\n id,\n allow: decided.allow,\n answer: decided.text,\n reason: decided.reason,\n decidedAt: decided.at,\n digest,\n ...(user ? { decidedBy: user } : {}),\n ...(decided.editedSql !== undefined ? { editedSql: decided.editedSql } : {}),\n ...(decided.editedSubject ? { editedSubject: decided.editedSubject } : {}),\n },\n },\n true,\n );\n })();\n },\n [run, user, dispatch],\n );\n const act = useCallback(\n (action: SurfaceAction) =>\n run({\n case: \"action\",\n value: {\n name: action.name,\n surfaceId: agentSurfaceId(action.surfaceId),\n sourceComponentId: action.sourceComponentId,\n timestamp: action.timestamp,\n // Values travel as JSON; anything that is not JSON (a bigint) is sent as text.\n context: asJson(action.context),\n ...(action.dataModel !== undefined ? { dataModel: asJson(action.dataModel) } : {}),\n ...(user ? { actor: user } : {}),\n },\n }),\n [run, user],\n );\n const report = useCallback<UseChat[\"report\"]>((key, state) => {\n const entry = states.current.get(key) ?? { controls: {} };\n if (state.data !== undefined) entry.data = state.data;\n if (state.componentId && state.controls) entry.controls[state.componentId] = state.controls;\n if (state.componentId && state.note) {\n // What a person did, for the agent's context on its next turn. The same thing twice in a row is told once.\n const last = entry.activity?.at(-1);\n if (!(last && last.componentId === state.componentId && last.kind === state.note.kind && last.summary === state.note.summary)) {\n entry.activity = [...(entry.activity ?? []), { componentId: state.componentId, kind: state.note.kind, summary: state.note.summary, ...(state.note.subject ? { subject: state.note.subject } : {}), at: new Date().toISOString() }].slice(-MAX_ACTIVITY);\n }\n }\n states.current.set(key, entry);\n save();\n }, [save]);\n const problem = useCallback<UseChat[\"problem\"]>((key, p) => {\n const message = { surfaceId: agentSurfaceId(key), code: p.code, path: p.path, message: p.message };\n // The same problem is reported once, however often the surface is drawn.\n if (!pending.current.some((e) => e.surfaceId === message.surfaceId && e.path === message.path && e.message === message.message)) pending.current.push(message);\n save();\n }, [save]);\n const stop = useCallback(() => {\n controller.current?.abort();\n controller.current = undefined;\n dispatch({ type: \"end\" });\n }, [dispatch]);\n const reset = useCallback(() => {\n controller.current?.abort();\n controller.current = undefined;\n states.current = new Map();\n pending.current = [];\n toldErrors.current = 0;\n dispatch({ type: \"reset\" });\n }, [dispatch]);\n\n return { thread, send, answer, act, report, problem, stop, reset, ready };\n}\n\n/** Bump when the kept shape changes; older conversations are then dropped. */\nconst STORE_VERSION = 1;\n\n/** Values travel as JSON; anything that is not JSON (a bigint) is sent as text. */\nconst asJson = (value: unknown): JsonObject => {\n const plain = JSON.parse(JSON.stringify(value ?? {}, (_, v) => (typeof v === \"bigint\" ? String(v) : v))) as unknown;\n return plain && typeof plain === \"object\" && !Array.isArray(plain) ? (plain as JsonObject) : { value: plain as JsonObject[string] };\n};\n\n/**\n * What goes with every turn: each agent surface as it now stands (the\n * latest one for each of the agent's surface IDs), and problems not yet\n * reported, including views the chat refused to draw.\n */\nfunction takeState(\n thread: ChatThread,\n states: Map<string, SurfaceLocal>,\n pending: { current: { surfaceId: string; code: string; path: string; message: string }[] },\n toldErrors: { current: number },\n): Pick<SendInit, \"surfaces\" | \"surfaceErrors\"> {\n const latestKey = new Map<string, string>();\n for (const key of Object.keys(thread.surfaces)) latestKey.set(agentSurfaceId(key), key);\n const surfaces = [...latestKey.entries()].map(([surfaceId, key]) => {\n const surface = thread.surfaces[key]!;\n const local = states.get(key);\n return {\n surfaceId,\n dataModel: asJson(local?.data ?? surface.data),\n controls: Object.fromEntries(Object.entries(local?.controls ?? {}).map(([id, c]) => [id, asJson(c)])),\n expects: Object.entries(surface.expects ?? {}).map(([event, schema]) => ({ event, schema: asJson(schema) })),\n activity: (local?.activity ?? []).map((a) => ({ componentId: a.componentId, kind: a.kind, summary: a.summary, at: a.at, ...(a.subject ? { subject: asJson(a.subject) } : {}) })),\n };\n });\n // Told once: what was done before this turn is not repeated on the next.\n for (const local of states.values()) if (local.activity?.length) local.activity = [];\n const refused = thread.messages.flatMap((m) => m.parts.flatMap((p) => (p.kind === \"error\" && p.code === \"INVALID_SURFACE\" ? [p.message] : [])));\n const fresh = refused.slice(toldErrors.current).map((message) => ({ surfaceId: \"\", code: \"INVALID_MESSAGE\", path: \"/\", message }));\n toldErrors.current = refused.length;\n const surfaceErrors = [...pending.current, ...fresh];\n pending.current = [];\n return { surfaces, surfaceErrors };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@surfaces-ui/chat",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Chat thread components for Surfaces UI: streaming replies, tool steps, approvals and inline agent-drawn components",
5
5
  "keywords": [
6
6
  "surfaces-ui",
@@ -46,12 +46,12 @@
46
46
  },
47
47
  "dependencies": {
48
48
  "@bufbuild/protobuf": "^2.17.0",
49
- "@surfaces-ui/agent": "0.3.0",
50
- "@surfaces-ui/components": "0.3.0",
51
- "@surfaces-ui/proto": "0.3.0",
52
- "@surfaces-ui/spec": "0.3.0",
53
- "@surfaces-ui/state": "0.3.0",
54
- "@surfaces-ui/trace": "0.3.0"
49
+ "@surfaces-ui/agent": "0.5.0",
50
+ "@surfaces-ui/components": "0.5.0",
51
+ "@surfaces-ui/proto": "0.5.0",
52
+ "@surfaces-ui/spec": "0.5.0",
53
+ "@surfaces-ui/state": "0.5.0",
54
+ "@surfaces-ui/trace": "0.5.0"
55
55
  },
56
56
  "devDependencies": {
57
57
  "@codemirror/view": "^6.43.15",
@@ -61,7 +61,7 @@
61
61
  "jsdom": "^31.0.0",
62
62
  "react": "^19.3.1",
63
63
  "react-dom": "^19.3.1",
64
- "@surfaces-ui/data": "0.3.0"
64
+ "@surfaces-ui/data": "0.5.0"
65
65
  },
66
66
  "publishConfig": {
67
67
  "access": "public",