@aparte/core 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/client/agent-runner.d.ts +8 -3
  2. package/dist/client/agent-runner.d.ts.map +1 -1
  3. package/dist/client/aparte-client.d.ts.map +1 -1
  4. package/dist/components/bubble/aparte-chat-bubble.d.ts +13 -3
  5. package/dist/components/bubble/aparte-chat-bubble.d.ts.map +1 -1
  6. package/dist/components/chat/aparte-chat.d.ts +64 -0
  7. package/dist/components/chat/aparte-chat.d.ts.map +1 -1
  8. package/dist/components/composer/aparte-composer-input.d.ts +3 -1
  9. package/dist/components/composer/aparte-composer-input.d.ts.map +1 -1
  10. package/dist/components/composer/aparte-composer-send.d.ts +11 -0
  11. package/dist/components/composer/aparte-composer-send.d.ts.map +1 -1
  12. package/dist/config/aparte-config.d.ts +84 -10
  13. package/dist/config/aparte-config.d.ts.map +1 -1
  14. package/dist/config/index.d.ts +2 -0
  15. package/dist/config/index.d.ts.map +1 -1
  16. package/dist/config/link-target.d.ts +39 -0
  17. package/dist/config/link-target.d.ts.map +1 -0
  18. package/dist/config/sanitize.d.ts +22 -3
  19. package/dist/config/sanitize.d.ts.map +1 -1
  20. package/dist/config/step-label.d.ts +22 -0
  21. package/dist/config/step-label.d.ts.map +1 -0
  22. package/dist/conversations/conversation-controller.d.ts +14 -0
  23. package/dist/conversations/conversation-controller.d.ts.map +1 -1
  24. package/dist/conversations/open-conversation.d.ts +28 -0
  25. package/dist/conversations/open-conversation.d.ts.map +1 -0
  26. package/dist/custom-elements.json +1273 -521
  27. package/dist/{defer-hydration-BE2ToXC_.js → defer-hydration-Ch3TOEJC.js} +372 -79
  28. package/dist/defer-hydration-Ch3TOEJC.js.map +1 -0
  29. package/dist/generated/element-attributes.d.ts +11 -4
  30. package/dist/generated/element-attributes.d.ts.map +1 -1
  31. package/dist/index.css +1 -1
  32. package/dist/index.d.ts +3 -2
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +41 -9
  35. package/dist/index.js.map +1 -1
  36. package/dist/index.node.d.ts +2 -2
  37. package/dist/index.node.d.ts.map +1 -1
  38. package/dist/index.node.js +1 -1
  39. package/dist/index.node.js.map +1 -1
  40. package/dist/renderers/citations.d.ts.map +1 -1
  41. package/dist/transport/agent-handler.d.ts +6 -0
  42. package/dist/transport/agent-handler.d.ts.map +1 -1
  43. package/dist/types/element-attributes.d.ts +5 -2
  44. package/dist/types/element-attributes.d.ts.map +1 -1
  45. package/dist/types/events.d.ts +4 -3
  46. package/dist/types/events.d.ts.map +1 -1
  47. package/dist/types/imperative-api.d.ts +15 -0
  48. package/dist/types/imperative-api.d.ts.map +1 -1
  49. package/dist/types/index.d.ts +1 -1
  50. package/dist/types/index.d.ts.map +1 -1
  51. package/dist/types/tools.d.ts +9 -0
  52. package/dist/types/tools.d.ts.map +1 -1
  53. package/package.json +2 -2
  54. package/dist/defer-hydration-BE2ToXC_.js.map +0 -1
@@ -1985,8 +1985,8 @@ function endTag(tag) {
1985
1985
  }
1986
1986
  return re;
1987
1987
  }
1988
- const COMMENT_END = /--!?>/g;
1989
- const ASCII_LETTER$1 = /[A-Za-z]/;
1988
+ const COMMENT_END$1 = /--!?>/g;
1989
+ const ASCII_LETTER$2 = /[A-Za-z]/;
1990
1990
  const SPACE = /\s/;
1991
1991
  const NAME_END = /[\s/>]/;
1992
1992
  const ATTR_NAME_END = /[\s/>=]/;
@@ -2099,8 +2099,8 @@ function rewriteTags(html) {
2099
2099
  if (html[at] === ">") i = at + 1;
2100
2100
  else if (html.startsWith("->", at)) i = at + 2;
2101
2101
  else {
2102
- COMMENT_END.lastIndex = at;
2103
- const m = COMMENT_END.exec(html);
2102
+ COMMENT_END$1.lastIndex = at;
2103
+ const m = COMMENT_END$1.exec(html);
2104
2104
  if (!m) break;
2105
2105
  i = m.index + m[0].length;
2106
2106
  }
@@ -2108,7 +2108,7 @@ function rewriteTags(html) {
2108
2108
  }
2109
2109
  const closing = html[lt + 1] === "/";
2110
2110
  const nameAt = lt + (closing ? 2 : 1);
2111
- if (!ASCII_LETTER$1.test(html[nameAt] ?? "")) {
2111
+ if (!ASCII_LETTER$2.test(html[nameAt] ?? "")) {
2112
2112
  if (html[lt + 1] === "!" || html[lt + 1] === "?" || closing) {
2113
2113
  const end2 = html.indexOf(">", lt + 1);
2114
2114
  i = end2 < 0 ? n : end2 + 1;
@@ -2165,6 +2165,22 @@ function webUrl(source) {
2165
2165
  const url = source.url?.trim();
2166
2166
  return url && /^https?:\/\//i.test(url) && isSafeUrl(url, "a") ? url : void 0;
2167
2167
  }
2168
+ function sourceLink(url, title, config, newTabWords) {
2169
+ const link = document.createElement("a");
2170
+ link.href = url;
2171
+ const opens2 = config.decideLink(url);
2172
+ if (opens2.target) link.target = opens2.target;
2173
+ if (opens2.rel) link.rel = opens2.rel;
2174
+ link.textContent = title;
2175
+ link.dir = "auto";
2176
+ if (opens2.target === "_blank") {
2177
+ const hint = document.createElement("span");
2178
+ hint.className = "aparte-sr-only";
2179
+ hint.textContent = ` ${newTabWords}`;
2180
+ link.append(hint);
2181
+ }
2182
+ return link;
2183
+ }
2168
2184
  function sourceDomain(source) {
2169
2185
  const url = webUrl(source);
2170
2186
  if (url) {
@@ -2558,18 +2574,10 @@ function drawCard() {
2558
2574
  const url = webUrl(source);
2559
2575
  const title = source.title || sourceDomain(source) || source.url || "";
2560
2576
  if (url) {
2561
- const link = document.createElement("a");
2577
+ const link = sourceLink(url, title, config, locale.opensInNewTab ?? "(opens in a new tab)");
2562
2578
  link.className = "aparte-citation-card__title";
2563
- link.href = url;
2564
- link.target = "_blank";
2565
- link.rel = "noopener noreferrer";
2566
2579
  link.dataset.aparteCardPart = "link";
2567
- link.textContent = title;
2568
- link.dir = "auto";
2569
- const hint = document.createElement("span");
2570
- hint.className = "aparte-sr-only";
2571
- hint.textContent = ` ${locale.opensInNewTab ?? "(opens in a new tab)"}`;
2572
- link.append(hint);
2580
+ link.addEventListener("click", announceLink);
2573
2581
  body.append(link);
2574
2582
  } else {
2575
2583
  const plain = document.createElement("p");
@@ -2602,6 +2610,23 @@ function drawCard() {
2602
2610
  else (el2.querySelector(".aparte-citation-card__pager button:not([disabled])") ?? el2.querySelector("a"))?.focus();
2603
2611
  }
2604
2612
  }
2613
+ function announceLink(event) {
2614
+ const chip = card?.chip;
2615
+ const anchor = event.currentTarget;
2616
+ if (!chip?.isConnected) return;
2617
+ const detail = {
2618
+ href: anchor.getAttribute("href") ?? "",
2619
+ anchor,
2620
+ messageId: chip.closest("aparte-chat-bubble")?.getAttribute("message-id") ?? null
2621
+ };
2622
+ const announced = chip.dispatchEvent(new CustomEvent("aparte-link-click", {
2623
+ bubbles: true,
2624
+ composed: true,
2625
+ cancelable: true,
2626
+ detail
2627
+ }));
2628
+ if (!announced) event.preventDefault();
2629
+ }
2605
2630
  function pagerButton(label, icon, part, disabled, act) {
2606
2631
  const button = document.createElement("button");
2607
2632
  button.type = "button";
@@ -2656,17 +2681,7 @@ function renderSourceList(container, after, sources2, config) {
2656
2681
  const title = s.title || domain || s.url || "";
2657
2682
  const url = webUrl(s);
2658
2683
  if (url) {
2659
- const link = document.createElement("a");
2660
- link.href = url;
2661
- link.target = "_blank";
2662
- link.rel = "noopener noreferrer";
2663
- link.textContent = title;
2664
- link.dir = "auto";
2665
- const hint = document.createElement("span");
2666
- hint.className = "aparte-sr-only";
2667
- hint.textContent = ` ${hintText}`;
2668
- link.append(hint);
2669
- item.append(link);
2684
+ item.append(sourceLink(url, title, config, hintText));
2670
2685
  } else {
2671
2686
  item.append(Object.assign(document.createElement("span"), { textContent: title, dir: "auto" }));
2672
2687
  }
@@ -4051,7 +4066,7 @@ function createStreamAdapter(opts) {
4051
4066
  const toolSegments = /* @__PURE__ */ new Map();
4052
4067
  const queued = /* @__PURE__ */ new Set();
4053
4068
  const unqueued = (id, update) => queued.delete(id) ? { ...update, queued: void 0 } : update;
4054
- const settle = (toolCallId, update) => {
4069
+ const settle2 = (toolCallId, update) => {
4055
4070
  const id = `tool-${toolCallId}`;
4056
4071
  target.updateSegment?.(id, unqueued(id, toolSegments.has(id) ? update : { ...update, deferred: void 0 }));
4057
4072
  };
@@ -4261,27 +4276,27 @@ function createStreamAdapter(opts) {
4261
4276
  dispatchLifecycleEvent(target, "aparte-tool-approval-request", { toolCallId: e.toolCallId, toolName: e.name, input: e.input }, targetId);
4262
4277
  break;
4263
4278
  case "tool-approved":
4264
- settle(e.toolCallId, { status: "pending" });
4279
+ settle2(e.toolCallId, { status: "pending" });
4265
4280
  break;
4266
4281
  case "tool-rejected":
4267
- settle(e.toolCallId, {
4282
+ settle2(e.toolCallId, {
4268
4283
  status: "rejected",
4269
4284
  result: e.reason,
4270
4285
  ...e.by ? { refusal: e.instruction ? { by: e.by, instruction: e.instruction } : { by: e.by } } : {}
4271
4286
  });
4272
4287
  break;
4273
4288
  case "tool-resolved":
4274
- settle(e.toolCallId, {
4289
+ settle2(e.toolCallId, {
4275
4290
  status: "resolved",
4276
4291
  result: e.result,
4277
4292
  ...e.structuredResult !== void 0 ? { structuredResult: e.structuredResult } : {}
4278
4293
  });
4279
4294
  break;
4280
4295
  case "tool-aborted":
4281
- settle(e.toolCallId, e.cause ? { status: "aborted", abortCause: e.cause } : { status: "aborted" });
4296
+ settle2(e.toolCallId, e.cause ? { status: "aborted", abortCause: e.cause } : { status: "aborted" });
4282
4297
  break;
4283
4298
  case "tool-failed":
4284
- settle(e.toolCallId, { status: "failed", result: e.error });
4299
+ settle2(e.toolCallId, { status: "failed", result: e.error });
4285
4300
  break;
4286
4301
  case "turn-limit-exceeded":
4287
4302
  if (e.scope === "global") {
@@ -4295,7 +4310,7 @@ function createStreamAdapter(opts) {
4295
4310
  code: AparteErrorCode.MAX_TURNS_EXCEEDED
4296
4311
  });
4297
4312
  } else if (e.toolCallId) {
4298
- settle(e.toolCallId, { status: "aborted", abortCause: "turn-limit" });
4313
+ settle2(e.toolCallId, { status: "aborted", abortCause: "turn-limit" });
4299
4314
  }
4300
4315
  break;
4301
4316
  case "run-aborted":
@@ -4504,9 +4519,10 @@ function createAparteAgentHandler(options) {
4504
4519
  return jsonError(400, "Invalid JSON body.");
4505
4520
  }
4506
4521
  if (body?.v !== 1) return jsonError(400, "Unsupported agent wire version: expected v 1.");
4507
- if (body.providerId !== void 0 && typeof body.providerId !== "string" || typeof body.messageId !== "string" || !Array.isArray(body.request?.messages)) {
4508
- return jsonError(400, "Body must be { v: 1, providerId?, messageId, request: { messages } }.");
4522
+ if (body.providerId !== void 0 && typeof body.providerId !== "string" || body.conversationId !== void 0 && typeof body.conversationId !== "string" || typeof body.messageId !== "string" || !Array.isArray(body.request?.messages)) {
4523
+ return jsonError(400, "Body must be { v: 1, providerId?, messageId, conversationId?, request: { messages } }.");
4509
4524
  }
4525
+ const conversationId = body.conversationId || void 0;
4510
4526
  if (body.request.toolChoice && typeof body.request.toolChoice === "object") {
4511
4527
  return jsonError(400, "A forced tool call cannot come from the browser.");
4512
4528
  }
@@ -4608,7 +4624,11 @@ function createAparteAgentHandler(options) {
4608
4624
  },
4609
4625
  toolLookup: (name) => {
4610
4626
  const t = offered.has(name) ? tools.get(name) : void 0;
4611
- return t ? (call, signal, run2) => t.handler(call, signal, run2 ? { request: req, run: run2 } : { request: req }) : void 0;
4627
+ return t ? (call, signal, run2) => t.handler(call, signal, {
4628
+ request: req,
4629
+ ...conversationId ? { conversationId } : {},
4630
+ ...run2 ? { run: run2 } : {}
4631
+ }) : void 0;
4612
4632
  },
4613
4633
  toolConfigLookup: (name) => {
4614
4634
  if (!offered.has(name)) return void 0;
@@ -4854,7 +4874,7 @@ const MAY_HOLD = /<(?:img|source)\b|data-aparte-image/i;
4854
4874
  const HELD = "a[data-aparte-image], span[data-aparte-image]";
4855
4875
  function applyImagePolicy(html, decide, words) {
4856
4876
  if (!html || !MAY_HOLD.test(html)) return html;
4857
- return typeof document === "undefined" ? applyImagePolicyWithoutDom(html, decide, words) : applyInTemplate(html, decide, words);
4877
+ return typeof document === "undefined" ? applyImagePolicyWithoutDom(html, decide, words) : applyInTemplate$1(html, decide, words);
4858
4878
  }
4859
4879
  function judgeImage(src, srcset, decide) {
4860
4880
  const candidates = srcset === void 0 ? [] : parseSrcset(srcset);
@@ -4872,7 +4892,7 @@ function judgeSource(src, srcset, decide) {
4872
4892
  if (kept.length) return writeSrcset(kept);
4873
4893
  return NO_ADDRESS.test(src) ? false : null;
4874
4894
  }
4875
- function applyInTemplate(html, decide, words) {
4895
+ function applyInTemplate$1(html, decide, words) {
4876
4896
  const template = document.createElement("template");
4877
4897
  template.innerHTML = html;
4878
4898
  const root = template.content;
@@ -4936,12 +4956,12 @@ function applyInTemplate(html, decide, words) {
4936
4956
  }
4937
4957
  return changed ? template.innerHTML : html;
4938
4958
  }
4939
- const RAW_TEXT = /* @__PURE__ */ new Set(["script", "style", "textarea", "title", "xmp", "iframe", "noembed", "noframes", "noscript", "plaintext"]);
4959
+ const RAW_TEXT$1 = /* @__PURE__ */ new Set(["script", "style", "textarea", "title", "xmp", "iframe", "noembed", "noframes", "noscript", "plaintext"]);
4940
4960
  const VOID = /* @__PURE__ */ new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
4941
- const ASCII_LETTER = /[A-Za-z]/;
4942
- const SAFE_NAME = /^[a-z][a-z0-9_.:-]*$/;
4961
+ const ASCII_LETTER$1 = /[A-Za-z]/;
4962
+ const SAFE_NAME$1 = /^[a-z][a-z0-9_.:-]*$/;
4943
4963
  function writeTag(tag, attrs, replace) {
4944
- const kept = attrs.filter(([name]) => !(name in replace) && SAFE_NAME.test(name));
4964
+ const kept = attrs.filter(([name]) => !(name in replace) && SAFE_NAME$1.test(name));
4945
4965
  const added = Object.entries(replace).filter((entry) => entry[1] !== null);
4946
4966
  return `<${tag}${[...kept, ...added].map(([name, value]) => ` ${name}="${escapeAttr(value)}"`).join("")}>`;
4947
4967
  }
@@ -4983,7 +5003,7 @@ function applyImagePolicyWithoutDom(html, decide, words) {
4983
5003
  }
4984
5004
  const closing = html[lt + 1] === "/";
4985
5005
  const nameAt = lt + (closing ? 2 : 1);
4986
- if (!ASCII_LETTER.test(html[nameAt] ?? "")) {
5006
+ if (!ASCII_LETTER$1.test(html[nameAt] ?? "")) {
4987
5007
  out += "<";
4988
5008
  i = lt + 1;
4989
5009
  continue;
@@ -5003,7 +5023,7 @@ function applyImagePolicyWithoutDom(html, decide, words) {
5003
5023
  continue;
5004
5024
  }
5005
5025
  const attr = (name) => attrs.find(([key]) => key === name)?.[1];
5006
- if (RAW_TEXT.has(tag)) {
5026
+ if (RAW_TEXT$1.has(tag)) {
5007
5027
  const close = lower.indexOf(`</${tag}`, end);
5008
5028
  const stop = close < 0 ? n : close;
5009
5029
  out += written + html.slice(end, stop);
@@ -5045,6 +5065,125 @@ function applyImagePolicyWithoutDom(html, decide, words) {
5045
5065
  }
5046
5066
  return out;
5047
5067
  }
5068
+ const STAYS = /^(?:#|mailto:|tel:|sms:)/i;
5069
+ const NEW_TAB = [["target", "_blank"], ["rel", "noopener noreferrer"]];
5070
+ const NEW_TAB_DECISION = Object.freeze({ target: "_blank", rel: "noopener noreferrer" });
5071
+ const IN_PLACE = Object.freeze({});
5072
+ function linkTargetAttributes(mode, href, wish) {
5073
+ if (mode !== "external-only" && !STAYS.test(href.replace(CONTROL_WS, ""))) return NEW_TAB;
5074
+ return linkAttributes(href, wish);
5075
+ }
5076
+ function linkDecision(mode, href) {
5077
+ return linkTargetAttributes(mode, href, "").length ? NEW_TAB_DECISION : IN_PLACE;
5078
+ }
5079
+ const MAY_LINK = /<a[\s/>]/i;
5080
+ function applyLinkTarget(html, mode) {
5081
+ if (!html || !MAY_LINK.test(html)) return html;
5082
+ return typeof document === "undefined" ? applyLinkTargetWithoutDom(html, mode) : applyInTemplate(html, mode);
5083
+ }
5084
+ function relForNewTab(rel) {
5085
+ const tokens = (rel ?? "").split(/[ \t\n\f\r]+/).filter((token) => token && token.toLowerCase() !== "opener");
5086
+ for (const needed of ["noopener", "noreferrer"]) {
5087
+ if (!tokens.some((token) => token.toLowerCase() === needed)) tokens.push(needed);
5088
+ }
5089
+ return tokens.join(" ");
5090
+ }
5091
+ function settle(decided, target, rel) {
5092
+ const wantedTarget = decided.find(([key]) => key === "target")?.[1];
5093
+ if (wantedTarget !== "_blank") return (target ?? void 0) === wantedTarget ? null : { target: wantedTarget, rel: void 0 };
5094
+ const wantedRel = relForNewTab(rel);
5095
+ return (target ?? void 0) === wantedTarget && (rel ?? void 0) === wantedRel ? null : { target: wantedTarget, rel: wantedRel };
5096
+ }
5097
+ function applyInTemplate(html, mode) {
5098
+ const template = document.createElement("template");
5099
+ template.innerHTML = html;
5100
+ let changed = false;
5101
+ for (const anchor of Array.from(template.content.querySelectorAll("a[href]"))) {
5102
+ const decided = linkTargetAttributes(mode, anchor.getAttribute("href") ?? "", anchor.getAttribute("target") ?? "");
5103
+ const settled2 = settle(decided, anchor.getAttribute("target"), anchor.getAttribute("rel"));
5104
+ if (!settled2) continue;
5105
+ anchor.removeAttribute("target");
5106
+ if (settled2.target !== void 0) anchor.setAttribute("target", settled2.target);
5107
+ if (settled2.rel !== void 0) {
5108
+ anchor.removeAttribute("rel");
5109
+ anchor.setAttribute("rel", settled2.rel);
5110
+ }
5111
+ changed = true;
5112
+ }
5113
+ return changed ? template.innerHTML : html;
5114
+ }
5115
+ const RAW_TEXT = /* @__PURE__ */ new Set(["script", "style", "textarea", "title", "xmp", "iframe", "noembed", "noframes", "noscript", "plaintext"]);
5116
+ const ASCII_LETTER = /[A-Za-z]/;
5117
+ const SAFE_NAME = /^[a-z][a-z0-9_.:-]*$/;
5118
+ const COMMENT_END = /--!?>/g;
5119
+ function commentEnd(html, at) {
5120
+ if (html[at] === ">") return at + 1;
5121
+ if (html.startsWith("->", at)) return at + 2;
5122
+ COMMENT_END.lastIndex = at;
5123
+ const m = COMMENT_END.exec(html);
5124
+ return m ? m.index + m[0].length : html.length;
5125
+ }
5126
+ function linkTag(written, attrs, mode) {
5127
+ const attr = (name) => attrs.find(([key]) => key === name)?.[1];
5128
+ const href = attr("href");
5129
+ if (href === void 0) return written;
5130
+ const decided = linkTargetAttributes(mode, href, attr("target") ?? "");
5131
+ const settled2 = settle(decided, attr("target"), attr("rel"));
5132
+ if (!settled2) return written;
5133
+ const kept = attrs.filter(([name]) => name !== "target" && (settled2.rel === void 0 || name !== "rel") && SAFE_NAME.test(name));
5134
+ const added = [];
5135
+ if (settled2.target !== void 0) added.push(["target", settled2.target]);
5136
+ if (settled2.rel !== void 0) added.push(["rel", settled2.rel]);
5137
+ return `<a${[...kept, ...added].map(([name, value]) => ` ${name}="${escapeAttr(value)}"`).join("")}>`;
5138
+ }
5139
+ function applyLinkTargetWithoutDom(html, mode) {
5140
+ if (!html || !MAY_LINK.test(html)) return html;
5141
+ const lower = html.toLowerCase();
5142
+ const n = html.length;
5143
+ let out = "";
5144
+ let i = 0;
5145
+ while (i < n) {
5146
+ const lt = html.indexOf("<", i);
5147
+ if (lt < 0) {
5148
+ out += html.slice(i);
5149
+ break;
5150
+ }
5151
+ out += html.slice(i, lt);
5152
+ if (html.startsWith("<!--", lt)) {
5153
+ const stop = commentEnd(html, lt + 4);
5154
+ out += html.slice(lt, stop);
5155
+ i = stop;
5156
+ continue;
5157
+ }
5158
+ const closing = html[lt + 1] === "/";
5159
+ const nameAt = lt + (closing ? 2 : 1);
5160
+ if (!ASCII_LETTER.test(html[nameAt] ?? "")) {
5161
+ out += "<";
5162
+ i = lt + 1;
5163
+ continue;
5164
+ }
5165
+ const { tag, attrs, end } = readTag(html, nameAt);
5166
+ if (end < 0) {
5167
+ out += html.slice(lt);
5168
+ break;
5169
+ }
5170
+ i = end;
5171
+ const written = html.slice(lt, end);
5172
+ if (closing) {
5173
+ out += written;
5174
+ continue;
5175
+ }
5176
+ if (RAW_TEXT.has(tag)) {
5177
+ const close = lower.indexOf(`</${tag}`, end);
5178
+ const stop = close < 0 ? n : close;
5179
+ out += written + html.slice(end, stop);
5180
+ i = stop;
5181
+ continue;
5182
+ }
5183
+ out += tag === "a" ? linkTag(written, attrs, mode) : written;
5184
+ }
5185
+ return out;
5186
+ }
5048
5187
  class AparteElicitationAbortError extends DOMException {
5049
5188
  /**
5050
5189
  * Which of the two ways it ended.
@@ -5202,6 +5341,8 @@ class AparteConfig {
5202
5341
  _imageDecider = compileImagePolicy([]);
5203
5342
  /** Whether the app named an image policy, the default included; see `decideImage`. */
5204
5343
  _imagePolicyNamed = false;
5344
+ // Where the links a reply holds open (`link-target.ts`): by default every one in a new tab.
5345
+ _linkTarget = "new-tab";
5205
5346
  _systemPromptTemplate;
5206
5347
  _systemPromptVarsProvider;
5207
5348
  _statusRenderer;
@@ -5303,6 +5444,8 @@ class AparteConfig {
5303
5444
  _activityRenderers = /* @__PURE__ */ new Map();
5304
5445
  /** What a plugin says about a call, read after the app's display — see {@link setToolLineProvider}. */
5305
5446
  _toolLineProvider = null;
5447
+ /** What a step is called on screen, by the name the run announces — see {@link registerStepLabel}. One entry per registration, so each remover takes back its own. */
5448
+ _stepLabels = /* @__PURE__ */ new Map();
5306
5449
  /** Tagged blocks the stream parser recognises in the prose — see {@link registerStreamBlock}. */
5307
5450
  _streamBlocks = /* @__PURE__ */ new Map();
5308
5451
  _segmentDefaults = /* @__PURE__ */ new Map();
@@ -5519,9 +5662,11 @@ class AparteConfig {
5519
5662
  * zero-dependency allowlist sanitizer.
5520
5663
  *
5521
5664
  * The function you pass REPLACES the built-in one, chat rules included: no
5522
- * `aparte-` classes, no layout styles, no form controls, external links in a new
5523
- * tab. DOMPurify's defaults hold none of the four, so chain it in front of
5524
- * `defaultSanitizer` rather than in its place (the example below).
5665
+ * `aparte-` classes, no layout styles, no form controls. DOMPurify's defaults hold
5666
+ * none of the three, so chain it in front of `defaultSanitizer` rather than in its
5667
+ * place (the example below). Where a link opens ({@link AparteConfig.setLinkTarget | setLinkTarget})
5668
+ * and which pictures load ({@link AparteConfig.setImagePolicy | setImagePolicy}) are
5669
+ * applied after it, whichever it is.
5525
5670
  *
5526
5671
  * @param sanitizer A sanitizer function, or `null` to DISABLE sanitization.
5527
5672
  * Disabling exposes you to XSS from LLM-authored content — only do so for
@@ -5541,16 +5686,19 @@ class AparteConfig {
5541
5686
  this._notify();
5542
5687
  }
5543
5688
  /**
5544
- * Run the active sanitizer over provider-produced HTML, then the image policy
5545
- * ({@link AparteConfig.setImagePolicy | setImagePolicy}): a picture the policy does not let
5546
- * load comes back as a link that loads it on a click. Public so a streaming-markdown
5547
- * provider (which appends DOM directly, bypassing `renderMarkdown`) can apply the same
5548
- * rules. The image policy runs whichever sanitizer is set, none included, so replacing it
5549
- * does not turn a reply's pictures back into requests the reader never made.
5689
+ * Run the active sanitizer over provider-produced HTML, then the link target
5690
+ * ({@link AparteConfig.setLinkTarget | setLinkTarget}): every link gets the `target` and
5691
+ * `rel` it opens with; then the image policy ({@link AparteConfig.setImagePolicy | setImagePolicy}):
5692
+ * a picture the policy does not let load comes back as a link that loads it on a click.
5693
+ * Public so a streaming-markdown provider (which appends DOM directly, bypassing
5694
+ * `renderMarkdown`) can apply the same rules. Both run whichever sanitizer is set, none
5695
+ * included, so replacing it does not send a reply's links back into the chat's own frame,
5696
+ * nor turn its pictures back into requests the reader never made.
5550
5697
  */
5551
5698
  sanitizeHtml(html) {
5552
5699
  const clean = this._sanitizer ? this._sanitizer(html) : html;
5553
- return applyImagePolicy(clean, (url) => this.decideImage(url), () => this._heldImageWords());
5700
+ const linked = applyLinkTarget(clean, this._linkTarget);
5701
+ return applyImagePolicy(linked, (url) => this.decideImage(url), () => this._heldImageWords());
5554
5702
  }
5555
5703
  /**
5556
5704
  * Which pictures a model or a tool chose load before the reader asks — in a reply's
@@ -5622,6 +5770,45 @@ class AparteConfig {
5622
5770
  icon: this.getIcon("image")
5623
5771
  };
5624
5772
  }
5773
+ /**
5774
+ * Where the links a reply holds open — in its Markdown, its sources, a document it wrote.
5775
+ * `'new-tab'`, the default, opens every one in a new tab, same-site ones included;
5776
+ * `'external-only'` opens a link to another site in a new tab and keeps a same-site one in
5777
+ * the page, as before 1.9. Either way a link to `#…`, `mailto:`, `tel:` or `sms:` is left as
5778
+ * written, a new tab goes with `rel="noopener noreferrer"`, and the `target` the model wrote
5779
+ * does not choose. What is on screen is drawn again.
5780
+ *
5781
+ * In a single-page app or an Electron window, a same-site link followed in place replaces
5782
+ * the whole app, the conversation with it. To route a link yourself — your router, a pane,
5783
+ * the system browser — cancel the chat's `aparte-link-click`, whichever mode is set.
5784
+ *
5785
+ * @example aparteGlobalConfig.setLinkTarget('external-only');
5786
+ */
5787
+ setLinkTarget(mode) {
5788
+ if (mode === this._linkTarget) return;
5789
+ this._linkTarget = mode;
5790
+ bumpRenderingVersion(this);
5791
+ this._notify();
5792
+ }
5793
+ /** Where the links a reply holds open: {@link AparteConfig.setLinkTarget | setLinkTarget}'s mode, `'new-tab'` by default. */
5794
+ getLinkTarget() {
5795
+ return this._linkTarget;
5796
+ }
5797
+ /**
5798
+ * Where a link to `href` opens under this config's link target: `{ target: '_blank', rel:
5799
+ * 'noopener noreferrer' }` for a new tab, `{}` for the page itself. For a plugin that draws
5800
+ * links itself, as `@aparte/plugin-streaming-markdown` does: set what it returns, and no
5801
+ * `target` of your own. It does not judge whether the address is safe to link —
5802
+ * `isSafeUrl` does.
5803
+ *
5804
+ * @example
5805
+ * const link = document.createElement('a');
5806
+ * link.href = url;
5807
+ * Object.assign(link, aparteGlobalConfig.decideLink(url));
5808
+ */
5809
+ decideLink(href) {
5810
+ return linkDecision(this._linkTarget, href);
5811
+ }
5625
5812
  /**
5626
5813
  * Set the system prompt template. Supports `{{key}}` placeholders resolved via setSystemPromptVarsProvider.
5627
5814
  * Pass undefined to clear.
@@ -6649,6 +6836,59 @@ class AparteConfig {
6649
6836
  getToolInputFormatter(toolName) {
6650
6837
  return this.getToolDisplay(toolName)?.formatInput;
6651
6838
  }
6839
+ /**
6840
+ * Say how a step is called on screen, in place of the name a run announced. A server that
6841
+ * streams `step-start { name }` sends a stable key — `slot-wait`, `restore`, `reread` —
6842
+ * and the page knows the person's language: this maps one to the other, wherever a step is
6843
+ * shown (the waiting indicator, which a screen reader reads in place of "Typing", and a
6844
+ * sub-agent's line). A name nobody labelled shows as it always did: itself, because core
6845
+ * never makes a label up.
6846
+ *
6847
+ * The label is text, never HTML, or a function of the locale, asked at every draw and on
6848
+ * every config change — so a language switch changes the words of a step that is open.
6849
+ * One that throws, or says nothing, leaves the name. One label per name, per config:
6850
+ * registering a name again replaces its label, and a chat with a config of its own reads
6851
+ * that config's labels, as it reads its tool displays.
6852
+ *
6853
+ * Only what is shown is labelled. The step keeps the name the run announced — for
6854
+ * {@link observeRunEvents}, for the target, for everything an app stores — and is never
6855
+ * saved with the reply. Registering tells the chats on the page, so a label reaches a step
6856
+ * that is open. Returns the function that takes the label off again (it changes nothing
6857
+ * once another registration has replaced it).
6858
+ *
6859
+ * @example
6860
+ * aparteGlobalConfig.registerStepLabel('slot-wait', 'Waiting for a free slot…');
6861
+ *
6862
+ * @example
6863
+ * // In the person's language, and live: a switch of the locale relabels a step that is open.
6864
+ * aparteGlobalConfig.registerStepLabel('reread', ({ locale }) =>
6865
+ * locale.tag?.startsWith('fr') ? 'Relecture de la conversation…' : 'Re-reading the conversation…');
6866
+ */
6867
+ registerStepLabel(name, label) {
6868
+ const entry = { label };
6869
+ this._stepLabels.set(name, entry);
6870
+ this._notify();
6871
+ return () => {
6872
+ if (this._stepLabels.get(name) !== entry) return;
6873
+ this._stepLabels.delete(name);
6874
+ this._notify();
6875
+ };
6876
+ }
6877
+ /**
6878
+ * The words shown for a step named `name`, or `undefined` when none are registered, they
6879
+ * say nothing, or the function that gives them throws — then the name itself is shown. A
6880
+ * function label is asked here, with the locale as it is now.
6881
+ */
6882
+ getStepLabel(name) {
6883
+ const entry = this._stepLabels.get(name);
6884
+ if (!entry) return void 0;
6885
+ try {
6886
+ const text = typeof entry.label === "function" ? entry.label({ name, locale: this._locale }) : entry.label;
6887
+ return typeof text === "string" && text.trim() ? text.trim() : void 0;
6888
+ } catch {
6889
+ return void 0;
6890
+ }
6891
+ }
6652
6892
  /**
6653
6893
  * Teach the stream parser a tagged block: `<tag attr="…">…</tag>` in the model's
6654
6894
  * prose becomes the segment `toSegment` builds, streamed delta by delta.
@@ -6853,7 +7093,7 @@ class AparteConfig {
6853
7093
  }
6854
7094
  /**
6855
7095
  * Put the configuration back to its defaults: the providers and the selected model,
6856
- * the tools with their renderers and summaries, the tool-line provider, the renderers and render hooks, the
7096
+ * the tools with their renderers and summaries, the tool-line provider, the step labels, the renderers and render hooks, the
6857
7097
  * Markdown and highlight providers, the code-language renderers, the sanitizer, the system prompt, the locale, icons,
6858
7098
  * avatars, actions and host handlers, the conversation manager, the question presenters
6859
7099
  * and their queue, the run-event observers. Three things stay: the transport, the key sources added with
@@ -6886,6 +7126,7 @@ class AparteConfig {
6886
7126
  this._imageDecider = compileImagePolicy([]);
6887
7127
  this._imagePolicyNamed = false;
6888
7128
  forgetShownImages(this);
7129
+ this._linkTarget = "new-tab";
6889
7130
  this._aiProviders.clear();
6890
7131
  this._fetchedModels.clear();
6891
7132
  this._tools.clear();
@@ -6896,6 +7137,7 @@ class AparteConfig {
6896
7137
  notifyRenderersChanged(this);
6897
7138
  this._toolDisplays.clear();
6898
7139
  this._toolLineProvider = null;
7140
+ this._stepLabels.clear();
6899
7141
  this._streamBlocks.clear();
6900
7142
  this._runEventObservers = [];
6901
7143
  this._modelConfig = {};
@@ -7634,6 +7876,21 @@ function tellConversationStatus(id, status) {
7634
7876
  function conversationStatusOf(id) {
7635
7877
  return known.get(id) ?? null;
7636
7878
  }
7879
+ const OPEN_CONVERSATION = Symbol.for("aparte.openConversation");
7880
+ function offerOpenConversation(host2, read) {
7881
+ const slot = host2;
7882
+ slot[OPEN_CONVERSATION] = read;
7883
+ return () => {
7884
+ if (slot[OPEN_CONVERSATION] === read) delete slot[OPEN_CONVERSATION];
7885
+ };
7886
+ }
7887
+ function openConversationOf(el2) {
7888
+ for (let node = el2; node; node = node.parentElement) {
7889
+ const read = node[OPEN_CONVERSATION];
7890
+ if (read) return read();
7891
+ }
7892
+ return null;
7893
+ }
7637
7894
  const MAX_COMPACTION_SAVE_WAITS = 6;
7638
7895
  class AparteConversationController {
7639
7896
  _binding;
@@ -7694,6 +7951,18 @@ class AparteConversationController {
7694
7951
  get activeId() {
7695
7952
  return this._activeId;
7696
7953
  }
7954
+ /**
7955
+ * The conversation a message sent now belongs to: the open one, or — for the first
7956
+ * message of a chat — the one that send is creating. `createNew()` makes it the
7957
+ * manager's active conversation synchronously, so the client, which hears the send
7958
+ * right after this controller does, already finds it there; this controller's own id
7959
+ * follows once the conversation is saved. `_ensureConversationAndPersist` reads the
7960
+ * same two places to decide where the message is saved, so a turn is carried to the
7961
+ * conversation its message was written in.
7962
+ */
7963
+ _openId() {
7964
+ return this._activeId ?? this._manager()?.activeId ?? null;
7965
+ }
7697
7966
  /**
7698
7967
  * Lazily resolve the conversation manager. Returns `undefined` if none is
7699
7968
  * registered — the controller then runs in degraded mode: optimistic UI
@@ -7847,12 +8116,17 @@ class AparteConversationController {
7847
8116
  }
7848
8117
  this._bound = true;
7849
8118
  this._manager();
8119
+ this._withdrawOpenConversation = offerOpenConversation(host2, () => this._openId());
7850
8120
  return () => this.unbind();
7851
8121
  }
8122
+ /** Takes the open-conversation reader off the host (see `bind`). */
8123
+ _withdrawOpenConversation = null;
7852
8124
  /** Detach event listeners. */
7853
8125
  /** Release handle for the hydration-retry subscription (see setConversationId). */
7854
8126
  _stopHydrationRetry = null;
7855
8127
  unbind() {
8128
+ this._withdrawOpenConversation?.();
8129
+ this._withdrawOpenConversation = null;
7856
8130
  this._bound = false;
7857
8131
  this._subscribedTo = null;
7858
8132
  this._persistActive();
@@ -9392,7 +9666,7 @@ function labelGroup(list, opts) {
9392
9666
  if (opts.titleId) list.setAttribute("aria-labelledby", opts.titleId);
9393
9667
  else if (opts.fallbackLabel) list.setAttribute("aria-label", opts.fallbackLabel);
9394
9668
  }
9395
- function buildEnumField(field, onChange, fallbackLabel, settle) {
9669
+ function buildEnumField(field, onChange, fallbackLabel, settle2) {
9396
9670
  const wrap = el$1("div", "aparte-elic-field aparte-elic-enum");
9397
9671
  const titleId = fieldHeader(wrap, field, fallbackLabel);
9398
9672
  const list = el$1("div", "aparte-elic-options");
@@ -9401,12 +9675,12 @@ function buildEnumField(field, onChange, fallbackLabel, settle) {
9401
9675
  const controlRecipe = type === "checkbox" ? "aparte-checkbox" : "aparte-radio";
9402
9676
  const allowOther = field.allowOther ?? contextConfig().getElicitationOptions().allowOther;
9403
9677
  const defaults = new Set(Array.isArray(field.default) ? field.default : field.default != null ? [field.default] : []);
9404
- const settling = settle != null && !field.multiple && defaults.size === 0;
9678
+ const settling = settle2 != null && !field.multiple && defaults.size === 0;
9405
9679
  labelGroup(list, { multiple: field.multiple, commands: settling, titleId, fallbackLabel });
9406
9680
  const buildOption = (value, label, description, recommended) => {
9407
9681
  if (settling) {
9408
9682
  const button = commandOption(label, description, recommended);
9409
- button.addEventListener("click", () => settle?.(value));
9683
+ button.addEventListener("click", () => settle2?.(value));
9410
9684
  return button;
9411
9685
  }
9412
9686
  const row = el$1("label", "aparte-field-choice aparte-elic-option" + (recommended ? " aparte-elic-option--recommended" : ""));
@@ -9521,18 +9795,18 @@ function buildEnumField(field, onChange, fallbackLabel, settle) {
9521
9795
  focus: () => controls()[0]?.focus()
9522
9796
  };
9523
9797
  }
9524
- function buildBooleanField(field, onChange, fallbackLabel, settle) {
9798
+ function buildBooleanField(field, onChange, fallbackLabel, settle2) {
9525
9799
  const wrap = el$1("div", "aparte-elic-field aparte-elic-boolean");
9526
9800
  const titleId = fieldHeader(wrap, field, fallbackLabel);
9527
9801
  const list = el$1("div", "aparte-elic-options");
9528
9802
  const name = `elic-${uuid()}`;
9529
- const settling = settle != null && field.default == null;
9803
+ const settling = settle2 != null && field.default == null;
9530
9804
  labelGroup(list, { commands: settling, titleId, fallbackLabel });
9531
9805
  if (settling) {
9532
9806
  const t2 = contextConfig();
9533
9807
  const mkCommand = (val, label, defaulted) => {
9534
9808
  const button = commandOption(label);
9535
- button.addEventListener("click", () => settle?.(val));
9809
+ button.addEventListener("click", () => settle2?.(val));
9536
9810
  if (defaulted) {
9537
9811
  const title = button.querySelector(".aparte-elic-option-title");
9538
9812
  onRelabel(() => {
@@ -9615,7 +9889,7 @@ function buildStringField(field, onChange, fallbackLabel) {
9615
9889
  focus: () => input.focus()
9616
9890
  };
9617
9891
  }
9618
- function buildField(field, onChange, fallbackLabel, key, settle) {
9892
+ function buildField(field, onChange, fallbackLabel, key, settle2) {
9619
9893
  const custom = contextConfig().getElicitationFieldRenderer()?.(field, { key, notifyChange: onChange });
9620
9894
  if (custom) {
9621
9895
  return {
@@ -9627,9 +9901,9 @@ function buildField(field, onChange, fallbackLabel, key, settle) {
9627
9901
  }
9628
9902
  switch (field.type) {
9629
9903
  case "enum":
9630
- return buildEnumField(field, onChange, fallbackLabel, settle);
9904
+ return buildEnumField(field, onChange, fallbackLabel, settle2);
9631
9905
  case "boolean":
9632
- return buildBooleanField(field, onChange, fallbackLabel, settle);
9906
+ return buildBooleanField(field, onChange, fallbackLabel, settle2);
9633
9907
  // No `settle`: text is written, not chosen, so it always needs a commit.
9634
9908
  case "string":
9635
9909
  return buildStringField(field, onChange, fallbackLabel);
@@ -9654,7 +9928,7 @@ function buildPanel(message, schema, onChange) {
9654
9928
  if (asked2) panel.appendChild(Object.assign(el$1("p", "aparte-elic-message", asked2), { dir: "auto" }));
9655
9929
  let settleCb = null;
9656
9930
  let settled2 = false;
9657
- const settle = (content) => {
9931
+ const settle2 = (content) => {
9658
9932
  if (settled2) return;
9659
9933
  settled2 = true;
9660
9934
  settleCb?.(content);
@@ -9752,7 +10026,7 @@ function buildPanel(message, schema, onChange) {
9752
10026
  };
9753
10027
  }
9754
10028
  const answerOnClick = contextConfig().getElicitationOptions().answerOnClick;
9755
- const field = buildField(schema, onChange, asked2, void 0, answerOnClick ? settle : void 0);
10029
+ const field = buildField(schema, onChange, asked2, void 0, answerOnClick ? settle2 : void 0);
9756
10030
  body.appendChild(field.el);
9757
10031
  return {
9758
10032
  el: panel,
@@ -9796,12 +10070,12 @@ function buildApprovalPanel(message, options, onChange, details, allowOther = tr
9796
10070
  }
9797
10071
  const dismiss = el("div", "aparte-elic-dismiss");
9798
10072
  panel.appendChild(dismiss);
9799
- let settle = null;
10073
+ let settle2 = null;
9800
10074
  let done = false;
9801
10075
  const fire = (answer) => {
9802
10076
  if (done) return;
9803
10077
  done = true;
9804
- settle?.(answer);
10078
+ settle2?.(answer);
9805
10079
  };
9806
10080
  const row = el("div", "aparte-approval-options");
9807
10081
  row.setAttribute("role", "group");
@@ -9837,7 +10111,7 @@ function buildApprovalPanel(message, options, onChange, details, allowOther = tr
9837
10111
  el: panel,
9838
10112
  dismiss,
9839
10113
  onSettle: (cb) => {
9840
- settle = cb;
10114
+ settle2 = cb;
9841
10115
  },
9842
10116
  getContent: () => ({ instruction: typed() }),
9843
10117
  isComplete: () => typed().length > 0,
@@ -10285,7 +10559,7 @@ class AparteClient {
10285
10559
  };
10286
10560
  const isStopped = () => this._isAborted || streamController.signal.aborted;
10287
10561
  const runOnce = async () => {
10288
- let result = opts?.resume ? { usage: void 0, suspended: opts.resume } : await this._streamLoop(targetElement, messageId, provider, baseRequest, authConfig, streamController, void 0, opts?.files);
10562
+ let result = opts?.resume ? { usage: void 0, suspended: opts.resume } : await this._streamLoop(targetElement, messageId, provider, baseRequest, authConfig, streamController, void 0, opts?.files, opts?.conversationId);
10289
10563
  const maxResumes = this.options.maxTurns ?? 10;
10290
10564
  let resumes = 0;
10291
10565
  let approvedAtLastPause = /* @__PURE__ */ new Set();
@@ -10323,7 +10597,9 @@ class AparteClient {
10323
10597
  { ...baseRequest, messages: messages2 },
10324
10598
  authConfig,
10325
10599
  streamController,
10326
- deferral
10600
+ deferral,
10601
+ void 0,
10602
+ opts?.conversationId
10327
10603
  );
10328
10604
  }
10329
10605
  const usage = result.usage;
@@ -10438,6 +10714,7 @@ class AparteClient {
10438
10714
  console.warn("[AparteClient] aparte-retry — no target found");
10439
10715
  return;
10440
10716
  }
10717
+ const conversationId = openConversationOf(targetElement) ?? void 0;
10441
10718
  const allMessages = targetElement.getMessages?.() ?? [];
10442
10719
  const retryIdx = allMessages.findIndex((m) => m.id === messageId);
10443
10720
  const retryMsg = retryIdx >= 0 ? allMessages[retryIdx] : void 0;
@@ -10468,6 +10745,7 @@ class AparteClient {
10468
10745
  {
10469
10746
  ...provider.retryTemperature !== void 0 ? { temperature: provider.retryTemperature } : {},
10470
10747
  ...this._turnMeta([...historyMessages].reverse().find((m) => m.role === "user")),
10748
+ ...conversationId ? { conversationId } : {},
10471
10749
  rebuild: async () => [
10472
10750
  ...this._systemMessages(),
10473
10751
  ...mergeAdjacentUserMessages(this._messagesToChatMessages(this._current(targetElement, historyMessages)))
@@ -10504,6 +10782,7 @@ class AparteClient {
10504
10782
  console.warn("[AparteClient] aparte-edit — no target found");
10505
10783
  return;
10506
10784
  }
10785
+ const conversationId = openConversationOf(targetElement) ?? void 0;
10507
10786
  const before = targetElement.getMessages?.().find((m) => m.id === messageId);
10508
10787
  targetElement.updateMessage?.(messageId, {
10509
10788
  content: newContent,
@@ -10544,6 +10823,7 @@ class AparteClient {
10544
10823
  authConfig,
10545
10824
  {
10546
10825
  ...this._turnMeta(editIdx >= 0 ? allMessages[editIdx] : void 0),
10826
+ ...conversationId ? { conversationId } : {},
10547
10827
  rebuild: async () => [
10548
10828
  ...this._systemMessages(),
10549
10829
  ...mergeAdjacentUserMessages(this._messagesToChatMessages(this._current(targetElement, historyMessages)))
@@ -10753,6 +11033,7 @@ class AparteClient {
10753
11033
  console.warn("[AparteClient] ⚠️ No target element found with appendMessage support. Provide a targetResolver in AparteClientOptions or ensure the composer has a `target` attribute.");
10754
11034
  return;
10755
11035
  }
11036
+ const conversationId = openConversationOf(targetElement) ?? void 0;
10756
11037
  this._closeDeferred(targetElement);
10757
11038
  if (this.options.echoUserMessage !== false && event.detail?.echoed !== true) {
10758
11039
  const echoFiles = Array.isArray(event.detail?.files) ? event.detail.files : [];
@@ -10823,7 +11104,8 @@ class AparteClient {
10823
11104
  {
10824
11105
  rebuild: async () => this._buildMessages(content, targetElement, fileParts),
10825
11106
  ...rawFiles.length > 0 ? { files: rawFiles } : {},
10826
- ...this._turnMeta(event.detail)
11107
+ ...this._turnMeta(event.detail),
11108
+ ...conversationId ? { conversationId } : {}
10827
11109
  }
10828
11110
  );
10829
11111
  }
@@ -10933,11 +11215,11 @@ ${content}
10933
11215
  * adapter, or the runner a host injected — after the fetch-level abort bookkeeping.
10934
11216
  */
10935
11217
  /** One run of the loop: its usage, and whether it paused (a server loop). */
10936
- async _streamLoop(targetElement, messageId, provider, baseRequest, authConfig, streamController = new AbortController(), deferral, files) {
11218
+ async _streamLoop(targetElement, messageId, provider, baseRequest, authConfig, streamController = new AbortController(), deferral, files, conversationId) {
10937
11219
  if (this._streamController !== streamController) this._streamController?.abort();
10938
11220
  this._streamController = streamController;
10939
11221
  const runner = this.options.streamRunner ?? runStreamAgent;
10940
- return this._runViaStreamRunner(runner, targetElement, messageId, provider, baseRequest, authConfig, streamController, deferral, files);
11222
+ return this._runViaStreamRunner(runner, targetElement, messageId, provider, baseRequest, authConfig, streamController, deferral, files, conversationId);
10941
11223
  }
10942
11224
  /**
10943
11225
  * Run the loop through a {@link AparteStreamRunner} — the engine's by default —
@@ -10948,7 +11230,7 @@ ${content}
10948
11230
  * produces is pinned by the `stream-parity` suite's snapshots, recorded while
10949
11231
  * the inline loop it replaced still ran beside it.
10950
11232
  */
10951
- async _runViaStreamRunner(streamRunner, targetElement, messageId, provider, baseRequest, authConfig, streamController, deferral, files) {
11233
+ async _runViaStreamRunner(streamRunner, targetElement, messageId, provider, baseRequest, authConfig, streamController, deferral, files, conversationId) {
10952
11234
  const signal = streamController.signal;
10953
11235
  const chatId = this._targetIdOf(targetElement);
10954
11236
  const adapter = createStreamAdapter({
@@ -10982,7 +11264,13 @@ ${content}
10982
11264
  const toolLookup = (name) => {
10983
11265
  const handler = this._config.getToolHandler(name);
10984
11266
  if (!handler) return void 0;
10985
- const context = { target: targetElement, config: this._config };
11267
+ const context = {
11268
+ target: targetElement,
11269
+ config: this._config,
11270
+ // The same id a server tool is handed (`createAparteAgentHandler`), so a
11271
+ // handler behaves the same whichever loop runs it.
11272
+ ...conversationId ? { conversationId } : {}
11273
+ };
10986
11274
  return (call, sig, run) => handler(call, sig, run ? { ...context, run } : context);
10987
11275
  };
10988
11276
  const hostOwnsDecision = Boolean(this.options.approvalResolver);
@@ -11009,6 +11297,7 @@ ${content}
11009
11297
  ...provider.id ? { providerId: provider.id } : {},
11010
11298
  ...deferral ? { deferral } : {},
11011
11299
  ...files && files.length > 0 ? { files } : {},
11300
+ ...conversationId ? { conversationId } : {},
11012
11301
  baseRequest,
11013
11302
  transportCall,
11014
11303
  toolLookup,
@@ -11265,6 +11554,7 @@ ${content}
11265
11554
  return false;
11266
11555
  }
11267
11556
  this._beginUserTurn();
11557
+ const conversationId = openConversationOf(targetElement) ?? void 0;
11268
11558
  this._resuming.add(last.id);
11269
11559
  try {
11270
11560
  const authConfig = provider.id ? await this._resolveAuth(provider.id) : void 0;
@@ -11282,7 +11572,8 @@ ${content}
11282
11572
  const at = now.findIndex((m) => m.id === last.id);
11283
11573
  return at >= 0 ? this._resumeBase(now, at) : base;
11284
11574
  },
11285
- ...recorded?.temperature !== void 0 ? { temperature: recorded.temperature } : {}
11575
+ ...recorded?.temperature !== void 0 ? { temperature: recorded.temperature } : {},
11576
+ ...conversationId ? { conversationId } : {}
11286
11577
  });
11287
11578
  } finally {
11288
11579
  this._resuming.delete(last.id);
@@ -11334,6 +11625,7 @@ const RUN_LEVEL = /* @__PURE__ */ new Set(["run-start", "run-done", "run-aborted
11334
11625
  function createAgentStreamRunner(options) {
11335
11626
  let warnedAttributedEnd = false;
11336
11627
  return async (opts) => {
11628
+ const endpoint = typeof options.endpoint === "function" ? options.endpoint(opts) : options.endpoint;
11337
11629
  const doFetch = options.fetch ?? fetch;
11338
11630
  const headers = typeof options.headers === "function" ? await options.headers() : options.headers ?? {};
11339
11631
  const { tools, ...request } = opts.baseRequest;
@@ -11341,11 +11633,12 @@ function createAgentStreamRunner(options) {
11341
11633
  v: 1,
11342
11634
  ...opts.providerId ? { providerId: opts.providerId } : {},
11343
11635
  messageId: opts.messageId,
11636
+ ...opts.conversationId ? { conversationId: opts.conversationId } : {},
11344
11637
  request,
11345
11638
  clientTools: tools ?? [],
11346
11639
  ...opts.deferral?.token ? { resume: { ticket: opts.deferral.token, outcomes: opts.deferral.outcomes ?? {} } } : {}
11347
11640
  };
11348
- const response = await doFetch(options.endpoint, {
11641
+ const response = await doFetch(endpoint, {
11349
11642
  method: "POST",
11350
11643
  headers: jsonHeaders(headers),
11351
11644
  body: JSON.stringify(body),
@@ -12062,4 +12355,4 @@ export {
12062
12355
  collectRendererStyles as y,
12063
12356
  contentToText as z
12064
12357
  };
12065
- //# sourceMappingURL=defer-hydration-BE2ToXC_.js.map
12358
+ //# sourceMappingURL=defer-hydration-Ch3TOEJC.js.map