@copilotkit/core 2.0.0-rc.5 → 2.0.0-rc.51
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/dist/a2ui-markdown-BxZr1mEU.mjs +1360 -0
- package/dist/a2ui-markdown-BxZr1mEU.mjs.map +1 -0
- package/dist/a2ui-markdown-DkMXFQih.cjs +1419 -0
- package/dist/a2ui-markdown-DkMXFQih.cjs.map +1 -0
- package/dist/chat-configuration.cjs +269 -0
- package/dist/chat-configuration.cjs.map +1 -0
- package/dist/chat-configuration.d.cts +123 -0
- package/dist/chat-configuration.d.cts.map +1 -0
- package/dist/chat-configuration.d.mts +123 -0
- package/dist/chat-configuration.d.mts.map +1 -0
- package/dist/chat-configuration.mjs +268 -0
- package/dist/chat-configuration.mjs.map +1 -0
- package/dist/generative-ui/index.cjs +3786 -0
- package/dist/generative-ui/index.cjs.map +1 -0
- package/dist/generative-ui/index.d.cts +1139 -0
- package/dist/generative-ui/index.d.cts.map +1 -0
- package/dist/generative-ui/index.d.mts +1139 -0
- package/dist/generative-ui/index.d.mts.map +1 -0
- package/dist/generative-ui/index.mjs +3737 -0
- package/dist/generative-ui/index.mjs.map +1 -0
- package/dist/index.cjs +10233 -2258
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3908
- package/dist/index.d.mts +3 -3908
- package/dist/index.mjs +9979 -2249
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +13761 -2223
- package/dist/index.umd.js.map +1 -1
- package/dist/learning-bridge-DEVwyO7F.d.cts +10553 -0
- package/dist/learning-bridge-DEVwyO7F.d.cts.map +1 -0
- package/dist/learning-bridge-DZOhtLs1.d.mts +10553 -0
- package/dist/learning-bridge-DZOhtLs1.d.mts.map +1 -0
- package/dist/styles.cjs +1 -1
- package/dist/styles.cjs.map +1 -1
- package/dist/styles.css +1 -1
- package/dist/styles.mjs +1 -1
- package/dist/styles.mjs.map +1 -1
- package/dist/viewport-CksL5y8p.mjs +954 -0
- package/dist/viewport-CksL5y8p.mjs.map +1 -0
- package/dist/viewport-D-tuKCeb.cjs +1182 -0
- package/dist/viewport-D-tuKCeb.cjs.map +1 -0
- package/package.json +35 -8
- package/stryker.config.mjs +6 -0
- package/tsdown.config.ts +12 -2
- package/vitest.mutation.config.mjs +6 -0
- package/dist/index.d.cts.map +0 -1
- package/dist/index.d.mts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"a2ui-markdown-DkMXFQih.cjs","names":["A2UI_VERSION","GENERATIVE_UI_ROOT_ID"],"sources":["../src/a2ui-markdown/fence-parser.ts","../src/a2ui-markdown/operations.ts"],"sourcesContent":["/** Language of a fenced code block that carries A2UI operations. */\nexport const A2UI_FENCE_LANGUAGE = \"a2ui\";\n\n/**\n * One part of an assistant message, in source order: prose markdown, or the\n * body of a top-level ```a2ui fence. `target` is the id from a\n * `target=<id>` token in the fence info string. With no target, the surface\n * goes to the chat.\n */\nexport type MarkdownSegment =\n | { type: \"markdown\"; text: string }\n | {\n type: \"a2ui\";\n index: number;\n text: string;\n closed: boolean;\n target?: string;\n };\n\ntype A2UISegment = Extract<MarkdownSegment, { type: \"a2ui\" }>;\n\n/** Column-0 fence opener: a run of 3+ backticks or tildes, then the info string. */\nconst FENCE_OPEN = /^(`{3,}|~{3,})(.*)$/;\n\n/** Info-string token that names the placement target of an a2ui fence. */\nconst TARGET_TOKEN = /^target=(.+)$/;\n\ninterface OpenFence {\n /** Fence character (` or ~). */\n char: string;\n /** Length of the opening marker; the closer must be at least this long. */\n length: number;\n /** Offset in the source where the fence body starts. */\n bodyStart: number;\n /** a2ui fence index, or -1 for fences of other languages. */\n index: number;\n /** Target id from the info string of an a2ui fence. */\n target: string | undefined;\n}\n\nfunction isCloser(line: string, fence: OpenFence) {\n const trimmed = line.trim();\n if (trimmed.length < fence.length) return false;\n for (const ch of trimmed) {\n if (ch !== fence.char) return false;\n }\n return true;\n}\n\n/** The id of the first `target=<id>` token. Other tokens are ignored. */\nfunction readTarget(tokens: string[]) {\n for (const token of tokens) {\n const match = TARGET_TOKEN.exec(token);\n if (match) return match[1];\n }\n return undefined;\n}\n\nfunction a2uiSegment(fence: OpenFence, text: string, closed: boolean) {\n const segment: A2UISegment = {\n type: \"a2ui\",\n index: fence.index,\n text,\n closed,\n };\n if (fence.target !== undefined) segment.target = fence.target;\n return segment;\n}\n\n/**\n * Split a (possibly still streaming) markdown string into prose segments and\n * top-level ```a2ui fences. Fences of other languages stay inside prose\n * segments byte-for-byte, and a2ui markers inside them are ignored. Only\n * column-0 fences are recognised, so a fence indented inside a list item is\n * left to the markdown renderer.\n *\n * The first info-string token must be exactly `a2ui`. A later\n * `target=<id>` token sets `target` on the segment (for example\n * ```` ```a2ui target=recommendations ````). Other tokens are ignored.\n *\n * An a2ui segment's `text` is the fence body. For a closed fence it ends with\n * \"\\n\" when non-empty. For an open (still streaming or aborted) fence it is\n * everything after the opener line, minus a half-streamed closing marker.\n *\n * @param markdown - The assistant message text, complete or still streaming.\n * @returns The segments in source order.\n *\n * @example\n * ```ts\n * for (const segment of splitA2UIMarkdown(message.content)) {\n * if (segment.type === \"a2ui\") renderSurface(segment.text, segment.target);\n * else renderMarkdown(segment.text);\n * }\n * ```\n */\nexport function splitA2UIMarkdown(markdown: string) {\n const segments: MarkdownSegment[] = [];\n let proseStart = 0;\n let fence: OpenFence | null = null;\n let a2uiIndex = 0;\n\n const pushProse = (end: number) => {\n if (end > proseStart) {\n segments.push({\n type: \"markdown\",\n text: markdown.slice(proseStart, end),\n });\n }\n };\n\n let lineStart = 0;\n while (lineStart <= markdown.length) {\n const newline = markdown.indexOf(\"\\n\", lineStart);\n const lineEnd = newline < 0 ? markdown.length : newline;\n // A CRLF line keeps its \"\\r\" in the source slices (prose stays\n // byte-identical) but is matched without it, since \".\" does not match \"\\r\".\n const hasCR = lineEnd > lineStart && markdown[lineEnd - 1] === \"\\r\";\n const line = markdown.slice(lineStart, hasCR ? lineEnd - 1 : lineEnd);\n\n if (fence) {\n if (isCloser(line, fence)) {\n if (fence.index >= 0) {\n const body = markdown.slice(\n fence.bodyStart,\n Math.max(fence.bodyStart, lineStart),\n );\n segments.push(a2uiSegment(fence, body, true));\n proseStart = hasCR ? lineEnd - 1 : lineEnd;\n }\n fence = null;\n }\n } else {\n const open = FENCE_OPEN.exec(line);\n if (open) {\n const marker = open[1] ?? \"\";\n const info = open[2] ?? \"\";\n const char = marker.charAt(0);\n // Backtick fences cannot have backticks in their info string (CommonMark).\n const isValidOpener = !(char === \"`\" && info.includes(\"`\"));\n if (isValidOpener) {\n const [lang = \"\", ...tokens] = info.trim().split(/\\s+/);\n const isA2UI = lang === A2UI_FENCE_LANGUAGE;\n if (isA2UI) pushProse(lineStart);\n fence = {\n char,\n length: marker.length,\n bodyStart: newline < 0 ? markdown.length : lineEnd + 1,\n index: isA2UI ? a2uiIndex++ : -1,\n target: isA2UI ? readTarget(tokens) : undefined,\n };\n }\n }\n }\n\n if (newline < 0) break;\n lineStart = newline + 1;\n }\n\n if (fence && fence.index >= 0) {\n const { char } = fence;\n let body = markdown.slice(fence.bodyStart);\n // Drop a closing marker that is still streaming in (e.g. \"``\").\n const lastNewline = body.lastIndexOf(\"\\n\");\n const lastLine = body.slice(lastNewline + 1).replace(/\\r$/, \"\");\n const isHalfCloser =\n lastLine.length > 0 && [...lastLine].every((ch) => ch === char);\n if (isHalfCloser) {\n body = body.slice(0, lastNewline + 1);\n }\n segments.push(a2uiSegment(fence, body, false));\n } else {\n pushProse(markdown.length);\n }\n\n return segments;\n}\n","import { jsonrepair } from \"jsonrepair\";\nimport { A2UI_VERSION, GENERATIVE_UI_ROOT_ID } from \"@copilotkit/shared\";\n\n/**\n * An A2UI v1.0 message as the model wrote it in an a2ui fence: an object that\n * carries one of createSurface, updateComponents, updateDataModel,\n * deleteSurface or callRendererFunction. The shape is not checked yet.\n * Validate it (for example with `validateOperation` from `@copilotkit/shared`)\n * before it reaches a surface or runs a function.\n *\n * It is named `A2UIMarkdownOperation` because `@copilotkit/shared` already\n * exports the strict `A2UIOperation` type.\n */\nexport type A2UIMarkdownOperation = Record<string, unknown>;\n\n/** The operation keys that change a surface. */\nconst SURFACE_OP_KEYS = [\n \"createSurface\",\n \"updateComponents\",\n \"updateDataModel\",\n \"deleteSurface\",\n] as const;\n\n/** The operation key of an agent-called function. It has no surface. */\nconst FUNCTION_CALL_KEY = \"callRendererFunction\";\n\nconst OP_KEYS = [...SURFACE_OP_KEYS, FUNCTION_CALL_KEY] as const;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isWhitespace(ch: string | undefined) {\n return ch === \" \" || ch === \"\\n\" || ch === \"\\r\" || ch === \"\\t\";\n}\n\nfunction skipWhitespace(s: string, i: number) {\n while (i < s.length && isWhitespace(s[i])) i++;\n return i;\n}\n\n/** Index of the closing quote of the JSON string opening at `start`, or -1. */\nfunction findStringEnd(s: string, start: number) {\n for (let i = start + 1; i < s.length; i++) {\n if (s[i] === \"\\\\\") {\n i++;\n continue;\n }\n if (s[i] === '\"') return i;\n }\n return -1;\n}\n\n/**\n * Find the first `\"key\":` whose value starts with `opener` and return the index\n * of that opener, or -1.\n */\nfunction findKeyValue(s: string, key: string, opener: string) {\n const needle = `\"${key}\"`;\n let from = 0;\n while (true) {\n const k = s.indexOf(needle, from);\n if (k < 0) return -1;\n let i = skipWhitespace(s, k + needle.length);\n if (s[i] === \":\") {\n i = skipWhitespace(s, i + 1);\n if (s[i] === opener) return i;\n }\n from = k + 1;\n }\n}\n\n/**\n * Read `\"key\":\"value\"` from partial JSON. The first match anywhere in the\n * text wins, at any depth.\n *\n * @param partialJson - JSON text that can still be streaming.\n * @param key - The field name.\n * @returns The string value, or null until its closing quote has arrived.\n *\n * @example\n * ```ts\n * extractStringField('{\"createSurface\":{\"surfaceId\":\"plan\",\"cat', \"surfaceId\"); // \"plan\"\n * ```\n */\nexport function extractStringField(partialJson: string, key: string) {\n const start = findKeyValue(partialJson, key, '\"');\n if (start < 0) return null;\n const end = findStringEnd(partialJson, start);\n if (end < 0) return null;\n try {\n const value: unknown = JSON.parse(partialJson.slice(start, end + 1));\n return typeof value === \"string\" ? value : null;\n } catch {\n return null;\n }\n}\n\nfunction pushItem(raw: string, items: unknown[]) {\n const trimmed = raw.trim();\n if (!trimmed) return;\n try {\n items.push(JSON.parse(trimmed));\n } catch {\n // Incomplete primitive; ignore until it completes.\n }\n}\n\n/**\n * Find `\"key\":[` in partial JSON and return every complete item of that array\n * so far, plus whether the array has closed. Items of a `components` array get\n * structural-key depth repair: a component that lost closing braces is fixed\n * when its `id`, `component`, `child` or `children` key shows where it ends.\n *\n * @param partialJson - JSON text that can still be streaming.\n * @param key - The name of the array field.\n * @returns `{ items, closed }`, or null when the key (with an array value)\n * has not appeared yet.\n *\n * @example\n * ```ts\n * const result = extractCompleteArrayItems(streamedText, \"components\");\n * if (result) render(result.items);\n * ```\n */\nexport function extractCompleteArrayItems(partialJson: string, key: string) {\n const open = findKeyValue(partialJson, key, \"[\");\n if (open < 0) return null;\n return completeArrayItemsAt(partialJson, open, {\n repairComponents: key === \"components\",\n });\n}\n\n/** Index of the last non-whitespace character before `i`, or -1. */\nfunction prevNonWhitespace(s: string, i: number) {\n let j = i - 1;\n while (j >= 0 && isWhitespace(s[j])) j--;\n return j;\n}\n\n/**\n * Keys that only ever belong at a component's top level. Seen nested inside\n * the component's objects, they mean the model forgot closing braces.\n */\nconst STRUCTURAL_KEYS = new Set([\"id\", \"component\", \"child\", \"children\"]);\n\n/** Whether a value starting with `ch` has the shape `key` takes on a component. */\nfunction structuralValueFits(key: string, ch: string | undefined) {\n if (key === \"children\") return ch === \"[\" || ch === \"{\";\n return ch === '\"';\n}\n\n/** `{\"id\":` — a new component object starting at `i`. */\nconst COMPONENT_START = /^\\{\\s*\"id\"\\s*:/;\n\n/**\n * Structural-key depth repair for one component item. While scanning, a\n * structural key (`id`, `component`, `child`, `children`) found as an object\n * key below the item's top level, with only objects (no arrays) between it\n * and the item root, a value of the expected shape, and not already present\n * at the top level, means closing braces were dropped: the missing `}` are\n * synthesized right before it so it lands at the top level. Containers still\n * open at the end are closed. Returns null when a string never terminates.\n */\nfunction repairComponentItem(item: string) {\n const stack: string[] = [];\n const topKeys = new Set<string>();\n let out = \"\";\n let copied = 0;\n for (let i = 0; i < item.length; i++) {\n const c = item[i];\n if (c === '\"') {\n const end = findStringEnd(item, i);\n if (end < 0) return null;\n const prev = prevNonWhitespace(item, i);\n const prevCh = item[prev];\n const colon = skipWhitespace(item, end + 1);\n const isKey =\n stack[stack.length - 1] === \"{\" &&\n (prevCh === \",\" || prevCh === \"{\") &&\n item[colon] === \":\";\n if (isKey) {\n let key: unknown;\n try {\n key = JSON.parse(item.slice(i, end + 1));\n } catch {\n return null;\n }\n if (typeof key === \"string\") {\n if (stack.length === 1) {\n topKeys.add(key);\n } else if (\n STRUCTURAL_KEYS.has(key) &&\n !topKeys.has(key) &&\n stack.every((x) => x === \"{\") &&\n structuralValueFits(key, item[skipWhitespace(item, colon + 1)])\n ) {\n const closers = \"}\".repeat(stack.length - 1);\n if (prevCh === \",\") {\n out += item.slice(copied, prev) + closers;\n copied = prev;\n } else {\n // `\"x\":{\"children\":…` — close the empty object, then a comma.\n out += item.slice(copied, i) + closers + \",\";\n copied = i;\n }\n stack.length = 1;\n topKeys.add(key);\n }\n }\n }\n i = end;\n continue;\n }\n if (c === \"{\" || c === \"[\") {\n stack.push(c);\n } else if (c === \"}\" || c === \"]\") {\n stack.pop();\n if (stack.length === 0) return out + item.slice(copied, i + 1);\n }\n }\n // Close the open brackets, innermost first.\n const closers = stack.reduceRight(\n (text, opener) => text + (opener === \"{\" ? \"}\" : \"]\"),\n \"\",\n );\n return out + item.slice(copied) + closers;\n}\n\nfunction parseRecord(text: string | null) {\n if (text === null) return undefined;\n try {\n const value: unknown = JSON.parse(text);\n return isRecord(value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Complete items of the (possibly unterminated) array whose \"[\" is at `open`.\n * With `repairComponents`, an item that balanced but does not parse is retried\n * with structural-key repair, and a `,{\"id\":` where an item expects a key\n * ends that (unbalanced) item there, so one malformed component cannot\n * swallow the rest of the array; the cut item is kept only if repair makes\n * it parse.\n */\nfunction completeArrayItemsAt(\n partialJson: string,\n open: number,\n options: { repairComponents: boolean },\n) {\n const { repairComponents } = options;\n const s = partialJson;\n const items: unknown[] = [];\n const stack: string[] = [];\n let inString = false;\n let itemStart = -1;\n\n const finishItem = (end: number, balanced: boolean) => {\n const raw = s.slice(itemStart, end);\n if (!repairComponents) {\n pushItem(raw, items);\n return;\n }\n if (balanced) {\n try {\n items.push(JSON.parse(raw));\n return;\n } catch {\n // Fall through to repair.\n }\n }\n const repaired = parseRecord(repairComponentItem(raw.trim()));\n if (repaired !== undefined) items.push(repaired);\n };\n\n for (let i = open + 1; i < s.length; i++) {\n const c = s[i];\n if (inString) {\n if (c === \"\\\\\") i++;\n else if (c === '\"') inString = false;\n continue;\n }\n if (c === '\"') {\n inString = true;\n if (stack.length === 0 && itemStart < 0) itemStart = i;\n continue;\n }\n if (c === \"{\" || c === \"[\") {\n if (\n repairComponents &&\n c === \"{\" &&\n stack[stack.length - 1] === \"{\" &&\n COMPONENT_START.test(s.slice(i, i + 24))\n ) {\n const prev = prevNonWhitespace(s, i);\n if (s[prev] === \",\") {\n // A new component where a key was expected: the current item\n // is missing closers. End it before the comma and start anew.\n finishItem(prev, false);\n stack.length = 0;\n itemStart = i;\n stack.push(c);\n continue;\n }\n }\n if (stack.length === 0) itemStart = i;\n stack.push(c);\n continue;\n }\n if (c === \"}\" || c === \"]\") {\n if (stack.length === 0) {\n // Closing bracket of the items array itself (or malformed input).\n if (c === \"]\") {\n if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);\n return { items, closed: true };\n }\n return { items, closed: false };\n }\n stack.pop();\n if (stack.length === 0) {\n finishItem(i + 1, true);\n itemStart = -1;\n }\n continue;\n }\n if (stack.length === 0) {\n if (c === \",\") {\n if (itemStart >= 0) pushItem(s.slice(itemStart, i), items);\n itemStart = -1;\n } else if (itemStart < 0 && !isWhitespace(c)) {\n itemStart = i; // start of a primitive item\n }\n }\n }\n return { items, closed: false };\n}\n\n/** The first operation key whose value is an object, with that value. */\nfunction getOperationEntry(op: A2UIMarkdownOperation) {\n for (const key of OP_KEYS) {\n const inner = op[key];\n if (isRecord(inner)) return { key, inner };\n }\n return null;\n}\n\n/**\n * The surfaceId an operation targets: the one nested under its operation key,\n * else a top-level `surfaceId`. A `callRendererFunction` operation targets no\n * surface, so it gets undefined.\n *\n * It is named `getMarkdownOperationSurfaceId` because `@copilotkit/shared`\n * already exports a strict `getOperationSurfaceId`. This one also reads a\n * top-level `surfaceId`, which models sometimes write.\n *\n * @param op - An operation from an a2ui fence.\n * @returns The surfaceId, or undefined when the operation names none or is a\n * function call.\n *\n * @example\n * ```ts\n * getMarkdownOperationSurfaceId({ updateDataModel: { surfaceId: \"plan\" } }); // \"plan\"\n * ```\n */\nexport function getMarkdownOperationSurfaceId(op: A2UIMarkdownOperation) {\n if (getOperationEntry(op)?.key === FUNCTION_CALL_KEY) return undefined;\n for (const key of SURFACE_OP_KEYS) {\n const inner = op[key];\n if (isRecord(inner) && typeof inner.surfaceId === \"string\") {\n return inner.surfaceId;\n }\n }\n return typeof op.surfaceId === \"string\" ? op.surfaceId : undefined;\n}\n\n/**\n * Index just past the JSON value starting at `start`, or -1 when the value is\n * still incomplete. A primitive at the very end of the input counts as\n * incomplete, since more digits or letters may still stream in.\n */\nfunction findValueEnd(s: string, start: number) {\n const c = s[start];\n if (c === '\"') {\n const end = findStringEnd(s, start);\n return end < 0 ? -1 : end + 1;\n }\n if (c === \"{\" || c === \"[\") {\n let depth = 0;\n for (let i = start; i < s.length; i++) {\n const ch = s[i];\n if (ch === '\"') {\n const end = findStringEnd(s, i);\n if (end < 0) return -1;\n i = end;\n } else if (ch === \"{\" || ch === \"[\") {\n depth++;\n } else if (ch === \"}\" || ch === \"]\") {\n depth--;\n if (depth === 0) return i + 1;\n }\n }\n return -1;\n }\n let i = start;\n while (i < s.length && !isWhitespace(s[i]) && !\",}]\".includes(s[i]!)) i++;\n return i >= s.length ? -1 : i;\n}\n\n/**\n * Walk the direct entries of the (possibly unterminated) JSON object whose \"{\"\n * is at `objStart`, calling `visit` with each key and the index where its value\n * starts. Nested objects and arrays are skipped whole, so keys inside them are\n * never visited. Stops when `visit` returns true, at the object's end, or where\n * the input runs out.\n */\nfunction visitDirectEntries(\n s: string,\n objStart: number,\n visit: (key: string, valueStart: number) => boolean,\n) {\n let i = objStart + 1;\n while (i < s.length) {\n i = skipWhitespace(s, i);\n const c = s[i];\n if (c === \",\") {\n i++;\n continue;\n }\n if (c !== '\"') return; // \"}\" (object closed), end of input, or malformed\n const keyEnd = findStringEnd(s, i);\n if (keyEnd < 0) return;\n let key: unknown;\n try {\n key = JSON.parse(s.slice(i, keyEnd + 1));\n } catch {\n return;\n }\n i = skipWhitespace(s, keyEnd + 1);\n if (s[i] !== \":\") return;\n i = skipWhitespace(s, i + 1);\n if (i >= s.length) return;\n if (typeof key === \"string\" && visit(key, i)) return;\n const valueEnd = findValueEnd(s, i);\n if (valueEnd < 0) return;\n i = valueEnd;\n }\n}\n\n/**\n * Value start of a direct `key` of the object at `objStart` whose value begins\n * with `opener` (any value when omitted), or -1.\n */\nfunction findDirectKeyValue(\n s: string,\n objStart: number,\n key: string,\n opener?: string,\n) {\n let found = -1;\n visitDirectEntries(s, objStart, (k, valueStart) => {\n if (k !== key) return false;\n if (opener === undefined || s[valueStart] === opener) found = valueStart;\n return true;\n });\n return found;\n}\n\n/** A direct string field of the object at `objStart`, once its closing quote has arrived. */\nfunction readDirectString(s: string, objStart: number, key: string) {\n if (objStart < 0) return null;\n const start = findDirectKeyValue(s, objStart, key, '\"');\n if (start < 0) return null;\n const end = findValueEnd(s, start);\n if (end < 0) return null;\n try {\n const value: unknown = JSON.parse(s.slice(start, end));\n return typeof value === \"string\" ? value : null;\n } catch {\n return null;\n }\n}\n\n/** A direct object field of the object at `objStart`, once the whole object has arrived. */\nfunction readDirectRecord(s: string, objStart: number, key: string) {\n const start = findDirectKeyValue(s, objStart, key, \"{\");\n if (start < 0) return undefined;\n const end = findValueEnd(s, start);\n if (end < 0) return undefined;\n return parseRecord(s.slice(start, end));\n}\n\n/**\n * The complete part of a (possibly unterminated) JSON value: the parsed value\n * when it is complete; for an open object, its complete entries plus the\n * complete items of any streaming array entry; otherwise undefined.\n */\nfunction completePartOfValue(s: string, start: number) {\n const end = findValueEnd(s, start);\n if (end >= 0) {\n try {\n const value: unknown = JSON.parse(s.slice(start, end));\n return value;\n } catch {\n return undefined;\n }\n }\n if (s[start] !== \"{\") return undefined;\n const out: Record<string, unknown> = {};\n visitDirectEntries(s, start, (key, valueStart) => {\n const valueEnd = findValueEnd(s, valueStart);\n if (valueEnd >= 0) {\n try {\n out[key] = JSON.parse(s.slice(valueStart, valueEnd));\n } catch {\n // Malformed entry; leave it out.\n }\n } else if (s[valueStart] === \"[\") {\n const { items } = completeArrayItemsAt(s, valueStart, {\n repairComponents: false,\n });\n if (items.length > 0) out[key] = items;\n }\n return false;\n });\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/**\n * Best-effort operation from an unfinished or malformed top-level object.\n * Fields are read only from the operation's own keys (`version` at the top\n * level, `surfaceId`, `catalogId`, `path`, `dataModel` and `components` inside\n * the operation object), never from component props or data-model values that\n * happen to share a name.\n *\n * A `createSurface` keeps its complete components and a `dataModel` that has\n * fully arrived, so a surface created in one line renders while it streams.\n * A `callRendererFunction` gives nothing: a function must not run with half\n * of its args.\n */\nfunction partialOperation(line: string) {\n const root = skipWhitespace(line, 0);\n if (line[root] !== \"{\") return null;\n const version = readDirectString(line, root, \"version\") ?? A2UI_VERSION;\n\n const components = findDirectKeyValue(line, root, \"updateComponents\", \"{\");\n if (components >= 0) {\n const arrayStart = findDirectKeyValue(line, components, \"components\", \"[\");\n if (arrayStart < 0) return null;\n const { items } = completeArrayItemsAt(line, arrayStart, {\n repairComponents: true,\n });\n if (items.length === 0) return null;\n const surfaceId = readDirectString(line, components, \"surfaceId\");\n return {\n version,\n updateComponents: {\n ...(surfaceId ? { surfaceId } : {}),\n components: items,\n },\n };\n }\n\n const data = findDirectKeyValue(line, root, \"updateDataModel\", \"{\");\n if (data >= 0) {\n const valueStart = findDirectKeyValue(line, data, \"value\");\n if (valueStart < 0) return null;\n const value = completePartOfValue(line, valueStart);\n if (value === undefined) return null;\n const surfaceId = readDirectString(line, data, \"surfaceId\");\n const path = readDirectString(line, data, \"path\");\n return {\n version,\n updateDataModel: {\n ...(surfaceId ? { surfaceId } : {}),\n ...(path ? { path } : {}),\n value,\n },\n };\n }\n\n const create = findDirectKeyValue(line, root, \"createSurface\", \"{\");\n if (create >= 0) {\n const surfaceId = readDirectString(line, create, \"surfaceId\");\n if (!surfaceId) return null;\n const catalogId = readDirectString(line, create, \"catalogId\");\n const dataModel = readDirectRecord(line, create, \"dataModel\");\n const componentsStart = findDirectKeyValue(line, create, \"components\", \"[\");\n const components =\n componentsStart < 0\n ? []\n : completeArrayItemsAt(line, componentsStart, {\n repairComponents: true,\n }).items;\n return {\n version,\n createSurface: {\n surfaceId,\n ...(catalogId ? { catalogId } : {}),\n ...(dataModel ? { dataModel } : {}),\n ...(components.length > 0 ? { components } : {}),\n },\n };\n }\n return null;\n}\n\n/**\n * A line that opens a new top-level operation: `{\"version\":\"1…` or\n * `{\"<operation>\":{`. Seen at the start of a line while an earlier object is\n * still unbalanced, it means that object is malformed and has ended.\n */\nconst OPERATION_START = new RegExp(\n `^\\\\{\\\\s*\"(?:version\"\\\\s*:\\\\s*\"\\\\d|(?:${OP_KEYS.join(\"|\")})\"\\\\s*:\\\\s*\\\\{)`,\n);\n\n/**\n * Scan the top-level object whose \"{\" is at `start`. Returns the index just\n * past it and whether it balanced. An unbalanced object ends early (at the\n * start of the line) when a line opens a new operation; otherwise it runs to\n * the end of the input. JSON strings cannot contain raw newlines, so a newline\n * inside a string ends it: a stray quote then breaks one line, not the rest of\n * the fence.\n */\nfunction scanTopLevelObject(s: string, start: number) {\n let depth = 0;\n let inString = false;\n for (let i = start; i < s.length; i++) {\n const c = s[i];\n if (inString) {\n if (c === \"\\\\\" && s[i + 1] !== \"\\n\") i++;\n else if (c === '\"' || c === \"\\n\") inString = false;\n if (c !== \"\\n\") continue;\n }\n if (c === \"\\n\") {\n const next = skipWhitespace(s, i + 1);\n if (OPERATION_START.test(s.slice(next, next + 40))) {\n return { end: i + 1, balanced: false };\n }\n continue;\n }\n if (c === '\"') inString = true;\n else if (c === \"{\" || c === \"[\") depth++;\n else if (c === \"}\" || c === \"]\") {\n depth--;\n if (depth === 0) return { end: i + 1, balanced: true };\n }\n }\n return { end: s.length, balanced: false };\n}\n\nconst OPERATION_NAMES = [\n \"createSurface\",\n \"updateComponents\",\n \"updateDataModel\",\n \"deleteSurface\",\n \"callRendererFunction\",\n];\n\n/** Whether a value is shaped like one A2UI operation, with named components. */\nfunction isOperationShape(value: unknown): boolean {\n if (!isRecord(value) || value.version !== A2UI_VERSION) return false;\n const names = OPERATION_NAMES.filter((name) => name in value);\n if (names.length !== 1 || Object.keys(value).length !== 2) return false;\n const body = value[names[0]!];\n if (!isRecord(body)) return false;\n if (names[0] === \"callRendererFunction\") return true;\n if (typeof body.surfaceId !== \"string\") return false;\n const components = body.components;\n return (\n components === undefined ||\n (Array.isArray(components) &&\n components.every(\n (c) =>\n isRecord(c) &&\n typeof c.id === \"string\" &&\n typeof c.component === \"string\",\n ))\n );\n}\n\n/** Openers minus closers ({ and [ against } and ]) outside strings. */\nfunction closerImbalance(line: string) {\n let depth = 0;\n let inString = false;\n for (let i = 0; i < line.length; i++) {\n const c = line[i];\n if (inString) {\n if (c === \"\\\\\") i++;\n else if (c === '\"') inString = false;\n } else if (c === '\"') inString = true;\n else if (c === \"{\" || c === \"[\") depth++;\n else if (c === \"}\" || c === \"]\") depth--;\n }\n return depth;\n}\n\n/** The text with closers and whitespace removed, to compare a repair. */\nfunction withoutClosers(text: string) {\n return text.replace(/[\\]}\\s]/g, \"\");\n}\n\n/**\n * Whether a component of the operation holds a structural key (`id`,\n * `component`, `child`, `children`) in a nested object: a closer added at\n * the end instead of where it was dropped. The scan below repairs those.\n */\nfunction nestsStructuralKey(value: unknown) {\n const nests = (v: unknown): boolean =>\n isRecord(v) &&\n Object.entries(v).some(([k, x]) => STRUCTURAL_KEYS.has(k) || nests(x));\n const body = isRecord(value)\n ? Object.values(value).find(isRecord)\n : undefined;\n const components = body?.components;\n return (\n Array.isArray(components) &&\n components.some(\n (c) => isRecord(c) && Object.values(c).some((prop) => nests(prop)),\n )\n );\n}\n\n/**\n * Repairs the complete lines of a fence that are not valid JSON (a missing\n * or extra brace) with jsonrepair, when the repair only adds or removes\n * closers and the result is shaped like an operation. A line still streaming in (no newline yet) is left alone.\n */\nfunction repairFenceLines(fenceText: string) {\n const repaired: string[] = [];\n const lines = fenceText.split(\"\\n\");\n // A top-level array spreads its closers over lines: nothing to repair.\n if (fenceText.trimStart().startsWith(\"[\"))\n return { text: fenceText, repaired };\n for (let n = 0; n < lines.length - 1; n++) {\n const line = lines[n]!;\n if (!line.trim().startsWith(\"{\")) continue;\n try {\n JSON.parse(line);\n continue;\n } catch {\n // Not valid JSON: try a repair.\n }\n // Only a slip of one closer: the first line of a pretty-printed\n // operation is off by more and must stay for the scan below.\n const imbalance = closerImbalance(line);\n if (Math.abs(imbalance) !== 1) continue;\n // A line that misses a closer and is followed by more than a new\n // operation is the start of an object over several lines.\n const next = lines.slice(n + 1).find((l) => l.trim() !== \"\");\n if (imbalance > 0 && next !== undefined && !next.trim().startsWith(\"{\")) {\n continue;\n }\n try {\n const fixed = jsonrepair(line);\n const value: unknown = JSON.parse(fixed);\n if (\n withoutClosers(fixed) === withoutClosers(line) &&\n isOperationShape(value) &&\n !nestsStructuralKey(value) &&\n // A call must not run with args that a closer moved.\n !(isRecord(value) && \"callRendererFunction\" in value)\n ) {\n repaired.push(line.trim());\n lines[n] = JSON.stringify(value);\n }\n } catch {\n // Leave it: the scan below drops or salvages it as before.\n }\n }\n return { text: lines.join(\"\\n\"), repaired };\n}\n\n/**\n * Parse the body of an a2ui fence as a stream of top-level JSON values, so\n * operations may be one per line (the documented format), several per line,\n * pretty-printed over many lines, or wrapped in a top-level array (which is\n * flattened). Whitespace and commas between objects are ignored.\n *\n * - A balanced object is `JSON.parse`d. When that fails (e.g. a stray quote),\n * its raw text goes to `invalidLines` and whatever `partialOperation` can\n * salvage (complete components, data-model entries, createSurface fields)\n * is kept.\n * - An unbalanced object followed by a line that opens a new operation is\n * treated the same way.\n * - The trailing unbalanced object (still streaming, or never closed) is\n * `partialObject` and yields a partial operation when it has usable data.\n * - Other text between objects is skipped and reported in `recovered` (and in\n * `invalidLines`, which predates it).\n *\n * `partialLine` is a deprecated alias of `partialObject`.\n *\n * @param fenceText - The body of an a2ui fence (`text` of an a2ui\n * `MarkdownSegment`), complete or still streaming.\n * @returns `{ operations, partialObject, partialLine, invalidLines, recovered }`.\n *\n * @example\n * ```ts\n * const { operations } = extractFenceOperations(segment.text);\n * ```\n */\nexport function extractFenceOperations(fenceText: string) {\n const { text: s, repaired: repairedLines } = repairFenceLines(fenceText);\n const operations: A2UIMarkdownOperation[] = [];\n const invalidLines: string[] = [];\n const recovered: string[] = [];\n let partialObject: string | null = null;\n\n const salvage = (raw: string) => {\n invalidLines.push(raw.trim());\n const partial = partialOperation(raw);\n if (partial) operations.push(partial);\n };\n\n let junkStart = -1;\n const flushJunk = (end: number) => {\n if (junkStart < 0) return;\n const junk = s.slice(junkStart, end).trim();\n junkStart = -1;\n if (!junk) return;\n recovered.push(junk);\n invalidLines.push(junk);\n };\n\n let i = 0;\n while (i < s.length) {\n const c = s[i]!;\n if (c === \"{\") {\n flushJunk(i);\n const { end, balanced } = scanTopLevelObject(s, i);\n const raw = s.slice(i, end);\n if (balanced) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n parsed = undefined;\n }\n if (isRecord(parsed)) operations.push(parsed);\n else salvage(raw);\n } else if (end < s.length) {\n salvage(raw);\n } else {\n partialObject = raw;\n const partial = partialOperation(raw);\n if (partial) operations.push(partial);\n }\n i = end;\n continue;\n }\n if (c === \"\\n\" || c === \"[\" || c === \"]\") {\n // A top-level array of operations is flattened by skipping its brackets.\n flushJunk(i);\n } else if (junkStart < 0 && !isWhitespace(c) && c !== \",\") {\n junkStart = i;\n }\n i++;\n }\n flushJunk(s.length);\n\n return {\n operations,\n partialObject,\n partialLine: partialObject,\n invalidLines,\n recovered,\n /** Complete lines that were off by one closing brace and were repaired. */\n repairedLines,\n };\n}\n\n/**\n * Normalise a fence's operations for the renderer: drop unknown messages, fill\n * in `version` and missing `surfaceId`s, keep only the first `createSurface`,\n * keep its `catalogId` when `catalogIds` lists it (else use `catalogId`), synthesize\n * `createSurface` when the model omitted it, and report the\n * surfaceId (the first one found, else `fallbackSurfaceId`).\n *\n * `callRendererFunction` operations target no surface. They get no surfaceId,\n * do not cause a synthesized `createSurface`, and come back in\n * `functionCalls` (in fence order), never in `operations`.\n *\n * @param input.operations - Operations from `extractFenceOperations`.\n * @param input.fallbackSurfaceId - The surfaceId to use when no operation\n * names one.\n * @param input.catalogId - The client catalog. It replaces a catalogId of the\n * model that `catalogIds` does not list.\n * @param input.catalogIds - The catalogs that the model can name. Left out,\n * only `catalogId`.\n * @returns `{ surfaceId, operations, functionCalls }`.\n *\n * @example\n * ```ts\n * const { surfaceId, operations, functionCalls } = prepareSurfaceOperations({\n * operations: extractFenceOperations(segment.text).operations,\n * fallbackSurfaceId: `${messageId}-${segment.index}`,\n * catalogId,\n * });\n * ```\n */\nexport function prepareSurfaceOperations(input: {\n operations: A2UIMarkdownOperation[];\n fallbackSurfaceId: string;\n catalogId: string;\n catalogIds?: readonly string[];\n}) {\n const { operations, fallbackSurfaceId, catalogId } = input;\n const catalogIds = input.catalogIds ?? [catalogId];\n const surfaceId =\n operations\n .map(getMarkdownOperationSurfaceId)\n .find((id): id is string => !!id) ?? fallbackSurfaceId;\n\n const out: A2UIMarkdownOperation[] = [];\n const functionCalls: A2UIMarkdownOperation[] = [];\n let hasCreate = false;\n for (const op of operations) {\n const entry = getOperationEntry(op);\n if (!entry) continue;\n const { key } = entry;\n const inner = { ...entry.inner };\n const version = typeof op.version === \"string\" ? op.version : A2UI_VERSION;\n if (key === FUNCTION_CALL_KEY) {\n functionCalls.push({ version, [key]: inner });\n continue;\n }\n if (typeof inner.surfaceId !== \"string\") inner.surfaceId = surfaceId;\n if (key === \"createSurface\") {\n // A surface is created once; a repeated createSurface (e.g. a later\n // reply that rebuilds a page target) would throw \"Surface already\n // exists\". Its data model and components become updates instead, so\n // the new UI is not lost.\n if (hasCreate) {\n const { surfaceId: id, dataModel, components } = inner;\n if (dataModel !== undefined) {\n out.push({\n version,\n updateDataModel: { surfaceId: id, path: \"/\", value: dataModel },\n });\n }\n if (Array.isArray(components) && components.length > 0) {\n out.push({\n version,\n updateComponents: { surfaceId: id, components },\n });\n }\n continue;\n }\n hasCreate = true;\n // The catalog is client-owned: a catalog that the client does not\n // list is replaced.\n if (!catalogIds.includes(inner.catalogId as string)) {\n inner.catalogId = catalogId;\n }\n }\n out.push({ version, [key]: inner });\n }\n\n if (!hasCreate && out.length > 0) {\n out.unshift({\n version: A2UI_VERSION,\n createSurface: { surfaceId, catalogId },\n });\n }\n return { surfaceId, operations: out, functionCalls };\n}\n\n/**\n * Components a user operates. A Card containing one of these is an\n * interactive panel and keeps its box; every other Card is informational.\n */\nconst INTERACTIVE_COMPONENTS = new Set([\n \"Button\",\n \"Pressable\",\n \"Form\",\n \"TextField\",\n \"TextArea\",\n \"Select\",\n \"CheckBox\",\n \"Radio\",\n \"RadioGroup\",\n \"Slider\",\n \"SegmentedControl\",\n \"ChoicePicker\",\n \"DateTimeInput\",\n]);\n\n/** A component id referenced by a `child`/`children` entry or a table cell. */\nfunction referencedId(value: unknown) {\n if (typeof value === \"string\") return value;\n if (isRecord(value)) {\n if (typeof value.componentId === \"string\") return value.componentId;\n if (typeof value.id === \"string\") return value.id;\n }\n return undefined;\n}\n\n/** Ids of a table cell / column that renders a component (`{componentId}` or `{id}`). */\nfunction cellComponentId(value: unknown) {\n return isRecord(value) ? referencedId(value) : undefined;\n}\n\n/**\n * More ids a component renders, beyond `child`, `children` and the table\n * cells: the typed child references of its catalog, which can sit at any\n * depth of its props (the `child` of each entry of `tabs`). The catalog\n * knows them; the operations alone do not.\n */\nexport type ChildIdsOf = (\n component: Record<string, unknown>,\n) => string[] | \"unknown\";\n\n/** The options of the walks that follow child ids. */\nexport interface ChildWalkOptions {\n childIds?: ChildIdsOf;\n}\n\n/**\n * Ids a component renders directly: `child`, `children` (string ids, an\n * array, or a `{componentId}` template), component cells of a Table's\n * `rows`/`columns`, and the ids that `extra` finds in its typed references.\n */\nfunction directChildIds(\n component: Record<string, unknown>,\n extra?: ChildIdsOf,\n) {\n const ids: string[] = [];\n const add = (id: string | undefined) => {\n if (id) ids.push(id);\n };\n const extraIds = extra?.(component);\n if (Array.isArray(extraIds)) extraIds.forEach(add);\n add(referencedId(component.child));\n const children = component.children;\n if (Array.isArray(children)) children.forEach((c) => add(referencedId(c)));\n else add(referencedId(children));\n if (Array.isArray(component.columns)) {\n component.columns.forEach((c) => add(cellComponentId(c)));\n }\n if (Array.isArray(component.rows)) {\n for (const row of component.rows) {\n if (Array.isArray(row)) row.forEach((c) => add(cellComponentId(c)));\n }\n }\n return ids;\n}\n\n/** Components of every updateComponents operation, by id (last definition wins). */\nfunction componentsById(operations: A2UIMarkdownOperation[]) {\n const byId = new Map<string, Record<string, unknown>>();\n for (const op of operations) {\n const update = op.updateComponents;\n const list = isRecord(update) ? update.components : undefined;\n if (!Array.isArray(list)) continue;\n for (const c of list) {\n if (isRecord(c) && typeof c.id === \"string\") byId.set(c.id, c);\n }\n }\n return byId;\n}\n\nfunction descendantIds(\n rootId: string,\n byId: Map<string, Record<string, unknown>>,\n extra?: ChildIdsOf,\n) {\n const seen = new Set<string>();\n const stack = [...directChildIds(byId.get(rootId) ?? {}, extra)];\n while (stack.length > 0) {\n const id = stack.pop()!;\n if (seen.has(id) || id === rootId) continue;\n seen.add(id);\n const c = byId.get(id);\n if (c) stack.push(...directChildIds(c, extra));\n }\n return seen;\n}\n\n/**\n * Ids of the `Card` components that are interactive panels: at least one\n * descendant (via `child`, `children` or table component cells) is a control\n * (Button, Pressable, Form, TextField, TextArea, Select, CheckBox, Radio,\n * RadioGroup, Slider, SegmentedControl, DateTimeInput).\n *\n * @param components - The components of one surface.\n * @returns The ids of the interactive cards.\n *\n * @example\n * ```ts\n * const interactive = classifySurfaceCards(components);\n * const keepsBox = interactive.has(\"quote-form\");\n * ```\n */\nexport function classifySurfaceCards(\n components: Record<string, unknown>[],\n options: ChildWalkOptions = {},\n) {\n const byId = new Map<string, Record<string, unknown>>();\n for (const c of components) {\n if (isRecord(c) && typeof c.id === \"string\") byId.set(c.id, c);\n }\n const interactive = new Set<string>();\n for (const [id, c] of byId) {\n if (c.component !== \"Card\") continue;\n for (const d of descendantIds(id, byId, options.childIds)) {\n const type = byId.get(d)?.component;\n if (typeof type === \"string\" && INTERACTIVE_COMPONENTS.has(type)) {\n interactive.add(id);\n break;\n }\n }\n }\n return interactive;\n}\n\n/**\n * Markdown mode: only interactive panels keep a box. Every `Card` that is not\n * an interactive panel (see `classifySurfaceCards`), sets no `variant` or\n * `border` of its own and is not nested inside an interactive panel becomes\n * `variant: \"section\"` (a heading plus content without a box). Operations\n * other than updateComponents pass through unchanged.\n *\n * @param operations - The operations of one surface.\n * @returns The operations with informational cards set to `variant: \"section\"`.\n * When no card changes, it returns the same array.\n *\n * @example\n * ```ts\n * const operations = flattenInformationalCards(prepared.operations);\n * ```\n */\nexport function flattenInformationalCards(\n operations: A2UIMarkdownOperation[],\n options: ChildWalkOptions = {},\n) {\n const byId = componentsById(operations);\n if (![...byId.values()].some((c) => c.component === \"Card\")) {\n return operations;\n }\n const interactive = classifySurfaceCards([...byId.values()], options);\n const insideInteractive = new Set<string>();\n for (const id of interactive) {\n for (const d of descendantIds(id, byId, options.childIds)) {\n insideInteractive.add(d);\n }\n }\n const flatten = (c: Record<string, unknown>) =>\n c.component === \"Card\" &&\n typeof c.id === \"string\" &&\n !interactive.has(c.id) &&\n !insideInteractive.has(c.id) &&\n c.variant == null &&\n c.border == null;\n\n const flattened: A2UIMarkdownOperation[] = operations.map((op) => {\n const update = op.updateComponents;\n if (!isRecord(update) || !Array.isArray(update.components)) return op;\n if (!update.components.some((c) => isRecord(c) && flatten(c))) return op;\n return {\n ...op,\n updateComponents: {\n ...update,\n components: update.components.map((c) =>\n isRecord(c) && flatten(c) ? { ...c, variant: \"section\" } : c,\n ),\n },\n };\n });\n return flattened;\n}\n\n/** Text-bearing components that belong in the chat's markdown, not a surface. */\nconst PROSE_TEXT_COMPONENTS = new Set([\"Title\", \"Text\", \"Caption\", \"Markdown\"]);\n\n/** A component that converts to markdown: text-bearing prose, or a separator next to it. */\ntype ProseItem =\n | { kind: \"text\"; markdown: string }\n | { kind: \"divider\" | \"spacer\" };\n\n/** One line of text: list items and headings cannot span lines in markdown. */\nfunction oneLine(text: string) {\n return text.trim().replace(/\\s*\\n\\s*/g, \" \");\n}\n\n/**\n * A literal List entry as list-item markdown: a non-empty string, or\n * `{ label, description? }` with literal strings only. Anything carrying\n * behaviour or decoration (`icon`, `action`, other keys, bound values) is null.\n */\nfunction listEntryMarkdown(entry: unknown) {\n if (typeof entry === \"string\") return entry.trim() ? oneLine(entry) : null;\n if (!isRecord(entry)) return null;\n for (const key of Object.keys(entry)) {\n if (key !== \"label\" && key !== \"description\") return null;\n }\n if (typeof entry.label !== \"string\" || !entry.label.trim()) return null;\n const label = oneLine(entry.label);\n if (entry.description === undefined) return label;\n if (typeof entry.description !== \"string\") return null;\n return entry.description.trim()\n ? `**${label}** — ${oneLine(entry.description)}`\n : label;\n}\n\n/**\n * A List of literal text items as a markdown list (`marker: \"number\"` →\n * `1. …`, otherwise `- …`), or null when it binds its items, renders\n * `children`, or any item is not plain text.\n */\nfunction listToMarkdown(c: Record<string, unknown>) {\n const children = c.children;\n if (children != null && !(Array.isArray(children) && children.length === 0)) {\n return null;\n }\n if (!Array.isArray(c.items) || c.items.length === 0) return null;\n const lines: string[] = [];\n for (const entry of c.items) {\n const line = listEntryMarkdown(entry);\n if (line === null) return null;\n lines.push(line);\n }\n if (c.marker === \"number\") {\n const start =\n typeof c.start === \"number\" && Number.isInteger(c.start) ? c.start : 1;\n return lines.map((line, i) => `${start + i}. ${line}`).join(\"\\n\");\n }\n return lines.map((line) => `- ${line}`).join(\"\\n\");\n}\n\n/** The prose item a component converts to, or null when it is not prose. */\nfunction toProseItem(c: Record<string, unknown> | undefined) {\n if (!c) return null;\n // A component with an accessibility envelope stays a component: markdown\n // has no place for its label, its live region or its hidden state.\n if (c.accessibility !== undefined) return null;\n if (c.component === \"Divider\") return { kind: \"divider\" as const };\n if (c.component === \"Spacer\") return { kind: \"spacer\" as const };\n if (c.component === \"List\") {\n // A horizontal list is a layout, not a text list; a bound direction\n // may be horizontal at render time.\n if (c.direction !== undefined && c.direction !== \"vertical\") return null;\n const markdown = listToMarkdown(c);\n return markdown === null ? null : { kind: \"text\" as const, markdown };\n }\n if (typeof c.component !== \"string\") return null;\n if (!PROSE_TEXT_COMPONENTS.has(c.component)) return null;\n // Only literal strings are prose; `{path}`-bound text is data.\n if (typeof c.text !== \"string\" || c.text.trim() === \"\") return null;\n const text = c.text.trim();\n switch (c.component) {\n case \"Title\": {\n const size = typeof c.size === \"string\" ? c.size : \"md\";\n const level =\n size === \"sm\" ? \"####\" : size === \"md\" || size === \"lg\" ? \"###\" : \"##\";\n return { kind: \"text\" as const, markdown: `${level} ${text}` };\n }\n case \"Text\":\n // Inline children (e.g. a Badge) have no markdown form.\n if (directChildIds(c).length > 0) return null;\n return {\n kind: \"text\" as const,\n markdown: c.strong === true ? `**${text}**` : text,\n };\n default:\n return { kind: \"text\" as const, markdown: text };\n }\n}\n\n/** Prose items as markdown: separators only survive between two text items. */\nfunction proseItemsToMarkdown(items: (ProseItem | null)[]) {\n const blocks: string[] = [];\n let pendingDivider = false;\n for (const item of items) {\n if (item?.kind === \"text\") {\n if (pendingDivider && blocks.length > 0) blocks.push(\"---\");\n pendingDivider = false;\n blocks.push(item.markdown);\n } else if (item?.kind === \"divider\") {\n pendingDivider = true;\n }\n }\n return blocks.join(\"\\n\\n\");\n}\n\n/** Column, column-direction Box, or an informational Card (section/unset variant). */\nfunction isVerticalStack(\n c: Record<string, unknown>,\n interactiveCards: Set<string>,\n) {\n // A container with an accessibility envelope keeps its children: lifted\n // text would lose its hidden state or its live region.\n if (c.accessibility !== undefined) return false;\n if (c.component === \"Column\") return true;\n if (c.component === \"Box\") {\n return c.direction == null || c.direction === \"col\";\n }\n if (c.component === \"Card\") {\n return (\n (c.variant == null || c.variant === \"section\") &&\n typeof c.id === \"string\" &&\n !interactiveCards.has(c.id)\n );\n }\n return false;\n}\n\n/** The child-id list of a stack (`children`, or a lone `child`), else null. */\n/**\n * The children of a stack in render order: `child` first (a Card renders\n * its `child` before its `children`), then `children`.\n */\nfunction stackChildren(c: Record<string, unknown>) {\n const first = typeof c.child === \"string\" ? [c.child] : [];\n if (Array.isArray(c.children)) return [...first, ...c.children];\n if (first.length > 0 && c.children === undefined) return first;\n return null;\n}\n\n/** A contiguous slice `[start, end)` of the stack's children. */\ntype ChildRun = { prose: boolean; start: number; end: number };\n\n/**\n * Partitions the stack's children into alternating prose and surface runs.\n * A run of consecutive prose items is prose only when it holds text: a run of\n * separators alone (Divider/Spacer between two UI components, or at the very\n * start/end of the stack) stays with the surface it sits in.\n */\nfunction partitionChildren(items: (ProseItem | null)[]) {\n const runs: ChildRun[] = [];\n let i = 0;\n while (i < items.length) {\n const candidate = items[i] !== null;\n let hasText = false;\n let j = i;\n while (j < items.length && (items[j] !== null) === candidate) {\n if (items[j]?.kind === \"text\") hasText = true;\n j++;\n }\n const prose = candidate && hasText;\n const last = runs[runs.length - 1];\n if (!prose && last && !last.prose) last.end = j;\n else runs.push({ prose, start: i, end: j });\n i = j;\n }\n return runs;\n}\n\n/** One block of a segmented surface, in render order. */\nexport type SurfaceSegment =\n | { kind: \"markdown\"; markdown: string }\n | { kind: \"surface\"; components: Record<string, unknown>[] };\n\n/**\n * Markdown mode: split a surface into markdown and surface segments so that\n * only real UI renders as A2UI and everything else is the chat's markdown.\n *\n * From `root`, descend through single-child vertical containers (Column,\n * column Box, informational Card) to the first one with several children:\n * the stack. Its children are partitioned, in order, into runs of prose and\n * runs of UI. Prose is `Title`, `Text`, `Caption`, `Markdown` with literal\n * text, a `List` of literal text items, plus `Divider`/`Spacer` next to them:\n * `Title` → heading by size (sm `####`, md/lg `###`, larger `##`), `Text` →\n * paragraph (`strong` → `**…**`), `Caption`/`Markdown` → paragraph, `List` →\n * `- …` (or `1. …` for `marker: \"number\"`, `**label** — description` for\n * described items), and a `Divider` between two prose blocks → `---`.\n *\n * Not prose: `{path}`-bound text or items, a Text with inline children, a\n * List with `children`/icons/actions, a template entry, a component with an\n * `accessibility` envelope, and a child whose component has not streamed\n * yet. Separators with no text beside them stay in\n * the surface. An interactive Card (see `classifySurfaceCards`) is never\n * entered.\n *\n * Each prose run becomes a markdown segment; each UI run becomes a surface\n * segment whose `root` is a copy of the stack (its other props kept, `child`\n * dropped) with only that run's `children`, followed by every component\n * reachable from them. When nothing is prose the input comes back as the one\n * surface segment (same array); when everything is (or `root` itself is),\n * there are only markdown segments.\n *\n * Pure and linear in the number of components, so it runs on every stream\n * update.\n *\n * @param components - The components of one surface, root included.\n * @returns The segments in render order.\n *\n * @example\n * ```ts\n * for (const segment of segmentSurfaceProse(components)) {\n * if (segment.kind === \"markdown\") renderMarkdown(segment.markdown);\n * else renderSurface(segment.components);\n * }\n * ```\n */\nexport function segmentSurfaceProse(\n components: Record<string, unknown>[],\n options: ChildWalkOptions = {},\n) {\n const unchanged: SurfaceSegment[] = [{ kind: \"surface\", components }];\n const byId = new Map<string, Record<string, unknown>>();\n for (const c of components) {\n if (isRecord(c) && typeof c.id === \"string\") byId.set(c.id, c);\n }\n const root = byId.get(GENERATIVE_UI_ROOT_ID);\n if (!root) return unchanged;\n // A component whose children are known only at render time (a bound\n // list of tabs) could reference any component. The lift cannot tell\n // which ones to keep, so it keeps the surface whole.\n const hasUnknownChildren = components.some(\n (c) => isRecord(c) && options.childIds?.(c) === \"unknown\",\n );\n if (hasUnknownChildren) return unchanged;\n\n const rootItem = toProseItem(root);\n if (rootItem?.kind === \"text\") {\n const whole: SurfaceSegment[] = [\n { kind: \"markdown\", markdown: rootItem.markdown },\n ];\n return whole;\n }\n\n const interactiveCards = classifySurfaceCards(components, options);\n let stack = root;\n let stackId: string = GENERATIVE_UI_ROOT_ID;\n let children: unknown[];\n const visited = new Set<string>();\n while (true) {\n if (!isVerticalStack(stack, interactiveCards)) return unchanged;\n visited.add(stackId);\n const list = stackChildren(stack);\n if (!list) return unchanged;\n children = list;\n const nextId = list.length === 1 ? list[0] : undefined;\n if (typeof nextId !== \"string\") break;\n const next = byId.get(nextId);\n if (!next || visited.has(nextId) || toProseItem(next)) break;\n stack = next;\n stackId = nextId;\n }\n\n const stackChildIds = children;\n const items = stackChildIds.map((id) =>\n typeof id === \"string\" ? toProseItem(byId.get(id)) : null,\n );\n const runs = partitionChildren(items);\n if (!runs.some((run) => run.prose)) return unchanged;\n\n // Which surface segments each component belongs to (shared ones go to all).\n const surfaceRuns = runs.filter((run) => !run.prose);\n const owners = new Map<string, number[]>();\n surfaceRuns.forEach((run, index) => {\n const pending = stackChildIds\n .slice(run.start, run.end)\n .map(referencedId)\n .filter((id): id is string => id !== undefined);\n const seen = new Set<string>();\n while (pending.length > 0) {\n const id = pending.pop()!;\n // `root` is replaced by the stack copy; the stack never nests in itself.\n const isSkipped = id === GENERATIVE_UI_ROOT_ID || id === stackId;\n if (isSkipped || seen.has(id)) continue;\n seen.add(id);\n const list = owners.get(id);\n if (list) list.push(index);\n else owners.set(id, [index]);\n const c = byId.get(id);\n if (c) pending.push(...directChildIds(c, options.childIds));\n }\n });\n const surfaceComponents = surfaceRuns.map((run) => {\n // `child` is folded into `children` by stackChildren, so the copy must\n // not render it a second time.\n const { child: _child, ...stackRest } = stack;\n const nextRoot: Record<string, unknown> = {\n ...stackRest,\n id: GENERATIVE_UI_ROOT_ID,\n children: stackChildIds.slice(run.start, run.end),\n };\n delete nextRoot.child;\n return [nextRoot];\n });\n for (const c of components) {\n if (!isRecord(c) || typeof c.id !== \"string\" || byId.get(c.id) !== c) {\n continue;\n }\n const ownerIndexes = owners.get(c.id) ?? [];\n for (const index of ownerIndexes) {\n surfaceComponents[index]!.push(c);\n }\n }\n\n let surfaceIndex = 0;\n const segments: SurfaceSegment[] = runs.map((run) => {\n if (run.prose) {\n return {\n kind: \"markdown\",\n markdown: proseItemsToMarkdown(items.slice(run.start, run.end)),\n };\n }\n return { kind: \"surface\", components: surfaceComponents[surfaceIndex++]! };\n });\n return segments;\n}\n"],"mappings":";;;;;AACA,MAAa,sBAAsB;;AAqBnC,MAAM,aAAa;;AAGnB,MAAM,eAAe;AAerB,SAAS,SAAS,MAAc,OAAkB;CAChD,MAAM,UAAU,KAAK,MAAM;AAC3B,KAAI,QAAQ,SAAS,MAAM,OAAQ,QAAO;AAC1C,MAAK,MAAM,MAAM,QACf,KAAI,OAAO,MAAM,KAAM,QAAO;AAEhC,QAAO;;;AAIT,SAAS,WAAW,QAAkB;AACpC,MAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,QAAQ,aAAa,KAAK,MAAM;AACtC,MAAI,MAAO,QAAO,MAAM;;;AAK5B,SAAS,YAAY,OAAkB,MAAc,QAAiB;CACpE,MAAM,UAAuB;EAC3B,MAAM;EACN,OAAO,MAAM;EACb;EACA;EACD;AACD,KAAI,MAAM,WAAW,OAAW,SAAQ,SAAS,MAAM;AACvD,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BT,SAAgB,kBAAkB,UAAkB;CAClD,MAAM,WAA8B,EAAE;CACtC,IAAI,aAAa;CACj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,CAAC;GAC5B,MAAM,IAAI,KAAK,IAAI,GAAG;AACtB,OAAI,EAAG,SAAQ,KAAK,GAAG,eAAe,GAAG,QAAQ,SAAS,CAAC;;GAE7D;CACF,MAAM,oBAAoB,YAAY,KAAK,QAAQ;EAGjD,MAAM,EAAE,OAAO,QAAQ,GAAG,cAAc;EACxC,MAAM,WAAoC;GACxC,GAAG;GACH,IAAIA;GACJ,UAAU,cAAc,MAAM,IAAI,OAAO,IAAI,IAAI;GAClD;AACD,SAAO,SAAS;AAChB,SAAO,CAAC,SAAS;GACjB;AACF,MAAK,MAAM,KAAK,YAAY;AAC1B,MAAI,CAAC,SAAS,EAAE,IAAI,OAAO,EAAE,OAAO,YAAY,KAAK,IAAI,EAAE,GAAG,KAAK,EACjE;EAEF,MAAM,eAAe,OAAO,IAAI,EAAE,GAAG,IAAI,EAAE;AAC3C,OAAK,MAAM,SAAS,aAClB,mBAAkB,OAAQ,KAAK,EAAE;;CAIrC,IAAI,eAAe;AAUnB,QATmC,KAAK,KAAK,QAAQ;AACnD,MAAI,IAAI,MACN,QAAO;GACL,MAAM;GACN,UAAU,qBAAqB,MAAM,MAAM,IAAI,OAAO,IAAI,IAAI,CAAC;GAChE;AAEH,SAAO;GAAE,MAAM;GAAW,YAAY,kBAAkB;GAAkB;GAC1E"}
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_viewport = require('./viewport-D-tuKCeb.cjs');
|
|
3
|
+
let _copilotkit_shared = require("@copilotkit/shared");
|
|
4
|
+
|
|
5
|
+
//#region src/chat/chat-configuration.ts
|
|
6
|
+
const CONTROLLED_SET_WARNING = "[CopilotKit] Ignoring setActiveThreadId(): threadId is controlled via the `threadId` prop on CopilotChatConfigurationProvider.";
|
|
7
|
+
const CONTROLLED_NEW_WARNING = "[CopilotKit] Ignoring startNewThread(): threadId is controlled via the `threadId` prop on CopilotChatConfigurationProvider.";
|
|
8
|
+
function isSameSnapshot(a, b) {
|
|
9
|
+
return a.agentId === b.agentId && a.threadId === b.threadId && a.hasExplicitThreadId === b.hasExplicitThreadId && a.isModalOpen === b.isModalOpen && a.drawerOpen === b.drawerOpen && a.drawerRegistered === b.drawerRegistered;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* One chat configuration provider's state. A nested provider passes its
|
|
13
|
+
* parent store, and the chain behaves as one:
|
|
14
|
+
*
|
|
15
|
+
* - **Thread**: a controlled `threadId` wins; then a picked or new thread;
|
|
16
|
+
* then the parent's thread; then a seed `threadId`; then a UUID minted once
|
|
17
|
+
* per store. Picking a thread or starting a new one is owned by the top-most
|
|
18
|
+
* store; nested stores pass the call up, after their own controlled check.
|
|
19
|
+
* - **Agent**: own `agentId`, then the parent's, then the provider default,
|
|
20
|
+
* then `DEFAULT_AGENT_ID`.
|
|
21
|
+
* - **Modal**: own state when `isModalDefaultOpen` is set (changes also go to
|
|
22
|
+
* the parent, and parent changes after creation come down); otherwise the
|
|
23
|
+
* parent's state; a store without either starts open.
|
|
24
|
+
* - **Drawer**: owned by the top-most store, so one drawer serves the chain.
|
|
25
|
+
* On a mobile-width viewport, opening the drawer closes the modal that is
|
|
26
|
+
* on screen and opening the modal closes the drawer.
|
|
27
|
+
*
|
|
28
|
+
* The store links to its parent (and registers its modal closer there) while
|
|
29
|
+
* it has subscribers, so a discarded store holds nothing.
|
|
30
|
+
*/
|
|
31
|
+
var ɵChatConfigurationStore = class {
|
|
32
|
+
#options;
|
|
33
|
+
#parent;
|
|
34
|
+
#fallbackThreadId = (0, _copilotkit_shared.randomUUID)();
|
|
35
|
+
#override = null;
|
|
36
|
+
#ownModalOpen;
|
|
37
|
+
#ownDrawerOpen = false;
|
|
38
|
+
#drawerCount = 0;
|
|
39
|
+
#modalClosers = [];
|
|
40
|
+
#listeners = /* @__PURE__ */ new Set();
|
|
41
|
+
#disconnectParent = null;
|
|
42
|
+
#lastParentModalOpen;
|
|
43
|
+
#snapshot;
|
|
44
|
+
#notified;
|
|
45
|
+
constructor(options, parent = null) {
|
|
46
|
+
this.#options = options;
|
|
47
|
+
this.#parent = parent;
|
|
48
|
+
this.#ownModalOpen = options.isModalDefaultOpen ?? true;
|
|
49
|
+
this.#lastParentModalOpen = parent?.getSnapshot().isModalOpen;
|
|
50
|
+
this.#snapshot = this.#compute();
|
|
51
|
+
this.#notified = this.#snapshot;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* The current values, read through the parent and the latest options, so a
|
|
55
|
+
* render always sees them. Same object until one of them changes.
|
|
56
|
+
*/
|
|
57
|
+
getSnapshot = () => {
|
|
58
|
+
const next = this.#compute();
|
|
59
|
+
if (!isSameSnapshot(next, this.#snapshot)) this.#snapshot = next;
|
|
60
|
+
return this.#snapshot;
|
|
61
|
+
};
|
|
62
|
+
/** Listen for changes. Returns unsubscribe. */
|
|
63
|
+
subscribe = (listener) => {
|
|
64
|
+
this.#listeners.add(listener);
|
|
65
|
+
if (this.#listeners.size === 1) this.#connect();
|
|
66
|
+
return () => {
|
|
67
|
+
this.#listeners.delete(listener);
|
|
68
|
+
if (this.#listeners.size === 0) this.#disconnect();
|
|
69
|
+
};
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* Take the provider's current props without notifying: for a render phase,
|
|
73
|
+
* where `getSnapshot()` already reflects them. Call {@link update} after
|
|
74
|
+
* the commit so subscribers hear about the change.
|
|
75
|
+
*/
|
|
76
|
+
ɵsetOptions(options) {
|
|
77
|
+
this.#options = options;
|
|
78
|
+
}
|
|
79
|
+
/** Give the provider's current props and notify subscribers. */
|
|
80
|
+
update(options) {
|
|
81
|
+
const hadOwnModal = this.#hasOwnModal;
|
|
82
|
+
this.#options = options;
|
|
83
|
+
if (hadOwnModal !== this.#hasOwnModal && this.#listeners.size > 0) {
|
|
84
|
+
this.#disconnect();
|
|
85
|
+
this.#connect();
|
|
86
|
+
}
|
|
87
|
+
this.#refresh();
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Show `threadId`. `explicit` (default `true`) marks it as a caller
|
|
91
|
+
* choice; `false` keeps the welcome screen for a fresh thread. Ignored with
|
|
92
|
+
* a warning when the thread is controlled.
|
|
93
|
+
*/
|
|
94
|
+
setActiveThreadId = (threadId, options) => {
|
|
95
|
+
if (this.#isThreadControlled) {
|
|
96
|
+
console.warn(CONTROLLED_SET_WARNING);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
if (this.#parent) {
|
|
100
|
+
this.#parent.setActiveThreadId(threadId, options);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
this.#override = {
|
|
104
|
+
threadId,
|
|
105
|
+
explicit: options?.explicit ?? true
|
|
106
|
+
};
|
|
107
|
+
this.#refresh();
|
|
108
|
+
};
|
|
109
|
+
/**
|
|
110
|
+
* Show a fresh client-side thread (new UUID, not explicit). Ignored with a
|
|
111
|
+
* warning when the thread is controlled.
|
|
112
|
+
*/
|
|
113
|
+
startNewThread = () => {
|
|
114
|
+
if (this.#isThreadControlled) {
|
|
115
|
+
console.warn(CONTROLLED_NEW_WARNING);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (this.#parent) {
|
|
119
|
+
this.#parent.startNewThread();
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
this.#override = {
|
|
123
|
+
threadId: (0, _copilotkit_shared.randomUUID)(),
|
|
124
|
+
explicit: false
|
|
125
|
+
};
|
|
126
|
+
this.#refresh();
|
|
127
|
+
};
|
|
128
|
+
/** Open or close the chat modal (closing the drawer on mobile). */
|
|
129
|
+
setModalOpen = (open) => {
|
|
130
|
+
if (open && require_viewport.ɵisMobileViewport()) this.setDrawerOpen(false);
|
|
131
|
+
this.#setModalState(open);
|
|
132
|
+
};
|
|
133
|
+
/** Open or close the drawer (closing the on-screen modal on mobile). */
|
|
134
|
+
setDrawerOpen = (open) => {
|
|
135
|
+
if (this.#parent) {
|
|
136
|
+
this.#parent.setDrawerOpen(open);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
this.#ownDrawerOpen = open;
|
|
140
|
+
this.#refresh();
|
|
141
|
+
if (!open || !require_viewport.ɵisMobileViewport()) return;
|
|
142
|
+
(this.#modalClosers[this.#modalClosers.length - 1] ?? ((next) => this.#setModalState(next)))(false);
|
|
143
|
+
};
|
|
144
|
+
/**
|
|
145
|
+
* Announce a mounted threads drawer; `drawerRegistered` stays `true` until
|
|
146
|
+
* every returned cleanup has run. Each cleanup runs once.
|
|
147
|
+
*/
|
|
148
|
+
registerDrawer = () => {
|
|
149
|
+
if (this.#parent) return this.#parent.registerDrawer();
|
|
150
|
+
this.#drawerCount++;
|
|
151
|
+
this.#refresh();
|
|
152
|
+
let active = true;
|
|
153
|
+
return () => {
|
|
154
|
+
if (!active) return;
|
|
155
|
+
active = false;
|
|
156
|
+
this.#drawerCount = Math.max(0, this.#drawerCount - 1);
|
|
157
|
+
this.#refresh();
|
|
158
|
+
};
|
|
159
|
+
};
|
|
160
|
+
/**
|
|
161
|
+
* Register the setter of the modal that is actually rendered, so the
|
|
162
|
+
* drawer's mobile exclusion closes it. The latest registration wins.
|
|
163
|
+
*/
|
|
164
|
+
registerModalCloser = (closeModal) => {
|
|
165
|
+
if (this.#parent) return this.#parent.registerModalCloser(closeModal);
|
|
166
|
+
this.#modalClosers.push(closeModal);
|
|
167
|
+
return () => {
|
|
168
|
+
const index = this.#modalClosers.lastIndexOf(closeModal);
|
|
169
|
+
if (index !== -1) this.#modalClosers.splice(index, 1);
|
|
170
|
+
};
|
|
171
|
+
};
|
|
172
|
+
/**
|
|
173
|
+
* Tell core which thread this chat shows, so captured interactions link to
|
|
174
|
+
* it. Re-registers when the agent changes. Returns the cleanup.
|
|
175
|
+
*/
|
|
176
|
+
bindOpenThread(registry) {
|
|
177
|
+
let agentId = this.getSnapshot().agentId;
|
|
178
|
+
let registration = registry.registerOpenThread({
|
|
179
|
+
agentId,
|
|
180
|
+
threadId: this.getSnapshot().threadId
|
|
181
|
+
});
|
|
182
|
+
const unsubscribe = this.subscribe(() => {
|
|
183
|
+
const { agentId: nextAgentId, threadId } = this.getSnapshot();
|
|
184
|
+
if (nextAgentId === agentId) {
|
|
185
|
+
registration.update(threadId);
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
registration.unregister();
|
|
189
|
+
agentId = nextAgentId;
|
|
190
|
+
registration = registry.registerOpenThread({
|
|
191
|
+
agentId,
|
|
192
|
+
threadId
|
|
193
|
+
});
|
|
194
|
+
});
|
|
195
|
+
return () => {
|
|
196
|
+
unsubscribe();
|
|
197
|
+
registration.unregister();
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
dispose() {
|
|
201
|
+
this.#disconnect();
|
|
202
|
+
this.#listeners.clear();
|
|
203
|
+
}
|
|
204
|
+
get #hasOwnModal() {
|
|
205
|
+
return this.#options.isModalDefaultOpen !== void 0;
|
|
206
|
+
}
|
|
207
|
+
get #isThreadControlled() {
|
|
208
|
+
const { threadId, hasExplicitThreadId } = this.#options;
|
|
209
|
+
return threadId !== void 0 && hasExplicitThreadId !== false;
|
|
210
|
+
}
|
|
211
|
+
#setModalState(open) {
|
|
212
|
+
if (this.#hasOwnModal || !this.#parent) {
|
|
213
|
+
this.#ownModalOpen = open;
|
|
214
|
+
this.#refresh();
|
|
215
|
+
if (this.#hasOwnModal) this.#parent?.setModalOpen(open);
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
this.#parent.setModalOpen(open);
|
|
219
|
+
}
|
|
220
|
+
#connect() {
|
|
221
|
+
const parent = this.#parent;
|
|
222
|
+
if (!parent) return;
|
|
223
|
+
const offParent = parent.subscribe(() => this.#onParentChange());
|
|
224
|
+
const offCloser = this.#hasOwnModal ? parent.registerModalCloser((open) => this.#setModalState(open)) : null;
|
|
225
|
+
this.#disconnectParent = () => {
|
|
226
|
+
offParent();
|
|
227
|
+
offCloser?.();
|
|
228
|
+
};
|
|
229
|
+
this.#refresh();
|
|
230
|
+
}
|
|
231
|
+
#disconnect() {
|
|
232
|
+
this.#disconnectParent?.();
|
|
233
|
+
this.#disconnectParent = null;
|
|
234
|
+
}
|
|
235
|
+
#onParentChange() {
|
|
236
|
+
const parentModalOpen = this.#parent?.getSnapshot().isModalOpen;
|
|
237
|
+
const parentModalChanged = parentModalOpen !== this.#lastParentModalOpen;
|
|
238
|
+
this.#lastParentModalOpen = parentModalOpen;
|
|
239
|
+
if (parentModalChanged && this.#hasOwnModal && parentModalOpen !== void 0) this.#ownModalOpen = parentModalOpen;
|
|
240
|
+
this.#refresh();
|
|
241
|
+
}
|
|
242
|
+
#compute() {
|
|
243
|
+
const options = this.#options;
|
|
244
|
+
const parent = this.#parent?.getSnapshot() ?? null;
|
|
245
|
+
const isControlled = this.#isThreadControlled;
|
|
246
|
+
const threadId = isControlled ? options.threadId : this.#override?.threadId ?? (parent?.threadId || options.threadId || this.#fallbackThreadId);
|
|
247
|
+
const ownExplicit = isControlled ? true : this.#override?.explicit ?? options.hasExplicitThreadId ?? false;
|
|
248
|
+
const ownsDrawer = parent === null;
|
|
249
|
+
return {
|
|
250
|
+
agentId: options.agentId ?? parent?.agentId ?? options.providerAgentId ?? _copilotkit_shared.DEFAULT_AGENT_ID,
|
|
251
|
+
threadId,
|
|
252
|
+
hasExplicitThreadId: ownExplicit || !!parent?.hasExplicitThreadId,
|
|
253
|
+
isModalOpen: this.#hasOwnModal || !parent ? this.#ownModalOpen : parent.isModalOpen,
|
|
254
|
+
drawerOpen: ownsDrawer ? this.#ownDrawerOpen : parent.drawerOpen,
|
|
255
|
+
drawerRegistered: ownsDrawer ? this.#drawerCount > 0 : parent.drawerRegistered
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
#refresh() {
|
|
259
|
+
const snapshot = this.getSnapshot();
|
|
260
|
+
if (snapshot === this.#notified) return;
|
|
261
|
+
this.#notified = snapshot;
|
|
262
|
+
const listeners = [...this.#listeners];
|
|
263
|
+
for (const listener of listeners) listener();
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
//#endregion
|
|
268
|
+
exports.ɵChatConfigurationStore = ɵChatConfigurationStore;
|
|
269
|
+
//# sourceMappingURL=chat-configuration.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chat-configuration.cjs","names":["#parent","#fallbackThreadId","#modalClosers","#listeners","#options","#ownModalOpen","#lastParentModalOpen","#snapshot","#compute","#notified","#connect","#disconnect","#hasOwnModal","#refresh","#isThreadControlled","#override","ɵisMobileViewport","#setModalState","#ownDrawerOpen","#drawerCount","#onParentChange","#disconnectParent","DEFAULT_AGENT_ID"],"sources":["../src/chat/chat-configuration.ts"],"sourcesContent":["import { DEFAULT_AGENT_ID, randomUUID } from \"@copilotkit/shared\";\nimport type { OpenThreadRegistration } from \"../core/learning-bridge\";\nimport { ɵisMobileViewport } from \"./viewport\";\n\n/**\n * Chat configuration state shared by React `CopilotChatConfigurationProvider`,\n * Vue `CopilotChatConfigurationProvider` and Angular\n * `provideCopilotChatConfiguration`: which agent and thread a chat shows, the\n * chat modal's open state, and the thread-list drawer.\n *\n * Internal (`ɵ`): framework packages use it, and it can change in any release.\n */\n\n/** The props a chat configuration provider takes. */\nexport interface ɵChatConfigurationOptions {\n agentId?: string;\n /**\n * The thread to show. It is controlled (imperative thread changes are\n * ignored with a warning) unless `hasExplicitThreadId` is `false`, which\n * marks it as a seed that a picked or new thread may replace.\n */\n threadId?: string;\n hasExplicitThreadId?: boolean;\n /**\n * Set to give this provider its own modal state, starting open or closed.\n * Unset, the provider shares its parent's modal state.\n */\n isModalDefaultOpen?: boolean;\n /** The app-wide default agent (`<CopilotKitProvider agentId>`). */\n providerAgentId?: string;\n}\n\n/** What a chat reads from its configuration. */\nexport interface ɵChatConfigurationSnapshot {\n agentId: string;\n threadId: string;\n /** `true` when a caller chose the thread (not a minted placeholder). */\n hasExplicitThreadId: boolean;\n isModalOpen: boolean;\n drawerOpen: boolean;\n /** `true` while at least one threads drawer is mounted. */\n drawerRegistered: boolean;\n}\n\n/** The core part {@link ɵChatConfigurationStore.bindOpenThread} needs. */\nexport interface ɵOpenThreadRegistry {\n registerOpenThread(params: {\n agentId: string;\n threadId: string;\n }): OpenThreadRegistration;\n}\n\nconst CONTROLLED_SET_WARNING =\n \"[CopilotKit] Ignoring setActiveThreadId(): threadId is controlled \" +\n \"via the `threadId` prop on CopilotChatConfigurationProvider.\";\nconst CONTROLLED_NEW_WARNING =\n \"[CopilotKit] Ignoring startNewThread(): threadId is controlled via \" +\n \"the `threadId` prop on CopilotChatConfigurationProvider.\";\n\ntype ModalCloser = (open: boolean) => void;\n\nfunction isSameSnapshot(\n a: ɵChatConfigurationSnapshot,\n b: ɵChatConfigurationSnapshot,\n) {\n return (\n a.agentId === b.agentId &&\n a.threadId === b.threadId &&\n a.hasExplicitThreadId === b.hasExplicitThreadId &&\n a.isModalOpen === b.isModalOpen &&\n a.drawerOpen === b.drawerOpen &&\n a.drawerRegistered === b.drawerRegistered\n );\n}\n\n/**\n * One chat configuration provider's state. A nested provider passes its\n * parent store, and the chain behaves as one:\n *\n * - **Thread**: a controlled `threadId` wins; then a picked or new thread;\n * then the parent's thread; then a seed `threadId`; then a UUID minted once\n * per store. Picking a thread or starting a new one is owned by the top-most\n * store; nested stores pass the call up, after their own controlled check.\n * - **Agent**: own `agentId`, then the parent's, then the provider default,\n * then `DEFAULT_AGENT_ID`.\n * - **Modal**: own state when `isModalDefaultOpen` is set (changes also go to\n * the parent, and parent changes after creation come down); otherwise the\n * parent's state; a store without either starts open.\n * - **Drawer**: owned by the top-most store, so one drawer serves the chain.\n * On a mobile-width viewport, opening the drawer closes the modal that is\n * on screen and opening the modal closes the drawer.\n *\n * The store links to its parent (and registers its modal closer there) while\n * it has subscribers, so a discarded store holds nothing.\n */\nexport class ɵChatConfigurationStore {\n #options: ɵChatConfigurationOptions;\n readonly #parent: ɵChatConfigurationStore | null;\n readonly #fallbackThreadId = randomUUID();\n #override: { threadId: string; explicit: boolean } | null = null;\n #ownModalOpen: boolean;\n #ownDrawerOpen = false;\n #drawerCount = 0;\n readonly #modalClosers: ModalCloser[] = [];\n readonly #listeners = new Set<() => void>();\n #disconnectParent: (() => void) | null = null;\n #lastParentModalOpen: boolean | undefined;\n #snapshot: ɵChatConfigurationSnapshot;\n #notified: ɵChatConfigurationSnapshot;\n\n constructor(\n options: ɵChatConfigurationOptions,\n parent: ɵChatConfigurationStore | null = null,\n ) {\n this.#options = options;\n this.#parent = parent;\n this.#ownModalOpen = options.isModalDefaultOpen ?? true;\n this.#lastParentModalOpen = parent?.getSnapshot().isModalOpen;\n this.#snapshot = this.#compute();\n this.#notified = this.#snapshot;\n }\n\n /**\n * The current values, read through the parent and the latest options, so a\n * render always sees them. Same object until one of them changes.\n */\n getSnapshot = () => {\n const next = this.#compute();\n if (!isSameSnapshot(next, this.#snapshot)) this.#snapshot = next;\n return this.#snapshot;\n };\n\n /** Listen for changes. Returns unsubscribe. */\n subscribe = (listener: () => void) => {\n this.#listeners.add(listener);\n if (this.#listeners.size === 1) this.#connect();\n return () => {\n this.#listeners.delete(listener);\n if (this.#listeners.size === 0) this.#disconnect();\n };\n };\n\n /**\n * Take the provider's current props without notifying: for a render phase,\n * where `getSnapshot()` already reflects them. Call {@link update} after\n * the commit so subscribers hear about the change.\n */\n ɵsetOptions(options: ɵChatConfigurationOptions) {\n this.#options = options;\n }\n\n /** Give the provider's current props and notify subscribers. */\n update(options: ɵChatConfigurationOptions) {\n const hadOwnModal = this.#hasOwnModal;\n this.#options = options;\n if (hadOwnModal !== this.#hasOwnModal && this.#listeners.size > 0) {\n this.#disconnect();\n this.#connect();\n }\n this.#refresh();\n }\n\n /**\n * Show `threadId`. `explicit` (default `true`) marks it as a caller\n * choice; `false` keeps the welcome screen for a fresh thread. Ignored with\n * a warning when the thread is controlled.\n */\n setActiveThreadId = (threadId: string, options?: { explicit?: boolean }) => {\n if (this.#isThreadControlled) {\n console.warn(CONTROLLED_SET_WARNING);\n return;\n }\n if (this.#parent) {\n this.#parent.setActiveThreadId(threadId, options);\n return;\n }\n this.#override = { threadId, explicit: options?.explicit ?? true };\n this.#refresh();\n };\n\n /**\n * Show a fresh client-side thread (new UUID, not explicit). Ignored with a\n * warning when the thread is controlled.\n */\n startNewThread = () => {\n if (this.#isThreadControlled) {\n console.warn(CONTROLLED_NEW_WARNING);\n return;\n }\n if (this.#parent) {\n this.#parent.startNewThread();\n return;\n }\n this.#override = { threadId: randomUUID(), explicit: false };\n this.#refresh();\n };\n\n /** Open or close the chat modal (closing the drawer on mobile). */\n setModalOpen = (open: boolean) => {\n if (open && ɵisMobileViewport()) this.setDrawerOpen(false);\n this.#setModalState(open);\n };\n\n /** Open or close the drawer (closing the on-screen modal on mobile). */\n setDrawerOpen = (open: boolean) => {\n if (this.#parent) {\n this.#parent.setDrawerOpen(open);\n return;\n }\n this.#ownDrawerOpen = open;\n this.#refresh();\n if (!open || !ɵisMobileViewport()) return;\n const latestCloser = this.#modalClosers[this.#modalClosers.length - 1];\n const closeModal = latestCloser ?? ((next) => this.#setModalState(next));\n closeModal(false);\n };\n\n /**\n * Announce a mounted threads drawer; `drawerRegistered` stays `true` until\n * every returned cleanup has run. Each cleanup runs once.\n */\n registerDrawer = (): (() => void) => {\n if (this.#parent) return this.#parent.registerDrawer();\n this.#drawerCount++;\n this.#refresh();\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n this.#drawerCount = Math.max(0, this.#drawerCount - 1);\n this.#refresh();\n };\n };\n\n /**\n * Register the setter of the modal that is actually rendered, so the\n * drawer's mobile exclusion closes it. The latest registration wins.\n */\n registerModalCloser = (closeModal: ModalCloser): (() => void) => {\n if (this.#parent) return this.#parent.registerModalCloser(closeModal);\n this.#modalClosers.push(closeModal);\n return () => {\n const index = this.#modalClosers.lastIndexOf(closeModal);\n if (index !== -1) this.#modalClosers.splice(index, 1);\n };\n };\n\n /**\n * Tell core which thread this chat shows, so captured interactions link to\n * it. Re-registers when the agent changes. Returns the cleanup.\n */\n bindOpenThread(registry: ɵOpenThreadRegistry) {\n let agentId = this.getSnapshot().agentId;\n let registration = registry.registerOpenThread({\n agentId,\n threadId: this.getSnapshot().threadId,\n });\n const unsubscribe = this.subscribe(() => {\n const { agentId: nextAgentId, threadId } = this.getSnapshot();\n if (nextAgentId === agentId) {\n registration.update(threadId);\n return;\n }\n registration.unregister();\n agentId = nextAgentId;\n registration = registry.registerOpenThread({ agentId, threadId });\n });\n return () => {\n unsubscribe();\n registration.unregister();\n };\n }\n\n dispose() {\n this.#disconnect();\n this.#listeners.clear();\n }\n\n get #hasOwnModal() {\n return this.#options.isModalDefaultOpen !== undefined;\n }\n\n get #isThreadControlled() {\n const { threadId, hasExplicitThreadId } = this.#options;\n return threadId !== undefined && hasExplicitThreadId !== false;\n }\n\n #setModalState(open: boolean) {\n if (this.#hasOwnModal || !this.#parent) {\n this.#ownModalOpen = open;\n this.#refresh();\n if (this.#hasOwnModal) this.#parent?.setModalOpen(open);\n return;\n }\n this.#parent.setModalOpen(open);\n }\n\n #connect() {\n const parent = this.#parent;\n if (!parent) return;\n const offParent = parent.subscribe(() => this.#onParentChange());\n const offCloser = this.#hasOwnModal\n ? parent.registerModalCloser((open) => this.#setModalState(open))\n : null;\n this.#disconnectParent = () => {\n offParent();\n offCloser?.();\n };\n // The parent may have changed while this store had no subscribers.\n this.#refresh();\n }\n\n #disconnect() {\n this.#disconnectParent?.();\n this.#disconnectParent = null;\n }\n\n #onParentChange() {\n const parentModalOpen = this.#parent?.getSnapshot().isModalOpen;\n const parentModalChanged = parentModalOpen !== this.#lastParentModalOpen;\n this.#lastParentModalOpen = parentModalOpen;\n // An owned modal follows changes made above it, not the parent's value\n // at creation (that would override `isModalDefaultOpen`).\n if (\n parentModalChanged &&\n this.#hasOwnModal &&\n parentModalOpen !== undefined\n ) {\n this.#ownModalOpen = parentModalOpen;\n }\n this.#refresh();\n }\n\n #compute(): ɵChatConfigurationSnapshot {\n const options = this.#options;\n const parent = this.#parent?.getSnapshot() ?? null;\n const isControlled = this.#isThreadControlled;\n const threadId = isControlled\n ? (options.threadId as string)\n : (this.#override?.threadId ??\n (parent?.threadId || options.threadId || this.#fallbackThreadId));\n const ownExplicit = isControlled\n ? true\n : (this.#override?.explicit ?? options.hasExplicitThreadId ?? false);\n const ownsDrawer = parent === null;\n return {\n agentId:\n options.agentId ??\n parent?.agentId ??\n options.providerAgentId ??\n DEFAULT_AGENT_ID,\n threadId,\n hasExplicitThreadId: ownExplicit || !!parent?.hasExplicitThreadId,\n isModalOpen:\n this.#hasOwnModal || !parent ? this.#ownModalOpen : parent.isModalOpen,\n drawerOpen: ownsDrawer ? this.#ownDrawerOpen : parent.drawerOpen,\n drawerRegistered: ownsDrawer\n ? this.#drawerCount > 0\n : parent.drawerRegistered,\n };\n }\n\n #refresh() {\n const snapshot = this.getSnapshot();\n if (snapshot === this.#notified) return;\n this.#notified = snapshot;\n const listeners = [...this.#listeners];\n for (const listener of listeners) listener();\n }\n}\n"],"mappings":";;;;;AAoDA,MAAM,yBACJ;AAEF,MAAM,yBACJ;AAKF,SAAS,eACP,GACA,GACA;AACA,QACE,EAAE,YAAY,EAAE,WAChB,EAAE,aAAa,EAAE,YACjB,EAAE,wBAAwB,EAAE,uBAC5B,EAAE,gBAAgB,EAAE,eACpB,EAAE,eAAe,EAAE,cACnB,EAAE,qBAAqB,EAAE;;;;;;;;;;;;;;;;;;;;;;AAwB7B,IAAa,0BAAb,MAAqC;CACnC;CACA,CAASA;CACT,CAASC,uDAAgC;CACzC,YAA4D;CAC5D;CACA,iBAAiB;CACjB,eAAe;CACf,CAASC,eAA+B,EAAE;CAC1C,CAASC,4BAAa,IAAI,KAAiB;CAC3C,oBAAyC;CACzC;CACA;CACA;CAEA,YACE,SACA,SAAyC,MACzC;AACA,QAAKC,UAAW;AAChB,QAAKJ,SAAU;AACf,QAAKK,eAAgB,QAAQ,sBAAsB;AACnD,QAAKC,sBAAuB,QAAQ,aAAa,CAAC;AAClD,QAAKC,WAAY,MAAKC,SAAU;AAChC,QAAK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AAgB,CAAC,SAAS,MAAKP,eAAgB,OAAO;GAC7D,YAAY,aAAa,MAAKa,gBAAiB,OAAO;GACtD,kBAAkB,aACd,MAAKC,cAAe,IACpB,OAAO;GACZ;;CAGH,WAAW;EACT,MAAM,WAAW,KAAK,aAAa;AACnC,MAAI,aAAa,MAAKV,SAAW;AACjC,QAAKA,WAAY;EACjB,MAAM,YAAY,CAAC,GAAG,MAAKN,UAAW;AACtC,OAAK,MAAM,YAAY,UAAW,WAAU"}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { r as OpenThreadRegistration } from "./learning-bridge-DEVwyO7F.cjs";
|
|
2
|
+
|
|
3
|
+
//#region src/chat/chat-configuration.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Chat configuration state shared by React `CopilotChatConfigurationProvider`,
|
|
6
|
+
* Vue `CopilotChatConfigurationProvider` and Angular
|
|
7
|
+
* `provideCopilotChatConfiguration`: which agent and thread a chat shows, the
|
|
8
|
+
* chat modal's open state, and the thread-list drawer.
|
|
9
|
+
*
|
|
10
|
+
* Internal (`ɵ`): framework packages use it, and it can change in any release.
|
|
11
|
+
*/
|
|
12
|
+
/** The props a chat configuration provider takes. */
|
|
13
|
+
interface ɵChatConfigurationOptions {
|
|
14
|
+
agentId?: string;
|
|
15
|
+
/**
|
|
16
|
+
* The thread to show. It is controlled (imperative thread changes are
|
|
17
|
+
* ignored with a warning) unless `hasExplicitThreadId` is `false`, which
|
|
18
|
+
* marks it as a seed that a picked or new thread may replace.
|
|
19
|
+
*/
|
|
20
|
+
threadId?: string;
|
|
21
|
+
hasExplicitThreadId?: boolean;
|
|
22
|
+
/**
|
|
23
|
+
* Set to give this provider its own modal state, starting open or closed.
|
|
24
|
+
* Unset, the provider shares its parent's modal state.
|
|
25
|
+
*/
|
|
26
|
+
isModalDefaultOpen?: boolean;
|
|
27
|
+
/** The app-wide default agent (`<CopilotKitProvider agentId>`). */
|
|
28
|
+
providerAgentId?: string;
|
|
29
|
+
}
|
|
30
|
+
/** What a chat reads from its configuration. */
|
|
31
|
+
interface ɵChatConfigurationSnapshot {
|
|
32
|
+
agentId: string;
|
|
33
|
+
threadId: string;
|
|
34
|
+
/** `true` when a caller chose the thread (not a minted placeholder). */
|
|
35
|
+
hasExplicitThreadId: boolean;
|
|
36
|
+
isModalOpen: boolean;
|
|
37
|
+
drawerOpen: boolean;
|
|
38
|
+
/** `true` while at least one threads drawer is mounted. */
|
|
39
|
+
drawerRegistered: boolean;
|
|
40
|
+
}
|
|
41
|
+
/** The core part {@link ɵChatConfigurationStore.bindOpenThread} needs. */
|
|
42
|
+
interface ɵOpenThreadRegistry {
|
|
43
|
+
registerOpenThread(params: {
|
|
44
|
+
agentId: string;
|
|
45
|
+
threadId: string;
|
|
46
|
+
}): OpenThreadRegistration;
|
|
47
|
+
}
|
|
48
|
+
type ModalCloser = (open: boolean) => void;
|
|
49
|
+
/**
|
|
50
|
+
* One chat configuration provider's state. A nested provider passes its
|
|
51
|
+
* parent store, and the chain behaves as one:
|
|
52
|
+
*
|
|
53
|
+
* - **Thread**: a controlled `threadId` wins; then a picked or new thread;
|
|
54
|
+
* then the parent's thread; then a seed `threadId`; then a UUID minted once
|
|
55
|
+
* per store. Picking a thread or starting a new one is owned by the top-most
|
|
56
|
+
* store; nested stores pass the call up, after their own controlled check.
|
|
57
|
+
* - **Agent**: own `agentId`, then the parent's, then the provider default,
|
|
58
|
+
* then `DEFAULT_AGENT_ID`.
|
|
59
|
+
* - **Modal**: own state when `isModalDefaultOpen` is set (changes also go to
|
|
60
|
+
* the parent, and parent changes after creation come down); otherwise the
|
|
61
|
+
* parent's state; a store without either starts open.
|
|
62
|
+
* - **Drawer**: owned by the top-most store, so one drawer serves the chain.
|
|
63
|
+
* On a mobile-width viewport, opening the drawer closes the modal that is
|
|
64
|
+
* on screen and opening the modal closes the drawer.
|
|
65
|
+
*
|
|
66
|
+
* The store links to its parent (and registers its modal closer there) while
|
|
67
|
+
* it has subscribers, so a discarded store holds nothing.
|
|
68
|
+
*/
|
|
69
|
+
declare class ɵChatConfigurationStore {
|
|
70
|
+
#private;
|
|
71
|
+
constructor(options: ɵChatConfigurationOptions, parent?: ɵChatConfigurationStore | null);
|
|
72
|
+
/**
|
|
73
|
+
* The current values, read through the parent and the latest options, so a
|
|
74
|
+
* render always sees them. Same object until one of them changes.
|
|
75
|
+
*/
|
|
76
|
+
getSnapshot: () => ɵChatConfigurationSnapshot;
|
|
77
|
+
/** Listen for changes. Returns unsubscribe. */
|
|
78
|
+
subscribe: (listener: () => void) => () => void;
|
|
79
|
+
/**
|
|
80
|
+
* Take the provider's current props without notifying: for a render phase,
|
|
81
|
+
* where `getSnapshot()` already reflects them. Call {@link update} after
|
|
82
|
+
* the commit so subscribers hear about the change.
|
|
83
|
+
*/
|
|
84
|
+
ɵsetOptions(options: ɵChatConfigurationOptions): void;
|
|
85
|
+
/** Give the provider's current props and notify subscribers. */
|
|
86
|
+
update(options: ɵChatConfigurationOptions): void;
|
|
87
|
+
/**
|
|
88
|
+
* Show `threadId`. `explicit` (default `true`) marks it as a caller
|
|
89
|
+
* choice; `false` keeps the welcome screen for a fresh thread. Ignored with
|
|
90
|
+
* a warning when the thread is controlled.
|
|
91
|
+
*/
|
|
92
|
+
setActiveThreadId: (threadId: string, options?: {
|
|
93
|
+
explicit?: boolean;
|
|
94
|
+
}) => void;
|
|
95
|
+
/**
|
|
96
|
+
* Show a fresh client-side thread (new UUID, not explicit). Ignored with a
|
|
97
|
+
* warning when the thread is controlled.
|
|
98
|
+
*/
|
|
99
|
+
startNewThread: () => void;
|
|
100
|
+
/** Open or close the chat modal (closing the drawer on mobile). */
|
|
101
|
+
setModalOpen: (open: boolean) => void;
|
|
102
|
+
/** Open or close the drawer (closing the on-screen modal on mobile). */
|
|
103
|
+
setDrawerOpen: (open: boolean) => void;
|
|
104
|
+
/**
|
|
105
|
+
* Announce a mounted threads drawer; `drawerRegistered` stays `true` until
|
|
106
|
+
* every returned cleanup has run. Each cleanup runs once.
|
|
107
|
+
*/
|
|
108
|
+
registerDrawer: () => (() => void);
|
|
109
|
+
/**
|
|
110
|
+
* Register the setter of the modal that is actually rendered, so the
|
|
111
|
+
* drawer's mobile exclusion closes it. The latest registration wins.
|
|
112
|
+
*/
|
|
113
|
+
registerModalCloser: (closeModal: ModalCloser) => (() => void);
|
|
114
|
+
/**
|
|
115
|
+
* Tell core which thread this chat shows, so captured interactions link to
|
|
116
|
+
* it. Re-registers when the agent changes. Returns the cleanup.
|
|
117
|
+
*/
|
|
118
|
+
bindOpenThread(registry: ɵOpenThreadRegistry): () => void;
|
|
119
|
+
dispose(): void;
|
|
120
|
+
}
|
|
121
|
+
//#endregion
|
|
122
|
+
export { ɵChatConfigurationOptions, ɵChatConfigurationSnapshot, ɵChatConfigurationStore, ɵOpenThreadRegistry };
|
|
123
|
+
//# sourceMappingURL=chat-configuration.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chat-configuration.d.cts","names":[],"sources":["../src/chat/chat-configuration.ts"],"mappings":";;;;;AAcA;;;;;;;UAAiB,yBAAA;EACf,OAAA;EAce;;AAIjB;;;EAZE,QAAA;EACA,mBAAA;EAaA;;;;EARA,kBAAA;EAcgB;EAZhB,eAAA;AAAA;;UAIe,0BAAA;EACf,OAAA;EACA,QAAA;EAYE;EAVF,mBAAA;EACA,WAAA;EACA,UAAA;EAU0B;EAR1B,gBAAA;AAAA;;UAIe,mBAAA;EACf,kBAAA,CAAmB,MAAA;IACjB,OAAA;IACA,QAAA;EAAA,IACE,sBAAA;AAAA;AAAA,KAUD,WAAA,IAAe,IAAA;;;;;;;;;;;;;;;;;;;;;cAoCP,uBAAA;EAAA;cAgBT,OAAA,EAAS,yBAAA,EACT,MAAA,GAAQ,uBAAA;EAwCH;;;;EA1BP,WAAA,QAAW,0BAAA;EA0DX;EAnDA,SAAA,GAAa,QAAA;EAiEG;;;;;EAnDhB,WAAA,CAAY,OAAA,EAAS,yBAAA;EA2FE;EAtFvB,MAAA,CAAO,OAAA,EAAS,yBAAA;EAmGS;;;;;EApFzB,iBAAA,GAAqB,QAAA,UAAkB,OAAA;IAAY,QAAA;EAAA;;;;;EAiBnD,cAAA;;EAcA,YAAA,GAAgB,IAAA;;EAMhB,aAAA,GAAiB,IAAA;;;;;EAiBjB,cAAA;;;;;EAiBA,mBAAA,GAAuB,UAAA,EAAY,WAAA;;;;;EAanC,cAAA,CAAe,QAAA,EAAU,mBAAA;EAsBzB,OAAA,CAAA;AAAA"}
|