@runtypelabs/persona 3.14.0 → 3.15.1

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.
@@ -3562,6 +3562,94 @@ var createXmlParser = () => {
3562
3562
  };
3563
3563
  };
3564
3564
 
3565
+ // src/utils/sequence-buffer.ts
3566
+ var SequenceReorderBuffer = class {
3567
+ constructor(emitter, gapTimeoutMs = 50) {
3568
+ this.nextExpectedSeq = null;
3569
+ this.buffer = /* @__PURE__ */ new Map();
3570
+ this.flushTimer = null;
3571
+ this.emitter = emitter;
3572
+ this.gapTimeoutMs = gapTimeoutMs;
3573
+ }
3574
+ push(payloadType, payload) {
3575
+ var _a, _b, _c;
3576
+ const seq = (_c = (_a = payload == null ? void 0 : payload.seq) != null ? _a : payload == null ? void 0 : payload.sequenceIndex) != null ? _c : (_b = payload == null ? void 0 : payload.agentContext) == null ? void 0 : _b.seq;
3577
+ if (seq === void 0 || seq === null) {
3578
+ if (this.buffer.size > 0) {
3579
+ this.flushAll();
3580
+ }
3581
+ this.emitter(payloadType, payload);
3582
+ return;
3583
+ }
3584
+ if (this.nextExpectedSeq === null) {
3585
+ this.nextExpectedSeq = 1;
3586
+ }
3587
+ if (seq === this.nextExpectedSeq) {
3588
+ this.emitter(payloadType, payload);
3589
+ this.nextExpectedSeq = seq + 1;
3590
+ this.drainConsecutive();
3591
+ return;
3592
+ }
3593
+ if (seq < this.nextExpectedSeq) {
3594
+ this.emitter(payloadType, payload);
3595
+ return;
3596
+ }
3597
+ const existing = this.buffer.get(seq);
3598
+ if (existing !== void 0) {
3599
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
3600
+ console.warn(
3601
+ `[persona] SequenceReorderBuffer: duplicate seq=${seq} (${existing.payloadType} vs ${payloadType}); emitting earlier event out-of-order to avoid loss`
3602
+ );
3603
+ }
3604
+ this.emitter(existing.payloadType, existing.payload);
3605
+ }
3606
+ this.buffer.set(seq, { payloadType, payload, seq });
3607
+ this.startGapTimer();
3608
+ }
3609
+ drainConsecutive() {
3610
+ while (this.buffer.has(this.nextExpectedSeq)) {
3611
+ const event = this.buffer.get(this.nextExpectedSeq);
3612
+ this.buffer.delete(this.nextExpectedSeq);
3613
+ this.emitter(event.payloadType, event.payload);
3614
+ this.nextExpectedSeq++;
3615
+ }
3616
+ if (this.buffer.size === 0) {
3617
+ this.clearGapTimer();
3618
+ }
3619
+ }
3620
+ startGapTimer() {
3621
+ if (this.flushTimer !== null) return;
3622
+ this.flushTimer = setTimeout(() => {
3623
+ this.flushAll();
3624
+ }, this.gapTimeoutMs);
3625
+ }
3626
+ clearGapTimer() {
3627
+ if (this.flushTimer !== null) {
3628
+ clearTimeout(this.flushTimer);
3629
+ this.flushTimer = null;
3630
+ }
3631
+ }
3632
+ flushAll() {
3633
+ this.clearGapTimer();
3634
+ if (this.buffer.size === 0) return;
3635
+ const sorted = [...this.buffer.entries()].sort((a, b) => a[0] - b[0]);
3636
+ for (const [seq, event] of sorted) {
3637
+ this.buffer.delete(seq);
3638
+ this.emitter(event.payloadType, event.payload);
3639
+ }
3640
+ if (sorted.length > 0) {
3641
+ this.nextExpectedSeq = sorted[sorted.length - 1][0] + 1;
3642
+ }
3643
+ }
3644
+ destroy() {
3645
+ this.clearGapTimer();
3646
+ this.buffer.clear();
3647
+ }
3648
+ flushPending() {
3649
+ this.flushAll();
3650
+ }
3651
+ };
3652
+
3565
3653
  // src/client.ts
3566
3654
  var DEFAULT_ENDPOINT = "https://api.runtype.com/v1/dispatch";
3567
3655
  var DEFAULT_CLIENT_API_BASE = "https://api.runtype.com";
@@ -4329,7 +4417,7 @@ var AgentWidgetClient = class {
4329
4417
  }
4330
4418
  }
4331
4419
  async streamResponse(body, onEvent, assistantMessageId) {
4332
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R, _S, _T, _U, _V, _W, _X, _Y, _Z, __, _$, _aa, _ba, _ca, _da, _ea, _fa, _ga, _ha, _ia, _ja, _ka, _la, _ma, _na, _oa, _pa, _qa, _ra, _sa, _ta, _ua, _va, _wa, _xa, _ya, _za, _Aa, _Ba, _Ca, _Da, _Ea, _Fa, _Ga, _Ha, _Ia, _Ja, _Ka, _La, _Ma, _Na, _Oa, _Pa, _Qa, _Ra, _Sa, _Ta, _Ua, _Va, _Wa, _Xa, _Ya, _Za, __a, _$a, _ab, _bb, _cb, _db, _eb, _fb, _gb, _hb, _ib, _jb, _kb, _lb, _mb, _nb;
4420
+ var _a, _b, _c, _d;
4333
4421
  const reader = body.getReader();
4334
4422
  const decoder = new TextDecoder();
4335
4423
  let buffer = "";
@@ -4385,15 +4473,15 @@ var AgentWidgetClient = class {
4385
4473
  }
4386
4474
  };
4387
4475
  const getStepKey = (payload) => {
4388
- var _a2, _b2, _c2, _d2, _e2;
4476
+ var _a2, _b2, _c2, _d2, _e;
4389
4477
  return normalizeKey(
4390
- (_e2 = (_d2 = (_c2 = (_b2 = (_a2 = payload.stepId) != null ? _a2 : payload.step_id) != null ? _b2 : payload.step) != null ? _c2 : payload.parentId) != null ? _d2 : payload.flowStepId) != null ? _e2 : payload.flow_step_id
4478
+ (_e = (_d2 = (_c2 = (_b2 = (_a2 = payload.stepId) != null ? _a2 : payload.step_id) != null ? _b2 : payload.step) != null ? _c2 : payload.parentId) != null ? _d2 : payload.flowStepId) != null ? _e : payload.flow_step_id
4391
4479
  );
4392
4480
  };
4393
4481
  const getToolCallKey = (payload) => {
4394
- var _a2, _b2, _c2, _d2, _e2, _f2, _g2;
4482
+ var _a2, _b2, _c2, _d2, _e, _f, _g;
4395
4483
  return normalizeKey(
4396
- (_g2 = (_f2 = (_e2 = (_d2 = (_c2 = (_b2 = (_a2 = payload.callId) != null ? _a2 : payload.call_id) != null ? _b2 : payload.requestId) != null ? _c2 : payload.request_id) != null ? _d2 : payload.toolCallId) != null ? _e2 : payload.tool_call_id) != null ? _f2 : payload.stepId) != null ? _g2 : payload.step_id
4484
+ (_g = (_f = (_e = (_d2 = (_c2 = (_b2 = (_a2 = payload.callId) != null ? _a2 : payload.call_id) != null ? _b2 : payload.requestId) != null ? _c2 : payload.request_id) != null ? _d2 : payload.toolCallId) != null ? _e : payload.tool_call_id) != null ? _f : payload.stepId) != null ? _g : payload.step_id
4397
4485
  );
4398
4486
  };
4399
4487
  const baseAssistantId = assistantMessageId;
@@ -4569,26 +4657,37 @@ var AgentWidgetClient = class {
4569
4657
  };
4570
4658
  const streamParsers = /* @__PURE__ */ new Map();
4571
4659
  const rawContentBuffers = /* @__PURE__ */ new Map();
4572
- const seqChunkBuffers = /* @__PURE__ */ new Map();
4573
- const reasonSeqBuffers = /* @__PURE__ */ new Map();
4574
- function insertSeqChunk(bufferMap, key, seq, text) {
4575
- let buf = bufferMap.get(key);
4576
- if (!buf) {
4577
- buf = [];
4578
- bufferMap.set(key, buf);
4579
- }
4580
- let lo = 0, hi = buf.length;
4660
+ const orderedChunkBuffers = /* @__PURE__ */ new Map();
4661
+ const assistantMessagesByPartId = /* @__PURE__ */ new Map();
4662
+ let lastSealedTextSegment = null;
4663
+ const insertOrderedChunk = (key, seq, text) => {
4664
+ var _a2;
4665
+ let chunks = orderedChunkBuffers.get(key);
4666
+ if (!chunks) {
4667
+ chunks = [];
4668
+ orderedChunkBuffers.set(key, chunks);
4669
+ }
4670
+ let lo = 0;
4671
+ let hi = chunks.length;
4581
4672
  while (lo < hi) {
4582
4673
  const mid = lo + hi >>> 1;
4583
- if (buf[mid].seq < seq) lo = mid + 1;
4584
- else hi = mid;
4674
+ if (chunks[mid].seq < seq) {
4675
+ lo = mid + 1;
4676
+ } else {
4677
+ hi = mid;
4678
+ }
4585
4679
  }
4586
- buf.splice(lo, 0, { seq, text });
4587
- let result = "";
4588
- for (let i = 0; i < buf.length; i++) result += buf[i].text;
4589
- return result;
4590
- }
4591
- let lastSealedTextSegment = null;
4680
+ if (((_a2 = chunks[lo]) == null ? void 0 : _a2.seq) === seq) {
4681
+ chunks[lo] = { seq, text };
4682
+ } else {
4683
+ chunks.splice(lo, 0, { seq, text });
4684
+ }
4685
+ let accumulated = "";
4686
+ for (let index = 0; index < chunks.length; index++) {
4687
+ accumulated += chunks[index].text;
4688
+ }
4689
+ return accumulated;
4690
+ };
4592
4691
  const reconcileSealedAssistantWithFinalResponse = (msg, finalContent) => {
4593
4692
  const finalString = ensureStringContent(finalContent);
4594
4693
  const rawBuffer = rawContentBuffers.get(msg.id);
@@ -4655,82 +4754,57 @@ var AgentWidgetClient = class {
4655
4754
  mergeIfBetter(bestDisplayText(parsedResult));
4656
4755
  finalizeCleanup();
4657
4756
  };
4757
+ const seqReadyQueue = [];
4758
+ let isDrainScheduled = false;
4759
+ let drainReadyQueue;
4760
+ const scheduleReadyQueueDrain = () => {
4761
+ if (isDrainScheduled) return;
4762
+ isDrainScheduled = true;
4763
+ queueMicrotask(() => {
4764
+ isDrainScheduled = false;
4765
+ drainReadyQueue();
4766
+ });
4767
+ };
4768
+ const seqBuffer = new SequenceReorderBuffer((payloadType, payload) => {
4769
+ seqReadyQueue.push({ payloadType, payload });
4770
+ scheduleReadyQueueDrain();
4771
+ });
4658
4772
  let agentExecution = null;
4659
4773
  const agentIterationMessages = /* @__PURE__ */ new Map();
4660
4774
  const iterationDisplay = (_a = this.config.iterationDisplay) != null ? _a : "separate";
4661
- while (true) {
4662
- const { done, value } = await reader.read();
4663
- if (done) break;
4664
- buffer += decoder.decode(value, { stream: true });
4665
- const events = buffer.split("\n\n");
4666
- buffer = (_b = events.pop()) != null ? _b : "";
4667
- for (const event of events) {
4668
- const lines = event.split("\n");
4669
- let eventType = "message";
4670
- let data = "";
4671
- for (const line of lines) {
4672
- if (line.startsWith("event:")) {
4673
- eventType = line.replace("event:", "").trim();
4674
- } else if (line.startsWith("data:")) {
4675
- data += line.replace("data:", "").trim();
4676
- }
4677
- }
4678
- if (!data) continue;
4679
- let payload;
4680
- try {
4681
- payload = JSON.parse(data);
4682
- } catch (error) {
4683
- onEvent({
4684
- type: "error",
4685
- error: error instanceof Error ? error : new Error("Failed to parse chat stream payload")
4686
- });
4687
- continue;
4688
- }
4689
- const payloadType = eventType !== "message" ? eventType : (_c = payload.type) != null ? _c : "message";
4690
- (_d = this.onSSEEvent) == null ? void 0 : _d.call(this, payloadType, payload);
4691
- if (this.parseSSEEvent) {
4692
- assistantMessageRef.current = assistantMessage;
4693
- const handled = await this.handleCustomSSEEvent(
4694
- payload,
4695
- onEvent,
4696
- assistantMessageRef,
4697
- emitMessage,
4698
- nextSequence,
4699
- partIdState
4700
- );
4701
- if (assistantMessageRef.current && assistantMessageRef.current !== assistantMessage) {
4702
- assistantMessage = assistantMessageRef.current;
4703
- }
4704
- if (handled) continue;
4705
- }
4775
+ drainReadyQueue = () => {
4776
+ var _a2, _b2, _c2, _d2, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R, _S, _T, _U, _V, _W, _X, _Y, _Z, __, _$, _aa, _ba, _ca, _da, _ea, _fa, _ga, _ha, _ia, _ja, _ka, _la, _ma, _na, _oa, _pa, _qa, _ra, _sa, _ta, _ua, _va, _wa, _xa, _ya, _za, _Aa, _Ba, _Ca, _Da, _Ea, _Fa, _Ga, _Ha, _Ia, _Ja, _Ka, _La, _Ma, _Na, _Oa, _Pa, _Qa, _Ra, _Sa, _Ta, _Ua, _Va, _Wa, _Xa, _Ya, _Za, __a, _$a, _ab, _bb, _cb, _db, _eb, _fb, _gb, _hb, _ib, _jb, _kb;
4777
+ for (let i = 0; i < seqReadyQueue.length; i++) {
4778
+ const payloadType = seqReadyQueue[i].payloadType;
4779
+ const payload = seqReadyQueue[i].payload;
4706
4780
  if (payloadType === "reason_start") {
4707
- const reasoningId = (_e = resolveReasoningId(payload, true)) != null ? _e : `reason-${nextSequence()}`;
4781
+ const reasoningId = (_a2 = resolveReasoningId(payload, true)) != null ? _a2 : `reason-${nextSequence()}`;
4708
4782
  const reasoningMessage = ensureReasoningMessage(reasoningId);
4709
- reasoningMessage.reasoning = (_f = reasoningMessage.reasoning) != null ? _f : {
4783
+ reasoningMessage.reasoning = (_b2 = reasoningMessage.reasoning) != null ? _b2 : {
4710
4784
  id: reasoningId,
4711
4785
  status: "streaming",
4712
4786
  chunks: []
4713
4787
  };
4714
- reasoningMessage.reasoning.startedAt = (_h = reasoningMessage.reasoning.startedAt) != null ? _h : resolveTimestamp((_g = payload.startedAt) != null ? _g : payload.timestamp);
4788
+ reasoningMessage.reasoning.startedAt = (_d2 = reasoningMessage.reasoning.startedAt) != null ? _d2 : resolveTimestamp((_c2 = payload.startedAt) != null ? _c2 : payload.timestamp);
4715
4789
  reasoningMessage.reasoning.completedAt = void 0;
4716
4790
  reasoningMessage.reasoning.durationMs = void 0;
4717
4791
  reasoningMessage.streaming = true;
4718
4792
  reasoningMessage.reasoning.status = "streaming";
4719
4793
  emitMessage(reasoningMessage);
4720
4794
  } else if (payloadType === "reason_delta" || payloadType === "reason_chunk") {
4721
- const reasoningId = (_j = (_i = resolveReasoningId(payload, false)) != null ? _i : resolveReasoningId(payload, true)) != null ? _j : `reason-${nextSequence()}`;
4795
+ const reasoningId = (_f = (_e = resolveReasoningId(payload, false)) != null ? _e : resolveReasoningId(payload, true)) != null ? _f : `reason-${nextSequence()}`;
4722
4796
  const reasoningMessage = ensureReasoningMessage(reasoningId);
4723
- reasoningMessage.reasoning = (_k = reasoningMessage.reasoning) != null ? _k : {
4797
+ reasoningMessage.reasoning = (_g = reasoningMessage.reasoning) != null ? _g : {
4724
4798
  id: reasoningId,
4725
4799
  status: "streaming",
4726
4800
  chunks: []
4727
4801
  };
4728
- reasoningMessage.reasoning.startedAt = (_m = reasoningMessage.reasoning.startedAt) != null ? _m : resolveTimestamp((_l = payload.startedAt) != null ? _l : payload.timestamp);
4729
- const chunk = (_p = (_o = (_n = payload.reasoningText) != null ? _n : payload.text) != null ? _o : payload.delta) != null ? _p : "";
4802
+ reasoningMessage.reasoning.startedAt = (_i = reasoningMessage.reasoning.startedAt) != null ? _i : resolveTimestamp((_h = payload.startedAt) != null ? _h : payload.timestamp);
4803
+ const chunk = (_l = (_k = (_j = payload.reasoningText) != null ? _j : payload.text) != null ? _k : payload.delta) != null ? _l : "";
4730
4804
  if (chunk && payload.hidden !== true) {
4731
4805
  const reasonSeq = typeof payload.sequenceIndex === "number" ? payload.sequenceIndex : void 0;
4732
4806
  if (reasonSeq !== void 0) {
4733
- const ordered = insertSeqChunk(reasonSeqBuffers, reasoningId, reasonSeq, String(chunk));
4807
+ const ordered = insertOrderedChunk(reasoningId, reasonSeq, String(chunk));
4734
4808
  reasoningMessage.reasoning.chunks = [ordered];
4735
4809
  } else {
4736
4810
  reasoningMessage.reasoning.chunks.push(String(chunk));
@@ -4739,32 +4813,30 @@ var AgentWidgetClient = class {
4739
4813
  reasoningMessage.reasoning.status = payload.done ? "complete" : "streaming";
4740
4814
  if (payload.done) {
4741
4815
  reasoningMessage.reasoning.completedAt = resolveTimestamp(
4742
- (_q = payload.completedAt) != null ? _q : payload.timestamp
4816
+ (_m = payload.completedAt) != null ? _m : payload.timestamp
4743
4817
  );
4744
- const start = (_r = reasoningMessage.reasoning.startedAt) != null ? _r : Date.now();
4818
+ const start = (_n = reasoningMessage.reasoning.startedAt) != null ? _n : Date.now();
4745
4819
  reasoningMessage.reasoning.durationMs = Math.max(
4746
4820
  0,
4747
- ((_s = reasoningMessage.reasoning.completedAt) != null ? _s : Date.now()) - start
4821
+ ((_o = reasoningMessage.reasoning.completedAt) != null ? _o : Date.now()) - start
4748
4822
  );
4749
- reasonSeqBuffers.delete(reasoningId);
4750
4823
  }
4751
4824
  reasoningMessage.streaming = reasoningMessage.reasoning.status !== "complete";
4752
4825
  emitMessage(reasoningMessage);
4753
4826
  } else if (payloadType === "reason_complete") {
4754
- const reasoningId = (_u = (_t = resolveReasoningId(payload, false)) != null ? _t : resolveReasoningId(payload, true)) != null ? _u : `reason-${nextSequence()}`;
4827
+ const reasoningId = (_q = (_p = resolveReasoningId(payload, false)) != null ? _p : resolveReasoningId(payload, true)) != null ? _q : `reason-${nextSequence()}`;
4755
4828
  const reasoningMessage = reasoningMessages.get(reasoningId);
4756
4829
  if (reasoningMessage == null ? void 0 : reasoningMessage.reasoning) {
4757
4830
  reasoningMessage.reasoning.status = "complete";
4758
4831
  reasoningMessage.reasoning.completedAt = resolveTimestamp(
4759
- (_v = payload.completedAt) != null ? _v : payload.timestamp
4832
+ (_r = payload.completedAt) != null ? _r : payload.timestamp
4760
4833
  );
4761
- const start = (_w = reasoningMessage.reasoning.startedAt) != null ? _w : Date.now();
4834
+ const start = (_s = reasoningMessage.reasoning.startedAt) != null ? _s : Date.now();
4762
4835
  reasoningMessage.reasoning.durationMs = Math.max(
4763
4836
  0,
4764
- ((_x = reasoningMessage.reasoning.completedAt) != null ? _x : Date.now()) - start
4837
+ ((_t = reasoningMessage.reasoning.completedAt) != null ? _t : Date.now()) - start
4765
4838
  );
4766
4839
  reasoningMessage.streaming = false;
4767
- reasonSeqBuffers.delete(reasoningId);
4768
4840
  emitMessage(reasoningMessage);
4769
4841
  }
4770
4842
  const stepKey = getStepKey(payload);
@@ -4772,14 +4844,14 @@ var AgentWidgetClient = class {
4772
4844
  reasoningContext.byStep.delete(stepKey);
4773
4845
  }
4774
4846
  } else if (payloadType === "tool_start") {
4775
- const toolId = (_y = resolveToolId(payload, true)) != null ? _y : `tool-${nextSequence()}`;
4776
- const toolName = (_z = payload.toolName) != null ? _z : payload.name;
4847
+ const toolId = (_u = resolveToolId(payload, true)) != null ? _u : `tool-${nextSequence()}`;
4848
+ const toolName = (_v = payload.toolName) != null ? _v : payload.name;
4777
4849
  if (isArtifactEmitToolName(toolName)) {
4778
4850
  artifactToolCallIds.add(toolId);
4779
4851
  continue;
4780
4852
  }
4781
4853
  const toolMessage = ensureToolMessage(toolId);
4782
- const tool = (_A = toolMessage.toolCall) != null ? _A : {
4854
+ const tool = (_w = toolMessage.toolCall) != null ? _w : {
4783
4855
  id: toolId,
4784
4856
  status: "pending"
4785
4857
  };
@@ -4790,7 +4862,7 @@ var AgentWidgetClient = class {
4790
4862
  } else if (payload.parameters !== void 0) {
4791
4863
  tool.args = payload.parameters;
4792
4864
  }
4793
- tool.startedAt = (_C = tool.startedAt) != null ? _C : resolveTimestamp((_B = payload.startedAt) != null ? _B : payload.timestamp);
4865
+ tool.startedAt = (_y = tool.startedAt) != null ? _y : resolveTimestamp((_x = payload.startedAt) != null ? _x : payload.timestamp);
4794
4866
  tool.completedAt = void 0;
4795
4867
  tool.durationMs = void 0;
4796
4868
  toolMessage.toolCall = tool;
@@ -4798,23 +4870,23 @@ var AgentWidgetClient = class {
4798
4870
  const agentCtx = payload.agentContext;
4799
4871
  if (agentCtx || payload.executionId) {
4800
4872
  toolMessage.agentMetadata = {
4801
- executionId: (_D = agentCtx == null ? void 0 : agentCtx.executionId) != null ? _D : payload.executionId,
4802
- iteration: (_E = agentCtx == null ? void 0 : agentCtx.iteration) != null ? _E : payload.iteration
4873
+ executionId: (_z = agentCtx == null ? void 0 : agentCtx.executionId) != null ? _z : payload.executionId,
4874
+ iteration: (_A = agentCtx == null ? void 0 : agentCtx.iteration) != null ? _A : payload.iteration
4803
4875
  };
4804
4876
  }
4805
4877
  emitMessage(toolMessage);
4806
4878
  } else if (payloadType === "tool_chunk" || payloadType === "tool_delta") {
4807
- const toolId = (_G = (_F = resolveToolId(payload, false)) != null ? _F : resolveToolId(payload, true)) != null ? _G : `tool-${nextSequence()}`;
4879
+ const toolId = (_C = (_B = resolveToolId(payload, false)) != null ? _B : resolveToolId(payload, true)) != null ? _C : `tool-${nextSequence()}`;
4808
4880
  if (artifactToolCallIds.has(toolId)) continue;
4809
4881
  const toolMessage = ensureToolMessage(toolId);
4810
- const tool = (_H = toolMessage.toolCall) != null ? _H : {
4882
+ const tool = (_D = toolMessage.toolCall) != null ? _D : {
4811
4883
  id: toolId,
4812
4884
  status: "running"
4813
4885
  };
4814
- tool.startedAt = (_J = tool.startedAt) != null ? _J : resolveTimestamp((_I = payload.startedAt) != null ? _I : payload.timestamp);
4815
- const chunkText = (_M = (_L = (_K = payload.text) != null ? _K : payload.delta) != null ? _L : payload.message) != null ? _M : "";
4886
+ tool.startedAt = (_F = tool.startedAt) != null ? _F : resolveTimestamp((_E = payload.startedAt) != null ? _E : payload.timestamp);
4887
+ const chunkText = (_I = (_H = (_G = payload.text) != null ? _G : payload.delta) != null ? _H : payload.message) != null ? _I : "";
4816
4888
  if (chunkText) {
4817
- tool.chunks = (_N = tool.chunks) != null ? _N : [];
4889
+ tool.chunks = (_J = tool.chunks) != null ? _J : [];
4818
4890
  tool.chunks.push(String(chunkText));
4819
4891
  }
4820
4892
  tool.status = "running";
@@ -4822,20 +4894,20 @@ var AgentWidgetClient = class {
4822
4894
  toolMessage.streaming = true;
4823
4895
  const agentCtxChunk = payload.agentContext;
4824
4896
  if (agentCtxChunk || payload.executionId) {
4825
- toolMessage.agentMetadata = (_Q = toolMessage.agentMetadata) != null ? _Q : {
4826
- executionId: (_O = agentCtxChunk == null ? void 0 : agentCtxChunk.executionId) != null ? _O : payload.executionId,
4827
- iteration: (_P = agentCtxChunk == null ? void 0 : agentCtxChunk.iteration) != null ? _P : payload.iteration
4897
+ toolMessage.agentMetadata = (_M = toolMessage.agentMetadata) != null ? _M : {
4898
+ executionId: (_K = agentCtxChunk == null ? void 0 : agentCtxChunk.executionId) != null ? _K : payload.executionId,
4899
+ iteration: (_L = agentCtxChunk == null ? void 0 : agentCtxChunk.iteration) != null ? _L : payload.iteration
4828
4900
  };
4829
4901
  }
4830
4902
  emitMessage(toolMessage);
4831
4903
  } else if (payloadType === "tool_complete") {
4832
- const toolId = (_S = (_R = resolveToolId(payload, false)) != null ? _R : resolveToolId(payload, true)) != null ? _S : `tool-${nextSequence()}`;
4904
+ const toolId = (_O = (_N = resolveToolId(payload, false)) != null ? _N : resolveToolId(payload, true)) != null ? _O : `tool-${nextSequence()}`;
4833
4905
  if (artifactToolCallIds.has(toolId)) {
4834
4906
  artifactToolCallIds.delete(toolId);
4835
4907
  continue;
4836
4908
  }
4837
4909
  const toolMessage = ensureToolMessage(toolId);
4838
- const tool = (_T = toolMessage.toolCall) != null ? _T : {
4910
+ const tool = (_P = toolMessage.toolCall) != null ? _P : {
4839
4911
  id: toolId,
4840
4912
  status: "running"
4841
4913
  };
@@ -4847,25 +4919,25 @@ var AgentWidgetClient = class {
4847
4919
  tool.duration = payload.duration;
4848
4920
  }
4849
4921
  tool.completedAt = resolveTimestamp(
4850
- (_U = payload.completedAt) != null ? _U : payload.timestamp
4922
+ (_Q = payload.completedAt) != null ? _Q : payload.timestamp
4851
4923
  );
4852
- const durationValue = (_V = payload.duration) != null ? _V : payload.executionTime;
4924
+ const durationValue = (_R = payload.duration) != null ? _R : payload.executionTime;
4853
4925
  if (typeof durationValue === "number") {
4854
4926
  tool.durationMs = durationValue;
4855
4927
  } else {
4856
- const start = (_W = tool.startedAt) != null ? _W : Date.now();
4928
+ const start = (_S = tool.startedAt) != null ? _S : Date.now();
4857
4929
  tool.durationMs = Math.max(
4858
4930
  0,
4859
- ((_X = tool.completedAt) != null ? _X : Date.now()) - start
4931
+ ((_T = tool.completedAt) != null ? _T : Date.now()) - start
4860
4932
  );
4861
4933
  }
4862
4934
  toolMessage.toolCall = tool;
4863
4935
  toolMessage.streaming = false;
4864
4936
  const agentCtxComplete = payload.agentContext;
4865
4937
  if (agentCtxComplete || payload.executionId) {
4866
- toolMessage.agentMetadata = (__ = toolMessage.agentMetadata) != null ? __ : {
4867
- executionId: (_Y = agentCtxComplete == null ? void 0 : agentCtxComplete.executionId) != null ? _Y : payload.executionId,
4868
- iteration: (_Z = agentCtxComplete == null ? void 0 : agentCtxComplete.iteration) != null ? _Z : payload.iteration
4938
+ toolMessage.agentMetadata = (_W = toolMessage.agentMetadata) != null ? _W : {
4939
+ executionId: (_U = agentCtxComplete == null ? void 0 : agentCtxComplete.executionId) != null ? _U : payload.executionId,
4940
+ iteration: (_V = agentCtxComplete == null ? void 0 : agentCtxComplete.iteration) != null ? _V : payload.iteration
4869
4941
  };
4870
4942
  }
4871
4943
  emitMessage(toolMessage);
@@ -4917,20 +4989,18 @@ var AgentWidgetClient = class {
4917
4989
  if (incomingPartId !== void 0) {
4918
4990
  partIdState.current = incomingPartId;
4919
4991
  }
4920
- const assistant = ensureAssistantMessage();
4921
- if (incomingPartId !== void 0 && !assistant.partId) {
4922
- assistant.partId = incomingPartId;
4992
+ const assistant = incomingPartId !== void 0 ? (_X = assistantMessagesByPartId.get(incomingPartId)) != null ? _X : ensureAssistantMessage() : ensureAssistantMessage();
4993
+ if (incomingPartId !== void 0) {
4994
+ if (!assistant.partId) {
4995
+ assistant.partId = incomingPartId;
4996
+ }
4997
+ assistantMessagesByPartId.set(incomingPartId, assistant);
4923
4998
  }
4924
- const chunk = (_ca = (_ba = (_aa = (_$ = payload.text) != null ? _$ : payload.delta) != null ? _aa : payload.content) != null ? _ba : payload.chunk) != null ? _ca : "";
4999
+ const chunk = (_$ = (__ = (_Z = (_Y = payload.text) != null ? _Y : payload.delta) != null ? _Z : payload.content) != null ? __ : payload.chunk) != null ? _$ : "";
4925
5000
  if (chunk) {
4926
5001
  const chunkSeq = typeof payload.seq === "number" ? payload.seq : void 0;
4927
- let accumulatedRaw;
4928
- if (chunkSeq !== void 0) {
4929
- accumulatedRaw = insertSeqChunk(seqChunkBuffers, assistant.id, chunkSeq, chunk);
4930
- } else {
4931
- const rawBuffer = (_da = rawContentBuffers.get(assistant.id)) != null ? _da : "";
4932
- accumulatedRaw = rawBuffer + chunk;
4933
- }
5002
+ const chunkBufferKey = incomingPartId != null ? incomingPartId : assistant.id;
5003
+ const accumulatedRaw = chunkSeq !== void 0 ? insertOrderedChunk(chunkBufferKey, chunkSeq, String(chunk)) : ((_aa = rawContentBuffers.get(assistant.id)) != null ? _aa : "") + chunk;
4934
5004
  assistant.rawContent = accumulatedRaw;
4935
5005
  if (!streamParsers.has(assistant.id)) {
4936
5006
  streamParsers.set(assistant.id, this.createStreamParser());
@@ -4942,11 +5012,7 @@ var AgentWidgetClient = class {
4942
5012
  }
4943
5013
  const isPlainTextParser = parser.__isPlainTextParser === true;
4944
5014
  if (isPlainTextParser) {
4945
- if (chunkSeq !== void 0) {
4946
- assistant.content = accumulatedRaw;
4947
- } else {
4948
- assistant.content += chunk;
4949
- }
5015
+ assistant.content = chunkSeq !== void 0 ? accumulatedRaw : assistant.content + chunk;
4950
5016
  rawContentBuffers.delete(assistant.id);
4951
5017
  streamParsers.delete(assistant.id);
4952
5018
  assistant.rawContent = void 0;
@@ -4956,47 +5022,36 @@ var AgentWidgetClient = class {
4956
5022
  const parsedResult = parser.processChunk(accumulatedRaw);
4957
5023
  if (parsedResult instanceof Promise) {
4958
5024
  parsedResult.then((result) => {
4959
- var _a2;
4960
- const text = typeof result === "string" ? result : (_a2 = result == null ? void 0 : result.text) != null ? _a2 : null;
5025
+ var _a3;
5026
+ const text = typeof result === "string" ? result : (_a3 = result == null ? void 0 : result.text) != null ? _a3 : null;
4961
5027
  if (text !== null && text.trim() !== "") {
4962
5028
  assistant.content = text;
4963
5029
  emitMessage(assistant);
4964
5030
  } else if (!looksLikeJson && !accumulatedRaw.trim().startsWith("<")) {
4965
5031
  const currentAssistant = assistantMessage;
4966
- if (currentAssistant && currentAssistant.id === assistant.id) {
4967
- if (chunkSeq !== void 0) {
4968
- currentAssistant.content = accumulatedRaw;
4969
- } else {
4970
- currentAssistant.content += chunk;
4971
- }
4972
- rawContentBuffers.delete(currentAssistant.id);
4973
- streamParsers.delete(currentAssistant.id);
4974
- currentAssistant.rawContent = void 0;
4975
- emitMessage(currentAssistant);
5032
+ const targetAssistant = currentAssistant && currentAssistant.id === assistant.id ? currentAssistant : assistant;
5033
+ if (targetAssistant.id === assistant.id) {
5034
+ targetAssistant.content = chunkSeq !== void 0 ? accumulatedRaw : targetAssistant.content + chunk;
5035
+ rawContentBuffers.delete(targetAssistant.id);
5036
+ streamParsers.delete(targetAssistant.id);
5037
+ targetAssistant.rawContent = void 0;
5038
+ emitMessage(targetAssistant);
4976
5039
  }
4977
5040
  }
4978
5041
  }).catch(() => {
4979
- if (chunkSeq !== void 0) {
4980
- assistant.content = accumulatedRaw;
4981
- } else {
4982
- assistant.content += chunk;
4983
- }
5042
+ assistant.content = chunkSeq !== void 0 ? accumulatedRaw : assistant.content + chunk;
4984
5043
  rawContentBuffers.delete(assistant.id);
4985
5044
  streamParsers.delete(assistant.id);
4986
5045
  assistant.rawContent = void 0;
4987
5046
  emitMessage(assistant);
4988
5047
  });
4989
5048
  } else {
4990
- const text = typeof parsedResult === "string" ? parsedResult : (_ea = parsedResult == null ? void 0 : parsedResult.text) != null ? _ea : null;
5049
+ const text = typeof parsedResult === "string" ? parsedResult : (_ba = parsedResult == null ? void 0 : parsedResult.text) != null ? _ba : null;
4991
5050
  if (text !== null && text.trim() !== "") {
4992
5051
  assistant.content = text;
4993
5052
  emitMessage(assistant);
4994
5053
  } else if (!looksLikeJson && !accumulatedRaw.trim().startsWith("<")) {
4995
- if (chunkSeq !== void 0) {
4996
- assistant.content = accumulatedRaw;
4997
- } else {
4998
- assistant.content += chunk;
4999
- }
5054
+ assistant.content = chunkSeq !== void 0 ? accumulatedRaw : assistant.content + chunk;
5000
5055
  rawContentBuffers.delete(assistant.id);
5001
5056
  streamParsers.delete(assistant.id);
5002
5057
  assistant.rawContent = void 0;
@@ -5005,7 +5060,7 @@ var AgentWidgetClient = class {
5005
5060
  }
5006
5061
  }
5007
5062
  if (payload.isComplete) {
5008
- const finalContent = (_ga = (_fa = payload.result) == null ? void 0 : _fa.response) != null ? _ga : assistant.content;
5063
+ const finalContent = (_da = (_ca = payload.result) == null ? void 0 : _ca.response) != null ? _da : assistant.content;
5009
5064
  if (finalContent) {
5010
5065
  const rawBuffer = rawContentBuffers.get(assistant.id);
5011
5066
  const contentToProcess = rawBuffer != null ? rawBuffer : ensureStringContent(finalContent);
@@ -5023,8 +5078,8 @@ var AgentWidgetClient = class {
5023
5078
  if (parsedResult instanceof Promise) {
5024
5079
  asyncPending = true;
5025
5080
  parsedResult.then((result) => {
5026
- var _a2;
5027
- const text = typeof result === "string" ? result : (_a2 = result == null ? void 0 : result.text) != null ? _a2 : null;
5081
+ var _a3;
5082
+ const text = typeof result === "string" ? result : (_a3 = result == null ? void 0 : result.text) != null ? _a3 : null;
5028
5083
  if (text !== null) {
5029
5084
  const currentAssistant = assistantMessage;
5030
5085
  if (currentAssistant && currentAssistant.id === assistant.id) {
@@ -5032,13 +5087,12 @@ var AgentWidgetClient = class {
5032
5087
  currentAssistant.streaming = false;
5033
5088
  streamParsers.delete(currentAssistant.id);
5034
5089
  rawContentBuffers.delete(currentAssistant.id);
5035
- seqChunkBuffers.delete(currentAssistant.id);
5036
5090
  emitMessage(currentAssistant);
5037
5091
  }
5038
5092
  }
5039
5093
  });
5040
5094
  } else {
5041
- extractedText = typeof parsedResult === "string" ? parsedResult : (_ha = parsedResult == null ? void 0 : parsedResult.text) != null ? _ha : null;
5095
+ extractedText = typeof parsedResult === "string" ? parsedResult : (_ea = parsedResult == null ? void 0 : parsedResult.text) != null ? _ea : null;
5042
5096
  }
5043
5097
  }
5044
5098
  }
@@ -5050,7 +5104,7 @@ var AgentWidgetClient = class {
5050
5104
  }
5051
5105
  const parserToClose = streamParsers.get(assistant.id);
5052
5106
  if (parserToClose) {
5053
- const closeResult = (_ia = parserToClose.close) == null ? void 0 : _ia.call(parserToClose);
5107
+ const closeResult = (_fa = parserToClose.close) == null ? void 0 : _fa.call(parserToClose);
5054
5108
  if (closeResult instanceof Promise) {
5055
5109
  closeResult.catch(() => {
5056
5110
  });
@@ -5058,7 +5112,6 @@ var AgentWidgetClient = class {
5058
5112
  streamParsers.delete(assistant.id);
5059
5113
  }
5060
5114
  rawContentBuffers.delete(assistant.id);
5061
- seqChunkBuffers.delete(assistant.id);
5062
5115
  assistant.streaming = false;
5063
5116
  emitMessage(assistant);
5064
5117
  }
@@ -5075,13 +5128,12 @@ var AgentWidgetClient = class {
5075
5128
  const msg = assistantMessage;
5076
5129
  streamParsers.delete(msg.id);
5077
5130
  rawContentBuffers.delete(msg.id);
5078
- seqChunkBuffers.delete(msg.id);
5079
5131
  if (msg.streaming !== false) {
5080
5132
  msg.streaming = false;
5081
5133
  emitMessage(msg);
5082
5134
  }
5083
5135
  }
5084
- const splitFinalContent = (_ja = payload.result) == null ? void 0 : _ja.response;
5136
+ const splitFinalContent = (_ga = payload.result) == null ? void 0 : _ga.response;
5085
5137
  const sealedForReconcile = lastSealedTextSegment;
5086
5138
  if (sealedForReconcile) {
5087
5139
  if (splitFinalContent !== void 0 && splitFinalContent !== null) {
@@ -5094,7 +5146,7 @@ var AgentWidgetClient = class {
5094
5146
  lastSealedTextSegment = null;
5095
5147
  continue;
5096
5148
  }
5097
- const finalContent = (_ka = payload.result) == null ? void 0 : _ka.response;
5149
+ const finalContent = (_ha = payload.result) == null ? void 0 : _ha.response;
5098
5150
  const assistant = ensureAssistantMessage();
5099
5151
  if (finalContent !== void 0 && finalContent !== null) {
5100
5152
  const parser = streamParsers.get(assistant.id);
@@ -5118,8 +5170,8 @@ var AgentWidgetClient = class {
5118
5170
  if (parsedResult instanceof Promise) {
5119
5171
  asyncPending = true;
5120
5172
  parsedResult.then((result) => {
5121
- var _a2;
5122
- const text = typeof result === "string" ? result : (_a2 = result == null ? void 0 : result.text) != null ? _a2 : null;
5173
+ var _a3;
5174
+ const text = typeof result === "string" ? result : (_a3 = result == null ? void 0 : result.text) != null ? _a3 : null;
5123
5175
  if (text !== null && text.trim() !== "") {
5124
5176
  const currentAssistant = assistantMessage;
5125
5177
  if (currentAssistant && currentAssistant.id === assistant.id) {
@@ -5127,7 +5179,6 @@ var AgentWidgetClient = class {
5127
5179
  currentAssistant.streaming = false;
5128
5180
  streamParsers.delete(currentAssistant.id);
5129
5181
  rawContentBuffers.delete(currentAssistant.id);
5130
- seqChunkBuffers.delete(currentAssistant.id);
5131
5182
  emitMessage(currentAssistant);
5132
5183
  }
5133
5184
  } else {
@@ -5142,13 +5193,12 @@ var AgentWidgetClient = class {
5142
5193
  currentAssistant.streaming = false;
5143
5194
  streamParsers.delete(currentAssistant.id);
5144
5195
  rawContentBuffers.delete(currentAssistant.id);
5145
- seqChunkBuffers.delete(currentAssistant.id);
5146
5196
  emitMessage(currentAssistant);
5147
5197
  }
5148
5198
  }
5149
5199
  });
5150
5200
  } else {
5151
- const text = typeof parsedResult === "string" ? parsedResult : (_la = parsedResult == null ? void 0 : parsedResult.text) != null ? _la : null;
5201
+ const text = typeof parsedResult === "string" ? parsedResult : (_ia = parsedResult == null ? void 0 : parsedResult.text) != null ? _ia : null;
5152
5202
  if (text !== null && text.trim() !== "") {
5153
5203
  assistant.content = text;
5154
5204
  hasExtractedText = true;
@@ -5172,7 +5222,7 @@ var AgentWidgetClient = class {
5172
5222
  assistant.content = ensureStringContent(finalContent);
5173
5223
  }
5174
5224
  if (parser) {
5175
- const closeResult = (_ma = parser.close) == null ? void 0 : _ma.call(parser);
5225
+ const closeResult = (_ja = parser.close) == null ? void 0 : _ja.call(parser);
5176
5226
  if (closeResult instanceof Promise) {
5177
5227
  closeResult.catch(() => {
5178
5228
  });
@@ -5180,25 +5230,22 @@ var AgentWidgetClient = class {
5180
5230
  }
5181
5231
  streamParsers.delete(assistant.id);
5182
5232
  rawContentBuffers.delete(assistant.id);
5183
- seqChunkBuffers.delete(assistant.id);
5184
5233
  assistant.streaming = false;
5185
5234
  emitMessage(assistant);
5186
5235
  }
5187
5236
  } else {
5188
5237
  streamParsers.delete(assistant.id);
5189
5238
  rawContentBuffers.delete(assistant.id);
5190
- seqChunkBuffers.delete(assistant.id);
5191
5239
  assistant.streaming = false;
5192
5240
  emitMessage(assistant);
5193
5241
  }
5194
5242
  } else if (payloadType === "flow_complete") {
5195
- const finalContent = (_na = payload.result) == null ? void 0 : _na.response;
5243
+ const finalContent = (_ka = payload.result) == null ? void 0 : _ka.response;
5196
5244
  if (didSplitByPartId) {
5197
5245
  if (assistantMessage !== null) {
5198
5246
  const msg = assistantMessage;
5199
5247
  streamParsers.delete(msg.id);
5200
5248
  rawContentBuffers.delete(msg.id);
5201
- seqChunkBuffers.delete(msg.id);
5202
5249
  if (msg.streaming !== false) {
5203
5250
  msg.streaming = false;
5204
5251
  emitMessage(msg);
@@ -5219,8 +5266,8 @@ var AgentWidgetClient = class {
5219
5266
  const parsedResult = parser.processChunk(stringContent);
5220
5267
  if (parsedResult instanceof Promise) {
5221
5268
  parsedResult.then((result) => {
5222
- var _a2;
5223
- const text = typeof result === "string" ? result : (_a2 = result == null ? void 0 : result.text) != null ? _a2 : null;
5269
+ var _a3;
5270
+ const text = typeof result === "string" ? result : (_a3 = result == null ? void 0 : result.text) != null ? _a3 : null;
5224
5271
  if (text !== null) {
5225
5272
  assistant.content = text;
5226
5273
  assistant.streaming = false;
@@ -5236,7 +5283,6 @@ var AgentWidgetClient = class {
5236
5283
  }
5237
5284
  streamParsers.delete(assistant.id);
5238
5285
  rawContentBuffers.delete(assistant.id);
5239
- seqChunkBuffers.delete(assistant.id);
5240
5286
  const contentChanged = displayContent !== assistant.content;
5241
5287
  const streamingChanged = assistant.streaming !== false;
5242
5288
  if (contentChanged) {
@@ -5251,7 +5297,6 @@ var AgentWidgetClient = class {
5251
5297
  const msg = assistantMessage;
5252
5298
  streamParsers.delete(msg.id);
5253
5299
  rawContentBuffers.delete(msg.id);
5254
- seqChunkBuffers.delete(msg.id);
5255
5300
  if (msg.streaming !== false) {
5256
5301
  msg.streaming = false;
5257
5302
  emitMessage(msg);
@@ -5262,11 +5307,11 @@ var AgentWidgetClient = class {
5262
5307
  } else if (payloadType === "agent_start") {
5263
5308
  agentExecution = {
5264
5309
  executionId: payload.executionId,
5265
- agentId: (_oa = payload.agentId) != null ? _oa : "virtual",
5266
- agentName: (_pa = payload.agentName) != null ? _pa : "",
5310
+ agentId: (_la = payload.agentId) != null ? _la : "virtual",
5311
+ agentName: (_ma = payload.agentName) != null ? _ma : "",
5267
5312
  status: "running",
5268
5313
  currentIteration: 0,
5269
- maxTurns: (_qa = payload.maxTurns) != null ? _qa : 1,
5314
+ maxTurns: (_na = payload.maxTurns) != null ? _na : 1,
5270
5315
  startedAt: resolveTimestamp(payload.startedAt)
5271
5316
  };
5272
5317
  } else if (payloadType === "agent_iteration_start") {
@@ -5286,7 +5331,7 @@ var AgentWidgetClient = class {
5286
5331
  } else if (payloadType === "agent_turn_delta") {
5287
5332
  if (payload.contentType === "text") {
5288
5333
  const assistant = ensureAssistantMessage();
5289
- assistant.content += (_ra = payload.delta) != null ? _ra : "";
5334
+ assistant.content += (_oa = payload.delta) != null ? _oa : "";
5290
5335
  assistant.agentMetadata = {
5291
5336
  executionId: payload.executionId,
5292
5337
  iteration: payload.iteration,
@@ -5295,14 +5340,14 @@ var AgentWidgetClient = class {
5295
5340
  };
5296
5341
  emitMessage(assistant);
5297
5342
  } else if (payload.contentType === "thinking") {
5298
- const reasoningId = (_sa = payload.turnId) != null ? _sa : `agent-think-${payload.iteration}`;
5343
+ const reasoningId = (_pa = payload.turnId) != null ? _pa : `agent-think-${payload.iteration}`;
5299
5344
  const reasoningMessage = ensureReasoningMessage(reasoningId);
5300
- reasoningMessage.reasoning = (_ta = reasoningMessage.reasoning) != null ? _ta : {
5345
+ reasoningMessage.reasoning = (_qa = reasoningMessage.reasoning) != null ? _qa : {
5301
5346
  id: reasoningId,
5302
5347
  status: "streaming",
5303
5348
  chunks: []
5304
5349
  };
5305
- reasoningMessage.reasoning.chunks.push((_ua = payload.delta) != null ? _ua : "");
5350
+ reasoningMessage.reasoning.chunks.push((_ra = payload.delta) != null ? _ra : "");
5306
5351
  reasoningMessage.agentMetadata = {
5307
5352
  executionId: payload.executionId,
5308
5353
  iteration: payload.iteration,
@@ -5310,12 +5355,12 @@ var AgentWidgetClient = class {
5310
5355
  };
5311
5356
  emitMessage(reasoningMessage);
5312
5357
  } else if (payload.contentType === "tool_input") {
5313
- const toolId = (_va = payload.toolCallId) != null ? _va : toolContext.lastId;
5358
+ const toolId = (_sa = payload.toolCallId) != null ? _sa : toolContext.lastId;
5314
5359
  if (toolId) {
5315
5360
  const toolMessage = toolMessages.get(toolId);
5316
5361
  if (toolMessage == null ? void 0 : toolMessage.toolCall) {
5317
- toolMessage.toolCall.chunks = (_wa = toolMessage.toolCall.chunks) != null ? _wa : [];
5318
- toolMessage.toolCall.chunks.push((_xa = payload.delta) != null ? _xa : "");
5362
+ toolMessage.toolCall.chunks = (_ta = toolMessage.toolCall.chunks) != null ? _ta : [];
5363
+ toolMessage.toolCall.chunks.push((_ua = payload.delta) != null ? _ua : "");
5319
5364
  emitMessage(toolMessage);
5320
5365
  }
5321
5366
  }
@@ -5327,20 +5372,20 @@ var AgentWidgetClient = class {
5327
5372
  if (reasoningMessage == null ? void 0 : reasoningMessage.reasoning) {
5328
5373
  reasoningMessage.reasoning.status = "complete";
5329
5374
  reasoningMessage.reasoning.completedAt = resolveTimestamp(payload.completedAt);
5330
- const start = (_ya = reasoningMessage.reasoning.startedAt) != null ? _ya : Date.now();
5375
+ const start = (_va = reasoningMessage.reasoning.startedAt) != null ? _va : Date.now();
5331
5376
  reasoningMessage.reasoning.durationMs = Math.max(
5332
5377
  0,
5333
- ((_za = reasoningMessage.reasoning.completedAt) != null ? _za : Date.now()) - start
5378
+ ((_wa = reasoningMessage.reasoning.completedAt) != null ? _wa : Date.now()) - start
5334
5379
  );
5335
5380
  reasoningMessage.streaming = false;
5336
5381
  emitMessage(reasoningMessage);
5337
5382
  }
5338
5383
  }
5339
5384
  } else if (payloadType === "agent_tool_start") {
5340
- const toolId = (_Aa = payload.toolCallId) != null ? _Aa : `agent-tool-${nextSequence()}`;
5385
+ const toolId = (_xa = payload.toolCallId) != null ? _xa : `agent-tool-${nextSequence()}`;
5341
5386
  trackToolId(getToolCallKey(payload), toolId);
5342
5387
  const toolMessage = ensureToolMessage(toolId);
5343
- const tool = (_Ba = toolMessage.toolCall) != null ? _Ba : {
5388
+ const tool = (_ya = toolMessage.toolCall) != null ? _ya : {
5344
5389
  id: toolId,
5345
5390
  status: "pending",
5346
5391
  name: void 0,
@@ -5352,12 +5397,12 @@ var AgentWidgetClient = class {
5352
5397
  completedAt: void 0,
5353
5398
  durationMs: void 0
5354
5399
  };
5355
- tool.name = (_Da = (_Ca = payload.toolName) != null ? _Ca : payload.name) != null ? _Da : tool.name;
5400
+ tool.name = (_Aa = (_za = payload.toolName) != null ? _za : payload.name) != null ? _Aa : tool.name;
5356
5401
  tool.status = "running";
5357
5402
  if (payload.parameters !== void 0) {
5358
5403
  tool.args = payload.parameters;
5359
5404
  }
5360
- tool.startedAt = resolveTimestamp((_Ea = payload.startedAt) != null ? _Ea : payload.timestamp);
5405
+ tool.startedAt = resolveTimestamp((_Ba = payload.startedAt) != null ? _Ba : payload.timestamp);
5361
5406
  toolMessage.toolCall = tool;
5362
5407
  toolMessage.streaming = true;
5363
5408
  toolMessage.agentMetadata = {
@@ -5366,21 +5411,21 @@ var AgentWidgetClient = class {
5366
5411
  };
5367
5412
  emitMessage(toolMessage);
5368
5413
  } else if (payloadType === "agent_tool_delta") {
5369
- const toolId = (_Fa = payload.toolCallId) != null ? _Fa : toolContext.lastId;
5414
+ const toolId = (_Ca = payload.toolCallId) != null ? _Ca : toolContext.lastId;
5370
5415
  if (toolId) {
5371
- const toolMessage = (_Ga = toolMessages.get(toolId)) != null ? _Ga : ensureToolMessage(toolId);
5416
+ const toolMessage = (_Da = toolMessages.get(toolId)) != null ? _Da : ensureToolMessage(toolId);
5372
5417
  if (toolMessage.toolCall) {
5373
- toolMessage.toolCall.chunks = (_Ha = toolMessage.toolCall.chunks) != null ? _Ha : [];
5374
- toolMessage.toolCall.chunks.push((_Ia = payload.delta) != null ? _Ia : "");
5418
+ toolMessage.toolCall.chunks = (_Ea = toolMessage.toolCall.chunks) != null ? _Ea : [];
5419
+ toolMessage.toolCall.chunks.push((_Fa = payload.delta) != null ? _Fa : "");
5375
5420
  toolMessage.toolCall.status = "running";
5376
5421
  toolMessage.streaming = true;
5377
5422
  emitMessage(toolMessage);
5378
5423
  }
5379
5424
  }
5380
5425
  } else if (payloadType === "agent_tool_complete") {
5381
- const toolId = (_Ja = payload.toolCallId) != null ? _Ja : toolContext.lastId;
5426
+ const toolId = (_Ga = payload.toolCallId) != null ? _Ga : toolContext.lastId;
5382
5427
  if (toolId) {
5383
- const toolMessage = (_Ka = toolMessages.get(toolId)) != null ? _Ka : ensureToolMessage(toolId);
5428
+ const toolMessage = (_Ha = toolMessages.get(toolId)) != null ? _Ha : ensureToolMessage(toolId);
5384
5429
  if (toolMessage.toolCall) {
5385
5430
  toolMessage.toolCall.status = "complete";
5386
5431
  if (payload.result !== void 0) {
@@ -5389,7 +5434,7 @@ var AgentWidgetClient = class {
5389
5434
  if (typeof payload.executionTime === "number") {
5390
5435
  toolMessage.toolCall.durationMs = payload.executionTime;
5391
5436
  }
5392
- toolMessage.toolCall.completedAt = resolveTimestamp((_La = payload.completedAt) != null ? _La : payload.timestamp);
5437
+ toolMessage.toolCall.completedAt = resolveTimestamp((_Ia = payload.completedAt) != null ? _Ia : payload.timestamp);
5393
5438
  toolMessage.streaming = false;
5394
5439
  emitMessage(toolMessage);
5395
5440
  const callKey = getToolCallKey(payload);
@@ -5404,7 +5449,7 @@ var AgentWidgetClient = class {
5404
5449
  const reflectionMessage = {
5405
5450
  id: reflectionId,
5406
5451
  role: "assistant",
5407
- content: (_Ma = payload.reflection) != null ? _Ma : "",
5452
+ content: (_Ja = payload.reflection) != null ? _Ja : "",
5408
5453
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
5409
5454
  streaming: false,
5410
5455
  variant: "reasoning",
@@ -5412,7 +5457,7 @@ var AgentWidgetClient = class {
5412
5457
  reasoning: {
5413
5458
  id: reflectionId,
5414
5459
  status: "complete",
5415
- chunks: [(_Na = payload.reflection) != null ? _Na : ""]
5460
+ chunks: [(_Ka = payload.reflection) != null ? _Ka : ""]
5416
5461
  },
5417
5462
  agentMetadata: {
5418
5463
  executionId: payload.executionId,
@@ -5433,7 +5478,7 @@ var AgentWidgetClient = class {
5433
5478
  }
5434
5479
  onEvent({ type: "status", status: "idle" });
5435
5480
  } else if (payloadType === "agent_error") {
5436
- const errorMessage = typeof payload.error === "string" ? payload.error : (_Pa = (_Oa = payload.error) == null ? void 0 : _Oa.message) != null ? _Pa : "Agent execution error";
5481
+ const errorMessage = typeof payload.error === "string" ? payload.error : (_Ma = (_La = payload.error) == null ? void 0 : _La.message) != null ? _Ma : "Agent execution error";
5437
5482
  if (payload.recoverable) {
5438
5483
  if (typeof console !== "undefined") {
5439
5484
  console.warn("[AgentWidget] Recoverable agent error:", errorMessage);
@@ -5446,7 +5491,7 @@ var AgentWidgetClient = class {
5446
5491
  }
5447
5492
  } else if (payloadType === "agent_ping") {
5448
5493
  } else if (payloadType === "agent_approval_start") {
5449
- const approvalId = (_Qa = payload.approvalId) != null ? _Qa : `approval-${nextSequence()}`;
5494
+ const approvalId = (_Na = payload.approvalId) != null ? _Na : `approval-${nextSequence()}`;
5450
5495
  const approvalMessage = {
5451
5496
  id: `approval-${approvalId}`,
5452
5497
  role: "assistant",
@@ -5458,17 +5503,17 @@ var AgentWidgetClient = class {
5458
5503
  approval: {
5459
5504
  id: approvalId,
5460
5505
  status: "pending",
5461
- agentId: (_Ra = agentExecution == null ? void 0 : agentExecution.agentId) != null ? _Ra : "virtual",
5462
- executionId: (_Ta = (_Sa = payload.executionId) != null ? _Sa : agentExecution == null ? void 0 : agentExecution.executionId) != null ? _Ta : "",
5463
- toolName: (_Ua = payload.toolName) != null ? _Ua : "",
5506
+ agentId: (_Oa = agentExecution == null ? void 0 : agentExecution.agentId) != null ? _Oa : "virtual",
5507
+ executionId: (_Qa = (_Pa = payload.executionId) != null ? _Pa : agentExecution == null ? void 0 : agentExecution.executionId) != null ? _Qa : "",
5508
+ toolName: (_Ra = payload.toolName) != null ? _Ra : "",
5464
5509
  toolType: payload.toolType,
5465
- description: (_Wa = payload.description) != null ? _Wa : `Execute ${(_Va = payload.toolName) != null ? _Va : "tool"}`,
5510
+ description: (_Ta = payload.description) != null ? _Ta : `Execute ${(_Sa = payload.toolName) != null ? _Sa : "tool"}`,
5466
5511
  parameters: payload.parameters
5467
5512
  }
5468
5513
  };
5469
5514
  emitMessage(approvalMessage);
5470
5515
  } else if (payloadType === "step_await" && payload.awaitReason === "approval_required") {
5471
- const approvalId = (_Xa = payload.approvalId) != null ? _Xa : `approval-${nextSequence()}`;
5516
+ const approvalId = (_Ua = payload.approvalId) != null ? _Ua : `approval-${nextSequence()}`;
5472
5517
  const approvalMessage = {
5473
5518
  id: `approval-${approvalId}`,
5474
5519
  role: "assistant",
@@ -5480,11 +5525,11 @@ var AgentWidgetClient = class {
5480
5525
  approval: {
5481
5526
  id: approvalId,
5482
5527
  status: "pending",
5483
- agentId: (_Ya = agentExecution == null ? void 0 : agentExecution.agentId) != null ? _Ya : "virtual",
5484
- executionId: (__a = (_Za = payload.executionId) != null ? _Za : agentExecution == null ? void 0 : agentExecution.executionId) != null ? __a : "",
5485
- toolName: (_$a = payload.toolName) != null ? _$a : "",
5528
+ agentId: (_Va = agentExecution == null ? void 0 : agentExecution.agentId) != null ? _Va : "virtual",
5529
+ executionId: (_Xa = (_Wa = payload.executionId) != null ? _Wa : agentExecution == null ? void 0 : agentExecution.executionId) != null ? _Xa : "",
5530
+ toolName: (_Ya = payload.toolName) != null ? _Ya : "",
5486
5531
  toolType: payload.toolType,
5487
- description: (_bb = payload.description) != null ? _bb : `Execute ${(_ab = payload.toolName) != null ? _ab : "tool"}`,
5532
+ description: (__a = payload.description) != null ? __a : `Execute ${(_Za = payload.toolName) != null ? _Za : "tool"}`,
5488
5533
  parameters: payload.parameters
5489
5534
  }
5490
5535
  };
@@ -5503,11 +5548,11 @@ var AgentWidgetClient = class {
5503
5548
  sequence: nextSequence(),
5504
5549
  approval: {
5505
5550
  id: approvalId,
5506
- status: (_cb = payload.decision) != null ? _cb : "approved",
5507
- agentId: (_db = agentExecution == null ? void 0 : agentExecution.agentId) != null ? _db : "virtual",
5508
- executionId: (_fb = (_eb = payload.executionId) != null ? _eb : agentExecution == null ? void 0 : agentExecution.executionId) != null ? _fb : "",
5509
- toolName: (_gb = payload.toolName) != null ? _gb : "",
5510
- description: (_hb = payload.description) != null ? _hb : "",
5551
+ status: (_$a = payload.decision) != null ? _$a : "approved",
5552
+ agentId: (_ab = agentExecution == null ? void 0 : agentExecution.agentId) != null ? _ab : "virtual",
5553
+ executionId: (_cb = (_bb = payload.executionId) != null ? _bb : agentExecution == null ? void 0 : agentExecution.executionId) != null ? _cb : "",
5554
+ toolName: (_db = payload.toolName) != null ? _db : "",
5555
+ description: (_eb = payload.description) != null ? _eb : "",
5511
5556
  resolvedAt: Date.now()
5512
5557
  }
5513
5558
  };
@@ -5545,7 +5590,7 @@ var AgentWidgetClient = class {
5545
5590
  }
5546
5591
  } else if (payloadType === "artifact_delta") {
5547
5592
  const deltaId = String(payload.id);
5548
- const deltaText = typeof payload.delta === "string" ? payload.delta : String((_ib = payload.delta) != null ? _ib : "");
5593
+ const deltaText = typeof payload.delta === "string" ? payload.delta : String((_fb = payload.delta) != null ? _fb : "");
5549
5594
  onEvent({
5550
5595
  type: "artifact_delta",
5551
5596
  id: deltaId,
@@ -5568,7 +5613,7 @@ var AgentWidgetClient = class {
5568
5613
  if (refMsg) {
5569
5614
  refMsg.streaming = false;
5570
5615
  try {
5571
- const parsed = JSON.parse((_jb = refMsg.rawContent) != null ? _jb : "{}");
5616
+ const parsed = JSON.parse((_gb = refMsg.rawContent) != null ? _gb : "{}");
5572
5617
  if (parsed.props) {
5573
5618
  parsed.props.status = "complete";
5574
5619
  const acc = artifactContent.get(artCompleteId);
@@ -5589,7 +5634,7 @@ var AgentWidgetClient = class {
5589
5634
  if (!m || typeof m !== "object") {
5590
5635
  continue;
5591
5636
  }
5592
- const id = String((_kb = m.id) != null ? _kb : `msg-${nextSequence()}`);
5637
+ const id = String((_hb = m.id) != null ? _hb : `msg-${nextSequence()}`);
5593
5638
  const roleRaw = m.role;
5594
5639
  const role = roleRaw === "user" ? "user" : roleRaw === "system" ? "system" : "assistant";
5595
5640
  const msg = {
@@ -5608,7 +5653,7 @@ var AgentWidgetClient = class {
5608
5653
  if (msg.rawContent) {
5609
5654
  try {
5610
5655
  const parsed = JSON.parse(msg.rawContent);
5611
- const refArtId = (_lb = parsed == null ? void 0 : parsed.props) == null ? void 0 : _lb.artifactId;
5656
+ const refArtId = (_ib = parsed == null ? void 0 : parsed.props) == null ? void 0 : _ib.artifactId;
5612
5657
  if (typeof refArtId === "string") {
5613
5658
  artifactIdsWithCards.add(refArtId);
5614
5659
  }
@@ -5619,13 +5664,12 @@ var AgentWidgetClient = class {
5619
5664
  assistantMessageRef.current = null;
5620
5665
  streamParsers.delete(id);
5621
5666
  rawContentBuffers.delete(id);
5622
- seqChunkBuffers.delete(id);
5623
5667
  } else if (payloadType === "error" || payloadType === "step_error" || payloadType === "dispatch_error" || payloadType === "flow_error") {
5624
5668
  let resolvedError = null;
5625
5669
  if (payload.error instanceof Error) {
5626
5670
  resolvedError = payload.error;
5627
5671
  } else if (payloadType === "dispatch_error") {
5628
- const msg = (_mb = payload.message) != null ? _mb : payload.error;
5672
+ const msg = (_jb = payload.message) != null ? _jb : payload.error;
5629
5673
  if (msg != null && msg !== "") {
5630
5674
  resolvedError = new Error(String(msg));
5631
5675
  }
@@ -5634,7 +5678,7 @@ var AgentWidgetClient = class {
5634
5678
  if (typeof e === "string" && e !== "") {
5635
5679
  resolvedError = new Error(e);
5636
5680
  } else if (e != null && typeof e === "object" && "message" in e) {
5637
- resolvedError = new Error(String((_nb = e.message) != null ? _nb : e));
5681
+ resolvedError = new Error(String((_kb = e.message) != null ? _kb : e));
5638
5682
  }
5639
5683
  } else if (payloadType === "error" && payload.error != null && payload.error !== "") {
5640
5684
  resolvedError = new Error(String(payload.error));
@@ -5650,7 +5694,60 @@ var AgentWidgetClient = class {
5650
5694
  }
5651
5695
  }
5652
5696
  }
5697
+ seqReadyQueue.length = 0;
5698
+ };
5699
+ while (true) {
5700
+ const { done, value } = await reader.read();
5701
+ if (done) break;
5702
+ buffer += decoder.decode(value, { stream: true });
5703
+ const events = buffer.split("\n\n");
5704
+ buffer = (_b = events.pop()) != null ? _b : "";
5705
+ for (const event of events) {
5706
+ const lines = event.split("\n");
5707
+ let eventType = "message";
5708
+ let data = "";
5709
+ for (const line of lines) {
5710
+ if (line.startsWith("event:")) {
5711
+ eventType = line.replace("event:", "").trim();
5712
+ } else if (line.startsWith("data:")) {
5713
+ data += line.replace("data:", "").trim();
5714
+ }
5715
+ }
5716
+ if (!data) continue;
5717
+ let payload;
5718
+ try {
5719
+ payload = JSON.parse(data);
5720
+ } catch (error) {
5721
+ onEvent({
5722
+ type: "error",
5723
+ error: error instanceof Error ? error : new Error("Failed to parse chat stream payload")
5724
+ });
5725
+ continue;
5726
+ }
5727
+ const payloadType = eventType !== "message" ? eventType : (_c = payload.type) != null ? _c : "message";
5728
+ (_d = this.onSSEEvent) == null ? void 0 : _d.call(this, payloadType, payload);
5729
+ if (this.parseSSEEvent) {
5730
+ assistantMessageRef.current = assistantMessage;
5731
+ const handled = await this.handleCustomSSEEvent(
5732
+ payload,
5733
+ onEvent,
5734
+ assistantMessageRef,
5735
+ emitMessage,
5736
+ nextSequence,
5737
+ partIdState
5738
+ );
5739
+ if (assistantMessageRef.current && assistantMessageRef.current !== assistantMessage) {
5740
+ assistantMessage = assistantMessageRef.current;
5741
+ }
5742
+ if (handled) continue;
5743
+ }
5744
+ seqBuffer.push(payloadType, payload);
5745
+ drainReadyQueue();
5746
+ }
5653
5747
  }
5748
+ seqBuffer.flushPending();
5749
+ drainReadyQueue();
5750
+ seqBuffer.destroy();
5654
5751
  }
5655
5752
  };
5656
5753
 
@@ -14492,17 +14589,38 @@ var createAgentExperience = (mount, initialConfig, runtimeOptions) => {
14492
14589
  } else if (action === "upvote" || action === "downvote") {
14493
14590
  const currentVote = (_a2 = messageVoteState.get(messageId)) != null ? _a2 : null;
14494
14591
  const wasActive = currentVote === action;
14592
+ const iconName = action === "upvote" ? "thumbs-up" : "thumbs-down";
14495
14593
  if (wasActive) {
14496
14594
  messageVoteState.delete(messageId);
14497
14595
  actionBtn.classList.remove("persona-message-action-active");
14596
+ const outlineIcon = renderLucideIcon(iconName, 14, "currentColor", 2);
14597
+ if (outlineIcon) {
14598
+ actionBtn.innerHTML = "";
14599
+ actionBtn.appendChild(outlineIcon);
14600
+ }
14498
14601
  } else {
14499
14602
  const oppositeAction = action === "upvote" ? "downvote" : "upvote";
14500
14603
  const oppositeBtn = actionsContainer.querySelector(`[data-action="${oppositeAction}"]`);
14501
14604
  if (oppositeBtn) {
14502
14605
  oppositeBtn.classList.remove("persona-message-action-active");
14606
+ const oppositeIconName = oppositeAction === "upvote" ? "thumbs-up" : "thumbs-down";
14607
+ const outlineIcon = renderLucideIcon(oppositeIconName, 14, "currentColor", 2);
14608
+ if (outlineIcon) {
14609
+ oppositeBtn.innerHTML = "";
14610
+ oppositeBtn.appendChild(outlineIcon);
14611
+ }
14503
14612
  }
14504
14613
  messageVoteState.set(messageId, action);
14505
14614
  actionBtn.classList.add("persona-message-action-active");
14615
+ const filledIcon = renderLucideIcon(iconName, 14, "currentColor", 2);
14616
+ if (filledIcon) {
14617
+ filledIcon.setAttribute("fill", "currentColor");
14618
+ actionBtn.innerHTML = "";
14619
+ actionBtn.appendChild(filledIcon);
14620
+ }
14621
+ actionBtn.classList.remove("persona-message-action-pop");
14622
+ void actionBtn.offsetWidth;
14623
+ actionBtn.classList.add("persona-message-action-pop");
14506
14624
  const messages = session.getMessages();
14507
14625
  const message = messages.find((m) => m.id === messageId);
14508
14626
  if (message && messageActionCallbacks.onFeedback) {
@@ -15996,8 +16114,10 @@ var createAgentExperience = (mount, initialConfig, runtimeOptions) => {
15996
16114
  }
15997
16115
  });
15998
16116
  }
15999
- if (eventStreamBuffer) {
16117
+ if (eventStreamBuffer || config.onSSEEvent) {
16000
16118
  session.setSSEEventCallback((type, payload) => {
16119
+ var _a2;
16120
+ (_a2 = config.onSSEEvent) == null ? void 0 : _a2.call(config, type, payload);
16001
16121
  eventStreamBuffer == null ? void 0 : eventStreamBuffer.push({
16002
16122
  id: `evt-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
16003
16123
  type,
@@ -16838,6 +16958,8 @@ var createAgentExperience = (mount, initialConfig, runtimeOptions) => {
16838
16958
  eventStreamStore.open().then(() => eventStreamBuffer == null ? void 0 : eventStreamBuffer.restore()).catch(() => {
16839
16959
  });
16840
16960
  session.setSSEEventCallback((type, payload) => {
16961
+ var _a3;
16962
+ (_a3 = config.onSSEEvent) == null ? void 0 : _a3.call(config, type, payload);
16841
16963
  eventStreamBuffer.push({
16842
16964
  id: `evt-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
16843
16965
  type,