@runtypelabs/persona 3.15.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.
@@ -3453,6 +3453,94 @@ var createXmlParser = () => {
3453
3453
  };
3454
3454
  };
3455
3455
 
3456
+ // src/utils/sequence-buffer.ts
3457
+ var SequenceReorderBuffer = class {
3458
+ constructor(emitter, gapTimeoutMs = 50) {
3459
+ this.nextExpectedSeq = null;
3460
+ this.buffer = /* @__PURE__ */ new Map();
3461
+ this.flushTimer = null;
3462
+ this.emitter = emitter;
3463
+ this.gapTimeoutMs = gapTimeoutMs;
3464
+ }
3465
+ push(payloadType, payload) {
3466
+ var _a, _b, _c;
3467
+ 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;
3468
+ if (seq === void 0 || seq === null) {
3469
+ if (this.buffer.size > 0) {
3470
+ this.flushAll();
3471
+ }
3472
+ this.emitter(payloadType, payload);
3473
+ return;
3474
+ }
3475
+ if (this.nextExpectedSeq === null) {
3476
+ this.nextExpectedSeq = 1;
3477
+ }
3478
+ if (seq === this.nextExpectedSeq) {
3479
+ this.emitter(payloadType, payload);
3480
+ this.nextExpectedSeq = seq + 1;
3481
+ this.drainConsecutive();
3482
+ return;
3483
+ }
3484
+ if (seq < this.nextExpectedSeq) {
3485
+ this.emitter(payloadType, payload);
3486
+ return;
3487
+ }
3488
+ const existing = this.buffer.get(seq);
3489
+ if (existing !== void 0) {
3490
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
3491
+ console.warn(
3492
+ `[persona] SequenceReorderBuffer: duplicate seq=${seq} (${existing.payloadType} vs ${payloadType}); emitting earlier event out-of-order to avoid loss`
3493
+ );
3494
+ }
3495
+ this.emitter(existing.payloadType, existing.payload);
3496
+ }
3497
+ this.buffer.set(seq, { payloadType, payload, seq });
3498
+ this.startGapTimer();
3499
+ }
3500
+ drainConsecutive() {
3501
+ while (this.buffer.has(this.nextExpectedSeq)) {
3502
+ const event = this.buffer.get(this.nextExpectedSeq);
3503
+ this.buffer.delete(this.nextExpectedSeq);
3504
+ this.emitter(event.payloadType, event.payload);
3505
+ this.nextExpectedSeq++;
3506
+ }
3507
+ if (this.buffer.size === 0) {
3508
+ this.clearGapTimer();
3509
+ }
3510
+ }
3511
+ startGapTimer() {
3512
+ if (this.flushTimer !== null) return;
3513
+ this.flushTimer = setTimeout(() => {
3514
+ this.flushAll();
3515
+ }, this.gapTimeoutMs);
3516
+ }
3517
+ clearGapTimer() {
3518
+ if (this.flushTimer !== null) {
3519
+ clearTimeout(this.flushTimer);
3520
+ this.flushTimer = null;
3521
+ }
3522
+ }
3523
+ flushAll() {
3524
+ this.clearGapTimer();
3525
+ if (this.buffer.size === 0) return;
3526
+ const sorted = [...this.buffer.entries()].sort((a, b) => a[0] - b[0]);
3527
+ for (const [seq, event] of sorted) {
3528
+ this.buffer.delete(seq);
3529
+ this.emitter(event.payloadType, event.payload);
3530
+ }
3531
+ if (sorted.length > 0) {
3532
+ this.nextExpectedSeq = sorted[sorted.length - 1][0] + 1;
3533
+ }
3534
+ }
3535
+ destroy() {
3536
+ this.clearGapTimer();
3537
+ this.buffer.clear();
3538
+ }
3539
+ flushPending() {
3540
+ this.flushAll();
3541
+ }
3542
+ };
3543
+
3456
3544
  // src/client.ts
3457
3545
  var DEFAULT_ENDPOINT = "https://api.runtype.com/v1/dispatch";
3458
3546
  var DEFAULT_CLIENT_API_BASE = "https://api.runtype.com";
@@ -4220,7 +4308,7 @@ var AgentWidgetClient = class {
4220
4308
  }
4221
4309
  }
4222
4310
  async streamResponse(body, onEvent, assistantMessageId) {
4223
- 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;
4311
+ var _a, _b, _c, _d;
4224
4312
  const reader = body.getReader();
4225
4313
  const decoder = new TextDecoder();
4226
4314
  let buffer = "";
@@ -4276,15 +4364,15 @@ var AgentWidgetClient = class {
4276
4364
  }
4277
4365
  };
4278
4366
  const getStepKey = (payload) => {
4279
- var _a2, _b2, _c2, _d2, _e2;
4367
+ var _a2, _b2, _c2, _d2, _e;
4280
4368
  return normalizeKey(
4281
- (_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
4369
+ (_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
4282
4370
  );
4283
4371
  };
4284
4372
  const getToolCallKey = (payload) => {
4285
- var _a2, _b2, _c2, _d2, _e2, _f2, _g2;
4373
+ var _a2, _b2, _c2, _d2, _e, _f, _g;
4286
4374
  return normalizeKey(
4287
- (_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
4375
+ (_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
4288
4376
  );
4289
4377
  };
4290
4378
  const baseAssistantId = assistantMessageId;
@@ -4460,26 +4548,37 @@ var AgentWidgetClient = class {
4460
4548
  };
4461
4549
  const streamParsers = /* @__PURE__ */ new Map();
4462
4550
  const rawContentBuffers = /* @__PURE__ */ new Map();
4463
- const seqChunkBuffers = /* @__PURE__ */ new Map();
4464
- const reasonSeqBuffers = /* @__PURE__ */ new Map();
4465
- function insertSeqChunk(bufferMap, key, seq, text) {
4466
- let buf = bufferMap.get(key);
4467
- if (!buf) {
4468
- buf = [];
4469
- bufferMap.set(key, buf);
4470
- }
4471
- let lo = 0, hi = buf.length;
4551
+ const orderedChunkBuffers = /* @__PURE__ */ new Map();
4552
+ const assistantMessagesByPartId = /* @__PURE__ */ new Map();
4553
+ let lastSealedTextSegment = null;
4554
+ const insertOrderedChunk = (key, seq, text) => {
4555
+ var _a2;
4556
+ let chunks = orderedChunkBuffers.get(key);
4557
+ if (!chunks) {
4558
+ chunks = [];
4559
+ orderedChunkBuffers.set(key, chunks);
4560
+ }
4561
+ let lo = 0;
4562
+ let hi = chunks.length;
4472
4563
  while (lo < hi) {
4473
4564
  const mid = lo + hi >>> 1;
4474
- if (buf[mid].seq < seq) lo = mid + 1;
4475
- else hi = mid;
4565
+ if (chunks[mid].seq < seq) {
4566
+ lo = mid + 1;
4567
+ } else {
4568
+ hi = mid;
4569
+ }
4476
4570
  }
4477
- buf.splice(lo, 0, { seq, text });
4478
- let result = "";
4479
- for (let i = 0; i < buf.length; i++) result += buf[i].text;
4480
- return result;
4481
- }
4482
- let lastSealedTextSegment = null;
4571
+ if (((_a2 = chunks[lo]) == null ? void 0 : _a2.seq) === seq) {
4572
+ chunks[lo] = { seq, text };
4573
+ } else {
4574
+ chunks.splice(lo, 0, { seq, text });
4575
+ }
4576
+ let accumulated = "";
4577
+ for (let index = 0; index < chunks.length; index++) {
4578
+ accumulated += chunks[index].text;
4579
+ }
4580
+ return accumulated;
4581
+ };
4483
4582
  const reconcileSealedAssistantWithFinalResponse = (msg, finalContent) => {
4484
4583
  const finalString = ensureStringContent(finalContent);
4485
4584
  const rawBuffer = rawContentBuffers.get(msg.id);
@@ -4546,82 +4645,57 @@ var AgentWidgetClient = class {
4546
4645
  mergeIfBetter(bestDisplayText(parsedResult));
4547
4646
  finalizeCleanup();
4548
4647
  };
4648
+ const seqReadyQueue = [];
4649
+ let isDrainScheduled = false;
4650
+ let drainReadyQueue;
4651
+ const scheduleReadyQueueDrain = () => {
4652
+ if (isDrainScheduled) return;
4653
+ isDrainScheduled = true;
4654
+ queueMicrotask(() => {
4655
+ isDrainScheduled = false;
4656
+ drainReadyQueue();
4657
+ });
4658
+ };
4659
+ const seqBuffer = new SequenceReorderBuffer((payloadType, payload) => {
4660
+ seqReadyQueue.push({ payloadType, payload });
4661
+ scheduleReadyQueueDrain();
4662
+ });
4549
4663
  let agentExecution = null;
4550
4664
  const agentIterationMessages = /* @__PURE__ */ new Map();
4551
4665
  const iterationDisplay = (_a = this.config.iterationDisplay) != null ? _a : "separate";
4552
- while (true) {
4553
- const { done, value } = await reader.read();
4554
- if (done) break;
4555
- buffer += decoder.decode(value, { stream: true });
4556
- const events = buffer.split("\n\n");
4557
- buffer = (_b = events.pop()) != null ? _b : "";
4558
- for (const event of events) {
4559
- const lines = event.split("\n");
4560
- let eventType = "message";
4561
- let data = "";
4562
- for (const line of lines) {
4563
- if (line.startsWith("event:")) {
4564
- eventType = line.replace("event:", "").trim();
4565
- } else if (line.startsWith("data:")) {
4566
- data += line.replace("data:", "").trim();
4567
- }
4568
- }
4569
- if (!data) continue;
4570
- let payload;
4571
- try {
4572
- payload = JSON.parse(data);
4573
- } catch (error) {
4574
- onEvent({
4575
- type: "error",
4576
- error: error instanceof Error ? error : new Error("Failed to parse chat stream payload")
4577
- });
4578
- continue;
4579
- }
4580
- const payloadType = eventType !== "message" ? eventType : (_c = payload.type) != null ? _c : "message";
4581
- (_d = this.onSSEEvent) == null ? void 0 : _d.call(this, payloadType, payload);
4582
- if (this.parseSSEEvent) {
4583
- assistantMessageRef.current = assistantMessage;
4584
- const handled = await this.handleCustomSSEEvent(
4585
- payload,
4586
- onEvent,
4587
- assistantMessageRef,
4588
- emitMessage,
4589
- nextSequence,
4590
- partIdState
4591
- );
4592
- if (assistantMessageRef.current && assistantMessageRef.current !== assistantMessage) {
4593
- assistantMessage = assistantMessageRef.current;
4594
- }
4595
- if (handled) continue;
4596
- }
4666
+ drainReadyQueue = () => {
4667
+ 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;
4668
+ for (let i = 0; i < seqReadyQueue.length; i++) {
4669
+ const payloadType = seqReadyQueue[i].payloadType;
4670
+ const payload = seqReadyQueue[i].payload;
4597
4671
  if (payloadType === "reason_start") {
4598
- const reasoningId = (_e = resolveReasoningId(payload, true)) != null ? _e : `reason-${nextSequence()}`;
4672
+ const reasoningId = (_a2 = resolveReasoningId(payload, true)) != null ? _a2 : `reason-${nextSequence()}`;
4599
4673
  const reasoningMessage = ensureReasoningMessage(reasoningId);
4600
- reasoningMessage.reasoning = (_f = reasoningMessage.reasoning) != null ? _f : {
4674
+ reasoningMessage.reasoning = (_b2 = reasoningMessage.reasoning) != null ? _b2 : {
4601
4675
  id: reasoningId,
4602
4676
  status: "streaming",
4603
4677
  chunks: []
4604
4678
  };
4605
- reasoningMessage.reasoning.startedAt = (_h = reasoningMessage.reasoning.startedAt) != null ? _h : resolveTimestamp((_g = payload.startedAt) != null ? _g : payload.timestamp);
4679
+ reasoningMessage.reasoning.startedAt = (_d2 = reasoningMessage.reasoning.startedAt) != null ? _d2 : resolveTimestamp((_c2 = payload.startedAt) != null ? _c2 : payload.timestamp);
4606
4680
  reasoningMessage.reasoning.completedAt = void 0;
4607
4681
  reasoningMessage.reasoning.durationMs = void 0;
4608
4682
  reasoningMessage.streaming = true;
4609
4683
  reasoningMessage.reasoning.status = "streaming";
4610
4684
  emitMessage(reasoningMessage);
4611
4685
  } else if (payloadType === "reason_delta" || payloadType === "reason_chunk") {
4612
- const reasoningId = (_j = (_i = resolveReasoningId(payload, false)) != null ? _i : resolveReasoningId(payload, true)) != null ? _j : `reason-${nextSequence()}`;
4686
+ const reasoningId = (_f = (_e = resolveReasoningId(payload, false)) != null ? _e : resolveReasoningId(payload, true)) != null ? _f : `reason-${nextSequence()}`;
4613
4687
  const reasoningMessage = ensureReasoningMessage(reasoningId);
4614
- reasoningMessage.reasoning = (_k = reasoningMessage.reasoning) != null ? _k : {
4688
+ reasoningMessage.reasoning = (_g = reasoningMessage.reasoning) != null ? _g : {
4615
4689
  id: reasoningId,
4616
4690
  status: "streaming",
4617
4691
  chunks: []
4618
4692
  };
4619
- reasoningMessage.reasoning.startedAt = (_m = reasoningMessage.reasoning.startedAt) != null ? _m : resolveTimestamp((_l = payload.startedAt) != null ? _l : payload.timestamp);
4620
- const chunk = (_p = (_o = (_n = payload.reasoningText) != null ? _n : payload.text) != null ? _o : payload.delta) != null ? _p : "";
4693
+ reasoningMessage.reasoning.startedAt = (_i = reasoningMessage.reasoning.startedAt) != null ? _i : resolveTimestamp((_h = payload.startedAt) != null ? _h : payload.timestamp);
4694
+ const chunk = (_l = (_k = (_j = payload.reasoningText) != null ? _j : payload.text) != null ? _k : payload.delta) != null ? _l : "";
4621
4695
  if (chunk && payload.hidden !== true) {
4622
4696
  const reasonSeq = typeof payload.sequenceIndex === "number" ? payload.sequenceIndex : void 0;
4623
4697
  if (reasonSeq !== void 0) {
4624
- const ordered = insertSeqChunk(reasonSeqBuffers, reasoningId, reasonSeq, String(chunk));
4698
+ const ordered = insertOrderedChunk(reasoningId, reasonSeq, String(chunk));
4625
4699
  reasoningMessage.reasoning.chunks = [ordered];
4626
4700
  } else {
4627
4701
  reasoningMessage.reasoning.chunks.push(String(chunk));
@@ -4630,32 +4704,30 @@ var AgentWidgetClient = class {
4630
4704
  reasoningMessage.reasoning.status = payload.done ? "complete" : "streaming";
4631
4705
  if (payload.done) {
4632
4706
  reasoningMessage.reasoning.completedAt = resolveTimestamp(
4633
- (_q = payload.completedAt) != null ? _q : payload.timestamp
4707
+ (_m = payload.completedAt) != null ? _m : payload.timestamp
4634
4708
  );
4635
- const start = (_r = reasoningMessage.reasoning.startedAt) != null ? _r : Date.now();
4709
+ const start = (_n = reasoningMessage.reasoning.startedAt) != null ? _n : Date.now();
4636
4710
  reasoningMessage.reasoning.durationMs = Math.max(
4637
4711
  0,
4638
- ((_s = reasoningMessage.reasoning.completedAt) != null ? _s : Date.now()) - start
4712
+ ((_o = reasoningMessage.reasoning.completedAt) != null ? _o : Date.now()) - start
4639
4713
  );
4640
- reasonSeqBuffers.delete(reasoningId);
4641
4714
  }
4642
4715
  reasoningMessage.streaming = reasoningMessage.reasoning.status !== "complete";
4643
4716
  emitMessage(reasoningMessage);
4644
4717
  } else if (payloadType === "reason_complete") {
4645
- const reasoningId = (_u = (_t = resolveReasoningId(payload, false)) != null ? _t : resolveReasoningId(payload, true)) != null ? _u : `reason-${nextSequence()}`;
4718
+ const reasoningId = (_q = (_p = resolveReasoningId(payload, false)) != null ? _p : resolveReasoningId(payload, true)) != null ? _q : `reason-${nextSequence()}`;
4646
4719
  const reasoningMessage = reasoningMessages.get(reasoningId);
4647
4720
  if (reasoningMessage == null ? void 0 : reasoningMessage.reasoning) {
4648
4721
  reasoningMessage.reasoning.status = "complete";
4649
4722
  reasoningMessage.reasoning.completedAt = resolveTimestamp(
4650
- (_v = payload.completedAt) != null ? _v : payload.timestamp
4723
+ (_r = payload.completedAt) != null ? _r : payload.timestamp
4651
4724
  );
4652
- const start = (_w = reasoningMessage.reasoning.startedAt) != null ? _w : Date.now();
4725
+ const start = (_s = reasoningMessage.reasoning.startedAt) != null ? _s : Date.now();
4653
4726
  reasoningMessage.reasoning.durationMs = Math.max(
4654
4727
  0,
4655
- ((_x = reasoningMessage.reasoning.completedAt) != null ? _x : Date.now()) - start
4728
+ ((_t = reasoningMessage.reasoning.completedAt) != null ? _t : Date.now()) - start
4656
4729
  );
4657
4730
  reasoningMessage.streaming = false;
4658
- reasonSeqBuffers.delete(reasoningId);
4659
4731
  emitMessage(reasoningMessage);
4660
4732
  }
4661
4733
  const stepKey = getStepKey(payload);
@@ -4663,14 +4735,14 @@ var AgentWidgetClient = class {
4663
4735
  reasoningContext.byStep.delete(stepKey);
4664
4736
  }
4665
4737
  } else if (payloadType === "tool_start") {
4666
- const toolId = (_y = resolveToolId(payload, true)) != null ? _y : `tool-${nextSequence()}`;
4667
- const toolName = (_z = payload.toolName) != null ? _z : payload.name;
4738
+ const toolId = (_u = resolveToolId(payload, true)) != null ? _u : `tool-${nextSequence()}`;
4739
+ const toolName = (_v = payload.toolName) != null ? _v : payload.name;
4668
4740
  if (isArtifactEmitToolName(toolName)) {
4669
4741
  artifactToolCallIds.add(toolId);
4670
4742
  continue;
4671
4743
  }
4672
4744
  const toolMessage = ensureToolMessage(toolId);
4673
- const tool = (_A = toolMessage.toolCall) != null ? _A : {
4745
+ const tool = (_w = toolMessage.toolCall) != null ? _w : {
4674
4746
  id: toolId,
4675
4747
  status: "pending"
4676
4748
  };
@@ -4681,7 +4753,7 @@ var AgentWidgetClient = class {
4681
4753
  } else if (payload.parameters !== void 0) {
4682
4754
  tool.args = payload.parameters;
4683
4755
  }
4684
- tool.startedAt = (_C = tool.startedAt) != null ? _C : resolveTimestamp((_B = payload.startedAt) != null ? _B : payload.timestamp);
4756
+ tool.startedAt = (_y = tool.startedAt) != null ? _y : resolveTimestamp((_x = payload.startedAt) != null ? _x : payload.timestamp);
4685
4757
  tool.completedAt = void 0;
4686
4758
  tool.durationMs = void 0;
4687
4759
  toolMessage.toolCall = tool;
@@ -4689,23 +4761,23 @@ var AgentWidgetClient = class {
4689
4761
  const agentCtx = payload.agentContext;
4690
4762
  if (agentCtx || payload.executionId) {
4691
4763
  toolMessage.agentMetadata = {
4692
- executionId: (_D = agentCtx == null ? void 0 : agentCtx.executionId) != null ? _D : payload.executionId,
4693
- iteration: (_E = agentCtx == null ? void 0 : agentCtx.iteration) != null ? _E : payload.iteration
4764
+ executionId: (_z = agentCtx == null ? void 0 : agentCtx.executionId) != null ? _z : payload.executionId,
4765
+ iteration: (_A = agentCtx == null ? void 0 : agentCtx.iteration) != null ? _A : payload.iteration
4694
4766
  };
4695
4767
  }
4696
4768
  emitMessage(toolMessage);
4697
4769
  } else if (payloadType === "tool_chunk" || payloadType === "tool_delta") {
4698
- const toolId = (_G = (_F = resolveToolId(payload, false)) != null ? _F : resolveToolId(payload, true)) != null ? _G : `tool-${nextSequence()}`;
4770
+ const toolId = (_C = (_B = resolveToolId(payload, false)) != null ? _B : resolveToolId(payload, true)) != null ? _C : `tool-${nextSequence()}`;
4699
4771
  if (artifactToolCallIds.has(toolId)) continue;
4700
4772
  const toolMessage = ensureToolMessage(toolId);
4701
- const tool = (_H = toolMessage.toolCall) != null ? _H : {
4773
+ const tool = (_D = toolMessage.toolCall) != null ? _D : {
4702
4774
  id: toolId,
4703
4775
  status: "running"
4704
4776
  };
4705
- tool.startedAt = (_J = tool.startedAt) != null ? _J : resolveTimestamp((_I = payload.startedAt) != null ? _I : payload.timestamp);
4706
- const chunkText = (_M = (_L = (_K = payload.text) != null ? _K : payload.delta) != null ? _L : payload.message) != null ? _M : "";
4777
+ tool.startedAt = (_F = tool.startedAt) != null ? _F : resolveTimestamp((_E = payload.startedAt) != null ? _E : payload.timestamp);
4778
+ const chunkText = (_I = (_H = (_G = payload.text) != null ? _G : payload.delta) != null ? _H : payload.message) != null ? _I : "";
4707
4779
  if (chunkText) {
4708
- tool.chunks = (_N = tool.chunks) != null ? _N : [];
4780
+ tool.chunks = (_J = tool.chunks) != null ? _J : [];
4709
4781
  tool.chunks.push(String(chunkText));
4710
4782
  }
4711
4783
  tool.status = "running";
@@ -4713,20 +4785,20 @@ var AgentWidgetClient = class {
4713
4785
  toolMessage.streaming = true;
4714
4786
  const agentCtxChunk = payload.agentContext;
4715
4787
  if (agentCtxChunk || payload.executionId) {
4716
- toolMessage.agentMetadata = (_Q = toolMessage.agentMetadata) != null ? _Q : {
4717
- executionId: (_O = agentCtxChunk == null ? void 0 : agentCtxChunk.executionId) != null ? _O : payload.executionId,
4718
- iteration: (_P = agentCtxChunk == null ? void 0 : agentCtxChunk.iteration) != null ? _P : payload.iteration
4788
+ toolMessage.agentMetadata = (_M = toolMessage.agentMetadata) != null ? _M : {
4789
+ executionId: (_K = agentCtxChunk == null ? void 0 : agentCtxChunk.executionId) != null ? _K : payload.executionId,
4790
+ iteration: (_L = agentCtxChunk == null ? void 0 : agentCtxChunk.iteration) != null ? _L : payload.iteration
4719
4791
  };
4720
4792
  }
4721
4793
  emitMessage(toolMessage);
4722
4794
  } else if (payloadType === "tool_complete") {
4723
- const toolId = (_S = (_R = resolveToolId(payload, false)) != null ? _R : resolveToolId(payload, true)) != null ? _S : `tool-${nextSequence()}`;
4795
+ const toolId = (_O = (_N = resolveToolId(payload, false)) != null ? _N : resolveToolId(payload, true)) != null ? _O : `tool-${nextSequence()}`;
4724
4796
  if (artifactToolCallIds.has(toolId)) {
4725
4797
  artifactToolCallIds.delete(toolId);
4726
4798
  continue;
4727
4799
  }
4728
4800
  const toolMessage = ensureToolMessage(toolId);
4729
- const tool = (_T = toolMessage.toolCall) != null ? _T : {
4801
+ const tool = (_P = toolMessage.toolCall) != null ? _P : {
4730
4802
  id: toolId,
4731
4803
  status: "running"
4732
4804
  };
@@ -4738,25 +4810,25 @@ var AgentWidgetClient = class {
4738
4810
  tool.duration = payload.duration;
4739
4811
  }
4740
4812
  tool.completedAt = resolveTimestamp(
4741
- (_U = payload.completedAt) != null ? _U : payload.timestamp
4813
+ (_Q = payload.completedAt) != null ? _Q : payload.timestamp
4742
4814
  );
4743
- const durationValue = (_V = payload.duration) != null ? _V : payload.executionTime;
4815
+ const durationValue = (_R = payload.duration) != null ? _R : payload.executionTime;
4744
4816
  if (typeof durationValue === "number") {
4745
4817
  tool.durationMs = durationValue;
4746
4818
  } else {
4747
- const start = (_W = tool.startedAt) != null ? _W : Date.now();
4819
+ const start = (_S = tool.startedAt) != null ? _S : Date.now();
4748
4820
  tool.durationMs = Math.max(
4749
4821
  0,
4750
- ((_X = tool.completedAt) != null ? _X : Date.now()) - start
4822
+ ((_T = tool.completedAt) != null ? _T : Date.now()) - start
4751
4823
  );
4752
4824
  }
4753
4825
  toolMessage.toolCall = tool;
4754
4826
  toolMessage.streaming = false;
4755
4827
  const agentCtxComplete = payload.agentContext;
4756
4828
  if (agentCtxComplete || payload.executionId) {
4757
- toolMessage.agentMetadata = (__ = toolMessage.agentMetadata) != null ? __ : {
4758
- executionId: (_Y = agentCtxComplete == null ? void 0 : agentCtxComplete.executionId) != null ? _Y : payload.executionId,
4759
- iteration: (_Z = agentCtxComplete == null ? void 0 : agentCtxComplete.iteration) != null ? _Z : payload.iteration
4829
+ toolMessage.agentMetadata = (_W = toolMessage.agentMetadata) != null ? _W : {
4830
+ executionId: (_U = agentCtxComplete == null ? void 0 : agentCtxComplete.executionId) != null ? _U : payload.executionId,
4831
+ iteration: (_V = agentCtxComplete == null ? void 0 : agentCtxComplete.iteration) != null ? _V : payload.iteration
4760
4832
  };
4761
4833
  }
4762
4834
  emitMessage(toolMessage);
@@ -4808,20 +4880,18 @@ var AgentWidgetClient = class {
4808
4880
  if (incomingPartId !== void 0) {
4809
4881
  partIdState.current = incomingPartId;
4810
4882
  }
4811
- const assistant = ensureAssistantMessage();
4812
- if (incomingPartId !== void 0 && !assistant.partId) {
4813
- assistant.partId = incomingPartId;
4883
+ const assistant = incomingPartId !== void 0 ? (_X = assistantMessagesByPartId.get(incomingPartId)) != null ? _X : ensureAssistantMessage() : ensureAssistantMessage();
4884
+ if (incomingPartId !== void 0) {
4885
+ if (!assistant.partId) {
4886
+ assistant.partId = incomingPartId;
4887
+ }
4888
+ assistantMessagesByPartId.set(incomingPartId, assistant);
4814
4889
  }
4815
- const chunk = (_ca = (_ba = (_aa = (_$ = payload.text) != null ? _$ : payload.delta) != null ? _aa : payload.content) != null ? _ba : payload.chunk) != null ? _ca : "";
4890
+ const chunk = (_$ = (__ = (_Z = (_Y = payload.text) != null ? _Y : payload.delta) != null ? _Z : payload.content) != null ? __ : payload.chunk) != null ? _$ : "";
4816
4891
  if (chunk) {
4817
4892
  const chunkSeq = typeof payload.seq === "number" ? payload.seq : void 0;
4818
- let accumulatedRaw;
4819
- if (chunkSeq !== void 0) {
4820
- accumulatedRaw = insertSeqChunk(seqChunkBuffers, assistant.id, chunkSeq, chunk);
4821
- } else {
4822
- const rawBuffer = (_da = rawContentBuffers.get(assistant.id)) != null ? _da : "";
4823
- accumulatedRaw = rawBuffer + chunk;
4824
- }
4893
+ const chunkBufferKey = incomingPartId != null ? incomingPartId : assistant.id;
4894
+ const accumulatedRaw = chunkSeq !== void 0 ? insertOrderedChunk(chunkBufferKey, chunkSeq, String(chunk)) : ((_aa = rawContentBuffers.get(assistant.id)) != null ? _aa : "") + chunk;
4825
4895
  assistant.rawContent = accumulatedRaw;
4826
4896
  if (!streamParsers.has(assistant.id)) {
4827
4897
  streamParsers.set(assistant.id, this.createStreamParser());
@@ -4833,11 +4903,7 @@ var AgentWidgetClient = class {
4833
4903
  }
4834
4904
  const isPlainTextParser = parser.__isPlainTextParser === true;
4835
4905
  if (isPlainTextParser) {
4836
- if (chunkSeq !== void 0) {
4837
- assistant.content = accumulatedRaw;
4838
- } else {
4839
- assistant.content += chunk;
4840
- }
4906
+ assistant.content = chunkSeq !== void 0 ? accumulatedRaw : assistant.content + chunk;
4841
4907
  rawContentBuffers.delete(assistant.id);
4842
4908
  streamParsers.delete(assistant.id);
4843
4909
  assistant.rawContent = void 0;
@@ -4847,47 +4913,36 @@ var AgentWidgetClient = class {
4847
4913
  const parsedResult = parser.processChunk(accumulatedRaw);
4848
4914
  if (parsedResult instanceof Promise) {
4849
4915
  parsedResult.then((result) => {
4850
- var _a2;
4851
- const text = typeof result === "string" ? result : (_a2 = result == null ? void 0 : result.text) != null ? _a2 : null;
4916
+ var _a3;
4917
+ const text = typeof result === "string" ? result : (_a3 = result == null ? void 0 : result.text) != null ? _a3 : null;
4852
4918
  if (text !== null && text.trim() !== "") {
4853
4919
  assistant.content = text;
4854
4920
  emitMessage(assistant);
4855
4921
  } else if (!looksLikeJson && !accumulatedRaw.trim().startsWith("<")) {
4856
4922
  const currentAssistant = assistantMessage;
4857
- if (currentAssistant && currentAssistant.id === assistant.id) {
4858
- if (chunkSeq !== void 0) {
4859
- currentAssistant.content = accumulatedRaw;
4860
- } else {
4861
- currentAssistant.content += chunk;
4862
- }
4863
- rawContentBuffers.delete(currentAssistant.id);
4864
- streamParsers.delete(currentAssistant.id);
4865
- currentAssistant.rawContent = void 0;
4866
- emitMessage(currentAssistant);
4923
+ const targetAssistant = currentAssistant && currentAssistant.id === assistant.id ? currentAssistant : assistant;
4924
+ if (targetAssistant.id === assistant.id) {
4925
+ targetAssistant.content = chunkSeq !== void 0 ? accumulatedRaw : targetAssistant.content + chunk;
4926
+ rawContentBuffers.delete(targetAssistant.id);
4927
+ streamParsers.delete(targetAssistant.id);
4928
+ targetAssistant.rawContent = void 0;
4929
+ emitMessage(targetAssistant);
4867
4930
  }
4868
4931
  }
4869
4932
  }).catch(() => {
4870
- if (chunkSeq !== void 0) {
4871
- assistant.content = accumulatedRaw;
4872
- } else {
4873
- assistant.content += chunk;
4874
- }
4933
+ assistant.content = chunkSeq !== void 0 ? accumulatedRaw : assistant.content + chunk;
4875
4934
  rawContentBuffers.delete(assistant.id);
4876
4935
  streamParsers.delete(assistant.id);
4877
4936
  assistant.rawContent = void 0;
4878
4937
  emitMessage(assistant);
4879
4938
  });
4880
4939
  } else {
4881
- const text = typeof parsedResult === "string" ? parsedResult : (_ea = parsedResult == null ? void 0 : parsedResult.text) != null ? _ea : null;
4940
+ const text = typeof parsedResult === "string" ? parsedResult : (_ba = parsedResult == null ? void 0 : parsedResult.text) != null ? _ba : null;
4882
4941
  if (text !== null && text.trim() !== "") {
4883
4942
  assistant.content = text;
4884
4943
  emitMessage(assistant);
4885
4944
  } else if (!looksLikeJson && !accumulatedRaw.trim().startsWith("<")) {
4886
- if (chunkSeq !== void 0) {
4887
- assistant.content = accumulatedRaw;
4888
- } else {
4889
- assistant.content += chunk;
4890
- }
4945
+ assistant.content = chunkSeq !== void 0 ? accumulatedRaw : assistant.content + chunk;
4891
4946
  rawContentBuffers.delete(assistant.id);
4892
4947
  streamParsers.delete(assistant.id);
4893
4948
  assistant.rawContent = void 0;
@@ -4896,7 +4951,7 @@ var AgentWidgetClient = class {
4896
4951
  }
4897
4952
  }
4898
4953
  if (payload.isComplete) {
4899
- const finalContent = (_ga = (_fa = payload.result) == null ? void 0 : _fa.response) != null ? _ga : assistant.content;
4954
+ const finalContent = (_da = (_ca = payload.result) == null ? void 0 : _ca.response) != null ? _da : assistant.content;
4900
4955
  if (finalContent) {
4901
4956
  const rawBuffer = rawContentBuffers.get(assistant.id);
4902
4957
  const contentToProcess = rawBuffer != null ? rawBuffer : ensureStringContent(finalContent);
@@ -4914,8 +4969,8 @@ var AgentWidgetClient = class {
4914
4969
  if (parsedResult instanceof Promise) {
4915
4970
  asyncPending = true;
4916
4971
  parsedResult.then((result) => {
4917
- var _a2;
4918
- const text = typeof result === "string" ? result : (_a2 = result == null ? void 0 : result.text) != null ? _a2 : null;
4972
+ var _a3;
4973
+ const text = typeof result === "string" ? result : (_a3 = result == null ? void 0 : result.text) != null ? _a3 : null;
4919
4974
  if (text !== null) {
4920
4975
  const currentAssistant = assistantMessage;
4921
4976
  if (currentAssistant && currentAssistant.id === assistant.id) {
@@ -4923,13 +4978,12 @@ var AgentWidgetClient = class {
4923
4978
  currentAssistant.streaming = false;
4924
4979
  streamParsers.delete(currentAssistant.id);
4925
4980
  rawContentBuffers.delete(currentAssistant.id);
4926
- seqChunkBuffers.delete(currentAssistant.id);
4927
4981
  emitMessage(currentAssistant);
4928
4982
  }
4929
4983
  }
4930
4984
  });
4931
4985
  } else {
4932
- extractedText = typeof parsedResult === "string" ? parsedResult : (_ha = parsedResult == null ? void 0 : parsedResult.text) != null ? _ha : null;
4986
+ extractedText = typeof parsedResult === "string" ? parsedResult : (_ea = parsedResult == null ? void 0 : parsedResult.text) != null ? _ea : null;
4933
4987
  }
4934
4988
  }
4935
4989
  }
@@ -4941,7 +4995,7 @@ var AgentWidgetClient = class {
4941
4995
  }
4942
4996
  const parserToClose = streamParsers.get(assistant.id);
4943
4997
  if (parserToClose) {
4944
- const closeResult = (_ia = parserToClose.close) == null ? void 0 : _ia.call(parserToClose);
4998
+ const closeResult = (_fa = parserToClose.close) == null ? void 0 : _fa.call(parserToClose);
4945
4999
  if (closeResult instanceof Promise) {
4946
5000
  closeResult.catch(() => {
4947
5001
  });
@@ -4949,7 +5003,6 @@ var AgentWidgetClient = class {
4949
5003
  streamParsers.delete(assistant.id);
4950
5004
  }
4951
5005
  rawContentBuffers.delete(assistant.id);
4952
- seqChunkBuffers.delete(assistant.id);
4953
5006
  assistant.streaming = false;
4954
5007
  emitMessage(assistant);
4955
5008
  }
@@ -4966,13 +5019,12 @@ var AgentWidgetClient = class {
4966
5019
  const msg = assistantMessage;
4967
5020
  streamParsers.delete(msg.id);
4968
5021
  rawContentBuffers.delete(msg.id);
4969
- seqChunkBuffers.delete(msg.id);
4970
5022
  if (msg.streaming !== false) {
4971
5023
  msg.streaming = false;
4972
5024
  emitMessage(msg);
4973
5025
  }
4974
5026
  }
4975
- const splitFinalContent = (_ja = payload.result) == null ? void 0 : _ja.response;
5027
+ const splitFinalContent = (_ga = payload.result) == null ? void 0 : _ga.response;
4976
5028
  const sealedForReconcile = lastSealedTextSegment;
4977
5029
  if (sealedForReconcile) {
4978
5030
  if (splitFinalContent !== void 0 && splitFinalContent !== null) {
@@ -4985,7 +5037,7 @@ var AgentWidgetClient = class {
4985
5037
  lastSealedTextSegment = null;
4986
5038
  continue;
4987
5039
  }
4988
- const finalContent = (_ka = payload.result) == null ? void 0 : _ka.response;
5040
+ const finalContent = (_ha = payload.result) == null ? void 0 : _ha.response;
4989
5041
  const assistant = ensureAssistantMessage();
4990
5042
  if (finalContent !== void 0 && finalContent !== null) {
4991
5043
  const parser = streamParsers.get(assistant.id);
@@ -5009,8 +5061,8 @@ var AgentWidgetClient = class {
5009
5061
  if (parsedResult instanceof Promise) {
5010
5062
  asyncPending = true;
5011
5063
  parsedResult.then((result) => {
5012
- var _a2;
5013
- const text = typeof result === "string" ? result : (_a2 = result == null ? void 0 : result.text) != null ? _a2 : null;
5064
+ var _a3;
5065
+ const text = typeof result === "string" ? result : (_a3 = result == null ? void 0 : result.text) != null ? _a3 : null;
5014
5066
  if (text !== null && text.trim() !== "") {
5015
5067
  const currentAssistant = assistantMessage;
5016
5068
  if (currentAssistant && currentAssistant.id === assistant.id) {
@@ -5018,7 +5070,6 @@ var AgentWidgetClient = class {
5018
5070
  currentAssistant.streaming = false;
5019
5071
  streamParsers.delete(currentAssistant.id);
5020
5072
  rawContentBuffers.delete(currentAssistant.id);
5021
- seqChunkBuffers.delete(currentAssistant.id);
5022
5073
  emitMessage(currentAssistant);
5023
5074
  }
5024
5075
  } else {
@@ -5033,13 +5084,12 @@ var AgentWidgetClient = class {
5033
5084
  currentAssistant.streaming = false;
5034
5085
  streamParsers.delete(currentAssistant.id);
5035
5086
  rawContentBuffers.delete(currentAssistant.id);
5036
- seqChunkBuffers.delete(currentAssistant.id);
5037
5087
  emitMessage(currentAssistant);
5038
5088
  }
5039
5089
  }
5040
5090
  });
5041
5091
  } else {
5042
- const text = typeof parsedResult === "string" ? parsedResult : (_la = parsedResult == null ? void 0 : parsedResult.text) != null ? _la : null;
5092
+ const text = typeof parsedResult === "string" ? parsedResult : (_ia = parsedResult == null ? void 0 : parsedResult.text) != null ? _ia : null;
5043
5093
  if (text !== null && text.trim() !== "") {
5044
5094
  assistant.content = text;
5045
5095
  hasExtractedText = true;
@@ -5063,7 +5113,7 @@ var AgentWidgetClient = class {
5063
5113
  assistant.content = ensureStringContent(finalContent);
5064
5114
  }
5065
5115
  if (parser) {
5066
- const closeResult = (_ma = parser.close) == null ? void 0 : _ma.call(parser);
5116
+ const closeResult = (_ja = parser.close) == null ? void 0 : _ja.call(parser);
5067
5117
  if (closeResult instanceof Promise) {
5068
5118
  closeResult.catch(() => {
5069
5119
  });
@@ -5071,25 +5121,22 @@ var AgentWidgetClient = class {
5071
5121
  }
5072
5122
  streamParsers.delete(assistant.id);
5073
5123
  rawContentBuffers.delete(assistant.id);
5074
- seqChunkBuffers.delete(assistant.id);
5075
5124
  assistant.streaming = false;
5076
5125
  emitMessage(assistant);
5077
5126
  }
5078
5127
  } else {
5079
5128
  streamParsers.delete(assistant.id);
5080
5129
  rawContentBuffers.delete(assistant.id);
5081
- seqChunkBuffers.delete(assistant.id);
5082
5130
  assistant.streaming = false;
5083
5131
  emitMessage(assistant);
5084
5132
  }
5085
5133
  } else if (payloadType === "flow_complete") {
5086
- const finalContent = (_na = payload.result) == null ? void 0 : _na.response;
5134
+ const finalContent = (_ka = payload.result) == null ? void 0 : _ka.response;
5087
5135
  if (didSplitByPartId) {
5088
5136
  if (assistantMessage !== null) {
5089
5137
  const msg = assistantMessage;
5090
5138
  streamParsers.delete(msg.id);
5091
5139
  rawContentBuffers.delete(msg.id);
5092
- seqChunkBuffers.delete(msg.id);
5093
5140
  if (msg.streaming !== false) {
5094
5141
  msg.streaming = false;
5095
5142
  emitMessage(msg);
@@ -5110,8 +5157,8 @@ var AgentWidgetClient = class {
5110
5157
  const parsedResult = parser.processChunk(stringContent);
5111
5158
  if (parsedResult instanceof Promise) {
5112
5159
  parsedResult.then((result) => {
5113
- var _a2;
5114
- const text = typeof result === "string" ? result : (_a2 = result == null ? void 0 : result.text) != null ? _a2 : null;
5160
+ var _a3;
5161
+ const text = typeof result === "string" ? result : (_a3 = result == null ? void 0 : result.text) != null ? _a3 : null;
5115
5162
  if (text !== null) {
5116
5163
  assistant.content = text;
5117
5164
  assistant.streaming = false;
@@ -5127,7 +5174,6 @@ var AgentWidgetClient = class {
5127
5174
  }
5128
5175
  streamParsers.delete(assistant.id);
5129
5176
  rawContentBuffers.delete(assistant.id);
5130
- seqChunkBuffers.delete(assistant.id);
5131
5177
  const contentChanged = displayContent !== assistant.content;
5132
5178
  const streamingChanged = assistant.streaming !== false;
5133
5179
  if (contentChanged) {
@@ -5142,7 +5188,6 @@ var AgentWidgetClient = class {
5142
5188
  const msg = assistantMessage;
5143
5189
  streamParsers.delete(msg.id);
5144
5190
  rawContentBuffers.delete(msg.id);
5145
- seqChunkBuffers.delete(msg.id);
5146
5191
  if (msg.streaming !== false) {
5147
5192
  msg.streaming = false;
5148
5193
  emitMessage(msg);
@@ -5153,11 +5198,11 @@ var AgentWidgetClient = class {
5153
5198
  } else if (payloadType === "agent_start") {
5154
5199
  agentExecution = {
5155
5200
  executionId: payload.executionId,
5156
- agentId: (_oa = payload.agentId) != null ? _oa : "virtual",
5157
- agentName: (_pa = payload.agentName) != null ? _pa : "",
5201
+ agentId: (_la = payload.agentId) != null ? _la : "virtual",
5202
+ agentName: (_ma = payload.agentName) != null ? _ma : "",
5158
5203
  status: "running",
5159
5204
  currentIteration: 0,
5160
- maxTurns: (_qa = payload.maxTurns) != null ? _qa : 1,
5205
+ maxTurns: (_na = payload.maxTurns) != null ? _na : 1,
5161
5206
  startedAt: resolveTimestamp(payload.startedAt)
5162
5207
  };
5163
5208
  } else if (payloadType === "agent_iteration_start") {
@@ -5177,7 +5222,7 @@ var AgentWidgetClient = class {
5177
5222
  } else if (payloadType === "agent_turn_delta") {
5178
5223
  if (payload.contentType === "text") {
5179
5224
  const assistant = ensureAssistantMessage();
5180
- assistant.content += (_ra = payload.delta) != null ? _ra : "";
5225
+ assistant.content += (_oa = payload.delta) != null ? _oa : "";
5181
5226
  assistant.agentMetadata = {
5182
5227
  executionId: payload.executionId,
5183
5228
  iteration: payload.iteration,
@@ -5186,14 +5231,14 @@ var AgentWidgetClient = class {
5186
5231
  };
5187
5232
  emitMessage(assistant);
5188
5233
  } else if (payload.contentType === "thinking") {
5189
- const reasoningId = (_sa = payload.turnId) != null ? _sa : `agent-think-${payload.iteration}`;
5234
+ const reasoningId = (_pa = payload.turnId) != null ? _pa : `agent-think-${payload.iteration}`;
5190
5235
  const reasoningMessage = ensureReasoningMessage(reasoningId);
5191
- reasoningMessage.reasoning = (_ta = reasoningMessage.reasoning) != null ? _ta : {
5236
+ reasoningMessage.reasoning = (_qa = reasoningMessage.reasoning) != null ? _qa : {
5192
5237
  id: reasoningId,
5193
5238
  status: "streaming",
5194
5239
  chunks: []
5195
5240
  };
5196
- reasoningMessage.reasoning.chunks.push((_ua = payload.delta) != null ? _ua : "");
5241
+ reasoningMessage.reasoning.chunks.push((_ra = payload.delta) != null ? _ra : "");
5197
5242
  reasoningMessage.agentMetadata = {
5198
5243
  executionId: payload.executionId,
5199
5244
  iteration: payload.iteration,
@@ -5201,12 +5246,12 @@ var AgentWidgetClient = class {
5201
5246
  };
5202
5247
  emitMessage(reasoningMessage);
5203
5248
  } else if (payload.contentType === "tool_input") {
5204
- const toolId = (_va = payload.toolCallId) != null ? _va : toolContext.lastId;
5249
+ const toolId = (_sa = payload.toolCallId) != null ? _sa : toolContext.lastId;
5205
5250
  if (toolId) {
5206
5251
  const toolMessage = toolMessages.get(toolId);
5207
5252
  if (toolMessage == null ? void 0 : toolMessage.toolCall) {
5208
- toolMessage.toolCall.chunks = (_wa = toolMessage.toolCall.chunks) != null ? _wa : [];
5209
- toolMessage.toolCall.chunks.push((_xa = payload.delta) != null ? _xa : "");
5253
+ toolMessage.toolCall.chunks = (_ta = toolMessage.toolCall.chunks) != null ? _ta : [];
5254
+ toolMessage.toolCall.chunks.push((_ua = payload.delta) != null ? _ua : "");
5210
5255
  emitMessage(toolMessage);
5211
5256
  }
5212
5257
  }
@@ -5218,20 +5263,20 @@ var AgentWidgetClient = class {
5218
5263
  if (reasoningMessage == null ? void 0 : reasoningMessage.reasoning) {
5219
5264
  reasoningMessage.reasoning.status = "complete";
5220
5265
  reasoningMessage.reasoning.completedAt = resolveTimestamp(payload.completedAt);
5221
- const start = (_ya = reasoningMessage.reasoning.startedAt) != null ? _ya : Date.now();
5266
+ const start = (_va = reasoningMessage.reasoning.startedAt) != null ? _va : Date.now();
5222
5267
  reasoningMessage.reasoning.durationMs = Math.max(
5223
5268
  0,
5224
- ((_za = reasoningMessage.reasoning.completedAt) != null ? _za : Date.now()) - start
5269
+ ((_wa = reasoningMessage.reasoning.completedAt) != null ? _wa : Date.now()) - start
5225
5270
  );
5226
5271
  reasoningMessage.streaming = false;
5227
5272
  emitMessage(reasoningMessage);
5228
5273
  }
5229
5274
  }
5230
5275
  } else if (payloadType === "agent_tool_start") {
5231
- const toolId = (_Aa = payload.toolCallId) != null ? _Aa : `agent-tool-${nextSequence()}`;
5276
+ const toolId = (_xa = payload.toolCallId) != null ? _xa : `agent-tool-${nextSequence()}`;
5232
5277
  trackToolId(getToolCallKey(payload), toolId);
5233
5278
  const toolMessage = ensureToolMessage(toolId);
5234
- const tool = (_Ba = toolMessage.toolCall) != null ? _Ba : {
5279
+ const tool = (_ya = toolMessage.toolCall) != null ? _ya : {
5235
5280
  id: toolId,
5236
5281
  status: "pending",
5237
5282
  name: void 0,
@@ -5243,12 +5288,12 @@ var AgentWidgetClient = class {
5243
5288
  completedAt: void 0,
5244
5289
  durationMs: void 0
5245
5290
  };
5246
- tool.name = (_Da = (_Ca = payload.toolName) != null ? _Ca : payload.name) != null ? _Da : tool.name;
5291
+ tool.name = (_Aa = (_za = payload.toolName) != null ? _za : payload.name) != null ? _Aa : tool.name;
5247
5292
  tool.status = "running";
5248
5293
  if (payload.parameters !== void 0) {
5249
5294
  tool.args = payload.parameters;
5250
5295
  }
5251
- tool.startedAt = resolveTimestamp((_Ea = payload.startedAt) != null ? _Ea : payload.timestamp);
5296
+ tool.startedAt = resolveTimestamp((_Ba = payload.startedAt) != null ? _Ba : payload.timestamp);
5252
5297
  toolMessage.toolCall = tool;
5253
5298
  toolMessage.streaming = true;
5254
5299
  toolMessage.agentMetadata = {
@@ -5257,21 +5302,21 @@ var AgentWidgetClient = class {
5257
5302
  };
5258
5303
  emitMessage(toolMessage);
5259
5304
  } else if (payloadType === "agent_tool_delta") {
5260
- const toolId = (_Fa = payload.toolCallId) != null ? _Fa : toolContext.lastId;
5305
+ const toolId = (_Ca = payload.toolCallId) != null ? _Ca : toolContext.lastId;
5261
5306
  if (toolId) {
5262
- const toolMessage = (_Ga = toolMessages.get(toolId)) != null ? _Ga : ensureToolMessage(toolId);
5307
+ const toolMessage = (_Da = toolMessages.get(toolId)) != null ? _Da : ensureToolMessage(toolId);
5263
5308
  if (toolMessage.toolCall) {
5264
- toolMessage.toolCall.chunks = (_Ha = toolMessage.toolCall.chunks) != null ? _Ha : [];
5265
- toolMessage.toolCall.chunks.push((_Ia = payload.delta) != null ? _Ia : "");
5309
+ toolMessage.toolCall.chunks = (_Ea = toolMessage.toolCall.chunks) != null ? _Ea : [];
5310
+ toolMessage.toolCall.chunks.push((_Fa = payload.delta) != null ? _Fa : "");
5266
5311
  toolMessage.toolCall.status = "running";
5267
5312
  toolMessage.streaming = true;
5268
5313
  emitMessage(toolMessage);
5269
5314
  }
5270
5315
  }
5271
5316
  } else if (payloadType === "agent_tool_complete") {
5272
- const toolId = (_Ja = payload.toolCallId) != null ? _Ja : toolContext.lastId;
5317
+ const toolId = (_Ga = payload.toolCallId) != null ? _Ga : toolContext.lastId;
5273
5318
  if (toolId) {
5274
- const toolMessage = (_Ka = toolMessages.get(toolId)) != null ? _Ka : ensureToolMessage(toolId);
5319
+ const toolMessage = (_Ha = toolMessages.get(toolId)) != null ? _Ha : ensureToolMessage(toolId);
5275
5320
  if (toolMessage.toolCall) {
5276
5321
  toolMessage.toolCall.status = "complete";
5277
5322
  if (payload.result !== void 0) {
@@ -5280,7 +5325,7 @@ var AgentWidgetClient = class {
5280
5325
  if (typeof payload.executionTime === "number") {
5281
5326
  toolMessage.toolCall.durationMs = payload.executionTime;
5282
5327
  }
5283
- toolMessage.toolCall.completedAt = resolveTimestamp((_La = payload.completedAt) != null ? _La : payload.timestamp);
5328
+ toolMessage.toolCall.completedAt = resolveTimestamp((_Ia = payload.completedAt) != null ? _Ia : payload.timestamp);
5284
5329
  toolMessage.streaming = false;
5285
5330
  emitMessage(toolMessage);
5286
5331
  const callKey = getToolCallKey(payload);
@@ -5295,7 +5340,7 @@ var AgentWidgetClient = class {
5295
5340
  const reflectionMessage = {
5296
5341
  id: reflectionId,
5297
5342
  role: "assistant",
5298
- content: (_Ma = payload.reflection) != null ? _Ma : "",
5343
+ content: (_Ja = payload.reflection) != null ? _Ja : "",
5299
5344
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
5300
5345
  streaming: false,
5301
5346
  variant: "reasoning",
@@ -5303,7 +5348,7 @@ var AgentWidgetClient = class {
5303
5348
  reasoning: {
5304
5349
  id: reflectionId,
5305
5350
  status: "complete",
5306
- chunks: [(_Na = payload.reflection) != null ? _Na : ""]
5351
+ chunks: [(_Ka = payload.reflection) != null ? _Ka : ""]
5307
5352
  },
5308
5353
  agentMetadata: {
5309
5354
  executionId: payload.executionId,
@@ -5324,7 +5369,7 @@ var AgentWidgetClient = class {
5324
5369
  }
5325
5370
  onEvent({ type: "status", status: "idle" });
5326
5371
  } else if (payloadType === "agent_error") {
5327
- const errorMessage = typeof payload.error === "string" ? payload.error : (_Pa = (_Oa = payload.error) == null ? void 0 : _Oa.message) != null ? _Pa : "Agent execution error";
5372
+ const errorMessage = typeof payload.error === "string" ? payload.error : (_Ma = (_La = payload.error) == null ? void 0 : _La.message) != null ? _Ma : "Agent execution error";
5328
5373
  if (payload.recoverable) {
5329
5374
  if (typeof console !== "undefined") {
5330
5375
  console.warn("[AgentWidget] Recoverable agent error:", errorMessage);
@@ -5337,7 +5382,7 @@ var AgentWidgetClient = class {
5337
5382
  }
5338
5383
  } else if (payloadType === "agent_ping") {
5339
5384
  } else if (payloadType === "agent_approval_start") {
5340
- const approvalId = (_Qa = payload.approvalId) != null ? _Qa : `approval-${nextSequence()}`;
5385
+ const approvalId = (_Na = payload.approvalId) != null ? _Na : `approval-${nextSequence()}`;
5341
5386
  const approvalMessage = {
5342
5387
  id: `approval-${approvalId}`,
5343
5388
  role: "assistant",
@@ -5349,17 +5394,17 @@ var AgentWidgetClient = class {
5349
5394
  approval: {
5350
5395
  id: approvalId,
5351
5396
  status: "pending",
5352
- agentId: (_Ra = agentExecution == null ? void 0 : agentExecution.agentId) != null ? _Ra : "virtual",
5353
- executionId: (_Ta = (_Sa = payload.executionId) != null ? _Sa : agentExecution == null ? void 0 : agentExecution.executionId) != null ? _Ta : "",
5354
- toolName: (_Ua = payload.toolName) != null ? _Ua : "",
5397
+ agentId: (_Oa = agentExecution == null ? void 0 : agentExecution.agentId) != null ? _Oa : "virtual",
5398
+ executionId: (_Qa = (_Pa = payload.executionId) != null ? _Pa : agentExecution == null ? void 0 : agentExecution.executionId) != null ? _Qa : "",
5399
+ toolName: (_Ra = payload.toolName) != null ? _Ra : "",
5355
5400
  toolType: payload.toolType,
5356
- description: (_Wa = payload.description) != null ? _Wa : `Execute ${(_Va = payload.toolName) != null ? _Va : "tool"}`,
5401
+ description: (_Ta = payload.description) != null ? _Ta : `Execute ${(_Sa = payload.toolName) != null ? _Sa : "tool"}`,
5357
5402
  parameters: payload.parameters
5358
5403
  }
5359
5404
  };
5360
5405
  emitMessage(approvalMessage);
5361
5406
  } else if (payloadType === "step_await" && payload.awaitReason === "approval_required") {
5362
- const approvalId = (_Xa = payload.approvalId) != null ? _Xa : `approval-${nextSequence()}`;
5407
+ const approvalId = (_Ua = payload.approvalId) != null ? _Ua : `approval-${nextSequence()}`;
5363
5408
  const approvalMessage = {
5364
5409
  id: `approval-${approvalId}`,
5365
5410
  role: "assistant",
@@ -5371,11 +5416,11 @@ var AgentWidgetClient = class {
5371
5416
  approval: {
5372
5417
  id: approvalId,
5373
5418
  status: "pending",
5374
- agentId: (_Ya = agentExecution == null ? void 0 : agentExecution.agentId) != null ? _Ya : "virtual",
5375
- executionId: (__a = (_Za = payload.executionId) != null ? _Za : agentExecution == null ? void 0 : agentExecution.executionId) != null ? __a : "",
5376
- toolName: (_$a = payload.toolName) != null ? _$a : "",
5419
+ agentId: (_Va = agentExecution == null ? void 0 : agentExecution.agentId) != null ? _Va : "virtual",
5420
+ executionId: (_Xa = (_Wa = payload.executionId) != null ? _Wa : agentExecution == null ? void 0 : agentExecution.executionId) != null ? _Xa : "",
5421
+ toolName: (_Ya = payload.toolName) != null ? _Ya : "",
5377
5422
  toolType: payload.toolType,
5378
- description: (_bb = payload.description) != null ? _bb : `Execute ${(_ab = payload.toolName) != null ? _ab : "tool"}`,
5423
+ description: (__a = payload.description) != null ? __a : `Execute ${(_Za = payload.toolName) != null ? _Za : "tool"}`,
5379
5424
  parameters: payload.parameters
5380
5425
  }
5381
5426
  };
@@ -5394,11 +5439,11 @@ var AgentWidgetClient = class {
5394
5439
  sequence: nextSequence(),
5395
5440
  approval: {
5396
5441
  id: approvalId,
5397
- status: (_cb = payload.decision) != null ? _cb : "approved",
5398
- agentId: (_db = agentExecution == null ? void 0 : agentExecution.agentId) != null ? _db : "virtual",
5399
- executionId: (_fb = (_eb = payload.executionId) != null ? _eb : agentExecution == null ? void 0 : agentExecution.executionId) != null ? _fb : "",
5400
- toolName: (_gb = payload.toolName) != null ? _gb : "",
5401
- description: (_hb = payload.description) != null ? _hb : "",
5442
+ status: (_$a = payload.decision) != null ? _$a : "approved",
5443
+ agentId: (_ab = agentExecution == null ? void 0 : agentExecution.agentId) != null ? _ab : "virtual",
5444
+ executionId: (_cb = (_bb = payload.executionId) != null ? _bb : agentExecution == null ? void 0 : agentExecution.executionId) != null ? _cb : "",
5445
+ toolName: (_db = payload.toolName) != null ? _db : "",
5446
+ description: (_eb = payload.description) != null ? _eb : "",
5402
5447
  resolvedAt: Date.now()
5403
5448
  }
5404
5449
  };
@@ -5436,7 +5481,7 @@ var AgentWidgetClient = class {
5436
5481
  }
5437
5482
  } else if (payloadType === "artifact_delta") {
5438
5483
  const deltaId = String(payload.id);
5439
- const deltaText = typeof payload.delta === "string" ? payload.delta : String((_ib = payload.delta) != null ? _ib : "");
5484
+ const deltaText = typeof payload.delta === "string" ? payload.delta : String((_fb = payload.delta) != null ? _fb : "");
5440
5485
  onEvent({
5441
5486
  type: "artifact_delta",
5442
5487
  id: deltaId,
@@ -5459,7 +5504,7 @@ var AgentWidgetClient = class {
5459
5504
  if (refMsg) {
5460
5505
  refMsg.streaming = false;
5461
5506
  try {
5462
- const parsed = JSON.parse((_jb = refMsg.rawContent) != null ? _jb : "{}");
5507
+ const parsed = JSON.parse((_gb = refMsg.rawContent) != null ? _gb : "{}");
5463
5508
  if (parsed.props) {
5464
5509
  parsed.props.status = "complete";
5465
5510
  const acc = artifactContent.get(artCompleteId);
@@ -5480,7 +5525,7 @@ var AgentWidgetClient = class {
5480
5525
  if (!m || typeof m !== "object") {
5481
5526
  continue;
5482
5527
  }
5483
- const id = String((_kb = m.id) != null ? _kb : `msg-${nextSequence()}`);
5528
+ const id = String((_hb = m.id) != null ? _hb : `msg-${nextSequence()}`);
5484
5529
  const roleRaw = m.role;
5485
5530
  const role = roleRaw === "user" ? "user" : roleRaw === "system" ? "system" : "assistant";
5486
5531
  const msg = {
@@ -5499,7 +5544,7 @@ var AgentWidgetClient = class {
5499
5544
  if (msg.rawContent) {
5500
5545
  try {
5501
5546
  const parsed = JSON.parse(msg.rawContent);
5502
- const refArtId = (_lb = parsed == null ? void 0 : parsed.props) == null ? void 0 : _lb.artifactId;
5547
+ const refArtId = (_ib = parsed == null ? void 0 : parsed.props) == null ? void 0 : _ib.artifactId;
5503
5548
  if (typeof refArtId === "string") {
5504
5549
  artifactIdsWithCards.add(refArtId);
5505
5550
  }
@@ -5510,13 +5555,12 @@ var AgentWidgetClient = class {
5510
5555
  assistantMessageRef.current = null;
5511
5556
  streamParsers.delete(id);
5512
5557
  rawContentBuffers.delete(id);
5513
- seqChunkBuffers.delete(id);
5514
5558
  } else if (payloadType === "error" || payloadType === "step_error" || payloadType === "dispatch_error" || payloadType === "flow_error") {
5515
5559
  let resolvedError = null;
5516
5560
  if (payload.error instanceof Error) {
5517
5561
  resolvedError = payload.error;
5518
5562
  } else if (payloadType === "dispatch_error") {
5519
- const msg = (_mb = payload.message) != null ? _mb : payload.error;
5563
+ const msg = (_jb = payload.message) != null ? _jb : payload.error;
5520
5564
  if (msg != null && msg !== "") {
5521
5565
  resolvedError = new Error(String(msg));
5522
5566
  }
@@ -5525,7 +5569,7 @@ var AgentWidgetClient = class {
5525
5569
  if (typeof e === "string" && e !== "") {
5526
5570
  resolvedError = new Error(e);
5527
5571
  } else if (e != null && typeof e === "object" && "message" in e) {
5528
- resolvedError = new Error(String((_nb = e.message) != null ? _nb : e));
5572
+ resolvedError = new Error(String((_kb = e.message) != null ? _kb : e));
5529
5573
  }
5530
5574
  } else if (payloadType === "error" && payload.error != null && payload.error !== "") {
5531
5575
  resolvedError = new Error(String(payload.error));
@@ -5541,7 +5585,60 @@ var AgentWidgetClient = class {
5541
5585
  }
5542
5586
  }
5543
5587
  }
5588
+ seqReadyQueue.length = 0;
5589
+ };
5590
+ while (true) {
5591
+ const { done, value } = await reader.read();
5592
+ if (done) break;
5593
+ buffer += decoder.decode(value, { stream: true });
5594
+ const events = buffer.split("\n\n");
5595
+ buffer = (_b = events.pop()) != null ? _b : "";
5596
+ for (const event of events) {
5597
+ const lines = event.split("\n");
5598
+ let eventType = "message";
5599
+ let data = "";
5600
+ for (const line of lines) {
5601
+ if (line.startsWith("event:")) {
5602
+ eventType = line.replace("event:", "").trim();
5603
+ } else if (line.startsWith("data:")) {
5604
+ data += line.replace("data:", "").trim();
5605
+ }
5606
+ }
5607
+ if (!data) continue;
5608
+ let payload;
5609
+ try {
5610
+ payload = JSON.parse(data);
5611
+ } catch (error) {
5612
+ onEvent({
5613
+ type: "error",
5614
+ error: error instanceof Error ? error : new Error("Failed to parse chat stream payload")
5615
+ });
5616
+ continue;
5617
+ }
5618
+ const payloadType = eventType !== "message" ? eventType : (_c = payload.type) != null ? _c : "message";
5619
+ (_d = this.onSSEEvent) == null ? void 0 : _d.call(this, payloadType, payload);
5620
+ if (this.parseSSEEvent) {
5621
+ assistantMessageRef.current = assistantMessage;
5622
+ const handled = await this.handleCustomSSEEvent(
5623
+ payload,
5624
+ onEvent,
5625
+ assistantMessageRef,
5626
+ emitMessage,
5627
+ nextSequence,
5628
+ partIdState
5629
+ );
5630
+ if (assistantMessageRef.current && assistantMessageRef.current !== assistantMessage) {
5631
+ assistantMessage = assistantMessageRef.current;
5632
+ }
5633
+ if (handled) continue;
5634
+ }
5635
+ seqBuffer.push(payloadType, payload);
5636
+ drainReadyQueue();
5637
+ }
5544
5638
  }
5639
+ seqBuffer.flushPending();
5640
+ drainReadyQueue();
5641
+ seqBuffer.destroy();
5545
5642
  }
5546
5643
  };
5547
5644
 
@@ -14383,17 +14480,38 @@ var createAgentExperience = (mount, initialConfig, runtimeOptions) => {
14383
14480
  } else if (action === "upvote" || action === "downvote") {
14384
14481
  const currentVote = (_a2 = messageVoteState.get(messageId)) != null ? _a2 : null;
14385
14482
  const wasActive = currentVote === action;
14483
+ const iconName = action === "upvote" ? "thumbs-up" : "thumbs-down";
14386
14484
  if (wasActive) {
14387
14485
  messageVoteState.delete(messageId);
14388
14486
  actionBtn.classList.remove("persona-message-action-active");
14487
+ const outlineIcon = renderLucideIcon(iconName, 14, "currentColor", 2);
14488
+ if (outlineIcon) {
14489
+ actionBtn.innerHTML = "";
14490
+ actionBtn.appendChild(outlineIcon);
14491
+ }
14389
14492
  } else {
14390
14493
  const oppositeAction = action === "upvote" ? "downvote" : "upvote";
14391
14494
  const oppositeBtn = actionsContainer.querySelector(`[data-action="${oppositeAction}"]`);
14392
14495
  if (oppositeBtn) {
14393
14496
  oppositeBtn.classList.remove("persona-message-action-active");
14497
+ const oppositeIconName = oppositeAction === "upvote" ? "thumbs-up" : "thumbs-down";
14498
+ const outlineIcon = renderLucideIcon(oppositeIconName, 14, "currentColor", 2);
14499
+ if (outlineIcon) {
14500
+ oppositeBtn.innerHTML = "";
14501
+ oppositeBtn.appendChild(outlineIcon);
14502
+ }
14394
14503
  }
14395
14504
  messageVoteState.set(messageId, action);
14396
14505
  actionBtn.classList.add("persona-message-action-active");
14506
+ const filledIcon = renderLucideIcon(iconName, 14, "currentColor", 2);
14507
+ if (filledIcon) {
14508
+ filledIcon.setAttribute("fill", "currentColor");
14509
+ actionBtn.innerHTML = "";
14510
+ actionBtn.appendChild(filledIcon);
14511
+ }
14512
+ actionBtn.classList.remove("persona-message-action-pop");
14513
+ void actionBtn.offsetWidth;
14514
+ actionBtn.classList.add("persona-message-action-pop");
14397
14515
  const messages = session.getMessages();
14398
14516
  const message = messages.find((m) => m.id === messageId);
14399
14517
  if (message && messageActionCallbacks.onFeedback) {