@aparte/core 1.8.0 → 1.10.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 (122) 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 +48 -11
  4. package/dist/client/aparte-client.d.ts.map +1 -1
  5. package/dist/client/stream-adapter.d.ts +5 -0
  6. package/dist/client/stream-adapter.d.ts.map +1 -1
  7. package/dist/client/wire-history.d.ts +21 -1
  8. package/dist/client/wire-history.d.ts.map +1 -1
  9. package/dist/components/bubble/aparte-chat-bubble.d.ts +13 -3
  10. package/dist/components/bubble/aparte-chat-bubble.d.ts.map +1 -1
  11. package/dist/components/chat/aparte-chat.d.ts +64 -0
  12. package/dist/components/chat/aparte-chat.d.ts.map +1 -1
  13. package/dist/components/composer/aparte-composer-action.d.ts +2 -1
  14. package/dist/components/composer/aparte-composer-action.d.ts.map +1 -1
  15. package/dist/components/composer/aparte-composer-add-attachment.d.ts.map +1 -1
  16. package/dist/components/composer/aparte-composer-attachments.d.ts.map +1 -1
  17. package/dist/components/composer/aparte-composer-input.d.ts +3 -1
  18. package/dist/components/composer/aparte-composer-input.d.ts.map +1 -1
  19. package/dist/components/composer/aparte-composer-send.d.ts +11 -0
  20. package/dist/components/composer/aparte-composer-send.d.ts.map +1 -1
  21. package/dist/components/composer/aparte-composer.d.ts +2 -1
  22. package/dist/components/composer/aparte-composer.d.ts.map +1 -1
  23. package/dist/components/context/aparte-context.d.ts +1 -1
  24. package/dist/components/context/aparte-context.d.ts.map +1 -1
  25. package/dist/components/conversation-list/aparte-conversation-list.d.ts +43 -1
  26. package/dist/components/conversation-list/aparte-conversation-list.d.ts.map +1 -1
  27. package/dist/components/conversation-list/index.d.ts +1 -1
  28. package/dist/components/conversation-list/index.d.ts.map +1 -1
  29. package/dist/components/elicitation/aparte-elicitation.d.ts.map +1 -1
  30. package/dist/components/index.d.ts +1 -1
  31. package/dist/components/index.d.ts.map +1 -1
  32. package/dist/components/launcher/aparte-launcher.d.ts.map +1 -1
  33. package/dist/components/scroll-rail/aparte-scroll-rail.d.ts +1 -1
  34. package/dist/components/scroll-rail/aparte-scroll-rail.d.ts.map +1 -1
  35. package/dist/components/sidebar/aparte-sidebar.d.ts +14 -1
  36. package/dist/components/sidebar/aparte-sidebar.d.ts.map +1 -1
  37. package/dist/components/split/aparte-split.d.ts +1 -1
  38. package/dist/components/split/aparte-split.d.ts.map +1 -1
  39. package/dist/components/suggestions/aparte-suggestions.d.ts +3 -2
  40. package/dist/components/suggestions/aparte-suggestions.d.ts.map +1 -1
  41. package/dist/components/viewport/aparte-chat-viewport.d.ts +3 -0
  42. package/dist/components/viewport/aparte-chat-viewport.d.ts.map +1 -1
  43. package/dist/config/aparte-config.d.ts +108 -13
  44. package/dist/config/aparte-config.d.ts.map +1 -1
  45. package/dist/config/index.d.ts +2 -0
  46. package/dist/config/index.d.ts.map +1 -1
  47. package/dist/config/link-target.d.ts +39 -0
  48. package/dist/config/link-target.d.ts.map +1 -0
  49. package/dist/config/sanitize.d.ts +22 -3
  50. package/dist/config/sanitize.d.ts.map +1 -1
  51. package/dist/config/step-label.d.ts +22 -0
  52. package/dist/config/step-label.d.ts.map +1 -0
  53. package/dist/context/checkpoint-state.d.ts +0 -7
  54. package/dist/context/checkpoint-state.d.ts.map +1 -1
  55. package/dist/context/measure.d.ts +3 -1
  56. package/dist/context/measure.d.ts.map +1 -1
  57. package/dist/conversations/conversation-controller.d.ts +56 -0
  58. package/dist/conversations/conversation-controller.d.ts.map +1 -1
  59. package/dist/conversations/open-conversation.d.ts +28 -0
  60. package/dist/conversations/open-conversation.d.ts.map +1 -0
  61. package/dist/custom-elements.json +1969 -335
  62. package/dist/{defer-hydration-BE2ToXC_.js → defer-hydration-OFqdbk3O.js} +991 -299
  63. package/dist/defer-hydration-OFqdbk3O.js.map +1 -0
  64. package/dist/elicitation/approval-panel.d.ts +1 -1
  65. package/dist/elicitation/approval-panel.d.ts.map +1 -1
  66. package/dist/elicitation/option-keys.d.ts +26 -0
  67. package/dist/elicitation/option-keys.d.ts.map +1 -0
  68. package/dist/elicitation/types.d.ts +16 -0
  69. package/dist/elicitation/types.d.ts.map +1 -1
  70. package/dist/generated/element-attributes.d.ts +13 -6
  71. package/dist/generated/element-attributes.d.ts.map +1 -1
  72. package/dist/{glyphs-LolG04CC.js → glyphs-BgKFtByg.js} +10 -10
  73. package/dist/{glyphs-LolG04CC.js.map → glyphs-BgKFtByg.js.map} +1 -1
  74. package/dist/host/aparte-chat-host.d.ts +42 -1
  75. package/dist/host/aparte-chat-host.d.ts.map +1 -1
  76. package/dist/icons/extended.d.ts +9 -0
  77. package/dist/icons/extended.d.ts.map +1 -1
  78. package/dist/icons.js +20 -11
  79. package/dist/icons.js.map +1 -1
  80. package/dist/index.css +1 -1
  81. package/dist/index.d.ts +10 -3
  82. package/dist/index.d.ts.map +1 -1
  83. package/dist/index.js +310 -197
  84. package/dist/index.js.map +1 -1
  85. package/dist/index.node.d.ts +8 -3
  86. package/dist/index.node.d.ts.map +1 -1
  87. package/dist/index.node.js +61 -58
  88. package/dist/index.node.js.map +1 -1
  89. package/dist/interop/chat-events.d.ts +64 -0
  90. package/dist/interop/chat-events.d.ts.map +1 -0
  91. package/dist/interop/element-props.d.ts +6 -0
  92. package/dist/interop/element-props.d.ts.map +1 -1
  93. package/dist/interop/element-spec.d.ts +85 -0
  94. package/dist/interop/element-spec.d.ts.map +1 -0
  95. package/dist/primitives/progress-spinner/aparte-progress-spinner.d.ts +1 -1
  96. package/dist/primitives/progress-spinner/aparte-progress-spinner.d.ts.map +1 -1
  97. package/dist/primitives/select/aparte-option.d.ts +1 -1
  98. package/dist/primitives/select/aparte-option.d.ts.map +1 -1
  99. package/dist/primitives/select/aparte-select.d.ts.map +1 -1
  100. package/dist/renderers/citations.d.ts.map +1 -1
  101. package/dist/transport/agent-handler.d.ts +14 -4
  102. package/dist/transport/agent-handler.d.ts.map +1 -1
  103. package/dist/types/element-attributes.d.ts +5 -2
  104. package/dist/types/element-attributes.d.ts.map +1 -1
  105. package/dist/types/events.d.ts +15 -13
  106. package/dist/types/events.d.ts.map +1 -1
  107. package/dist/types/imperative-api.d.ts +26 -0
  108. package/dist/types/imperative-api.d.ts.map +1 -1
  109. package/dist/types/index.d.ts +2 -2
  110. package/dist/types/index.d.ts.map +1 -1
  111. package/dist/types/models.d.ts +26 -0
  112. package/dist/types/models.d.ts.map +1 -1
  113. package/dist/types/segments.d.ts +2 -1
  114. package/dist/types/segments.d.ts.map +1 -1
  115. package/dist/types/tools.d.ts +60 -5
  116. package/dist/types/tools.d.ts.map +1 -1
  117. package/dist/utils/segments.d.ts +1 -0
  118. package/dist/utils/segments.d.ts.map +1 -1
  119. package/dist/utils/tool-line.d.ts +9 -8
  120. package/dist/utils/tool-line.d.ts.map +1 -1
  121. package/package.json +2 -2
  122. package/dist/defer-hydration-BE2ToXC_.js.map +0 -1
@@ -1,6 +1,6 @@
1
1
  import { runSubAgent as runSubAgent$1, startSubAgent as startSubAgent$1, toolRefusal as toolRefusal$1, unansweredTail, runStreamAgent } from "@aparte/engine";
2
2
  import { c as cssEscape, b as enhanceTabs, d as eventOrigin, r as rootOf } from "./kit-keyboard-BUSLQ5i4.js";
3
- import { A as APARTE_ICON_GLYPHS } from "./glyphs-LolG04CC.js";
3
+ import { A as APARTE_ICON_GLYPHS } from "./glyphs-BgKFtByg.js";
4
4
  function contentToText(content) {
5
5
  if (typeof content === "string") return content;
6
6
  return content.filter((p) => p.type === "text").map((p) => p.text).join("");
@@ -1184,7 +1184,7 @@ function openSegmentIds(segments) {
1184
1184
  }
1185
1185
  function adoptMessageSegments(message) {
1186
1186
  if (!message.segments?.length) return { ...message };
1187
- const live2 = message.status === "streaming" || message.status === "pending";
1187
+ const live2 = message.status === "streaming" || message.status === "pending" || (message.deferredCalls?.length ?? 0) > 0;
1188
1188
  return {
1189
1189
  ...message,
1190
1190
  segments: message.segments.reduce((acc, segment) => {
@@ -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/>=]/;
@@ -2025,23 +2025,23 @@ function rebuildTag(tag, attrs) {
2025
2025
  const isInput = tag === "input";
2026
2026
  const attr = (name) => attrs.find(([n]) => n === name)?.[1];
2027
2027
  if (isInput && (attr("type") ?? "").trim().toLowerCase() !== "checkbox") return "";
2028
- const written = [];
2028
+ const written2 = [];
2029
2029
  if (isInput) {
2030
- written.push('type="checkbox"');
2031
- if (attr("checked") !== void 0) written.push("checked");
2032
- written.push("disabled");
2030
+ written2.push('type="checkbox"');
2031
+ if (attr("checked") !== void 0) written2.push("checked");
2032
+ written2.push("disabled");
2033
2033
  }
2034
2034
  for (const [name, value] of attrs) {
2035
2035
  if (!SAFE_ATTR_NAME.test(name) || isInput && (name === "type" || name === "checked" || name === "disabled")) continue;
2036
2036
  const kept = keepAttribute(tag, name, value);
2037
- if (kept !== null) written.push(`${name}="${escapeValue(kept)}"`);
2037
+ if (kept !== null) written2.push(`${name}="${escapeValue(kept)}"`);
2038
2038
  }
2039
2039
  if (tag === "a") {
2040
2040
  const href = attrs.find(([n]) => n === "href");
2041
2041
  const kept = href ? keepAttribute("a", "href", href[1]) : null;
2042
- for (const [name, value] of linkAttributes(kept ?? "", attr("target") ?? "")) written.push(`${name}="${value}"`);
2042
+ for (const [name, value] of linkAttributes(kept ?? "", attr("target") ?? "")) written2.push(`${name}="${value}"`);
2043
2043
  }
2044
- return `<${tag}${written.length ? " " + written.join(" ") : ""}>`;
2044
+ return `<${tag}${written2.length ? " " + written2.join(" ") : ""}>`;
2045
2045
  }
2046
2046
  function readTag(html, nameAt) {
2047
2047
  const n = html.length;
@@ -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;
@@ -2149,6 +2149,32 @@ const defaultSanitizer = (html) => {
2149
2149
  sanitizeChildren(doc.body, container, doc);
2150
2150
  return container.innerHTML;
2151
2151
  };
2152
+ const isChatHost = (node) => node.localName === "aparte-chat" || node.hasAttribute("data-aparte-chat");
2153
+ function parentOf(node) {
2154
+ if (node.parentElement) return node.parentElement;
2155
+ const root = node.getRootNode?.();
2156
+ return root && "host" in root ? root.host : null;
2157
+ }
2158
+ function chatIdOf(el2) {
2159
+ for (let node = el2 ?? null; node; node = parentOf(node)) {
2160
+ if (node.localName.startsWith("aparte-")) {
2161
+ const target = node.getAttribute("target");
2162
+ if (target) return target;
2163
+ }
2164
+ if (isChatHost(node) && node.id) return node.id;
2165
+ }
2166
+ return void 0;
2167
+ }
2168
+ function dispatchChatEvent(el2, type, detail, init = {}) {
2169
+ const targetId = detail.targetId ?? chatIdOf(el2);
2170
+ const stamped = targetId === void 0 ? detail : { ...detail, targetId };
2171
+ return el2.dispatchEvent(new CustomEvent(type, {
2172
+ bubbles: true,
2173
+ composed: true,
2174
+ cancelable: init.cancelable === true,
2175
+ detail: stamped
2176
+ }));
2177
+ }
2152
2178
  const CHIP_CLASS = "aparte-citation";
2153
2179
  const MARKER_CLASS = "aparte-citation-marker";
2154
2180
  const WORD = /[\p{L}\p{N}]/u;
@@ -2165,6 +2191,22 @@ function webUrl(source) {
2165
2191
  const url = source.url?.trim();
2166
2192
  return url && /^https?:\/\//i.test(url) && isSafeUrl(url, "a") ? url : void 0;
2167
2193
  }
2194
+ function sourceLink(url, title, config, newTabWords) {
2195
+ const link = document.createElement("a");
2196
+ link.href = url;
2197
+ const opens2 = config.decideLink(url);
2198
+ if (opens2.target) link.target = opens2.target;
2199
+ if (opens2.rel) link.rel = opens2.rel;
2200
+ link.textContent = title;
2201
+ link.dir = "auto";
2202
+ if (opens2.target === "_blank") {
2203
+ const hint = document.createElement("span");
2204
+ hint.className = "aparte-sr-only";
2205
+ hint.textContent = ` ${newTabWords}`;
2206
+ link.append(hint);
2207
+ }
2208
+ return link;
2209
+ }
2168
2210
  function sourceDomain(source) {
2169
2211
  const url = webUrl(source);
2170
2212
  if (url) {
@@ -2558,18 +2600,10 @@ function drawCard() {
2558
2600
  const url = webUrl(source);
2559
2601
  const title = source.title || sourceDomain(source) || source.url || "";
2560
2602
  if (url) {
2561
- const link = document.createElement("a");
2603
+ const link = sourceLink(url, title, config, locale.opensInNewTab ?? "(opens in a new tab)");
2562
2604
  link.className = "aparte-citation-card__title";
2563
- link.href = url;
2564
- link.target = "_blank";
2565
- link.rel = "noopener noreferrer";
2566
2605
  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);
2606
+ link.addEventListener("click", announceLink);
2573
2607
  body.append(link);
2574
2608
  } else {
2575
2609
  const plain = document.createElement("p");
@@ -2602,6 +2636,18 @@ function drawCard() {
2602
2636
  else (el2.querySelector(".aparte-citation-card__pager button:not([disabled])") ?? el2.querySelector("a"))?.focus();
2603
2637
  }
2604
2638
  }
2639
+ function announceLink(event) {
2640
+ const chip = card?.chip;
2641
+ const anchor = event.currentTarget;
2642
+ if (!chip?.isConnected) return;
2643
+ const detail = {
2644
+ href: anchor.getAttribute("href") ?? "",
2645
+ anchor,
2646
+ messageId: chip.closest("aparte-chat-bubble")?.getAttribute("message-id") ?? null
2647
+ };
2648
+ const announced = dispatchChatEvent(chip, "aparte-link-click", detail, { cancelable: true });
2649
+ if (!announced) event.preventDefault();
2650
+ }
2605
2651
  function pagerButton(label, icon, part, disabled, act) {
2606
2652
  const button = document.createElement("button");
2607
2653
  button.type = "button";
@@ -2656,17 +2702,7 @@ function renderSourceList(container, after, sources2, config) {
2656
2702
  const title = s.title || domain || s.url || "";
2657
2703
  const url = webUrl(s);
2658
2704
  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);
2705
+ item.append(sourceLink(url, title, config, hintText));
2670
2706
  } else {
2671
2707
  item.append(Object.assign(document.createElement("span"), { textContent: title, dir: "auto" }));
2672
2708
  }
@@ -3170,18 +3206,18 @@ function describeToolInput(input, format) {
3170
3206
  }
3171
3207
  const reported = /* @__PURE__ */ new WeakSet();
3172
3208
  function toolLineOf(segment, config) {
3173
- const provider = config.getToolLineProvider();
3174
- if (!provider) return void 0;
3175
- try {
3176
- const line = provider(segment);
3177
- return line && typeof line === "object" ? line : void 0;
3178
- } catch (err) {
3179
- if (!reported.has(provider)) {
3180
- reported.add(provider);
3181
- console.error("[aparte] The tool-line provider threw; the row keeps its default line. Further throws from it are not reported.", err);
3209
+ for (const provider of config.getToolLineProviders()) {
3210
+ try {
3211
+ const line = provider(segment);
3212
+ if (line && typeof line === "object") return line;
3213
+ } catch (err) {
3214
+ if (!reported.has(provider)) {
3215
+ reported.add(provider);
3216
+ console.error("[aparte] A tool-line provider threw; the row keeps its default line. Further throws from it are not reported.", err);
3217
+ }
3182
3218
  }
3183
- return void 0;
3184
3219
  }
3220
+ return void 0;
3185
3221
  }
3186
3222
  const textOf = (value) => typeof value === "string" ? value.trim() : "";
3187
3223
  function toolNameOf(segment, config, line = toolLineOf(segment, config)) {
@@ -3213,11 +3249,19 @@ function toolTargetPartsOf(segment, config, line = toolLineOf(segment, config))
3213
3249
  const text = textOf(line?.target);
3214
3250
  return { text, isWords: text !== "" };
3215
3251
  }
3216
- function toolActivityOf(_segment, line) {
3217
- return textOf(line?.activity);
3252
+ function displayText$1(field, segment) {
3253
+ if (field === void 0) return "";
3254
+ try {
3255
+ return textOf(typeof field === "function" ? field(segment) : field);
3256
+ } catch {
3257
+ return "";
3258
+ }
3259
+ }
3260
+ function toolActivityOf(segment, line, config) {
3261
+ return displayText$1(config.getToolDisplay(segment.toolCall?.name ?? "")?.activity, segment) || textOf(line?.activity);
3218
3262
  }
3219
- function toolLineNoteOf(line) {
3220
- return textOf(line?.note);
3263
+ function toolLineNoteOf(segment, line, config) {
3264
+ return displayText$1(config.getToolDisplay(segment.toolCall?.name ?? "")?.note, segment) || textOf(line?.note);
3221
3265
  }
3222
3266
  function describeInput(segment) {
3223
3267
  return describeToolInput(segment.toolCall?.input, contextConfig().getToolInputFormatter(segment.toolCall?.name ?? ""));
@@ -3261,7 +3305,7 @@ function reasonOf(segment) {
3261
3305
  return "";
3262
3306
  }
3263
3307
  function noteOf(segment, line) {
3264
- return [reasonOf(segment), toolLineNoteOf(line)].filter(Boolean).join(" · ");
3308
+ return [reasonOf(segment), toolLineNoteOf(segment, line, contextConfig())].filter(Boolean).join(" · ");
3265
3309
  }
3266
3310
  function outcomeOf(segment) {
3267
3311
  const text = displayText(segment.result ?? "");
@@ -3458,7 +3502,7 @@ function setTarget(element, segment, line) {
3458
3502
  function setActivity(element, segment, line) {
3459
3503
  const el2 = element.querySelector(".aparte-tool-activity");
3460
3504
  if (!el2) return;
3461
- const text = toolActivityOf(segment, line);
3505
+ const text = toolActivityOf(segment, line, contextConfig());
3462
3506
  if (el2.textContent !== text) el2.textContent = text;
3463
3507
  el2.toggleAttribute("hidden", !text);
3464
3508
  }
@@ -3564,7 +3608,7 @@ function pillMarkup(segment, line, withOpen = true) {
3564
3608
  const badge = stateBadge(segment);
3565
3609
  const icon = iconOf(segment);
3566
3610
  const target = toolTarget(segment, line);
3567
- const activity = toolActivityOf(segment, line);
3611
+ const activity = toolActivityOf(segment, line, contextConfig());
3568
3612
  const note = noteOf(segment, line);
3569
3613
  const name = nameOf(segment, line);
3570
3614
  const quiet = quietOf(segment);
@@ -4044,14 +4088,15 @@ const toolRefusal = toolRefusal$1;
4044
4088
  const runSubAgent = runSubAgent$1;
4045
4089
  const startSubAgent = startSubAgent$1;
4046
4090
  function createStreamAdapter(opts) {
4047
- const { target, config, messageId, targetId, observe: notify = true } = opts;
4091
+ const { target, config, messageId, targetId, conversationId, observe: notify = true } = opts;
4092
+ const turnOf = { messageId, ...conversationId ? { conversationId } : {} };
4048
4093
  let parser = new AparteStreamParser({ blocks: config.getStreamBlocks() });
4049
4094
  let streaming = /* @__PURE__ */ new Set();
4050
4095
  let thinkingId = null;
4051
4096
  const toolSegments = /* @__PURE__ */ new Map();
4052
4097
  const queued = /* @__PURE__ */ new Set();
4053
4098
  const unqueued = (id, update) => queued.delete(id) ? { ...update, queued: void 0 } : update;
4054
- const settle = (toolCallId, update) => {
4099
+ const settle2 = (toolCallId, update) => {
4055
4100
  const id = `tool-${toolCallId}`;
4056
4101
  target.updateSegment?.(id, unqueued(id, toolSegments.has(id) ? update : { ...update, deferred: void 0 }));
4057
4102
  };
@@ -4258,30 +4303,30 @@ function createStreamAdapter(opts) {
4258
4303
  }
4259
4304
  case "tool-awaiting-approval":
4260
4305
  target.updateSegment?.(`tool-${e.toolCallId}`, unqueued(`tool-${e.toolCallId}`, { status: "awaiting-approval" }));
4261
- dispatchLifecycleEvent(target, "aparte-tool-approval-request", { toolCallId: e.toolCallId, toolName: e.name, input: e.input }, targetId);
4306
+ dispatchLifecycleEvent(target, "aparte-tool-approval-request", { toolCallId: e.toolCallId, toolName: e.name, input: e.input, ...turnOf }, targetId);
4262
4307
  break;
4263
4308
  case "tool-approved":
4264
- settle(e.toolCallId, { status: "pending" });
4309
+ settle2(e.toolCallId, { status: "pending" });
4265
4310
  break;
4266
4311
  case "tool-rejected":
4267
- settle(e.toolCallId, {
4312
+ settle2(e.toolCallId, {
4268
4313
  status: "rejected",
4269
4314
  result: e.reason,
4270
4315
  ...e.by ? { refusal: e.instruction ? { by: e.by, instruction: e.instruction } : { by: e.by } } : {}
4271
4316
  });
4272
4317
  break;
4273
4318
  case "tool-resolved":
4274
- settle(e.toolCallId, {
4319
+ settle2(e.toolCallId, {
4275
4320
  status: "resolved",
4276
4321
  result: e.result,
4277
4322
  ...e.structuredResult !== void 0 ? { structuredResult: e.structuredResult } : {}
4278
4323
  });
4279
4324
  break;
4280
4325
  case "tool-aborted":
4281
- settle(e.toolCallId, e.cause ? { status: "aborted", abortCause: e.cause } : { status: "aborted" });
4326
+ settle2(e.toolCallId, e.cause ? { status: "aborted", abortCause: e.cause } : { status: "aborted" });
4282
4327
  break;
4283
4328
  case "tool-failed":
4284
- settle(e.toolCallId, { status: "failed", result: e.error });
4329
+ settle2(e.toolCallId, { status: "failed", result: e.error });
4285
4330
  break;
4286
4331
  case "turn-limit-exceeded":
4287
4332
  if (e.scope === "global") {
@@ -4295,7 +4340,7 @@ function createStreamAdapter(opts) {
4295
4340
  code: AparteErrorCode.MAX_TURNS_EXCEEDED
4296
4341
  });
4297
4342
  } else if (e.toolCallId) {
4298
- settle(e.toolCallId, { status: "aborted", abortCause: "turn-limit" });
4343
+ settle2(e.toolCallId, { status: "aborted", abortCause: "turn-limit" });
4299
4344
  }
4300
4345
  break;
4301
4346
  case "run-aborted":
@@ -4372,7 +4417,7 @@ function createStreamAdapter(opts) {
4372
4417
  );
4373
4418
  }
4374
4419
  if (e.type === "tool-awaiting-approval") {
4375
- dispatchLifecycleEvent(target, "aparte-tool-approval-request", { toolCallId: e.toolCallId, toolName: e.name, input: e.input, agentId }, targetId);
4420
+ dispatchLifecycleEvent(target, "aparte-tool-approval-request", { toolCallId: e.toolCallId, toolName: e.name, input: e.input, agentId, ...turnOf }, targetId);
4376
4421
  }
4377
4422
  };
4378
4423
  }
@@ -4504,9 +4549,10 @@ function createAparteAgentHandler(options) {
4504
4549
  return jsonError(400, "Invalid JSON body.");
4505
4550
  }
4506
4551
  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 } }.");
4552
+ 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)) {
4553
+ return jsonError(400, "Body must be { v: 1, providerId?, messageId, conversationId?, request: { messages } }.");
4509
4554
  }
4555
+ const conversationId = body.conversationId || void 0;
4510
4556
  if (body.request.toolChoice && typeof body.request.toolChoice === "object") {
4511
4557
  return jsonError(400, "A forced tool call cannot come from the browser.");
4512
4558
  }
@@ -4533,7 +4579,8 @@ function createAparteAgentHandler(options) {
4533
4579
  ...!body.request.modelId && options.defaultModel ? { modelId: options.defaultModel } : {},
4534
4580
  tools: [...[...tools.values()].map((t) => t.tool), ...clientTools]
4535
4581
  };
4536
- if (options.prepareRequest) request = await options.prepareRequest(request, req);
4582
+ const turn2 = { messageId: body.messageId, ...conversationId ? { conversationId } : {} };
4583
+ if (options.prepareRequest) request = await options.prepareRequest(request, req, turn2);
4537
4584
  const offered = new Set((request.tools ?? []).map((t) => t.name));
4538
4585
  const tail = unansweredTail(request.messages);
4539
4586
  if (!body.resume && tail.length > 0) {
@@ -4560,7 +4607,7 @@ function createAparteAgentHandler(options) {
4560
4607
  }
4561
4608
  const key = await options.resolveKey?.(providerId);
4562
4609
  const external = new Set(clientTools.map((t) => t.name));
4563
- const rule = (call) => options.approvalPolicy?.(call, tools.get(call.name)?.tool);
4610
+ const rule = (call) => options.approvalPolicy?.(call, tools.get(call.name)?.tool, turn2);
4564
4611
  const run = new AbortController();
4565
4612
  if (req.signal.aborted) run.abort();
4566
4613
  else req.signal.addEventListener("abort", () => run.abort(), { once: true });
@@ -4608,7 +4655,11 @@ function createAparteAgentHandler(options) {
4608
4655
  },
4609
4656
  toolLookup: (name) => {
4610
4657
  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;
4658
+ return t ? (call, signal, run2) => t.handler(call, signal, {
4659
+ request: req,
4660
+ ...conversationId ? { conversationId } : {},
4661
+ ...run2 ? { run: run2 } : {}
4662
+ }) : void 0;
4612
4663
  },
4613
4664
  toolConfigLookup: (name) => {
4614
4665
  if (!offered.has(name)) return void 0;
@@ -4854,7 +4905,7 @@ const MAY_HOLD = /<(?:img|source)\b|data-aparte-image/i;
4854
4905
  const HELD = "a[data-aparte-image], span[data-aparte-image]";
4855
4906
  function applyImagePolicy(html, decide, words) {
4856
4907
  if (!html || !MAY_HOLD.test(html)) return html;
4857
- return typeof document === "undefined" ? applyImagePolicyWithoutDom(html, decide, words) : applyInTemplate(html, decide, words);
4908
+ return typeof document === "undefined" ? applyImagePolicyWithoutDom(html, decide, words) : applyInTemplate$1(html, decide, words);
4858
4909
  }
4859
4910
  function judgeImage(src, srcset, decide) {
4860
4911
  const candidates = srcset === void 0 ? [] : parseSrcset(srcset);
@@ -4872,7 +4923,7 @@ function judgeSource(src, srcset, decide) {
4872
4923
  if (kept.length) return writeSrcset(kept);
4873
4924
  return NO_ADDRESS.test(src) ? false : null;
4874
4925
  }
4875
- function applyInTemplate(html, decide, words) {
4926
+ function applyInTemplate$1(html, decide, words) {
4876
4927
  const template = document.createElement("template");
4877
4928
  template.innerHTML = html;
4878
4929
  const root = template.content;
@@ -4936,12 +4987,12 @@ function applyInTemplate(html, decide, words) {
4936
4987
  }
4937
4988
  return changed ? template.innerHTML : html;
4938
4989
  }
4939
- const RAW_TEXT = /* @__PURE__ */ new Set(["script", "style", "textarea", "title", "xmp", "iframe", "noembed", "noframes", "noscript", "plaintext"]);
4990
+ const RAW_TEXT$1 = /* @__PURE__ */ new Set(["script", "style", "textarea", "title", "xmp", "iframe", "noembed", "noframes", "noscript", "plaintext"]);
4940
4991
  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_.:-]*$/;
4992
+ const ASCII_LETTER$1 = /[A-Za-z]/;
4993
+ const SAFE_NAME$1 = /^[a-z][a-z0-9_.:-]*$/;
4943
4994
  function writeTag(tag, attrs, replace) {
4944
- const kept = attrs.filter(([name]) => !(name in replace) && SAFE_NAME.test(name));
4995
+ const kept = attrs.filter(([name]) => !(name in replace) && SAFE_NAME$1.test(name));
4945
4996
  const added = Object.entries(replace).filter((entry) => entry[1] !== null);
4946
4997
  return `<${tag}${[...kept, ...added].map(([name, value]) => ` ${name}="${escapeAttr(value)}"`).join("")}>`;
4947
4998
  }
@@ -4983,7 +5034,7 @@ function applyImagePolicyWithoutDom(html, decide, words) {
4983
5034
  }
4984
5035
  const closing = html[lt + 1] === "/";
4985
5036
  const nameAt = lt + (closing ? 2 : 1);
4986
- if (!ASCII_LETTER.test(html[nameAt] ?? "")) {
5037
+ if (!ASCII_LETTER$1.test(html[nameAt] ?? "")) {
4987
5038
  out += "<";
4988
5039
  i = lt + 1;
4989
5040
  continue;
@@ -4994,19 +5045,19 @@ function applyImagePolicyWithoutDom(html, decide, words) {
4994
5045
  break;
4995
5046
  }
4996
5047
  i = end;
4997
- const written = html.slice(lt, end);
5048
+ const written2 = html.slice(lt, end);
4998
5049
  if (closing) {
4999
5050
  if (tag === "a") links = Math.max(0, links - 1);
5000
5051
  const at = open.lastIndexOf(tag);
5001
5052
  if (at >= 0) open.length = at;
5002
- out += written;
5053
+ out += written2;
5003
5054
  continue;
5004
5055
  }
5005
5056
  const attr = (name) => attrs.find(([key]) => key === name)?.[1];
5006
- if (RAW_TEXT.has(tag)) {
5057
+ if (RAW_TEXT$1.has(tag)) {
5007
5058
  const close = lower.indexOf(`</${tag}`, end);
5008
5059
  const stop = close < 0 ? n : close;
5009
- out += written + html.slice(end, stop);
5060
+ out += written2 + html.slice(end, stop);
5010
5061
  i = stop;
5011
5062
  continue;
5012
5063
  }
@@ -5025,14 +5076,14 @@ function applyImagePolicyWithoutDom(html, decide, words) {
5025
5076
  if (tag === "source") {
5026
5077
  const kept = judgeSource(attr("src") ?? "", attr("srcset"), decide);
5027
5078
  if (kept === false) continue;
5028
- out += kept === (attr("srcset") ?? null) ? written : writeTag(tag, attrs, { srcset: kept });
5079
+ out += kept === (attr("srcset") ?? null) ? written2 : writeTag(tag, attrs, { srcset: kept });
5029
5080
  continue;
5030
5081
  }
5031
5082
  if (tag === "img") {
5032
5083
  const judged = judgeImage(attr("src") ?? "", attr("srcset"), decide);
5033
5084
  if (!judged) {
5034
5085
  const inPicture = open[open.length - 1] === "picture";
5035
- if (attr("srcset") === void 0 && (!inPicture || attr("referrerpolicy") === "no-referrer")) out += written;
5086
+ if (attr("srcset") === void 0 && (!inPicture || attr("referrerpolicy") === "no-referrer")) out += written2;
5036
5087
  else out += writeTag(tag, attrs, { srcset: null, ...inPicture ? { referrerpolicy: "no-referrer" } : {} });
5037
5088
  continue;
5038
5089
  }
@@ -5040,8 +5091,127 @@ function applyImagePolicyWithoutDom(html, decide, words) {
5040
5091
  else if (judged.decision === "load") out += writeTag(tag, attrs, { srcset: judged.srcset, referrerpolicy: "no-referrer" });
5041
5092
  continue;
5042
5093
  }
5043
- if (!VOID.has(tag) && !written.endsWith("/>")) open.push(tag);
5044
- out += written;
5094
+ if (!VOID.has(tag) && !written2.endsWith("/>")) open.push(tag);
5095
+ out += written2;
5096
+ }
5097
+ return out;
5098
+ }
5099
+ const STAYS = /^(?:#|mailto:|tel:|sms:)/i;
5100
+ const NEW_TAB = [["target", "_blank"], ["rel", "noopener noreferrer"]];
5101
+ const NEW_TAB_DECISION = Object.freeze({ target: "_blank", rel: "noopener noreferrer" });
5102
+ const IN_PLACE = Object.freeze({});
5103
+ function linkTargetAttributes(mode, href, wish) {
5104
+ if (mode !== "external-only" && !STAYS.test(href.replace(CONTROL_WS, ""))) return NEW_TAB;
5105
+ return linkAttributes(href, wish);
5106
+ }
5107
+ function linkDecision(mode, href) {
5108
+ return linkTargetAttributes(mode, href, "").length ? NEW_TAB_DECISION : IN_PLACE;
5109
+ }
5110
+ const MAY_LINK = /<a[\s/>]/i;
5111
+ function applyLinkTarget(html, mode) {
5112
+ if (!html || !MAY_LINK.test(html)) return html;
5113
+ return typeof document === "undefined" ? applyLinkTargetWithoutDom(html, mode) : applyInTemplate(html, mode);
5114
+ }
5115
+ function relForNewTab(rel) {
5116
+ const tokens = (rel ?? "").split(/[ \t\n\f\r]+/).filter((token) => token && token.toLowerCase() !== "opener");
5117
+ for (const needed of ["noopener", "noreferrer"]) {
5118
+ if (!tokens.some((token) => token.toLowerCase() === needed)) tokens.push(needed);
5119
+ }
5120
+ return tokens.join(" ");
5121
+ }
5122
+ function settle(decided, target, rel) {
5123
+ const wantedTarget = decided.find(([key]) => key === "target")?.[1];
5124
+ if (wantedTarget !== "_blank") return (target ?? void 0) === wantedTarget ? null : { target: wantedTarget, rel: void 0 };
5125
+ const wantedRel = relForNewTab(rel);
5126
+ return (target ?? void 0) === wantedTarget && (rel ?? void 0) === wantedRel ? null : { target: wantedTarget, rel: wantedRel };
5127
+ }
5128
+ function applyInTemplate(html, mode) {
5129
+ const template = document.createElement("template");
5130
+ template.innerHTML = html;
5131
+ let changed = false;
5132
+ for (const anchor of Array.from(template.content.querySelectorAll("a[href]"))) {
5133
+ const decided = linkTargetAttributes(mode, anchor.getAttribute("href") ?? "", anchor.getAttribute("target") ?? "");
5134
+ const settled2 = settle(decided, anchor.getAttribute("target"), anchor.getAttribute("rel"));
5135
+ if (!settled2) continue;
5136
+ anchor.removeAttribute("target");
5137
+ if (settled2.target !== void 0) anchor.setAttribute("target", settled2.target);
5138
+ if (settled2.rel !== void 0) {
5139
+ anchor.removeAttribute("rel");
5140
+ anchor.setAttribute("rel", settled2.rel);
5141
+ }
5142
+ changed = true;
5143
+ }
5144
+ return changed ? template.innerHTML : html;
5145
+ }
5146
+ const RAW_TEXT = /* @__PURE__ */ new Set(["script", "style", "textarea", "title", "xmp", "iframe", "noembed", "noframes", "noscript", "plaintext"]);
5147
+ const ASCII_LETTER = /[A-Za-z]/;
5148
+ const SAFE_NAME = /^[a-z][a-z0-9_.:-]*$/;
5149
+ const COMMENT_END = /--!?>/g;
5150
+ function commentEnd(html, at) {
5151
+ if (html[at] === ">") return at + 1;
5152
+ if (html.startsWith("->", at)) return at + 2;
5153
+ COMMENT_END.lastIndex = at;
5154
+ const m = COMMENT_END.exec(html);
5155
+ return m ? m.index + m[0].length : html.length;
5156
+ }
5157
+ function linkTag(written2, attrs, mode) {
5158
+ const attr = (name) => attrs.find(([key]) => key === name)?.[1];
5159
+ const href = attr("href");
5160
+ if (href === void 0) return written2;
5161
+ const decided = linkTargetAttributes(mode, href, attr("target") ?? "");
5162
+ const settled2 = settle(decided, attr("target"), attr("rel"));
5163
+ if (!settled2) return written2;
5164
+ const kept = attrs.filter(([name]) => name !== "target" && (settled2.rel === void 0 || name !== "rel") && SAFE_NAME.test(name));
5165
+ const added = [];
5166
+ if (settled2.target !== void 0) added.push(["target", settled2.target]);
5167
+ if (settled2.rel !== void 0) added.push(["rel", settled2.rel]);
5168
+ return `<a${[...kept, ...added].map(([name, value]) => ` ${name}="${escapeAttr(value)}"`).join("")}>`;
5169
+ }
5170
+ function applyLinkTargetWithoutDom(html, mode) {
5171
+ if (!html || !MAY_LINK.test(html)) return html;
5172
+ const lower = html.toLowerCase();
5173
+ const n = html.length;
5174
+ let out = "";
5175
+ let i = 0;
5176
+ while (i < n) {
5177
+ const lt = html.indexOf("<", i);
5178
+ if (lt < 0) {
5179
+ out += html.slice(i);
5180
+ break;
5181
+ }
5182
+ out += html.slice(i, lt);
5183
+ if (html.startsWith("<!--", lt)) {
5184
+ const stop = commentEnd(html, lt + 4);
5185
+ out += html.slice(lt, stop);
5186
+ i = stop;
5187
+ continue;
5188
+ }
5189
+ const closing = html[lt + 1] === "/";
5190
+ const nameAt = lt + (closing ? 2 : 1);
5191
+ if (!ASCII_LETTER.test(html[nameAt] ?? "")) {
5192
+ out += "<";
5193
+ i = lt + 1;
5194
+ continue;
5195
+ }
5196
+ const { tag, attrs, end } = readTag(html, nameAt);
5197
+ if (end < 0) {
5198
+ out += html.slice(lt);
5199
+ break;
5200
+ }
5201
+ i = end;
5202
+ const written2 = html.slice(lt, end);
5203
+ if (closing) {
5204
+ out += written2;
5205
+ continue;
5206
+ }
5207
+ if (RAW_TEXT.has(tag)) {
5208
+ const close = lower.indexOf(`</${tag}`, end);
5209
+ const stop = close < 0 ? n : close;
5210
+ out += written2 + html.slice(end, stop);
5211
+ i = stop;
5212
+ continue;
5213
+ }
5214
+ out += tag === "a" ? linkTag(written2, attrs, mode) : written2;
5045
5215
  }
5046
5216
  return out;
5047
5217
  }
@@ -5202,6 +5372,8 @@ class AparteConfig {
5202
5372
  _imageDecider = compileImagePolicy([]);
5203
5373
  /** Whether the app named an image policy, the default included; see `decideImage`. */
5204
5374
  _imagePolicyNamed = false;
5375
+ // Where the links a reply holds open (`link-target.ts`): by default every one in a new tab.
5376
+ _linkTarget = "new-tab";
5205
5377
  _systemPromptTemplate;
5206
5378
  _systemPromptVarsProvider;
5207
5379
  _statusRenderer;
@@ -5303,6 +5475,10 @@ class AparteConfig {
5303
5475
  _activityRenderers = /* @__PURE__ */ new Map();
5304
5476
  /** What a plugin says about a call, read after the app's display — see {@link setToolLineProvider}. */
5305
5477
  _toolLineProvider = null;
5478
+ /** Providers added with `registerToolLineProvider`, asked in the order they were added. */
5479
+ _extraToolLineProviders = [];
5480
+ /** 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. */
5481
+ _stepLabels = /* @__PURE__ */ new Map();
5306
5482
  /** Tagged blocks the stream parser recognises in the prose — see {@link registerStreamBlock}. */
5307
5483
  _streamBlocks = /* @__PURE__ */ new Map();
5308
5484
  _segmentDefaults = /* @__PURE__ */ new Map();
@@ -5519,9 +5695,11 @@ class AparteConfig {
5519
5695
  * zero-dependency allowlist sanitizer.
5520
5696
  *
5521
5697
  * 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).
5698
+ * `aparte-` classes, no layout styles, no form controls. DOMPurify's defaults hold
5699
+ * none of the three, so chain it in front of `defaultSanitizer` rather than in its
5700
+ * place (the example below). Where a link opens ({@link AparteConfig.setLinkTarget | setLinkTarget})
5701
+ * and which pictures load ({@link AparteConfig.setImagePolicy | setImagePolicy}) are
5702
+ * applied after it, whichever it is.
5525
5703
  *
5526
5704
  * @param sanitizer A sanitizer function, or `null` to DISABLE sanitization.
5527
5705
  * Disabling exposes you to XSS from LLM-authored content — only do so for
@@ -5541,16 +5719,19 @@ class AparteConfig {
5541
5719
  this._notify();
5542
5720
  }
5543
5721
  /**
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.
5722
+ * Run the active sanitizer over provider-produced HTML, then the link target
5723
+ * ({@link AparteConfig.setLinkTarget | setLinkTarget}): every link gets the `target` and
5724
+ * `rel` it opens with; then the image policy ({@link AparteConfig.setImagePolicy | setImagePolicy}):
5725
+ * a picture the policy does not let load comes back as a link that loads it on a click.
5726
+ * Public so a streaming-markdown provider (which appends DOM directly, bypassing
5727
+ * `renderMarkdown`) can apply the same rules. Both run whichever sanitizer is set, none
5728
+ * included, so replacing it does not send a reply's links back into the chat's own frame,
5729
+ * nor turn its pictures back into requests the reader never made.
5550
5730
  */
5551
5731
  sanitizeHtml(html) {
5552
5732
  const clean = this._sanitizer ? this._sanitizer(html) : html;
5553
- return applyImagePolicy(clean, (url) => this.decideImage(url), () => this._heldImageWords());
5733
+ const linked = applyLinkTarget(clean, this._linkTarget);
5734
+ return applyImagePolicy(linked, (url) => this.decideImage(url), () => this._heldImageWords());
5554
5735
  }
5555
5736
  /**
5556
5737
  * Which pictures a model or a tool chose load before the reader asks — in a reply's
@@ -5622,6 +5803,45 @@ class AparteConfig {
5622
5803
  icon: this.getIcon("image")
5623
5804
  };
5624
5805
  }
5806
+ /**
5807
+ * Where the links a reply holds open — in its Markdown, its sources, a document it wrote.
5808
+ * `'new-tab'`, the default, opens every one in a new tab, same-site ones included;
5809
+ * `'external-only'` opens a link to another site in a new tab and keeps a same-site one in
5810
+ * the page, as before 1.9. Either way a link to `#…`, `mailto:`, `tel:` or `sms:` is left as
5811
+ * written, a new tab goes with `rel="noopener noreferrer"`, and the `target` the model wrote
5812
+ * does not choose. What is on screen is drawn again.
5813
+ *
5814
+ * In a single-page app or an Electron window, a same-site link followed in place replaces
5815
+ * the whole app, the conversation with it. To route a link yourself — your router, a pane,
5816
+ * the system browser — cancel the chat's `aparte-link-click`, whichever mode is set.
5817
+ *
5818
+ * @example aparteGlobalConfig.setLinkTarget('external-only');
5819
+ */
5820
+ setLinkTarget(mode) {
5821
+ if (mode === this._linkTarget) return;
5822
+ this._linkTarget = mode;
5823
+ bumpRenderingVersion(this);
5824
+ this._notify();
5825
+ }
5826
+ /** Where the links a reply holds open: {@link AparteConfig.setLinkTarget | setLinkTarget}'s mode, `'new-tab'` by default. */
5827
+ getLinkTarget() {
5828
+ return this._linkTarget;
5829
+ }
5830
+ /**
5831
+ * Where a link to `href` opens under this config's link target: `{ target: '_blank', rel:
5832
+ * 'noopener noreferrer' }` for a new tab, `{}` for the page itself. For a plugin that draws
5833
+ * links itself, as `@aparte/plugin-streaming-markdown` does: set what it returns, and no
5834
+ * `target` of your own. It does not judge whether the address is safe to link —
5835
+ * `isSafeUrl` does.
5836
+ *
5837
+ * @example
5838
+ * const link = document.createElement('a');
5839
+ * link.href = url;
5840
+ * Object.assign(link, aparteGlobalConfig.decideLink(url));
5841
+ */
5842
+ decideLink(href) {
5843
+ return linkDecision(this._linkTarget, href);
5844
+ }
5625
5845
  /**
5626
5846
  * Set the system prompt template. Supports `{{key}}` placeholders resolved via setSystemPromptVarsProvider.
5627
5847
  * Pass undefined to clear.
@@ -6050,11 +6270,12 @@ class AparteConfig {
6050
6270
  /**
6051
6271
  * What the policy says about one call, with the tool's own `needsApproval` as the
6052
6272
  * answer when it has no opinion. The one place the two are combined, so the client's
6053
- * gate predicate and its approval channel cannot disagree.
6273
+ * gate predicate and its approval channel cannot disagree. `turn` is handed to the
6274
+ * policy as its third argument; the client passes the turn the call belongs to.
6054
6275
  */
6055
- ruleOnToolCall(call) {
6276
+ ruleOnToolCall(call, turn2) {
6056
6277
  const tool = this._tools.get(call.name)?.tool;
6057
- const ruling = this._approvalPolicy?.(call, tool);
6278
+ const ruling = this._approvalPolicy?.(call, tool, turn2);
6058
6279
  if (ruling) return ruling;
6059
6280
  return { verdict: tool?.needsApproval ? "ask" : "allow" };
6060
6281
  }
@@ -6579,7 +6800,40 @@ class AparteConfig {
6579
6800
  bumpRenderingVersion(this);
6580
6801
  this._notify();
6581
6802
  }
6582
- /** The tool-line provider this config reads: its own, else the page's. */
6803
+ /**
6804
+ * Add a tool-line provider beside the one {@link AparteConfig.setToolLineProvider | setToolLineProvider()}
6805
+ * holds, and return the function that removes it. The providers are asked in order — the
6806
+ * app's `setToolLineProvider` first, then these in the order they were added — and the
6807
+ * first one that answers a call wins, so a plugin registering its own never replaces the
6808
+ * app's, nor another plugin's. Each call is a provider of its own, even with the same function.
6809
+ * @example
6810
+ * const release = aparteGlobalConfig.registerToolLineProvider((segment) =>
6811
+ * segment.toolCall.name === 'delegate' ? { activity: 'Reading the parser' } : undefined);
6812
+ * release();
6813
+ */
6814
+ registerToolLineProvider(provider) {
6815
+ const entry = (segment) => provider(segment);
6816
+ this._extraToolLineProviders.push(entry);
6817
+ bumpRenderingVersion(this);
6818
+ this._notify();
6819
+ return () => {
6820
+ const at = this._extraToolLineProviders.indexOf(entry);
6821
+ if (at === -1) return;
6822
+ this._extraToolLineProviders.splice(at, 1);
6823
+ bumpRenderingVersion(this);
6824
+ this._notify();
6825
+ };
6826
+ }
6827
+ /**
6828
+ * Every tool-line provider this config reads, in the order they are asked: its own
6829
+ * (`setToolLineProvider`, then the registered ones), else the page's.
6830
+ */
6831
+ getToolLineProviders() {
6832
+ const own = [...this._toolLineProvider ? [this._toolLineProvider] : [], ...this._extraToolLineProviders];
6833
+ if (own.length || this === aparteGlobalConfig) return own;
6834
+ return aparteGlobalConfig.getToolLineProviders();
6835
+ }
6836
+ /** The tool-line provider `setToolLineProvider` set: this config's own, else the page's. */
6583
6837
  getToolLineProvider() {
6584
6838
  if (this._toolLineProvider || this === aparteGlobalConfig) return this._toolLineProvider;
6585
6839
  return aparteGlobalConfig._toolLineProvider;
@@ -6649,6 +6903,59 @@ class AparteConfig {
6649
6903
  getToolInputFormatter(toolName) {
6650
6904
  return this.getToolDisplay(toolName)?.formatInput;
6651
6905
  }
6906
+ /**
6907
+ * Say how a step is called on screen, in place of the name a run announced. A server that
6908
+ * streams `step-start { name }` sends a stable key — `slot-wait`, `restore`, `reread` —
6909
+ * and the page knows the person's language: this maps one to the other, wherever a step is
6910
+ * shown (the waiting indicator, which a screen reader reads in place of "Typing", and a
6911
+ * sub-agent's line). A name nobody labelled shows as it always did: itself, because core
6912
+ * never makes a label up.
6913
+ *
6914
+ * The label is text, never HTML, or a function of the locale, asked at every draw and on
6915
+ * every config change — so a language switch changes the words of a step that is open.
6916
+ * One that throws, or says nothing, leaves the name. One label per name, per config:
6917
+ * registering a name again replaces its label, and a chat with a config of its own reads
6918
+ * that config's labels, as it reads its tool displays.
6919
+ *
6920
+ * Only what is shown is labelled. The step keeps the name the run announced — for
6921
+ * {@link observeRunEvents}, for the target, for everything an app stores — and is never
6922
+ * saved with the reply. Registering tells the chats on the page, so a label reaches a step
6923
+ * that is open. Returns the function that takes the label off again (it changes nothing
6924
+ * once another registration has replaced it).
6925
+ *
6926
+ * @example
6927
+ * aparteGlobalConfig.registerStepLabel('slot-wait', 'Waiting for a free slot…');
6928
+ *
6929
+ * @example
6930
+ * // In the person's language, and live: a switch of the locale relabels a step that is open.
6931
+ * aparteGlobalConfig.registerStepLabel('reread', ({ locale }) =>
6932
+ * locale.tag?.startsWith('fr') ? 'Relecture de la conversation…' : 'Re-reading the conversation…');
6933
+ */
6934
+ registerStepLabel(name, label) {
6935
+ const entry = { label };
6936
+ this._stepLabels.set(name, entry);
6937
+ this._notify();
6938
+ return () => {
6939
+ if (this._stepLabels.get(name) !== entry) return;
6940
+ this._stepLabels.delete(name);
6941
+ this._notify();
6942
+ };
6943
+ }
6944
+ /**
6945
+ * The words shown for a step named `name`, or `undefined` when none are registered, they
6946
+ * say nothing, or the function that gives them throws — then the name itself is shown. A
6947
+ * function label is asked here, with the locale as it is now.
6948
+ */
6949
+ getStepLabel(name) {
6950
+ const entry = this._stepLabels.get(name);
6951
+ if (!entry) return void 0;
6952
+ try {
6953
+ const text = typeof entry.label === "function" ? entry.label({ name, locale: this._locale }) : entry.label;
6954
+ return typeof text === "string" && text.trim() ? text.trim() : void 0;
6955
+ } catch {
6956
+ return void 0;
6957
+ }
6958
+ }
6652
6959
  /**
6653
6960
  * Teach the stream parser a tagged block: `<tag attr="…">…</tag>` in the model's
6654
6961
  * prose becomes the segment `toSegment` builds, streamed delta by delta.
@@ -6853,7 +7160,7 @@ class AparteConfig {
6853
7160
  }
6854
7161
  /**
6855
7162
  * 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
7163
+ * the tools with their renderers and summaries, the tool-line provider, the step labels, the renderers and render hooks, the
6857
7164
  * Markdown and highlight providers, the code-language renderers, the sanitizer, the system prompt, the locale, icons,
6858
7165
  * avatars, actions and host handlers, the conversation manager, the question presenters
6859
7166
  * and their queue, the run-event observers. Three things stay: the transport, the key sources added with
@@ -6886,6 +7193,7 @@ class AparteConfig {
6886
7193
  this._imageDecider = compileImagePolicy([]);
6887
7194
  this._imagePolicyNamed = false;
6888
7195
  forgetShownImages(this);
7196
+ this._linkTarget = "new-tab";
6889
7197
  this._aiProviders.clear();
6890
7198
  this._fetchedModels.clear();
6891
7199
  this._tools.clear();
@@ -6896,6 +7204,8 @@ class AparteConfig {
6896
7204
  notifyRenderersChanged(this);
6897
7205
  this._toolDisplays.clear();
6898
7206
  this._toolLineProvider = null;
7207
+ this._extraToolLineProviders = [];
7208
+ this._stepLabels.clear();
6899
7209
  this._streamBlocks.clear();
6900
7210
  this._runEventObservers = [];
6901
7211
  this._modelConfig = {};
@@ -7634,6 +7944,32 @@ function tellConversationStatus(id, status) {
7634
7944
  function conversationStatusOf(id) {
7635
7945
  return known.get(id) ?? null;
7636
7946
  }
7947
+ const OPEN_CONVERSATION = Symbol.for("aparte.openConversation");
7948
+ function offerOpenConversation(host2, read) {
7949
+ const slot = host2;
7950
+ slot[OPEN_CONVERSATION] = read;
7951
+ return () => {
7952
+ if (slot[OPEN_CONVERSATION] === read) delete slot[OPEN_CONVERSATION];
7953
+ };
7954
+ }
7955
+ function openConversationOf(el2) {
7956
+ for (let node = el2; node; node = node.parentElement) {
7957
+ const read = node[OPEN_CONVERSATION];
7958
+ if (read) return read();
7959
+ }
7960
+ return null;
7961
+ }
7962
+ const boundTo = /* @__PURE__ */ new WeakMap();
7963
+ function enrol(manager, controller, on) {
7964
+ if (!manager) return;
7965
+ let set = boundTo.get(manager);
7966
+ if (on) {
7967
+ if (!set) boundTo.set(manager, set = /* @__PURE__ */ new Set());
7968
+ set.add(controller);
7969
+ } else {
7970
+ set?.delete(controller);
7971
+ }
7972
+ }
7637
7973
  const MAX_COMPACTION_SAVE_WAITS = 6;
7638
7974
  class AparteConversationController {
7639
7975
  _binding;
@@ -7642,6 +7978,11 @@ class AparteConversationController {
7642
7978
  _isStreaming = false;
7643
7979
  _isLoadingConversation = false;
7644
7980
  _ensureInFlight = null;
7981
+ /**
7982
+ * The conversation this chat's first message is creating, from the moment `createNew()`
7983
+ * is called until it resolves — see {@link pendingId}.
7984
+ */
7985
+ _pendingId = null;
7645
7986
  /** The conversation the turn in flight started in, and what the lists were told of it. */
7646
7987
  _turn = null;
7647
7988
  /** The reply the turn in flight writes into, from its `aparte-message-start`. */
@@ -7694,6 +8035,31 @@ class AparteConversationController {
7694
8035
  get activeId() {
7695
8036
  return this._activeId;
7696
8037
  }
8038
+ /**
8039
+ * The conversation this chat's first message is creating, while it is being created:
8040
+ * set when the send calls `createNew()`, `null` again once {@link activeId} holds it.
8041
+ *
8042
+ * It is this chat's own, whatever the manager says. The manager has ONE `activeId`,
8043
+ * which every chat on it writes when it opens or creates a conversation; with two chats
8044
+ * it names the one that moved last. A wrapper that is handed this id back — through
8045
+ * `onConversationCreated`, or bound to the manager's `activeId`, which changes before
8046
+ * the creation resolves — knows from it that the chat already shows that conversation.
8047
+ */
8048
+ get pendingId() {
8049
+ return this._pendingId;
8050
+ }
8051
+ /**
8052
+ * The conversation a message sent now belongs to: the open one, or — for the first
8053
+ * message of a chat — the one that send is creating. The client hears the send right
8054
+ * after this controller does, so the creation has already started and its id is known
8055
+ * ({@link pendingId}); this controller's own id follows once the conversation is saved.
8056
+ * `_ensureConversationAndPersist` reads the same two places to decide where the message
8057
+ * is saved, so a turn is carried to the conversation its message was written in. Never
8058
+ * the manager's `activeId`: that may be another chat's conversation.
8059
+ */
8060
+ _openId() {
8061
+ return this._activeId ?? this._pendingId;
8062
+ }
7697
8063
  /**
7698
8064
  * Lazily resolve the conversation manager. Returns `undefined` if none is
7699
8065
  * registered — the controller then runs in degraded mode: optimistic UI
@@ -7702,7 +8068,7 @@ class AparteConversationController {
7702
8068
  * conversation lifecycle yet.
7703
8069
  */
7704
8070
  _manager() {
7705
- const manager = this._options.manager ?? (() => {
8071
+ const manager = this._options.manager ?? this._keptManager ?? (() => {
7706
8072
  const scoped = resolveConfig(this._binding.host);
7707
8073
  const m = scoped.getConversationManager();
7708
8074
  if (!m) this._warnManagerOnTheWrongConfig(scoped);
@@ -7710,11 +8076,63 @@ class AparteConversationController {
7710
8076
  })();
7711
8077
  if (manager && this._bound && manager !== this._subscribedTo) {
7712
8078
  this._unsubscribeManager?.();
8079
+ enrol(this._subscribedTo, this, false);
8080
+ enrol(manager, this, true);
7713
8081
  this._subscribedTo = manager;
7714
8082
  this._unsubscribeManager = manager.subscribe(this._onManagerChanged);
7715
8083
  }
7716
8084
  return manager;
7717
8085
  }
8086
+ /**
8087
+ * The manager a config change could not take the open conversation away from: the new
8088
+ * config's manager does not hold it, or the new config has none. The chat keeps saving
8089
+ * that conversation where it lives until it opens another — see {@link followConfig}.
8090
+ */
8091
+ _keptManager = null;
8092
+ /** Release handle for a wait on a new manager still loading its list (see followConfig). */
8093
+ _stopConfigWait = null;
8094
+ /**
8095
+ * The chat was given another config (`AparteChatHost.setConfig`), and its conversation
8096
+ * manager may be another one. Nothing on screen is lost either way:
8097
+ * - the new manager holds the open conversation: it is opened again from there, and saved there;
8098
+ * - it does not, or the new config has no manager: the chat keeps the manager it had for
8099
+ * the conversation it shows, and goes on saving it there; the next conversation it
8100
+ * opens comes from the new config.
8101
+ * A manager still loading its list is waited for before it is asked.
8102
+ */
8103
+ followConfig() {
8104
+ this._stopConfigWait?.();
8105
+ this._stopConfigWait = null;
8106
+ if (this._options.manager || !this._bound) return;
8107
+ const host2 = this._binding.host;
8108
+ const before = this._keptManager ?? this._subscribedTo;
8109
+ const next = resolveConfig(host2).getConversationManager();
8110
+ const id = this._openId();
8111
+ if (!before || next === before || !id) {
8112
+ this._keptManager = null;
8113
+ this._manager();
8114
+ return;
8115
+ }
8116
+ this._keptManager = before;
8117
+ if (!next) return;
8118
+ const decide = () => {
8119
+ if (!this._bound || this._openId() !== id || resolveConfig(host2).getConversationManager() !== next) return;
8120
+ if (!next.conversations.some((c) => c.id === id)) return;
8121
+ this._keptManager = null;
8122
+ this._manager();
8123
+ void this.setConversationId(id);
8124
+ };
8125
+ if (next.initialized) {
8126
+ decide();
8127
+ return;
8128
+ }
8129
+ const stop = next.subscribe(() => {
8130
+ stop();
8131
+ this._stopConfigWait = null;
8132
+ decide();
8133
+ });
8134
+ this._stopConfigWait = stop;
8135
+ }
7718
8136
  /**
7719
8137
  * Degraded mode is legitimate — a host that never opted into the conversation
7720
8138
  * lifecycle has no manager and should not be nagged. Registering one on the
@@ -7747,7 +8165,7 @@ class AparteConversationController {
7747
8165
  this._turn = null;
7748
8166
  return;
7749
8167
  }
7750
- const id = this._turn?.id ?? (status === "running" ? this._activeId ?? this._manager()?.activeId ?? null : null);
8168
+ const id = this._turn?.id ?? (status === "running" ? this._openId() : null);
7751
8169
  if (!id) return;
7752
8170
  this._turn = { id, status };
7753
8171
  tellConversationStatus(id, status);
@@ -7847,13 +8265,19 @@ class AparteConversationController {
7847
8265
  }
7848
8266
  this._bound = true;
7849
8267
  this._manager();
8268
+ this._withdrawOpenConversation = offerOpenConversation(host2, () => this._openId());
7850
8269
  return () => this.unbind();
7851
8270
  }
8271
+ /** Takes the open-conversation reader off the host (see `bind`). */
8272
+ _withdrawOpenConversation = null;
7852
8273
  /** Detach event listeners. */
7853
8274
  /** Release handle for the hydration-retry subscription (see setConversationId). */
7854
8275
  _stopHydrationRetry = null;
7855
8276
  unbind() {
8277
+ this._withdrawOpenConversation?.();
8278
+ this._withdrawOpenConversation = null;
7856
8279
  this._bound = false;
8280
+ enrol(this._subscribedTo, this, false);
7857
8281
  this._subscribedTo = null;
7858
8282
  this._persistActive();
7859
8283
  if (this._turn?.status === "running") this._setTurn(null);
@@ -7861,6 +8285,9 @@ class AparteConversationController {
7861
8285
  this._turnMessage = null;
7862
8286
  this._stopHydrationRetry?.();
7863
8287
  this._stopHydrationRetry = null;
8288
+ this._stopConfigWait?.();
8289
+ this._stopConfigWait = null;
8290
+ this._keptManager = null;
7864
8291
  const host2 = this._binding.host;
7865
8292
  if (this._onSendCapture) {
7866
8293
  host2.removeEventListener("aparte-send", this._onSendCapture, { capture: true });
@@ -7985,6 +8412,10 @@ class AparteConversationController {
7985
8412
  }
7986
8413
  async _openConversation(id) {
7987
8414
  const isSwitch = id !== this._activeId;
8415
+ if (isSwitch && this._keptManager) {
8416
+ this._persistActive();
8417
+ this._keptManager = null;
8418
+ }
7988
8419
  const manager = this._manager();
7989
8420
  if (isSwitch && this._isStreaming) {
7990
8421
  if (this._turn?.status === "waiting") this._turn = null;
@@ -8164,13 +8595,31 @@ class AparteConversationController {
8164
8595
  }
8165
8596
  void manager.updateMessages(this._activeId, msgs, tree);
8166
8597
  }
8598
+ /**
8599
+ * The conversation the manager names as active, for a chat that has none: only when this
8600
+ * controller is the one chat on that manager (an app that called `manager.createNew()`
8601
+ * itself and never gave the id to the chat), and only an empty conversation, whose
8602
+ * messages are in memory — a save from this chat must not write over messages it never
8603
+ * showed. With several chats the manager's `activeId` names whichever moved last.
8604
+ */
8605
+ _adoptable(manager) {
8606
+ const id = manager.activeId;
8607
+ if (!id || this._ensureInFlight) return null;
8608
+ const chats = boundTo.get(manager);
8609
+ if (!chats || chats.size !== 1 || !chats.has(this)) return null;
8610
+ const conv = manager.conversations.find((c) => c.id === id);
8611
+ if (!conv || conv.archivedAt || !manager.isLoaded(id) || (conv.messages?.length ?? 0) > 0) return null;
8612
+ return id;
8613
+ }
8167
8614
  async _ensureConversationAndPersist(userMsg) {
8168
8615
  const manager = this._manager();
8169
8616
  if (!manager) {
8170
8617
  return;
8171
8618
  }
8619
+ const adopted = this._activeId === null && this._pendingId === null ? this._adoptable(manager) : null;
8620
+ if (adopted) this._activeId = adopted;
8172
8621
  const wasActiveId = this._activeId;
8173
- let convId = wasActiveId ?? manager.activeId;
8622
+ let convId = wasActiveId ?? this._pendingId;
8174
8623
  if (convId && this._activeId === null && this._ensureInFlight) {
8175
8624
  await this._ensureInFlight.catch(() => {
8176
8625
  });
@@ -8179,10 +8628,13 @@ class AparteConversationController {
8179
8628
  if (!convId) {
8180
8629
  if (!this._ensureInFlight) {
8181
8630
  const text = (userMsg.content ?? "").toString().trim();
8182
- this._ensureInFlight = manager.createNew(text).then((conv) => conv.id);
8631
+ const created = manager.createNew(text);
8632
+ this._pendingId = manager.activeId;
8633
+ this._ensureInFlight = created.then((conv) => conv.id);
8183
8634
  }
8184
8635
  convId = await this._ensureInFlight;
8185
8636
  this._ensureInFlight = null;
8637
+ this._pendingId = null;
8186
8638
  if (this._activeId !== wasActiveId && this._activeId !== convId) {
8187
8639
  void manager.delete(convId).catch(() => {
8188
8640
  });
@@ -8218,15 +8670,6 @@ function gateGlide(el2) {
8218
8670
  el2.addEventListener("aparte-send", lift);
8219
8671
  return off;
8220
8672
  }
8221
- function chatIdOf(el2) {
8222
- let node = el2.parentElement;
8223
- while (node) {
8224
- const isHost = node.tagName.toLowerCase() === "aparte-chat" || node.hasAttribute("data-aparte-chat");
8225
- if (isHost && node.id) return node.id;
8226
- node = node.parentElement;
8227
- }
8228
- return void 0;
8229
- }
8230
8673
  class CheckpointStateWatcher {
8231
8674
  constructor(_options) {
8232
8675
  this._options = _options;
@@ -8382,6 +8825,8 @@ class AparteChatHost {
8382
8825
  _controller;
8383
8826
  _teardown = [];
8384
8827
  _bound = false;
8828
+ /** A config given while a turn was in flight, applied when it ends — see {@link setConfig}. */
8829
+ _nextConfig = null;
8385
8830
  constructor(binding, options = {}) {
8386
8831
  this.binding = binding;
8387
8832
  this.options = options;
@@ -8473,15 +8918,89 @@ class AparteChatHost {
8473
8918
  _setStreamingId(id) {
8474
8919
  if (this._streamingId === id) return;
8475
8920
  this._streamingId = id;
8921
+ if (id === null && this._nextConfig) {
8922
+ const { config } = this._nextConfig;
8923
+ this._nextConfig = null;
8924
+ this._applyConfig(config);
8925
+ }
8476
8926
  this.binding.onStreamingChange?.(id);
8477
8927
  this._vp()?.setTranscriptBusy?.(id !== null);
8478
8928
  }
8929
+ // ── config ─────────────────────────────────────────────────────────────
8930
+ /**
8931
+ * Give the chat another instance config, or none (`undefined`: the page's). A wrapper
8932
+ * calls it when its `config` prop changes: the boundary on the host moves, and every
8933
+ * element inside re-resolves its config. The config it already has changes nothing, so a
8934
+ * wrapper may hand it on every render — a NEW object each render is a new config each time.
8935
+ *
8936
+ * The messages stay. When the new config's conversation manager is another one, the open
8937
+ * conversation is opened again from it if it holds that conversation; otherwise the chat
8938
+ * keeps saving it to the manager it had, until it opens another one.
8939
+ *
8940
+ * Not in the middle of a turn: a reply half-drawn with one configuration's renderers and
8941
+ * finished with another's is worse than a change that waits. The last config given
8942
+ * during the turn is applied when the turn ends.
8943
+ */
8944
+ setConfig(config) {
8945
+ if (config === this.options.config) {
8946
+ this._nextConfig = null;
8947
+ return;
8948
+ }
8949
+ if (this._streamingId !== null) {
8950
+ this._nextConfig = { config };
8951
+ return;
8952
+ }
8953
+ this._nextConfig = null;
8954
+ this._applyConfig(config);
8955
+ }
8956
+ _applyConfig(config) {
8957
+ if (config === this.options.config) return;
8958
+ this.options.config = config;
8959
+ if (!this._bound) return;
8960
+ if (config) attachConfig(this.binding.host, config);
8961
+ else detachConfig(this.binding.host);
8962
+ this._controller?.followConfig();
8963
+ }
8479
8964
  // ── conversation ───────────────────────────────────────────────────────
8480
- /** Load / switch the active conversation via the controller. */
8965
+ /**
8966
+ * Load / switch the active conversation via the controller. The same id again re-reads
8967
+ * it from the manager: this is the imperative call, the one that means "open this now".
8968
+ * A `conversationId` prop goes through {@link syncConversationId}.
8969
+ */
8481
8970
  setConversationId(id) {
8482
8971
  this._conversationId = id;
8483
8972
  return this._controller?.setConversationId(id) ?? Promise.resolve();
8484
8973
  }
8974
+ /**
8975
+ * Follow a wrapper's `conversationId` prop: open `id`, unless it is the conversation this
8976
+ * chat already shows or is creating.
8977
+ *
8978
+ * The documented pattern gives the created conversation back to the chat — the prop set
8979
+ * from `onConversationCreated`, or bound to the manager's `activeId`, which names the new
8980
+ * conversation before the creation even resolves. That id arrives while the first reply
8981
+ * streams, and opening it then re-read a conversation the manager did not hold the reply
8982
+ * of yet: the transcript was replaced under the stream. Compared with the controller, not
8983
+ * with the last prop: the person opens other conversations from the list without the prop
8984
+ * hearing of it.
8985
+ */
8986
+ syncConversationId(id) {
8987
+ const controller = this._controller;
8988
+ if (!controller) {
8989
+ this._conversationId = id;
8990
+ return Promise.resolve();
8991
+ }
8992
+ if (id === controller.activeId || id !== null && id === controller.pendingId) return Promise.resolve();
8993
+ return this.setConversationId(id);
8994
+ }
8995
+ /**
8996
+ * The conversation this chat shows: the one it opened, or the one its first message is
8997
+ * creating; `null` for a chat with none yet. Per chat, which the manager's single
8998
+ * `activeId` cannot say once several chats share it.
8999
+ */
9000
+ getConversationId() {
9001
+ const controller = this._controller;
9002
+ return controller ? controller.activeId ?? controller.pendingId : this._conversationId;
9003
+ }
8485
9004
  _unbindController;
8486
9005
  _createController(host2) {
8487
9006
  const convBinding = {
@@ -9243,8 +9762,44 @@ function messageWireText(message) {
9243
9762
  const text = extractWireText(message);
9244
9763
  return message.compaction ? underPreamble(text) : text;
9245
9764
  }
9765
+ const FAILS_AGAIN = /* @__PURE__ */ new Set([
9766
+ AparteErrorCode.USAGE_CONTEXT_EXCEEDED,
9767
+ AparteErrorCode.PROVIDER_POLICY,
9768
+ AparteErrorCode.USAGE_BAD_REQUEST
9769
+ ]);
9770
+ function failedForGood(reply, asked2) {
9771
+ const segments = reply.segments ?? [];
9772
+ let code;
9773
+ for (let i = segments.length - 1; i >= 0; i--) {
9774
+ const s = segments[i];
9775
+ if (s.type === "error") {
9776
+ code = s.code;
9777
+ break;
9778
+ }
9779
+ }
9780
+ if (code !== void 0 && FAILS_AGAIN.has(code)) return true;
9781
+ return asked2.some((m) => (m.attachments?.length ?? 0) > 0);
9782
+ }
9783
+ function withoutAbandonedTurns(messages) {
9784
+ const dropped = /* @__PURE__ */ new Set();
9785
+ let asked2 = [];
9786
+ for (const m of messages) {
9787
+ if (m.role === "user") {
9788
+ if (!m.compaction) asked2.push(m);
9789
+ } else if (m.role === "assistant") {
9790
+ if (m.status !== "error") {
9791
+ asked2 = [];
9792
+ } else if (failedForGood(m, asked2)) {
9793
+ for (const a of asked2) dropped.add(a);
9794
+ dropped.add(m);
9795
+ asked2 = [];
9796
+ }
9797
+ }
9798
+ }
9799
+ return dropped.size === 0 ? [...messages] : messages.filter((m) => !dropped.has(m));
9800
+ }
9246
9801
  function wireMessages(messages) {
9247
- return messages.filter((m) => {
9802
+ return withoutAbandonedTurns(messages).filter((m) => {
9248
9803
  if (m.role !== "user" && m.role !== "assistant") return false;
9249
9804
  return m.status !== "error" && !isInFlight(m);
9250
9805
  }).flatMap((m) => {
@@ -9392,7 +9947,7 @@ function labelGroup(list, opts) {
9392
9947
  if (opts.titleId) list.setAttribute("aria-labelledby", opts.titleId);
9393
9948
  else if (opts.fallbackLabel) list.setAttribute("aria-label", opts.fallbackLabel);
9394
9949
  }
9395
- function buildEnumField(field, onChange, fallbackLabel, settle) {
9950
+ function buildEnumField(field, onChange, fallbackLabel, settle2) {
9396
9951
  const wrap = el$1("div", "aparte-elic-field aparte-elic-enum");
9397
9952
  const titleId = fieldHeader(wrap, field, fallbackLabel);
9398
9953
  const list = el$1("div", "aparte-elic-options");
@@ -9401,12 +9956,12 @@ function buildEnumField(field, onChange, fallbackLabel, settle) {
9401
9956
  const controlRecipe = type === "checkbox" ? "aparte-checkbox" : "aparte-radio";
9402
9957
  const allowOther = field.allowOther ?? contextConfig().getElicitationOptions().allowOther;
9403
9958
  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;
9959
+ const settling = settle2 != null && !field.multiple && defaults.size === 0;
9405
9960
  labelGroup(list, { multiple: field.multiple, commands: settling, titleId, fallbackLabel });
9406
9961
  const buildOption = (value, label, description, recommended) => {
9407
9962
  if (settling) {
9408
9963
  const button = commandOption(label, description, recommended);
9409
- button.addEventListener("click", () => settle?.(value));
9964
+ button.addEventListener("click", () => settle2?.(value));
9410
9965
  return button;
9411
9966
  }
9412
9967
  const row = el$1("label", "aparte-field-choice aparte-elic-option" + (recommended ? " aparte-elic-option--recommended" : ""));
@@ -9521,18 +10076,18 @@ function buildEnumField(field, onChange, fallbackLabel, settle) {
9521
10076
  focus: () => controls()[0]?.focus()
9522
10077
  };
9523
10078
  }
9524
- function buildBooleanField(field, onChange, fallbackLabel, settle) {
10079
+ function buildBooleanField(field, onChange, fallbackLabel, settle2) {
9525
10080
  const wrap = el$1("div", "aparte-elic-field aparte-elic-boolean");
9526
10081
  const titleId = fieldHeader(wrap, field, fallbackLabel);
9527
10082
  const list = el$1("div", "aparte-elic-options");
9528
10083
  const name = `elic-${uuid()}`;
9529
- const settling = settle != null && field.default == null;
10084
+ const settling = settle2 != null && field.default == null;
9530
10085
  labelGroup(list, { commands: settling, titleId, fallbackLabel });
9531
10086
  if (settling) {
9532
10087
  const t2 = contextConfig();
9533
10088
  const mkCommand = (val, label, defaulted) => {
9534
10089
  const button = commandOption(label);
9535
- button.addEventListener("click", () => settle?.(val));
10090
+ button.addEventListener("click", () => settle2?.(val));
9536
10091
  if (defaulted) {
9537
10092
  const title = button.querySelector(".aparte-elic-option-title");
9538
10093
  onRelabel(() => {
@@ -9615,7 +10170,7 @@ function buildStringField(field, onChange, fallbackLabel) {
9615
10170
  focus: () => input.focus()
9616
10171
  };
9617
10172
  }
9618
- function buildField(field, onChange, fallbackLabel, key, settle) {
10173
+ function buildField(field, onChange, fallbackLabel, key, settle2) {
9619
10174
  const custom = contextConfig().getElicitationFieldRenderer()?.(field, { key, notifyChange: onChange });
9620
10175
  if (custom) {
9621
10176
  return {
@@ -9627,9 +10182,9 @@ function buildField(field, onChange, fallbackLabel, key, settle) {
9627
10182
  }
9628
10183
  switch (field.type) {
9629
10184
  case "enum":
9630
- return buildEnumField(field, onChange, fallbackLabel, settle);
10185
+ return buildEnumField(field, onChange, fallbackLabel, settle2);
9631
10186
  case "boolean":
9632
- return buildBooleanField(field, onChange, fallbackLabel, settle);
10187
+ return buildBooleanField(field, onChange, fallbackLabel, settle2);
9633
10188
  // No `settle`: text is written, not chosen, so it always needs a commit.
9634
10189
  case "string":
9635
10190
  return buildStringField(field, onChange, fallbackLabel);
@@ -9654,7 +10209,7 @@ function buildPanel(message, schema, onChange) {
9654
10209
  if (asked2) panel.appendChild(Object.assign(el$1("p", "aparte-elic-message", asked2), { dir: "auto" }));
9655
10210
  let settleCb = null;
9656
10211
  let settled2 = false;
9657
- const settle = (content) => {
10212
+ const settle2 = (content) => {
9658
10213
  if (settled2) return;
9659
10214
  settled2 = true;
9660
10215
  settleCb?.(content);
@@ -9752,7 +10307,7 @@ function buildPanel(message, schema, onChange) {
9752
10307
  };
9753
10308
  }
9754
10309
  const answerOnClick = contextConfig().getElicitationOptions().answerOnClick;
9755
- const field = buildField(schema, onChange, asked2, void 0, answerOnClick ? settle : void 0);
10310
+ const field = buildField(schema, onChange, asked2, void 0, answerOnClick ? settle2 : void 0);
9756
10311
  body.appendChild(field.el);
9757
10312
  return {
9758
10313
  el: panel,
@@ -9775,7 +10330,7 @@ function el(tag, className, text) {
9775
10330
  return node;
9776
10331
  }
9777
10332
  let askSeq = 0;
9778
- function buildApprovalPanel(message, options, onChange, details, allowOther = true) {
10333
+ function buildApprovalPanel(message, options, onChange, details, allowOther = true, preview) {
9779
10334
  const cfg = contextConfig();
9780
10335
  const panel = el("div", "aparte-elic-panel aparte-approval-panel");
9781
10336
  const body = el("div", "aparte-elic-body");
@@ -9794,14 +10349,20 @@ function buildApprovalPanel(message, options, onChange, details, allowOther = tr
9794
10349
  pre.tabIndex = 0;
9795
10350
  body.append(argsLabel, pre);
9796
10351
  }
10352
+ if (preview !== void 0 && preview !== "") {
10353
+ const slot = el("div", "aparte-approval-preview");
10354
+ if (typeof preview === "string") slot.innerHTML = cfg.sanitizeHtml(preview);
10355
+ else slot.appendChild(preview);
10356
+ body.appendChild(slot);
10357
+ }
9797
10358
  const dismiss = el("div", "aparte-elic-dismiss");
9798
10359
  panel.appendChild(dismiss);
9799
- let settle = null;
10360
+ let settle2 = null;
9800
10361
  let done = false;
9801
10362
  const fire = (answer) => {
9802
10363
  if (done) return;
9803
10364
  done = true;
9804
- settle?.(answer);
10365
+ settle2?.(answer);
9805
10366
  };
9806
10367
  const row = el("div", "aparte-approval-options");
9807
10368
  row.setAttribute("role", "group");
@@ -9837,7 +10398,7 @@ function buildApprovalPanel(message, options, onChange, details, allowOther = tr
9837
10398
  el: panel,
9838
10399
  dismiss,
9839
10400
  onSettle: (cb) => {
9840
- settle = cb;
10401
+ settle2 = cb;
9841
10402
  },
9842
10403
  getContent: () => ({ instruction: typed() }),
9843
10404
  isComplete: () => typed().length > 0,
@@ -10112,6 +10673,21 @@ class AparteClient {
10112
10673
  this._isAborted = true;
10113
10674
  this._streamController?.abort();
10114
10675
  }
10676
+ /**
10677
+ * What the call would do, as the tool's display draws it for the approval panel
10678
+ * (`AparteToolDisplay.approvalPreview`), read from the chat's config, the one the row
10679
+ * renders with. `undefined` when the display has none, answers `null`, or throws: the
10680
+ * question then shows the arguments alone.
10681
+ */
10682
+ _approvalPreviewOf(call, target) {
10683
+ const display = resolveConfig(target).getToolDisplay(call.name);
10684
+ try {
10685
+ return display?.approvalPreview?.({ id: call.id, name: call.name, input: call.input }) ?? void 0;
10686
+ } catch (error) {
10687
+ console.warn(`[aparte] The approval preview of "${call.name}" threw; the question shows the arguments alone.`, error);
10688
+ return void 0;
10689
+ }
10690
+ }
10115
10691
  /**
10116
10692
  * Ask the human at the COMPOSER, and report what they decided.
10117
10693
  *
@@ -10133,8 +10709,9 @@ class AparteClient {
10133
10709
  * that wants to answer programmatically registers an `approvalResolver` (headless,
10134
10710
  * no DOM) or its own presenter, both strictly more capable than an id on an event.
10135
10711
  */
10136
- async _askForApproval(event, signal, target) {
10712
+ async _askForApproval(event, signal, target, turn2) {
10137
10713
  const agentName = event.agent?.name?.trim();
10714
+ const preview = this._approvalPreviewOf(event, target);
10138
10715
  const answer = await requestUserInput({
10139
10716
  kind: "approval",
10140
10717
  /*
@@ -10171,7 +10748,11 @@ class AparteClient {
10171
10748
  { value: "deny", label: () => this._config.getLocale().rejectTool ?? "Reject", tone: "deny" }
10172
10749
  ],
10173
10750
  signal,
10174
- target
10751
+ target,
10752
+ ...preview !== void 0 ? { preview } : {},
10753
+ // Which turn asks: a presenter of the app's own files the request under it.
10754
+ messageId: turn2.messageId,
10755
+ ...turn2.conversationId ? { conversationId: turn2.conversationId } : {}
10175
10756
  });
10176
10757
  if (answer.action !== "accept") return { approved: false, by: "person" };
10177
10758
  const content = answer.content;
@@ -10223,6 +10804,11 @@ class AparteClient {
10223
10804
  */
10224
10805
  async _streamTurn(targetElement, messageId, provider, messages, modelId, authConfig, opts) {
10225
10806
  const chatId = this._targetIdOf(targetElement);
10807
+ const turn2 = {
10808
+ ...opts?.conversationId ? { conversationId: opts.conversationId } : {},
10809
+ messageId,
10810
+ ...chatId ? { targetId: chatId } : {}
10811
+ };
10226
10812
  const registeredTools = this._toolsForCurrentModel();
10227
10813
  const buildRequest = async (requestMessages2) => {
10228
10814
  let built = {
@@ -10234,7 +10820,7 @@ class AparteClient {
10234
10820
  ...opts?.meta ? { _meta: opts.meta } : {}
10235
10821
  };
10236
10822
  if (this.options.requestInterceptor) {
10237
- built = await this.options.requestInterceptor(built);
10823
+ built = await this.options.requestInterceptor(built, turn2);
10238
10824
  }
10239
10825
  if (built.toolChoice === "none") {
10240
10826
  const toolPrompts = this._config.resolveToolSystemPrompts(registeredTools);
@@ -10267,7 +10853,7 @@ class AparteClient {
10267
10853
  if (this._streamController !== streamController) this._streamController?.abort();
10268
10854
  this._streamController = streamController;
10269
10855
  this._turnsInFlight.add(messageId);
10270
- this._agentNames.set(messageId, /* @__PURE__ */ new Map());
10856
+ this._agentNames.set(messageId, new Map(opts?.agentNames ?? []));
10271
10857
  const compactor = opts?.rebuild ? resolveConfig(targetElement).getCompactor() ?? this._config.getCompactor() : null;
10272
10858
  const turnIds = () => {
10273
10859
  const path = targetElement.getMessages?.() ?? [];
@@ -10285,11 +10871,11 @@ class AparteClient {
10285
10871
  };
10286
10872
  const isStopped = () => this._isAborted || streamController.signal.aborted;
10287
10873
  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);
10874
+ 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, opts?.userMessage);
10289
10875
  const maxResumes = this.options.maxTurns ?? 10;
10290
10876
  let resumes = 0;
10291
10877
  let approvedAtLastPause = /* @__PURE__ */ new Set();
10292
- const rowEvents = createStreamAdapter({ target: targetElement, config: this._config, messageId, ...chatId ? { targetId: chatId } : {} });
10878
+ const rowEvents = createStreamAdapter({ target: targetElement, config: this._config, messageId, ...chatId ? { targetId: chatId } : {}, ...opts?.conversationId ? { conversationId: opts.conversationId } : {} });
10293
10879
  while (result.suspended) {
10294
10880
  const stopped = this._isAborted || streamController.signal.aborted;
10295
10881
  if (!stopped && ++resumes > maxResumes) {
@@ -10300,7 +10886,7 @@ class AparteClient {
10300
10886
  break;
10301
10887
  }
10302
10888
  const approvedNow = /* @__PURE__ */ new Set();
10303
- const outcomes = stopped ? void 0 : await this._answerDeferred(targetElement, messageId, result.suspended.pending, streamController.signal, rowEvents, approvedAtLastPause, approvedNow);
10889
+ const outcomes = stopped ? void 0 : await this._answerDeferred(targetElement, turn2, result.suspended.pending, streamController.signal, rowEvents, approvedAtLastPause, approvedNow);
10304
10890
  approvedAtLastPause = approvedNow;
10305
10891
  if (!outcomes) {
10306
10892
  this._closeOpenCalls(targetElement, messageId);
@@ -10323,7 +10909,10 @@ class AparteClient {
10323
10909
  { ...baseRequest, messages: messages2 },
10324
10910
  authConfig,
10325
10911
  streamController,
10326
- deferral
10912
+ deferral,
10913
+ void 0,
10914
+ opts?.conversationId,
10915
+ opts?.userMessage
10327
10916
  );
10328
10917
  }
10329
10918
  const usage = result.usage;
@@ -10438,6 +11027,7 @@ class AparteClient {
10438
11027
  console.warn("[AparteClient] aparte-retry — no target found");
10439
11028
  return;
10440
11029
  }
11030
+ const conversationId = openConversationOf(targetElement) ?? void 0;
10441
11031
  const allMessages = targetElement.getMessages?.() ?? [];
10442
11032
  const retryIdx = allMessages.findIndex((m) => m.id === messageId);
10443
11033
  const retryMsg = retryIdx >= 0 ? allMessages[retryIdx] : void 0;
@@ -10458,6 +11048,7 @@ class AparteClient {
10458
11048
  const authConfig = providerId ? await this._resolveAuth(providerId) : void 0;
10459
11049
  const chatMessages = this._messagesToChatMessages(historyMessages);
10460
11050
  const systemMessages = this._systemMessages();
11051
+ const asked2 = [...historyMessages].reverse().find((m) => m.role === "user");
10461
11052
  await this._streamTurn(
10462
11053
  targetElement,
10463
11054
  newMessageId,
@@ -10467,7 +11058,9 @@ class AparteClient {
10467
11058
  authConfig,
10468
11059
  {
10469
11060
  ...provider.retryTemperature !== void 0 ? { temperature: provider.retryTemperature } : {},
10470
- ...this._turnMeta([...historyMessages].reverse().find((m) => m.role === "user")),
11061
+ ...this._turnMeta(asked2),
11062
+ ...conversationId ? { conversationId } : {},
11063
+ ...asked2 ? { userMessage: { content: messageWireText(asked2), messageId: asked2.id } } : {},
10471
11064
  rebuild: async () => [
10472
11065
  ...this._systemMessages(),
10473
11066
  ...mergeAdjacentUserMessages(this._messagesToChatMessages(this._current(targetElement, historyMessages)))
@@ -10504,6 +11097,7 @@ class AparteClient {
10504
11097
  console.warn("[AparteClient] aparte-edit — no target found");
10505
11098
  return;
10506
11099
  }
11100
+ const conversationId = openConversationOf(targetElement) ?? void 0;
10507
11101
  const before = targetElement.getMessages?.().find((m) => m.id === messageId);
10508
11102
  targetElement.updateMessage?.(messageId, {
10509
11103
  content: newContent,
@@ -10544,6 +11138,11 @@ class AparteClient {
10544
11138
  authConfig,
10545
11139
  {
10546
11140
  ...this._turnMeta(editIdx >= 0 ? allMessages[editIdx] : void 0),
11141
+ ...conversationId ? { conversationId } : {},
11142
+ userMessage: {
11143
+ content: editIdx >= 0 ? messageWireText(allMessages[editIdx]) : String(newContent),
11144
+ messageId
11145
+ },
10547
11146
  rebuild: async () => [
10548
11147
  ...this._systemMessages(),
10549
11148
  ...mergeAdjacentUserMessages(this._messagesToChatMessages(this._current(targetElement, historyMessages)))
@@ -10672,14 +11271,7 @@ class AparteClient {
10672
11271
  * through to the next one up rather than answer "no id".
10673
11272
  */
10674
11273
  _targetIdOf(el2) {
10675
- let node = el2 ?? null;
10676
- while (node) {
10677
- const tag = node.tagName?.toLowerCase();
10678
- const isHost = tag === "aparte-chat" || node.hasAttribute?.("data-aparte-chat");
10679
- if (isHost && node.id) return node.id;
10680
- node = node.parentElement;
10681
- }
10682
- return el2?.id || void 0;
11274
+ return chatIdOf(el2) ?? (el2?.id || void 0);
10683
11275
  }
10684
11276
  /**
10685
11277
  * Convert AparteMessage[] to AparteChatMessage[] for re-submission (retry, edit).
@@ -10753,6 +11345,7 @@ class AparteClient {
10753
11345
  console.warn("[AparteClient] ⚠️ No target element found with appendMessage support. Provide a targetResolver in AparteClientOptions or ensure the composer has a `target` attribute.");
10754
11346
  return;
10755
11347
  }
11348
+ const conversationId = openConversationOf(targetElement) ?? void 0;
10756
11349
  this._closeDeferred(targetElement);
10757
11350
  if (this.options.echoUserMessage !== false && event.detail?.echoed !== true) {
10758
11351
  const echoFiles = Array.isArray(event.detail?.files) ? event.detail.files : [];
@@ -10767,6 +11360,8 @@ class AparteClient {
10767
11360
  });
10768
11361
  if (event.detail && typeof event.detail === "object") event.detail.echoed = true;
10769
11362
  }
11363
+ const shown2 = targetElement.getMessages?.().at(-1);
11364
+ const sentId = shown2?.role === "user" ? shown2.id : void 0;
10770
11365
  const messageId = uuid();
10771
11366
  const config = this._config.getModelConfig();
10772
11367
  const providerId = explicitProviderId || config.defaultProvider;
@@ -10823,7 +11418,9 @@ class AparteClient {
10823
11418
  {
10824
11419
  rebuild: async () => this._buildMessages(content, targetElement, fileParts),
10825
11420
  ...rawFiles.length > 0 ? { files: rawFiles } : {},
10826
- ...this._turnMeta(event.detail)
11421
+ ...this._turnMeta(event.detail),
11422
+ ...conversationId ? { conversationId } : {},
11423
+ userMessage: { content: this._userContent(content, fileParts), ...sentId ? { messageId: sentId } : {} }
10827
11424
  }
10828
11425
  );
10829
11426
  }
@@ -10839,19 +11436,18 @@ class AparteClient {
10839
11436
  } else if (typeof historyOption === "function") {
10840
11437
  messages.push(...historyOption(viewportMessages));
10841
11438
  }
10842
- const userMsg = parts && parts.length > 0 ? [{ type: "text", text: userContent }, ...parts] : userContent;
10843
- messages.push({ role: "user", content: userMsg });
11439
+ messages.push({ role: "user", content: this._userContent(userContent, parts) });
10844
11440
  return mergeAdjacentUserMessages(messages);
10845
11441
  }
11442
+ /** The message being sent, as the request carries it: the text, then the files inlined as parts. */
11443
+ _userContent(text, parts) {
11444
+ return parts && parts.length > 0 ? [{ type: "text", text }, ...parts] : text;
11445
+ }
10846
11446
  _toHistoryMessages(path) {
10847
11447
  const { summary, messages } = historyFromCheckpoint(path);
10848
- let cutoff = 0;
10849
- for (let i = 0; i < messages.length; i++) {
10850
- const m = messages[i];
10851
- if (m.role === "assistant" && m.status !== "error" && !isInFlight(m)) {
10852
- cutoff = i + 1;
10853
- }
10854
- }
11448
+ let cutoff = messages.length;
11449
+ while (cutoff > 0 && isInFlight(messages[cutoff - 1])) cutoff--;
11450
+ if (cutoff > 0 && messages[cutoff - 1].role === "user") cutoff--;
10855
11451
  return [...this._summaryMessage(summary), ...wireMessages(messages.slice(0, cutoff))];
10856
11452
  }
10857
11453
  /**
@@ -10933,11 +11529,11 @@ ${content}
10933
11529
  * adapter, or the runner a host injected — after the fetch-level abort bookkeeping.
10934
11530
  */
10935
11531
  /** 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) {
11532
+ async _streamLoop(targetElement, messageId, provider, baseRequest, authConfig, streamController = new AbortController(), deferral, files, conversationId, userMessage) {
10937
11533
  if (this._streamController !== streamController) this._streamController?.abort();
10938
11534
  this._streamController = streamController;
10939
11535
  const runner = this.options.streamRunner ?? runStreamAgent;
10940
- return this._runViaStreamRunner(runner, targetElement, messageId, provider, baseRequest, authConfig, streamController, deferral, files);
11536
+ return this._runViaStreamRunner(runner, targetElement, messageId, provider, baseRequest, authConfig, streamController, deferral, files, conversationId, userMessage);
10941
11537
  }
10942
11538
  /**
10943
11539
  * Run the loop through a {@link AparteStreamRunner} — the engine's by default —
@@ -10948,20 +11544,29 @@ ${content}
10948
11544
  * produces is pinned by the `stream-parity` suite's snapshots, recorded while
10949
11545
  * the inline loop it replaced still ran beside it.
10950
11546
  */
10951
- async _runViaStreamRunner(streamRunner, targetElement, messageId, provider, baseRequest, authConfig, streamController, deferral, files) {
11547
+ async _runViaStreamRunner(streamRunner, targetElement, messageId, provider, baseRequest, authConfig, streamController, deferral, files, conversationId, userMessage) {
10952
11548
  const signal = streamController.signal;
10953
11549
  const chatId = this._targetIdOf(targetElement);
11550
+ const turn2 = {
11551
+ ...conversationId ? { conversationId } : {},
11552
+ messageId,
11553
+ ...chatId ? { targetId: chatId } : {}
11554
+ };
10954
11555
  const adapter = createStreamAdapter({
10955
11556
  target: targetElement,
10956
11557
  config: this._config,
10957
11558
  messageId,
10958
- ...chatId ? { targetId: chatId } : {}
11559
+ ...chatId ? { targetId: chatId } : {},
11560
+ ...conversationId ? { conversationId } : {}
10959
11561
  });
10960
11562
  const prefixSegments = baseRequest._meta?.["prefixSegments"];
10961
11563
  let suspended;
10962
11564
  let finishReason;
10963
11565
  let toolCrash;
10964
11566
  const emitter = (event) => {
11567
+ if (event.type === "run-suspended" && event.agentId == null) {
11568
+ this._keepSubAgentCalls(targetElement, messageId, event.pending, event.ticket);
11569
+ }
10965
11570
  adapter(event);
10966
11571
  if (event.type === "agent-start" && event.name) this._agentNames.get(messageId)?.set(event.agentId, event.name);
10967
11572
  if (event.agentId != null) return;
@@ -10982,7 +11587,13 @@ ${content}
10982
11587
  const toolLookup = (name) => {
10983
11588
  const handler = this._config.getToolHandler(name);
10984
11589
  if (!handler) return void 0;
10985
- const context = { target: targetElement, config: this._config };
11590
+ const context = {
11591
+ target: targetElement,
11592
+ config: this._config,
11593
+ // The same id a server tool is handed (`createAparteAgentHandler`), so a
11594
+ // handler behaves the same whichever loop runs it.
11595
+ ...conversationId ? { conversationId } : {}
11596
+ };
10986
11597
  return (call, sig, run) => handler(call, sig, run ? { ...context, run } : context);
10987
11598
  };
10988
11599
  const hostOwnsDecision = Boolean(this.options.approvalResolver);
@@ -10993,12 +11604,12 @@ ${content}
10993
11604
  maxTurns: tool.maxTurns,
10994
11605
  parallel: tool.parallel,
10995
11606
  needsApproval: hostOwnsDecision ? tool.needsApproval : (call) => {
10996
- const verdict = this._config.ruleOnToolCall(call).verdict;
11607
+ const verdict = this._config.ruleOnToolCall(call, turn2).verdict;
10997
11608
  return verdict === "allow" ? false : verdict;
10998
11609
  }
10999
11610
  };
11000
11611
  };
11001
- const approvalResolver = this._approvalResolverFor(targetElement);
11612
+ const approvalResolver = this._approvalResolverFor(targetElement, turn2);
11002
11613
  const asToolCrash = (error) => {
11003
11614
  if (toolCrash === void 0 || error instanceof AparteError) return error;
11004
11615
  const text = error instanceof Error ? error.message || error.name : typeof error === "string" ? error : String(error);
@@ -11009,6 +11620,8 @@ ${content}
11009
11620
  ...provider.id ? { providerId: provider.id } : {},
11010
11621
  ...deferral ? { deferral } : {},
11011
11622
  ...files && files.length > 0 ? { files } : {},
11623
+ ...conversationId ? { conversationId } : {},
11624
+ ...userMessage ? { userMessage } : {},
11012
11625
  baseRequest,
11013
11626
  transportCall,
11014
11627
  toolLookup,
@@ -11045,14 +11658,16 @@ ${content}
11045
11658
  * the tool's `needsApproval` — reads a tool the page does not have, and said
11046
11659
  * "allow": the page approved, silently, what the server wanted a person to decide.
11047
11660
  */
11048
- _approvalResolverFor(targetElement, gatedElsewhere = false) {
11049
- return this.options.approvalResolver ?? (async (call, sig) => {
11050
- const ruling = gatedElsewhere ? this._config.getApprovalPolicy()?.(call, this._config.getTools().find((t) => t.name === call.name)) ?? { verdict: "ask" } : this._config.ruleOnToolCall(call);
11661
+ _approvalResolverFor(targetElement, turn2, gatedElsewhere = false) {
11662
+ const host2 = this.options.approvalResolver;
11663
+ if (host2) return (call, sig) => host2(call, sig, turn2);
11664
+ return (async (call, sig) => {
11665
+ const ruling = gatedElsewhere ? this._config.getApprovalPolicy()?.(call, this._config.getTools().find((t) => t.name === call.name), turn2) ?? { verdict: "ask" } : this._config.ruleOnToolCall(call, turn2);
11051
11666
  if (ruling.verdict === "allow") return { approved: true };
11052
11667
  if (ruling.verdict === "deny") {
11053
11668
  return { approved: false, reason: ruling.reason?.trim() || "Tool execution was refused by the approval policy.", by: "policy" };
11054
11669
  }
11055
- return this._askForApproval(call, sig, targetElement);
11670
+ return this._askForApproval(call, sig, targetElement, turn2);
11056
11671
  });
11057
11672
  }
11058
11673
  /**
@@ -11063,9 +11678,10 @@ ${content}
11063
11678
  * nobody answered — the turn was stopped, or the channel gave up — and there is no
11064
11679
  * resume. A channel that CRASHES fails the turn, as it does for a run in the page.
11065
11680
  */
11066
- async _answerDeferred(targetElement, messageId, pending2, signal, rowEvents, approvedBefore = /* @__PURE__ */ new Set(), approvedNow = /* @__PURE__ */ new Set()) {
11681
+ async _answerDeferred(targetElement, turn2, pending2, signal, rowEvents, approvedBefore = /* @__PURE__ */ new Set(), approvedNow = /* @__PURE__ */ new Set()) {
11067
11682
  const outcomes = {};
11068
- const resolver = this._approvalResolverFor(targetElement, true);
11683
+ const { messageId } = turn2;
11684
+ const resolver = this._approvalResolverFor(targetElement, turn2, true);
11069
11685
  const refuseTheRest = (after) => {
11070
11686
  for (const rest of pending2.slice(after + 1)) {
11071
11687
  outcomes[rest.toolCallId] = { kind: "decision", approved: false, reason: NOT_RUN_AFTER_A_REFUSAL, by: "earlier-refusal" };
@@ -11095,7 +11711,7 @@ ${content}
11095
11711
  const key = approvalKey(call);
11096
11712
  if (!approvedBefore.has(key) && !approvedNow.has(key)) {
11097
11713
  try {
11098
- gate = await this._gateBrowserTool(asked2, signal, targetElement, rowEvents);
11714
+ gate = await this._gateBrowserTool(asked2, signal, targetElement, turn2, rowEvents);
11099
11715
  } catch (error) {
11100
11716
  if (!signal.aborted && error?.name !== "AbortError") throw error;
11101
11717
  gate = void 0;
@@ -11112,7 +11728,11 @@ ${content}
11112
11728
  const handler = this._config.getToolHandler(p.name);
11113
11729
  try {
11114
11730
  if (!handler) throw new Error(`No browser handler is registered for "${p.name}".`);
11115
- const result = await handler(ran, signal, { target: targetElement, config: this._config });
11731
+ const result = await handler(ran, signal, {
11732
+ target: targetElement,
11733
+ config: this._config,
11734
+ ...turn2.conversationId ? { conversationId: turn2.conversationId } : {}
11735
+ });
11116
11736
  outcomes[p.toolCallId] = {
11117
11737
  kind: "result",
11118
11738
  content: result.content,
@@ -11133,8 +11753,8 @@ ${content}
11133
11753
  * rule (`ruleOnToolCall`) and the default channel asks. `null` when nothing gates the
11134
11754
  * call, the decision when something did, `undefined` when nobody answered.
11135
11755
  */
11136
- async _gateBrowserTool(call, signal, targetElement, rowEvents) {
11137
- const ruling = this.options.approvalResolver ? this._config.getTools().find((t) => t.name === call.name)?.needsApproval ? "ask" : "allow" : this._config.ruleOnToolCall(call).verdict;
11756
+ async _gateBrowserTool(call, signal, targetElement, turn2, rowEvents) {
11757
+ const ruling = this.options.approvalResolver ? this._config.getTools().find((t) => t.name === call.name)?.needsApproval ? "ask" : "allow" : this._config.ruleOnToolCall(call, turn2).verdict;
11138
11758
  if (ruling === "allow") return null;
11139
11759
  if (ruling === "ask") {
11140
11760
  rowEvents?.({
@@ -11145,7 +11765,7 @@ ${content}
11145
11765
  ...call.agent ? { agentId: call.agent.id } : {}
11146
11766
  });
11147
11767
  }
11148
- const decision = await this._approvalResolverFor(targetElement)(call, signal) ?? void 0;
11768
+ const decision = await this._approvalResolverFor(targetElement, turn2)(call, signal) ?? void 0;
11149
11769
  if (decision?.approved && ruling === "ask") {
11150
11770
  if (call.agent) rowEvents?.({ type: "tool-approved", toolCallId: call.id, agentId: call.agent.id });
11151
11771
  else targetElement.updateSegment?.(`tool-${call.id}`, { status: "pending" });
@@ -11159,16 +11779,49 @@ ${content}
11159
11779
  * history that resumes them is built first; a new pause marks what still waits.
11160
11780
  */
11161
11781
  _spendPause(targetElement, messageId) {
11162
- const segments = targetElement.getMessage?.(messageId)?.segments ?? targetElement.getMessages?.()?.find((m) => m.id === messageId)?.segments;
11782
+ const message = this._messageOf(targetElement, messageId);
11783
+ const segments = message?.segments;
11163
11784
  const paused = (segment) => segment.type === "tool_call" && Boolean(segment.deferred);
11164
- if (!segments?.some(paused)) return;
11785
+ const rows = Boolean(segments?.some(paused));
11786
+ if (!rows && !message?.deferredCalls?.length) return;
11165
11787
  targetElement.updateMessage?.(messageId, {
11166
- segments: segments.map((segment) => {
11167
- if (!paused(segment)) return segment;
11168
- const { deferred: _spent, ...rest } = segment;
11169
- return rest;
11170
- })
11788
+ ...rows ? {
11789
+ segments: segments.map((segment) => {
11790
+ if (!paused(segment)) return segment;
11791
+ const { deferred: _spent, ...rest } = segment;
11792
+ return rest;
11793
+ })
11794
+ } : {},
11795
+ // A sub-agent's paused calls go with the rows': the server answers them now.
11796
+ ...message?.deferredCalls?.length ? { deferredCalls: void 0 } : {}
11797
+ });
11798
+ }
11799
+ /** A reply by its id, tree-wide first: a retry during the wait moves the path. */
11800
+ _messageOf(targetElement, messageId) {
11801
+ return targetElement.getMessage?.(messageId) ?? targetElement.getMessages?.()?.find((m) => m.id === messageId);
11802
+ }
11803
+ /**
11804
+ * Keep on the reply the calls a paused run left that no row of the reply holds: a
11805
+ * sub-agent's, which its line draws. The rows of the reply carry their own pause
11806
+ * (`deferred`); these would otherwise be in nothing the conversation saves, and a reload
11807
+ * would find no pause to resume. Each keeps the name its sub-agent was announced with,
11808
+ * which a reload has no other way to know.
11809
+ */
11810
+ _keepSubAgentCalls(targetElement, messageId, pending2, ticket) {
11811
+ const names = this._agentNames.get(messageId);
11812
+ const kept = pending2.filter((p) => p.agentId != null).map((p) => {
11813
+ const agentName = names?.get(p.agentId);
11814
+ return {
11815
+ toolCallId: p.toolCallId,
11816
+ name: p.name,
11817
+ input: p.input ?? {},
11818
+ reason: p.reason,
11819
+ agentId: p.agentId,
11820
+ ...agentName ? { agentName } : {},
11821
+ ...typeof ticket === "string" ? { ticket } : {}
11822
+ };
11171
11823
  });
11824
+ if (kept.length > 0) targetElement.updateMessage?.(messageId, { deferredCalls: kept });
11172
11825
  }
11173
11826
  /**
11174
11827
  * Close the reply's calls that can no longer finish — paused, queued, or running on a
@@ -11179,15 +11832,21 @@ ${content}
11179
11832
  * the wait moves the head. A run in the page ends every call itself: nothing to do.
11180
11833
  */
11181
11834
  _closeOpenCalls(targetElement, messageId) {
11182
- const segments = targetElement.getMessage?.(messageId)?.segments ?? targetElement.getMessages?.()?.find((m) => m.id === messageId)?.segments;
11835
+ const message = this._messageOf(targetElement, messageId);
11836
+ const segments = message?.segments;
11183
11837
  const unfinished = (segment) => segment.type === "tool_call" && (segment.status === "pending" || segment.status === "awaiting-approval");
11184
- if (!segments?.some(unfinished)) return;
11838
+ const rows = Boolean(segments?.some(unfinished));
11839
+ if (!rows && !message?.deferredCalls?.length) return;
11185
11840
  targetElement.updateMessage?.(messageId, {
11186
- segments: segments.map((segment) => {
11187
- if (!unfinished(segment)) return segment;
11188
- const { deferred: _spent, ...rest } = segment;
11189
- return { ...rest, status: "aborted" };
11190
- })
11841
+ ...rows ? {
11842
+ segments: segments.map((segment) => {
11843
+ if (!unfinished(segment)) return segment;
11844
+ const { deferred: _spent, ...rest } = segment;
11845
+ return { ...rest, status: "aborted" };
11846
+ })
11847
+ } : {},
11848
+ // A sub-agent's paused calls end with the rows: nothing will answer them now.
11849
+ ...message?.deferredCalls?.length ? { deferredCalls: void 0 } : {}
11191
11850
  });
11192
11851
  }
11193
11852
  /**
@@ -11226,13 +11885,19 @@ ${content}
11226
11885
  _closeDeferred(targetElement) {
11227
11886
  const messages = targetElement.getMessages?.() ?? [];
11228
11887
  const last = [...messages].reverse().find((m) => m.role === "assistant");
11229
- if (!last?.segments?.some(isOpenDeferred)) return;
11230
- const segments = last.segments.map((segment) => {
11231
- if (!isOpenDeferred(segment)) return segment;
11232
- const { deferred: _closed, ...rest } = segment;
11233
- return { ...rest, status: "aborted" };
11888
+ const rows = Boolean(last?.segments?.some(isOpenDeferred));
11889
+ if (!last || !rows && !last.deferredCalls?.length) return;
11890
+ targetElement.updateMessage?.(last.id, {
11891
+ ...rows ? {
11892
+ segments: last.segments.map((segment) => {
11893
+ if (!isOpenDeferred(segment)) return segment;
11894
+ const { deferred: _closed, ...rest } = segment;
11895
+ return { ...rest, status: "aborted" };
11896
+ })
11897
+ } : {},
11898
+ // A sub-agent's wait is closed with them: no row answers it on the wire.
11899
+ ...last.deferredCalls?.length ? { deferredCalls: void 0 } : {}
11234
11900
  });
11235
- targetElement.updateMessage?.(last.id, { segments });
11236
11901
  }
11237
11902
  /**
11238
11903
  * Answer a turn a server loop paused, when the conversation comes back — a reload, a
@@ -11254,8 +11919,9 @@ ${content}
11254
11919
  const messages = targetElement.getMessages?.() ?? [];
11255
11920
  const last = [...messages].reverse().find((m) => m.role === "assistant");
11256
11921
  const open = (last?.segments ?? []).filter(isOpenDeferred);
11257
- const ticket = open.find((s) => s.deferred?.ticket)?.deferred?.ticket;
11258
- if (!last || open.length === 0 || !ticket || this._resuming.has(last.id) || this._turnsInFlight.has(last.id)) return false;
11922
+ const kept = last?.deferredCalls ?? [];
11923
+ const ticket = open.find((s) => s.deferred?.ticket)?.deferred?.ticket ?? kept.find((c) => c.ticket)?.ticket;
11924
+ if (!last || open.length + kept.length === 0 || !ticket || this._resuming.has(last.id) || this._turnsInFlight.has(last.id)) return false;
11259
11925
  const config = this._config.getModelConfig();
11260
11926
  const recorded = last.model && this._config.getAIProvider(last.model.providerId) ? last.model : void 0;
11261
11927
  const providerId = recorded?.providerId ?? config.defaultProvider;
@@ -11265,15 +11931,27 @@ ${content}
11265
11931
  return false;
11266
11932
  }
11267
11933
  this._beginUserTurn();
11934
+ const conversationId = openConversationOf(targetElement) ?? void 0;
11268
11935
  this._resuming.add(last.id);
11269
11936
  try {
11270
11937
  const authConfig = provider.id ? await this._resolveAuth(provider.id) : void 0;
11271
- const pending2 = open.map((s) => ({
11272
- toolCallId: s.toolCall.id,
11273
- name: s.toolCall.name,
11274
- input: s.toolCall.input,
11275
- reason: s.deferred.reason
11276
- }));
11938
+ const pending2 = [
11939
+ ...open.map((s) => ({
11940
+ toolCallId: s.toolCall.id,
11941
+ name: s.toolCall.name,
11942
+ input: s.toolCall.input,
11943
+ reason: s.deferred.reason
11944
+ })),
11945
+ // Asked under their sub-agent, by the name it was announced with.
11946
+ ...kept.map((c) => ({
11947
+ toolCallId: c.toolCallId,
11948
+ name: c.name,
11949
+ input: c.input,
11950
+ reason: c.reason,
11951
+ ...c.agentId !== void 0 ? { agentId: c.agentId } : {}
11952
+ }))
11953
+ ];
11954
+ const agentNames = new Map(kept.flatMap((c) => c.agentId !== void 0 && c.agentName ? [[c.agentId, c.agentName]] : []));
11277
11955
  const base = this._resumeBase(messages, messages.indexOf(last));
11278
11956
  await this._streamTurn(targetElement, last.id, provider, base, recorded?.modelId ?? config.defaultModel ?? "", authConfig, {
11279
11957
  resume: { pending: pending2, ticket },
@@ -11282,7 +11960,9 @@ ${content}
11282
11960
  const at = now.findIndex((m) => m.id === last.id);
11283
11961
  return at >= 0 ? this._resumeBase(now, at) : base;
11284
11962
  },
11285
- ...recorded?.temperature !== void 0 ? { temperature: recorded.temperature } : {}
11963
+ ...recorded?.temperature !== void 0 ? { temperature: recorded.temperature } : {},
11964
+ ...conversationId ? { conversationId } : {},
11965
+ ...agentNames.size > 0 ? { agentNames } : {}
11286
11966
  });
11287
11967
  } finally {
11288
11968
  this._resuming.delete(last.id);
@@ -11334,6 +12014,7 @@ const RUN_LEVEL = /* @__PURE__ */ new Set(["run-start", "run-done", "run-aborted
11334
12014
  function createAgentStreamRunner(options) {
11335
12015
  let warnedAttributedEnd = false;
11336
12016
  return async (opts) => {
12017
+ const endpoint = typeof options.endpoint === "function" ? options.endpoint(opts) : options.endpoint;
11337
12018
  const doFetch = options.fetch ?? fetch;
11338
12019
  const headers = typeof options.headers === "function" ? await options.headers() : options.headers ?? {};
11339
12020
  const { tools, ...request } = opts.baseRequest;
@@ -11341,11 +12022,12 @@ function createAgentStreamRunner(options) {
11341
12022
  v: 1,
11342
12023
  ...opts.providerId ? { providerId: opts.providerId } : {},
11343
12024
  messageId: opts.messageId,
12025
+ ...opts.conversationId ? { conversationId: opts.conversationId } : {},
11344
12026
  request,
11345
12027
  clientTools: tools ?? [],
11346
12028
  ...opts.deferral?.token ? { resume: { ticket: opts.deferral.token, outcomes: opts.deferral.outcomes ?? {} } } : {}
11347
12029
  };
11348
- const response = await doFetch(options.endpoint, {
12030
+ const response = await doFetch(endpoint, {
11349
12031
  method: "POST",
11350
12032
  headers: jsonHeaders(headers),
11351
12033
  body: JSON.stringify(body),
@@ -11721,26 +12403,34 @@ const APARTE_DEFAULT_UI_EVENTS = [
11721
12403
  "aparte-message-resumed",
11722
12404
  "aparte-tool-approval-request"
11723
12405
  ];
12406
+ const written = /* @__PURE__ */ new WeakMap();
12407
+ function writeOnce(el2, key, value, write) {
12408
+ let last = written.get(el2);
12409
+ if (!last) written.set(el2, last = /* @__PURE__ */ new Map());
12410
+ if (last.has(key) && last.get(key) === value) return;
12411
+ last.set(key, value);
12412
+ write();
12413
+ }
11724
12414
  function applyElementProps(el2, props, transformValue = (value) => value) {
11725
12415
  for (const [key, value] of Object.entries(props)) {
11726
12416
  if (key.startsWith("--")) {
11727
- if (value === null || value === void 0) el2.style.removeProperty(key);
11728
- else if (typeof value === "object" || typeof value === "function") el2.style.removeProperty(key);
11729
- else el2.style.setProperty(key, String(value));
12417
+ if (value === null || value === void 0) writeOnce(el2, key, null, () => el2.style.removeProperty(key));
12418
+ else if (typeof value === "object" || typeof value === "function") writeOnce(el2, key, null, () => el2.style.removeProperty(key));
12419
+ else writeOnce(el2, key, String(value), () => el2.style.setProperty(key, String(value)));
11730
12420
  } else if (key.toLowerCase().startsWith("on")) {
11731
12421
  el2.removeAttribute(key);
11732
12422
  } else if (value === false && isDefaultOn(el2, key)) {
11733
- el2.setAttribute(key, "false");
12423
+ writeOnce(el2, key, "false", () => el2.setAttribute(key, "false"));
11734
12424
  } else if (value === null || value === void 0 || value === false) {
11735
- el2.removeAttribute(key);
12425
+ writeOnce(el2, key, null, () => el2.removeAttribute(key));
11736
12426
  } else if (typeof value === "number" && Number.isNaN(value)) {
11737
- el2.removeAttribute(key);
12427
+ writeOnce(el2, key, null, () => el2.removeAttribute(key));
11738
12428
  } else if (value === true) {
11739
- el2.setAttribute(key, "");
12429
+ writeOnce(el2, key, "", () => el2.setAttribute(key, ""));
11740
12430
  } else if (typeof value === "object" || typeof value === "function") {
11741
12431
  el2[key] = transformValue(value);
11742
12432
  } else {
11743
- el2.setAttribute(key, String(value));
12433
+ writeOnce(el2, key, String(value), () => el2.setAttribute(key, String(value)));
11744
12434
  }
11745
12435
  }
11746
12436
  }
@@ -11947,95 +12637,97 @@ function deferHydrationOf(ctor) {
11947
12637
  };
11948
12638
  }
11949
12639
  export {
11950
- isFormatAdapter as $,
12640
+ installDialogTriggersOnce as $,
11951
12641
  APARTE_CONFIG_CHANGE as A,
11952
- contextConfig as B,
11953
- copyText as C,
11954
- createAgentStreamRunner as D,
11955
- createAparteAgentHandler as E,
11956
- createAparteChatHandler as F,
11957
- createSegmentList as G,
11958
- createStreamAdapter as H,
11959
- declineDefaultRenderers as I,
11960
- defaultSanitizer as J,
11961
- deferHydrationOf as K,
11962
- defineMountedSegmentRenderer as L,
11963
- defineMountedToolRenderer as M,
11964
- detachConfig as N,
11965
- escapeAttr as O,
11966
- escapeHtml as P,
11967
- estimateTokens as Q,
11968
- estimateWireTokens as R,
12642
+ contentToText as B,
12643
+ contextConfig as C,
12644
+ copyText as D,
12645
+ createAgentStreamRunner as E,
12646
+ createAparteAgentHandler as F,
12647
+ createAparteChatHandler as G,
12648
+ createSegmentList as H,
12649
+ createStreamAdapter as I,
12650
+ declineDefaultRenderers as J,
12651
+ defaultSanitizer as K,
12652
+ deferHydrationOf as L,
12653
+ defineMountedSegmentRenderer as M,
12654
+ defineMountedToolRenderer as N,
12655
+ detachConfig as O,
12656
+ dispatchChatEvent as P,
12657
+ escapeAttr as Q,
12658
+ escapeHtml as R,
11969
12659
  SUGGESTIONS_BLOCK_LANGUAGE as S,
11970
- filesToAttachments as T,
11971
- formatDuration as U,
11972
- getAllRenderers as V,
11973
- getSegmentRenderer as W,
11974
- historyFromCheckpoint as X,
11975
- installDefaultRenderersOnce as Y,
11976
- installDialogTriggersOnce as Z,
11977
- isAwaitingReply as _,
12660
+ estimateTokens as T,
12661
+ estimateWireTokens as U,
12662
+ filesToAttachments as V,
12663
+ formatDuration as W,
12664
+ getAllRenderers as X,
12665
+ getSegmentRenderer as Y,
12666
+ historyFromCheckpoint as Z,
12667
+ installDefaultRenderersOnce as _,
11978
12668
  APARTE_CONVERSATION_SCHEMA_VERSION as a,
11979
- isSafeUrl as a0,
11980
- isSegmentSettled as a1,
11981
- measureContext as a2,
11982
- onRenderersChange as a3,
11983
- overrideSegmentRenderer as a4,
11984
- parseAparteEventStream as a5,
11985
- parseMarkdownToSegments as a6,
11986
- pluralize as a7,
11987
- populateBubbleFromMessage as a8,
11988
- readableToAsyncIterable as a9,
11989
- renderingVersionOf as aA,
11990
- renderSourceList as aB,
11991
- mergeSegmentUpdate as aC,
11992
- toolNameOf as aD,
11993
- writeStreamedMarkdown as aE,
11994
- replaceHighlighted as aF,
11995
- toolRendererThatDrew as aG,
11996
- activityRendererThatDrew as aH,
11997
- CheckpointStateWatcher as aI,
11998
- chatIdOf as aJ,
11999
- stampSegmentActivity as aK,
12000
- stampSegmentOnInsert as aL,
12001
- stampSegmentOnUpdate as aM,
12002
- renumberSegments as aN,
12003
- openSegmentIds as aO,
12004
- isTerminalStatus as aP,
12005
- adoptMessageSegments as aQ,
12006
- APARTE_DERIVED_SEGMENTS as aR,
12007
- rememberConversationStatus as aS,
12008
- tellConversationStatus as aT,
12009
- conversationStatusOf as aU,
12010
- visibleReply as aV,
12011
- usageTokens as aW,
12012
- inRenderedContent as aX,
12013
- registerDefaultRenderers as aa,
12014
- registerSegmentRenderer as ab,
12015
- releaseDeferredHydration as ac,
12016
- renderCitations as ad,
12017
- renderCodeLanguages as ae,
12018
- requestUserInput as af,
12019
- resolveConfig as ag,
12020
- revokeAttachmentUrls as ah,
12021
- runSubAgent as ai,
12022
- runWithConfig as aj,
12023
- segmentDuration as ak,
12024
- segmentTiming as al,
12025
- setupSuggestionBlocks as am,
12026
- startSubAgent as an,
12027
- subscribeConfigChange as ao,
12028
- toToolCallView as ap,
12029
- toolRefusal as aq,
12030
- unregisterSegmentRenderer as ar,
12031
- uuid as as,
12032
- gateGlide as at,
12033
- chatBoundaryOf as au,
12034
- relabelCodeLanguages as av,
12035
- relabelCitations as aw,
12036
- toolCallRenderer as ax,
12037
- activityRenderer as ay,
12038
- isMountedRenderer as az,
12669
+ isAwaitingReply as a0,
12670
+ isFormatAdapter as a1,
12671
+ isSafeUrl as a2,
12672
+ isSegmentSettled as a3,
12673
+ measureContext as a4,
12674
+ onRenderersChange as a5,
12675
+ overrideSegmentRenderer as a6,
12676
+ parseAparteEventStream as a7,
12677
+ parseMarkdownToSegments as a8,
12678
+ pluralize as a9,
12679
+ toolCallRenderer as aA,
12680
+ activityRenderer as aB,
12681
+ isMountedRenderer as aC,
12682
+ renderingVersionOf as aD,
12683
+ renderSourceList as aE,
12684
+ mergeSegmentUpdate as aF,
12685
+ toolNameOf as aG,
12686
+ writeStreamedMarkdown as aH,
12687
+ replaceHighlighted as aI,
12688
+ toolRendererThatDrew as aJ,
12689
+ activityRendererThatDrew as aK,
12690
+ CheckpointStateWatcher as aL,
12691
+ stampSegmentActivity as aM,
12692
+ stampSegmentOnInsert as aN,
12693
+ stampSegmentOnUpdate as aO,
12694
+ renumberSegments as aP,
12695
+ openSegmentIds as aQ,
12696
+ isTerminalStatus as aR,
12697
+ adoptMessageSegments as aS,
12698
+ APARTE_DERIVED_SEGMENTS as aT,
12699
+ rememberConversationStatus as aU,
12700
+ tellConversationStatus as aV,
12701
+ conversationStatusOf as aW,
12702
+ visibleReply as aX,
12703
+ usageTokens as aY,
12704
+ inRenderedContent as aZ,
12705
+ populateBubbleFromMessage as aa,
12706
+ readableToAsyncIterable as ab,
12707
+ registerDefaultRenderers as ac,
12708
+ registerSegmentRenderer as ad,
12709
+ releaseDeferredHydration as ae,
12710
+ renderCitations as af,
12711
+ renderCodeLanguages as ag,
12712
+ requestUserInput as ah,
12713
+ resolveConfig as ai,
12714
+ revokeAttachmentUrls as aj,
12715
+ runSubAgent as ak,
12716
+ runWithConfig as al,
12717
+ segmentDuration as am,
12718
+ segmentTiming as an,
12719
+ setupSuggestionBlocks as ao,
12720
+ startSubAgent as ap,
12721
+ subscribeConfigChange as aq,
12722
+ toToolCallView as ar,
12723
+ toolRefusal as as,
12724
+ unregisterSegmentRenderer as at,
12725
+ uuid as au,
12726
+ withoutAbandonedTurns as av,
12727
+ gateGlide as aw,
12728
+ chatBoundaryOf as ax,
12729
+ relabelCodeLanguages as ay,
12730
+ relabelCitations as az,
12039
12731
  APARTE_DEFAULT_BUBBLE_ACTIONS as b,
12040
12732
  APARTE_DEFAULT_HOST_HANDLERS as c,
12041
12733
  APARTE_DEFAULT_ICON_FALLBACKS as d,
@@ -12059,7 +12751,7 @@ export {
12059
12751
  attachConfig as v,
12060
12752
  buildApprovalPanel as w,
12061
12753
  buildElicitationPanel as x,
12062
- collectRendererStyles as y,
12063
- contentToText as z
12754
+ chatIdOf as y,
12755
+ collectRendererStyles as z
12064
12756
  };
12065
- //# sourceMappingURL=defer-hydration-BE2ToXC_.js.map
12757
+ //# sourceMappingURL=defer-hydration-OFqdbk3O.js.map