@aparte/core 1.9.0 → 1.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/dist/client/aparte-client.d.ts +48 -11
  2. package/dist/client/aparte-client.d.ts.map +1 -1
  3. package/dist/client/stream-adapter.d.ts +5 -0
  4. package/dist/client/stream-adapter.d.ts.map +1 -1
  5. package/dist/client/wire-history.d.ts +21 -1
  6. package/dist/client/wire-history.d.ts.map +1 -1
  7. package/dist/components/bubble/aparte-chat-bubble.d.ts.map +1 -1
  8. package/dist/components/composer/aparte-composer-action.d.ts +2 -1
  9. package/dist/components/composer/aparte-composer-action.d.ts.map +1 -1
  10. package/dist/components/composer/aparte-composer-add-attachment.d.ts.map +1 -1
  11. package/dist/components/composer/aparte-composer-attachments.d.ts.map +1 -1
  12. package/dist/components/composer/aparte-composer-input.d.ts.map +1 -1
  13. package/dist/components/composer/aparte-composer.d.ts +2 -1
  14. package/dist/components/composer/aparte-composer.d.ts.map +1 -1
  15. package/dist/components/context/aparte-context.d.ts +1 -1
  16. package/dist/components/context/aparte-context.d.ts.map +1 -1
  17. package/dist/components/conversation-list/aparte-conversation-list.d.ts +49 -2
  18. package/dist/components/conversation-list/aparte-conversation-list.d.ts.map +1 -1
  19. package/dist/components/conversation-list/index.d.ts +1 -1
  20. package/dist/components/conversation-list/index.d.ts.map +1 -1
  21. package/dist/components/elicitation/aparte-elicitation.d.ts.map +1 -1
  22. package/dist/components/index.d.ts +1 -1
  23. package/dist/components/index.d.ts.map +1 -1
  24. package/dist/components/launcher/aparte-launcher.d.ts.map +1 -1
  25. package/dist/components/scroll-rail/aparte-scroll-rail.d.ts +1 -1
  26. package/dist/components/scroll-rail/aparte-scroll-rail.d.ts.map +1 -1
  27. package/dist/components/sidebar/aparte-sidebar.d.ts +14 -1
  28. package/dist/components/sidebar/aparte-sidebar.d.ts.map +1 -1
  29. package/dist/components/split/aparte-split.d.ts +1 -1
  30. package/dist/components/split/aparte-split.d.ts.map +1 -1
  31. package/dist/components/suggestions/aparte-suggestions.d.ts +3 -2
  32. package/dist/components/suggestions/aparte-suggestions.d.ts.map +1 -1
  33. package/dist/components/viewport/aparte-chat-viewport.d.ts +3 -0
  34. package/dist/components/viewport/aparte-chat-viewport.d.ts.map +1 -1
  35. package/dist/config/aparte-config.d.ts +24 -3
  36. package/dist/config/aparte-config.d.ts.map +1 -1
  37. package/dist/context/checkpoint-state.d.ts +0 -7
  38. package/dist/context/checkpoint-state.d.ts.map +1 -1
  39. package/dist/context/measure.d.ts +3 -1
  40. package/dist/context/measure.d.ts.map +1 -1
  41. package/dist/conversations/conversation-controller.d.ts +48 -6
  42. package/dist/conversations/conversation-controller.d.ts.map +1 -1
  43. package/dist/custom-elements.json +1474 -592
  44. package/dist/{defer-hydration-Ch3TOEJC.js → defer-hydration-OFqdbk3O.js} +647 -248
  45. package/dist/defer-hydration-OFqdbk3O.js.map +1 -0
  46. package/dist/elicitation/approval-panel.d.ts +1 -1
  47. package/dist/elicitation/approval-panel.d.ts.map +1 -1
  48. package/dist/elicitation/option-keys.d.ts +26 -0
  49. package/dist/elicitation/option-keys.d.ts.map +1 -0
  50. package/dist/elicitation/types.d.ts +16 -0
  51. package/dist/elicitation/types.d.ts.map +1 -1
  52. package/dist/generated/element-attributes.d.ts +2 -2
  53. package/dist/generated/element-attributes.d.ts.map +1 -1
  54. package/dist/{glyphs-LolG04CC.js → glyphs-BgKFtByg.js} +10 -10
  55. package/dist/{glyphs-LolG04CC.js.map → glyphs-BgKFtByg.js.map} +1 -1
  56. package/dist/host/aparte-chat-host.d.ts +42 -1
  57. package/dist/host/aparte-chat-host.d.ts.map +1 -1
  58. package/dist/icons/extended.d.ts +9 -0
  59. package/dist/icons/extended.d.ts.map +1 -1
  60. package/dist/icons.js +20 -11
  61. package/dist/icons.js.map +1 -1
  62. package/dist/index.css +1 -1
  63. package/dist/index.d.ts +8 -2
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +271 -190
  66. package/dist/index.js.map +1 -1
  67. package/dist/index.node.d.ts +7 -2
  68. package/dist/index.node.d.ts.map +1 -1
  69. package/dist/index.node.js +61 -58
  70. package/dist/index.node.js.map +1 -1
  71. package/dist/interop/chat-events.d.ts +64 -0
  72. package/dist/interop/chat-events.d.ts.map +1 -0
  73. package/dist/interop/element-props.d.ts +6 -0
  74. package/dist/interop/element-props.d.ts.map +1 -1
  75. package/dist/interop/element-spec.d.ts +85 -0
  76. package/dist/interop/element-spec.d.ts.map +1 -0
  77. package/dist/primitives/progress-spinner/aparte-progress-spinner.d.ts +1 -1
  78. package/dist/primitives/progress-spinner/aparte-progress-spinner.d.ts.map +1 -1
  79. package/dist/primitives/select/aparte-option.d.ts +1 -1
  80. package/dist/primitives/select/aparte-option.d.ts.map +1 -1
  81. package/dist/primitives/select/aparte-select.d.ts.map +1 -1
  82. package/dist/renderers/citations.d.ts.map +1 -1
  83. package/dist/transport/agent-handler.d.ts +8 -4
  84. package/dist/transport/agent-handler.d.ts.map +1 -1
  85. package/dist/types/events.d.ts +11 -10
  86. package/dist/types/events.d.ts.map +1 -1
  87. package/dist/types/imperative-api.d.ts +11 -0
  88. package/dist/types/imperative-api.d.ts.map +1 -1
  89. package/dist/types/index.d.ts +1 -1
  90. package/dist/types/index.d.ts.map +1 -1
  91. package/dist/types/models.d.ts +26 -0
  92. package/dist/types/models.d.ts.map +1 -1
  93. package/dist/types/segments.d.ts +2 -1
  94. package/dist/types/segments.d.ts.map +1 -1
  95. package/dist/types/tools.d.ts +51 -5
  96. package/dist/types/tools.d.ts.map +1 -1
  97. package/dist/utils/segments.d.ts +1 -0
  98. package/dist/utils/segments.d.ts.map +1 -1
  99. package/dist/utils/tool-line.d.ts +9 -8
  100. package/dist/utils/tool-line.d.ts.map +1 -1
  101. package/package.json +2 -2
  102. package/dist/defer-hydration-Ch3TOEJC.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) => {
@@ -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;
@@ -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;
@@ -2619,12 +2645,7 @@ function announceLink(event) {
2619
2645
  anchor,
2620
2646
  messageId: chip.closest("aparte-chat-bubble")?.getAttribute("message-id") ?? null
2621
2647
  };
2622
- const announced = chip.dispatchEvent(new CustomEvent("aparte-link-click", {
2623
- bubbles: true,
2624
- composed: true,
2625
- cancelable: true,
2626
- detail
2627
- }));
2648
+ const announced = dispatchChatEvent(chip, "aparte-link-click", detail, { cancelable: true });
2628
2649
  if (!announced) event.preventDefault();
2629
2650
  }
2630
2651
  function pagerButton(label, icon, part, disabled, act) {
@@ -3185,18 +3206,18 @@ function describeToolInput(input, format) {
3185
3206
  }
3186
3207
  const reported = /* @__PURE__ */ new WeakSet();
3187
3208
  function toolLineOf(segment, config) {
3188
- const provider = config.getToolLineProvider();
3189
- if (!provider) return void 0;
3190
- try {
3191
- const line = provider(segment);
3192
- return line && typeof line === "object" ? line : void 0;
3193
- } catch (err) {
3194
- if (!reported.has(provider)) {
3195
- reported.add(provider);
3196
- 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
+ }
3197
3218
  }
3198
- return void 0;
3199
3219
  }
3220
+ return void 0;
3200
3221
  }
3201
3222
  const textOf = (value) => typeof value === "string" ? value.trim() : "";
3202
3223
  function toolNameOf(segment, config, line = toolLineOf(segment, config)) {
@@ -3228,11 +3249,19 @@ function toolTargetPartsOf(segment, config, line = toolLineOf(segment, config))
3228
3249
  const text = textOf(line?.target);
3229
3250
  return { text, isWords: text !== "" };
3230
3251
  }
3231
- function toolActivityOf(_segment, line) {
3232
- 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);
3233
3262
  }
3234
- function toolLineNoteOf(line) {
3235
- return textOf(line?.note);
3263
+ function toolLineNoteOf(segment, line, config) {
3264
+ return displayText$1(config.getToolDisplay(segment.toolCall?.name ?? "")?.note, segment) || textOf(line?.note);
3236
3265
  }
3237
3266
  function describeInput(segment) {
3238
3267
  return describeToolInput(segment.toolCall?.input, contextConfig().getToolInputFormatter(segment.toolCall?.name ?? ""));
@@ -3276,7 +3305,7 @@ function reasonOf(segment) {
3276
3305
  return "";
3277
3306
  }
3278
3307
  function noteOf(segment, line) {
3279
- return [reasonOf(segment), toolLineNoteOf(line)].filter(Boolean).join(" · ");
3308
+ return [reasonOf(segment), toolLineNoteOf(segment, line, contextConfig())].filter(Boolean).join(" · ");
3280
3309
  }
3281
3310
  function outcomeOf(segment) {
3282
3311
  const text = displayText(segment.result ?? "");
@@ -3473,7 +3502,7 @@ function setTarget(element, segment, line) {
3473
3502
  function setActivity(element, segment, line) {
3474
3503
  const el2 = element.querySelector(".aparte-tool-activity");
3475
3504
  if (!el2) return;
3476
- const text = toolActivityOf(segment, line);
3505
+ const text = toolActivityOf(segment, line, contextConfig());
3477
3506
  if (el2.textContent !== text) el2.textContent = text;
3478
3507
  el2.toggleAttribute("hidden", !text);
3479
3508
  }
@@ -3579,7 +3608,7 @@ function pillMarkup(segment, line, withOpen = true) {
3579
3608
  const badge = stateBadge(segment);
3580
3609
  const icon = iconOf(segment);
3581
3610
  const target = toolTarget(segment, line);
3582
- const activity = toolActivityOf(segment, line);
3611
+ const activity = toolActivityOf(segment, line, contextConfig());
3583
3612
  const note = noteOf(segment, line);
3584
3613
  const name = nameOf(segment, line);
3585
3614
  const quiet = quietOf(segment);
@@ -4059,7 +4088,8 @@ const toolRefusal = toolRefusal$1;
4059
4088
  const runSubAgent = runSubAgent$1;
4060
4089
  const startSubAgent = startSubAgent$1;
4061
4090
  function createStreamAdapter(opts) {
4062
- 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 } : {} };
4063
4093
  let parser = new AparteStreamParser({ blocks: config.getStreamBlocks() });
4064
4094
  let streaming = /* @__PURE__ */ new Set();
4065
4095
  let thinkingId = null;
@@ -4273,7 +4303,7 @@ function createStreamAdapter(opts) {
4273
4303
  }
4274
4304
  case "tool-awaiting-approval":
4275
4305
  target.updateSegment?.(`tool-${e.toolCallId}`, unqueued(`tool-${e.toolCallId}`, { status: "awaiting-approval" }));
4276
- 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);
4277
4307
  break;
4278
4308
  case "tool-approved":
4279
4309
  settle2(e.toolCallId, { status: "pending" });
@@ -4387,7 +4417,7 @@ function createStreamAdapter(opts) {
4387
4417
  );
4388
4418
  }
4389
4419
  if (e.type === "tool-awaiting-approval") {
4390
- 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);
4391
4421
  }
4392
4422
  };
4393
4423
  }
@@ -4549,7 +4579,8 @@ function createAparteAgentHandler(options) {
4549
4579
  ...!body.request.modelId && options.defaultModel ? { modelId: options.defaultModel } : {},
4550
4580
  tools: [...[...tools.values()].map((t) => t.tool), ...clientTools]
4551
4581
  };
4552
- 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);
4553
4584
  const offered = new Set((request.tools ?? []).map((t) => t.name));
4554
4585
  const tail = unansweredTail(request.messages);
4555
4586
  if (!body.resume && tail.length > 0) {
@@ -4576,7 +4607,7 @@ function createAparteAgentHandler(options) {
4576
4607
  }
4577
4608
  const key = await options.resolveKey?.(providerId);
4578
4609
  const external = new Set(clientTools.map((t) => t.name));
4579
- const rule = (call) => options.approvalPolicy?.(call, tools.get(call.name)?.tool);
4610
+ const rule = (call) => options.approvalPolicy?.(call, tools.get(call.name)?.tool, turn2);
4580
4611
  const run = new AbortController();
4581
4612
  if (req.signal.aborted) run.abort();
4582
4613
  else req.signal.addEventListener("abort", () => run.abort(), { once: true });
@@ -5014,19 +5045,19 @@ function applyImagePolicyWithoutDom(html, decide, words) {
5014
5045
  break;
5015
5046
  }
5016
5047
  i = end;
5017
- const written = html.slice(lt, end);
5048
+ const written2 = html.slice(lt, end);
5018
5049
  if (closing) {
5019
5050
  if (tag === "a") links = Math.max(0, links - 1);
5020
5051
  const at = open.lastIndexOf(tag);
5021
5052
  if (at >= 0) open.length = at;
5022
- out += written;
5053
+ out += written2;
5023
5054
  continue;
5024
5055
  }
5025
5056
  const attr = (name) => attrs.find(([key]) => key === name)?.[1];
5026
5057
  if (RAW_TEXT$1.has(tag)) {
5027
5058
  const close = lower.indexOf(`</${tag}`, end);
5028
5059
  const stop = close < 0 ? n : close;
5029
- out += written + html.slice(end, stop);
5060
+ out += written2 + html.slice(end, stop);
5030
5061
  i = stop;
5031
5062
  continue;
5032
5063
  }
@@ -5045,14 +5076,14 @@ function applyImagePolicyWithoutDom(html, decide, words) {
5045
5076
  if (tag === "source") {
5046
5077
  const kept = judgeSource(attr("src") ?? "", attr("srcset"), decide);
5047
5078
  if (kept === false) continue;
5048
- out += kept === (attr("srcset") ?? null) ? written : writeTag(tag, attrs, { srcset: kept });
5079
+ out += kept === (attr("srcset") ?? null) ? written2 : writeTag(tag, attrs, { srcset: kept });
5049
5080
  continue;
5050
5081
  }
5051
5082
  if (tag === "img") {
5052
5083
  const judged = judgeImage(attr("src") ?? "", attr("srcset"), decide);
5053
5084
  if (!judged) {
5054
5085
  const inPicture = open[open.length - 1] === "picture";
5055
- 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;
5056
5087
  else out += writeTag(tag, attrs, { srcset: null, ...inPicture ? { referrerpolicy: "no-referrer" } : {} });
5057
5088
  continue;
5058
5089
  }
@@ -5060,8 +5091,8 @@ function applyImagePolicyWithoutDom(html, decide, words) {
5060
5091
  else if (judged.decision === "load") out += writeTag(tag, attrs, { srcset: judged.srcset, referrerpolicy: "no-referrer" });
5061
5092
  continue;
5062
5093
  }
5063
- if (!VOID.has(tag) && !written.endsWith("/>")) open.push(tag);
5064
- out += written;
5094
+ if (!VOID.has(tag) && !written2.endsWith("/>")) open.push(tag);
5095
+ out += written2;
5065
5096
  }
5066
5097
  return out;
5067
5098
  }
@@ -5123,13 +5154,13 @@ function commentEnd(html, at) {
5123
5154
  const m = COMMENT_END.exec(html);
5124
5155
  return m ? m.index + m[0].length : html.length;
5125
5156
  }
5126
- function linkTag(written, attrs, mode) {
5157
+ function linkTag(written2, attrs, mode) {
5127
5158
  const attr = (name) => attrs.find(([key]) => key === name)?.[1];
5128
5159
  const href = attr("href");
5129
- if (href === void 0) return written;
5160
+ if (href === void 0) return written2;
5130
5161
  const decided = linkTargetAttributes(mode, href, attr("target") ?? "");
5131
5162
  const settled2 = settle(decided, attr("target"), attr("rel"));
5132
- if (!settled2) return written;
5163
+ if (!settled2) return written2;
5133
5164
  const kept = attrs.filter(([name]) => name !== "target" && (settled2.rel === void 0 || name !== "rel") && SAFE_NAME.test(name));
5134
5165
  const added = [];
5135
5166
  if (settled2.target !== void 0) added.push(["target", settled2.target]);
@@ -5168,19 +5199,19 @@ function applyLinkTargetWithoutDom(html, mode) {
5168
5199
  break;
5169
5200
  }
5170
5201
  i = end;
5171
- const written = html.slice(lt, end);
5202
+ const written2 = html.slice(lt, end);
5172
5203
  if (closing) {
5173
- out += written;
5204
+ out += written2;
5174
5205
  continue;
5175
5206
  }
5176
5207
  if (RAW_TEXT.has(tag)) {
5177
5208
  const close = lower.indexOf(`</${tag}`, end);
5178
5209
  const stop = close < 0 ? n : close;
5179
- out += written + html.slice(end, stop);
5210
+ out += written2 + html.slice(end, stop);
5180
5211
  i = stop;
5181
5212
  continue;
5182
5213
  }
5183
- out += tag === "a" ? linkTag(written, attrs, mode) : written;
5214
+ out += tag === "a" ? linkTag(written2, attrs, mode) : written2;
5184
5215
  }
5185
5216
  return out;
5186
5217
  }
@@ -5444,6 +5475,8 @@ class AparteConfig {
5444
5475
  _activityRenderers = /* @__PURE__ */ new Map();
5445
5476
  /** What a plugin says about a call, read after the app's display — see {@link setToolLineProvider}. */
5446
5477
  _toolLineProvider = null;
5478
+ /** Providers added with `registerToolLineProvider`, asked in the order they were added. */
5479
+ _extraToolLineProviders = [];
5447
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. */
5448
5481
  _stepLabels = /* @__PURE__ */ new Map();
5449
5482
  /** Tagged blocks the stream parser recognises in the prose — see {@link registerStreamBlock}. */
@@ -6237,11 +6270,12 @@ class AparteConfig {
6237
6270
  /**
6238
6271
  * What the policy says about one call, with the tool's own `needsApproval` as the
6239
6272
  * answer when it has no opinion. The one place the two are combined, so the client's
6240
- * 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.
6241
6275
  */
6242
- ruleOnToolCall(call) {
6276
+ ruleOnToolCall(call, turn2) {
6243
6277
  const tool = this._tools.get(call.name)?.tool;
6244
- const ruling = this._approvalPolicy?.(call, tool);
6278
+ const ruling = this._approvalPolicy?.(call, tool, turn2);
6245
6279
  if (ruling) return ruling;
6246
6280
  return { verdict: tool?.needsApproval ? "ask" : "allow" };
6247
6281
  }
@@ -6766,7 +6800,40 @@ class AparteConfig {
6766
6800
  bumpRenderingVersion(this);
6767
6801
  this._notify();
6768
6802
  }
6769
- /** 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. */
6770
6837
  getToolLineProvider() {
6771
6838
  if (this._toolLineProvider || this === aparteGlobalConfig) return this._toolLineProvider;
6772
6839
  return aparteGlobalConfig._toolLineProvider;
@@ -7137,6 +7204,7 @@ class AparteConfig {
7137
7204
  notifyRenderersChanged(this);
7138
7205
  this._toolDisplays.clear();
7139
7206
  this._toolLineProvider = null;
7207
+ this._extraToolLineProviders = [];
7140
7208
  this._stepLabels.clear();
7141
7209
  this._streamBlocks.clear();
7142
7210
  this._runEventObservers = [];
@@ -7891,6 +7959,17 @@ function openConversationOf(el2) {
7891
7959
  }
7892
7960
  return null;
7893
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
+ }
7894
7973
  const MAX_COMPACTION_SAVE_WAITS = 6;
7895
7974
  class AparteConversationController {
7896
7975
  _binding;
@@ -7899,6 +7978,11 @@ class AparteConversationController {
7899
7978
  _isStreaming = false;
7900
7979
  _isLoadingConversation = false;
7901
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;
7902
7986
  /** The conversation the turn in flight started in, and what the lists were told of it. */
7903
7987
  _turn = null;
7904
7988
  /** The reply the turn in flight writes into, from its `aparte-message-start`. */
@@ -7951,17 +8035,30 @@ class AparteConversationController {
7951
8035
  get activeId() {
7952
8036
  return this._activeId;
7953
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
+ }
7954
8051
  /**
7955
8052
  * The conversation a message sent now belongs to: the open one, or — for the first
7956
- * message of a chat — the one that send is creating. `createNew()` makes it the
7957
- * manager's active conversation synchronously, so the client, which hears the send
7958
- * right after this controller does, already finds it there; this controller's own id
7959
- * follows once the conversation is saved. `_ensureConversationAndPersist` reads the
7960
- * same two places to decide where the message is saved, so a turn is carried to the
7961
- * conversation its message was written in.
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.
7962
8059
  */
7963
8060
  _openId() {
7964
- return this._activeId ?? this._manager()?.activeId ?? null;
8061
+ return this._activeId ?? this._pendingId;
7965
8062
  }
7966
8063
  /**
7967
8064
  * Lazily resolve the conversation manager. Returns `undefined` if none is
@@ -7971,7 +8068,7 @@ class AparteConversationController {
7971
8068
  * conversation lifecycle yet.
7972
8069
  */
7973
8070
  _manager() {
7974
- const manager = this._options.manager ?? (() => {
8071
+ const manager = this._options.manager ?? this._keptManager ?? (() => {
7975
8072
  const scoped = resolveConfig(this._binding.host);
7976
8073
  const m = scoped.getConversationManager();
7977
8074
  if (!m) this._warnManagerOnTheWrongConfig(scoped);
@@ -7979,11 +8076,63 @@ class AparteConversationController {
7979
8076
  })();
7980
8077
  if (manager && this._bound && manager !== this._subscribedTo) {
7981
8078
  this._unsubscribeManager?.();
8079
+ enrol(this._subscribedTo, this, false);
8080
+ enrol(manager, this, true);
7982
8081
  this._subscribedTo = manager;
7983
8082
  this._unsubscribeManager = manager.subscribe(this._onManagerChanged);
7984
8083
  }
7985
8084
  return manager;
7986
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
+ }
7987
8136
  /**
7988
8137
  * Degraded mode is legitimate — a host that never opted into the conversation
7989
8138
  * lifecycle has no manager and should not be nagged. Registering one on the
@@ -8016,7 +8165,7 @@ class AparteConversationController {
8016
8165
  this._turn = null;
8017
8166
  return;
8018
8167
  }
8019
- 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);
8020
8169
  if (!id) return;
8021
8170
  this._turn = { id, status };
8022
8171
  tellConversationStatus(id, status);
@@ -8128,6 +8277,7 @@ class AparteConversationController {
8128
8277
  this._withdrawOpenConversation?.();
8129
8278
  this._withdrawOpenConversation = null;
8130
8279
  this._bound = false;
8280
+ enrol(this._subscribedTo, this, false);
8131
8281
  this._subscribedTo = null;
8132
8282
  this._persistActive();
8133
8283
  if (this._turn?.status === "running") this._setTurn(null);
@@ -8135,6 +8285,9 @@ class AparteConversationController {
8135
8285
  this._turnMessage = null;
8136
8286
  this._stopHydrationRetry?.();
8137
8287
  this._stopHydrationRetry = null;
8288
+ this._stopConfigWait?.();
8289
+ this._stopConfigWait = null;
8290
+ this._keptManager = null;
8138
8291
  const host2 = this._binding.host;
8139
8292
  if (this._onSendCapture) {
8140
8293
  host2.removeEventListener("aparte-send", this._onSendCapture, { capture: true });
@@ -8259,6 +8412,10 @@ class AparteConversationController {
8259
8412
  }
8260
8413
  async _openConversation(id) {
8261
8414
  const isSwitch = id !== this._activeId;
8415
+ if (isSwitch && this._keptManager) {
8416
+ this._persistActive();
8417
+ this._keptManager = null;
8418
+ }
8262
8419
  const manager = this._manager();
8263
8420
  if (isSwitch && this._isStreaming) {
8264
8421
  if (this._turn?.status === "waiting") this._turn = null;
@@ -8438,13 +8595,31 @@ class AparteConversationController {
8438
8595
  }
8439
8596
  void manager.updateMessages(this._activeId, msgs, tree);
8440
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
+ }
8441
8614
  async _ensureConversationAndPersist(userMsg) {
8442
8615
  const manager = this._manager();
8443
8616
  if (!manager) {
8444
8617
  return;
8445
8618
  }
8619
+ const adopted = this._activeId === null && this._pendingId === null ? this._adoptable(manager) : null;
8620
+ if (adopted) this._activeId = adopted;
8446
8621
  const wasActiveId = this._activeId;
8447
- let convId = wasActiveId ?? manager.activeId;
8622
+ let convId = wasActiveId ?? this._pendingId;
8448
8623
  if (convId && this._activeId === null && this._ensureInFlight) {
8449
8624
  await this._ensureInFlight.catch(() => {
8450
8625
  });
@@ -8453,10 +8628,13 @@ class AparteConversationController {
8453
8628
  if (!convId) {
8454
8629
  if (!this._ensureInFlight) {
8455
8630
  const text = (userMsg.content ?? "").toString().trim();
8456
- 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);
8457
8634
  }
8458
8635
  convId = await this._ensureInFlight;
8459
8636
  this._ensureInFlight = null;
8637
+ this._pendingId = null;
8460
8638
  if (this._activeId !== wasActiveId && this._activeId !== convId) {
8461
8639
  void manager.delete(convId).catch(() => {
8462
8640
  });
@@ -8492,15 +8670,6 @@ function gateGlide(el2) {
8492
8670
  el2.addEventListener("aparte-send", lift);
8493
8671
  return off;
8494
8672
  }
8495
- function chatIdOf(el2) {
8496
- let node = el2.parentElement;
8497
- while (node) {
8498
- const isHost = node.tagName.toLowerCase() === "aparte-chat" || node.hasAttribute("data-aparte-chat");
8499
- if (isHost && node.id) return node.id;
8500
- node = node.parentElement;
8501
- }
8502
- return void 0;
8503
- }
8504
8673
  class CheckpointStateWatcher {
8505
8674
  constructor(_options) {
8506
8675
  this._options = _options;
@@ -8656,6 +8825,8 @@ class AparteChatHost {
8656
8825
  _controller;
8657
8826
  _teardown = [];
8658
8827
  _bound = false;
8828
+ /** A config given while a turn was in flight, applied when it ends — see {@link setConfig}. */
8829
+ _nextConfig = null;
8659
8830
  constructor(binding, options = {}) {
8660
8831
  this.binding = binding;
8661
8832
  this.options = options;
@@ -8747,15 +8918,89 @@ class AparteChatHost {
8747
8918
  _setStreamingId(id) {
8748
8919
  if (this._streamingId === id) return;
8749
8920
  this._streamingId = id;
8921
+ if (id === null && this._nextConfig) {
8922
+ const { config } = this._nextConfig;
8923
+ this._nextConfig = null;
8924
+ this._applyConfig(config);
8925
+ }
8750
8926
  this.binding.onStreamingChange?.(id);
8751
8927
  this._vp()?.setTranscriptBusy?.(id !== null);
8752
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
+ }
8753
8964
  // ── conversation ───────────────────────────────────────────────────────
8754
- /** 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
+ */
8755
8970
  setConversationId(id) {
8756
8971
  this._conversationId = id;
8757
8972
  return this._controller?.setConversationId(id) ?? Promise.resolve();
8758
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
+ }
8759
9004
  _unbindController;
8760
9005
  _createController(host2) {
8761
9006
  const convBinding = {
@@ -9517,8 +9762,44 @@ function messageWireText(message) {
9517
9762
  const text = extractWireText(message);
9518
9763
  return message.compaction ? underPreamble(text) : text;
9519
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
+ }
9520
9801
  function wireMessages(messages) {
9521
- return messages.filter((m) => {
9802
+ return withoutAbandonedTurns(messages).filter((m) => {
9522
9803
  if (m.role !== "user" && m.role !== "assistant") return false;
9523
9804
  return m.status !== "error" && !isInFlight(m);
9524
9805
  }).flatMap((m) => {
@@ -10049,7 +10330,7 @@ function el(tag, className, text) {
10049
10330
  return node;
10050
10331
  }
10051
10332
  let askSeq = 0;
10052
- function buildApprovalPanel(message, options, onChange, details, allowOther = true) {
10333
+ function buildApprovalPanel(message, options, onChange, details, allowOther = true, preview) {
10053
10334
  const cfg = contextConfig();
10054
10335
  const panel = el("div", "aparte-elic-panel aparte-approval-panel");
10055
10336
  const body = el("div", "aparte-elic-body");
@@ -10068,6 +10349,12 @@ function buildApprovalPanel(message, options, onChange, details, allowOther = tr
10068
10349
  pre.tabIndex = 0;
10069
10350
  body.append(argsLabel, pre);
10070
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
+ }
10071
10358
  const dismiss = el("div", "aparte-elic-dismiss");
10072
10359
  panel.appendChild(dismiss);
10073
10360
  let settle2 = null;
@@ -10386,6 +10673,21 @@ class AparteClient {
10386
10673
  this._isAborted = true;
10387
10674
  this._streamController?.abort();
10388
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
+ }
10389
10691
  /**
10390
10692
  * Ask the human at the COMPOSER, and report what they decided.
10391
10693
  *
@@ -10407,8 +10709,9 @@ class AparteClient {
10407
10709
  * that wants to answer programmatically registers an `approvalResolver` (headless,
10408
10710
  * no DOM) or its own presenter, both strictly more capable than an id on an event.
10409
10711
  */
10410
- async _askForApproval(event, signal, target) {
10712
+ async _askForApproval(event, signal, target, turn2) {
10411
10713
  const agentName = event.agent?.name?.trim();
10714
+ const preview = this._approvalPreviewOf(event, target);
10412
10715
  const answer = await requestUserInput({
10413
10716
  kind: "approval",
10414
10717
  /*
@@ -10445,7 +10748,11 @@ class AparteClient {
10445
10748
  { value: "deny", label: () => this._config.getLocale().rejectTool ?? "Reject", tone: "deny" }
10446
10749
  ],
10447
10750
  signal,
10448
- 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 } : {}
10449
10756
  });
10450
10757
  if (answer.action !== "accept") return { approved: false, by: "person" };
10451
10758
  const content = answer.content;
@@ -10497,6 +10804,11 @@ class AparteClient {
10497
10804
  */
10498
10805
  async _streamTurn(targetElement, messageId, provider, messages, modelId, authConfig, opts) {
10499
10806
  const chatId = this._targetIdOf(targetElement);
10807
+ const turn2 = {
10808
+ ...opts?.conversationId ? { conversationId: opts.conversationId } : {},
10809
+ messageId,
10810
+ ...chatId ? { targetId: chatId } : {}
10811
+ };
10500
10812
  const registeredTools = this._toolsForCurrentModel();
10501
10813
  const buildRequest = async (requestMessages2) => {
10502
10814
  let built = {
@@ -10508,7 +10820,7 @@ class AparteClient {
10508
10820
  ...opts?.meta ? { _meta: opts.meta } : {}
10509
10821
  };
10510
10822
  if (this.options.requestInterceptor) {
10511
- built = await this.options.requestInterceptor(built);
10823
+ built = await this.options.requestInterceptor(built, turn2);
10512
10824
  }
10513
10825
  if (built.toolChoice === "none") {
10514
10826
  const toolPrompts = this._config.resolveToolSystemPrompts(registeredTools);
@@ -10541,7 +10853,7 @@ class AparteClient {
10541
10853
  if (this._streamController !== streamController) this._streamController?.abort();
10542
10854
  this._streamController = streamController;
10543
10855
  this._turnsInFlight.add(messageId);
10544
- this._agentNames.set(messageId, /* @__PURE__ */ new Map());
10856
+ this._agentNames.set(messageId, new Map(opts?.agentNames ?? []));
10545
10857
  const compactor = opts?.rebuild ? resolveConfig(targetElement).getCompactor() ?? this._config.getCompactor() : null;
10546
10858
  const turnIds = () => {
10547
10859
  const path = targetElement.getMessages?.() ?? [];
@@ -10559,11 +10871,11 @@ class AparteClient {
10559
10871
  };
10560
10872
  const isStopped = () => this._isAborted || streamController.signal.aborted;
10561
10873
  const runOnce = async () => {
10562
- let result = opts?.resume ? { usage: void 0, suspended: opts.resume } : await this._streamLoop(targetElement, messageId, provider, baseRequest, authConfig, streamController, void 0, opts?.files, opts?.conversationId);
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);
10563
10875
  const maxResumes = this.options.maxTurns ?? 10;
10564
10876
  let resumes = 0;
10565
10877
  let approvedAtLastPause = /* @__PURE__ */ new Set();
10566
- 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 } : {} });
10567
10879
  while (result.suspended) {
10568
10880
  const stopped = this._isAborted || streamController.signal.aborted;
10569
10881
  if (!stopped && ++resumes > maxResumes) {
@@ -10574,7 +10886,7 @@ class AparteClient {
10574
10886
  break;
10575
10887
  }
10576
10888
  const approvedNow = /* @__PURE__ */ new Set();
10577
- 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);
10578
10890
  approvedAtLastPause = approvedNow;
10579
10891
  if (!outcomes) {
10580
10892
  this._closeOpenCalls(targetElement, messageId);
@@ -10599,7 +10911,8 @@ class AparteClient {
10599
10911
  streamController,
10600
10912
  deferral,
10601
10913
  void 0,
10602
- opts?.conversationId
10914
+ opts?.conversationId,
10915
+ opts?.userMessage
10603
10916
  );
10604
10917
  }
10605
10918
  const usage = result.usage;
@@ -10735,6 +11048,7 @@ class AparteClient {
10735
11048
  const authConfig = providerId ? await this._resolveAuth(providerId) : void 0;
10736
11049
  const chatMessages = this._messagesToChatMessages(historyMessages);
10737
11050
  const systemMessages = this._systemMessages();
11051
+ const asked2 = [...historyMessages].reverse().find((m) => m.role === "user");
10738
11052
  await this._streamTurn(
10739
11053
  targetElement,
10740
11054
  newMessageId,
@@ -10744,8 +11058,9 @@ class AparteClient {
10744
11058
  authConfig,
10745
11059
  {
10746
11060
  ...provider.retryTemperature !== void 0 ? { temperature: provider.retryTemperature } : {},
10747
- ...this._turnMeta([...historyMessages].reverse().find((m) => m.role === "user")),
11061
+ ...this._turnMeta(asked2),
10748
11062
  ...conversationId ? { conversationId } : {},
11063
+ ...asked2 ? { userMessage: { content: messageWireText(asked2), messageId: asked2.id } } : {},
10749
11064
  rebuild: async () => [
10750
11065
  ...this._systemMessages(),
10751
11066
  ...mergeAdjacentUserMessages(this._messagesToChatMessages(this._current(targetElement, historyMessages)))
@@ -10824,6 +11139,10 @@ class AparteClient {
10824
11139
  {
10825
11140
  ...this._turnMeta(editIdx >= 0 ? allMessages[editIdx] : void 0),
10826
11141
  ...conversationId ? { conversationId } : {},
11142
+ userMessage: {
11143
+ content: editIdx >= 0 ? messageWireText(allMessages[editIdx]) : String(newContent),
11144
+ messageId
11145
+ },
10827
11146
  rebuild: async () => [
10828
11147
  ...this._systemMessages(),
10829
11148
  ...mergeAdjacentUserMessages(this._messagesToChatMessages(this._current(targetElement, historyMessages)))
@@ -10952,14 +11271,7 @@ class AparteClient {
10952
11271
  * through to the next one up rather than answer "no id".
10953
11272
  */
10954
11273
  _targetIdOf(el2) {
10955
- let node = el2 ?? null;
10956
- while (node) {
10957
- const tag = node.tagName?.toLowerCase();
10958
- const isHost = tag === "aparte-chat" || node.hasAttribute?.("data-aparte-chat");
10959
- if (isHost && node.id) return node.id;
10960
- node = node.parentElement;
10961
- }
10962
- return el2?.id || void 0;
11274
+ return chatIdOf(el2) ?? (el2?.id || void 0);
10963
11275
  }
10964
11276
  /**
10965
11277
  * Convert AparteMessage[] to AparteChatMessage[] for re-submission (retry, edit).
@@ -11048,6 +11360,8 @@ class AparteClient {
11048
11360
  });
11049
11361
  if (event.detail && typeof event.detail === "object") event.detail.echoed = true;
11050
11362
  }
11363
+ const shown2 = targetElement.getMessages?.().at(-1);
11364
+ const sentId = shown2?.role === "user" ? shown2.id : void 0;
11051
11365
  const messageId = uuid();
11052
11366
  const config = this._config.getModelConfig();
11053
11367
  const providerId = explicitProviderId || config.defaultProvider;
@@ -11105,7 +11419,8 @@ class AparteClient {
11105
11419
  rebuild: async () => this._buildMessages(content, targetElement, fileParts),
11106
11420
  ...rawFiles.length > 0 ? { files: rawFiles } : {},
11107
11421
  ...this._turnMeta(event.detail),
11108
- ...conversationId ? { conversationId } : {}
11422
+ ...conversationId ? { conversationId } : {},
11423
+ userMessage: { content: this._userContent(content, fileParts), ...sentId ? { messageId: sentId } : {} }
11109
11424
  }
11110
11425
  );
11111
11426
  }
@@ -11121,19 +11436,18 @@ class AparteClient {
11121
11436
  } else if (typeof historyOption === "function") {
11122
11437
  messages.push(...historyOption(viewportMessages));
11123
11438
  }
11124
- const userMsg = parts && parts.length > 0 ? [{ type: "text", text: userContent }, ...parts] : userContent;
11125
- messages.push({ role: "user", content: userMsg });
11439
+ messages.push({ role: "user", content: this._userContent(userContent, parts) });
11126
11440
  return mergeAdjacentUserMessages(messages);
11127
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
+ }
11128
11446
  _toHistoryMessages(path) {
11129
11447
  const { summary, messages } = historyFromCheckpoint(path);
11130
- let cutoff = 0;
11131
- for (let i = 0; i < messages.length; i++) {
11132
- const m = messages[i];
11133
- if (m.role === "assistant" && m.status !== "error" && !isInFlight(m)) {
11134
- cutoff = i + 1;
11135
- }
11136
- }
11448
+ let cutoff = messages.length;
11449
+ while (cutoff > 0 && isInFlight(messages[cutoff - 1])) cutoff--;
11450
+ if (cutoff > 0 && messages[cutoff - 1].role === "user") cutoff--;
11137
11451
  return [...this._summaryMessage(summary), ...wireMessages(messages.slice(0, cutoff))];
11138
11452
  }
11139
11453
  /**
@@ -11215,11 +11529,11 @@ ${content}
11215
11529
  * adapter, or the runner a host injected — after the fetch-level abort bookkeeping.
11216
11530
  */
11217
11531
  /** One run of the loop: its usage, and whether it paused (a server loop). */
11218
- async _streamLoop(targetElement, messageId, provider, baseRequest, authConfig, streamController = new AbortController(), deferral, files, conversationId) {
11532
+ async _streamLoop(targetElement, messageId, provider, baseRequest, authConfig, streamController = new AbortController(), deferral, files, conversationId, userMessage) {
11219
11533
  if (this._streamController !== streamController) this._streamController?.abort();
11220
11534
  this._streamController = streamController;
11221
11535
  const runner = this.options.streamRunner ?? runStreamAgent;
11222
- return this._runViaStreamRunner(runner, targetElement, messageId, provider, baseRequest, authConfig, streamController, deferral, files, conversationId);
11536
+ return this._runViaStreamRunner(runner, targetElement, messageId, provider, baseRequest, authConfig, streamController, deferral, files, conversationId, userMessage);
11223
11537
  }
11224
11538
  /**
11225
11539
  * Run the loop through a {@link AparteStreamRunner} — the engine's by default —
@@ -11230,20 +11544,29 @@ ${content}
11230
11544
  * produces is pinned by the `stream-parity` suite's snapshots, recorded while
11231
11545
  * the inline loop it replaced still ran beside it.
11232
11546
  */
11233
- async _runViaStreamRunner(streamRunner, targetElement, messageId, provider, baseRequest, authConfig, streamController, deferral, files, conversationId) {
11547
+ async _runViaStreamRunner(streamRunner, targetElement, messageId, provider, baseRequest, authConfig, streamController, deferral, files, conversationId, userMessage) {
11234
11548
  const signal = streamController.signal;
11235
11549
  const chatId = this._targetIdOf(targetElement);
11550
+ const turn2 = {
11551
+ ...conversationId ? { conversationId } : {},
11552
+ messageId,
11553
+ ...chatId ? { targetId: chatId } : {}
11554
+ };
11236
11555
  const adapter = createStreamAdapter({
11237
11556
  target: targetElement,
11238
11557
  config: this._config,
11239
11558
  messageId,
11240
- ...chatId ? { targetId: chatId } : {}
11559
+ ...chatId ? { targetId: chatId } : {},
11560
+ ...conversationId ? { conversationId } : {}
11241
11561
  });
11242
11562
  const prefixSegments = baseRequest._meta?.["prefixSegments"];
11243
11563
  let suspended;
11244
11564
  let finishReason;
11245
11565
  let toolCrash;
11246
11566
  const emitter = (event) => {
11567
+ if (event.type === "run-suspended" && event.agentId == null) {
11568
+ this._keepSubAgentCalls(targetElement, messageId, event.pending, event.ticket);
11569
+ }
11247
11570
  adapter(event);
11248
11571
  if (event.type === "agent-start" && event.name) this._agentNames.get(messageId)?.set(event.agentId, event.name);
11249
11572
  if (event.agentId != null) return;
@@ -11281,12 +11604,12 @@ ${content}
11281
11604
  maxTurns: tool.maxTurns,
11282
11605
  parallel: tool.parallel,
11283
11606
  needsApproval: hostOwnsDecision ? tool.needsApproval : (call) => {
11284
- const verdict = this._config.ruleOnToolCall(call).verdict;
11607
+ const verdict = this._config.ruleOnToolCall(call, turn2).verdict;
11285
11608
  return verdict === "allow" ? false : verdict;
11286
11609
  }
11287
11610
  };
11288
11611
  };
11289
- const approvalResolver = this._approvalResolverFor(targetElement);
11612
+ const approvalResolver = this._approvalResolverFor(targetElement, turn2);
11290
11613
  const asToolCrash = (error) => {
11291
11614
  if (toolCrash === void 0 || error instanceof AparteError) return error;
11292
11615
  const text = error instanceof Error ? error.message || error.name : typeof error === "string" ? error : String(error);
@@ -11298,6 +11621,7 @@ ${content}
11298
11621
  ...deferral ? { deferral } : {},
11299
11622
  ...files && files.length > 0 ? { files } : {},
11300
11623
  ...conversationId ? { conversationId } : {},
11624
+ ...userMessage ? { userMessage } : {},
11301
11625
  baseRequest,
11302
11626
  transportCall,
11303
11627
  toolLookup,
@@ -11334,14 +11658,16 @@ ${content}
11334
11658
  * the tool's `needsApproval` — reads a tool the page does not have, and said
11335
11659
  * "allow": the page approved, silently, what the server wanted a person to decide.
11336
11660
  */
11337
- _approvalResolverFor(targetElement, gatedElsewhere = false) {
11338
- return this.options.approvalResolver ?? (async (call, sig) => {
11339
- 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);
11340
11666
  if (ruling.verdict === "allow") return { approved: true };
11341
11667
  if (ruling.verdict === "deny") {
11342
11668
  return { approved: false, reason: ruling.reason?.trim() || "Tool execution was refused by the approval policy.", by: "policy" };
11343
11669
  }
11344
- return this._askForApproval(call, sig, targetElement);
11670
+ return this._askForApproval(call, sig, targetElement, turn2);
11345
11671
  });
11346
11672
  }
11347
11673
  /**
@@ -11352,9 +11678,10 @@ ${content}
11352
11678
  * nobody answered — the turn was stopped, or the channel gave up — and there is no
11353
11679
  * resume. A channel that CRASHES fails the turn, as it does for a run in the page.
11354
11680
  */
11355
- 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()) {
11356
11682
  const outcomes = {};
11357
- const resolver = this._approvalResolverFor(targetElement, true);
11683
+ const { messageId } = turn2;
11684
+ const resolver = this._approvalResolverFor(targetElement, turn2, true);
11358
11685
  const refuseTheRest = (after) => {
11359
11686
  for (const rest of pending2.slice(after + 1)) {
11360
11687
  outcomes[rest.toolCallId] = { kind: "decision", approved: false, reason: NOT_RUN_AFTER_A_REFUSAL, by: "earlier-refusal" };
@@ -11384,7 +11711,7 @@ ${content}
11384
11711
  const key = approvalKey(call);
11385
11712
  if (!approvedBefore.has(key) && !approvedNow.has(key)) {
11386
11713
  try {
11387
- gate = await this._gateBrowserTool(asked2, signal, targetElement, rowEvents);
11714
+ gate = await this._gateBrowserTool(asked2, signal, targetElement, turn2, rowEvents);
11388
11715
  } catch (error) {
11389
11716
  if (!signal.aborted && error?.name !== "AbortError") throw error;
11390
11717
  gate = void 0;
@@ -11401,7 +11728,11 @@ ${content}
11401
11728
  const handler = this._config.getToolHandler(p.name);
11402
11729
  try {
11403
11730
  if (!handler) throw new Error(`No browser handler is registered for "${p.name}".`);
11404
- 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
+ });
11405
11736
  outcomes[p.toolCallId] = {
11406
11737
  kind: "result",
11407
11738
  content: result.content,
@@ -11422,8 +11753,8 @@ ${content}
11422
11753
  * rule (`ruleOnToolCall`) and the default channel asks. `null` when nothing gates the
11423
11754
  * call, the decision when something did, `undefined` when nobody answered.
11424
11755
  */
11425
- async _gateBrowserTool(call, signal, targetElement, rowEvents) {
11426
- 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;
11427
11758
  if (ruling === "allow") return null;
11428
11759
  if (ruling === "ask") {
11429
11760
  rowEvents?.({
@@ -11434,7 +11765,7 @@ ${content}
11434
11765
  ...call.agent ? { agentId: call.agent.id } : {}
11435
11766
  });
11436
11767
  }
11437
- const decision = await this._approvalResolverFor(targetElement)(call, signal) ?? void 0;
11768
+ const decision = await this._approvalResolverFor(targetElement, turn2)(call, signal) ?? void 0;
11438
11769
  if (decision?.approved && ruling === "ask") {
11439
11770
  if (call.agent) rowEvents?.({ type: "tool-approved", toolCallId: call.id, agentId: call.agent.id });
11440
11771
  else targetElement.updateSegment?.(`tool-${call.id}`, { status: "pending" });
@@ -11448,16 +11779,49 @@ ${content}
11448
11779
  * history that resumes them is built first; a new pause marks what still waits.
11449
11780
  */
11450
11781
  _spendPause(targetElement, messageId) {
11451
- 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;
11452
11784
  const paused = (segment) => segment.type === "tool_call" && Boolean(segment.deferred);
11453
- if (!segments?.some(paused)) return;
11785
+ const rows = Boolean(segments?.some(paused));
11786
+ if (!rows && !message?.deferredCalls?.length) return;
11454
11787
  targetElement.updateMessage?.(messageId, {
11455
- segments: segments.map((segment) => {
11456
- if (!paused(segment)) return segment;
11457
- const { deferred: _spent, ...rest } = segment;
11458
- return rest;
11459
- })
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
+ };
11460
11823
  });
11824
+ if (kept.length > 0) targetElement.updateMessage?.(messageId, { deferredCalls: kept });
11461
11825
  }
11462
11826
  /**
11463
11827
  * Close the reply's calls that can no longer finish — paused, queued, or running on a
@@ -11468,15 +11832,21 @@ ${content}
11468
11832
  * the wait moves the head. A run in the page ends every call itself: nothing to do.
11469
11833
  */
11470
11834
  _closeOpenCalls(targetElement, messageId) {
11471
- 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;
11472
11837
  const unfinished = (segment) => segment.type === "tool_call" && (segment.status === "pending" || segment.status === "awaiting-approval");
11473
- if (!segments?.some(unfinished)) return;
11838
+ const rows = Boolean(segments?.some(unfinished));
11839
+ if (!rows && !message?.deferredCalls?.length) return;
11474
11840
  targetElement.updateMessage?.(messageId, {
11475
- segments: segments.map((segment) => {
11476
- if (!unfinished(segment)) return segment;
11477
- const { deferred: _spent, ...rest } = segment;
11478
- return { ...rest, status: "aborted" };
11479
- })
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 } : {}
11480
11850
  });
11481
11851
  }
11482
11852
  /**
@@ -11515,13 +11885,19 @@ ${content}
11515
11885
  _closeDeferred(targetElement) {
11516
11886
  const messages = targetElement.getMessages?.() ?? [];
11517
11887
  const last = [...messages].reverse().find((m) => m.role === "assistant");
11518
- if (!last?.segments?.some(isOpenDeferred)) return;
11519
- const segments = last.segments.map((segment) => {
11520
- if (!isOpenDeferred(segment)) return segment;
11521
- const { deferred: _closed, ...rest } = segment;
11522
- 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 } : {}
11523
11900
  });
11524
- targetElement.updateMessage?.(last.id, { segments });
11525
11901
  }
11526
11902
  /**
11527
11903
  * Answer a turn a server loop paused, when the conversation comes back — a reload, a
@@ -11543,8 +11919,9 @@ ${content}
11543
11919
  const messages = targetElement.getMessages?.() ?? [];
11544
11920
  const last = [...messages].reverse().find((m) => m.role === "assistant");
11545
11921
  const open = (last?.segments ?? []).filter(isOpenDeferred);
11546
- const ticket = open.find((s) => s.deferred?.ticket)?.deferred?.ticket;
11547
- 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;
11548
11925
  const config = this._config.getModelConfig();
11549
11926
  const recorded = last.model && this._config.getAIProvider(last.model.providerId) ? last.model : void 0;
11550
11927
  const providerId = recorded?.providerId ?? config.defaultProvider;
@@ -11558,12 +11935,23 @@ ${content}
11558
11935
  this._resuming.add(last.id);
11559
11936
  try {
11560
11937
  const authConfig = provider.id ? await this._resolveAuth(provider.id) : void 0;
11561
- const pending2 = open.map((s) => ({
11562
- toolCallId: s.toolCall.id,
11563
- name: s.toolCall.name,
11564
- input: s.toolCall.input,
11565
- reason: s.deferred.reason
11566
- }));
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]] : []));
11567
11955
  const base = this._resumeBase(messages, messages.indexOf(last));
11568
11956
  await this._streamTurn(targetElement, last.id, provider, base, recorded?.modelId ?? config.defaultModel ?? "", authConfig, {
11569
11957
  resume: { pending: pending2, ticket },
@@ -11573,7 +11961,8 @@ ${content}
11573
11961
  return at >= 0 ? this._resumeBase(now, at) : base;
11574
11962
  },
11575
11963
  ...recorded?.temperature !== void 0 ? { temperature: recorded.temperature } : {},
11576
- ...conversationId ? { conversationId } : {}
11964
+ ...conversationId ? { conversationId } : {},
11965
+ ...agentNames.size > 0 ? { agentNames } : {}
11577
11966
  });
11578
11967
  } finally {
11579
11968
  this._resuming.delete(last.id);
@@ -12014,26 +12403,34 @@ const APARTE_DEFAULT_UI_EVENTS = [
12014
12403
  "aparte-message-resumed",
12015
12404
  "aparte-tool-approval-request"
12016
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
+ }
12017
12414
  function applyElementProps(el2, props, transformValue = (value) => value) {
12018
12415
  for (const [key, value] of Object.entries(props)) {
12019
12416
  if (key.startsWith("--")) {
12020
- if (value === null || value === void 0) el2.style.removeProperty(key);
12021
- else if (typeof value === "object" || typeof value === "function") el2.style.removeProperty(key);
12022
- 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)));
12023
12420
  } else if (key.toLowerCase().startsWith("on")) {
12024
12421
  el2.removeAttribute(key);
12025
12422
  } else if (value === false && isDefaultOn(el2, key)) {
12026
- el2.setAttribute(key, "false");
12423
+ writeOnce(el2, key, "false", () => el2.setAttribute(key, "false"));
12027
12424
  } else if (value === null || value === void 0 || value === false) {
12028
- el2.removeAttribute(key);
12425
+ writeOnce(el2, key, null, () => el2.removeAttribute(key));
12029
12426
  } else if (typeof value === "number" && Number.isNaN(value)) {
12030
- el2.removeAttribute(key);
12427
+ writeOnce(el2, key, null, () => el2.removeAttribute(key));
12031
12428
  } else if (value === true) {
12032
- el2.setAttribute(key, "");
12429
+ writeOnce(el2, key, "", () => el2.setAttribute(key, ""));
12033
12430
  } else if (typeof value === "object" || typeof value === "function") {
12034
12431
  el2[key] = transformValue(value);
12035
12432
  } else {
12036
- el2.setAttribute(key, String(value));
12433
+ writeOnce(el2, key, String(value), () => el2.setAttribute(key, String(value)));
12037
12434
  }
12038
12435
  }
12039
12436
  }
@@ -12240,95 +12637,97 @@ function deferHydrationOf(ctor) {
12240
12637
  };
12241
12638
  }
12242
12639
  export {
12243
- isFormatAdapter as $,
12640
+ installDialogTriggersOnce as $,
12244
12641
  APARTE_CONFIG_CHANGE as A,
12245
- contextConfig as B,
12246
- copyText as C,
12247
- createAgentStreamRunner as D,
12248
- createAparteAgentHandler as E,
12249
- createAparteChatHandler as F,
12250
- createSegmentList as G,
12251
- createStreamAdapter as H,
12252
- declineDefaultRenderers as I,
12253
- defaultSanitizer as J,
12254
- deferHydrationOf as K,
12255
- defineMountedSegmentRenderer as L,
12256
- defineMountedToolRenderer as M,
12257
- detachConfig as N,
12258
- escapeAttr as O,
12259
- escapeHtml as P,
12260
- estimateTokens as Q,
12261
- 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,
12262
12659
  SUGGESTIONS_BLOCK_LANGUAGE as S,
12263
- filesToAttachments as T,
12264
- formatDuration as U,
12265
- getAllRenderers as V,
12266
- getSegmentRenderer as W,
12267
- historyFromCheckpoint as X,
12268
- installDefaultRenderersOnce as Y,
12269
- installDialogTriggersOnce as Z,
12270
- 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 _,
12271
12668
  APARTE_CONVERSATION_SCHEMA_VERSION as a,
12272
- isSafeUrl as a0,
12273
- isSegmentSettled as a1,
12274
- measureContext as a2,
12275
- onRenderersChange as a3,
12276
- overrideSegmentRenderer as a4,
12277
- parseAparteEventStream as a5,
12278
- parseMarkdownToSegments as a6,
12279
- pluralize as a7,
12280
- populateBubbleFromMessage as a8,
12281
- readableToAsyncIterable as a9,
12282
- renderingVersionOf as aA,
12283
- renderSourceList as aB,
12284
- mergeSegmentUpdate as aC,
12285
- toolNameOf as aD,
12286
- writeStreamedMarkdown as aE,
12287
- replaceHighlighted as aF,
12288
- toolRendererThatDrew as aG,
12289
- activityRendererThatDrew as aH,
12290
- CheckpointStateWatcher as aI,
12291
- chatIdOf as aJ,
12292
- stampSegmentActivity as aK,
12293
- stampSegmentOnInsert as aL,
12294
- stampSegmentOnUpdate as aM,
12295
- renumberSegments as aN,
12296
- openSegmentIds as aO,
12297
- isTerminalStatus as aP,
12298
- adoptMessageSegments as aQ,
12299
- APARTE_DERIVED_SEGMENTS as aR,
12300
- rememberConversationStatus as aS,
12301
- tellConversationStatus as aT,
12302
- conversationStatusOf as aU,
12303
- visibleReply as aV,
12304
- usageTokens as aW,
12305
- inRenderedContent as aX,
12306
- registerDefaultRenderers as aa,
12307
- registerSegmentRenderer as ab,
12308
- releaseDeferredHydration as ac,
12309
- renderCitations as ad,
12310
- renderCodeLanguages as ae,
12311
- requestUserInput as af,
12312
- resolveConfig as ag,
12313
- revokeAttachmentUrls as ah,
12314
- runSubAgent as ai,
12315
- runWithConfig as aj,
12316
- segmentDuration as ak,
12317
- segmentTiming as al,
12318
- setupSuggestionBlocks as am,
12319
- startSubAgent as an,
12320
- subscribeConfigChange as ao,
12321
- toToolCallView as ap,
12322
- toolRefusal as aq,
12323
- unregisterSegmentRenderer as ar,
12324
- uuid as as,
12325
- gateGlide as at,
12326
- chatBoundaryOf as au,
12327
- relabelCodeLanguages as av,
12328
- relabelCitations as aw,
12329
- toolCallRenderer as ax,
12330
- activityRenderer as ay,
12331
- 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,
12332
12731
  APARTE_DEFAULT_BUBBLE_ACTIONS as b,
12333
12732
  APARTE_DEFAULT_HOST_HANDLERS as c,
12334
12733
  APARTE_DEFAULT_ICON_FALLBACKS as d,
@@ -12352,7 +12751,7 @@ export {
12352
12751
  attachConfig as v,
12353
12752
  buildApprovalPanel as w,
12354
12753
  buildElicitationPanel as x,
12355
- collectRendererStyles as y,
12356
- contentToText as z
12754
+ chatIdOf as y,
12755
+ collectRendererStyles as z
12357
12756
  };
12358
- //# sourceMappingURL=defer-hydration-Ch3TOEJC.js.map
12757
+ //# sourceMappingURL=defer-hydration-OFqdbk3O.js.map