@ghuri/ai-widget 0.3.1 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -0
- package/dist/core/client.d.ts +6 -0
- package/dist/core/index.d.ts +1 -1
- package/dist/core/output.d.ts +26 -0
- package/dist/core/types.d.ts +11 -0
- package/dist/{core-2Z4rCitF.js → core-vIc1mTTy.js} +188 -127
- package/dist/core-vIc1mTTy.js.map +1 -0
- package/dist/core.js +1 -1
- package/dist/index.js +3 -3
- package/dist/react.js +2 -1
- package/dist/react.js.map +1 -1
- package/dist/{src-ERXeGEmS.js → src-DLeXsfmQ.js} +106 -9
- package/dist/src-DLeXsfmQ.js.map +1 -0
- package/dist/ui/element.d.ts +8 -1
- package/dist/ui/labels.d.ts +2 -0
- package/package.json +1 -1
- package/dist/core-2Z4rCitF.js.map +0 -1
- package/dist/src-ERXeGEmS.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"core-vIc1mTTy.js","names":["parsedOutput","output","value","IMAGE_TYPES","cleanImage","i","splitToolOutput","raw","splitSavedOutput","saved","text","p","images","photosOf","list","a","isNote","textOf","content","outputOf","split","messagesFromHistory","out","tools","byApproval","pending","titles","assistant","n","current","m","messages","photos","parts","msg","last","title","part","waiting","QUALITY","scaledSize","longest","width","height","maxEdge","k","prepareImage","opts","contentType","file","bitmap","size","blob","encode","canvas","ctx","resolve","b","parseSse","parser","SseParser","end","event","chunk","rest","data","line","payload","readChunks","decoder","reader","body","cancel","signal","done","SESSION_MARGIN_MS","ATTACHMENT_DEFAULTS","empty","objectUrl","revoke","url","HttpError","detail","status","code","retryAfter","fields","httpError","res","retry","problemFor","err","isAbort","sessionUsable","expires","s","now","snapshot","u","ChatClient","listener","set","name","l","patch","prefix","started","session","headers","init","path","retried","again","message","ready","attachments","conversationId","o","mine","allowed","t","id","reason","files","preview","accept","kept","x","maxCount","entry","uploadFile","generation","live","controller","prepare","prepared","maxBytes","attachment","fraction","discardFile","byId","decisions","d","toolName","problem","action","q","c","user","finished","turn","cut","texts","chunks","textChunks","stopped","why","known"],"sources":["../src/core/output.ts","../src/core/history.ts","../src/core/prepare.ts","../src/core/sse.ts","../src/core/client.ts"],"sourcesContent":["// Tool results for display. Many MCP servers send their JSON only as text (ChatGPT's directory rule drops\n// structuredContent without an outputSchema); cards, events and counts want the object. Ghuri AI parses the live stream\n// already (displayOutput on the server); this covers saved conversations and older servers.\n\n/** Text that is a JSON object or array, parsed; anything else unchanged. */\nexport function parsedOutput(output: unknown): unknown {\n if (typeof output !== 'string') return output\n const t = output.trim()\n if (!(t.startsWith('{') && t.endsWith('}')) && !(t.startsWith('[') && t.endsWith(']'))) return output\n try {\n const value = JSON.parse(t)\n return value && typeof value === 'object' ? value : output\n } catch {\n return output\n }\n}\n\n/** A picture a tool returned (a screenshot of a draft design, for example), base64. */\nexport interface ToolImage {\n mediaType: string\n data: string\n width?: number\n height?: number\n}\n\nconst IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/webp']\n\nfunction cleanImage(i: any): ToolImage | null {\n if (!i || typeof i !== 'object' || typeof i.data !== 'string' || !IMAGE_TYPES.includes(i.mediaType))\n return null\n // base64 only: never a URL or markup.\n if (!/^[A-Za-z0-9+/=]+$/.test(i.data)) return null\n return {\n mediaType: i.mediaType,\n data: i.data,\n ...(Number.isFinite(i.width) ? { width: i.width } : {}),\n ...(Number.isFinite(i.height) ? { height: i.height } : {}),\n }\n}\n\n/**\n * A live tool result (`tool-output-available`): Ghuri AI streams checked pictures as\n * `{ ghuriToolImages: 1, output, images }` and sends anything a product shaped like that as text, so only this shape\n * draws pictures here. Saved conversations go through `splitSavedOutput`.\n */\nexport function splitToolOutput(raw: unknown): { output: unknown; images: ToolImage[] } {\n const r = raw as any\n if (r && typeof r === 'object' && r.ghuriToolImages === 1 && Array.isArray(r.images)) {\n return {\n output: parsedOutput(r.output),\n images: r.images.map(cleanImage).filter(Boolean) as ToolImage[],\n }\n }\n return { output: parsedOutput(raw), images: [] }\n}\n\n/**\n * A saved tool result with pictures: what the model was given (`{ type: 'content', value: [text…, file…] }`). Ghuri AI\n * saves that shape only for checked pictures; a product's own JSON is saved as `{ type: 'json' }`.\n */\nexport function splitSavedOutput(saved: { value?: unknown }): { output: unknown; images: ToolImage[] } {\n const value = Array.isArray(saved?.value) ? (saved.value as any[]) : []\n const text = value\n .filter((p) => p?.type === 'text' && typeof p.text === 'string')\n .map((p) => p.text)\n .join('\\n')\n const images = value\n .filter((p) => p?.type === 'file' && p.data?.type === 'data')\n .map((p) => cleanImage({ mediaType: p.mediaType, data: p.data.data }))\n .filter(Boolean) as ToolImage[]\n return { output: parsedOutput(text), images }\n}\n","// A saved conversation (`GET /v1/conversations/<id>`) as the widget's messages. Ghuri AI stores AI SDK model\n// messages: `user`, then `assistant` and `tool` messages until the next user message. Everything between two user\n// messages becomes one assistant message, as it was shown while it streamed.\nimport { parsedOutput, splitSavedOutput } from './output'\nimport type { Attachment, ChatMessage, MessagePart, PendingApproval, ToolPart } from './types'\n\ntype Part = { type?: string; [key: string]: any }\ntype ModelMessage = { role?: string; content?: string | Part[] }\n\n/** The photos a saved user message carries (Ghuri AI keeps them under `providerOptions.ghuri.attachments`). */\nfunction photosOf(p: Part): Attachment[] | null {\n const list = p.providerOptions?.ghuri?.attachments\n if (!Array.isArray(list)) return null\n return list.filter(\n (a): a is Attachment =>\n !!a && typeof a === 'object' && typeof a.ref === 'string' && typeof a.name === 'string',\n )\n}\n\n/** A note Ghuri AI added to the message for the model (today's date): not the user's words, never shown. */\nfunction isNote(p: Part): boolean {\n return typeof p.providerOptions?.ghuri?.note === 'string'\n}\n\nfunction textOf(content: ModelMessage['content']): string {\n if (typeof content === 'string') return content\n return (content ?? [])\n .filter((p) => p.type === 'text' && typeof p.text === 'string' && !photosOf(p) && !isNote(p))\n .map((p) => p.text as string)\n .join('')\n}\n\nfunction outputOf(output: any): {\n state: ToolPart['state']\n output?: unknown\n images?: ToolPart['images']\n errorText?: string\n} {\n switch (output?.type) {\n case 'execution-denied':\n return { state: 'denied', errorText: typeof output.reason === 'string' ? output.reason : undefined }\n case 'error-text':\n case 'error-json':\n return {\n state: 'error',\n errorText: typeof output.value === 'string' ? output.value : JSON.stringify(output.value),\n }\n case undefined:\n return { state: 'done', output }\n case 'content': {\n // A result with pictures: its text, and the pictures for the step's thumbnails.\n const split = splitSavedOutput(output)\n return { state: 'done', output: split.output, ...(split.images.length ? { images: split.images } : {}) }\n }\n default:\n // Saved results keep the server's text; JSON text is parsed for cards and counts.\n return { state: 'done', output: parsedOutput(output.value) }\n }\n}\n\n/**\n * Convert saved messages. `titles` (tool name → title) labels tool steps; saved messages do not carry titles, so it\n * holds what the widget learnt while streaming, plus the titles of `pending` approvals.\n */\nexport function messagesFromHistory(\n messages: ModelMessage[],\n pending: PendingApproval[] = [],\n titles: Map<string, string> = new Map(),\n): ChatMessage[] {\n const out: ChatMessage[] = []\n const tools = new Map<string, ToolPart>()\n const byApproval = new Map<string, ToolPart>()\n for (const a of pending) if (a.title) titles.set(a.toolName, a.title)\n let assistant: ChatMessage | null = null\n let n = 0\n\n const current = (): ChatMessage => {\n if (!assistant) {\n assistant = { id: `h${n++}`, role: 'assistant', parts: [] }\n out.push(assistant)\n }\n return assistant\n }\n\n for (const m of messages) {\n if (m.role === 'user') {\n assistant = null\n // The photo list the model read is not shown as text; its photos are.\n const photos = Array.isArray(m.content) ? m.content.flatMap((p) => photosOf(p) ?? []) : []\n const text = textOf(m.content)\n const parts: MessagePart[] = []\n if (photos.length) parts.push({ kind: 'attachments', id: `h${n++}`, attachments: photos })\n if (text || !photos.length) parts.push({ kind: 'text', id: `h${n++}`, text })\n out.push({ id: `h${n++}`, role: 'user', parts })\n continue\n }\n if (m.role === 'assistant') {\n const msg = current()\n const content: Part[] =\n typeof m.content === 'string' ? [{ type: 'text', text: m.content }] : (m.content ?? [])\n for (const p of content) {\n if (p.type === 'text' && typeof p.text === 'string' && p.text) {\n const last = msg.parts.at(-1)\n if (last?.kind === 'text') last.text += p.text\n else msg.parts.push({ kind: 'text', id: `h${n++}`, text: p.text })\n } else if (p.type === 'tool-call' && typeof p.toolCallId === 'string') {\n const title = titles.get(p.toolName)\n const part: ToolPart = {\n kind: 'tool',\n toolCallId: p.toolCallId,\n toolName: String(p.toolName ?? ''),\n ...(title ? { title } : {}),\n input: p.input,\n state: 'running',\n }\n tools.set(part.toolCallId, part)\n msg.parts.push(part)\n } else if (p.type === 'tool-approval-request' && typeof p.toolCallId === 'string') {\n const part = tools.get(p.toolCallId)\n if (part) {\n part.state = 'awaiting-approval'\n part.approvalId = p.approvalId\n byApproval.set(p.approvalId, part)\n }\n }\n }\n continue\n }\n if (m.role === 'tool' && Array.isArray(m.content)) {\n for (const p of m.content) {\n if (p.type === 'tool-approval-response') {\n const part = byApproval.get(p.approvalId)\n if (part && part.state === 'awaiting-approval') part.state = p.approved ? 'running' : 'denied'\n } else if (p.type === 'tool-result') {\n const part = tools.get(p.toolCallId)\n if (part) Object.assign(part, outputOf(p.output))\n }\n }\n }\n }\n\n // A call still waiting is only waiting if the server says so (anything else was closed by a later message).\n const waiting = new Set(pending.map((a) => a.toolCallId))\n for (const part of tools.values()) {\n if (part.state === 'awaiting-approval' && !waiting.has(part.toolCallId)) part.state = 'denied'\n }\n return out.filter((m) => m.parts.length > 0) as ChatMessage[]\n}\n\n/** Every part of `messages`, for lookups by tool call id. */\nexport function toolParts(messages: ChatMessage[]): Map<string, ToolPart> {\n const out = new Map<string, ToolPart>()\n for (const m of messages)\n for (const p of m.parts as MessagePart[]) if (p.kind === 'tool') out.set(p.toolCallId, p)\n return out\n}\n","// Getting a photo ready to upload, in the browser: scale it so its longest edge is at most `maxEdge` and re-encode\n// it, which also drops its metadata (EXIF, including the phone's GPS location). A GIF is kept as it is (re-encoding\n// would lose its animation; GIFs carry no EXIF). Where the browser cannot decode or encode the picture, the file is\n// sent unchanged and the product's own checks decide.\nimport type { PreparedImage } from './types'\n\nconst QUALITY = 0.85\n\n/** The size to draw at: the longest edge at most `maxEdge`, never enlarged. */\nexport function scaledSize(\n width: number,\n height: number,\n maxEdge: number,\n): { width: number; height: number } {\n const longest = Math.max(width, height)\n if (!longest || longest <= maxEdge) return { width, height }\n const k = maxEdge / longest\n return { width: Math.max(1, Math.round(width * k)), height: Math.max(1, Math.round(height * k)) }\n}\n\nexport async function prepareImage(\n file: Blob,\n opts: { maxEdge: number; contentType: string },\n): Promise<PreparedImage> {\n const { contentType } = opts\n if (contentType === 'image/gif' || typeof createImageBitmap !== 'function')\n return { blob: file, contentType }\n let bitmap: ImageBitmap\n try {\n // 'from-image' turns the picture upright from its EXIF orientation before the EXIF is dropped.\n bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' })\n } catch {\n return { blob: file, contentType }\n }\n try {\n const size = scaledSize(bitmap.width, bitmap.height, opts.maxEdge)\n const blob = await encode(bitmap, size, contentType)\n if (!blob) return { blob: file, contentType, width: bitmap.width, height: bitmap.height }\n return { blob, contentType: blob.type || contentType, ...size }\n } finally {\n bitmap.close()\n }\n}\n\nasync function encode(\n bitmap: ImageBitmap,\n size: { width: number; height: number },\n contentType: string,\n): Promise<Blob | null> {\n if (typeof OffscreenCanvas === 'function') {\n const canvas = new OffscreenCanvas(size.width, size.height)\n const ctx = canvas.getContext('2d')\n if (!ctx) return null\n ctx.drawImage(bitmap, 0, 0, size.width, size.height)\n return canvas.convertToBlob({ type: contentType, quality: QUALITY }).catch(() => null)\n }\n if (typeof document === 'undefined') return null\n const canvas = document.createElement('canvas')\n canvas.width = size.width\n canvas.height = size.height\n const ctx = canvas.getContext('2d')\n if (!ctx) return null\n ctx.drawImage(bitmap, 0, 0, size.width, size.height)\n return new Promise((resolve) => canvas.toBlob((b) => resolve(b), contentType, QUALITY))\n}\n","// Reading Ghuri AI's reply stream: Server-Sent Events whose `data:` lines are AI SDK UI message chunks\n// (`{\"type\":\"text-delta\",…}`), ending with `data: [DONE]`. Written here rather than taken from the AI SDK so the\n// logic layer has no dependencies and the same rules can be ported to the Kotlin library.\n\n/** One parsed chunk. Unknown types are passed through and ignored by the client. */\nexport type StreamChunk = { type: string; [key: string]: unknown }\n\n/** Parse a complete SSE text (tests, or a body read in one go). */\nexport function parseSse(text: string): StreamChunk[] {\n const parser = new SseParser()\n const out = parser.push(text)\n out.push(...parser.end())\n return out\n}\n\n/**\n * An incremental SSE parser: feed it text as it arrives, get back the chunks whose events are complete. Handles events\n * split across reads, `\\r\\n` line endings, comment lines and several `data:` lines per event (joined with `\\n`).\n */\nexport class SseParser {\n private buffer = ''\n /** A `\\r` that ended the last read: it may be the first half of a `\\r\\n` split across two reads. */\n private carry = ''\n /** True once `data: [DONE]` was seen. */\n done = false\n\n push(text: string): StreamChunk[] {\n let t = this.carry + text\n this.carry = ''\n if (t.endsWith('\\r')) {\n this.carry = '\\r'\n t = t.slice(0, -1)\n }\n this.buffer += t.replace(/\\r\\n?/g, '\\n')\n const out: StreamChunk[] = []\n let end = this.buffer.indexOf('\\n\\n')\n while (end !== -1) {\n const event = this.buffer.slice(0, end)\n this.buffer = this.buffer.slice(end + 2)\n const chunk = this.parseEvent(event)\n if (chunk) out.push(chunk)\n end = this.buffer.indexOf('\\n\\n')\n }\n return out\n }\n\n /** The stream ended: parse what is left (an event without its blank line). */\n end(): StreamChunk[] {\n this.carry = ''\n const rest = this.buffer.trim()\n this.buffer = ''\n if (!rest) return []\n const chunk = this.parseEvent(rest)\n return chunk ? [chunk] : []\n }\n\n private parseEvent(event: string): StreamChunk | null {\n const data: string[] = []\n for (const line of event.split('\\n')) {\n if (line.startsWith('data:')) data.push(line.slice(line.startsWith('data: ') ? 6 : 5))\n }\n if (!data.length) return null\n const payload = data.join('\\n')\n if (payload === '[DONE]') {\n this.done = true\n return null\n }\n try {\n const value = JSON.parse(payload)\n return value && typeof value === 'object' && typeof value.type === 'string'\n ? (value as StreamChunk)\n : null\n } catch {\n return null\n }\n }\n}\n\n/** Read a fetch response body as stream chunks, as they arrive. */\nexport async function* readChunks(\n body: ReadableStream<Uint8Array>,\n signal?: AbortSignal,\n): AsyncGenerator<StreamChunk> {\n const parser = new SseParser()\n const decoder = new TextDecoder()\n const reader = body.getReader()\n // Stopping must also end a read that is waiting for the next bytes.\n const cancel = () => void reader.cancel().catch(() => {})\n signal?.addEventListener('abort', cancel, { once: true })\n try {\n while (true) {\n if (signal?.aborted) return\n const { value, done } = await reader.read()\n if (done) break\n for (const chunk of parser.push(decoder.decode(value, { stream: true }))) yield chunk\n }\n for (const chunk of parser.push(decoder.decode())) yield chunk\n for (const chunk of parser.end()) yield chunk\n } finally {\n signal?.removeEventListener('abort', cancel)\n reader.releaseLock()\n }\n}\n","// The widget's logic layer: one chat with Ghuri AI for one signed-in user. It starts and renews the session through\n// the product's backend, sends messages, reads the streamed reply, handles confirmations, history and every error,\n// and publishes plain state for a UI to draw. It never sees the app key or the user's MCP token; the session token\n// lives in memory only.\nimport { messagesFromHistory } from './history'\nimport { splitToolOutput } from './output'\nimport { prepareImage } from './prepare'\nimport { parseSse, readChunks, type StreamChunk } from './sse'\nimport type {\n Allowance,\n Attachment,\n AttachmentPolicy,\n AttachmentsPart,\n ChangePreview,\n ChatClientOptions,\n ChatEvents,\n ChatMessage,\n ChatState,\n ConversationSummary,\n Decision,\n PendingApproval,\n Problem,\n SessionInfo,\n TextPart,\n ToolPart,\n TurnResult,\n Upload,\n} from './types'\n\n/** A session is renewed this long before it expires, so a request never starts on a session about to end. */\nconst SESSION_MARGIN_MS = 30_000\n\ntype Listener = (state: ChatState) => void\ntype EventListener<K extends keyof ChatEvents> = (event: ChatEvents[K]) => void\n\n/** Photo defaults (Ghuri AI takes at most 10 per message; Commerce's limit is 5 MB). */\nexport const ATTACHMENT_DEFAULTS = {\n accept: ['image/jpeg', 'image/png', 'image/webp', 'image/gif'],\n maxCount: 10,\n maxBytes: 5 * 1024 * 1024,\n maxEdge: 2048,\n} as const\n\n/** A fresh empty state (new arrays every time: the state is changed in place). */\nfunction empty(canAttach = false): ChatState {\n return {\n status: 'idle',\n conversationId: null,\n messages: [],\n pendingApprovals: [],\n problem: null,\n lastTurn: null,\n canAttach,\n uploads: [],\n allowances: [],\n }\n}\n\nfunction objectUrl(blob: Blob): string | undefined {\n try {\n return typeof URL.createObjectURL === 'function' ? URL.createObjectURL(blob) : undefined\n } catch {\n return undefined\n }\n}\n\nfunction revoke(url: string | undefined): void {\n try {\n if (url && typeof URL.revokeObjectURL === 'function') URL.revokeObjectURL(url)\n } catch {\n // nothing to free\n }\n}\n\n/** A request answered with an error status, kept so the caller can turn it into a `Problem`. */\nclass HttpError extends Error {\n constructor(\n readonly status: number,\n readonly code: string,\n readonly detail: string,\n readonly retryAfter?: number,\n /** The field errors of a `400` (`{ attachments: [...] }`). */\n readonly fields: Record<string, unknown> = {},\n ) {\n super(detail || `HTTP ${status}`)\n }\n}\n\nasync function httpError(res: Response): Promise<HttpError> {\n let body: any = null\n try {\n body = await res.json()\n } catch {\n // not JSON\n }\n const retry = Number(res.headers.get('retry-after'))\n return new HttpError(\n res.status,\n typeof body?.code === 'string' ? body.code : '',\n typeof body?.detail === 'string' ? body.detail : '',\n Number.isFinite(retry) && retry > 0 ? retry : undefined,\n body && typeof body === 'object' && !Array.isArray(body) ? body : {},\n )\n}\n\n/** What the user is told about a failed request. */\nexport function problemFor(err: unknown): Problem {\n if (!(err instanceof HttpError)) return { code: 'unavailable' }\n const { status, code, detail } = err\n const photos = err.fields.attachments\n if (status === 400 && Array.isArray(photos))\n return { code: 'photos-refused', ...(typeof photos[0] === 'string' ? { message: photos[0] } : {}) }\n if (status === 429) return { code: 'throttled', ...(err.retryAfter ? { retryAfter: err.retryAfter } : {}) }\n if (code === 'turn_in_progress') return { code: 'in-progress' }\n if (code === 'conversation_too_long') return { code: 'conversation-full' }\n if (code === 'mcp_forbidden') return { code: 'forbidden' }\n if (code === 'mcp_unavailable' || status === 502) return { code: 'store-unreachable' }\n if (code === 'model_unavailable' || code === 'no_active_profile' || status === 503)\n return { code: 'unavailable' }\n return { code: 'failed', ...(detail ? { message: detail } : {}) }\n}\n\nfunction isAbort(err: unknown): boolean {\n return err instanceof DOMException ? err.name === 'AbortError' : (err as Error)?.name === 'AbortError'\n}\n\n/**\n * Whether a session is safe to use for a new request. An expiry that cannot be read is trusted until Ghuri AI says\n * otherwise (a 401 starts a new session), rather than starting a new session on every request.\n */\nfunction sessionUsable(s: SessionInfo, now: number): boolean {\n const expires = new Date(s.expiresAt).getTime()\n return Number.isNaN(expires) || expires - SESSION_MARGIN_MS > now\n}\n\n/** Copy the state so every change has new objects (React's useSyncExternalStore, Lit's change detection). */\nfunction snapshot(s: ChatState): ChatState {\n return {\n ...s,\n messages: s.messages.map((m) => ({ ...m, parts: m.parts.map((p) => ({ ...p })) })),\n pendingApprovals: [...s.pendingApprovals],\n uploads: s.uploads.map((u) => ({ ...u })),\n allowances: [...s.allowances],\n }\n}\n\nexport class ChatClient {\n private readonly opts: ChatClientOptions\n private state: ChatState\n private view: ChatState\n private readonly listeners = new Set<Listener>()\n private readonly events = new Map<keyof ChatEvents, Set<(e: any) => void>>()\n private session: SessionInfo | null = null\n private starting: Promise<SessionInfo> | null = null\n private controller: AbortController | null = null\n /** Every tool step of the open conversation, by tool call id (an approval's reply finishes earlier steps). */\n private tools = new Map<string, ToolPart>()\n /** Tool name → title, learnt from the stream (saved messages do not carry titles). */\n private readonly titles = new Map<string, string>()\n private retryAction: (() => Promise<void>) | null = null\n /**\n * Bumped whenever the open conversation is replaced (new, opened, ended). A turn or a load that started under an\n * older generation stops touching the state, so a reply that was replaced cannot overwrite what replaced it.\n */\n private generation = 0\n private seq = 0\n /** The files behind `state.uploads` (for retries) and their upload's abort controller. */\n private files = new Map<string, { file: Blob; controller?: AbortController }>()\n /** Object URLs made for chips and sent photos, freed when the conversation is replaced. */\n private previews = new Set<string>()\n /** The app's photo policy for new conversations, once Ghuri AI told us (`loadCapabilities`). */\n private policy: AttachmentPolicy | null = null\n private loadingPolicy: Promise<void> | null = null\n /** Set once the widget asked (it was shown); a new conversation then asks again, an ended client does not. */\n private capabilitiesWanted = false\n\n constructor(opts: ChatClientOptions) {\n this.opts = { ...opts, apiUrl: opts.apiUrl.replace(/\\/+$/, '') }\n // Photos are never offered before Ghuri AI says the app takes them (loadCapabilities).\n this.state = empty(false)\n this.view = snapshot(this.state)\n }\n\n // --- state and events ----------------------------------------------------------------------------------------\n\n getState(): ChatState {\n return this.view\n }\n\n /** Called on every change; returns the unsubscribe function. */\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener)\n return () => this.listeners.delete(listener)\n }\n\n on<K extends keyof ChatEvents>(name: K, listener: EventListener<K>): () => void {\n let set = this.events.get(name)\n if (!set) {\n set = new Set()\n this.events.set(name, set)\n }\n set.add(listener)\n return () => set.delete(listener)\n }\n\n private emit<K extends keyof ChatEvents>(name: K, event: ChatEvents[K]): void {\n for (const l of this.events.get(name) ?? []) l(event)\n }\n\n private changed(patch: Partial<ChatState> = {}): void {\n Object.assign(this.state, patch)\n this.view = snapshot(this.state)\n for (const l of this.listeners) l(this.view)\n }\n\n private id(prefix: string): string {\n this.seq += 1\n return `${prefix}${this.seq}`\n }\n\n // --- sessions ------------------------------------------------------------------------------------------------\n\n private now(): number {\n return (this.opts.now ?? Date.now)()\n }\n\n private async ensureSession(): Promise<SessionInfo> {\n const s = this.session\n if (s && sessionUsable(s, this.now())) return s\n this.session = null\n if (!this.starting) {\n this.starting = this.opts\n .startSession()\n .then((started) => {\n this.session = started\n return started\n })\n .finally(() => {\n this.starting = null\n })\n }\n return this.starting\n }\n\n /**\n * A request to Ghuri AI with the session token. A `401` is handled once: an expired user token is refreshed through\n * the product (or, if the product's session is gone, a new session started), an expired session is replaced; then\n * the request is sent again.\n */\n private async request(path: string, init: RequestInit = {}, retried = false): Promise<Response> {\n const session = await this.ensureSession()\n const headers = new Headers(init.headers)\n headers.set('authorization', `Bearer ${session.sessionToken}`)\n if (init.body !== undefined) headers.set('content-type', 'application/json')\n const res = await (this.opts.fetch ?? fetch)(`${this.opts.apiUrl}${path}`, { ...init, headers })\n if (res.status !== 401 || retried) return res\n const err = await httpError(res)\n this.changed({ problem: { code: 'reconnecting' } })\n if (err.code === 'user_token_expired') {\n try {\n await this.opts.refreshUserToken(session.sessionId)\n } catch {\n this.session = null // the product's session is gone: start a new one\n }\n } else {\n this.session = null\n }\n const again = await this.request(path, init, true)\n if (this.state.problem?.code === 'reconnecting') this.changed({ problem: null })\n return again\n }\n\n private async json<T>(path: string, init: RequestInit = {}): Promise<T> {\n const res = await this.request(path, init)\n if (!res.ok) throw await httpError(res)\n return (await res.json()) as T\n }\n\n // --- actions -------------------------------------------------------------------------------------------------\n\n /**\n * Send a message with the photos that finished uploading. Waiting changes, if any, are cancelled by it (Ghuri AI\n * closes them). Nothing is sent while a photo is still being prepared or uploaded.\n */\n async send(text: string): Promise<void> {\n const message = text.trim()\n const ready = this.state.uploads.filter((u) => u.status === 'ready' && u.attachment)\n if ((!message && !ready.length) || this.busy() || this.uploading() || this.retryable()) return\n for (const a of this.state.pendingApprovals) {\n const part = this.tools.get(a.toolCallId)\n if (part) part.state = 'denied'\n }\n const attachments = ready.map((u) => u.attachment as Attachment)\n const parts: ChatMessage['parts'] = []\n if (attachments.length) {\n const part: AttachmentsPart = {\n kind: 'attachments',\n id: this.id('p'),\n attachments: ready.map((u) => ({\n ...(u.attachment as Attachment),\n ...(u.previewUrl ? { previewUrl: u.previewUrl } : {}),\n })),\n }\n parts.push(part)\n }\n if (message) parts.push({ kind: 'text', id: this.id('t'), text: message })\n this.state.messages.push({ id: this.id('u'), role: 'user', parts })\n // The sent photos' previews stay in the message; refused ones are dropped with the draft.\n for (const u of this.state.uploads) if (u.status !== 'ready') revoke(u.previewUrl)\n this.files = new Map()\n this.changed({ pendingApprovals: [], problem: null, uploads: [] })\n const conversationId = this.state.conversationId\n await this.turn('/v1/chat', {\n message,\n ...(conversationId ? { conversationId } : {}),\n ...(attachments.length ? { attachments } : {}),\n // A new conversation takes photos only if the client that starts it can upload (Ghuri AI pins it).\n ...(!conversationId && this.opts.uploadFile ? { capabilities: { attachments: true } } : {}),\n })\n }\n\n // --- photos --------------------------------------------------------------------------------------------------\n\n /** The limits photos are checked against: the product's own, within what the app's profile takes. */\n attachmentLimits(): { accept: string[]; maxCount: number; maxBytes: number; maxEdge: number } {\n const o = this.opts.attachments ?? {}\n // The product's own limits, within what the app's profile takes (the profile is the upper bound).\n const mine = o.accept?.length ? o.accept : [...ATTACHMENT_DEFAULTS.accept]\n const allowed = this.policy?.accept?.length ? this.policy.accept : null\n return {\n accept: allowed ? mine.filter((t) => allowed.includes(t)) : mine,\n maxCount: Math.min(\n o.maxCount ?? ATTACHMENT_DEFAULTS.maxCount,\n this.policy?.maxCount ?? ATTACHMENT_DEFAULTS.maxCount,\n ATTACHMENT_DEFAULTS.maxCount,\n ),\n maxBytes: o.maxBytes ?? ATTACHMENT_DEFAULTS.maxBytes,\n maxEdge: o.maxEdge ?? ATTACHMENT_DEFAULTS.maxEdge,\n }\n }\n\n /** A photo that failed to upload and can be retried: sending would silently leave it out. */\n private retryable(): boolean {\n return this.state.uploads.some((u) => u.status === 'failed' && u.error === 'upload')\n }\n\n /** Whether a new conversation offers photos: this client can upload and the app's profile takes them. */\n private newConversationTakesPhotos(): boolean {\n return !!this.opts.uploadFile && this.policy?.enabled === true\n }\n\n /**\n * Ask Ghuri AI whether the app takes photos (once; again after a refusal). Until it answers, no photo button: a\n * photo uploaded to an app that refuses it would only leave a stray file in the product. Starts the session.\n */\n loadCapabilities(): Promise<void> {\n if (!this.opts.uploadFile) return Promise.resolve()\n this.capabilitiesWanted = true\n if (this.policy) return Promise.resolve()\n if (this.loadingPolicy) return this.loadingPolicy\n this.loadingPolicy = (async () => {\n try {\n const data = await this.json<{ attachments?: Partial<AttachmentPolicy> }>('/v1/capabilities')\n const a = data?.attachments ?? {}\n this.policy = {\n enabled: a.enabled === true,\n ...(Array.isArray(a.accept) ? { accept: a.accept.filter((t) => typeof t === 'string') } : {}),\n ...(Number.isInteger(a.maxCount) ? { maxCount: a.maxCount } : {}),\n }\n } catch (err) {\n // An older Ghuri AI without the endpoint: no photos. Anything else: ask again next time.\n if (err instanceof HttpError && err.status === 404) this.policy = { enabled: false }\n } finally {\n this.loadingPolicy = null\n }\n if (!this.state.conversationId && this.state.canAttach !== this.newConversationTakesPhotos())\n this.changed({ canAttach: this.newConversationTakesPhotos() })\n })()\n return this.loadingPolicy\n }\n\n private uploading(): boolean {\n return this.state.uploads.some((u) => u.status === 'preparing' || u.status === 'uploading')\n }\n\n private upload(id: string): Upload | undefined {\n return this.state.uploads.find((u) => u.id === id)\n }\n\n private refuse(u: Upload, reason: 'type' | 'size' | 'count' | 'upload', message?: string): void {\n u.status = 'failed'\n u.error = reason\n if (message) u.message = message\n this.emit('attachment-error', {\n name: u.name,\n contentType: u.contentType,\n reason,\n ...(message ? { message } : {}),\n })\n }\n\n /**\n * Add photos to the message being written: each is checked, scaled (location data dropped) and uploaded to the\n * product. Refused ones stay as failed chips the user can remove. Does nothing where photos are not offered.\n */\n addFiles(files: Iterable<Blob> | ArrayLike<Blob>): void {\n if (!this.state.canAttach || !this.opts.uploadFile) return\n const { accept, maxCount } = this.attachmentLimits()\n for (const file of Array.from(files as ArrayLike<Blob>)) {\n const name = (file as File).name || 'photo'\n const contentType = file.type || ''\n const u: Upload = {\n id: this.id('f'),\n name,\n contentType,\n size: file.size,\n status: 'preparing',\n progress: 0,\n }\n const preview = accept.includes(contentType) ? objectUrl(file) : undefined\n if (preview) {\n u.previewUrl = preview\n this.previews.add(preview)\n }\n this.state.uploads.push(u)\n const kept = this.state.uploads.filter((x) => x.status !== 'failed' || x.error === 'upload').length\n if (!accept.includes(contentType)) this.refuse(u, 'type')\n else if (kept > maxCount) this.refuse(u, 'count')\n else {\n this.files.set(u.id, { file })\n void this.startUpload(u.id)\n }\n }\n this.changed()\n }\n\n /** Take a photo off the message being written (stops its upload). */\n removeUpload(id: string): void {\n const u = this.upload(id)\n if (!u) return\n if (u.attachment) this.discard(u.attachment)\n this.files.get(id)?.controller?.abort()\n this.files.delete(id)\n revoke(u.previewUrl)\n if (u.previewUrl) this.previews.delete(u.previewUrl)\n this.changed({ uploads: this.state.uploads.filter((x) => x.id !== id) })\n }\n\n /** Upload a photo again after it failed to upload. */\n retryUpload(id: string): void {\n const u = this.upload(id)\n if (u?.status !== 'failed' || u.error !== 'upload' || !this.files.has(id)) return\n void this.startUpload(id)\n }\n\n private async startUpload(id: string): Promise<void> {\n const entry = this.files.get(id)\n const u = this.upload(id)\n const uploadFile = this.opts.uploadFile\n if (!entry || !u || !uploadFile) return\n const generation = this.generation\n const live = () => generation === this.generation && this.upload(id) === u\n const controller = new AbortController()\n entry.controller = controller\n Object.assign(u, { status: 'preparing', progress: 0, error: undefined, message: undefined })\n this.changed()\n const { maxBytes, maxEdge } = this.attachmentLimits()\n try {\n const prepare = this.opts.prepareImage ?? prepareImage\n let prepared: Awaited<ReturnType<typeof prepare>>\n try {\n prepared = await prepare(entry.file, { maxEdge, contentType: u.contentType })\n } catch {\n prepared = { blob: entry.file, contentType: u.contentType }\n }\n if (!live() || controller.signal.aborted) return\n if (prepared.blob.size > maxBytes) {\n this.refuse(u, 'size')\n this.changed()\n return\n }\n Object.assign(u, { status: 'uploading', size: prepared.blob.size })\n this.changed()\n const attachment = await uploadFile(prepared.blob, {\n name: u.name,\n contentType: prepared.contentType,\n size: prepared.blob.size,\n ...(prepared.width ? { width: prepared.width } : {}),\n ...(prepared.height ? { height: prepared.height } : {}),\n signal: controller.signal,\n onProgress: (fraction) => {\n if (!live() || u.status !== 'uploading') return\n u.progress = Math.max(0, Math.min(1, Number(fraction) || 0))\n this.changed()\n },\n })\n if (!live() || controller.signal.aborted) {\n // Removed (or the conversation changed) while it uploaded: the product has it, but it will not be sent.\n if (attachment && typeof attachment.ref === 'string' && attachment.ref) this.discard(attachment)\n return\n }\n if (!attachment || typeof attachment.ref !== 'string' || !attachment.ref)\n throw new Error('The upload gave no reference.')\n Object.assign(u, {\n status: 'ready',\n progress: 1,\n attachment: {\n ...attachment,\n name: attachment.name || u.name,\n contentType: attachment.contentType || prepared.contentType,\n ...(prepared.width && !attachment.width ? { width: prepared.width } : {}),\n ...(prepared.height && !attachment.height ? { height: prepared.height } : {}),\n },\n })\n this.changed()\n } catch (err) {\n if (!live() || isAbort(err) || controller.signal.aborted) return\n this.refuse(u, 'upload', err instanceof Error && err.message ? err.message : undefined)\n this.changed()\n }\n }\n\n /** Stop every upload and free every preview (the conversation is replaced). */\n /** Tell the product an uploaded photo will not be sent (it may delete it). Never throws. */\n private discard(attachment: Attachment): void {\n const discardFile = this.opts.discardFile\n if (!discardFile) return\n try {\n void Promise.resolve(discardFile(attachment)).catch(() => {})\n } catch {\n // the product's callback failed: nothing to do\n }\n }\n\n private dropPhotos(): void {\n // A draft the user moved away from: its uploaded photos will not be sent.\n for (const u of this.state.uploads) if (u.attachment) this.discard(u.attachment)\n for (const entry of this.files.values()) entry.controller?.abort()\n this.files = new Map()\n for (const url of this.previews) revoke(url)\n this.previews = new Set()\n }\n\n /** Confirm or cancel the waiting changes: one decision for each, sent together. */\n async decide(decisions: Decision[]): Promise<void> {\n const id = this.state.conversationId\n if (!id || this.busy() || !this.state.pendingApprovals.length) return\n const pending = this.state.pendingApprovals\n const byId = new Map(decisions.map((d) => [d.approvalId, d]))\n for (const a of pending) {\n const part = this.tools.get(a.toolCallId)\n const d = byId.get(a.approvalId)\n if (part) part.state = d?.approved ? 'running' : 'denied'\n if (part && d?.approved && d.allowForConversation) part.granted = true\n }\n this.changed({ pendingApprovals: [], problem: null })\n const outcome = await this.turn(`/v1/conversations/${encodeURIComponent(id)}/approvals`, { decisions })\n if (outcome !== 'not-sent') return\n // The decisions never reached Ghuri AI (or it refused them): the changes are still waiting, as they were.\n for (const a of pending) {\n const part = this.tools.get(a.toolCallId)\n if (part) {\n part.state = 'awaiting-approval'\n delete part.granted\n }\n }\n this.retryAction = () => this.decide(decisions)\n this.changed({ pendingApprovals: pending, status: 'awaiting-approval' })\n }\n\n /**\n * Take back \"Allow for this conversation\" for a tool: its next call asks again. Returns whether Ghuri AI took it\n * back (false: nothing was in force, or the request failed; the problem then says why).\n */\n async revokeAllowance(toolName: string): Promise<boolean> {\n const id = this.state.conversationId\n if (!id) return false\n try {\n const data = await this.json<{ allowances?: Allowance[] }>(\n `/v1/conversations/${encodeURIComponent(id)}/allowances/${encodeURIComponent(toolName)}`,\n { method: 'DELETE' },\n )\n this.changed({ allowances: data.allowances ?? [] })\n return true\n } catch (err) {\n // 404: it had already ended (expired, or taken back elsewhere); either way nothing is allowed for it now.\n const problem = problemFor(err)\n this.changed({\n allowances: this.state.allowances.filter((a) => a.toolName !== toolName),\n ...((err as { status?: number })?.status === 404 ? {} : { problem }),\n })\n return false\n }\n }\n\n /** Confirm every waiting change. */\n approveAll(): Promise<void> {\n return this.decide(this.state.pendingApprovals.map((a) => ({ approvalId: a.approvalId, approved: true })))\n }\n\n /** Cancel every waiting change. */\n rejectAll(reason?: string): Promise<void> {\n return this.decide(\n this.state.pendingApprovals.map((a) => ({\n approvalId: a.approvalId,\n approved: false,\n ...(reason ? { reason } : {}),\n })),\n )\n }\n\n /** Stop the reply being written (Ghuri AI stops the turn; what finished is kept). */\n stop(): void {\n this.controller?.abort()\n }\n\n /** Run the action that failed again (Try again). */\n async retry(): Promise<void> {\n const action = this.retryAction\n if (!action || this.busy()) return\n this.retryAction = null\n this.changed({ problem: null })\n await action()\n }\n\n dismissProblem(): void {\n this.changed({ problem: null })\n }\n\n /** Start a new conversation (the next message creates it). */\n newConversation(): void {\n this.reset()\n // Ask again only when photos were already asked about (the widget is shown): a hidden panel starts no session.\n if (this.capabilitiesWanted) void this.loadCapabilities()\n }\n\n /** Forget the open conversation (new conversation, end). */\n private reset(): void {\n this.generation += 1\n this.controller?.abort()\n this.dropPhotos()\n this.tools = new Map()\n this.retryAction = null\n this.state = empty(this.newConversationTakesPhotos())\n this.changed()\n }\n\n /** The user's conversations in this product and tenant, newest first. */\n async listConversations(opts: { limit?: number; offset?: number } = {}): Promise<{\n count: number\n results: ConversationSummary[]\n }> {\n const q = new URLSearchParams({ limit: String(opts.limit ?? 30), offset: String(opts.offset ?? 0) })\n return this.json(`/v1/conversations?${q}`)\n }\n\n /** Open a saved conversation, including any change still waiting for a decision. */\n async openConversation(id: string): Promise<void> {\n this.generation += 1\n const generation = this.generation\n this.controller?.abort()\n this.changed({ status: 'loading', problem: null })\n try {\n const data = await this.json<{\n messages: any[]\n pendingApprovals: PendingApproval[]\n toolTitles?: Record<string, string>\n attachments?: boolean\n allowances?: Allowance[]\n allowedCalls?: Array<{ toolCallId: string; preview?: ChangePreview }>\n }>(`/v1/conversations/${encodeURIComponent(id)}`)\n if (generation !== this.generation) return // replaced while it loaded\n // Saved messages carry no titles; the server keeps the ones this conversation's tools had.\n for (const [name, title] of Object.entries(data.toolTitles ?? {}))\n if (typeof title === 'string' && title) this.titles.set(name, title)\n const pending = data.pendingApprovals ?? []\n for (const a of pending) if (a.title) this.titles.set(a.toolName, a.title)\n const messages = messagesFromHistory(data.messages ?? [], pending, this.titles)\n this.tools = new Map()\n for (const m of messages)\n for (const p of m.parts) if (p.kind === 'tool') this.tools.set(p.toolCallId, p)\n this.keepPreviews(pending)\n // Steps that ran without a card, on an allowance: marked, with what they changed.\n for (const c of data.allowedCalls ?? []) {\n const part = this.tools.get(c.toolCallId)\n if (!part) continue\n part.allowed = true\n if (c.preview) part.preview = c.preview\n }\n this.retryAction = null\n this.dropPhotos()\n this.state = {\n // Photos only where the conversation was started with them (Ghuri AI pins it) and this client can upload.\n ...empty(!!this.opts.uploadFile && data.attachments === true),\n conversationId: id,\n messages,\n pendingApprovals: pending,\n allowances: data.allowances ?? [],\n status: pending.length ? 'awaiting-approval' : 'idle',\n }\n this.changed()\n } catch (err) {\n if (generation !== this.generation) return\n this.retryAction = () => this.openConversation(id)\n this.changed({ status: 'idle', problem: problemFor(err) })\n }\n }\n\n /** Load the open conversation again (after a reply was cut off). */\n async reload(): Promise<void> {\n if (this.state.conversationId) await this.openConversation(this.state.conversationId)\n }\n\n /** End the session through the product (logout, store switch) and forget everything. */\n async end(): Promise<void> {\n this.controller?.abort()\n const session = this.session\n this.session = null\n // Ending never starts anything: no capabilities request, so no new session for a widget that is going away.\n this.capabilitiesWanted = false\n this.reset()\n if (session) await this.opts.endSession?.(session.sessionId)\n }\n\n private busy(): boolean {\n return (\n this.state.status === 'sending' || this.state.status === 'streaming' || this.state.status === 'loading'\n )\n }\n\n // --- a turn --------------------------------------------------------------------------------------------------\n\n /**\n * Post a message or decisions and read the streamed reply into a new assistant message. Returns `not-sent` when the\n * request failed or was refused before a reply started (nothing happened on the server), else `answered`.\n */\n private async turn(path: string, body: unknown): Promise<'answered' | 'not-sent'> {\n const generation = this.generation\n const current = () => generation === this.generation\n const assistant: ChatMessage = { id: this.id('a'), role: 'assistant', parts: [] }\n this.state.messages.push(assistant)\n this.changed({ status: 'sending' })\n const controller = new AbortController()\n this.controller = controller\n let res: Response\n try {\n res = await this.request(path, {\n method: 'POST',\n body: JSON.stringify(body),\n // JSON as a fallback: servers that negotiate content types strictly still answer, and still stream.\n headers: { accept: 'text/event-stream, application/json;q=0.9' },\n signal: controller.signal,\n })\n if (!res.ok) throw await httpError(res)\n } catch (err) {\n if (this.controller === controller) this.controller = null\n if (!current()) return 'answered' // replaced meanwhile: leave the new conversation alone\n this.drop(assistant)\n if (isAbort(err)) {\n this.changed({ status: 'idle' })\n return 'not-sent'\n }\n const problem = problemFor(err)\n if (problem.code === 'photos-refused') {\n // Not this app or not this conversation: take the unsent message back, stop offering photos here, and ask\n // Ghuri AI again what new conversations take. Sending the same photos again would only be refused again.\n const user = this.state.messages.at(-1)\n if (user?.role === 'user') this.drop(user)\n this.policy = null\n this.changed({ status: 'idle', problem, canAttach: false })\n void this.loadCapabilities()\n return 'not-sent'\n }\n this.retryAction = () => this.turn(path, body).then(() => undefined)\n this.changed({ status: 'idle', problem })\n return 'not-sent'\n }\n\n if (!current()) return 'answered'\n this.changed({ status: 'streaming' })\n let finished = false\n let turn: TurnResult | null = null\n let cut = false\n const texts = new Map<string, TextPart>()\n try {\n const chunks = res.body ? readChunks(res.body, controller.signal) : textChunks(await res.text())\n for await (const chunk of chunks) {\n if (!current()) break\n if (chunk.type === 'finish') finished = true\n else if (chunk.type === 'data-turn') turn = chunk.data as TurnResult\n this.apply(chunk, assistant, texts)\n this.changed()\n }\n } catch (err) {\n if (!isAbort(err)) cut = true\n } finally {\n if (this.controller === controller) this.controller = null\n }\n if (!current()) return 'answered'\n if (!assistant.parts.length) this.drop(assistant)\n\n if (turn) {\n this.finishTurn(turn)\n } else {\n // Stopped by the user, or the connection dropped before the reply finished.\n const stopped = controller.signal.aborted\n this.settleUnfinished(stopped)\n if (!stopped && (cut || !finished) && !this.state.problem) this.state.problem = { code: 'cut-off' }\n this.changed({ status: this.state.pendingApprovals.length ? 'awaiting-approval' : 'idle' })\n }\n return 'answered'\n }\n\n /**\n * Steps still writing or running when a reply ended early never get their result: mark them, so nothing spins\n * forever. A confirmed change in that state may or may not have run (\"outcome unknown\").\n */\n private settleUnfinished(stopped: boolean): void {\n const why = stopped ? 'Stopped before it finished.' : 'The reply was cut off before it finished.'\n for (const part of this.tools.values()) {\n if (part.state !== 'input' && part.state !== 'running') continue\n part.state = 'error'\n part.errorText = part.approvalId\n ? `${why} The result was not recorded; check before trying again.`\n : why\n }\n }\n\n private drop(message: ChatMessage): void {\n this.state.messages = this.state.messages.filter((m) => m !== message)\n }\n\n private finishTurn(turn: TurnResult): void {\n // A step still writing or running when the turn ended never gets a result now (a call cut at the output limit\n // stops while its input is still streaming): settle it, so no step is left spinning.\n this.settleUnfinished(false)\n const pending = turn.pendingApprovals ?? []\n for (const a of pending) if (a.title) this.titles.set(a.toolName, a.title)\n this.keepPreviews(pending)\n let problem: Problem | null = this.state.problem\n if (turn.userTokenExpired) {\n problem = { code: 'token-expired' }\n // Renew the token now, so \"Continue\" works; a failure here is handled on the next request.\n const s = this.session\n if (s) this.opts.refreshUserToken(s.sessionId).catch(() => (this.session = null))\n } else if (turn.limitReached === 'steps') {\n problem = { code: 'step-limit' }\n } else if (turn.status === 'error') {\n problem =\n turn.limitReached === 'conversation'\n ? { code: 'conversation-full' }\n : turn.limitReached === 'output'\n ? { code: turn.cut === 'text' ? 'answer-cut' : 'too-long' }\n : { code: 'failed', ...(turn.error ? { message: turn.error } : {}) }\n }\n this.changed({\n conversationId: turn.conversationId ?? this.state.conversationId,\n pendingApprovals: pending,\n lastTurn: turn,\n allowances: turn.allowances ?? [],\n problem,\n status: pending.length ? 'awaiting-approval' : 'idle',\n })\n if (pending.length) this.emit('approval-pending', { approvals: pending })\n this.emit('turn-end', turn)\n }\n\n /** Copy each waiting change's preview onto its step, so the record after the decision still names it. */\n private keepPreviews(pending: PendingApproval[]): void {\n for (const a of pending) {\n const part = this.tools.get(a.toolCallId)\n if (part && a.preview) part.preview = a.preview\n }\n }\n\n /** Apply one stream chunk to the reply being written. */\n private apply(chunk: StreamChunk, assistant: ChatMessage, texts: Map<string, TextPart>): void {\n const c = chunk as any\n switch (chunk.type) {\n case 'start': {\n const id = c.messageMetadata?.conversationId\n if (typeof id === 'string') this.state.conversationId = id\n return\n }\n case 'text-start': {\n const part: TextPart = { kind: 'text', id: this.id('t'), text: '' }\n texts.set(String(c.id), part)\n assistant.parts.push(part)\n return\n }\n case 'text-delta': {\n let part = texts.get(String(c.id))\n if (!part) {\n part = { kind: 'text', id: this.id('t'), text: '' }\n texts.set(String(c.id), part)\n assistant.parts.push(part)\n }\n part.text += String(c.delta ?? '')\n return\n }\n case 'tool-input-start':\n case 'tool-input-available': {\n const part = this.toolPart(c, assistant)\n if (chunk.type === 'tool-input-available') {\n part.input = c.input\n if (part.state === 'input') part.state = 'running'\n }\n return\n }\n case 'tool-input-error': {\n const part = this.toolPart(c, assistant)\n part.state = 'error'\n part.errorText = String(c.errorText ?? '')\n return\n }\n case 'tool-approval-request': {\n const part = this.tools.get(String(c.toolCallId))\n if (part) {\n part.state = 'awaiting-approval'\n part.approvalId = String(c.approvalId)\n }\n return\n }\n case 'tool-output-available':\n case 'tool-output-error': {\n const part = this.tools.get(String(c.toolCallId))\n if (!part) return\n if (chunk.type === 'tool-output-available') {\n part.state = 'done'\n const { output, images } = splitToolOutput(c.output)\n part.output = output\n if (images.length) part.images = images\n } else {\n part.state = 'error'\n part.errorText = String(c.errorText ?? '')\n }\n this.emit('tool-result', {\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n ...(part.title ? { title: part.title } : {}),\n input: part.input,\n ...(part.state === 'done' ? { output: part.output } : { error: part.errorText }),\n ...(part.images?.length ? { images: part.images } : {}),\n })\n return\n }\n case 'tool-output-denied': {\n const part = this.tools.get(String(c.toolCallId))\n if (part) part.state = 'denied'\n return\n }\n case 'data-allowed': {\n // A call that runs on an allowance: Ghuri AI marks it just before its result, with what it changed.\n const d = c.data ?? {}\n const part = this.tools.get(String(d.toolCallId))\n if (!part) return\n part.allowed = true\n if (d.preview) part.preview = d.preview as ChangePreview\n return\n }\n case 'error':\n this.state.problem = { code: 'failed', ...(c.errorText ? { message: String(c.errorText) } : {}) }\n return\n default:\n return // start-step, finish-step, text-end, tool-input-delta, finish, data-turn, unknown types\n }\n }\n\n private toolPart(c: any, assistant: ChatMessage): ToolPart {\n const id = String(c.toolCallId)\n let part = this.tools.get(id)\n if (!part) {\n part = { kind: 'tool', toolCallId: id, toolName: String(c.toolName ?? ''), state: 'input' }\n this.tools.set(id, part)\n assistant.parts.push(part)\n }\n if (typeof c.title === 'string' && c.title) {\n part.title = c.title\n this.titles.set(part.toolName, c.title)\n } else if (!part.title) {\n const known = this.titles.get(part.toolName)\n if (known) part.title = known\n }\n return part\n }\n}\n\nasync function* textChunks(text: string): AsyncGenerator<StreamChunk> {\n yield* parseSse(text)\n}\n"],"mappings":";AAKA,SAAgBA,EAAa,GAA0B;CACrD,IAAI,OAAOC,KAAW,UAAU,OAAOA;CACvC,IAAM,IAAIA,EAAO,KAAK;CACtB,IAAI,EAAE,EAAE,WAAW,GAAG,KAA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AIoF,CAAE;EAM5B,IALKpF,MACH,IAAO;GAAE,MAAM;GAAQ,YAAYoF;GAAI,UAAU,OAAO0B,EAAE,YAAY,EAAE;GAAG,OAAO;EAAQ,GAC1F,KAAK,MAAM,IAAI1B,GAAIpF,CAAI,GACvBV,EAAU,MAAM,KAAKU,CAAI,IAEvB,OAAO8G,EAAE,SAAU,YAAYA,EAAE,OAEnC,AADA,EAAK,QAAQA,EAAE,OACf,KAAK,OAAO,IAAI9G,EAAK,UAAU8G,EAAE,KAAK;OACjC,IAAI,CAAC9G,EAAK,OAAO;GACtB,IAAMwH,IAAQ,KAAK,OAAO,IAAIxH,EAAK,QAAQ;GAC3C,AAAIwH,MAAO,EAAK,QAAQA;EAC1B;EACA,OAAOxH;CACT;AACF;AAEA,gBAAgBqH,EAAW,GAA2C;CACpE,OAAOhG,EAAShD,CAAI;AACtB"}
|
package/dist/core.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as ATTACHMENT_DEFAULTS, n as ChatClient, i as SseParser, l as messagesFromHistory, a as parseSse, u as parsedOutput, s as prepareImage, r as problemFor, o as readChunks, c as scaledSize } from "./core-
|
|
1
|
+
export { t as ATTACHMENT_DEFAULTS, n as ChatClient, i as SseParser, l as messagesFromHistory, a as parseSse, u as parsedOutput, s as prepareImage, r as problemFor, o as readChunks, c as scaledSize, d as splitSavedOutput, f as splitToolOutput } from "./core-vIc1mTTy.js";
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { a as e, c as t,
|
|
2
|
-
import { t as
|
|
3
|
-
export {
|
|
1
|
+
import { a as e, c as t, d as n, f as r, i, l as a, n as o, o as s, r as c, s as l, t as u, u as d } from "./core-vIc1mTTy.js";
|
|
2
|
+
import { t as f } from "./src-DLeXsfmQ.js";
|
|
3
|
+
export { u as ATTACHMENT_DEFAULTS, o as ChatClient, f as GhuriChatElement, i as SseParser, a as messagesFromHistory, e as parseSse, d as parsedOutput, l as prepareImage, c as problemFor, s as readChunks, t as scaledSize, n as splitSavedOutput, r as splitToolOutput };
|
package/dist/react.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "./src-
|
|
1
|
+
import "./src-DLeXsfmQ.js";
|
|
2
2
|
import { createElement as e, forwardRef as t, useEffect as n, useImperativeHandle as r, useRef as i, useState as a } from "react";
|
|
3
3
|
import { createPortal as o } from "react-dom";
|
|
4
4
|
// src/react.tsx
|
|
@@ -31,6 +31,7 @@ var c = t(function(t, c) {
|
|
|
31
31
|
endSession: (e) => u.current.endSession?.(e) ?? Promise.resolve(),
|
|
32
32
|
...t.fetch ? { fetch: t.fetch } : {},
|
|
33
33
|
...t.uploadFile ? { uploadFile: (e, n) => (u.current.uploadFile ?? t.uploadFile)(e, n) } : {},
|
|
34
|
+
...t.discardFile ? { discardFile: (e) => (u.current.discardFile ?? t.discardFile)(e) } : {},
|
|
34
35
|
...t.attachments ? { attachments: t.attachments } : {},
|
|
35
36
|
...t.prepareImage ? { prepareImage: t.prepareImage } : {},
|
|
36
37
|
layout: t.layout,
|
package/dist/react.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react.js","names":["toCards","out","tool","spec","cards","wrap","fn","setPortals","m","container","ctx","next","GhuriChat","forwardRef","element","useRef","latest","props","portals","useState","useImperativeHandle","ref","useEffect","el","p","id","file","info","handlers","name","createElement","node","createPortal"],"sources":["../src/react.tsx"],"sourcesContent":["// @ghuri/ai-widget/react: <GhuriChat> for React apps. A thin wrapper around <ghuri-chat>: props configure it, `on*`\n// props receive its events, and `cards` take React components (rendered with portals into the element's card slots,\n// so they live in the app's React tree and its CSS applies).\nimport {\n type CSSProperties,\n createElement,\n forwardRef,\n type ReactNode,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from 'react'\nimport { createPortal } from 'react-dom'\nimport './index'\nimport type { ChatEvents } from './core/types'\nimport type { CardContext, CardSpec, GhuriChatElement, GhuriChatOptions } from './ui/element'\n\nexport interface ReactCardSpec {\n result?: (ctx: CardContext) => ReactNode\n confirm?: (ctx: CardContext) => ReactNode\n}\n\nexport interface GhuriChatProps extends Omit<GhuriChatOptions, 'cards'> {\n /** Panel layout: whether it is shown. */\n open?: boolean\n cards?: Record<string, ReactCardSpec>\n onToolResult?: (e: ChatEvents['tool-result']) => void\n onApprovalPending?: (e: ChatEvents['approval-pending']) => void\n onTurnEnd?: (e: ChatEvents['turn-end']) => void\n onAttachmentError?: (e: ChatEvents['attachment-error']) => void\n onOpen?: () => void\n onClose?: () => void\n className?: string\n style?: CSSProperties\n}\n\nexport type { CardContext, GhuriChatElement, GhuriChatOptions } from './ui/element'\n\ntype Portals = Map<HTMLElement, ReactNode>\ntype SetPortals = (update: (m: Portals) => Portals) => void\n\n/** Each React card becomes a DOM renderer that puts its node in a portal (removed when the card goes away). */\nfunction toCards(\n cards: Record<string, ReactCardSpec> | undefined,\n setPortals: SetPortals,\n): Record<string, CardSpec> {\n const out: Record<string, CardSpec> = {}\n for (const [tool, spec] of Object.entries(cards ?? {})) {\n const wrap = (fn?: (ctx: CardContext) => ReactNode) =>\n fn\n ? (container: HTMLElement, ctx: CardContext) => {\n setPortals((m) => new Map(m).set(container, fn(ctx)))\n return () =>\n setPortals((m) => {\n const next = new Map(m)\n next.delete(container)\n return next\n })\n }\n : undefined\n out[tool] = { result: wrap(spec.result), confirm: wrap(spec.confirm) }\n }\n return out\n}\n\nexport const GhuriChat = forwardRef<GhuriChatElement | null, GhuriChatProps>(function GhuriChat(props, ref) {\n const element = useRef<GhuriChatElement | null>(null)\n const latest = useRef(props)\n latest.current = props\n const [portals, setPortals] = useState<Portals>(() => new Map())\n useImperativeHandle(ref, () => element.current as GhuriChatElement, [])\n\n // Connect once per Ghuri AI URL; the product's callbacks are read from the latest props on every call.\n // biome-ignore lint/correctness/useExhaustiveDependencies: reconnect only when the API URL changes\n useEffect(() => {\n const el = element.current\n if (!el) return\n const p = latest.current\n el.configure({\n apiUrl: p.apiUrl,\n startSession: () => latest.current.startSession(),\n refreshUserToken: (id) => latest.current.refreshUserToken(id),\n endSession: (id) => latest.current.endSession?.(id) ?? Promise.resolve(),\n ...(p.fetch ? { fetch: p.fetch } : {}),\n // Whether photos are offered is decided when connecting: give `uploadFile` from the first render.\n ...(p.uploadFile\n ? { uploadFile: (file, info) => (latest.current.uploadFile ?? p.uploadFile!)(file, info) }\n : {}),\n ...(p.attachments ? { attachments: p.attachments } : {}),\n ...(p.prepareImage ? { prepareImage: p.prepareImage } : {}),\n layout: p.layout,\n title: p.title,\n subtitle: p.subtitle,\n locale: p.locale,\n labels: p.labels,\n starters: p.starters,\n toolSteps: p.toolSteps,\n cards: toCards(p.cards, setPortals),\n })\n }, [props.apiUrl])\n\n // How it looks: applied without reconnecting.\n useEffect(() => {\n element.current?.setOptions({\n layout: props.layout,\n title: props.title,\n subtitle: props.subtitle,\n locale: props.locale,\n labels: props.labels,\n starters: props.starters,\n toolSteps: props.toolSteps,\n cards: toCards(props.cards, setPortals),\n })\n }, [\n props.layout,\n props.title,\n props.subtitle,\n props.locale,\n props.labels,\n props.starters,\n props.toolSteps,\n props.cards,\n ])\n\n useEffect(() => {\n const el = element.current\n if (!el || props.open === undefined) return\n if (props.open) el.show()\n else el.hide()\n }, [props.open])\n\n useEffect(() => {\n const el = element.current\n if (!el) return\n const handlers: Array<[string, (e: Event) => void]> = [\n ['ghuri:tool-result', (e) => latest.current.onToolResult?.((e as CustomEvent).detail)],\n ['ghuri:approval-pending', (e) => latest.current.onApprovalPending?.((e as CustomEvent).detail)],\n ['ghuri:turn-end', (e) => latest.current.onTurnEnd?.((e as CustomEvent).detail)],\n ['ghuri:attachment-error', (e) => latest.current.onAttachmentError?.((e as CustomEvent).detail)],\n ['ghuri:open', () => latest.current.onOpen?.()],\n ['ghuri:close', () => latest.current.onClose?.()],\n ]\n for (const [name, fn] of handlers) el.addEventListener(name, fn)\n return () => {\n for (const [name, fn] of handlers) el.removeEventListener(name, fn)\n }\n }, [])\n\n return createElement(\n 'ghuri-chat',\n { ref: element, className: props.className, style: props.style, layout: props.layout ?? 'panel' },\n ...[...portals].map(([container, node]) => createPortal(node, container, container.slot)),\n )\n})\n"],"mappings":";;;;AA2CA,SAASA,EACP,GACA,GAC0B;CAC1B,IAAMC,IAAgC,CAAC;CACvC,KAAK,IAAM,CAACC,GAAMC,MAAS,OAAO,QAAQC,KAAS,CAAC,CAAC,GAAG;EACtD,IAAMC,KAAQ,MACZC,KACK,GAAwB,OACvBC,GAAY,MAAM,IAAI,IAAIC,CAAC,CAAC,CAAC,IAAIC,GAAWH,EAAGI,CAAG,CAAC,CAAC,SAElDH,GAAY,MAAM;GAChB,IAAMI,IAAO,IAAI,IAAIH,CAAC;GAEtB,OADAG,EAAK,OAAOF,CAAS,GACdE;EACT,CAAC,KAEL,KAAA;EACN,EAAIT,KAAQ;GAAE,QAAQG,EAAKF,EAAK,MAAM;GAAG,SAASE,EAAKF,EAAK,OAAO;EAAE;CACvE;CACA,OAAOF;AACT;AAEA,IAAaW,IAAYC,EAAoD,SAAmB,GAAO,GAAK;CAC1G,IAAMC,IAAUC,EAAgC,IAAI,GAC9CC,IAASD,EAAOE,CAAK;CAC3B,EAAO,UAAUA;CACjB,IAAM,CAACC,GAASX,KAAcY,wBAAwB,IAAI,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"react.js","names":["toCards","out","tool","spec","cards","wrap","fn","setPortals","m","container","ctx","next","GhuriChat","forwardRef","element","useRef","latest","props","portals","useState","useImperativeHandle","ref","useEffect","el","p","id","file","info","a","handlers","name","createElement","node","createPortal"],"sources":["../src/react.tsx"],"sourcesContent":["// @ghuri/ai-widget/react: <GhuriChat> for React apps. A thin wrapper around <ghuri-chat>: props configure it, `on*`\n// props receive its events, and `cards` take React components (rendered with portals into the element's card slots,\n// so they live in the app's React tree and its CSS applies).\nimport {\n type CSSProperties,\n createElement,\n forwardRef,\n type ReactNode,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from 'react'\nimport { createPortal } from 'react-dom'\nimport './index'\nimport type { ChatEvents } from './core/types'\nimport type { CardContext, CardSpec, GhuriChatElement, GhuriChatOptions } from './ui/element'\n\nexport interface ReactCardSpec {\n result?: (ctx: CardContext) => ReactNode\n confirm?: (ctx: CardContext) => ReactNode\n}\n\nexport interface GhuriChatProps extends Omit<GhuriChatOptions, 'cards'> {\n /** Panel layout: whether it is shown. */\n open?: boolean\n cards?: Record<string, ReactCardSpec>\n onToolResult?: (e: ChatEvents['tool-result']) => void\n onApprovalPending?: (e: ChatEvents['approval-pending']) => void\n onTurnEnd?: (e: ChatEvents['turn-end']) => void\n onAttachmentError?: (e: ChatEvents['attachment-error']) => void\n onOpen?: () => void\n onClose?: () => void\n className?: string\n style?: CSSProperties\n}\n\nexport type { CardContext, GhuriChatElement, GhuriChatOptions } from './ui/element'\n\ntype Portals = Map<HTMLElement, ReactNode>\ntype SetPortals = (update: (m: Portals) => Portals) => void\n\n/** Each React card becomes a DOM renderer that puts its node in a portal (removed when the card goes away). */\nfunction toCards(\n cards: Record<string, ReactCardSpec> | undefined,\n setPortals: SetPortals,\n): Record<string, CardSpec> {\n const out: Record<string, CardSpec> = {}\n for (const [tool, spec] of Object.entries(cards ?? {})) {\n const wrap = (fn?: (ctx: CardContext) => ReactNode) =>\n fn\n ? (container: HTMLElement, ctx: CardContext) => {\n setPortals((m) => new Map(m).set(container, fn(ctx)))\n return () =>\n setPortals((m) => {\n const next = new Map(m)\n next.delete(container)\n return next\n })\n }\n : undefined\n out[tool] = { result: wrap(spec.result), confirm: wrap(spec.confirm) }\n }\n return out\n}\n\nexport const GhuriChat = forwardRef<GhuriChatElement | null, GhuriChatProps>(function GhuriChat(props, ref) {\n const element = useRef<GhuriChatElement | null>(null)\n const latest = useRef(props)\n latest.current = props\n const [portals, setPortals] = useState<Portals>(() => new Map())\n useImperativeHandle(ref, () => element.current as GhuriChatElement, [])\n\n // Connect once per Ghuri AI URL; the product's callbacks are read from the latest props on every call.\n // biome-ignore lint/correctness/useExhaustiveDependencies: reconnect only when the API URL changes\n useEffect(() => {\n const el = element.current\n if (!el) return\n const p = latest.current\n el.configure({\n apiUrl: p.apiUrl,\n startSession: () => latest.current.startSession(),\n refreshUserToken: (id) => latest.current.refreshUserToken(id),\n endSession: (id) => latest.current.endSession?.(id) ?? Promise.resolve(),\n ...(p.fetch ? { fetch: p.fetch } : {}),\n // Whether photos are offered is decided when connecting: give `uploadFile` from the first render.\n ...(p.uploadFile\n ? { uploadFile: (file, info) => (latest.current.uploadFile ?? p.uploadFile!)(file, info) }\n : {}),\n ...(p.discardFile ? { discardFile: (a) => (latest.current.discardFile ?? p.discardFile!)(a) } : {}),\n ...(p.attachments ? { attachments: p.attachments } : {}),\n ...(p.prepareImage ? { prepareImage: p.prepareImage } : {}),\n layout: p.layout,\n title: p.title,\n subtitle: p.subtitle,\n locale: p.locale,\n labels: p.labels,\n starters: p.starters,\n toolSteps: p.toolSteps,\n cards: toCards(p.cards, setPortals),\n })\n }, [props.apiUrl])\n\n // How it looks: applied without reconnecting.\n useEffect(() => {\n element.current?.setOptions({\n layout: props.layout,\n title: props.title,\n subtitle: props.subtitle,\n locale: props.locale,\n labels: props.labels,\n starters: props.starters,\n toolSteps: props.toolSteps,\n cards: toCards(props.cards, setPortals),\n })\n }, [\n props.layout,\n props.title,\n props.subtitle,\n props.locale,\n props.labels,\n props.starters,\n props.toolSteps,\n props.cards,\n ])\n\n useEffect(() => {\n const el = element.current\n if (!el || props.open === undefined) return\n if (props.open) el.show()\n else el.hide()\n }, [props.open])\n\n useEffect(() => {\n const el = element.current\n if (!el) return\n const handlers: Array<[string, (e: Event) => void]> = [\n ['ghuri:tool-result', (e) => latest.current.onToolResult?.((e as CustomEvent).detail)],\n ['ghuri:approval-pending', (e) => latest.current.onApprovalPending?.((e as CustomEvent).detail)],\n ['ghuri:turn-end', (e) => latest.current.onTurnEnd?.((e as CustomEvent).detail)],\n ['ghuri:attachment-error', (e) => latest.current.onAttachmentError?.((e as CustomEvent).detail)],\n ['ghuri:open', () => latest.current.onOpen?.()],\n ['ghuri:close', () => latest.current.onClose?.()],\n ]\n for (const [name, fn] of handlers) el.addEventListener(name, fn)\n return () => {\n for (const [name, fn] of handlers) el.removeEventListener(name, fn)\n }\n }, [])\n\n return createElement(\n 'ghuri-chat',\n { ref: element, className: props.className, style: props.style, layout: props.layout ?? 'panel' },\n ...[...portals].map(([container, node]) => createPortal(node, container, container.slot)),\n )\n})\n"],"mappings":";;;;AA2CA,SAASA,EACP,GACA,GAC0B;CAC1B,IAAMC,IAAgC,CAAC;CACvC,KAAK,IAAM,CAACC,GAAMC,MAAS,OAAO,QAAQC,KAAS,CAAC,CAAC,GAAG;EACtD,IAAMC,KAAQ,MACZC,KACK,GAAwB,OACvBC,GAAY,MAAM,IAAI,IAAIC,CAAC,CAAC,CAAC,IAAIC,GAAWH,EAAGI,CAAG,CAAC,CAAC,SAElDH,GAAY,MAAM;GAChB,IAAMI,IAAO,IAAI,IAAIH,CAAC;GAEtB,OADAG,EAAK,OAAOF,CAAS,GACdE;EACT,CAAC,KAEL,KAAA;EACN,EAAIT,KAAQ;GAAE,QAAQG,EAAKF,EAAK,MAAM;GAAG,SAASE,EAAKF,EAAK,OAAO;EAAE;CACvE;CACA,OAAOF;AACT;AAEA,IAAaW,IAAYC,EAAoD,SAAmB,GAAO,GAAK;CAC1G,IAAMC,IAAUC,EAAgC,IAAI,GAC9CC,IAASD,EAAOE,CAAK;CAC3B,EAAO,UAAUA;CACjB,IAAM,CAACC,GAASX,KAAcY,wBAAwB,IAAI,IAAI,CAAC;CAgF/D,OA/EAC,EAAoBC,SAAWP,EAAQ,SAA6B,CAAC,CAAC,GAItEQ,QAAgB;EACd,IAAMC,IAAKT,EAAQ;EACnB,IAAI,CAACS,GAAI;EACT,IAAMC,IAAIR,EAAO;EACjB,EAAG,UAAU;GACX,QAAQQ,EAAE;GACV,oBAAoBR,EAAO,QAAQ,aAAa;GAChD,mBAAmB,MAAOA,EAAO,QAAQ,iBAAiBS,CAAE;GA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IAAMC,IAAKT,EAAQ;EACnB,IAAI,CAACS,GAAI;EACT,IAAMM,IAAgD;GACpD,CAAC,sBAAsB,MAAMb,EAAO,QAAQ,eAAgB,EAAkB,MAAM,CAAC;GACrF,CAAC,2BAA2B,MAAMA,EAAO,QAAQ,oBAAqB,EAAkB,MAAM,CAAC;GAC/F,CAAC,mBAAmB,MAAMA,EAAO,QAAQ,YAAa,EAAkB,MAAM,CAAC;GAC/E,CAAC,2BAA2B,MAAMA,EAAO,QAAQ,oBAAqB,EAAkB,MAAM,CAAC;GAC/F,CAAC,oBAAoBA,EAAO,QAAQ,SAAS,CAAC;GAC9C,CAAC,qBAAqBA,EAAO,QAAQ,UAAU,CAAC;EAClD;EACA,KAAK,IAAM,CAACc,GAAMxB,MAAOuB,GAAU,EAAG,iBAAiBC,GAAMxB,CAAE;EAC/D,aAAa;GACX,KAAK,IAAM,CAACwB,GAAMxB,MAAOuB,GAAU,EAAG,oBAAoBC,GAAMxB,CAAE;EACpE;CACF,GAAG,CAAC,CAAC,GAEEyB,EACL,cACA;EAAE,KAAKjB;EAAS,WAAWG,EAAM;EAAW,OAAOA,EAAM;EAAO,QAAQA,EAAM,UAAU;CAAQ,GAChG,GAAG,CAAC,GAAGC,CAAO,CAAC,CAAC,KAAK,CAACT,GAAWuB,OAAUC,EAAaD,GAAMvB,GAAWA,EAAU,IAAI,CAAC,CAC1F;AACF,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as e, t } from "./core-
|
|
1
|
+
import { n as e, t } from "./core-vIc1mTTy.js";
|
|
2
2
|
import { LitElement as n, css as r, html as i, nothing as a, svg as o } from "lit";
|
|
3
3
|
import { styleMap as s } from "lit/directives/style-map.js";
|
|
4
4
|
import { unsafeSVG as c } from "lit/directives/unsafe-svg.js";
|
|
@@ -92,6 +92,8 @@ function _(e, t = 16) {
|
|
|
92
92
|
}
|
|
93
93
|
// src/ui/labels.ts
|
|
94
94
|
var v = {
|
|
95
|
+
picture: "Picture",
|
|
96
|
+
showPicture: (e, t) => t > 1 ? `Show picture ${e} of ${t}` : "Show picture",
|
|
95
97
|
attachPhoto: "Add photos",
|
|
96
98
|
removePhoto: "Remove photo",
|
|
97
99
|
retryPhoto: "Upload again",
|
|
@@ -210,6 +212,8 @@ var v = {
|
|
|
210
212
|
loading: "Loading…"
|
|
211
213
|
}, y = {
|
|
212
214
|
...v,
|
|
215
|
+
picture: "ছবি",
|
|
216
|
+
showPicture: (e, t) => t > 1 ? `ছবি ${e}/${t} বড় করে দেখুন` : "ছবি বড় করে দেখুন",
|
|
213
217
|
attachPhoto: "ছবি যোগ করুন",
|
|
214
218
|
removePhoto: "ছবি সরান",
|
|
215
219
|
retryPhoto: "আবার আপলোড করুন",
|
|
@@ -1298,6 +1302,62 @@ var j = r`
|
|
|
1298
1302
|
text-align: center;
|
|
1299
1303
|
overflow-wrap: anywhere;
|
|
1300
1304
|
}
|
|
1305
|
+
.step-pictures {
|
|
1306
|
+
display: flex;
|
|
1307
|
+
flex-direction: column;
|
|
1308
|
+
gap: 6px;
|
|
1309
|
+
}
|
|
1310
|
+
.pictures {
|
|
1311
|
+
display: flex;
|
|
1312
|
+
flex-wrap: wrap;
|
|
1313
|
+
gap: 6px;
|
|
1314
|
+
}
|
|
1315
|
+
.picture {
|
|
1316
|
+
display: block;
|
|
1317
|
+
padding: 0;
|
|
1318
|
+
border: 1px solid var(--_border);
|
|
1319
|
+
border-radius: var(--_radius-sm);
|
|
1320
|
+
overflow: hidden;
|
|
1321
|
+
background: var(--_surface);
|
|
1322
|
+
cursor: zoom-in;
|
|
1323
|
+
}
|
|
1324
|
+
.picture img {
|
|
1325
|
+
display: block;
|
|
1326
|
+
height: 100px;
|
|
1327
|
+
width: auto;
|
|
1328
|
+
max-width: 180px;
|
|
1329
|
+
object-fit: cover;
|
|
1330
|
+
object-position: top;
|
|
1331
|
+
}
|
|
1332
|
+
.lightbox {
|
|
1333
|
+
position: fixed;
|
|
1334
|
+
inset: 0;
|
|
1335
|
+
z-index: 2147483000;
|
|
1336
|
+
display: grid;
|
|
1337
|
+
place-items: center;
|
|
1338
|
+
padding: 24px;
|
|
1339
|
+
background: rgb(0 0 0 / 0.75);
|
|
1340
|
+
cursor: zoom-out;
|
|
1341
|
+
}
|
|
1342
|
+
.lightbox img {
|
|
1343
|
+
max-width: 100%;
|
|
1344
|
+
max-height: 100%;
|
|
1345
|
+
border-radius: var(--_radius-sm);
|
|
1346
|
+
background: #fff;
|
|
1347
|
+
cursor: default;
|
|
1348
|
+
}
|
|
1349
|
+
.lightbox-close {
|
|
1350
|
+
position: absolute;
|
|
1351
|
+
top: 12px;
|
|
1352
|
+
right: 12px;
|
|
1353
|
+
display: grid;
|
|
1354
|
+
place-items: center;
|
|
1355
|
+
width: 32px;
|
|
1356
|
+
height: 32px;
|
|
1357
|
+
border-radius: 999px;
|
|
1358
|
+
background: rgb(255 255 255 / 0.9);
|
|
1359
|
+
color: #18181b;
|
|
1360
|
+
}
|
|
1301
1361
|
.stop {
|
|
1302
1362
|
flex: none;
|
|
1303
1363
|
display: inline-flex;
|
|
@@ -1459,7 +1519,8 @@ var j = r`
|
|
|
1459
1519
|
draft: { state: !0 },
|
|
1460
1520
|
expanded: { state: !0 },
|
|
1461
1521
|
unticked: { state: !0 },
|
|
1462
|
-
dragging: { state: !0 }
|
|
1522
|
+
dragging: { state: !0 },
|
|
1523
|
+
enlarged: { state: !0 }
|
|
1463
1524
|
};
|
|
1464
1525
|
chat = null;
|
|
1465
1526
|
options = null;
|
|
@@ -1472,7 +1533,7 @@ var j = r`
|
|
|
1472
1533
|
};
|
|
1473
1534
|
guarding = !1;
|
|
1474
1535
|
constructor() {
|
|
1475
|
-
super(), this.layout = "panel", this.open = !1, this.locale = "", this.heading = "", this.subtitle = "", this.state = null, this.view = "chat", this.conversations = null, this.draft = "", this.expanded = /* @__PURE__ */ new Set(), this.unticked = /* @__PURE__ */ new Set();
|
|
1536
|
+
super(), this.layout = "panel", this.open = !1, this.locale = "", this.heading = "", this.subtitle = "", this.state = null, this.view = "chat", this.conversations = null, this.draft = "", this.expanded = /* @__PURE__ */ new Set(), this.unticked = /* @__PURE__ */ new Set(), this.enlarged = null;
|
|
1476
1537
|
}
|
|
1477
1538
|
configure(t) {
|
|
1478
1539
|
this.detach(), this.options = t, t.layout && (this.layout = t.layout), t.title !== void 0 && (this.heading = t.title), t.subtitle !== void 0 && (this.subtitle = t.subtitle), t.locale && (this.locale = t.locale);
|
|
@@ -1551,8 +1612,8 @@ var j = r`
|
|
|
1551
1612
|
this.stickToBottom = !e || e.scrollHeight - e.scrollTop - e.clientHeight < 80;
|
|
1552
1613
|
}
|
|
1553
1614
|
}
|
|
1554
|
-
updated() {
|
|
1555
|
-
if (this.stickToBottom) {
|
|
1615
|
+
updated(e) {
|
|
1616
|
+
if (e.has("enlarged") && this.enlarged && this.renderRoot.querySelector(".lightbox-close")?.focus(), this.stickToBottom) {
|
|
1556
1617
|
let e = this.renderRoot.querySelector(".scroll");
|
|
1557
1618
|
e && (e.scrollTop = e.scrollHeight);
|
|
1558
1619
|
}
|
|
@@ -1651,8 +1712,30 @@ var j = r`
|
|
|
1651
1712
|
</div>
|
|
1652
1713
|
${this.renderScroll()} ${this.renderBottom()}
|
|
1653
1714
|
</section>
|
|
1715
|
+
${this.renderEnlarged()}
|
|
1654
1716
|
</div>` : i`${this.renderHeader()}
|
|
1655
|
-
${this.view === "history" ? this.renderPanelHistory() : i`${this.renderScroll()} ${this.renderBottom()}`}
|
|
1717
|
+
${this.view === "history" ? this.renderPanelHistory() : i`${this.renderScroll()} ${this.renderBottom()}`}
|
|
1718
|
+
${this.renderEnlarged()}`;
|
|
1719
|
+
}
|
|
1720
|
+
renderEnlarged() {
|
|
1721
|
+
if (!this.enlarged) return a;
|
|
1722
|
+
let e = this.labels;
|
|
1723
|
+
return i`<div
|
|
1724
|
+
class="lightbox"
|
|
1725
|
+
part="lightbox"
|
|
1726
|
+
role="dialog"
|
|
1727
|
+
aria-modal="true"
|
|
1728
|
+
aria-label=${e.picture}
|
|
1729
|
+
@click=${() => this.enlarged = null}
|
|
1730
|
+
@keydown=${(e) => {
|
|
1731
|
+
e.key === "Escape" && (this.enlarged = null);
|
|
1732
|
+
}}
|
|
1733
|
+
>
|
|
1734
|
+
<img src=${this.enlarged} alt=${e.picture} @click=${(e) => e.stopPropagation()} />
|
|
1735
|
+
<button class="lightbox-close" aria-label=${e.close} @click=${() => this.enlarged = null}>
|
|
1736
|
+
${_("x", 16)}
|
|
1737
|
+
</button>
|
|
1738
|
+
</div>`;
|
|
1656
1739
|
}
|
|
1657
1740
|
currentTitle() {
|
|
1658
1741
|
let e = this.state?.conversationId;
|
|
@@ -1840,10 +1923,21 @@ var j = r`
|
|
|
1840
1923
|
client: this.chat
|
|
1841
1924
|
}, n);
|
|
1842
1925
|
if (this.options?.toolSteps === "hide") return a;
|
|
1843
|
-
let r = e.state === "done" ? m(e.output) : null, o = e.state === "done" ? i`<span class="ok">${_("check", 13)}</span>` : e.state === "error" ? i`<span class="bad">${_("circle-alert", 13)}</span>` : e.state === "denied" ? _("ban", 13) : i`<span class="spin">${_("loader", 13)}</span
|
|
1844
|
-
return i`<span class="step" part="tool-step" title=${e.state === "error" ? e.errorText ?? "" : ""}>
|
|
1926
|
+
let r = e.state === "done" ? m(e.output) : null, o = e.state === "done" ? i`<span class="ok">${_("check", 13)}</span>` : e.state === "error" ? i`<span class="bad">${_("circle-alert", 13)}</span>` : e.state === "denied" ? _("ban", 13) : i`<span class="spin">${_("loader", 13)}</span>`, s = i`<span class="step" part="tool-step" title=${e.state === "error" ? e.errorText ?? "" : ""}>
|
|
1845
1927
|
${o}<span>${this.toolLabel(e)}${r === null ? "" : ` · ${t.found(r)}`}</span>
|
|
1846
1928
|
</span>`;
|
|
1929
|
+
return e.state !== "done" || !e.images?.length ? s : i`<div class="step-pictures" part="tool-pictures">
|
|
1930
|
+
${s}
|
|
1931
|
+
<div class="pictures">
|
|
1932
|
+
${e.images.map((n, r) => i`<button
|
|
1933
|
+
class="picture"
|
|
1934
|
+
aria-label=${t.showPicture(r + 1, e.images.length)}
|
|
1935
|
+
@click=${() => this.enlarged = I(n)}
|
|
1936
|
+
>
|
|
1937
|
+
<img src=${I(n)} alt=${t.showPicture(r + 1, e.images.length)} />
|
|
1938
|
+
</button>`)}
|
|
1939
|
+
</div>
|
|
1940
|
+
</div>`;
|
|
1847
1941
|
}
|
|
1848
1942
|
renderAllowed(e) {
|
|
1849
1943
|
let t = this.labels, n = this.state?.allowances.find((t) => t.toolName === e.toolName), r = e.state === "done" ? i`<span class="ok">${_("check", 13)}</span>` : e.state === "error" ? i`<span class="bad">${_("circle-alert", 13)}</span>` : i`<span class="spin">${_("loader", 13)}</span>`;
|
|
@@ -2071,8 +2165,11 @@ function F(e) {
|
|
|
2071
2165
|
let t = new Date(e);
|
|
2072
2166
|
return Number.isNaN(t.getTime()) ? "" : `${String(t.getHours()).padStart(2, "0")}:${String(t.getMinutes()).padStart(2, "0")}`;
|
|
2073
2167
|
}
|
|
2168
|
+
function I(e) {
|
|
2169
|
+
return `data:${e.mediaType};base64,${e.data}`;
|
|
2170
|
+
}
|
|
2074
2171
|
// src/index.ts
|
|
2075
2172
|
typeof customElements < "u" && !customElements.get("ghuri-chat") && customElements.define("ghuri-chat", N);
|
|
2076
2173
|
export { N as t };
|
|
2077
2174
|
|
|
2078
|
-
//# sourceMappingURL=src-
|
|
2175
|
+
//# sourceMappingURL=src-DLeXsfmQ.js.map
|