@ghuri/ai-widget 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -41,7 +41,7 @@ chat.addEventListener('ghuri:tool-result', (e) => {/* e.detail: toolName, input,
41
41
 
42
42
  **Parts** for anything else (`ghuri-chat::part(user-bubble) { background: … }`): `header`, `title`, `user-bubble`,
43
43
  `assistant`, `tool-step`, `decided`, `confirm-card`, `confirm-header`, `button-primary`, `button-secondary`,
44
- `problem`, `composer`, `input`, `send`, `stop`, `history`, `empty`, `starter`.
44
+ `problem`, `composer`, `input`, `send`, `stop`, `history`, `empty`, `starter`, `preview` (the product's description of a waiting change).
45
45
 
46
46
  **Custom cards** (`cards: { <tool name>: { result?, confirm? } }`): `result` replaces a finished tool's step,
47
47
  `confirm` replaces the generic confirm card when that tool's change waits alone (`ctx.decide(true | false)`). The
@@ -17,6 +17,11 @@ export declare class ChatClient {
17
17
  /** Tool name → title, learnt from the stream (saved messages do not carry titles). */
18
18
  private readonly titles;
19
19
  private retryAction;
20
+ /**
21
+ * Bumped whenever the open conversation is replaced (new, opened, ended). A turn or a load that started under an
22
+ * older generation stops touching the state, so a reply that was replaced cannot overwrite what replaced it.
23
+ */
24
+ private generation;
20
25
  private seq;
21
26
  constructor(opts: ChatClientOptions);
22
27
  getState(): ChatState;
@@ -65,10 +70,20 @@ export declare class ChatClient {
65
70
  /** End the session through the product (logout, store switch) and forget everything. */
66
71
  end(): Promise<void>;
67
72
  private busy;
68
- /** Post a message or decisions and read the streamed reply into a new assistant message. */
73
+ /**
74
+ * Post a message or decisions and read the streamed reply into a new assistant message. Returns `not-sent` when the
75
+ * request failed or was refused before a reply started (nothing happened on the server), else `answered`.
76
+ */
69
77
  private turn;
78
+ /**
79
+ * Steps still writing or running when a reply ended early never get their result: mark them, so nothing spins
80
+ * forever. A confirmed change in that state may or may not have run ("outcome unknown").
81
+ */
82
+ private settleUnfinished;
70
83
  private drop;
71
84
  private finishTurn;
85
+ /** Copy each waiting change's preview onto its step, so the record after the decision still names it. */
86
+ private keepPreviews;
72
87
  /** Apply one stream chunk to the reply being written. */
73
88
  private apply;
74
89
  private toolPart;
@@ -11,6 +11,8 @@ export declare function parseSse(text: string): StreamChunk[];
11
11
  */
12
12
  export declare class SseParser {
13
13
  private buffer;
14
+ /** A `\r` that ended the last read: it may be the first half of a `\r\n` split across two reads. */
15
+ private carry;
14
16
  /** True once `data: [DONE]` was seen. */
15
17
  done: boolean;
16
18
  push(text: string): StreamChunk[];
@@ -26,6 +26,8 @@ export interface ToolPart {
26
26
  toolName: string;
27
27
  /** The tool's human title from the product's MCP server, when it has one. */
28
28
  title?: string;
29
+ /** For a change that waited for confirmation: the product's description of it (kept for the decided record). */
30
+ preview?: ChangePreview;
29
31
  input?: unknown;
30
32
  /**
31
33
  * `input`: the AI is still writing the call; `running`: the call was sent; `awaiting-approval`: a change waiting for
@@ -48,12 +50,26 @@ export interface ChatMessage {
48
50
  parts: MessagePart[];
49
51
  }
50
52
  /** A change waiting for the user's decision (Ghuri AI's `pendingApprovals`). */
53
+ /**
54
+ * The product's own description of a waiting change (its describe tool): what it touches, in words, and the values it
55
+ * changes. Display text from the product, never from the model; `current` was read when the change was proposed.
56
+ */
57
+ export interface ChangePreview {
58
+ summary: string;
59
+ changes: Array<{
60
+ label: string;
61
+ current?: string;
62
+ next: string;
63
+ }>;
64
+ }
51
65
  export interface PendingApproval {
52
66
  approvalId: string;
53
67
  toolCallId: string;
54
68
  toolName: string;
55
69
  title?: string;
56
70
  input: unknown;
71
+ /** The product's description of the change, when it gave one. */
72
+ preview?: ChangePreview;
57
73
  }
58
74
  export interface Decision {
59
75
  approvalId: string;
@@ -86,19 +86,22 @@ function r(e) {
86
86
  }
87
87
  var i = class {
88
88
  buffer = "";
89
+ carry = "";
89
90
  done = !1;
90
91
  push(e) {
91
- this.buffer += e.replace(/\r\n?/g, "\n");
92
- let t = [], n = this.buffer.indexOf("\n\n");
93
- for (; n !== -1;) {
94
- let e = this.buffer.slice(0, n);
95
- this.buffer = this.buffer.slice(n + 2);
96
- let r = this.parseEvent(e);
97
- r && t.push(r), n = this.buffer.indexOf("\n\n");
92
+ let t = this.carry + e;
93
+ this.carry = "", t.endsWith("\r") && (this.carry = "\r", t = t.slice(0, -1)), this.buffer += t.replace(/\r\n?/g, "\n");
94
+ let n = [], r = this.buffer.indexOf("\n\n");
95
+ for (; r !== -1;) {
96
+ let e = this.buffer.slice(0, r);
97
+ this.buffer = this.buffer.slice(r + 2);
98
+ let t = this.parseEvent(e);
99
+ t && n.push(t), r = this.buffer.indexOf("\n\n");
98
100
  }
99
- return t;
101
+ return n;
100
102
  }
101
103
  end() {
104
+ this.carry = "";
102
105
  let e = this.buffer.trim();
103
106
  if (this.buffer = "", !e) return [];
104
107
  let t = this.parseEvent(e);
@@ -177,7 +180,11 @@ function u(e) {
177
180
  function d(e) {
178
181
  return e instanceof DOMException ? e.name === "AbortError" : e?.name === "AbortError";
179
182
  }
180
- function f(e) {
183
+ function f(e, t) {
184
+ let n = new Date(e.expiresAt).getTime();
185
+ return Number.isNaN(n) || n - o > t;
186
+ }
187
+ function p(e) {
181
188
  return {
182
189
  ...e,
183
190
  messages: e.messages.map((e) => ({
@@ -187,10 +194,10 @@ function f(e) {
187
194
  pendingApprovals: [...e.pendingApprovals]
188
195
  };
189
196
  }
190
- var p = class {
197
+ var m = class {
191
198
  opts;
192
199
  state = s();
193
- view = f(this.state);
200
+ view = p(this.state);
194
201
  listeners = /* @__PURE__ */ new Set();
195
202
  events = /* @__PURE__ */ new Map();
196
203
  session = null;
@@ -199,6 +206,7 @@ var p = class {
199
206
  tools = /* @__PURE__ */ new Map();
200
207
  titles = /* @__PURE__ */ new Map();
201
208
  retryAction = null;
209
+ generation = 0;
202
210
  seq = 0;
203
211
  constructor(e) {
204
212
  this.opts = {
@@ -220,7 +228,7 @@ var p = class {
220
228
  for (let n of this.events.get(e) ?? []) n(t);
221
229
  }
222
230
  changed(e = {}) {
223
- Object.assign(this.state, e), this.view = f(this.state);
231
+ Object.assign(this.state, e), this.view = p(this.state);
224
232
  for (let e of this.listeners) e(this.view);
225
233
  }
226
234
  id(e) {
@@ -231,7 +239,7 @@ var p = class {
231
239
  }
232
240
  async ensureSession() {
233
241
  let e = this.session;
234
- return e && new Date(e.expiresAt).getTime() - o > this.now() ? e : (this.session = null, this.starting ||= this.opts.startSession().then((e) => (this.session = e, e)).finally(() => {
242
+ return e && f(e, this.now()) ? e : (this.session = null, this.starting ||= this.opts.startSession().then((e) => (this.session = e, e)).finally(() => {
235
243
  this.starting = null;
236
244
  }), this.starting);
237
245
  }
@@ -287,15 +295,24 @@ var p = class {
287
295
  async decide(e) {
288
296
  let t = this.state.conversationId;
289
297
  if (!t || this.busy() || !this.state.pendingApprovals.length) return;
290
- let n = new Map(e.map((e) => [e.approvalId, e]));
291
- for (let e of this.state.pendingApprovals) {
298
+ let n = this.state.pendingApprovals, r = new Map(e.map((e) => [e.approvalId, e]));
299
+ for (let e of n) {
292
300
  let t = this.tools.get(e.toolCallId);
293
- t && (t.state = n.get(e.approvalId)?.approved ? "running" : "denied");
301
+ t && (t.state = r.get(e.approvalId)?.approved ? "running" : "denied");
294
302
  }
295
- this.changed({
303
+ if (this.changed({
296
304
  pendingApprovals: [],
297
305
  problem: null
298
- }), await this.turn(`/v1/conversations/${encodeURIComponent(t)}/approvals`, { decisions: e });
306
+ }), await this.turn(`/v1/conversations/${encodeURIComponent(t)}/approvals`, { decisions: e }) === "not-sent") {
307
+ for (let e of n) {
308
+ let t = this.tools.get(e.toolCallId);
309
+ t && (t.state = "awaiting-approval");
310
+ }
311
+ this.retryAction = () => this.decide(e), this.changed({
312
+ pendingApprovals: n,
313
+ status: "awaiting-approval"
314
+ });
315
+ }
299
316
  }
300
317
  approveAll() {
301
318
  return this.decide(this.state.pendingApprovals.map((e) => ({
@@ -321,7 +338,7 @@ var p = class {
321
338
  this.changed({ problem: null });
322
339
  }
323
340
  newConversation() {
324
- this.controller?.abort(), this.tools = /* @__PURE__ */ new Map(), this.retryAction = null, this.state = s(), this.changed();
341
+ this.generation += 1, this.controller?.abort(), this.tools = /* @__PURE__ */ new Map(), this.retryAction = null, this.state = s(), this.changed();
325
342
  }
326
343
  async listConversations(e = {}) {
327
344
  let t = new URLSearchParams({
@@ -331,29 +348,33 @@ var p = class {
331
348
  return this.json(`/v1/conversations?${t}`);
332
349
  }
333
350
  async openConversation(e) {
351
+ this.generation += 1;
352
+ let t = this.generation;
334
353
  this.controller?.abort(), this.changed({
335
354
  status: "loading",
336
355
  problem: null
337
356
  });
338
357
  try {
339
- let t = await this.json(`/v1/conversations/${encodeURIComponent(e)}`);
340
- for (let [e, n] of Object.entries(t.toolTitles ?? {})) typeof n == "string" && n && this.titles.set(e, n);
341
- let r = t.pendingApprovals ?? [];
342
- for (let e of r) e.title && this.titles.set(e.toolName, e.title);
343
- let i = n(t.messages ?? [], r, this.titles);
358
+ let r = await this.json(`/v1/conversations/${encodeURIComponent(e)}`);
359
+ if (t !== this.generation) return;
360
+ for (let [e, t] of Object.entries(r.toolTitles ?? {})) typeof t == "string" && t && this.titles.set(e, t);
361
+ let i = r.pendingApprovals ?? [];
362
+ for (let e of i) e.title && this.titles.set(e.toolName, e.title);
363
+ let a = n(r.messages ?? [], i, this.titles);
344
364
  this.tools = /* @__PURE__ */ new Map();
345
- for (let e of i) for (let t of e.parts) t.kind === "tool" && this.tools.set(t.toolCallId, t);
346
- this.retryAction = null, this.state = {
365
+ for (let e of a) for (let t of e.parts) t.kind === "tool" && this.tools.set(t.toolCallId, t);
366
+ this.keepPreviews(i), this.retryAction = null, this.state = {
347
367
  ...s(),
348
368
  conversationId: e,
349
- messages: i,
350
- pendingApprovals: r,
351
- status: r.length ? "awaiting-approval" : "idle"
369
+ messages: a,
370
+ pendingApprovals: i,
371
+ status: i.length ? "awaiting-approval" : "idle"
352
372
  }, this.changed();
353
- } catch (t) {
373
+ } catch (n) {
374
+ if (t !== this.generation) return;
354
375
  this.retryAction = () => this.openConversation(e), this.changed({
355
376
  status: "idle",
356
- problem: u(t)
377
+ problem: u(n)
357
378
  });
358
379
  }
359
380
  }
@@ -369,44 +390,53 @@ var p = class {
369
390
  return this.state.status === "sending" || this.state.status === "streaming" || this.state.status === "loading";
370
391
  }
371
392
  async turn(e, t) {
372
- let n = {
393
+ let n = this.generation, r = () => n === this.generation, i = {
373
394
  id: this.id("a"),
374
395
  role: "assistant",
375
396
  parts: []
376
397
  };
377
- this.state.messages.push(n), this.changed({ status: "sending" });
378
- let r = new AbortController();
379
- this.controller = r;
380
- let i;
398
+ this.state.messages.push(i), this.changed({ status: "sending" });
399
+ let o = new AbortController();
400
+ this.controller = o;
401
+ let s;
381
402
  try {
382
- if (i = await this.request(e, {
403
+ if (s = await this.request(e, {
383
404
  method: "POST",
384
405
  body: JSON.stringify(t),
385
406
  headers: { accept: "text/event-stream, application/json;q=0.9" },
386
- signal: r.signal
387
- }), !i.ok) throw await l(i);
388
- } catch (i) {
389
- if (this.drop(n), d(i)) {
390
- this.changed({ status: "idle" });
391
- return;
392
- }
393
- this.retryAction = () => this.turn(e, t), this.changed({
407
+ signal: o.signal
408
+ }), !s.ok) throw await l(s);
409
+ } catch (n) {
410
+ return this.controller === o && (this.controller = null), r() ? (this.drop(i), d(n) ? (this.changed({ status: "idle" }), "not-sent") : (this.retryAction = () => this.turn(e, t).then(() => void 0), this.changed({
394
411
  status: "idle",
395
- problem: u(i)
396
- }), this.controller === r && (this.controller = null);
397
- return;
412
+ problem: u(n)
413
+ }), "not-sent")) : "answered";
398
414
  }
415
+ if (!r()) return "answered";
399
416
  this.changed({ status: "streaming" });
400
- let o = !1, s = null, c = /* @__PURE__ */ new Map();
417
+ let c = !1, f = null, p = !1, m = /* @__PURE__ */ new Map();
401
418
  try {
402
- let e = i.body ? a(i.body, r.signal) : m(await i.text());
403
- for await (let t of e) t.type === "finish" ? o = !0 : t.type === "data-turn" && (s = t.data), this.apply(t, n, c), this.changed();
419
+ let e = s.body ? a(s.body, o.signal) : h(await s.text());
420
+ for await (let t of e) {
421
+ if (!r()) break;
422
+ t.type === "finish" ? c = !0 : t.type === "data-turn" && (f = t.data), this.apply(t, i, m), this.changed();
423
+ }
404
424
  } catch (e) {
405
- d(e) || this.changed({ problem: { code: "cut-off" } });
425
+ d(e) || (p = !0);
406
426
  } finally {
407
- this.controller === r && (this.controller = null);
427
+ this.controller === o && (this.controller = null);
428
+ }
429
+ if (!r()) return "answered";
430
+ if (i.parts.length || this.drop(i), f) this.finishTurn(f);
431
+ else {
432
+ let e = o.signal.aborted;
433
+ this.settleUnfinished(e), e || !p && c || this.state.problem || (this.state.problem = { code: "cut-off" }), this.changed({ status: this.state.pendingApprovals.length ? "awaiting-approval" : "idle" });
408
434
  }
409
- n.parts.length || this.drop(n), s ? this.finishTurn(s) : (r.signal.aborted || o || this.state.problem || this.changed({ problem: { code: "cut-off" } }), this.changed({ status: this.state.pendingApprovals.length ? "awaiting-approval" : "idle" }));
435
+ return "answered";
436
+ }
437
+ settleUnfinished(e) {
438
+ let t = e ? "Stopped before it finished." : "The reply was cut off before it finished.";
439
+ for (let e of this.tools.values()) (e.state === "input" || e.state === "running") && (e.state = "error", e.errorText = e.approvalId ? `${t} The result was not recorded; check before trying again.` : t);
410
440
  }
411
441
  drop(e) {
412
442
  this.state.messages = this.state.messages.filter((t) => t !== e);
@@ -414,6 +444,7 @@ var p = class {
414
444
  finishTurn(e) {
415
445
  let t = e.pendingApprovals ?? [];
416
446
  for (let e of t) e.title && this.titles.set(e.toolName, e.title);
447
+ this.keepPreviews(t);
417
448
  let n = this.state.problem;
418
449
  if (e.userTokenExpired) {
419
450
  n = { code: "token-expired" };
@@ -431,6 +462,12 @@ var p = class {
431
462
  status: t.length ? "awaiting-approval" : "idle"
432
463
  }), t.length && this.emit("approval-pending", { approvals: t }), this.emit("turn-end", e);
433
464
  }
465
+ keepPreviews(e) {
466
+ for (let t of e) {
467
+ let e = this.tools.get(t.toolCallId);
468
+ e && t.preview && (e.preview = t.preview);
469
+ }
470
+ }
434
471
  apply(e, t, n) {
435
472
  let r = e;
436
473
  switch (e.type) {
@@ -515,9 +552,9 @@ var p = class {
515
552
  return r;
516
553
  }
517
554
  };
518
- async function* m(e) {
555
+ async function* h(e) {
519
556
  yield* r(e);
520
557
  }
521
- export { a, r as i, u as n, n as o, i as r, p as t };
558
+ export { a, r as i, u as n, n as o, i as r, m as t };
522
559
 
523
- //# sourceMappingURL=core-BqhB9RhK.js.map
560
+ //# sourceMappingURL=core-BekZ5K2i.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core-BekZ5K2i.js","names":["textOf","content","p","outputOf","output","messagesFromHistory","out","tools","byApproval","a","pending","titles","assistant","n","current","m","messages","msg","last","title","part","waiting","parseSse","parser","SseParser","text","end","event","chunk","rest","data","line","payload","value","readChunks","decoder","reader","body","cancel","signal","done","SESSION_MARGIN_MS","empty","HttpError","detail","status","code","retryAfter","httpError","res","retry","problemFor","err","isAbort","sessionUsable","expires","s","now","snapshot","ChatClient","opts","listener","set","name","l","patch","prefix","started","session","headers","init","path","retried","again","message","user","conversationId","id","byId","decisions","d","reason","action","q","generation","controller","finished","turn","cut","texts","chunks","textChunks","stopped","why","problem","c","known"],"sources":["../src/core/history.ts","../src/core/sse.ts","../src/core/client.ts"],"sourcesContent":["// A saved conversation (`GET /v1/conversations/<id>`) as the widget's messages. Ghuri AI stores AI SDK model\n// messages: `user`, then `assistant` and `tool` messages until the next user message. Everything between two user\n// messages becomes one assistant message, as it was shown while it streamed.\nimport type { ChatMessage, MessagePart, PendingApproval, ToolPart } from './types'\n\ntype Part = { type?: string; [key: string]: any }\ntype ModelMessage = { role?: string; content?: string | Part[] }\n\nfunction textOf(content: ModelMessage['content']): string {\n if (typeof content === 'string') return content\n return (content ?? [])\n .filter((p) => p.type === 'text' && typeof p.text === 'string')\n .map((p) => p.text as string)\n .join('')\n}\n\nfunction outputOf(output: any): { state: ToolPart['state']; output?: unknown; errorText?: string } {\n switch (output?.type) {\n case 'execution-denied':\n return { state: 'denied', errorText: typeof output.reason === 'string' ? output.reason : undefined }\n case 'error-text':\n case 'error-json':\n return {\n state: 'error',\n errorText: typeof output.value === 'string' ? output.value : JSON.stringify(output.value),\n }\n case undefined:\n return { state: 'done', output }\n default:\n return { state: 'done', output: output.value }\n }\n}\n\n/**\n * Convert saved messages. `titles` (tool name → title) labels tool steps; saved messages do not carry titles, so it\n * holds what the widget learnt while streaming, plus the titles of `pending` approvals.\n */\nexport function messagesFromHistory(\n messages: ModelMessage[],\n pending: PendingApproval[] = [],\n titles: Map<string, string> = new Map(),\n): ChatMessage[] {\n const out: ChatMessage[] = []\n const tools = new Map<string, ToolPart>()\n const byApproval = new Map<string, ToolPart>()\n for (const a of pending) if (a.title) titles.set(a.toolName, a.title)\n let assistant: ChatMessage | null = null\n let n = 0\n\n const current = (): ChatMessage => {\n if (!assistant) {\n assistant = { id: `h${n++}`, role: 'assistant', parts: [] }\n out.push(assistant)\n }\n return assistant\n }\n\n for (const m of messages) {\n if (m.role === 'user') {\n assistant = null\n out.push({\n id: `h${n++}`,\n role: 'user',\n parts: [{ kind: 'text', id: `h${n++}`, text: textOf(m.content) }],\n })\n continue\n }\n if (m.role === 'assistant') {\n const msg = current()\n const content: Part[] =\n typeof m.content === 'string' ? [{ type: 'text', text: m.content }] : (m.content ?? [])\n for (const p of content) {\n if (p.type === 'text' && typeof p.text === 'string' && p.text) {\n const last = msg.parts.at(-1)\n if (last?.kind === 'text') last.text += p.text\n else msg.parts.push({ kind: 'text', id: `h${n++}`, text: p.text })\n } else if (p.type === 'tool-call' && typeof p.toolCallId === 'string') {\n const title = titles.get(p.toolName)\n const part: ToolPart = {\n kind: 'tool',\n toolCallId: p.toolCallId,\n toolName: String(p.toolName ?? ''),\n ...(title ? { title } : {}),\n input: p.input,\n state: 'running',\n }\n tools.set(part.toolCallId, part)\n msg.parts.push(part)\n } else if (p.type === 'tool-approval-request' && typeof p.toolCallId === 'string') {\n const part = tools.get(p.toolCallId)\n if (part) {\n part.state = 'awaiting-approval'\n part.approvalId = p.approvalId\n byApproval.set(p.approvalId, part)\n }\n }\n }\n continue\n }\n if (m.role === 'tool' && Array.isArray(m.content)) {\n for (const p of m.content) {\n if (p.type === 'tool-approval-response') {\n const part = byApproval.get(p.approvalId)\n if (part && part.state === 'awaiting-approval') part.state = p.approved ? 'running' : 'denied'\n } else if (p.type === 'tool-result') {\n const part = tools.get(p.toolCallId)\n if (part) Object.assign(part, outputOf(p.output))\n }\n }\n }\n }\n\n // A call still waiting is only waiting if the server says so (anything else was closed by a later message).\n const waiting = new Set(pending.map((a) => a.toolCallId))\n for (const part of tools.values()) {\n if (part.state === 'awaiting-approval' && !waiting.has(part.toolCallId)) part.state = 'denied'\n }\n return out.filter((m) => m.parts.length > 0) as ChatMessage[]\n}\n\n/** Every part of `messages`, for lookups by tool call id. */\nexport function toolParts(messages: ChatMessage[]): Map<string, ToolPart> {\n const out = new Map<string, ToolPart>()\n for (const m of messages)\n for (const p of m.parts as MessagePart[]) if (p.kind === 'tool') out.set(p.toolCallId, p)\n return out\n}\n","// Reading Ghuri AI's reply stream: Server-Sent Events whose `data:` lines are AI SDK UI message chunks\n// (`{\"type\":\"text-delta\",…}`), ending with `data: [DONE]`. Written here rather than taken from the AI SDK so the\n// logic layer has no dependencies and the same rules can be ported to the Kotlin library.\n\n/** One parsed chunk. Unknown types are passed through and ignored by the client. */\nexport type StreamChunk = { type: string; [key: string]: unknown }\n\n/** Parse a complete SSE text (tests, or a body read in one go). */\nexport function parseSse(text: string): StreamChunk[] {\n const parser = new SseParser()\n const out = parser.push(text)\n out.push(...parser.end())\n return out\n}\n\n/**\n * An incremental SSE parser: feed it text as it arrives, get back the chunks whose events are complete. Handles events\n * split across reads, `\\r\\n` line endings, comment lines and several `data:` lines per event (joined with `\\n`).\n */\nexport class SseParser {\n private buffer = ''\n /** A `\\r` that ended the last read: it may be the first half of a `\\r\\n` split across two reads. */\n private carry = ''\n /** True once `data: [DONE]` was seen. */\n done = false\n\n push(text: string): StreamChunk[] {\n let t = this.carry + text\n this.carry = ''\n if (t.endsWith('\\r')) {\n this.carry = '\\r'\n t = t.slice(0, -1)\n }\n this.buffer += t.replace(/\\r\\n?/g, '\\n')\n const out: StreamChunk[] = []\n let end = this.buffer.indexOf('\\n\\n')\n while (end !== -1) {\n const event = this.buffer.slice(0, end)\n this.buffer = this.buffer.slice(end + 2)\n const chunk = this.parseEvent(event)\n if (chunk) out.push(chunk)\n end = this.buffer.indexOf('\\n\\n')\n }\n return out\n }\n\n /** The stream ended: parse what is left (an event without its blank line). */\n end(): StreamChunk[] {\n this.carry = ''\n const rest = this.buffer.trim()\n this.buffer = ''\n if (!rest) return []\n const chunk = this.parseEvent(rest)\n return chunk ? [chunk] : []\n }\n\n private parseEvent(event: string): StreamChunk | null {\n const data: string[] = []\n for (const line of event.split('\\n')) {\n if (line.startsWith('data:')) data.push(line.slice(line.startsWith('data: ') ? 6 : 5))\n }\n if (!data.length) return null\n const payload = data.join('\\n')\n if (payload === '[DONE]') {\n this.done = true\n return null\n }\n try {\n const value = JSON.parse(payload)\n return value && typeof value === 'object' && typeof value.type === 'string'\n ? (value as StreamChunk)\n : null\n } catch {\n return null\n }\n }\n}\n\n/** Read a fetch response body as stream chunks, as they arrive. */\nexport async function* readChunks(\n body: ReadableStream<Uint8Array>,\n signal?: AbortSignal,\n): AsyncGenerator<StreamChunk> {\n const parser = new SseParser()\n const decoder = new TextDecoder()\n const reader = body.getReader()\n // Stopping must also end a read that is waiting for the next bytes.\n const cancel = () => void reader.cancel().catch(() => {})\n signal?.addEventListener('abort', cancel, { once: true })\n try {\n while (true) {\n if (signal?.aborted) return\n const { value, done } = await reader.read()\n if (done) break\n for (const chunk of parser.push(decoder.decode(value, { stream: true }))) yield chunk\n }\n for (const chunk of parser.push(decoder.decode())) yield chunk\n for (const chunk of parser.end()) yield chunk\n } finally {\n signal?.removeEventListener('abort', cancel)\n reader.releaseLock()\n }\n}\n","// The widget's logic layer: one chat with Ghuri AI for one signed-in user. It starts and renews the session through\n// the product's backend, sends messages, reads the streamed reply, handles confirmations, history and every error,\n// and publishes plain state for a UI to draw. It never sees the app key or the user's MCP token; the session token\n// lives in memory only.\nimport { messagesFromHistory } from './history'\nimport { parseSse, readChunks, type StreamChunk } from './sse'\nimport type {\n ChatClientOptions,\n ChatEvents,\n ChatMessage,\n ChatState,\n ConversationSummary,\n Decision,\n PendingApproval,\n Problem,\n SessionInfo,\n TextPart,\n ToolPart,\n TurnResult,\n} from './types'\n\n/** A session is renewed this long before it expires, so a request never starts on a session about to end. */\nconst SESSION_MARGIN_MS = 30_000\n\ntype Listener = (state: ChatState) => void\ntype EventListener<K extends keyof ChatEvents> = (event: ChatEvents[K]) => void\n\n/** A fresh empty state (new arrays every time: the state is changed in place). */\nfunction empty(): ChatState {\n return {\n status: 'idle',\n conversationId: null,\n messages: [],\n pendingApprovals: [],\n problem: null,\n lastTurn: null,\n }\n}\n\n/** A request answered with an error status, kept so the caller can turn it into a `Problem`. */\nclass HttpError extends Error {\n constructor(\n readonly status: number,\n readonly code: string,\n readonly detail: string,\n readonly retryAfter?: number,\n ) {\n super(detail || `HTTP ${status}`)\n }\n}\n\nasync function httpError(res: Response): Promise<HttpError> {\n let body: any = null\n try {\n body = await res.json()\n } catch {\n // not JSON\n }\n const retry = Number(res.headers.get('retry-after'))\n return new HttpError(\n res.status,\n typeof body?.code === 'string' ? body.code : '',\n typeof body?.detail === 'string' ? body.detail : '',\n Number.isFinite(retry) && retry > 0 ? retry : undefined,\n )\n}\n\n/** What the user is told about a failed request. */\nexport function problemFor(err: unknown): Problem {\n if (!(err instanceof HttpError)) return { code: 'unavailable' }\n const { status, code, detail } = err\n if (status === 429) return { code: 'throttled', ...(err.retryAfter ? { retryAfter: err.retryAfter } : {}) }\n if (code === 'turn_in_progress') return { code: 'in-progress' }\n if (code === 'conversation_too_long') return { code: 'conversation-full' }\n if (code === 'mcp_forbidden') return { code: 'forbidden' }\n if (code === 'mcp_unavailable' || status === 502) return { code: 'store-unreachable' }\n if (code === 'model_unavailable' || code === 'no_active_profile' || status === 503)\n return { code: 'unavailable' }\n return { code: 'failed', ...(detail ? { message: detail } : {}) }\n}\n\nfunction isAbort(err: unknown): boolean {\n return err instanceof DOMException ? err.name === 'AbortError' : (err as Error)?.name === 'AbortError'\n}\n\n/**\n * Whether a session is safe to use for a new request. An expiry that cannot be read is trusted until Ghuri AI says\n * otherwise (a 401 starts a new session), rather than starting a new session on every request.\n */\nfunction sessionUsable(s: SessionInfo, now: number): boolean {\n const expires = new Date(s.expiresAt).getTime()\n return Number.isNaN(expires) || expires - SESSION_MARGIN_MS > now\n}\n\n/** Copy the state so every change has new objects (React's useSyncExternalStore, Lit's change detection). */\nfunction snapshot(s: ChatState): ChatState {\n return {\n ...s,\n messages: s.messages.map((m) => ({ ...m, parts: m.parts.map((p) => ({ ...p })) })),\n pendingApprovals: [...s.pendingApprovals],\n }\n}\n\nexport class ChatClient {\n private readonly opts: ChatClientOptions\n private state: ChatState = empty()\n private view: ChatState = snapshot(this.state)\n private readonly listeners = new Set<Listener>()\n private readonly events = new Map<keyof ChatEvents, Set<(e: any) => void>>()\n private session: SessionInfo | null = null\n private starting: Promise<SessionInfo> | null = null\n private controller: AbortController | null = null\n /** Every tool step of the open conversation, by tool call id (an approval's reply finishes earlier steps). */\n private tools = new Map<string, ToolPart>()\n /** Tool name → title, learnt from the stream (saved messages do not carry titles). */\n private readonly titles = new Map<string, string>()\n private retryAction: (() => Promise<void>) | null = null\n /**\n * Bumped whenever the open conversation is replaced (new, opened, ended). A turn or a load that started under an\n * older generation stops touching the state, so a reply that was replaced cannot overwrite what replaced it.\n */\n private generation = 0\n private seq = 0\n\n constructor(opts: ChatClientOptions) {\n this.opts = { ...opts, apiUrl: opts.apiUrl.replace(/\\/+$/, '') }\n }\n\n // --- state and events ----------------------------------------------------------------------------------------\n\n getState(): ChatState {\n return this.view\n }\n\n /** Called on every change; returns the unsubscribe function. */\n subscribe(listener: Listener): () => void {\n this.listeners.add(listener)\n return () => this.listeners.delete(listener)\n }\n\n on<K extends keyof ChatEvents>(name: K, listener: EventListener<K>): () => void {\n let set = this.events.get(name)\n if (!set) {\n set = new Set()\n this.events.set(name, set)\n }\n set.add(listener)\n return () => set.delete(listener)\n }\n\n private emit<K extends keyof ChatEvents>(name: K, event: ChatEvents[K]): void {\n for (const l of this.events.get(name) ?? []) l(event)\n }\n\n private changed(patch: Partial<ChatState> = {}): void {\n Object.assign(this.state, patch)\n this.view = snapshot(this.state)\n for (const l of this.listeners) l(this.view)\n }\n\n private id(prefix: string): string {\n this.seq += 1\n return `${prefix}${this.seq}`\n }\n\n // --- sessions ------------------------------------------------------------------------------------------------\n\n private now(): number {\n return (this.opts.now ?? Date.now)()\n }\n\n private async ensureSession(): Promise<SessionInfo> {\n const s = this.session\n if (s && sessionUsable(s, this.now())) return s\n this.session = null\n if (!this.starting) {\n this.starting = this.opts\n .startSession()\n .then((started) => {\n this.session = started\n return started\n })\n .finally(() => {\n this.starting = null\n })\n }\n return this.starting\n }\n\n /**\n * A request to Ghuri AI with the session token. A `401` is handled once: an expired user token is refreshed through\n * the product (or, if the product's session is gone, a new session started), an expired session is replaced; then\n * the request is sent again.\n */\n private async request(path: string, init: RequestInit = {}, retried = false): Promise<Response> {\n const session = await this.ensureSession()\n const headers = new Headers(init.headers)\n headers.set('authorization', `Bearer ${session.sessionToken}`)\n if (init.body !== undefined) headers.set('content-type', 'application/json')\n const res = await (this.opts.fetch ?? fetch)(`${this.opts.apiUrl}${path}`, { ...init, headers })\n if (res.status !== 401 || retried) return res\n const err = await httpError(res)\n this.changed({ problem: { code: 'reconnecting' } })\n if (err.code === 'user_token_expired') {\n try {\n await this.opts.refreshUserToken(session.sessionId)\n } catch {\n this.session = null // the product's session is gone: start a new one\n }\n } else {\n this.session = null\n }\n const again = await this.request(path, init, true)\n if (this.state.problem?.code === 'reconnecting') this.changed({ problem: null })\n return again\n }\n\n private async json<T>(path: string, init: RequestInit = {}): Promise<T> {\n const res = await this.request(path, init)\n if (!res.ok) throw await httpError(res)\n return (await res.json()) as T\n }\n\n // --- actions -------------------------------------------------------------------------------------------------\n\n /** Send a message. Waiting changes, if any, are cancelled by it (Ghuri AI closes them). */\n async send(text: string): Promise<void> {\n const message = text.trim()\n if (!message || this.busy()) return\n for (const a of this.state.pendingApprovals) {\n const part = this.tools.get(a.toolCallId)\n if (part) part.state = 'denied'\n }\n const user: ChatMessage = {\n id: this.id('u'),\n role: 'user',\n parts: [{ kind: 'text', id: this.id('t'), text: message }],\n }\n this.state.messages.push(user)\n this.changed({ pendingApprovals: [], problem: null })\n const conversationId = this.state.conversationId\n await this.turn('/v1/chat', { message, ...(conversationId ? { conversationId } : {}) })\n }\n\n /** Confirm or cancel the waiting changes: one decision for each, sent together. */\n async decide(decisions: Decision[]): Promise<void> {\n const id = this.state.conversationId\n if (!id || this.busy() || !this.state.pendingApprovals.length) return\n const pending = this.state.pendingApprovals\n const byId = new Map(decisions.map((d) => [d.approvalId, d]))\n for (const a of pending) {\n const part = this.tools.get(a.toolCallId)\n if (part) part.state = byId.get(a.approvalId)?.approved ? 'running' : 'denied'\n }\n this.changed({ pendingApprovals: [], problem: null })\n const outcome = await this.turn(`/v1/conversations/${encodeURIComponent(id)}/approvals`, { decisions })\n if (outcome !== 'not-sent') return\n // The decisions never reached Ghuri AI (or it refused them): the changes are still waiting, as they were.\n for (const a of pending) {\n const part = this.tools.get(a.toolCallId)\n if (part) part.state = 'awaiting-approval'\n }\n this.retryAction = () => this.decide(decisions)\n this.changed({ pendingApprovals: pending, status: 'awaiting-approval' })\n }\n\n /** Confirm every waiting change. */\n approveAll(): Promise<void> {\n return this.decide(this.state.pendingApprovals.map((a) => ({ approvalId: a.approvalId, approved: true })))\n }\n\n /** Cancel every waiting change. */\n rejectAll(reason?: string): Promise<void> {\n return this.decide(\n this.state.pendingApprovals.map((a) => ({\n approvalId: a.approvalId,\n approved: false,\n ...(reason ? { reason } : {}),\n })),\n )\n }\n\n /** Stop the reply being written (Ghuri AI stops the turn; what finished is kept). */\n stop(): void {\n this.controller?.abort()\n }\n\n /** Run the action that failed again (Try again). */\n async retry(): Promise<void> {\n const action = this.retryAction\n if (!action || this.busy()) return\n this.retryAction = null\n this.changed({ problem: null })\n await action()\n }\n\n dismissProblem(): void {\n this.changed({ problem: null })\n }\n\n /** Start a new conversation (the next message creates it). */\n newConversation(): void {\n this.generation += 1\n this.controller?.abort()\n this.tools = new Map()\n this.retryAction = null\n this.state = empty()\n this.changed()\n }\n\n /** The user's conversations in this product and tenant, newest first. */\n async listConversations(opts: { limit?: number; offset?: number } = {}): Promise<{\n count: number\n results: ConversationSummary[]\n }> {\n const q = new URLSearchParams({ limit: String(opts.limit ?? 30), offset: String(opts.offset ?? 0) })\n return this.json(`/v1/conversations?${q}`)\n }\n\n /** Open a saved conversation, including any change still waiting for a decision. */\n async openConversation(id: string): Promise<void> {\n this.generation += 1\n const generation = this.generation\n this.controller?.abort()\n this.changed({ status: 'loading', problem: null })\n try {\n const data = await this.json<{\n messages: any[]\n pendingApprovals: PendingApproval[]\n toolTitles?: Record<string, string>\n }>(`/v1/conversations/${encodeURIComponent(id)}`)\n if (generation !== this.generation) return // replaced while it loaded\n // Saved messages carry no titles; the server keeps the ones this conversation's tools had.\n for (const [name, title] of Object.entries(data.toolTitles ?? {}))\n if (typeof title === 'string' && title) this.titles.set(name, title)\n const pending = data.pendingApprovals ?? []\n for (const a of pending) if (a.title) this.titles.set(a.toolName, a.title)\n const messages = messagesFromHistory(data.messages ?? [], pending, this.titles)\n this.tools = new Map()\n for (const m of messages)\n for (const p of m.parts) if (p.kind === 'tool') this.tools.set(p.toolCallId, p)\n this.keepPreviews(pending)\n this.retryAction = null\n this.state = {\n ...empty(),\n conversationId: id,\n messages,\n pendingApprovals: pending,\n status: pending.length ? 'awaiting-approval' : 'idle',\n }\n this.changed()\n } catch (err) {\n if (generation !== this.generation) return\n this.retryAction = () => this.openConversation(id)\n this.changed({ status: 'idle', problem: problemFor(err) })\n }\n }\n\n /** Load the open conversation again (after a reply was cut off). */\n async reload(): Promise<void> {\n if (this.state.conversationId) await this.openConversation(this.state.conversationId)\n }\n\n /** End the session through the product (logout, store switch) and forget everything. */\n async end(): Promise<void> {\n this.controller?.abort()\n const session = this.session\n this.session = null\n this.newConversation()\n if (session) await this.opts.endSession?.(session.sessionId)\n }\n\n private busy(): boolean {\n return (\n this.state.status === 'sending' || this.state.status === 'streaming' || this.state.status === 'loading'\n )\n }\n\n // --- a turn --------------------------------------------------------------------------------------------------\n\n /**\n * Post a message or decisions and read the streamed reply into a new assistant message. Returns `not-sent` when the\n * request failed or was refused before a reply started (nothing happened on the server), else `answered`.\n */\n private async turn(path: string, body: unknown): Promise<'answered' | 'not-sent'> {\n const generation = this.generation\n const current = () => generation === this.generation\n const assistant: ChatMessage = { id: this.id('a'), role: 'assistant', parts: [] }\n this.state.messages.push(assistant)\n this.changed({ status: 'sending' })\n const controller = new AbortController()\n this.controller = controller\n let res: Response\n try {\n res = await this.request(path, {\n method: 'POST',\n body: JSON.stringify(body),\n // JSON as a fallback: servers that negotiate content types strictly still answer, and still stream.\n headers: { accept: 'text/event-stream, application/json;q=0.9' },\n signal: controller.signal,\n })\n if (!res.ok) throw await httpError(res)\n } catch (err) {\n if (this.controller === controller) this.controller = null\n if (!current()) return 'answered' // replaced meanwhile: leave the new conversation alone\n this.drop(assistant)\n if (isAbort(err)) {\n this.changed({ status: 'idle' })\n return 'not-sent'\n }\n this.retryAction = () => this.turn(path, body).then(() => undefined)\n this.changed({ status: 'idle', problem: problemFor(err) })\n return 'not-sent'\n }\n\n if (!current()) return 'answered'\n this.changed({ status: 'streaming' })\n let finished = false\n let turn: TurnResult | null = null\n let cut = false\n const texts = new Map<string, TextPart>()\n try {\n const chunks = res.body ? readChunks(res.body, controller.signal) : textChunks(await res.text())\n for await (const chunk of chunks) {\n if (!current()) break\n if (chunk.type === 'finish') finished = true\n else if (chunk.type === 'data-turn') turn = chunk.data as TurnResult\n this.apply(chunk, assistant, texts)\n this.changed()\n }\n } catch (err) {\n if (!isAbort(err)) cut = true\n } finally {\n if (this.controller === controller) this.controller = null\n }\n if (!current()) return 'answered'\n if (!assistant.parts.length) this.drop(assistant)\n\n if (turn) {\n this.finishTurn(turn)\n } else {\n // Stopped by the user, or the connection dropped before the reply finished.\n const stopped = controller.signal.aborted\n this.settleUnfinished(stopped)\n if (!stopped && (cut || !finished) && !this.state.problem) this.state.problem = { code: 'cut-off' }\n this.changed({ status: this.state.pendingApprovals.length ? 'awaiting-approval' : 'idle' })\n }\n return 'answered'\n }\n\n /**\n * Steps still writing or running when a reply ended early never get their result: mark them, so nothing spins\n * forever. A confirmed change in that state may or may not have run (\"outcome unknown\").\n */\n private settleUnfinished(stopped: boolean): void {\n const why = stopped ? 'Stopped before it finished.' : 'The reply was cut off before it finished.'\n for (const part of this.tools.values()) {\n if (part.state !== 'input' && part.state !== 'running') continue\n part.state = 'error'\n part.errorText = part.approvalId\n ? `${why} The result was not recorded; check before trying again.`\n : why\n }\n }\n\n private drop(message: ChatMessage): void {\n this.state.messages = this.state.messages.filter((m) => m !== message)\n }\n\n private finishTurn(turn: TurnResult): void {\n const pending = turn.pendingApprovals ?? []\n for (const a of pending) if (a.title) this.titles.set(a.toolName, a.title)\n this.keepPreviews(pending)\n let problem: Problem | null = this.state.problem\n if (turn.userTokenExpired) {\n problem = { code: 'token-expired' }\n // Renew the token now, so \"Continue\" works; a failure here is handled on the next request.\n const s = this.session\n if (s) this.opts.refreshUserToken(s.sessionId).catch(() => (this.session = null))\n } else if (turn.status === 'error') {\n problem =\n turn.limitReached === 'conversation'\n ? { code: 'conversation-full' }\n : { code: 'failed', ...(turn.error ? { message: turn.error } : {}) }\n }\n this.changed({\n conversationId: turn.conversationId ?? this.state.conversationId,\n pendingApprovals: pending,\n lastTurn: turn,\n problem,\n status: pending.length ? 'awaiting-approval' : 'idle',\n })\n if (pending.length) this.emit('approval-pending', { approvals: pending })\n this.emit('turn-end', turn)\n }\n\n /** Copy each waiting change's preview onto its step, so the record after the decision still names it. */\n private keepPreviews(pending: PendingApproval[]): void {\n for (const a of pending) {\n const part = this.tools.get(a.toolCallId)\n if (part && a.preview) part.preview = a.preview\n }\n }\n\n /** Apply one stream chunk to the reply being written. */\n private apply(chunk: StreamChunk, assistant: ChatMessage, texts: Map<string, TextPart>): void {\n const c = chunk as any\n switch (chunk.type) {\n case 'start': {\n const id = c.messageMetadata?.conversationId\n if (typeof id === 'string') this.state.conversationId = id\n return\n }\n case 'text-start': {\n const part: TextPart = { kind: 'text', id: this.id('t'), text: '' }\n texts.set(String(c.id), part)\n assistant.parts.push(part)\n return\n }\n case 'text-delta': {\n let part = texts.get(String(c.id))\n if (!part) {\n part = { kind: 'text', id: this.id('t'), text: '' }\n texts.set(String(c.id), part)\n assistant.parts.push(part)\n }\n part.text += String(c.delta ?? '')\n return\n }\n case 'tool-input-start':\n case 'tool-input-available': {\n const part = this.toolPart(c, assistant)\n if (chunk.type === 'tool-input-available') {\n part.input = c.input\n if (part.state === 'input') part.state = 'running'\n }\n return\n }\n case 'tool-input-error': {\n const part = this.toolPart(c, assistant)\n part.state = 'error'\n part.errorText = String(c.errorText ?? '')\n return\n }\n case 'tool-approval-request': {\n const part = this.tools.get(String(c.toolCallId))\n if (part) {\n part.state = 'awaiting-approval'\n part.approvalId = String(c.approvalId)\n }\n return\n }\n case 'tool-output-available':\n case 'tool-output-error': {\n const part = this.tools.get(String(c.toolCallId))\n if (!part) return\n if (chunk.type === 'tool-output-available') {\n part.state = 'done'\n part.output = c.output\n } else {\n part.state = 'error'\n part.errorText = String(c.errorText ?? '')\n }\n this.emit('tool-result', {\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n ...(part.title ? { title: part.title } : {}),\n input: part.input,\n ...(part.state === 'done' ? { output: part.output } : { error: part.errorText }),\n })\n return\n }\n case 'tool-output-denied': {\n const part = this.tools.get(String(c.toolCallId))\n if (part) part.state = 'denied'\n return\n }\n case 'error':\n this.state.problem = { code: 'failed', ...(c.errorText ? { message: String(c.errorText) } : {}) }\n return\n default:\n return // start-step, finish-step, text-end, tool-input-delta, finish, data-turn, unknown types\n }\n }\n\n private toolPart(c: any, assistant: ChatMessage): ToolPart {\n const id = String(c.toolCallId)\n let part = this.tools.get(id)\n if (!part) {\n part = { kind: 'tool', toolCallId: id, toolName: String(c.toolName ?? ''), state: 'input' }\n this.tools.set(id, part)\n assistant.parts.push(part)\n }\n if (typeof c.title === 'string' && c.title) {\n part.title = c.title\n this.titles.set(part.toolName, c.title)\n } else if (!part.title) {\n const known = this.titles.get(part.toolName)\n if (known) part.title = known\n }\n return part\n }\n}\n\nasync function* textChunks(text: string): AsyncGenerator<StreamChunk> {\n yield* parseSse(text)\n}\n"],"mappings":";AAQA,SAASA,EAAO,GAA0C;CAExD,OADI,OAAOC,KAAY,WAAiBA,KAChCA,KAAW,CAAC,EAAA,CACjB,QAAQ,MAAMC,EAAE,SAAS,UAAU,OAAOA,EAAE,QAAS,QAAQ,CAAC,CAC9D,KAAK,MAAMA,EAAE,IAAc,CAAC,CAC5B,KAAK,EAAE;AACZ;AAEA,SAASC,EAAS,GAAiF;CACjG,QAAQC,GAAQ,MAAhB;EACE,KAAK,oBACH,OAAO;GAAE,OAAO;GAAU,WAAW,OAAOA,EAAO,UAAW,WAAWA,EAAO,SAAS,KAAA;EAAU;EACrG,KAAK;EACL,KAAK,cACH,OAAO;GACL,OAAO;GACP,WAAW,OAAOA,EAAO,SAAU,WAAWA,EAAO,QAAQ,KAAK,UAAUA,EAAO,KAAK;EAC1F;EACF,KAAK,KAAA,GACH,OAAO;GAAE,OAAO;GAAQ;EAAO;EACjC,SACE,OAAO;GAAE,OAAO;GAAQ,QAAQA,EAAO;EAAM;CACjD;AACF;AAMA,SAAgBC,EACd,GACA,IAA6B,CAAC,GAC9B,oBAA8B,IAAI,IAAI,GACvB;CACf,IAAMC,IAAqB,CAAC,GACtBC,oBAAQ,IAAI,IAAsB,GAClCC,oBAAa,IAAI,IAAs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EAAK;KACZ,GAAIA,EAAK,UAAU,SAAS,EAAE,QAAQA,EAAK,OAAO,IAAI,EAAE,OAAOA,EAAK,UAAU;IAChF,CAAC;IACD;GACF;GACA,KAAK,sBAAsB;IACzB,IAAMA,IAAO,KAAK,MAAM,IAAI,OAAO2E,EAAE,UAAU,CAAC;IAChD,AAAI3E,MAAM,EAAK,QAAQ;IACvB;GACF;GACA,KAAK;IACH,KAAK,MAAM,UAAU;KAAE,MAAM;KAAU,GAAI2E,EAAE,YAAY,EAAE,SAAS,OAAOA,EAAE,SAAS,EAAE,IAAI,CAAC;IAAG;IAChG;GACF,SACE;EACJ;CACF;CAEA,SAAiB,GAAQ,GAAkC;EACzD,IAAMlB,IAAK,OAAOkB,EAAE,UAAU,GAC1B3E,IAAO,KAAK,MAAM,IAAIyD,CAAE;EAM5B,IALKzD,MACH,IAAO;GAAE,MAAM;GAAQ,YAAYyD;GAAI,UAAU,OAAOkB,EAAE,YAAY,EAAE;GAAG,OAAO;EAAQ,GAC1F,KAAK,MAAM,IAAIlB,GAAIzD,CAAI,GACvBR,EAAU,MAAM,KAAKQ,CAAI,IAEvB,OAAO2E,EAAE,SAAU,YAAYA,EAAE,OAEnC,AADA,EAAK,QAAQA,EAAE,OACf,KAAK,OAAO,IAAI3E,EAAK,UAAU2E,EAAE,KAAK;OACjC,IAAI,CAAC3E,EAAK,OAAO;GACtB,IAAM4E,IAAQ,KAAK,OAAO,IAAI5E,EAAK,QAAQ;GAC3C,AAAI4E,MAAO,EAAK,QAAQA;EAC1B;EACA,OAAO5E;CACT;AACF;AAEA,gBAAgBuE,EAAW,GAA2C;CACpE,OAAOrE,EAASG,CAAI;AACtB"}
package/dist/core.js CHANGED
@@ -1 +1 @@
1
- export { t as ChatClient, r as SseParser, o as messagesFromHistory, i as parseSse, n as problemFor, a as readChunks } from "./core-BqhB9RhK.js";
1
+ export { t as ChatClient, r as SseParser, o as messagesFromHistory, i as parseSse, n as problemFor, a as readChunks } from "./core-BekZ5K2i.js";
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import { a as e, i as t, n, o as r, r as i, t as a } from "./core-BqhB9RhK.js";
2
- import { t as o } from "./src-DcFnX61O.js";
1
+ import { a as e, i as t, n, o as r, r as i, t as a } from "./core-BekZ5K2i.js";
2
+ import { t as o } from "./src-I1h_3l4Z.js";
3
3
  export { a as ChatClient, o as GhuriChatElement, i as SseParser, r as messagesFromHistory, t as parseSse, n as problemFor, e as readChunks };
package/dist/react.js CHANGED
@@ -1,4 +1,4 @@
1
- import "./src-DcFnX61O.js";
1
+ import "./src-I1h_3l4Z.js";
2
2
  import { createElement as e, forwardRef as t, useEffect as n, useImperativeHandle as r, useRef as i, useState as a } from "react";
3
3
  import { createPortal as o } from "react-dom";
4
4
  // src/react.tsx