@aegishex/chatbot 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +87 -2
- package/dist/aegishex-chatbot.global.js +138 -0
- package/dist/aegishex-chatbot.global.js.map +7 -0
- package/dist/client.d.ts +52 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +821 -0
- package/dist/index.js.map +7 -0
- package/dist/sse.d.ts +15 -0
- package/dist/styles.d.ts +2 -0
- package/dist/types.d.ts +43 -0
- package/dist/widget.d.ts +35 -0
- package/package.json +40 -4
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/sse.ts", "../src/types.ts", "../src/client.ts", "../src/styles.ts", "../src/widget.ts"],
|
|
4
|
+
"sourcesContent": ["/** Minimal Server-Sent Events parser for streams read with `fetch` (which, unlike EventSource, can send headers). */\n\nexport interface SseEvent {\n event: string;\n data: string;\n id?: string;\n retry?: number;\n}\n\n/**\n * Feed text chunks in and get complete events out. Handles CRLF/LF line endings, multi-line `data:`,\n * comment lines (keep-alives) and events split across chunks.\n */\nexport class SseParser {\n private buffer = \"\";\n\n push(chunk: string): SseEvent[] {\n this.buffer += chunk.replace(/\\r\\n?/g, \"\\n\");\n const events: SseEvent[] = [];\n let boundary = this.buffer.indexOf(\"\\n\\n\");\n while (boundary !== -1) {\n const block = this.buffer.slice(0, boundary);\n this.buffer = this.buffer.slice(boundary + 2);\n const parsed = parseBlock(block);\n if (parsed) events.push(parsed);\n boundary = this.buffer.indexOf(\"\\n\\n\");\n }\n return events;\n }\n}\n\nfunction parseBlock(block: string): SseEvent | null {\n let event = \"message\";\n const data: string[] = [];\n let id: string | undefined;\n let retry: number | undefined;\n for (const line of block.split(\"\\n\")) {\n if (!line || line.startsWith(\":\")) continue;\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n const value = colon === -1 ? \"\" : line.slice(colon + 1).replace(/^ /, \"\");\n if (field === \"event\") event = value;\n else if (field === \"data\") data.push(value);\n else if (field === \"id\") id = value;\n else if (field === \"retry\" && /^\\d+$/.test(value)) retry = Number(value);\n }\n if (!data.length && retry === undefined) return null;\n return { event, data: data.join(\"\\n\"), id, retry };\n}\n", "/** Contracts of the AegisHex public client API (`/api/client/v1`). */\n\nexport type RunPhase = \"working\" | \"awaiting_approval\" | \"completed\" | \"failed\" | \"denied\" | \"cancelled\";\n\nexport const FINAL_PHASES: ReadonlySet<RunPhase> = new Set([\"completed\", \"failed\", \"denied\", \"cancelled\"]);\n\nexport interface WidgetConfig {\n assistantName: string;\n greeting: string;\n accentColor: string;\n organization: string;\n minMessageLength: number;\n maxMessageLength: number;\n}\n\nexport interface RunStep {\n sequence: number;\n label: string;\n status: \"done\" | \"running\" | \"problem\";\n}\n\nexport interface RunApproval {\n action: string;\n amount: string;\n status: \"pending\" | \"approved\" | \"denied\";\n}\n\nexport interface RunFact {\n label: string;\n value: string;\n}\n\nexport interface RunView {\n runId: string;\n reference: string;\n phase: RunPhase;\n message: string;\n steps: RunStep[];\n approval: RunApproval | null;\n facts: RunFact[];\n answer: string;\n supportUrl?: string | null;\n sourcesCollapsible?: boolean;\n createdAt: string;\n completedAt: string | null;\n}\n\nexport interface StartedRun {\n runToken: string;\n run: RunView;\n}\n", "import { SseParser } from \"./sse\";\nimport { FINAL_PHASES, type RunView, type StartedRun, type WidgetConfig } from \"./types\";\n\nexport interface ClientOptions {\n /** Base URL of the AegisHex API, e.g. `https://api.aegishex.example`. */\n apiBaseUrl: string;\n /** Publishable widget key (`ahx_pk_\u2026`), created on the Chatbot page of the AegisHex dashboard. */\n publishableKey: string;\n /** Custom fetch (tests, server-side rendering). Defaults to the global fetch. */\n fetch?: typeof fetch;\n}\n\nexport interface FollowOptions {\n /** Called with the full run view every time it changes. */\n onUpdate: (view: RunView) => void;\n /** Stops following (the promise rejects with an AbortError). */\n signal?: AbortSignal;\n}\n\n/** An error answer from the API, with its message already written for people. */\nexport class ChatbotError extends Error {\n readonly status: number;\n readonly retryAfterS: number | null;\n\n constructor(message: string, status: number, retryAfterS: number | null = null) {\n super(message);\n this.name = \"ChatbotError\";\n this.status = status;\n this.retryAfterS = retryAfterS;\n }\n\n /** True when retrying the same request can succeed (network trouble, rate limits, server errors). */\n get retryable(): boolean {\n return this.status === 0 || this.status === 429 || this.status >= 500;\n }\n}\n\nconst STREAM_FAILURES_BEFORE_POLLING = 3;\nconst POLL_INTERVAL_MS = 2000;\nconst MAX_BACKOFF_MS = 15000;\n\nconst VISITOR_STORAGE_KEY = \"aegishex:visitor-id\";\n\nfunction newIdempotencyKey(): string {\n const random = globalThis.crypto?.randomUUID?.();\n return random ?? `msg-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;\n}\n\nfunction getOrCreateVisitorId(): string {\n try {\n const existing = globalThis.sessionStorage?.getItem(VISITOR_STORAGE_KEY);\n if (existing && existing.length >= 16) return existing;\n const generated = newIdempotencyKey();\n globalThis.sessionStorage?.setItem(VISITOR_STORAGE_KEY, generated);\n return generated;\n } catch {\n return newIdempotencyKey();\n }\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(abortError());\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(abortError());\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\nfunction abortError(): Error {\n const error = new Error(\"Stopped following the run.\");\n error.name = \"AbortError\";\n return error;\n}\n\n/** Typed client for the AegisHex public client API. Works in browsers and in Node 18+. */\nexport class AegisHexClient {\n private readonly base: string;\n private readonly key: string;\n private readonly visitorId: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(options: ClientOptions) {\n if (!options.publishableKey?.startsWith(\"ahx_pk_\")) {\n throw new ChatbotError(\"A publishable widget key (ahx_pk_\u2026) is required.\", 0);\n }\n this.base = options.apiBaseUrl.replace(/\\/+$/, \"\");\n this.key = options.publishableKey;\n this.visitorId = getOrCreateVisitorId();\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (!fetchImpl) throw new ChatbotError(\"fetch is not available in this environment.\", 0);\n this.fetchImpl = fetchImpl.bind(globalThis);\n }\n\n /** Assistant name, greeting, accent colour and message limits configured for this key. */\n getConfig(): Promise<WidgetConfig> {\n return this.json<WidgetConfig>(\"GET\", \"/api/client/v1/config\");\n }\n\n /** Send a message. It starts one agent run; keep `runToken` to follow it. */\n sendMessage(message: string, options: { idempotencyKey?: string } = {}): Promise<StartedRun> {\n return this.json<StartedRun>(\"POST\", \"/api/client/v1/runs\", { message },\n { \"Idempotency-Key\": options.idempotencyKey ?? newIdempotencyKey(), \"X-Visitor-Id\": this.visitorId });\n }\n\n /** Current view of a run (the polling fallback). */\n getRun(runId: string, runToken: string): Promise<RunView> {\n return this.json<RunView>(\"GET\", `/api/client/v1/runs/${encodeURIComponent(runId)}`, undefined,\n { \"X-Run-Token\": runToken });\n }\n\n /** Stop an unfinished run; a pending approval is withdrawn and nothing is executed. */\n cancelRun(runId: string, runToken: string): Promise<RunView> {\n return this.json<RunView>(\"POST\", `/api/client/v1/runs/${encodeURIComponent(runId)}/cancel`, undefined,\n { \"X-Run-Token\": runToken, \"Idempotency-Key\": newIdempotencyKey() });\n }\n\n /**\n * Follow a run until it finishes and resolve with the final view.\n *\n * Uses the Server-Sent Events stream and reconnects after network drops (the first event after a reconnect\n * is always the current state, so nothing is missed). After repeated stream failures it falls back to polling.\n */\n async followRun(runId: string, runToken: string, options: FollowOptions): Promise<RunView> {\n const { onUpdate, signal } = options;\n let failures = 0;\n let retryMs = 2000;\n while (failures < STREAM_FAILURES_BEFORE_POLLING) {\n if (signal?.aborted) throw abortError();\n try {\n const outcome = await this.readStream(runId, runToken, onUpdate, signal, (ms) => { retryMs = ms; });\n if (outcome) return outcome;\n failures = 0; // the server closed a healthy stream (time limit): reconnect right away\n await sleep(250, signal);\n } catch (error) {\n if ((error as Error).name === \"AbortError\") throw error;\n if (error instanceof ChatbotError && !error.retryable) throw error;\n failures += 1;\n await sleep(Math.min(retryMs * 2 ** (failures - 1), MAX_BACKOFF_MS), signal);\n }\n }\n return this.pollRun(runId, runToken, onUpdate, signal);\n }\n\n private async readStream(runId: string, runToken: string, onUpdate: (view: RunView) => void,\n signal: AbortSignal | undefined, onRetry: (ms: number) => void): Promise<RunView | null> {\n const response = await this.request(\"GET\", `/api/client/v1/runs/${encodeURIComponent(runId)}/events`, undefined,\n { \"X-Run-Token\": runToken, Accept: \"text/event-stream\" }, signal);\n if (!response.body) throw new ChatbotError(\"Streaming is not supported here.\", 0);\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n const parser = new SseParser();\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) return null;\n for (const event of parser.push(decoder.decode(value, { stream: true }))) {\n if (event.retry !== undefined) onRetry(event.retry);\n if (event.event === \"snapshot\" || event.event === \"end\") {\n const view = JSON.parse(event.data) as RunView;\n onUpdate(view);\n if (event.event === \"end\" || FINAL_PHASES.has(view.phase)) return view;\n } else if (event.event === \"gone\") {\n throw new ChatbotError(\"This conversation is no longer available.\", 404);\n }\n }\n }\n } finally {\n reader.cancel().catch(() => undefined);\n }\n }\n\n private async pollRun(runId: string, runToken: string, onUpdate: (view: RunView) => void,\n signal: AbortSignal | undefined): Promise<RunView> {\n let previous = \"\";\n for (;;) {\n try {\n const view = await this.getRun(runId, runToken);\n const serialized = JSON.stringify(view);\n if (serialized !== previous) {\n previous = serialized;\n onUpdate(view);\n }\n if (FINAL_PHASES.has(view.phase)) return view;\n } catch (error) {\n if (error instanceof ChatbotError && !error.retryable) throw error;\n }\n await sleep(POLL_INTERVAL_MS, signal);\n }\n }\n\n private async json<T>(method: string, path: string, body?: unknown, headers: Record<string, string> = {}): Promise<T> {\n const response = await this.request(method, path, body, headers);\n return (await response.json()) as T;\n }\n\n private async request(method: string, path: string, body: unknown, headers: Record<string, string>,\n signal?: AbortSignal): Promise<Response> {\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.base}${path}`, {\n method,\n headers: { \"X-AegisHex-Key\": this.key, ...(body === undefined ? {} : { \"Content-Type\": \"application/json\" }),\n ...headers },\n body: body === undefined ? undefined : JSON.stringify(body),\n credentials: \"omit\",\n signal,\n });\n } catch (error) {\n if ((error as Error).name === \"AbortError\") throw error;\n throw new ChatbotError(\"Can't reach the assistant right now. Check your connection and try again.\", 0);\n }\n if (!response.ok) throw await toError(response);\n return response;\n }\n}\n\nasync function toError(response: Response): Promise<ChatbotError> {\n const retryHeader = response.headers.get(\"Retry-After\");\n const retryAfter = retryHeader && /^\\d+$/.test(retryHeader) ? Number(retryHeader) : null;\n let message = \"Something went wrong. Please try again.\";\n try {\n const body = (await response.json()) as { message?: unknown; details?: { reason?: unknown }[] };\n if (typeof body.message === \"string\" && body.message) message = body.message;\n const reason = body.details?.[0]?.reason;\n if (response.status === 422 && typeof reason === \"string\") message = reason.replace(/^Value error, /, \"\");\n } catch {\n // keep the generic message\n }\n return new ChatbotError(message, response.status, retryAfter);\n}\n", "/** Widget styles, scoped by the Shadow DOM so the host page and the widget never affect each other. */\n\nconst LIGHT = `\n --ah-bg: #ffffff; --ah-surface: #f6f8fc; --ah-surface-2: #eef1f7; --ah-text: #17233b; --ah-muted: #596a80;\n --ah-border: #e3e8f0; --ah-shadow: 0 18px 48px rgba(23, 35, 59, .18), 0 2px 8px rgba(23, 35, 59, .08);\n --ah-good: #0b7f66; --ah-good-bg: #e6f6f1; --ah-warn: #8a5a00; --ah-warn-bg: #fff6e0; --ah-warn-border: #f2d48a;\n --ah-bad: #b42335; --ah-bad-bg: #fdecef;`;\nconst DARK = `\n --ah-bg: #111a2c; --ah-surface: #172238; --ah-surface-2: #1e2b45; --ah-text: #e6ebf5; --ah-muted: #a3b0c4;\n --ah-border: #2a3954; --ah-shadow: 0 18px 48px rgba(0, 0, 0, .5), 0 2px 8px rgba(0, 0, 0, .35);\n --ah-good: #6fdcbc; --ah-good-bg: #12352f; --ah-warn: #f5c868; --ah-warn-bg: #3a2f14; --ah-warn-border: #6b5520;\n --ah-bad: #ff9aa8; --ah-bad-bg: #3d1a24;`;\n\nexport const STYLES: string = `\n:host { all: initial; ${LIGHT} --ah-accent: #5364dd; --ah-on-accent: #ffffff; --ah-z: 2147483000;\n font-family: \"Segoe UI\", -apple-system, BlinkMacSystemFont, Roboto, Helvetica, Arial, sans-serif; }\n:host([data-theme=\"dark\"]) { ${DARK} }\n@media (prefers-color-scheme: dark) { :host([data-theme=\"auto\"]) { ${DARK} } }\n*, *::before, *::after { box-sizing: border-box; }\nbutton, textarea { font: inherit; color: inherit; }\n.root { position: fixed; bottom: 20px; right: 20px; z-index: var(--ah-z); display: flex; flex-direction: column;\n align-items: flex-end; gap: 14px; }\n.root.left { right: auto; left: 20px; align-items: flex-start; }\n.root.inline { position: static; display: block; height: 100%; }\n.launcher { width: 58px; height: 58px; border-radius: 50%; border: 0; cursor: pointer; background: var(--ah-accent);\n color: var(--ah-on-accent); display: grid; place-items: center; box-shadow: var(--ah-shadow);\n transition: transform .15s ease, box-shadow .15s ease; }\n.launcher:hover { transform: translateY(-2px); }\n.launcher:focus-visible, button:focus-visible { outline: 3px solid color-mix(in srgb, var(--ah-accent) 45%, transparent); outline-offset: 2px; }\n.launcher svg { width: 26px; height: 26px; }\n.panel { width: min(390px, calc(100vw - 32px)); height: min(620px, calc(100vh - 110px)); background: var(--ah-bg);\n color: var(--ah-text); border: 1px solid var(--ah-border); border-radius: 18px; box-shadow: var(--ah-shadow);\n display: flex; flex-direction: column; overflow: hidden; transform-origin: bottom right;\n animation: ah-pop .18s ease-out; }\n.root.left .panel { transform-origin: bottom left; }\n.root.inline .panel { width: 100%; height: 100%; min-height: 420px; box-shadow: none; animation: none; }\n.panel[hidden] { display: none; }\n@keyframes ah-pop { from { opacity: 0; transform: translateY(8px) scale(.98); } to { opacity: 1; transform: none; } }\n.header { display: flex; align-items: center; gap: 11px; padding: 14px 14px 14px 16px; border-bottom: 1px solid var(--ah-border);\n background: linear-gradient(180deg, color-mix(in srgb, var(--ah-accent) 9%, var(--ah-bg)), var(--ah-bg)); }\n.mark { width: 34px; height: 34px; border-radius: 10px; display: grid; place-items: center; flex: none;\n background: var(--ah-accent); color: var(--ah-on-accent); }\n.mark svg { width: 20px; height: 20px; }\n.titles { flex: 1; min-width: 0; }\n.title { font-size: 15px; font-weight: 700; line-height: 1.25; margin: 0; }\n.subtitle { font-size: 12px; color: var(--ah-muted); display: flex; align-items: center; gap: 6px; margin-top: 2px; }\n.online { width: 7px; height: 7px; border-radius: 50%; background: var(--ah-good); }\n.icon-btn { width: 34px; height: 34px; border-radius: 9px; border: 0; background: transparent; cursor: pointer;\n color: var(--ah-muted); display: grid; place-items: center; }\n.icon-btn:hover { background: var(--ah-surface-2); color: var(--ah-text); }\n.icon-btn svg { width: 18px; height: 18px; }\n.log { flex: 1; overflow-y: auto; padding: 16px 14px 8px; display: flex; flex-direction: column; gap: 12px;\n scroll-behavior: smooth; overscroll-behavior: contain; }\n.row { display: flex; }\n.row.user { justify-content: flex-end; }\n.bubble { max-width: 86%; padding: 10px 13px; border-radius: 14px; font-size: 14px; line-height: 1.5;\n white-space: pre-wrap; overflow-wrap: anywhere; }\n.row.user .bubble { background: var(--ah-accent); color: var(--ah-on-accent); border-bottom-right-radius: 5px; }\n.row.bot .bubble { background: var(--ah-surface); border: 1px solid var(--ah-border); border-bottom-left-radius: 5px; }\n.card { width: 100%; max-width: 92%; background: var(--ah-surface); border: 1px solid var(--ah-border);\n border-radius: 14px; border-bottom-left-radius: 5px; padding: 12px 13px; font-size: 14px; line-height: 1.5; }\n.answer { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }\n.support-link { align-self: flex-start; color: inherit; font-weight: 600; text-decoration: underline; }\n.status { display: flex; align-items: center; gap: 8px; font-size: 12px; font-weight: 600; color: var(--ah-muted);\n margin-bottom: 8px; letter-spacing: .01em; }\n.badge { display: inline-flex; align-items: center; gap: 5px; padding: 2px 8px; border-radius: 999px; font-size: 11.5px;\n font-weight: 600; }\n.badge svg { width: 12px; height: 12px; }\n.badge.good { background: var(--ah-good-bg); color: var(--ah-good); }\n.badge.warn { background: var(--ah-warn-bg); color: var(--ah-warn); }\n.badge.bad { background: var(--ah-bad-bg); color: var(--ah-bad); }\n.badge.busy { background: var(--ah-surface-2); color: var(--ah-muted); }\n.steps { list-style: none; margin: 10px 0 0; padding: 10px 0 0; border-top: 1px dashed var(--ah-border);\n display: flex; flex-direction: column; gap: 6px; }\n.steps li { display: flex; align-items: center; gap: 8px; font-size: 12.5px; color: var(--ah-muted); }\n.steps li.done { color: var(--ah-text); }\n.steps .dot { width: 16px; height: 16px; flex: none; display: grid; place-items: center; border-radius: 50%; }\n.steps li.done .dot { background: var(--ah-good-bg); color: var(--ah-good); }\n.steps li.problem .dot { background: var(--ah-bad-bg); color: var(--ah-bad); }\n.steps .dot svg { width: 10px; height: 10px; }\n.spinner { width: 12px; height: 12px; border: 2px solid var(--ah-border); border-top-color: var(--ah-accent);\n border-radius: 50%; animation: ah-spin .8s linear infinite; }\n@keyframes ah-spin { to { transform: rotate(360deg); } }\n.typing { display: inline-flex; gap: 4px; padding: 2px 0; }\n.typing span { width: 6px; height: 6px; border-radius: 50%; background: var(--ah-muted); opacity: .5;\n animation: ah-blink 1.2s infinite ease-in-out; }\n.typing span:nth-child(2) { animation-delay: .15s; } .typing span:nth-child(3) { animation-delay: .3s; }\n@keyframes ah-blink { 0%, 80%, 100% { opacity: .25; transform: translateY(0); } 40% { opacity: 1; transform: translateY(-2px); } }\n.approval { margin-top: 10px; padding: 11px 12px; border-radius: 11px; background: var(--ah-warn-bg);\n border: 1px solid var(--ah-warn-border); color: var(--ah-text); }\n.approval strong { display: block; font-size: 13px; margin-bottom: 3px; text-transform: capitalize; }\n.approval p { margin: 0; font-size: 12.5px; color: var(--ah-muted); }\n.facts { margin: 10px 0 0; padding: 0; display: grid; grid-template-columns: fit-content(45%) minmax(0, 1fr);\n gap: 6px 12px; font-size: 13px; }\n.facts dt { color: var(--ah-muted); overflow-wrap: anywhere; }\n.facts dd { margin: 0; font-weight: 600; overflow-wrap: anywhere; }\n.facts .passage { grid-column: 1 / -1; }\n.facts dt.passage:not(:first-child) { margin-top: 6px; }\n.facts dd.passage { white-space: pre-wrap; font-weight: 400; }\n.sources { margin-top: 10px; font-size: 12px; color: var(--ah-muted); }\n.sources summary { cursor: pointer; width: fit-content; }\n.sources dd { color: var(--ah-text); }\n.card-actions { display: flex; justify-content: space-between; align-items: center; margin-top: 10px; gap: 8px; }\n.ref { font-size: 11.5px; color: var(--ah-muted); }\n.link-btn { border: 0; background: none; padding: 0; color: var(--ah-accent); font-size: 12.5px; font-weight: 600; cursor: pointer; }\n.link-btn:hover { text-decoration: underline; }\n.notice { margin: 0 14px 8px; padding: 9px 12px; border-radius: 10px; font-size: 12.5px; line-height: 1.45;\n background: var(--ah-bad-bg); color: var(--ah-bad); }\n.notice[hidden] { display: none; }\n.composer { border-top: 1px solid var(--ah-border); padding: 10px 12px 8px; background: var(--ah-bg); }\n.input-row { display: flex; align-items: flex-end; gap: 8px; background: var(--ah-surface); border: 1px solid var(--ah-border);\n border-radius: 14px; padding: 6px 6px 6px 12px; transition: border-color .15s; }\n.input-row:focus-within { border-color: var(--ah-accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--ah-accent) 22%, transparent); }\ntextarea { flex: 1; border: 0; background: transparent; resize: none; outline: none; box-shadow: none; font-size: 14px; line-height: 1.45;\n max-height: 120px; min-height: 22px; padding: 6px 0; }\ntextarea::placeholder { color: var(--ah-muted); }\n.send { width: 36px; height: 36px; flex: none; border: 0; border-radius: 10px; background: var(--ah-accent);\n color: var(--ah-on-accent); cursor: pointer; display: grid; place-items: center; transition: opacity .15s; }\n.send:disabled { opacity: .45; cursor: not-allowed; }\n.send svg { width: 17px; height: 17px; }\n.quick-action { margin: 0 0 8px; padding: 5px 10px; border: 1px solid var(--ah-border); border-radius: 999px;\n background: var(--ah-surface); color: var(--ah-text); cursor: pointer; font-size: 12px; font-weight: 600; }\n.quick-action:hover { border-color: var(--ah-accent); }\n.foot { display: flex; justify-content: space-between; gap: 8px; margin-top: 6px; font-size: 11px; color: var(--ah-muted); }\n.foot b { font-weight: 700; color: var(--ah-text); }\n.foot b span { color: #0e9f80; }\n.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }\n@media (max-width: 480px) {\n .root:not(.inline) { bottom: 12px; right: 12px; left: 12px; align-items: flex-end; }\n .root:not(.inline) .panel { width: 100%; height: calc(100vh - 96px); }\n}\n@media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation: none !important; transition: none !important; } }\n`;\n", "import { AegisHexClient, ChatbotError, type ClientOptions } from \"./client\";\nimport { STYLES } from \"./styles\";\nimport { FINAL_PHASES, type RunView, type WidgetConfig } from \"./types\";\n\nexport type Theme = \"light\" | \"dark\" | \"auto\";\n\nexport interface ChatbotOptions extends ClientOptions {\n /** Colour scheme; `auto` follows the visitor's system setting. Default `auto`. */\n theme?: Theme;\n /** Corner for the floating launcher. Default `bottom-right`. */\n position?: \"bottom-right\" | \"bottom-left\";\n /** Open the chat panel immediately. */\n open?: boolean;\n /** Override the accent colour configured on the key (hex, e.g. `#5364dd`). */\n accentColor?: string;\n /** Render inside this element (no launcher, always open) instead of floating over the page. */\n target?: HTMLElement;\n /** Keep the conversation across page loads in this tab (sessionStorage). Default true. */\n persist?: boolean;\n /** Optional site-managed action shown in the chat composer. */\n quickAction?: { label: string; onSelect: () => void };\n}\n\nexport interface ChatbotHandle {\n open(): void;\n close(): void;\n toggle(): void;\n /** Send a message as if the visitor typed it. */\n send(text: string): Promise<void>;\n /** Remove the widget and stop following runs. */\n destroy(): void;\n readonly host: HTMLElement;\n}\n\ntype Entry =\n | { kind: \"user\"; id: string; text: string }\n | { kind: \"bot\"; id: string; text: string }\n | { kind: \"run\"; id: string; runId: string; runToken: string; view: RunView };\n\nconst ICONS = {\n chat: '<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.6A8 8 0 1 1 21 12Z\"/></svg>',\n close: '<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.2\" stroke-linecap=\"round\" aria-hidden=\"true\"><path d=\"M18 6 6 18M6 6l12 12\"/></svg>',\n send: '<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"M5 12h14M13 6l6 6-6 6\"/></svg>',\n mark: '<svg viewBox=\"0 0 40 40\" fill=\"none\" aria-hidden=\"true\"><path d=\"M20 3 34.5 11.5v17L20 37 5.5 28.5v-17L20 3Z\" stroke=\"currentColor\" stroke-width=\"3\"/><path d=\"m14.8 20 3.4 3.4 7.2-7.2\" stroke=\"currentColor\" stroke-width=\"3\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>',\n check: '<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"3.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\"><path d=\"m5 12.5 4.5 4.5L19 7.5\"/></svg>',\n alert: '<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"3\" stroke-linecap=\"round\" aria-hidden=\"true\"><path d=\"M12 7v6M12 17h.01\"/></svg>',\n clock: '<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.6\" stroke-linecap=\"round\" aria-hidden=\"true\"><circle cx=\"12\" cy=\"12\" r=\"8.5\"/><path d=\"M12 7.5V12l3 2\"/></svg>',\n} as const;\n\nconst DEFAULT_CONFIG: WidgetConfig = {\n assistantName: \"Assistant\", greeting: \"Hi! How can I help?\", accentColor: \"#5364dd\", organization: \"\",\n minMessageLength: 2, maxMessageLength: 2000,\n};\n\n/** Build an element; text always goes through textContent, so visitor and server text is never parsed as HTML. */\nfunction el<K extends keyof HTMLElementTagNameMap>(tag: K, className?: string, text?: string): HTMLElementTagNameMap[K] {\n const node = document.createElement(tag);\n if (className) node.className = className;\n if (text !== undefined) node.textContent = text;\n return node;\n}\n\nfunction icon(name: keyof typeof ICONS): HTMLSpanElement {\n const span = el(\"span\");\n span.style.display = \"contents\";\n span.innerHTML = ICONS[name]; // static, trusted markup only\n return span;\n}\n\n/** White or near-black text, whichever reads better on the accent colour (WCAG relative luminance). */\nexport function readableOn(hex: string): string {\n const match = /^#([0-9a-f]{6})$/i.exec(hex);\n if (!match) return \"#ffffff\";\n const channels = [0, 2, 4].map((offset) => parseInt(match[1].slice(offset, offset + 2), 16) / 255)\n .map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));\n const luminance = 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2];\n return luminance > 0.36 ? \"#111827\" : \"#ffffff\";\n}\n\nlet counter = 0;\nconst nextId = () => `m${Date.now().toString(36)}${(counter += 1)}`;\n\n/** Mount the AegisHex chat widget on the page and return a handle to control it. */\nexport function mountChatbot(options: ChatbotOptions): ChatbotHandle {\n const client = new AegisHexClient(options);\n const inline = Boolean(options.target);\n const storageKey = `aegishex-chat:${options.publishableKey.slice(-12)}`;\n const persist = options.persist !== false;\n\n const host = el(\"div\");\n host.setAttribute(\"data-aegishex-chatbot\", \"\");\n host.setAttribute(\"data-theme\", options.theme ?? \"auto\");\n const shadow = host.attachShadow({ mode: \"open\" });\n const style = el(\"style\");\n style.textContent = STYLES;\n shadow.append(style);\n\n const root = el(\"div\", `root${options.position === \"bottom-left\" ? \" left\" : \"\"}${inline ? \" inline\" : \"\"}`);\n const panel = el(\"section\", \"panel\");\n panel.setAttribute(\"role\", inline ? \"region\" : \"dialog\");\n panel.setAttribute(\"aria-label\", \"Chat\");\n if (!inline) panel.hidden = true;\n\n // Header\n const header = el(\"header\", \"header\");\n const mark = el(\"div\", \"mark\");\n mark.append(icon(\"mark\"));\n const titles = el(\"div\", \"titles\");\n const title = el(\"h2\", \"title\", DEFAULT_CONFIG.assistantName);\n const subtitle = el(\"div\", \"subtitle\");\n const online = el(\"span\", \"online\");\n const subtitleText = el(\"span\", undefined, \"Verified answers\");\n subtitle.append(online, subtitleText);\n titles.append(title, subtitle);\n header.append(mark, titles);\n let closeButton: HTMLButtonElement | null = null;\n if (!inline) {\n closeButton = el(\"button\", \"icon-btn\");\n closeButton.type = \"button\";\n closeButton.setAttribute(\"aria-label\", \"Close chat\");\n closeButton.append(icon(\"close\"));\n header.append(closeButton);\n }\n\n // Conversation\n const log = el(\"div\", \"log\");\n log.setAttribute(\"role\", \"log\");\n log.setAttribute(\"aria-live\", \"polite\");\n log.setAttribute(\"aria-relevant\", \"additions text\");\n const notice = el(\"p\", \"notice\");\n notice.setAttribute(\"role\", \"alert\");\n notice.hidden = true;\n\n // Composer\n const composer = el(\"form\", \"composer\");\n const inputRow = el(\"div\", \"input-row\");\n const label = el(\"label\", \"sr-only\", \"Message\");\n const input = el(\"textarea\");\n input.rows = 1;\n input.placeholder = \"Type your message\u2026\";\n input.id = \"aegishex-input\";\n label.htmlFor = input.id;\n const send = el(\"button\", \"send\");\n send.type = \"submit\";\n send.setAttribute(\"aria-label\", \"Send message\");\n send.append(icon(\"send\"));\n inputRow.append(label, input, send);\n const foot = el(\"div\", \"foot\");\n const hint = el(\"span\", undefined, \"Enter to send \u00B7 Shift+Enter for a new line\");\n const powered = el(\"span\");\n powered.append(document.createTextNode(\"Powered by \"));\n const brand = el(\"b\", undefined, \"aegis\");\n brand.append(el(\"span\", undefined, \"hex\"));\n powered.append(brand);\n foot.append(hint, powered);\n if (options.quickAction) {\n const { label, onSelect } = options.quickAction;\n const action = el(\"button\", \"quick-action\", label);\n action.type = \"button\";\n action.addEventListener(\"click\", onSelect);\n composer.append(action);\n }\n composer.append(inputRow, foot);\n\n panel.append(header, log, notice, composer);\n\n let launcher: HTMLButtonElement | null = null;\n if (!inline) {\n launcher = el(\"button\", \"launcher\");\n launcher.type = \"button\";\n launcher.setAttribute(\"aria-label\", \"Open chat\");\n launcher.setAttribute(\"aria-expanded\", \"false\");\n launcher.append(icon(\"chat\"));\n }\n root.append(panel);\n if (launcher) root.append(launcher);\n shadow.append(root);\n (options.target ?? document.body).append(host);\n\n // ------------------------------------------------------------------------------------------------------------\n let config = DEFAULT_CONFIG;\n let entries: Entry[] = loadEntries();\n let sending = false;\n const following = new Map<string, AbortController>();\n let destroyed = false;\n\n function applyConfig(next: WidgetConfig) {\n config = next;\n const accent = options.accentColor && /^#[0-9a-f]{6}$/i.test(options.accentColor) ? options.accentColor : next.accentColor;\n host.style.setProperty(\"--ah-accent\", accent);\n host.style.setProperty(\"--ah-on-accent\", readableOn(accent));\n title.textContent = next.assistantName;\n subtitleText.textContent = next.organization ? `${next.organization} \u00B7 verified answers` : \"Verified answers\";\n input.maxLength = next.maxMessageLength;\n render();\n }\n\n function loadEntries(): Entry[] {\n if (!persist) return [];\n try {\n const raw = window.sessionStorage.getItem(storageKey);\n const parsed = raw ? (JSON.parse(raw) as Entry[]) : [];\n return Array.isArray(parsed) ? parsed.slice(-50) : [];\n } catch {\n return [];\n }\n }\n\n function save() {\n if (!persist) return;\n try {\n window.sessionStorage.setItem(storageKey, JSON.stringify(entries.slice(-50)));\n } catch {\n // storage full or blocked: the conversation simply won't survive a reload\n }\n }\n\n function activeRun(): Extract<Entry, { kind: \"run\" }> | undefined {\n return entries.find((entry): entry is Extract<Entry, { kind: \"run\" }> => entry.kind === \"run\"\n && !FINAL_PHASES.has(entry.view.phase));\n }\n\n function showNotice(message: string | null) {\n notice.textContent = message ?? \"\";\n notice.hidden = !message;\n }\n\n function updateComposer() {\n const busy = sending || Boolean(activeRun());\n const length = input.value.trim().length;\n send.disabled = busy || length < config.minMessageLength;\n input.disabled = sending;\n if (busy) hint.textContent = \"Waiting for the current request to finish\u2026\";\n else if (length > 0 && length < config.minMessageLength) hint.textContent = `Add a little more detail (${config.minMessageLength - length} more characters).`;\n else hint.textContent = \"Enter to send \u00B7 Shift+Enter for a new line\";\n }\n\n function renderRun(entry: Extract<Entry, { kind: \"run\" }>): HTMLElement {\n const { view } = entry;\n const card = el(\"div\", \"card\");\n card.setAttribute(\"data-phase\", view.phase);\n const status = el(\"div\", \"status\");\n const badge = (kind: string, text: string, glyph?: keyof typeof ICONS) => {\n const node = el(\"span\", `badge ${kind}`);\n if (glyph) node.append(icon(glyph));\n else if (kind === \"busy\") node.append(el(\"span\", \"spinner\"));\n node.append(document.createTextNode(text));\n return node;\n };\n if (view.phase === \"working\") {\n status.append(badge(\"busy\", view.steps.length ? \"Working on it\" : \"Thinking\u2026\"));\n } else if (view.phase === \"awaiting_approval\") status.append(badge(\"warn\", \"Waiting for approval\", \"clock\"));\n else if (view.phase === \"completed\") status.append(badge(\"good\", view.facts.length ? \"Verified\" : \"Done\", \"check\"));\n else if (view.phase === \"denied\") status.append(badge(\"bad\", \"Declined\", \"alert\"));\n else if (view.phase === \"cancelled\") status.append(badge(\"bad\", \"Stopped\", \"alert\"));\n else status.append(badge(\"bad\", \"Couldn't finish\", \"alert\"));\n card.append(status);\n\n if (view.phase === \"working\" && !view.steps.length) {\n const typing = el(\"span\", \"typing\");\n typing.setAttribute(\"aria-label\", \"Working\");\n typing.append(el(\"span\"), el(\"span\"), el(\"span\"));\n card.append(typing);\n } else {\n card.append(el(\"p\", \"answer\", view.answer));\n if (view.supportUrl && /^https?:\\/\\//i.test(view.supportUrl)) {\n const support = el(\"a\", \"support-link\", \"Contact support\");\n support.href = view.supportUrl;\n support.target = \"_blank\";\n support.rel = \"noopener noreferrer\";\n card.append(support);\n }\n }\n if (view.approval && view.phase === \"awaiting_approval\") {\n const box = el(\"div\", \"approval\");\n box.append(el(\"strong\", undefined, view.approval.amount ? `${view.approval.action} \u00B7 ${view.approval.amount}` : view.approval.action));\n box.append(el(\"p\", undefined, `A person on the ${config.organization || \"site\"} team reviews this before anything happens.`));\n card.append(box);\n }\n if (view.facts.length && (view.phase === \"completed\" || view.phase === \"awaiting_approval\")) {\n const facts = el(\"dl\", \"facts\");\n for (const fact of view.facts) {\n const className = fact.label.startsWith(\"Source: \") ? \"passage\" : undefined;\n facts.append(el(\"dt\", className, fact.label), el(\"dd\", className, fact.value));\n }\n if (view.sourcesCollapsible) {\n const sources = el(\"details\", \"sources\");\n sources.append(el(\"summary\", undefined, view.facts.length === 1 ? \"View source\" : \"View sources\"), facts);\n card.append(sources);\n } else {\n card.append(facts);\n }\n }\n if (view.steps.length && !FINAL_PHASES.has(view.phase)) {\n const steps = el(\"ul\", \"steps\");\n steps.setAttribute(\"aria-label\", \"Progress\");\n for (const step of view.steps) {\n const item = el(\"li\", step.status);\n const dot = el(\"span\", \"dot\");\n if (step.status === \"done\") dot.append(icon(\"check\"));\n else if (step.status === \"problem\") dot.append(icon(\"alert\"));\n else dot.append(el(\"span\", \"spinner\"));\n item.append(dot, document.createTextNode(step.label));\n steps.append(item);\n }\n card.append(steps);\n }\n const actions = el(\"div\", \"card-actions\");\n if (!view.runId.startsWith(\"greet-\")) {\n actions.append(el(\"span\", \"ref\", `Ref ${view.reference}`));\n }\n if (!FINAL_PHASES.has(view.phase)) {\n const stop = el(\"button\", \"link-btn\", \"Stop request\");\n stop.type = \"button\";\n stop.addEventListener(\"click\", () => void stopRun(entry));\n actions.append(stop);\n }\n if (actions.childElementCount > 0) card.append(actions);\n return card;\n }\n\n function render() {\n const nearBottom = log.scrollHeight - log.scrollTop - log.clientHeight < 80;\n log.replaceChildren();\n const greeting = el(\"div\", \"row bot\");\n greeting.append(el(\"div\", \"bubble\", config.greeting));\n log.append(greeting);\n for (const entry of entries) {\n const row = el(\"div\", `row ${entry.kind === \"user\" ? \"user\" : \"bot\"}`);\n if (entry.kind === \"run\") row.append(renderRun(entry));\n else row.append(el(\"div\", \"bubble\", entry.text));\n log.append(row);\n }\n if (nearBottom || sending) log.scrollTop = log.scrollHeight;\n updateComposer();\n }\n\n function follow(entry: Extract<Entry, { kind: \"run\" }>) {\n if (following.has(entry.runId) || FINAL_PHASES.has(entry.view.phase)) return;\n const controller = new AbortController();\n following.set(entry.runId, controller);\n client.followRun(entry.runId, entry.runToken, {\n signal: controller.signal,\n onUpdate: (view) => {\n entry.view = view;\n save();\n render();\n },\n }).catch((error: unknown) => {\n if ((error as Error).name === \"AbortError\" || destroyed) return;\n showNotice(error instanceof ChatbotError ? error.message : \"Lost track of this request. Reload to try again.\");\n }).finally(() => {\n following.delete(entry.runId);\n render();\n });\n }\n\n async function stopRun(entry: Extract<Entry, { kind: \"run\" }>) {\n try {\n entry.view = await client.cancelRun(entry.runId, entry.runToken);\n following.get(entry.runId)?.abort();\n save();\n render();\n } catch (error) {\n showNotice(error instanceof ChatbotError ? error.message : \"Couldn't stop the request.\");\n }\n }\n\n let promptHistory: string[] = [];\n let historyIndex = -1;\n let draft = \"\";\n\n async function sendMessage(text: string) {\n const message = text.trim();\n if (sending || activeRun() || message.length < config.minMessageLength) return;\n if (promptHistory[promptHistory.length - 1] !== message) promptHistory.push(message);\n historyIndex = -1;\n draft = \"\";\n sending = true;\n showNotice(null);\n const userEntry: Entry = { kind: \"user\", id: nextId(), text: message };\n entries.push(userEntry);\n input.value = \"\";\n autosize();\n render();\n try {\n const started = await client.sendMessage(message);\n const runEntry: Extract<Entry, { kind: \"run\" }> = { kind: \"run\", id: nextId(), runId: started.run.runId,\n runToken: started.runToken, view: started.run };\n entries.push(runEntry);\n save();\n follow(runEntry);\n } catch (error) {\n entries = entries.filter((entry) => entry !== userEntry);\n input.value = message;\n autosize();\n const wait = error instanceof ChatbotError && error.retryAfterS ? ` (${error.retryAfterS}s)` : \"\";\n showNotice(error instanceof ChatbotError ? `${error.message}${wait}` : \"Something went wrong. Please try again.\");\n } finally {\n sending = false;\n render();\n input.focus();\n }\n }\n\n function autosize() {\n input.style.height = \"auto\";\n input.style.height = `${Math.min(input.scrollHeight, 120)}px`;\n }\n\n function setOpen(open: boolean) {\n if (inline) return;\n panel.hidden = !open;\n launcher?.setAttribute(\"aria-expanded\", String(open));\n launcher?.setAttribute(\"aria-label\", open ? \"Close chat\" : \"Open chat\");\n if (open) {\n render();\n log.scrollTop = log.scrollHeight;\n input.focus();\n } else {\n launcher?.focus();\n }\n }\n\n composer.addEventListener(\"submit\", (event) => {\n event.preventDefault();\n void sendMessage(input.value);\n });\n input.addEventListener(\"keydown\", (event) => {\n if (event.key === \"Enter\" && !event.shiftKey && !event.isComposing) {\n event.preventDefault();\n void sendMessage(input.value);\n return;\n }\n if (event.key === \"ArrowUp\" && !event.shiftKey && !event.isComposing && promptHistory.length > 0) {\n const pos = input.selectionStart ?? 0;\n if (!input.value.slice(0, pos).includes(\"\\n\")) {\n event.preventDefault();\n if (historyIndex === -1) {\n draft = input.value;\n historyIndex = promptHistory.length - 1;\n } else if (historyIndex > 0) {\n historyIndex -= 1;\n }\n input.value = promptHistory[historyIndex] ?? \"\";\n autosize();\n updateComposer();\n input.setSelectionRange(input.value.length, input.value.length);\n }\n return;\n }\n if (event.key === \"ArrowDown\" && !event.shiftKey && !event.isComposing && historyIndex !== -1) {\n const pos = input.selectionEnd ?? input.value.length;\n if (!input.value.slice(pos).includes(\"\\n\")) {\n event.preventDefault();\n if (historyIndex < promptHistory.length - 1) {\n historyIndex += 1;\n input.value = promptHistory[historyIndex] ?? \"\";\n } else {\n historyIndex = -1;\n input.value = draft;\n }\n autosize();\n updateComposer();\n input.setSelectionRange(input.value.length, input.value.length);\n }\n }\n });\n input.addEventListener(\"input\", () => {\n historyIndex = -1;\n autosize();\n updateComposer();\n });\n launcher?.addEventListener(\"click\", () => setOpen(panel.hidden));\n closeButton?.addEventListener(\"click\", () => setOpen(false));\n panel.addEventListener(\"keydown\", (event) => {\n if (event.key === \"Escape\" && !inline) setOpen(false);\n });\n\n render();\n client.getConfig().then(applyConfig).catch((error: unknown) => {\n showNotice(error instanceof ChatbotError ? error.message : \"The assistant is unavailable right now.\");\n });\n for (const entry of entries) if (entry.kind === \"run\") follow(entry);\n if (options.open) setOpen(true);\n\n return {\n host,\n open: () => setOpen(true),\n close: () => setOpen(false),\n toggle: () => setOpen(panel.hidden),\n send: (text: string) => sendMessage(text),\n destroy: () => {\n destroyed = true;\n for (const controller of following.values()) controller.abort();\n following.clear();\n host.remove();\n },\n };\n}\n"],
|
|
5
|
+
"mappings": ";AAaO,IAAM,YAAN,MAAgB;AAAA,EAAhB;AACL,SAAQ,SAAS;AAAA;AAAA,EAEjB,KAAK,OAA2B;AAC9B,SAAK,UAAU,MAAM,QAAQ,UAAU,IAAI;AAC3C,UAAM,SAAqB,CAAC;AAC5B,QAAI,WAAW,KAAK,OAAO,QAAQ,MAAM;AACzC,WAAO,aAAa,IAAI;AACtB,YAAM,QAAQ,KAAK,OAAO,MAAM,GAAG,QAAQ;AAC3C,WAAK,SAAS,KAAK,OAAO,MAAM,WAAW,CAAC;AAC5C,YAAM,SAAS,WAAW,KAAK;AAC/B,UAAI,OAAQ,QAAO,KAAK,MAAM;AAC9B,iBAAW,KAAK,OAAO,QAAQ,MAAM;AAAA,IACvC;AACA,WAAO;AAAA,EACT;AACF;AAEA,SAAS,WAAW,OAAgC;AAClD,MAAI,QAAQ;AACZ,QAAM,OAAiB,CAAC;AACxB,MAAI;AACJ,MAAI;AACJ,aAAW,QAAQ,MAAM,MAAM,IAAI,GAAG;AACpC,QAAI,CAAC,QAAQ,KAAK,WAAW,GAAG,EAAG;AACnC,UAAM,QAAQ,KAAK,QAAQ,GAAG;AAC9B,UAAM,QAAQ,UAAU,KAAK,OAAO,KAAK,MAAM,GAAG,KAAK;AACvD,UAAM,QAAQ,UAAU,KAAK,KAAK,KAAK,MAAM,QAAQ,CAAC,EAAE,QAAQ,MAAM,EAAE;AACxE,QAAI,UAAU,QAAS,SAAQ;AAAA,aACtB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ACT,mBAAe;AAAA,EACjB,CAAC;AACD,YAAU,iBAAiB,SAAS,MAAM,QAAQ,MAAM,MAAM,CAAC;AAC/D,eAAa,iBAAiB,SAAS,MAAM,QAAQ,KAAK,CAAC;AAC3D,QAAM,iBAAiB,WAAW,CAAC,UAAU;AAC3C,QAAI,MAAM,QAAQ,YAAY,CAAC,OAAQ,SAAQ,KAAK;AAAA,EACtD,CAAC;AAED,SAAO;AACP,SAAO,UAAU,EAAE,KAAK,WAAW,EAAE,MAAM,CAAC,UAAmB;AAC7D,eAAW,iBAAiB,eAAe,MAAM,UAAU,yCAAyC;AAAA,EACtG,CAAC;AACD,aAAW,SAAS,QAAS,KAAI,MAAM,SAAS,MAAO,QAAO,KAAK;AACnE,MAAI,QAAQ,KAAM,SAAQ,IAAI;AAE9B,SAAO;AAAA,IACL;AAAA,IACA,MAAM,MAAM,QAAQ,IAAI;AAAA,IACxB,OAAO,MAAM,QAAQ,KAAK;AAAA,IAC1B,QAAQ,MAAM,QAAQ,MAAM,MAAM;AAAA,IAClC,MAAM,CAAC,SAAiB,YAAY,IAAI;AAAA,IACxC,SAAS,MAAM;AACb,kBAAY;AACZ,iBAAW,cAAc,UAAU,OAAO,EAAG,YAAW,MAAM;AAC9D,gBAAU,MAAM;AAChB,WAAK,OAAO;AAAA,IACd;AAAA,EACF;AACF;",
|
|
6
|
+
"names": ["label"]
|
|
7
|
+
}
|
package/dist/sse.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Minimal Server-Sent Events parser for streams read with `fetch` (which, unlike EventSource, can send headers). */
|
|
2
|
+
export interface SseEvent {
|
|
3
|
+
event: string;
|
|
4
|
+
data: string;
|
|
5
|
+
id?: string;
|
|
6
|
+
retry?: number;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Feed text chunks in and get complete events out. Handles CRLF/LF line endings, multi-line `data:`,
|
|
10
|
+
* comment lines (keep-alives) and events split across chunks.
|
|
11
|
+
*/
|
|
12
|
+
export declare class SseParser {
|
|
13
|
+
private buffer;
|
|
14
|
+
push(chunk: string): SseEvent[];
|
|
15
|
+
}
|
package/dist/styles.d.ts
ADDED
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** Contracts of the AegisHex public client API (`/api/client/v1`). */
|
|
2
|
+
export type RunPhase = "working" | "awaiting_approval" | "completed" | "failed" | "denied" | "cancelled";
|
|
3
|
+
export declare const FINAL_PHASES: ReadonlySet<RunPhase>;
|
|
4
|
+
export interface WidgetConfig {
|
|
5
|
+
assistantName: string;
|
|
6
|
+
greeting: string;
|
|
7
|
+
accentColor: string;
|
|
8
|
+
organization: string;
|
|
9
|
+
minMessageLength: number;
|
|
10
|
+
maxMessageLength: number;
|
|
11
|
+
}
|
|
12
|
+
export interface RunStep {
|
|
13
|
+
sequence: number;
|
|
14
|
+
label: string;
|
|
15
|
+
status: "done" | "running" | "problem";
|
|
16
|
+
}
|
|
17
|
+
export interface RunApproval {
|
|
18
|
+
action: string;
|
|
19
|
+
amount: string;
|
|
20
|
+
status: "pending" | "approved" | "denied";
|
|
21
|
+
}
|
|
22
|
+
export interface RunFact {
|
|
23
|
+
label: string;
|
|
24
|
+
value: string;
|
|
25
|
+
}
|
|
26
|
+
export interface RunView {
|
|
27
|
+
runId: string;
|
|
28
|
+
reference: string;
|
|
29
|
+
phase: RunPhase;
|
|
30
|
+
message: string;
|
|
31
|
+
steps: RunStep[];
|
|
32
|
+
approval: RunApproval | null;
|
|
33
|
+
facts: RunFact[];
|
|
34
|
+
answer: string;
|
|
35
|
+
supportUrl?: string | null;
|
|
36
|
+
sourcesCollapsible?: boolean;
|
|
37
|
+
createdAt: string;
|
|
38
|
+
completedAt: string | null;
|
|
39
|
+
}
|
|
40
|
+
export interface StartedRun {
|
|
41
|
+
runToken: string;
|
|
42
|
+
run: RunView;
|
|
43
|
+
}
|
package/dist/widget.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type ClientOptions } from "./client";
|
|
2
|
+
export type Theme = "light" | "dark" | "auto";
|
|
3
|
+
export interface ChatbotOptions extends ClientOptions {
|
|
4
|
+
/** Colour scheme; `auto` follows the visitor's system setting. Default `auto`. */
|
|
5
|
+
theme?: Theme;
|
|
6
|
+
/** Corner for the floating launcher. Default `bottom-right`. */
|
|
7
|
+
position?: "bottom-right" | "bottom-left";
|
|
8
|
+
/** Open the chat panel immediately. */
|
|
9
|
+
open?: boolean;
|
|
10
|
+
/** Override the accent colour configured on the key (hex, e.g. `#5364dd`). */
|
|
11
|
+
accentColor?: string;
|
|
12
|
+
/** Render inside this element (no launcher, always open) instead of floating over the page. */
|
|
13
|
+
target?: HTMLElement;
|
|
14
|
+
/** Keep the conversation across page loads in this tab (sessionStorage). Default true. */
|
|
15
|
+
persist?: boolean;
|
|
16
|
+
/** Optional site-managed action shown in the chat composer. */
|
|
17
|
+
quickAction?: {
|
|
18
|
+
label: string;
|
|
19
|
+
onSelect: () => void;
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
export interface ChatbotHandle {
|
|
23
|
+
open(): void;
|
|
24
|
+
close(): void;
|
|
25
|
+
toggle(): void;
|
|
26
|
+
/** Send a message as if the visitor typed it. */
|
|
27
|
+
send(text: string): Promise<void>;
|
|
28
|
+
/** Remove the widget and stop following runs. */
|
|
29
|
+
destroy(): void;
|
|
30
|
+
readonly host: HTMLElement;
|
|
31
|
+
}
|
|
32
|
+
/** White or near-black text, whichever reads better on the accent colour (WCAG relative luminance). */
|
|
33
|
+
export declare function readableOn(hex: string): string;
|
|
34
|
+
/** Mount the AegisHex chat widget on the page and return a handle to control it. */
|
|
35
|
+
export declare function mountChatbot(options: ChatbotOptions): ChatbotHandle;
|
package/package.json
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aegishex/chatbot",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Embeddable AegisHex chat widget: talk to verified agents from any website, with live run progress and human approval pauses.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"module": "./dist/index.js",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"import": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./script": "./dist/aegishex-chatbot.global.js"
|
|
16
|
+
},
|
|
17
|
+
"unpkg": "./dist/aegishex-chatbot.global.js",
|
|
18
|
+
"files": [
|
|
19
|
+
"dist",
|
|
20
|
+
"README.md"
|
|
21
|
+
],
|
|
22
|
+
"sideEffects": false,
|
|
23
|
+
"keywords": [
|
|
24
|
+
"aegishex",
|
|
25
|
+
"chatbot",
|
|
26
|
+
"widget",
|
|
27
|
+
"agents",
|
|
28
|
+
"sse"
|
|
29
|
+
],
|
|
30
|
+
"scripts": {
|
|
31
|
+
"build": "node build.mjs && tsc -p tsconfig.build.json",
|
|
32
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
33
|
+
"test": "vitest run",
|
|
34
|
+
"prepublishOnly": "npm run typecheck && npm test && npm run build"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"esbuild": "^0.28.2",
|
|
38
|
+
"jsdom": "^31.0.1",
|
|
39
|
+
"typescript": "5.9.3",
|
|
40
|
+
"vitest": "^5.1.1"
|
|
41
|
+
}
|
|
42
|
+
}
|