@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 CHANGED
@@ -1,3 +1,88 @@
1
- # Temporary Holding Version
1
+ # @aegishex/chatbot
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An embeddable chat widget for [AegisHex](../../README.md). Visitors on any website can talk to your verified agents. They see live progress while a run works, wait while a person on your team approves consequential actions (refunds, payments), and get answers built only from verified facts.
4
+
5
+ * **One script tag or one import.** It has no dependencies. The script is about 23 KB minified, and the Shadow DOM keeps the page's styles and the widget's styles apart.
6
+ * **Live progress** over Server-Sent Events. It reconnects after network drops and falls back to polling.
7
+ * **Approval pauses** are shown clearly. The visitor can stop a request that is waiting.
8
+ * **Light, dark or automatic** theme, using your accent colour. Works on mobile, with the keyboard and with screen readers.
9
+ * **Safe to put in a public page.** The publishable key can only start and follow chat runs, and only from the sites you list.
10
+
11
+ ## Embed with a script tag
12
+
13
+ Create a key on the **Chatbot** page of the AegisHex dashboard and list the sites allowed to use it. Then add:
14
+
15
+ ```html
16
+ <script src="https://YOUR-AEGISHEX-API/widget/v1/aegishex-chatbot.js" data-key="ahx_pk_…" async></script>
17
+ ```
18
+
19
+ | Attribute | Default | Meaning |
20
+ |---|---|---|
21
+ | `data-key` | required | Publishable key (`ahx_pk_…`) |
22
+ | `data-api-base` | the script's origin | AegisHex API base URL |
23
+ | `data-theme` | `auto` | `light`, `dark` or `auto` |
24
+ | `data-position` | `bottom-right` | `bottom-right` or `bottom-left` |
25
+ | `data-open` | `false` | Open the chat when the page loads |
26
+ | `data-accent` | the key's colour | Accent colour override, `#rrggbb` |
27
+
28
+ The script also exposes `window.AegisHexChatbot` (`mountChatbot`, `AegisHexClient`, and `instance` for the tag-mounted widget).
29
+
30
+ ## Use from a bundler
31
+
32
+ ```bash
33
+ npm install @aegishex/chatbot
34
+ ```
35
+
36
+ ```ts
37
+ import { mountChatbot } from "@aegishex/chatbot";
38
+
39
+ const chat = mountChatbot({
40
+ apiBaseUrl: "https://YOUR-AEGISHEX-API",
41
+ publishableKey: "ahx_pk_…",
42
+ theme: "auto",
43
+ });
44
+ chat.open();
45
+ ```
46
+
47
+ Pass `target: element` to render the chat inside your own layout instead of as a floating button.
48
+
49
+ ### Headless client
50
+
51
+ Build your own UI on the same API:
52
+
53
+ ```ts
54
+ import { AegisHexClient } from "@aegishex/chatbot";
55
+
56
+ const client = new AegisHexClient({ apiBaseUrl: "https://YOUR-AEGISHEX-API", publishableKey: "ahx_pk_…" });
57
+ const { run, runToken } = await client.sendMessage("Please refund my damaged order A-1043.");
58
+ const final = await client.followRun(run.runId, runToken, {
59
+ onUpdate: (view) => console.log(view.phase, view.steps.map((step) => step.label)),
60
+ });
61
+ console.log(final.answer, final.facts);
62
+ ```
63
+
64
+ `view.phase` is one of `working`, `awaiting_approval`, `completed`, `failed`, `denied` or `cancelled`. Errors are `ChatbotError` values with a readable `message`, the HTTP `status`, `retryAfterS` (on rate limits) and `retryable`.
65
+
66
+ ## How the key stays safe
67
+
68
+ * The key works only for the public client API. It can start runs of the task class chosen on the key and follow those runs, and nothing else.
69
+ * Browsers can use it only from the sites listed on the key.
70
+ * Every run comes with a `runToken`, so a visitor can follow only their own conversations.
71
+ * New conversations are rate-limited per visitor and per key.
72
+ * Revoking the key in the dashboard stops every site using it at once.
73
+
74
+ ## Develop
75
+
76
+ ```bash
77
+ npm install
78
+ npm test # vitest + jsdom
79
+ npm run typecheck
80
+ npm run build # dist/index.js (ESM + types) and dist/aegishex-chatbot.global.js (script tag)
81
+ ```
82
+
83
+ The AegisHex API serves the built script at `/widget/v1/aegishex-chatbot.js`. A sample storefront is in `examples/sample-site`:
84
+
85
+ ```bash
86
+ cd examples/sample-site && python -m http.server 5500
87
+ # open http://localhost:5500/?key=ahx_pk_…
88
+ ```
@@ -0,0 +1,138 @@
1
+ "use strict";var AegisHexChatbot=(()=>{var ee=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var Ae=Object.prototype.hasOwnProperty;var Re=(r,t)=>{for(var o in t)ee(r,o,{get:t[o],enumerable:!0})},Te=(r,t,o,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Se(t))!Ae.call(r,s)&&s!==o&&ee(r,s,{get:()=>t[s],enumerable:!(i=Ce(t,s))||i.enumerable});return r};var Le=r=>Te(ee({},"__esModule",{value:!0}),r);var Ke={};Re(Ke,{AegisHexClient:()=>V,ChatbotError:()=>b,instance:()=>xe,mountChatbot:()=>re});var G=class{constructor(){this.buffer=""}push(t){this.buffer+=t.replace(/\r\n?/g,`
2
+ `);let o=[],i=this.buffer.indexOf(`
3
+
4
+ `);for(;i!==-1;){let s=this.buffer.slice(0,i);this.buffer=this.buffer.slice(i+2);let d=Ie(s);d&&o.push(d),i=this.buffer.indexOf(`
5
+
6
+ `)}return o}};function Ie(r){let t="message",o=[],i,s;for(let d of r.split(`
7
+ `)){if(!d||d.startsWith(":"))continue;let p=d.indexOf(":"),f=p===-1?d:d.slice(0,p),g=p===-1?"":d.slice(p+1).replace(/^ /,"");f==="event"?t=g:f==="data"?o.push(g):f==="id"?i=g:f==="retry"&&/^\d+$/.test(g)&&(s=Number(g))}return!o.length&&s===void 0?null:{event:t,data:o.join(`
8
+ `),id:i,retry:s}}var L=new Set(["completed","failed","denied","cancelled"]);var b=class extends Error{constructor(t,o,i=null){super(t),this.name="ChatbotError",this.status=o,this.retryAfterS=i}get retryable(){return this.status===0||this.status===429||this.status>=500}},Me=3,Oe=2e3,$e=15e3,he="aegishex:visitor-id";function Y(){return globalThis.crypto?.randomUUID?.()??`msg-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function He(){try{let r=globalThis.sessionStorage?.getItem(he);if(r&&r.length>=16)return r;let t=Y();return globalThis.sessionStorage?.setItem(he,t),t}catch{return Y()}}function te(r,t){return new Promise((o,i)=>{if(t?.aborted)return i(ne());let s=setTimeout(()=>{t?.removeEventListener("abort",d),o()},r),d=()=>{clearTimeout(s),i(ne())};t?.addEventListener("abort",d,{once:!0})})}function ne(){let r=new Error("Stopped following the run.");return r.name="AbortError",r}var V=class{constructor(t){if(!t.publishableKey?.startsWith("ahx_pk_"))throw new b("A publishable widget key (ahx_pk_\u2026) is required.",0);this.base=t.apiBaseUrl.replace(/\/+$/,""),this.key=t.publishableKey,this.visitorId=He();let o=t.fetch??globalThis.fetch;if(!o)throw new b("fetch is not available in this environment.",0);this.fetchImpl=o.bind(globalThis)}getConfig(){return this.json("GET","/api/client/v1/config")}sendMessage(t,o={}){return this.json("POST","/api/client/v1/runs",{message:t},{"Idempotency-Key":o.idempotencyKey??Y(),"X-Visitor-Id":this.visitorId})}getRun(t,o){return this.json("GET",`/api/client/v1/runs/${encodeURIComponent(t)}`,void 0,{"X-Run-Token":o})}cancelRun(t,o){return this.json("POST",`/api/client/v1/runs/${encodeURIComponent(t)}/cancel`,void 0,{"X-Run-Token":o,"Idempotency-Key":Y()})}async followRun(t,o,i){let{onUpdate:s,signal:d}=i,p=0,f=2e3;for(;p<Me;){if(d?.aborted)throw ne();try{let g=await this.readStream(t,o,s,d,x=>{f=x});if(g)return g;p=0,await te(250,d)}catch(g){if(g.name==="AbortError"||g instanceof b&&!g.retryable)throw g;p+=1,await te(Math.min(f*2**(p-1),$e),d)}}return this.pollRun(t,o,s,d)}async readStream(t,o,i,s,d){let p=await this.request("GET",`/api/client/v1/runs/${encodeURIComponent(t)}/events`,void 0,{"X-Run-Token":o,Accept:"text/event-stream"},s);if(!p.body)throw new b("Streaming is not supported here.",0);let f=p.body.getReader(),g=new TextDecoder,x=new G;try{for(;;){let{value:_,done:q}=await f.read();if(q)return null;for(let E of x.push(g.decode(_,{stream:!0})))if(E.retry!==void 0&&d(E.retry),E.event==="snapshot"||E.event==="end"){let $=JSON.parse(E.data);if(i($),E.event==="end"||L.has($.phase))return $}else if(E.event==="gone")throw new b("This conversation is no longer available.",404)}}finally{f.cancel().catch(()=>{})}}async pollRun(t,o,i,s){let d="";for(;;){try{let p=await this.getRun(t,o),f=JSON.stringify(p);if(f!==d&&(d=f,i(p)),L.has(p.phase))return p}catch(p){if(p instanceof b&&!p.retryable)throw p}await te(Oe,s)}}async json(t,o,i,s={}){return await(await this.request(t,o,i,s)).json()}async request(t,o,i,s,d){let p;try{p=await this.fetchImpl(`${this.base}${o}`,{method:t,headers:{"X-AegisHex-Key":this.key,...i===void 0?{}:{"Content-Type":"application/json"},...s},body:i===void 0?void 0:JSON.stringify(i),credentials:"omit",signal:d})}catch(f){throw f.name==="AbortError"?f:new b("Can't reach the assistant right now. Check your connection and try again.",0)}if(!p.ok)throw await ze(p);return p}};async function ze(r){let t=r.headers.get("Retry-After"),o=t&&/^\d+$/.test(t)?Number(t):null,i="Something went wrong. Please try again.";try{let s=await r.json();typeof s.message=="string"&&s.message&&(i=s.message);let d=s.details?.[0]?.reason;r.status===422&&typeof d=="string"&&(i=d.replace(/^Value error, /,""))}catch{}return new b(i,r.status,o)}var Pe=`
9
+ --ah-bg: #ffffff; --ah-surface: #f6f8fc; --ah-surface-2: #eef1f7; --ah-text: #17233b; --ah-muted: #596a80;
10
+ --ah-border: #e3e8f0; --ah-shadow: 0 18px 48px rgba(23, 35, 59, .18), 0 2px 8px rgba(23, 35, 59, .08);
11
+ --ah-good: #0b7f66; --ah-good-bg: #e6f6f1; --ah-warn: #8a5a00; --ah-warn-bg: #fff6e0; --ah-warn-border: #f2d48a;
12
+ --ah-bad: #b42335; --ah-bad-bg: #fdecef;`,ge=`
13
+ --ah-bg: #111a2c; --ah-surface: #172238; --ah-surface-2: #1e2b45; --ah-text: #e6ebf5; --ah-muted: #a3b0c4;
14
+ --ah-border: #2a3954; --ah-shadow: 0 18px 48px rgba(0, 0, 0, .5), 0 2px 8px rgba(0, 0, 0, .35);
15
+ --ah-good: #6fdcbc; --ah-good-bg: #12352f; --ah-warn: #f5c868; --ah-warn-bg: #3a2f14; --ah-warn-border: #6b5520;
16
+ --ah-bad: #ff9aa8; --ah-bad-bg: #3d1a24;`,fe=`
17
+ :host { all: initial; ${Pe} --ah-accent: #5364dd; --ah-on-accent: #ffffff; --ah-z: 2147483000;
18
+ font-family: "Segoe UI", -apple-system, BlinkMacSystemFont, Roboto, Helvetica, Arial, sans-serif; }
19
+ :host([data-theme="dark"]) { ${ge} }
20
+ @media (prefers-color-scheme: dark) { :host([data-theme="auto"]) { ${ge} } }
21
+ *, *::before, *::after { box-sizing: border-box; }
22
+ button, textarea { font: inherit; color: inherit; }
23
+ .root { position: fixed; bottom: 20px; right: 20px; z-index: var(--ah-z); display: flex; flex-direction: column;
24
+ align-items: flex-end; gap: 14px; }
25
+ .root.left { right: auto; left: 20px; align-items: flex-start; }
26
+ .root.inline { position: static; display: block; height: 100%; }
27
+ .launcher { width: 58px; height: 58px; border-radius: 50%; border: 0; cursor: pointer; background: var(--ah-accent);
28
+ color: var(--ah-on-accent); display: grid; place-items: center; box-shadow: var(--ah-shadow);
29
+ transition: transform .15s ease, box-shadow .15s ease; }
30
+ .launcher:hover { transform: translateY(-2px); }
31
+ .launcher:focus-visible, button:focus-visible { outline: 3px solid color-mix(in srgb, var(--ah-accent) 45%, transparent); outline-offset: 2px; }
32
+ .launcher svg { width: 26px; height: 26px; }
33
+ .panel { width: min(390px, calc(100vw - 32px)); height: min(620px, calc(100vh - 110px)); background: var(--ah-bg);
34
+ color: var(--ah-text); border: 1px solid var(--ah-border); border-radius: 18px; box-shadow: var(--ah-shadow);
35
+ display: flex; flex-direction: column; overflow: hidden; transform-origin: bottom right;
36
+ animation: ah-pop .18s ease-out; }
37
+ .root.left .panel { transform-origin: bottom left; }
38
+ .root.inline .panel { width: 100%; height: 100%; min-height: 420px; box-shadow: none; animation: none; }
39
+ .panel[hidden] { display: none; }
40
+ @keyframes ah-pop { from { opacity: 0; transform: translateY(8px) scale(.98); } to { opacity: 1; transform: none; } }
41
+ .header { display: flex; align-items: center; gap: 11px; padding: 14px 14px 14px 16px; border-bottom: 1px solid var(--ah-border);
42
+ background: linear-gradient(180deg, color-mix(in srgb, var(--ah-accent) 9%, var(--ah-bg)), var(--ah-bg)); }
43
+ .mark { width: 34px; height: 34px; border-radius: 10px; display: grid; place-items: center; flex: none;
44
+ background: var(--ah-accent); color: var(--ah-on-accent); }
45
+ .mark svg { width: 20px; height: 20px; }
46
+ .titles { flex: 1; min-width: 0; }
47
+ .title { font-size: 15px; font-weight: 700; line-height: 1.25; margin: 0; }
48
+ .subtitle { font-size: 12px; color: var(--ah-muted); display: flex; align-items: center; gap: 6px; margin-top: 2px; }
49
+ .online { width: 7px; height: 7px; border-radius: 50%; background: var(--ah-good); }
50
+ .icon-btn { width: 34px; height: 34px; border-radius: 9px; border: 0; background: transparent; cursor: pointer;
51
+ color: var(--ah-muted); display: grid; place-items: center; }
52
+ .icon-btn:hover { background: var(--ah-surface-2); color: var(--ah-text); }
53
+ .icon-btn svg { width: 18px; height: 18px; }
54
+ .log { flex: 1; overflow-y: auto; padding: 16px 14px 8px; display: flex; flex-direction: column; gap: 12px;
55
+ scroll-behavior: smooth; overscroll-behavior: contain; }
56
+ .row { display: flex; }
57
+ .row.user { justify-content: flex-end; }
58
+ .bubble { max-width: 86%; padding: 10px 13px; border-radius: 14px; font-size: 14px; line-height: 1.5;
59
+ white-space: pre-wrap; overflow-wrap: anywhere; }
60
+ .row.user .bubble { background: var(--ah-accent); color: var(--ah-on-accent); border-bottom-right-radius: 5px; }
61
+ .row.bot .bubble { background: var(--ah-surface); border: 1px solid var(--ah-border); border-bottom-left-radius: 5px; }
62
+ .card { width: 100%; max-width: 92%; background: var(--ah-surface); border: 1px solid var(--ah-border);
63
+ border-radius: 14px; border-bottom-left-radius: 5px; padding: 12px 13px; font-size: 14px; line-height: 1.5; }
64
+ .answer { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
65
+ .support-link { align-self: flex-start; color: inherit; font-weight: 600; text-decoration: underline; }
66
+ .status { display: flex; align-items: center; gap: 8px; font-size: 12px; font-weight: 600; color: var(--ah-muted);
67
+ margin-bottom: 8px; letter-spacing: .01em; }
68
+ .badge { display: inline-flex; align-items: center; gap: 5px; padding: 2px 8px; border-radius: 999px; font-size: 11.5px;
69
+ font-weight: 600; }
70
+ .badge svg { width: 12px; height: 12px; }
71
+ .badge.good { background: var(--ah-good-bg); color: var(--ah-good); }
72
+ .badge.warn { background: var(--ah-warn-bg); color: var(--ah-warn); }
73
+ .badge.bad { background: var(--ah-bad-bg); color: var(--ah-bad); }
74
+ .badge.busy { background: var(--ah-surface-2); color: var(--ah-muted); }
75
+ .steps { list-style: none; margin: 10px 0 0; padding: 10px 0 0; border-top: 1px dashed var(--ah-border);
76
+ display: flex; flex-direction: column; gap: 6px; }
77
+ .steps li { display: flex; align-items: center; gap: 8px; font-size: 12.5px; color: var(--ah-muted); }
78
+ .steps li.done { color: var(--ah-text); }
79
+ .steps .dot { width: 16px; height: 16px; flex: none; display: grid; place-items: center; border-radius: 50%; }
80
+ .steps li.done .dot { background: var(--ah-good-bg); color: var(--ah-good); }
81
+ .steps li.problem .dot { background: var(--ah-bad-bg); color: var(--ah-bad); }
82
+ .steps .dot svg { width: 10px; height: 10px; }
83
+ .spinner { width: 12px; height: 12px; border: 2px solid var(--ah-border); border-top-color: var(--ah-accent);
84
+ border-radius: 50%; animation: ah-spin .8s linear infinite; }
85
+ @keyframes ah-spin { to { transform: rotate(360deg); } }
86
+ .typing { display: inline-flex; gap: 4px; padding: 2px 0; }
87
+ .typing span { width: 6px; height: 6px; border-radius: 50%; background: var(--ah-muted); opacity: .5;
88
+ animation: ah-blink 1.2s infinite ease-in-out; }
89
+ .typing span:nth-child(2) { animation-delay: .15s; } .typing span:nth-child(3) { animation-delay: .3s; }
90
+ @keyframes ah-blink { 0%, 80%, 100% { opacity: .25; transform: translateY(0); } 40% { opacity: 1; transform: translateY(-2px); } }
91
+ .approval { margin-top: 10px; padding: 11px 12px; border-radius: 11px; background: var(--ah-warn-bg);
92
+ border: 1px solid var(--ah-warn-border); color: var(--ah-text); }
93
+ .approval strong { display: block; font-size: 13px; margin-bottom: 3px; text-transform: capitalize; }
94
+ .approval p { margin: 0; font-size: 12.5px; color: var(--ah-muted); }
95
+ .facts { margin: 10px 0 0; padding: 0; display: grid; grid-template-columns: fit-content(45%) minmax(0, 1fr);
96
+ gap: 6px 12px; font-size: 13px; }
97
+ .facts dt { color: var(--ah-muted); overflow-wrap: anywhere; }
98
+ .facts dd { margin: 0; font-weight: 600; overflow-wrap: anywhere; }
99
+ .facts .passage { grid-column: 1 / -1; }
100
+ .facts dt.passage:not(:first-child) { margin-top: 6px; }
101
+ .facts dd.passage { white-space: pre-wrap; font-weight: 400; }
102
+ .sources { margin-top: 10px; font-size: 12px; color: var(--ah-muted); }
103
+ .sources summary { cursor: pointer; width: fit-content; }
104
+ .sources dd { color: var(--ah-text); }
105
+ .card-actions { display: flex; justify-content: space-between; align-items: center; margin-top: 10px; gap: 8px; }
106
+ .ref { font-size: 11.5px; color: var(--ah-muted); }
107
+ .link-btn { border: 0; background: none; padding: 0; color: var(--ah-accent); font-size: 12.5px; font-weight: 600; cursor: pointer; }
108
+ .link-btn:hover { text-decoration: underline; }
109
+ .notice { margin: 0 14px 8px; padding: 9px 12px; border-radius: 10px; font-size: 12.5px; line-height: 1.45;
110
+ background: var(--ah-bad-bg); color: var(--ah-bad); }
111
+ .notice[hidden] { display: none; }
112
+ .composer { border-top: 1px solid var(--ah-border); padding: 10px 12px 8px; background: var(--ah-bg); }
113
+ .input-row { display: flex; align-items: flex-end; gap: 8px; background: var(--ah-surface); border: 1px solid var(--ah-border);
114
+ border-radius: 14px; padding: 6px 6px 6px 12px; transition: border-color .15s; }
115
+ .input-row:focus-within { border-color: var(--ah-accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--ah-accent) 22%, transparent); }
116
+ textarea { flex: 1; border: 0; background: transparent; resize: none; outline: none; box-shadow: none; font-size: 14px; line-height: 1.45;
117
+ max-height: 120px; min-height: 22px; padding: 6px 0; }
118
+ textarea::placeholder { color: var(--ah-muted); }
119
+ .send { width: 36px; height: 36px; flex: none; border: 0; border-radius: 10px; background: var(--ah-accent);
120
+ color: var(--ah-on-accent); cursor: pointer; display: grid; place-items: center; transition: opacity .15s; }
121
+ .send:disabled { opacity: .45; cursor: not-allowed; }
122
+ .send svg { width: 17px; height: 17px; }
123
+ .quick-action { margin: 0 0 8px; padding: 5px 10px; border: 1px solid var(--ah-border); border-radius: 999px;
124
+ background: var(--ah-surface); color: var(--ah-text); cursor: pointer; font-size: 12px; font-weight: 600; }
125
+ .quick-action:hover { border-color: var(--ah-accent); }
126
+ .foot { display: flex; justify-content: space-between; gap: 8px; margin-top: 6px; font-size: 11px; color: var(--ah-muted); }
127
+ .foot b { font-weight: 700; color: var(--ah-text); }
128
+ .foot b span { color: #0e9f80; }
129
+ .sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
130
+ @media (max-width: 480px) {
131
+ .root:not(.inline) { bottom: 12px; right: 12px; left: 12px; align-items: flex-end; }
132
+ .root:not(.inline) .panel { width: 100%; height: calc(100vh - 96px); }
133
+ }
134
+ @media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation: none !important; transition: none !important; } }
135
+ `;var Ne={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>',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>',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>',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>',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>',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>',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>'},be={assistantName:"Assistant",greeting:"Hi! How can I help?",accentColor:"#5364dd",organization:"",minMessageLength:2,maxMessageLength:2e3};function a(r,t,o){let i=document.createElement(r);return t&&(i.className=t),o!==void 0&&(i.textContent=o),i}function O(r){let t=a("span");return t.style.display="contents",t.innerHTML=Ne[r],t}function Ve(r){let t=/^#([0-9a-f]{6})$/i.exec(r);if(!t)return"#ffffff";let o=[0,2,4].map(s=>parseInt(t[1].slice(s,s+2),16)/255).map(s=>s<=.03928?s/12.92:((s+.055)/1.055)**2.4);return .2126*o[0]+.7152*o[1]+.0722*o[2]>.36?"#111827":"#ffffff"}var _e=0,me=()=>`m${Date.now().toString(36)}${_e+=1}`;function re(r){let t=new V(r),o=!!r.target,i=`aegishex-chat:${r.publishableKey.slice(-12)}`,s=r.persist!==!1,d=a("div");d.setAttribute("data-aegishex-chatbot",""),d.setAttribute("data-theme",r.theme??"auto");let p=d.attachShadow({mode:"open"}),f=a("style");f.textContent=fe,p.append(f);let g=a("div",`root${r.position==="bottom-left"?" left":""}${o?" inline":""}`),x=a("section","panel");x.setAttribute("role",o?"region":"dialog"),x.setAttribute("aria-label","Chat"),o||(x.hidden=!0);let _=a("header","header"),q=a("div","mark");q.append(O("mark"));let E=a("div","titles"),$=a("h2","title",be.assistantName),ae=a("div","subtitle"),ve=a("span","online"),oe=a("span",void 0,"Verified answers");ae.append(ve,oe),E.append($,ae),_.append(q,E);let H=null;o||(H=a("button","icon-btn"),H.type="button",H.setAttribute("aria-label","Close chat"),H.append(O("close")),_.append(H));let m=a("div","log");m.setAttribute("role","log"),m.setAttribute("aria-live","polite"),m.setAttribute("aria-relevant","additions text");let B=a("p","notice");B.setAttribute("role","alert"),B.hidden=!0;let F=a("form","composer"),ie=a("div","input-row"),se=a("label","sr-only","Message"),l=a("textarea");l.rows=1,l.placeholder="Type your message\u2026",l.id="aegishex-input",se.htmlFor=l.id;let K=a("button","send");K.type="submit",K.setAttribute("aria-label","Send message"),K.append(O("send")),ie.append(se,l,K);let de=a("div","foot"),W=a("span",void 0,"Enter to send \xB7 Shift+Enter for a new line"),X=a("span");X.append(document.createTextNode("Powered by "));let le=a("b",void 0,"aegis");if(le.append(a("span",void 0,"hex")),X.append(le),de.append(W,X),r.quickAction){let{label:e,onSelect:n}=r.quickAction,c=a("button","quick-action",e);c.type="button",c.addEventListener("click",n),F.append(c)}F.append(ie,de),x.append(_,m,B,F);let y=null;o||(y=a("button","launcher"),y.type="button",y.setAttribute("aria-label","Open chat"),y.setAttribute("aria-expanded","false"),y.append(O("chat"))),g.append(x),y&&g.append(y),p.append(g),(r.target??document.body).append(d);let I=be,S=ye(),z=!1,P=new Map,pe=!1;function we(e){I=e;let n=r.accentColor&&/^#[0-9a-f]{6}$/i.test(r.accentColor)?r.accentColor:e.accentColor;d.style.setProperty("--ah-accent",n),d.style.setProperty("--ah-on-accent",Ve(n)),$.textContent=e.assistantName,oe.textContent=e.organization?`${e.organization} \xB7 verified answers`:"Verified answers",l.maxLength=e.maxMessageLength,A()}function ye(){if(!s)return[];try{let e=window.sessionStorage.getItem(i),n=e?JSON.parse(e):[];return Array.isArray(n)?n.slice(-50):[]}catch{return[]}}function J(){if(s)try{window.sessionStorage.setItem(i,JSON.stringify(S.slice(-50)))}catch{}}function ce(){return S.find(e=>e.kind==="run"&&!L.has(e.view.phase))}function U(e){B.textContent=e??"",B.hidden=!e}function D(){let e=z||!!ce(),n=l.value.trim().length;K.disabled=e||n<I.minMessageLength,l.disabled=z,e?W.textContent="Waiting for the current request to finish\u2026":n>0&&n<I.minMessageLength?W.textContent=`Add a little more detail (${I.minMessageLength-n} more characters).`:W.textContent="Enter to send \xB7 Shift+Enter for a new line"}function ke(e){let{view:n}=e,c=a("div","card");c.setAttribute("data-phase",n.phase);let h=a("div","status"),k=(u,v,T)=>{let C=a("span",`badge ${u}`);return T?C.append(O(T)):u==="busy"&&C.append(a("span","spinner")),C.append(document.createTextNode(v)),C};if(n.phase==="working"?h.append(k("busy",n.steps.length?"Working on it":"Thinking\u2026")):n.phase==="awaiting_approval"?h.append(k("warn","Waiting for approval","clock")):n.phase==="completed"?h.append(k("good",n.facts.length?"Verified":"Done","check")):n.phase==="denied"?h.append(k("bad","Declined","alert")):n.phase==="cancelled"?h.append(k("bad","Stopped","alert")):h.append(k("bad","Couldn't finish","alert")),c.append(h),n.phase==="working"&&!n.steps.length){let u=a("span","typing");u.setAttribute("aria-label","Working"),u.append(a("span"),a("span"),a("span")),c.append(u)}else if(c.append(a("p","answer",n.answer)),n.supportUrl&&/^https?:\/\//i.test(n.supportUrl)){let u=a("a","support-link","Contact support");u.href=n.supportUrl,u.target="_blank",u.rel="noopener noreferrer",c.append(u)}if(n.approval&&n.phase==="awaiting_approval"){let u=a("div","approval");u.append(a("strong",void 0,n.approval.amount?`${n.approval.action} \xB7 ${n.approval.amount}`:n.approval.action)),u.append(a("p",void 0,`A person on the ${I.organization||"site"} team reviews this before anything happens.`)),c.append(u)}if(n.facts.length&&(n.phase==="completed"||n.phase==="awaiting_approval")){let u=a("dl","facts");for(let v of n.facts){let T=v.label.startsWith("Source: ")?"passage":void 0;u.append(a("dt",T,v.label),a("dd",T,v.value))}if(n.sourcesCollapsible){let v=a("details","sources");v.append(a("summary",void 0,n.facts.length===1?"View source":"View sources"),u),c.append(v)}else c.append(u)}if(n.steps.length&&!L.has(n.phase)){let u=a("ul","steps");u.setAttribute("aria-label","Progress");for(let v of n.steps){let T=a("li",v.status),C=a("span","dot");v.status==="done"?C.append(O("check")):v.status==="problem"?C.append(O("alert")):C.append(a("span","spinner")),T.append(C,document.createTextNode(v.label)),u.append(T)}c.append(u)}let N=a("div","card-actions");if(n.runId.startsWith("greet-")||N.append(a("span","ref",`Ref ${n.reference}`)),!L.has(n.phase)){let u=a("button","link-btn","Stop request");u.type="button",u.addEventListener("click",()=>{Ee(e)}),N.append(u)}return N.childElementCount>0&&c.append(N),c}function A(){let e=m.scrollHeight-m.scrollTop-m.clientHeight<80;m.replaceChildren();let n=a("div","row bot");n.append(a("div","bubble",I.greeting)),m.append(n);for(let c of S){let h=a("div",`row ${c.kind==="user"?"user":"bot"}`);c.kind==="run"?h.append(ke(c)):h.append(a("div","bubble",c.text)),m.append(h)}(e||z)&&(m.scrollTop=m.scrollHeight),D()}function ue(e){if(P.has(e.runId)||L.has(e.view.phase))return;let n=new AbortController;P.set(e.runId,n),t.followRun(e.runId,e.runToken,{signal:n.signal,onUpdate:c=>{e.view=c,J(),A()}}).catch(c=>{c.name==="AbortError"||pe||U(c instanceof b?c.message:"Lost track of this request. Reload to try again.")}).finally(()=>{P.delete(e.runId),A()})}async function Ee(e){try{e.view=await t.cancelRun(e.runId,e.runToken),P.get(e.runId)?.abort(),J(),A()}catch(n){U(n instanceof b?n.message:"Couldn't stop the request.")}}let R=[],w=-1,Z="";async function Q(e){let n=e.trim();if(z||ce()||n.length<I.minMessageLength)return;R[R.length-1]!==n&&R.push(n),w=-1,Z="",z=!0,U(null);let c={kind:"user",id:me(),text:n};S.push(c),l.value="",j(),A();try{let h=await t.sendMessage(n),k={kind:"run",id:me(),runId:h.run.runId,runToken:h.runToken,view:h.run};S.push(k),J(),ue(k)}catch(h){S=S.filter(N=>N!==c),l.value=n,j();let k=h instanceof b&&h.retryAfterS?` (${h.retryAfterS}s)`:"";U(h instanceof b?`${h.message}${k}`:"Something went wrong. Please try again.")}finally{z=!1,A(),l.focus()}}function j(){l.style.height="auto",l.style.height=`${Math.min(l.scrollHeight,120)}px`}function M(e){o||(x.hidden=!e,y?.setAttribute("aria-expanded",String(e)),y?.setAttribute("aria-label",e?"Close chat":"Open chat"),e?(A(),m.scrollTop=m.scrollHeight,l.focus()):y?.focus())}F.addEventListener("submit",e=>{e.preventDefault(),Q(l.value)}),l.addEventListener("keydown",e=>{if(e.key==="Enter"&&!e.shiftKey&&!e.isComposing){e.preventDefault(),Q(l.value);return}if(e.key==="ArrowUp"&&!e.shiftKey&&!e.isComposing&&R.length>0){let n=l.selectionStart??0;l.value.slice(0,n).includes(`
136
+ `)||(e.preventDefault(),w===-1?(Z=l.value,w=R.length-1):w>0&&(w-=1),l.value=R[w]??"",j(),D(),l.setSelectionRange(l.value.length,l.value.length));return}if(e.key==="ArrowDown"&&!e.shiftKey&&!e.isComposing&&w!==-1){let n=l.selectionEnd??l.value.length;l.value.slice(n).includes(`
137
+ `)||(e.preventDefault(),w<R.length-1?(w+=1,l.value=R[w]??""):(w=-1,l.value=Z),j(),D(),l.setSelectionRange(l.value.length,l.value.length))}}),l.addEventListener("input",()=>{w=-1,j(),D()}),y?.addEventListener("click",()=>M(x.hidden)),H?.addEventListener("click",()=>M(!1)),x.addEventListener("keydown",e=>{e.key==="Escape"&&!o&&M(!1)}),A(),t.getConfig().then(we).catch(e=>{U(e instanceof b?e.message:"The assistant is unavailable right now.")});for(let e of S)e.kind==="run"&&ue(e);return r.open&&M(!0),{host:d,open:()=>M(!0),close:()=>M(!1),toggle:()=>M(x.hidden),send:e=>Q(e),destroy:()=>{pe=!0;for(let e of P.values())e.abort();P.clear(),d.remove()}}}var xe=null;function Be(){let r=document.currentScript,t=r?.dataset.key;if(!r||!t)return;let o=()=>{try{xe=re({publishableKey:t,apiBaseUrl:r.dataset.apiBase||new URL(r.src,window.location.href).origin,theme:["light","dark","auto"].includes(r.dataset.theme??"")?r.dataset.theme:"auto",position:r.dataset.position==="bottom-left"?"bottom-left":"bottom-right",open:r.dataset.open==="true",accentColor:r.dataset.accent})}catch(i){console.error("[aegishex] chatbot not started:",i.message)}};document.body?o():document.addEventListener("DOMContentLoaded",o,{once:!0})}Be();return Le(Ke);})();
138
+ //# sourceMappingURL=aegishex-chatbot.global.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/auto.ts", "../src/sse.ts", "../src/types.ts", "../src/client.ts", "../src/styles.ts", "../src/widget.ts"],
4
+ "sourcesContent": ["/**\n * Script-tag entry (`dist/aegishex-chatbot.global.js`, exposed as `window.AegisHexChatbot`).\n *\n * ```html\n * <script src=\"https://api.example.com/widget/v1/aegishex-chatbot.js\" data-key=\"ahx_pk_\u2026\" async></script>\n * ```\n *\n * Optional attributes: `data-api-base` (defaults to the script's origin), `data-theme` (light | dark | auto),\n * `data-position` (bottom-right | bottom-left), `data-open` (\"true\"), `data-accent` (#rrggbb).\n */\nimport { AegisHexClient, ChatbotError } from \"./client\";\nimport { mountChatbot, type ChatbotHandle, type ChatbotOptions, type Theme } from \"./widget\";\n\nexport { AegisHexClient, ChatbotError, mountChatbot };\nexport type { ChatbotHandle, ChatbotOptions };\n\n/** The widget mounted from the script tag, if any. */\nexport let instance: ChatbotHandle | null = null;\n\nfunction autoMount(): void {\n const script = document.currentScript as HTMLScriptElement | null;\n const key = script?.dataset.key;\n if (!script || !key) return;\n const start = () => {\n try {\n instance = mountChatbot({\n publishableKey: key,\n apiBaseUrl: script.dataset.apiBase || new URL(script.src, window.location.href).origin,\n theme: ([\"light\", \"dark\", \"auto\"].includes(script.dataset.theme ?? \"\") ? script.dataset.theme : \"auto\") as Theme,\n position: script.dataset.position === \"bottom-left\" ? \"bottom-left\" : \"bottom-right\",\n open: script.dataset.open === \"true\",\n accentColor: script.dataset.accent,\n });\n } catch (error) {\n console.error(\"[aegishex] chatbot not started:\", (error as Error).message);\n }\n };\n if (document.body) start();\n else document.addEventListener(\"DOMContentLoaded\", start, { once: true });\n}\n\nautoMount();\n", "/** 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": "idAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,oBAAAE,EAAA,iBAAAC,EAAA,aAAAC,GAAA,iBAAAC,KCaO,IAAMC,EAAN,KAAgB,CA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eAAgBF,EAChB,WAAYD,EAAO,QAAQ,SAAW,IAAI,IAAIA,EAAO,IAAK,OAAO,SAAS,IAAI,EAAE,OAChF,MAAQ,CAAC,QAAS,OAAQ,MAAM,EAAE,SAASA,EAAO,QAAQ,OAAS,EAAE,EAAIA,EAAO,QAAQ,MAAQ,OAChG,SAAUA,EAAO,QAAQ,WAAa,cAAgB,cAAgB,eACtE,KAAMA,EAAO,QAAQ,OAAS,OAC9B,YAAaA,EAAO,QAAQ,MAC9B,CAAC,CACH,OAASI,EAAO,CACd,QAAQ,MAAM,kCAAoCA,EAAgB,OAAO,CAC3E,CACF,EACI,SAAS,KAAMF,EAAM,EACpB,SAAS,iBAAiB,mBAAoBA,EAAO,CAAE,KAAM,EAAK,CAAC,CAC1E,CAEAH,GAAU",
6
+ "names": ["auto_exports", "__export", "AegisHexClient", "ChatbotError", "instance", "mountChatbot", "SseParser", "chunk", "events", "boundary", "block", "parsed", "parseBlock", "event", "data", "id", "retry", "line", "colon", "field", "value", "FINAL_PHASES", "ChatbotError", "message", "status", "retryAfterS", "STREAM_FAILURES_BEFORE_POLLING", "POLL_INTERVAL_MS", "MAX_BACKOFF_MS", "VISITOR_STORAGE_KEY", "newIdempotencyKey", "getOrCreateVisitorId", "existing", "generated", "sleep", "ms", "signal", "resolve", "reject", "abortError", "timer", "onAbort", "error", "AegisHexClient", "options", "fetchImpl", "runId", "runToken", "onUpdate", "failures", "retryMs", "outcome", "onRetry", "response", "reader", "decoder", "parser", "SseParser", "value", "done", "event", "view", "FINAL_PHASES", "previous", "serialized", "method", "path", "body", "headers", "toError", "retryHeader", "retryAfter", "reason", "LIGHT", "DARK", "STYLES", "ICONS", "DEFAULT_CONFIG", "el", "tag", "className", "text", "node", "icon", "name", "span", "readableOn", "hex", "match", "channels", "offset", "c", "counter", "nextId", "mountChatbot", "options", "client", "AegisHexClient", "inline", "storageKey", "persist", "host", "shadow", "style", "STYLES", "root", "panel", "header", "mark", "titles", "title", "subtitle", "online", "subtitleText", "closeButton", "log", "notice", "composer", "inputRow", "label", "input", "send", "foot", "hint", "powered", "brand", "onSelect", "action", "launcher", "config", "entries", "loadEntries", "sending", "following", "destroyed", "applyConfig", "next", "accent", "render", "raw", "parsed", "save", "activeRun", "entry", "FINAL_PHASES", "showNotice", "message", "updateComposer", "busy", "length", "renderRun", "view", "card", "status", "badge", "kind", "glyph", "typing", "support", "box", "facts", "fact", "sources", "steps", "step", "item", "dot", "actions", "stop", "stopRun", "nearBottom", "greeting", "row", "follow", "controller", "error", "ChatbotError", "promptHistory", "historyIndex", "draft", "sendMessage", "userEntry", "autosize", "started", "runEntry", "wait", "setOpen", "open", "event", "pos", "instance", "autoMount", "script", "key", "start", "mountChatbot", "error"]
7
+ }
@@ -0,0 +1,52 @@
1
+ import { type RunView, type StartedRun, type WidgetConfig } from "./types";
2
+ export interface ClientOptions {
3
+ /** Base URL of the AegisHex API, e.g. `https://api.aegishex.example`. */
4
+ apiBaseUrl: string;
5
+ /** Publishable widget key (`ahx_pk_…`), created on the Chatbot page of the AegisHex dashboard. */
6
+ publishableKey: string;
7
+ /** Custom fetch (tests, server-side rendering). Defaults to the global fetch. */
8
+ fetch?: typeof fetch;
9
+ }
10
+ export interface FollowOptions {
11
+ /** Called with the full run view every time it changes. */
12
+ onUpdate: (view: RunView) => void;
13
+ /** Stops following (the promise rejects with an AbortError). */
14
+ signal?: AbortSignal;
15
+ }
16
+ /** An error answer from the API, with its message already written for people. */
17
+ export declare class ChatbotError extends Error {
18
+ readonly status: number;
19
+ readonly retryAfterS: number | null;
20
+ constructor(message: string, status: number, retryAfterS?: number | null);
21
+ /** True when retrying the same request can succeed (network trouble, rate limits, server errors). */
22
+ get retryable(): boolean;
23
+ }
24
+ /** Typed client for the AegisHex public client API. Works in browsers and in Node 18+. */
25
+ export declare class AegisHexClient {
26
+ private readonly base;
27
+ private readonly key;
28
+ private readonly visitorId;
29
+ private readonly fetchImpl;
30
+ constructor(options: ClientOptions);
31
+ /** Assistant name, greeting, accent colour and message limits configured for this key. */
32
+ getConfig(): Promise<WidgetConfig>;
33
+ /** Send a message. It starts one agent run; keep `runToken` to follow it. */
34
+ sendMessage(message: string, options?: {
35
+ idempotencyKey?: string;
36
+ }): Promise<StartedRun>;
37
+ /** Current view of a run (the polling fallback). */
38
+ getRun(runId: string, runToken: string): Promise<RunView>;
39
+ /** Stop an unfinished run; a pending approval is withdrawn and nothing is executed. */
40
+ cancelRun(runId: string, runToken: string): Promise<RunView>;
41
+ /**
42
+ * Follow a run until it finishes and resolve with the final view.
43
+ *
44
+ * Uses the Server-Sent Events stream and reconnects after network drops (the first event after a reconnect
45
+ * is always the current state, so nothing is missed). After repeated stream failures it falls back to polling.
46
+ */
47
+ followRun(runId: string, runToken: string, options: FollowOptions): Promise<RunView>;
48
+ private readStream;
49
+ private pollRun;
50
+ private json;
51
+ private request;
52
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @aegishex/chatbot: embed an AegisHex agent on any website.
3
+ *
4
+ * ```ts
5
+ * import { mountChatbot } from "@aegishex/chatbot";
6
+ * mountChatbot({ apiBaseUrl: "https://api.example.com", publishableKey: "ahx_pk_…" });
7
+ * ```
8
+ */
9
+ export { AegisHexClient, ChatbotError } from "./client";
10
+ export type { ClientOptions, FollowOptions } from "./client";
11
+ export { mountChatbot, readableOn } from "./widget";
12
+ export type { ChatbotHandle, ChatbotOptions, Theme } from "./widget";
13
+ export { SseParser } from "./sse";
14
+ export type { SseEvent } from "./sse";
15
+ export { FINAL_PHASES } from "./types";
16
+ export type { RunApproval, RunFact, RunPhase, RunStep, RunView, StartedRun, WidgetConfig } from "./types";