@aparte/core 1.5.0 → 1.7.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 (63) hide show
  1. package/dist/client/agent-runner.d.ts.map +1 -1
  2. package/dist/client/aparte-client.d.ts +6 -0
  3. package/dist/client/aparte-client.d.ts.map +1 -1
  4. package/dist/client/stream-adapter.d.ts +72 -2
  5. package/dist/client/stream-adapter.d.ts.map +1 -1
  6. package/dist/client/wire-history.d.ts +5 -2
  7. package/dist/client/wire-history.d.ts.map +1 -1
  8. package/dist/components/bubble/aparte-chat-bubble.d.ts +15 -1
  9. package/dist/components/bubble/aparte-chat-bubble.d.ts.map +1 -1
  10. package/dist/components/conversation-list/aparte-conversation-list.d.ts +46 -22
  11. package/dist/components/conversation-list/aparte-conversation-list.d.ts.map +1 -1
  12. package/dist/components/viewport/aparte-chat-viewport.d.ts +10 -0
  13. package/dist/components/viewport/aparte-chat-viewport.d.ts.map +1 -1
  14. package/dist/config/aparte-config.d.ts +112 -4
  15. package/dist/config/aparte-config.d.ts.map +1 -1
  16. package/dist/config/bubble-shell-renderer.d.ts +3 -0
  17. package/dist/config/bubble-shell-renderer.d.ts.map +1 -1
  18. package/dist/config/index.d.ts +1 -1
  19. package/dist/config/index.d.ts.map +1 -1
  20. package/dist/config/locale.d.ts +9 -0
  21. package/dist/config/locale.d.ts.map +1 -1
  22. package/dist/custom-elements.json +1233 -77
  23. package/dist/{defer-hydration-lK-7XQXf.js → defer-hydration-o5MFsc_Z.js} +730 -237
  24. package/dist/defer-hydration-o5MFsc_Z.js.map +1 -0
  25. package/dist/elicitation/panel.d.ts.map +1 -1
  26. package/dist/host/aparte-chat-host.d.ts +8 -0
  27. package/dist/host/aparte-chat-host.d.ts.map +1 -1
  28. package/dist/index.css +1 -1
  29. package/dist/index.d.ts +11 -3
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +278 -211
  32. package/dist/index.js.map +1 -1
  33. package/dist/index.node.d.ts +11 -3
  34. package/dist/index.node.d.ts.map +1 -1
  35. package/dist/index.node.js +46 -36
  36. package/dist/index.node.js.map +1 -1
  37. package/dist/kit-keyboard-BUSLQ5i4.js +434 -0
  38. package/dist/kit-keyboard-BUSLQ5i4.js.map +1 -0
  39. package/dist/renderers/segment-renderers.d.ts.map +1 -1
  40. package/dist/renderers/segments/activity.d.ts +5 -0
  41. package/dist/renderers/segments/activity.d.ts.map +1 -0
  42. package/dist/renderers/segments/tool-call.d.ts.map +1 -1
  43. package/dist/transport/agent-handler.d.ts.map +1 -1
  44. package/dist/types/chat.d.ts +22 -0
  45. package/dist/types/chat.d.ts.map +1 -1
  46. package/dist/types/event-map.d.ts +4 -0
  47. package/dist/types/event-map.d.ts.map +1 -1
  48. package/dist/types/index.d.ts +2 -2
  49. package/dist/types/index.d.ts.map +1 -1
  50. package/dist/types/segments.d.ts +53 -1
  51. package/dist/types/segments.d.ts.map +1 -1
  52. package/dist/types/tools.d.ts +67 -1
  53. package/dist/types/tools.d.ts.map +1 -1
  54. package/dist/utils/menu.d.ts +90 -0
  55. package/dist/utils/menu.d.ts.map +1 -0
  56. package/dist/utils/segment-list.d.ts +49 -0
  57. package/dist/utils/segment-list.d.ts.map +1 -0
  58. package/dist/utils/tabs.d.ts +49 -0
  59. package/dist/utils/tabs.d.ts.map +1 -0
  60. package/dist/utils/tool-line.d.ts +36 -9
  61. package/dist/utils/tool-line.d.ts.map +1 -1
  62. package/package.json +2 -2
  63. package/dist/defer-hydration-lK-7XQXf.js.map +0 -1
@@ -1,4 +1,5 @@
1
- import { toolRefusal as toolRefusal$1, unansweredTail, runStreamAgent } from "@aparte/engine";
1
+ import { runSubAgent as runSubAgent$1, startSubAgent as startSubAgent$1, toolRefusal as toolRefusal$1, unansweredTail, runStreamAgent } from "@aparte/engine";
2
+ import { c as cssEscape, b as enhanceTabs, d as eventOrigin, r as rootOf } from "./kit-keyboard-BUSLQ5i4.js";
2
3
  import { A as APARTE_ICON_GLYPHS } from "./glyphs-LolG04CC.js";
3
4
  function contentToText(content) {
4
5
  if (typeof content === "string") return content;
@@ -106,6 +107,7 @@ const APARTE_DEFAULT_LOCALE = {
106
107
  elicitationAnswerLabel: "Your answer",
107
108
  approvalInstructionPlaceholder: "Or tell it what to do instead…",
108
109
  approvalAsk: "Allow {tool}?",
110
+ approvalAskBy: "Allow {tool} for {agent}?",
109
111
  approvalWaiting: "Waiting",
110
112
  scrollToBottom: "Scroll to bottom",
111
113
  suggestionsLabel: "Suggested prompts",
@@ -3164,7 +3166,23 @@ function describeToolInput(input, format) {
3164
3166
  return "";
3165
3167
  }
3166
3168
  }
3167
- function toolNameOf(segment, config) {
3169
+ const reported = /* @__PURE__ */ new WeakSet();
3170
+ function toolLineOf(segment, config) {
3171
+ const provider = config.getToolLineProvider();
3172
+ if (!provider) return void 0;
3173
+ try {
3174
+ const line = provider(segment);
3175
+ return line && typeof line === "object" ? line : void 0;
3176
+ } catch (err) {
3177
+ if (!reported.has(provider)) {
3178
+ reported.add(provider);
3179
+ console.error("[aparte] The tool-line provider threw; the row keeps its default line. Further throws from it are not reported.", err);
3180
+ }
3181
+ return void 0;
3182
+ }
3183
+ }
3184
+ const textOf = (value) => typeof value === "string" ? value.trim() : "";
3185
+ function toolNameOf(segment, config, line = toolLineOf(segment, config)) {
3168
3186
  const identifier = segment.toolCall?.name ?? "tool";
3169
3187
  const label = config.getToolDisplay(identifier)?.label;
3170
3188
  if (label !== void 0) {
@@ -3174,17 +3192,30 @@ function toolNameOf(segment, config) {
3174
3192
  } catch {
3175
3193
  }
3176
3194
  }
3195
+ const provided = textOf(line?.label);
3196
+ if (provided) return { text: provided, isLabel: true };
3177
3197
  return { text: identifier, isLabel: false };
3178
3198
  }
3179
- function toolTargetOf(segment, config) {
3199
+ function toolTargetOf(segment, config, line = toolLineOf(segment, config)) {
3200
+ return toolTargetPartsOf(segment, config, line).text;
3201
+ }
3202
+ function toolTargetPartsOf(segment, config, line = toolLineOf(segment, config)) {
3180
3203
  const summary = config.getToolSummary(segment.toolCall?.name ?? "");
3181
- if (!summary) return "";
3182
- try {
3183
- const text = summary(segment);
3184
- return typeof text === "string" ? text.trim() : "";
3185
- } catch {
3186
- return "";
3204
+ if (summary) {
3205
+ try {
3206
+ const text2 = textOf(summary(segment));
3207
+ if (text2) return { text: text2, isWords: false };
3208
+ } catch {
3209
+ }
3187
3210
  }
3211
+ const text = textOf(line?.target);
3212
+ return { text, isWords: text !== "" };
3213
+ }
3214
+ function toolActivityOf(_segment, line) {
3215
+ return textOf(line?.activity);
3216
+ }
3217
+ function toolLineNoteOf(line) {
3218
+ return textOf(line?.note);
3188
3219
  }
3189
3220
  function describeInput(segment) {
3190
3221
  return describeToolInput(segment.toolCall?.input, contextConfig().getToolInputFormatter(segment.toolCall?.name ?? ""));
@@ -3201,7 +3232,7 @@ function stateBadge(segment) {
3201
3232
  if (status === "failed") return `${cfg.getIcon("close")}${word(cfg.t("toolFailed"))}`;
3202
3233
  return "";
3203
3234
  }
3204
- function noteOf(segment) {
3235
+ function reasonOf(segment) {
3205
3236
  const cfg = contextConfig();
3206
3237
  if (segment.status === "rejected") {
3207
3238
  const by = segment.refusal?.by;
@@ -3226,32 +3257,52 @@ function noteOf(segment) {
3226
3257
  }
3227
3258
  return "";
3228
3259
  }
3260
+ function noteOf(segment, line) {
3261
+ return [reasonOf(segment), toolLineNoteOf(line)].filter(Boolean).join(" · ");
3262
+ }
3229
3263
  function outcomeOf(segment) {
3230
3264
  const text = displayText(segment.result ?? "");
3231
3265
  if (!text) return null;
3232
3266
  if (segment.status === "rejected" && segment.refusal) return null;
3233
3267
  return { key: "toolOutput", text };
3234
3268
  }
3235
- function behindOf(segment) {
3236
- const details = contextConfig().getToolDisplay(segment.toolCall?.name ?? "")?.details;
3269
+ function behindOf(segment, line, row) {
3270
+ const display = contextConfig().getToolDisplay(segment.toolCall?.name ?? "");
3271
+ const details = display && "details" in display ? display.details : line?.details;
3237
3272
  if (details === false) return { kind: "none" };
3238
3273
  if (typeof details !== "function") return { kind: "parts" };
3239
3274
  try {
3240
- const out = details(segment);
3275
+ const out = details(segment, row ? heldBy(row) : void 0);
3241
3276
  if (!out) return { kind: "none" };
3242
3277
  return { kind: "body", body: typeof out === "string" ? contextConfig().sanitizeHtml(out) : out };
3243
3278
  } catch {
3244
3279
  return { kind: "none" };
3245
3280
  }
3246
3281
  }
3247
- const appDetailOf = (element) => element.querySelector(':scope > .aparte-tool-detail[data-details="app"]');
3282
+ function disclosureOf(row) {
3283
+ if (row.tagName === "DETAILS") return row;
3284
+ return row.querySelector(":scope > details.aparte-tool-disclosure");
3285
+ }
3286
+ const appDetailOf = (element) => element.querySelector(':scope > .aparte-tool-detail[data-details="app"], :scope > .aparte-tool-disclosure > .aparte-tool-detail[data-details="app"]');
3248
3287
  function setBody(element, body) {
3249
3288
  const detail = element.querySelector(".aparte-tool-detail");
3250
3289
  if (!detail) return;
3251
- if (typeof body === "string") detail.innerHTML = body;
3252
- else detail.replaceChildren(body);
3290
+ if (typeof body !== "string" && body.parentNode === detail) return;
3291
+ if (typeof body === "string") {
3292
+ detail.innerHTML = body;
3293
+ heldBodies.delete(detail);
3294
+ } else {
3295
+ detail.replaceChildren(body);
3296
+ heldBodies.set(detail, body);
3297
+ }
3253
3298
  drawnBodies.set(detail, serialized(body));
3254
3299
  }
3300
+ const heldBodies = /* @__PURE__ */ new WeakMap();
3301
+ function heldBy(row) {
3302
+ const detail = appDetailOf(row);
3303
+ const body = detail ? heldBodies.get(detail) : void 0;
3304
+ return body && body.parentNode === detail ? body : void 0;
3305
+ }
3255
3306
  const drawnBodies = /* @__PURE__ */ new WeakMap();
3256
3307
  const serialized = (body) => typeof body === "string" ? body : body.outerHTML;
3257
3308
  function relabelBody(detail, body) {
@@ -3268,7 +3319,11 @@ function relabelBody(detail, body) {
3268
3319
  const prev = document.createElement("div");
3269
3320
  if (before !== void 0) prev.innerHTML = before;
3270
3321
  if (before !== void 0 && sameShape(prev, next) && sameShape(prev, detail)) patchChanges(detail, prev, next);
3271
- else detail.replaceChildren(...Array.from(next.childNodes));
3322
+ else {
3323
+ detail.replaceChildren(...Array.from(next.childNodes));
3324
+ if (typeof body === "string") heldBodies.delete(detail);
3325
+ else heldBodies.set(detail, body);
3326
+ }
3272
3327
  drawnBodies.set(detail, now);
3273
3328
  }
3274
3329
  function sameShape(a, b) {
@@ -3298,10 +3353,10 @@ function patchChanges(live2, prev, next) {
3298
3353
  }
3299
3354
  }
3300
3355
  }
3301
- function setNote(element, segment) {
3356
+ function setNote(element, segment, line) {
3302
3357
  const el2 = element.querySelector(".aparte-tool-note");
3303
3358
  if (!el2) return;
3304
- const text = noteOf(segment);
3359
+ const text = noteOf(segment, line);
3305
3360
  if (el2.textContent !== text) el2.textContent = text;
3306
3361
  el2.toggleAttribute("hidden", !text);
3307
3362
  if (text) el2.setAttribute("title", text);
@@ -3386,18 +3441,26 @@ function highlightParts(element) {
3386
3441
  });
3387
3442
  }
3388
3443
  }
3389
- function toolTarget(segment) {
3390
- return toolTargetOf(segment, contextConfig());
3444
+ function toolTarget(segment, line) {
3445
+ return toolTargetPartsOf(segment, contextConfig(), line);
3391
3446
  }
3392
- function setTarget(element, segment) {
3447
+ function setTarget(element, segment, line) {
3393
3448
  const el2 = element.querySelector(".aparte-tool-target");
3394
3449
  if (!el2) return;
3395
- const text = toolTarget(segment);
3450
+ const { text, isWords } = toolTarget(segment, line);
3451
+ if (el2.textContent !== text) el2.textContent = text;
3452
+ el2.toggleAttribute("hidden", !text);
3453
+ el2.classList.toggle("aparte-tool-target--words", isWords);
3454
+ }
3455
+ function setActivity(element, segment, line) {
3456
+ const el2 = element.querySelector(".aparte-tool-activity");
3457
+ if (!el2) return;
3458
+ const text = toolActivityOf(segment, line);
3396
3459
  if (el2.textContent !== text) el2.textContent = text;
3397
3460
  el2.toggleAttribute("hidden", !text);
3398
3461
  }
3399
- function nameOf(segment) {
3400
- return toolNameOf(segment, contextConfig());
3462
+ function nameOf(segment, line) {
3463
+ return toolNameOf(segment, contextConfig(), line);
3401
3464
  }
3402
3465
  function iconOf(segment) {
3403
3466
  const cfg = contextConfig();
@@ -3421,76 +3484,148 @@ function setQuiet(element, segment) {
3421
3484
  element.querySelector(".aparte-tool-name")?.classList.toggle("aparte-shimmer", quiet.shimmer);
3422
3485
  element.querySelector(".aparte-tool-state")?.classList.toggle("aparte-sr-only", quiet.stateHidden);
3423
3486
  }
3424
- function setName(element, segment) {
3487
+ function setName(element, segment, line) {
3425
3488
  const el2 = element.querySelector(".aparte-tool-name");
3426
3489
  if (!el2) return;
3427
- const { text, isLabel } = nameOf(segment);
3490
+ const { text, isLabel } = nameOf(segment, line);
3428
3491
  if (el2.textContent !== text) el2.textContent = text;
3429
3492
  el2.classList.toggle("aparte-tool-name--label", isLabel);
3430
3493
  }
3431
- function pillMarkup(segment) {
3494
+ const opens = /* @__PURE__ */ new WeakMap();
3495
+ function openOf(line) {
3496
+ const open = line?.open;
3497
+ return open && typeof open.onOpen === "function" ? open : void 0;
3498
+ }
3499
+ function openAttrs(line) {
3500
+ const open = openOf(line);
3501
+ return open ? ` data-opens${open.current ? " data-current" : ""}` : "";
3502
+ }
3503
+ function openMarkup(line) {
3504
+ const open = openOf(line);
3505
+ if (!open) return "";
3506
+ const label = escapeAttr(typeof open.label === "string" ? open.label.trim() : "");
3507
+ const icon = contextConfig().getIcon("maximize");
3508
+ return `<button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-tool-open" aria-label="${label}" title="${label}"${open.current ? ' aria-current="true"' : ""}>${icon}</button>`;
3509
+ }
3510
+ function setOpen(row, line, structural) {
3511
+ const open = openOf(line);
3512
+ const lineEl = row.querySelector(":scope > .aparte-tool-line");
3513
+ let button = row.querySelector(":scope > :is(.aparte-tool-line, .aparte-tool-open-slot) > .aparte-tool-open");
3514
+ if (open) opens.set(row, open);
3515
+ else opens.delete(row);
3516
+ if (structural && lineEl && !!open !== !!button) {
3517
+ if (button) {
3518
+ button.remove();
3519
+ button = null;
3520
+ } else {
3521
+ const tpl = document.createElement("template");
3522
+ tpl.innerHTML = openMarkup(line);
3523
+ button = tpl.content.firstElementChild;
3524
+ lineEl.insertBefore(button, lineEl.querySelector(":scope > .aparte-tool-activity"));
3525
+ }
3526
+ }
3527
+ row.toggleAttribute("data-opens", !!open && !!button);
3528
+ row.toggleAttribute("data-current", !!open?.current && !!button);
3529
+ if (!open || !button) return;
3530
+ const label = typeof open.label === "string" ? open.label.trim() : "";
3531
+ if (button.getAttribute("aria-label") !== label) {
3532
+ button.setAttribute("aria-label", label);
3533
+ button.title = label;
3534
+ }
3535
+ if (open.current) button.setAttribute("aria-current", "true");
3536
+ else button.removeAttribute("aria-current");
3537
+ }
3538
+ const wiredOpen = /* @__PURE__ */ new WeakSet();
3539
+ function wireOpen(row) {
3540
+ if (wiredOpen.has(row)) return;
3541
+ wiredOpen.add(row);
3542
+ row.addEventListener("click", (event) => {
3543
+ const open = opens.get(row);
3544
+ const target = event.target;
3545
+ if (!open || !target?.closest || target.closest(".aparte-segment-tool-call") !== row) return;
3546
+ if (!target.closest(".aparte-tool-open")) {
3547
+ if (disclosureOf(row) || target.closest(".aparte-tool-line")?.parentElement !== row) return;
3548
+ if (row.ownerDocument.getSelection?.()?.isCollapsed === false) return;
3549
+ }
3550
+ try {
3551
+ open.onOpen(row);
3552
+ } catch (err) {
3553
+ console.error("[aparte] a tool line's onOpen threw", err);
3554
+ }
3555
+ });
3556
+ }
3557
+ function pillMarkup(segment, line, withOpen = true) {
3432
3558
  const badge = stateBadge(segment);
3433
3559
  const icon = iconOf(segment);
3434
- const target = toolTarget(segment);
3435
- const note = noteOf(segment);
3436
- const name = nameOf(segment);
3560
+ const target = toolTarget(segment, line);
3561
+ const activity = toolActivityOf(segment, line);
3562
+ const note = noteOf(segment, line);
3563
+ const name = nameOf(segment, line);
3437
3564
  const quiet = quietOf(segment);
3565
+ const open = withOpen ? openMarkup(line) : "";
3438
3566
  return `
3439
3567
  <span class="aparte-tool-label">
3440
3568
  <span class="aparte-tool-icon">${icon}</span>
3441
3569
  <span class="aparte-tool-name${name.isLabel ? " aparte-tool-name--label" : ""}${quiet.shimmer ? " aparte-shimmer" : ""}">${escapeHtml(name.text)}</span>
3442
- <span class="aparte-tool-target"${target ? "" : " hidden"}>${escapeHtml(target)}</span>
3570
+ <span class="aparte-tool-target${target.isWords ? " aparte-tool-target--words" : ""}"${target.text ? "" : " hidden"}>${escapeHtml(target.text)}</span>
3443
3571
  </span>
3444
3572
  <span class="aparte-spinner aparte-tool-spinner" aria-hidden="true"${quiet.spinner ? "" : " hidden"}></span>
3445
3573
  <span class="aparte-tool-state${quiet.stateHidden ? " aparte-sr-only" : ""}">${badge}</span>
3446
- <span class="aparte-tool-note"${note ? ` title="${escapeAttr(note)}"` : " hidden"}>${escapeHtml(note)}</span>`;
3574
+ <span class="aparte-tool-note"${note ? ` title="${escapeAttr(note)}"` : " hidden"}>${escapeHtml(note)}</span>${open}
3575
+ <span class="aparte-tool-activity"${activity ? "" : " hidden"}>${escapeHtml(activity)}</span>`;
3447
3576
  }
3448
3577
  function placeholderMarkup(segment) {
3449
3578
  return `<div class="aparte-segment aparte-segment-tool-call" data-segment-id="${escapeHtml(segment.id)}" data-status="${escapeAttr(segment.status ?? "pending")}" data-tool-call-id="${escapeAttr(segment.toolCall?.id ?? "")}" data-tool-name="${escapeAttr(segment.toolCall?.name ?? "tool")}" hidden></div>`;
3450
3579
  }
3451
- const isPlaceholder = (element) => element.hidden && element.classList.contains("aparte-segment-tool-call") && element.childElementCount === 0;
3452
- const drawnBy = /* @__PURE__ */ new WeakMap();
3453
- const behind = /* @__PURE__ */ new WeakMap();
3580
+ const isPlaceholder$1 = (element) => element.hidden && element.classList.contains("aparte-segment-tool-call") && element.childElementCount === 0;
3581
+ const drawnBy$1 = /* @__PURE__ */ new WeakMap();
3582
+ const behind$1 = /* @__PURE__ */ new WeakMap();
3454
3583
  function toolRendererThatDrew(element) {
3455
- return behind.get(element) ?? null;
3584
+ return behind$1.get(element) ?? null;
3456
3585
  }
3457
3586
  function drawerOf(element, current) {
3458
- const recorded = drawnBy.get(element);
3587
+ const recorded = drawnBy$1.get(element);
3459
3588
  if (recorded) return recorded;
3460
3589
  return element.classList.contains("aparte-segment-tool-call") ? null : current;
3461
3590
  }
3462
- function drawDefault(segment, behind2) {
3591
+ function drawDefault(segment, behind2, line) {
3463
3592
  const name = segment.toolCall?.name ?? "tool";
3464
3593
  const status = segment.status ?? "pending";
3465
3594
  const toolCallId = segment.toolCall?.id ?? "";
3466
- const pill = pillMarkup(segment);
3595
+ const pill = pillMarkup(segment, line);
3467
3596
  const quiet = isQuiet(segment) ? " data-quiet" : "";
3597
+ const opensAt = openAttrs(line);
3468
3598
  const toggle = contextConfig().getIcon("expand");
3469
3599
  const input = behind2.kind === "parts" ? describeInput(segment) : "";
3470
3600
  const outcome = behind2.kind === "parts" ? outcomeOf(segment) : null;
3471
3601
  if (behind2.kind === "none" || behind2.kind === "parts" && !input && !outcome) {
3472
3602
  return `
3473
- <div class="aparte-segment aparte-segment-tool-call" data-segment-id="${escapeHtml(segment.id)}" data-status="${escapeAttr(status)}" data-tool-call-id="${escapeAttr(toolCallId)}" data-tool-name="${escapeAttr(name)}"${quiet}><div class="aparte-tool-line">${pill}</div>
3603
+ <div class="aparte-segment aparte-segment-tool-call" data-segment-id="${escapeHtml(segment.id)}" data-status="${escapeAttr(status)}" data-tool-call-id="${escapeAttr(toolCallId)}" data-tool-name="${escapeAttr(name)}"${quiet}${opensAt}><div class="aparte-tool-line">${pill}</div>
3474
3604
  </div>
3475
3605
  `;
3476
3606
  }
3477
3607
  const cfg = contextConfig();
3478
3608
  const copy = copyButtonMarkup("aparte-tool-copy");
3479
3609
  const open = segment.collapsed !== void 0 ? !segment.collapsed : cfg.getToolDisplay(name)?.open === true;
3610
+ const openButton = openMarkup(line);
3611
+ const disclosure = openButton ? `<details class="aparte-tool-disclosure"${open ? " open" : ""}>` : "";
3612
+ const rowStart = openButton ? `<div class="aparte-segment aparte-segment-tool-call" data-segment-id="${escapeHtml(segment.id)}" data-status="${escapeAttr(status)}" data-tool-call-id="${escapeAttr(toolCallId)}" data-tool-name="${escapeAttr(name)}"${quiet}${opensAt}>${disclosure}` : `<details class="aparte-segment aparte-segment-tool-call" data-segment-id="${escapeHtml(segment.id)}" data-status="${escapeAttr(status)}" data-tool-call-id="${escapeAttr(toolCallId)}" data-tool-name="${escapeAttr(name)}"${quiet}${opensAt}${open ? " open" : ""}>`;
3613
+ const rowEnd = openButton ? `</details><span class="aparte-tool-open-slot">${openButton}</span></div>` : "</details>";
3614
+ const summaryPill = pillMarkup(segment, line, false);
3480
3615
  if (behind2.kind === "body") {
3481
3616
  const tpl = document.createElement("template");
3482
3617
  tpl.innerHTML = `
3483
- <details class="aparte-segment aparte-segment-tool-call" data-segment-id="${escapeHtml(segment.id)}" data-status="${escapeAttr(status)}" data-tool-call-id="${escapeAttr(toolCallId)}" data-tool-name="${escapeAttr(name)}"${quiet}${open ? " open" : ""}>
3484
- <summary class="aparte-tool-summary"><span class="aparte-tool-toggle">${toggle}</span>${pill}</summary>
3618
+ ${rowStart}
3619
+ <summary class="aparte-tool-summary"><span class="aparte-tool-toggle">${toggle}</span>${summaryPill}</summary>
3485
3620
  <div class="aparte-tool-detail" data-details="app"></div>
3486
- </details>`.trim();
3621
+ ${rowEnd}`.trim();
3487
3622
  const row = tpl.content.firstElementChild;
3488
3623
  setBody(row, behind2.body);
3489
3624
  return row;
3490
3625
  }
3491
3626
  return `
3492
- <details class="aparte-segment aparte-segment-tool-call" data-segment-id="${escapeHtml(segment.id)}" data-status="${escapeAttr(status)}" data-tool-call-id="${escapeAttr(toolCallId)}" data-tool-name="${escapeAttr(name)}"${quiet}${open ? " open" : ""}>
3493
- <summary class="aparte-tool-summary"><span class="aparte-tool-toggle">${toggle}</span>${pill}</summary>
3627
+ ${rowStart}
3628
+ <summary class="aparte-tool-summary"><span class="aparte-tool-toggle">${toggle}</span>${summaryPill}</summary>
3494
3629
  <div class="aparte-tool-detail">
3495
3630
  ${input ? `
3496
3631
  <div class="aparte-tool-part" data-part="input">
@@ -3503,7 +3638,7 @@ function drawDefault(segment, behind2) {
3503
3638
  <div class="aparte-tool-part-body" role="region" tabindex="0" aria-label="${escapeAttr(cfg.t(outcome.key))}"><pre><code>${escapeHtml(outcome.text)}</code></pre></div>
3504
3639
  </div>` : ""}
3505
3640
  </div>
3506
- </details>
3641
+ ${rowEnd}
3507
3642
  `;
3508
3643
  }
3509
3644
  const toolCallRenderer = {
@@ -3516,12 +3651,13 @@ const toolCallRenderer = {
3516
3651
  injectToolRendererStyles(name, customRenderer);
3517
3652
  const out = customRenderer.render(segment);
3518
3653
  if (out instanceof HTMLElement) {
3519
- drawnBy.set(out, customRenderer);
3520
- behind.set(out, customRenderer);
3654
+ drawnBy$1.set(out, customRenderer);
3655
+ behind$1.set(out, customRenderer);
3521
3656
  }
3522
3657
  return out || placeholderMarkup(segment);
3523
3658
  }
3524
- return drawDefault(segment, behindOf(segment));
3659
+ const line = toolLineOf(segment, contextConfig());
3660
+ return drawDefault(segment, behindOf(segment, line), line);
3525
3661
  },
3526
3662
  /**
3527
3663
  * The pill's glyphs, and the label it wears while a person is deciding.
@@ -3534,18 +3670,21 @@ const toolCallRenderer = {
3534
3670
  * No child node is added or removed, per the relabel contract.
3535
3671
  */
3536
3672
  relabel: (element, segment) => {
3537
- if (isPlaceholder(element)) return;
3673
+ if (isPlaceholder$1(element)) return;
3538
3674
  const cfg = contextConfig();
3539
3675
  const custom = drawerOf(element, cfg.getToolRenderer(segment.toolCall?.name) ?? null);
3540
3676
  if (custom) {
3541
3677
  custom.relabel?.(element, segment);
3542
3678
  return;
3543
3679
  }
3680
+ const line = toolLineOf(segment, cfg);
3544
3681
  const icon = element.querySelector(".aparte-tool-icon");
3545
3682
  if (icon) icon.innerHTML = iconOf(segment);
3546
- setName(element, segment);
3547
- setTarget(element, segment);
3548
- setNote(element, segment);
3683
+ setName(element, segment, line);
3684
+ setTarget(element, segment, line);
3685
+ setActivity(element, segment, line);
3686
+ setNote(element, segment, line);
3687
+ setOpen(element, line, false);
3549
3688
  const inputLabel = element.querySelector('[data-part="input"] .aparte-tool-part-label');
3550
3689
  if (inputLabel) inputLabel.textContent = cfg.t("toolInput");
3551
3690
  element.querySelector('[data-part="input"] .aparte-tool-part-body')?.setAttribute("aria-label", cfg.t("toolInput"));
@@ -3556,7 +3695,7 @@ const toolCallRenderer = {
3556
3695
  for (const button of element.querySelectorAll(".aparte-tool-copy")) relabelCopyButton(button);
3557
3696
  const appDetail = appDetailOf(element);
3558
3697
  if (appDetail) {
3559
- const behind2 = behindOf(segment);
3698
+ const behind2 = behindOf(segment, line, element);
3560
3699
  if (behind2.kind === "body") relabelBody(appDetail, behind2.body);
3561
3700
  }
3562
3701
  const statusEl = element.querySelector(".aparte-tool-state");
@@ -3579,13 +3718,13 @@ const toolCallRenderer = {
3579
3718
  update: (element, segment) => {
3580
3719
  const status = segment.status ?? "pending";
3581
3720
  const hidden = contextConfig().isToolHidden(segment.toolCall?.name ?? "tool");
3582
- if (hidden && isPlaceholder(element)) {
3721
+ if (hidden && isPlaceholder$1(element)) {
3583
3722
  element.setAttribute("data-status", status);
3584
3723
  return;
3585
3724
  }
3586
3725
  const custom = hidden ? null : contextConfig().getToolRenderer(segment.toolCall?.name) ?? null;
3587
- const drawn2 = isPlaceholder(element) ? null : drawerOf(element, custom);
3588
- if (drawn2 && drawn2 === custom && drawn2.update && !isPlaceholder(element)) {
3726
+ const drawn2 = isPlaceholder$1(element) ? null : drawerOf(element, custom);
3727
+ if (drawn2 && drawn2 === custom && drawn2.update && !isPlaceholder$1(element)) {
3589
3728
  drawn2.update(element, segment);
3590
3729
  return;
3591
3730
  }
@@ -3599,27 +3738,36 @@ const toolCallRenderer = {
3599
3738
  element.replaceWith(rebuilt);
3600
3739
  toolCallRenderer.setup?.(rebuilt, segment);
3601
3740
  }
3741
+ return rebuilt;
3602
3742
  };
3603
- if (custom || drawn2 || hidden || isPlaceholder(element)) {
3743
+ if (custom || drawn2 || hidden || isPlaceholder$1(element)) {
3604
3744
  rebuild(toolCallRenderer.render(segment));
3605
3745
  return;
3606
3746
  }
3607
- const behind2 = behindOf(segment);
3747
+ const line = toolLineOf(segment, contextConfig());
3748
+ const behind2 = behindOf(segment, line, element);
3608
3749
  const input = behind2.kind === "parts" ? describeInput(segment) : "";
3609
3750
  const outcome = behind2.kind === "parts" ? outcomeOf(segment) : null;
3610
3751
  const wantsDetail = behind2.kind === "body" || !!input || !!outcome;
3611
3752
  const holdsAppDetail = !!appDetailOf(element);
3612
- if (wantsDetail !== (element.tagName === "DETAILS") || wantsDetail && behind2.kind === "body" !== holdsAppDetail) {
3613
- rebuild(drawDefault(segment, behind2));
3753
+ const disclosure = disclosureOf(element);
3754
+ const wrapped = !!disclosure && disclosure !== element;
3755
+ if (wantsDetail !== !!disclosure || wantsDetail && behind2.kind === "body" !== holdsAppDetail || wantsDetail && wrapped !== !!openOf(line)) {
3756
+ const wasOpen = disclosure?.open;
3757
+ const now = rebuild(drawDefault(segment, behind2, line));
3758
+ const next = now && wasOpen !== void 0 ? disclosureOf(now) : null;
3759
+ if (next && wasOpen !== void 0) next.open = wasOpen;
3614
3760
  return;
3615
3761
  }
3616
3762
  element.setAttribute("data-status", status);
3617
3763
  const badge = element.querySelector(".aparte-tool-state");
3618
3764
  if (badge) badge.innerHTML = stateBadge(segment);
3619
3765
  setQuiet(element, segment);
3620
- setName(element, segment);
3621
- setTarget(element, segment);
3622
- setNote(element, segment);
3766
+ setName(element, segment, line);
3767
+ setTarget(element, segment, line);
3768
+ setActivity(element, segment, line);
3769
+ setNote(element, segment, line);
3770
+ setOpen(element, line, true);
3623
3771
  if (behind2.kind === "body") {
3624
3772
  setBody(element, behind2.body);
3625
3773
  return;
@@ -3631,11 +3779,15 @@ const toolCallRenderer = {
3631
3779
  setup: (element, segment) => {
3632
3780
  const hidden = contextConfig().isToolHidden(segment.toolCall?.name ?? "tool");
3633
3781
  const customRenderer = hidden ? void 0 : contextConfig().getToolRenderer(segment.toolCall?.name);
3634
- if (customRenderer) behind.set(element, customRenderer);
3635
- if (isPlaceholder(element)) return;
3782
+ if (customRenderer) behind$1.set(element, customRenderer);
3783
+ if (isPlaceholder$1(element)) return;
3784
+ if (!customRenderer) {
3785
+ setOpen(element, toolLineOf(segment, contextConfig()), false);
3786
+ wireOpen(element);
3787
+ }
3636
3788
  wireParts(element);
3637
3789
  highlightParts(element);
3638
- if (customRenderer) drawnBy.set(element, customRenderer);
3790
+ if (customRenderer) drawnBy$1.set(element, customRenderer);
3639
3791
  customRenderer?.setup?.(element, segment);
3640
3792
  },
3641
3793
  /**
@@ -3644,10 +3796,10 @@ const toolCallRenderer = {
3644
3796
  * all the same, and the stream that caused it is not interrupted.
3645
3797
  */
3646
3798
  cleanup: (element, segment) => {
3647
- behind.delete(element);
3648
- const custom = drawnBy.get(element);
3799
+ behind$1.delete(element);
3800
+ const custom = drawnBy$1.get(element);
3649
3801
  if (!custom) return;
3650
- drawnBy.delete(element);
3802
+ drawnBy$1.delete(element);
3651
3803
  try {
3652
3804
  custom.cleanup?.(element, segment);
3653
3805
  } catch (err) {
@@ -3659,6 +3811,88 @@ const toolCallRenderer = {
3659
3811
  // has no other way onto the page.
3660
3812
  getStyles: () => ""
3661
3813
  };
3814
+ function placeholder(segment) {
3815
+ const el2 = document.createElement("div");
3816
+ el2.className = "aparte-segment aparte-segment-activity";
3817
+ el2.setAttribute("data-segment-id", segment.id);
3818
+ el2.setAttribute("data-activity-type", segment.activityType);
3819
+ el2.hidden = true;
3820
+ return el2;
3821
+ }
3822
+ const isPlaceholder = (element) => element.hidden && element.classList.contains("aparte-segment-activity") && element.childElementCount === 0;
3823
+ const drawnBy = /* @__PURE__ */ new WeakMap();
3824
+ const behind = /* @__PURE__ */ new WeakMap();
3825
+ function activityRendererThatDrew(element) {
3826
+ return behind.get(element) ?? null;
3827
+ }
3828
+ const rendererOf = (segment) => contextConfig().getActivityRenderer(segment.activityType) ?? null;
3829
+ const activityRenderer = {
3830
+ type: "activity",
3831
+ render: (segment) => {
3832
+ const custom = rendererOf(segment);
3833
+ if (!custom) return placeholder(segment);
3834
+ const out = custom.render(segment);
3835
+ if (out instanceof HTMLElement) {
3836
+ drawnBy.set(out, custom);
3837
+ behind.set(out, custom);
3838
+ return out;
3839
+ }
3840
+ return out.trim() ? out : placeholder(segment);
3841
+ },
3842
+ setup: (element, segment) => {
3843
+ const custom = rendererOf(segment);
3844
+ if (!custom) return;
3845
+ behind.set(element, custom);
3846
+ if (isPlaceholder(element)) return;
3847
+ drawnBy.set(element, custom);
3848
+ custom.setup?.(element, segment);
3849
+ },
3850
+ /**
3851
+ * The agent sent it again. The renderer that drew it patches it, when it can and is still
3852
+ * the one registered; otherwise it is drawn again here, and the bubble follows the element.
3853
+ */
3854
+ update: (element, segment) => {
3855
+ const custom = rendererOf(segment);
3856
+ const drawn2 = drawnBy.get(element) ?? null;
3857
+ if (drawn2 && drawn2 === custom && drawn2.update) {
3858
+ drawn2.update(element, segment);
3859
+ return;
3860
+ }
3861
+ if (!custom && !drawn2 && isPlaceholder(element)) {
3862
+ element.setAttribute("data-activity-type", segment.activityType);
3863
+ return;
3864
+ }
3865
+ const out = activityRenderer.render(segment);
3866
+ let rebuilt;
3867
+ if (typeof out === "string") {
3868
+ const tpl = document.createElement("template");
3869
+ tpl.innerHTML = out.trim();
3870
+ rebuilt = tpl.content.firstElementChild;
3871
+ } else {
3872
+ rebuilt = out;
3873
+ }
3874
+ if (!rebuilt) return;
3875
+ if (!rebuilt.hasAttribute("data-segment-id")) rebuilt.setAttribute("data-segment-id", segment.id);
3876
+ activityRenderer.cleanup?.(element, segment);
3877
+ element.replaceWith(rebuilt);
3878
+ activityRenderer.setup?.(rebuilt, segment);
3879
+ },
3880
+ relabel: (element, segment) => {
3881
+ drawnBy.get(element)?.relabel?.(element, segment);
3882
+ },
3883
+ /** The element leaves for good: the renderer that drew it cleans up. A cleanup that throws is reported, nothing more. */
3884
+ cleanup: (element, segment) => {
3885
+ behind.delete(element);
3886
+ const custom = drawnBy.get(element);
3887
+ if (!custom) return;
3888
+ drawnBy.delete(element);
3889
+ try {
3890
+ custom.cleanup?.(element, segment);
3891
+ } catch (err) {
3892
+ console.error("[aparte] an activity renderer's cleanup threw", err);
3893
+ }
3894
+ }
3895
+ };
3662
3896
  const registries = /* @__PURE__ */ new WeakMap();
3663
3897
  function registryFor(config) {
3664
3898
  let reg = registries.get(config);
@@ -3797,11 +4031,14 @@ const DEFAULT_RENDERERS = [
3797
4031
  thinkingRenderer,
3798
4032
  codeRenderer,
3799
4033
  errorRenderer,
3800
- toolCallRenderer
4034
+ toolCallRenderer,
4035
+ activityRenderer
3801
4036
  ];
3802
4037
  const toolRefusal = toolRefusal$1;
4038
+ const runSubAgent = runSubAgent$1;
4039
+ const startSubAgent = startSubAgent$1;
3803
4040
  function createStreamAdapter(opts) {
3804
- const { target, config, messageId, targetId } = opts;
4041
+ const { target, config, messageId, targetId, observe: notify = true } = opts;
3805
4042
  let parser = new AparteStreamParser({ blocks: config.getStreamBlocks() });
3806
4043
  let streaming = /* @__PURE__ */ new Set();
3807
4044
  let thinkingId = null;
@@ -3830,20 +4067,20 @@ function createStreamAdapter(opts) {
3830
4067
  return { id, text, start, length: content.length, citations: [] };
3831
4068
  }).filter((s) => s.text);
3832
4069
  if (spans.length === 0) return;
3833
- const placed = /* @__PURE__ */ new Set();
4070
+ const placed2 = /* @__PURE__ */ new Set();
3834
4071
  for (const citation of callCitations) {
3835
4072
  const span = spans.find((s) => s.start >= 0 && citation.end > s.start && citation.end <= s.start + s.length);
3836
4073
  if (!span) continue;
3837
4074
  const end = citation.end - span.start;
3838
4075
  const start = citation.start === void 0 ? void 0 : Math.max(0, Math.min(end, citation.start - span.start));
3839
4076
  span.citations.push({ ...citation, end, ...start === void 0 ? {} : { start } });
3840
- for (const id of citation.sources) placed.add(id);
4077
+ for (const id of citation.sources) placed2.add(id);
3841
4078
  }
3842
4079
  const last = spans[spans.length - 1];
3843
4080
  const now = /* @__PURE__ */ new Set();
3844
4081
  for (const span of spans) {
3845
4082
  const named = new Set(span.citations.flatMap((c) => c.sources));
3846
- const sources2 = callSources.filter((s) => named.has(s.id) || span === last && !placed.has(s.id));
4083
+ const sources2 = callSources.filter((s) => named.has(s.id) || span === last && !placed2.has(s.id));
3847
4084
  if (sources2.length === 0) {
3848
4085
  if (given.has(span.id)) target.updateSegment?.(span.id, { sources: void 0, citations: void 0 });
3849
4086
  continue;
@@ -3855,13 +4092,52 @@ function createStreamAdapter(opts) {
3855
4092
  };
3856
4093
  const settleThinking = (fold) => {
3857
4094
  if (!thinkingId || thinkingCollapsed) return;
3858
- const chatConfig = typeof Element !== "undefined" && target instanceof Element ? resolveConfig(target) : config;
3859
- const keepOpen = !fold || chatConfig.getSegmentDefaults("thinking")?.collapsed === false;
4095
+ const chatConfig2 = typeof Element !== "undefined" && target instanceof Element ? resolveConfig(target) : config;
4096
+ const keepOpen = !fold || chatConfig2.getSegmentDefaults("thinking")?.collapsed === false;
3860
4097
  target.updateSegment?.(thinkingId, keepOpen ? { isStreaming: false } : { collapsed: true, isStreaming: false });
3861
4098
  thinkingCollapsed = true;
3862
4099
  };
3863
- return (e) => {
4100
+ const steps = [];
4101
+ let shownStep = null;
4102
+ const showStep = () => {
4103
+ const next = steps.at(-1) ?? null;
4104
+ if (next === shownStep) return;
4105
+ shownStep = next;
4106
+ target.setStep?.(messageId, next);
4107
+ };
4108
+ const endSteps = () => {
4109
+ steps.length = 0;
4110
+ showStep();
4111
+ };
4112
+ const flushText = () => {
4113
+ const finals = parser.finalize();
4114
+ for (const s of finals) {
4115
+ noteText(s);
4116
+ if (!streaming.has(s.id)) target.addSegment?.(s);
4117
+ else if ("content" in s) target.updateSegment?.(s.id, segmentContentUpdate(s));
4118
+ }
4119
+ placeSources();
4120
+ };
4121
+ const activities = /* @__PURE__ */ new Set();
4122
+ const placed = (id) => {
4123
+ if (activities.has(id)) return true;
4124
+ const existing = target.getMessage ? target.getMessage(messageId)?.segments : target.segments;
4125
+ if (!existing?.some((s) => s.id === id)) return false;
4126
+ activities.add(id);
4127
+ return true;
4128
+ };
4129
+ const handle = (e) => {
3864
4130
  switch (e.type) {
4131
+ case "step-start":
4132
+ steps.push(e.name);
4133
+ showStep();
4134
+ break;
4135
+ case "step-end": {
4136
+ const at = steps.lastIndexOf(e.name);
4137
+ if (at >= 0) steps.splice(at, 1);
4138
+ showStep();
4139
+ break;
4140
+ }
3865
4141
  case "run-start":
3866
4142
  target.updateMessage?.(messageId, { status: "streaming" });
3867
4143
  break;
@@ -3920,14 +4196,19 @@ function createStreamAdapter(opts) {
3920
4196
  } else if (result.segments.length === 0) ;
3921
4197
  break;
3922
4198
  }
3923
- case "text-flush": {
3924
- const finals = parser.finalize();
3925
- for (const s of finals) {
3926
- noteText(s);
3927
- if (!streaming.has(s.id)) target.addSegment?.(s);
3928
- else if ("content" in s) target.updateSegment?.(s.id, segmentContentUpdate(s));
4199
+ case "text-flush":
4200
+ flushText();
4201
+ break;
4202
+ case "activity": {
4203
+ const id = `activity-${e.id}`;
4204
+ if (placed(id)) {
4205
+ target.updateSegment?.(id, { activityType: e.activityType, content: e.content });
4206
+ break;
3929
4207
  }
3930
- placeSources();
4208
+ activities.add(id);
4209
+ flushText();
4210
+ const segment = { id, type: "activity", activityId: e.id, activityType: e.activityType, content: e.content };
4211
+ target.addSegment?.(segment);
3931
4212
  break;
3932
4213
  }
3933
4214
  case "sources": {
@@ -4002,11 +4283,14 @@ function createStreamAdapter(opts) {
4002
4283
  }
4003
4284
  break;
4004
4285
  case "run-aborted":
4286
+ endSteps();
4005
4287
  dispatchLifecycleEvent(target, "aparte-message-aborted", { messageId }, targetId);
4006
4288
  break;
4007
4289
  case "run-suspended": {
4290
+ endSteps();
4008
4291
  const ticket = e.ticket;
4009
4292
  for (const p of e.pending) {
4293
+ if (p.agentId != null) continue;
4010
4294
  const id = `tool-${p.toolCallId}`;
4011
4295
  const deferred2 = { reason: p.reason, ...typeof ticket === "string" ? { ticket } : {} };
4012
4296
  target.updateSegment?.(id, { deferred: deferred2 });
@@ -4022,6 +4306,7 @@ function createStreamAdapter(opts) {
4022
4306
  break;
4023
4307
  }
4024
4308
  case "run-done":
4309
+ endSteps();
4025
4310
  target.updateMessage?.(messageId, {
4026
4311
  status: "completed",
4027
4312
  ...e.finishReason ? { finishReason: e.finishReason } : {}
@@ -4035,7 +4320,47 @@ function createStreamAdapter(opts) {
4035
4320
  break;
4036
4321
  }
4037
4322
  };
4323
+ const chatConfig = () => typeof Element !== "undefined" && target instanceof Element ? resolveConfig(target) : config;
4324
+ const reported2 = /* @__PURE__ */ new Set();
4325
+ const observe = (e, own) => {
4326
+ const observers2 = /* @__PURE__ */ new Set();
4327
+ for (const c of /* @__PURE__ */ new Set([own, config, aparteGlobalConfig])) {
4328
+ for (const fn of c.getRunEventObservers()) observers2.add(fn);
4329
+ }
4330
+ if (observers2.size === 0) return false;
4331
+ const ctx = { messageId, target, ...targetId !== void 0 ? { targetId } : {}, config: own };
4332
+ for (const fn of observers2) {
4333
+ try {
4334
+ fn(e, ctx);
4335
+ } catch (error) {
4336
+ if (!reported2.has(fn)) {
4337
+ reported2.add(fn);
4338
+ console.error("[aparte] A run-event observer threw; the reply goes on without it. Further throws from it in this reply are not reported.", error);
4339
+ }
4340
+ }
4341
+ }
4342
+ return true;
4343
+ };
4344
+ return (e) => {
4345
+ const own = chatConfig();
4346
+ const observed2 = !notify || observe(e, own);
4347
+ const agentId = e.agentId;
4348
+ if (agentId == null && e.type !== "agent-start" && e.type !== "agent-end") {
4349
+ handle(e);
4350
+ return;
4351
+ }
4352
+ if (!observed2 && !warnedConfigs.has(own)) {
4353
+ warnedConfigs.add(own);
4354
+ console.warn(
4355
+ `[aparte] A sub-agent's events arrived (agent "${String(agentId)}") and nothing draws them: they are kept out of the reply and not shown. Add @aparte/plugin-subagents (setupSubagents()) to show one line per sub-agent, or hear them with config.observeRunEvents().`
4356
+ );
4357
+ }
4358
+ if (e.type === "tool-awaiting-approval") {
4359
+ dispatchLifecycleEvent(target, "aparte-tool-approval-request", { toolCallId: e.toolCallId, toolName: e.name, input: e.input, agentId }, targetId);
4360
+ }
4361
+ };
4038
4362
  }
4363
+ const warnedConfigs = /* @__PURE__ */ new WeakSet();
4039
4364
  function readableToAsyncIterable(stream, signal) {
4040
4365
  return {
4041
4366
  [Symbol.asyncIterator]() {
@@ -4267,7 +4592,7 @@ function createAparteAgentHandler(options) {
4267
4592
  },
4268
4593
  toolLookup: (name) => {
4269
4594
  const t = offered.has(name) ? tools.get(name) : void 0;
4270
- return t ? (call, signal) => t.handler(call, signal, { request: req }) : void 0;
4595
+ return t ? (call, signal, run2) => t.handler(call, signal, run2 ? { request: req, run: run2 } : { request: req }) : void 0;
4271
4596
  },
4272
4597
  toolConfigLookup: (name) => {
4273
4598
  if (!offered.has(name)) return void 0;
@@ -4294,7 +4619,12 @@ function createAparteAgentHandler(options) {
4294
4619
  emitter,
4295
4620
  signal: run.signal,
4296
4621
  ...options.maxTurns !== void 0 ? { maxTurns: options.maxTurns } : {},
4297
- ...options.toolTimeoutMs !== void 0 ? { toolTimeoutMs: options.toolTimeoutMs } : {}
4622
+ ...options.toolTimeoutMs !== void 0 ? { toolTimeoutMs: options.toolTimeoutMs } : {},
4623
+ // Ids that cannot repeat from one request to the next, as the browser
4624
+ // client mints them. The engine's default is a counter per run, and every
4625
+ // request is a run: the resume of a paused reply named its first sub-agent
4626
+ // `agent-0` again, and the page took it for the first one resumed.
4627
+ idGen: (prefix) => prefix === "synthetic-tool" ? uuid() : `${prefix}-${uuid()}`
4298
4628
  }).then(async () => {
4299
4629
  await pendingWrite;
4300
4630
  close();
@@ -4951,9 +5281,15 @@ class AparteConfig {
4951
5281
  /** Bumped by `reset()`: a restore function from before it must not undo what came after. */
4952
5282
  _overrideGeneration = 0;
4953
5283
  _toolDisplays = new ToolTable();
5284
+ /** By activity type — see {@link registerActivityRenderer}. */
5285
+ _activityRenderers = /* @__PURE__ */ new Map();
5286
+ /** What a plugin says about a call, read after the app's display — see {@link setToolLineProvider}. */
5287
+ _toolLineProvider = null;
4954
5288
  /** Tagged blocks the stream parser recognises in the prose — see {@link registerStreamBlock}. */
4955
5289
  _streamBlocks = /* @__PURE__ */ new Map();
4956
5290
  _segmentDefaults = /* @__PURE__ */ new Map();
5291
+ /** One entry per registration, so each remover takes back its own — see {@link observeRunEvents}. */
5292
+ _runEventObservers = [];
4957
5293
  // Host handlers — what the app declares it can actually complete.
4958
5294
  _hostHandlers = { ...APARTE_DEFAULT_HOST_HANDLERS };
4959
5295
  // Bubble Actions — APARTE_DEFAULT_BUBBLE_ACTIONS is the single source of truth
@@ -6082,6 +6418,45 @@ class AparteConfig {
6082
6418
  this._toolRenderers.delete(match);
6083
6419
  notifyRenderersChanged(this);
6084
6420
  }
6421
+ /**
6422
+ * Draw one type of agent activity — the structured progress an agent reports while it
6423
+ * works ("3 of 5 sources read"), which reaches the reply as an `activity` segment and is
6424
+ * updated in place each time the agent sends it again. Returns the function that takes
6425
+ * this renderer off again (it changes nothing once another one has replaced it).
6426
+ *
6427
+ * An activity with no renderer for its type is kept on the message and draws nothing:
6428
+ * no row, no room, no orphan header on a turn that holds nothing else. It is never sent
6429
+ * to the model either way. Activities already on screen follow a registration.
6430
+ *
6431
+ * @example
6432
+ * const off = aparteGlobalConfig.registerActivityRenderer('search-progress', {
6433
+ * render: (segment) => {
6434
+ * const el = document.createElement('p');
6435
+ * const { read, of } = segment.content as { read: number; of: number };
6436
+ * el.textContent = `${read} of ${of} sources read`;
6437
+ * return el;
6438
+ * },
6439
+ * update: (el, segment) => {
6440
+ * const { read, of } = segment.content as { read: number; of: number };
6441
+ * el.textContent = `${read} of ${of} sources read`;
6442
+ * },
6443
+ * });
6444
+ */
6445
+ registerActivityRenderer(activityType, renderer) {
6446
+ if (this._activityRenderers.get(activityType) !== renderer) {
6447
+ this._activityRenderers.set(activityType, renderer);
6448
+ notifyRenderersChanged(this);
6449
+ }
6450
+ return () => {
6451
+ if (this._activityRenderers.get(activityType) !== renderer) return;
6452
+ this._activityRenderers.delete(activityType);
6453
+ notifyRenderersChanged(this);
6454
+ };
6455
+ }
6456
+ /** The renderer registered for an activity type, or undefined. */
6457
+ getActivityRenderer(activityType) {
6458
+ return this._activityRenderers.get(activityType);
6459
+ }
6085
6460
  /** The renderer that draws a tool named `toolName` — exact, pattern or `'*'` — or undefined. */
6086
6461
  getToolRenderer(toolName) {
6087
6462
  return this._toolRenderers.resolve(toolName)?.value;
@@ -6162,6 +6537,35 @@ class AparteConfig {
6162
6537
  const rank = { exact: 2, pattern: 1, any: 0 };
6163
6538
  return !renderer || rank[renderer.level] <= rank[display.level];
6164
6539
  }
6540
+ /**
6541
+ * Say more about a call than its display does: what ran it, what it is doing now, a
6542
+ * short note after its state. For a plugin that knows a call from the inside — a
6543
+ * sub-agent's line is the line of the call that opened it.
6544
+ *
6545
+ * One provider per config; `null` removes it. It is consulted AFTER the app's display,
6546
+ * field by field, so the app always wins: `label` and `target` are read when the display
6547
+ * gives none, `details` when the display has no `details` key. `activity`, a second
6548
+ * line under the name, and `note` show in every state they are given: give `activity` for
6549
+ * the call's whole life, or never, or the row changes height. A function, called whenever the
6550
+ * row is drawn, updated or relabelled — never text stored on the segment — so its words
6551
+ * follow a language switch. One that throws, or returns nothing, leaves the default
6552
+ * line. A chat with a config of its own and no provider reads {@link aparteGlobalConfig}'s.
6553
+ *
6554
+ * @example
6555
+ * aparteGlobalConfig.setToolLineProvider((segment) =>
6556
+ * segment.toolCall.name === 'delegate' ? { activity: 'Reading the parser', note: '3 tools' } : undefined);
6557
+ */
6558
+ setToolLineProvider(provider) {
6559
+ if (this._toolLineProvider === provider) return;
6560
+ this._toolLineProvider = provider;
6561
+ bumpRenderingVersion(this);
6562
+ this._notify();
6563
+ }
6564
+ /** The tool-line provider this config reads: its own, else the page's. */
6565
+ getToolLineProvider() {
6566
+ if (this._toolLineProvider || this === aparteGlobalConfig) return this._toolLineProvider;
6567
+ return aparteGlobalConfig._toolLineProvider;
6568
+ }
6165
6569
  /** Drop one field of the entry under `match`, and the entry when nothing is left. */
6166
6570
  _dropToolDisplayField(match, field) {
6167
6571
  const entry = this._toolDisplays.get(match);
@@ -6259,6 +6663,33 @@ class AparteConfig {
6259
6663
  getStreamBlocks() {
6260
6664
  return Array.from(this._streamBlocks.values());
6261
6665
  }
6666
+ /**
6667
+ * Hear every event of a reply's run, before the reply handles it — including the
6668
+ * events of its sub-agents, which the reply never draws: an event that carries an
6669
+ * `agentId`, and `agent-start` / `agent-end`, are kept out of the reply whether anyone
6670
+ * observes them or not. This is how a plugin draws a sub-agent's conversation.
6671
+ *
6672
+ * A chat hears the observers of its own config first, then those of
6673
+ * {@link aparteGlobalConfig}, the way a segment renderer is found: one registered once on
6674
+ * the page reaches a chat that carries a config of its own. An observer that throws is
6675
+ * reported once per reply, and the reply goes on. Returns the function that removes it.
6676
+ *
6677
+ * @example
6678
+ * const stop = aparteGlobalConfig.observeRunEvents((event, { messageId }) => {
6679
+ * if (event.type === 'agent-start') console.info(`${messageId}: ${event.name} started`);
6680
+ * });
6681
+ */
6682
+ observeRunEvents(observer) {
6683
+ const entry = { fn: observer };
6684
+ this._runEventObservers.push(entry);
6685
+ return () => {
6686
+ this._runEventObservers = this._runEventObservers.filter((e) => e !== entry);
6687
+ };
6688
+ }
6689
+ /** The observers registered on this config, in registration order (read by the stream adapter). */
6690
+ getRunEventObservers() {
6691
+ return this._runEventObservers.map((e) => e.fn);
6692
+ }
6262
6693
  // ─────────────────────────────────────────────────────────────────────────
6263
6694
  // Conversation Manager (optional, agnostic persistence layer)
6264
6695
  // ─────────────────────────────────────────────────────────────────────────
@@ -6404,10 +6835,10 @@ class AparteConfig {
6404
6835
  }
6405
6836
  /**
6406
6837
  * Put the configuration back to its defaults: the providers and the selected model,
6407
- * the tools with their renderers and summaries, the renderers and render hooks, the
6838
+ * the tools with their renderers and summaries, the tool-line provider, the renderers and render hooks, the
6408
6839
  * Markdown and highlight providers, the code-language renderers, the sanitizer, the system prompt, the locale, icons,
6409
6840
  * avatars, actions and host handlers, the conversation manager, the question presenters
6410
- * and their queue. Three things stay: the transport, the key sources added with
6841
+ * and their queue, the run-event observers. Three things stay: the transport, the key sources added with
6411
6842
  * {@link AparteConfig.registerKeyProvider | registerKeyProvider()} (an `AparteClient`'s
6412
6843
  * `keyResolver` among them), and the {@link AparteConfig.subscribe | subscribe()} listeners.
6413
6844
  */
@@ -6442,10 +6873,13 @@ class AparteConfig {
6442
6873
  this._tools.clear();
6443
6874
  this._toolRenderers.clear();
6444
6875
  this._toolRendererOverrides.clear();
6876
+ this._activityRenderers.clear();
6445
6877
  this._overrideGeneration++;
6446
6878
  notifyRenderersChanged(this);
6447
6879
  this._toolDisplays.clear();
6880
+ this._toolLineProvider = null;
6448
6881
  this._streamBlocks.clear();
6882
+ this._runEventObservers = [];
6449
6883
  this._modelConfig = {};
6450
6884
  this._requireModelSelection = false;
6451
6885
  this._elicitationAllowOther = true;
@@ -7150,9 +7584,6 @@ class AparteConversationManager {
7150
7584
  return (msg.content ?? "").trim();
7151
7585
  }
7152
7586
  }
7153
- function cssEscape(value) {
7154
- return value.replace(/["\\]/g, "\\$&").replace(/[\n\r\f]/g, (c) => `\\${c.charCodeAt(0).toString(16)} `);
7155
- }
7156
7587
  function filesToAttachments(files) {
7157
7588
  return files.map((file) => ({
7158
7589
  id: uuid(),
@@ -7876,6 +8307,8 @@ class AparteChatHost {
7876
8307
  options;
7877
8308
  /** Id of the assistant message currently streaming (null when idle). */
7878
8309
  _streamingId = null;
8310
+ /** The step the streaming reply is on: kept until its bubble is painted, never in the list. */
8311
+ _step = null;
7879
8312
  /**
7880
8313
  * The message object each bubble was last drawn from, by id (skip-rerender cache).
7881
8314
  *
@@ -8147,6 +8580,7 @@ class AparteChatHost {
8147
8580
  if (updates.status) {
8148
8581
  this._bubbleById(messageId)?.updateMessage?.({ status: updates.status });
8149
8582
  }
8583
+ if (this._step?.messageId === messageId && isTerminalStatus(merged.status)) this._step = null;
8150
8584
  if (index !== msgs.length - 1 && RENDERED_FIELDS.some((key) => key in updates)) {
8151
8585
  this._renderedIds.delete(messageId);
8152
8586
  const bubble = this._bubbleById(messageId);
@@ -8160,6 +8594,15 @@ class AparteChatHost {
8160
8594
  }
8161
8595
  }
8162
8596
  }
8597
+ /**
8598
+ * Say the step the agent is on in the reply's waiting indicator, or `null` for none. Live
8599
+ * only: never written into the message list. Kept for a bubble the framework has not
8600
+ * painted yet, and given to it when it is.
8601
+ */
8602
+ setStep(messageId, name) {
8603
+ this._step = name === null ? null : { messageId, name };
8604
+ this._bubbleById(messageId)?.setStep?.(name);
8605
+ }
8163
8606
  /** Append/replace the last message content (streaming text). */
8164
8607
  updateLastMessage(content, options) {
8165
8608
  if (options?.append) this.binding.onTypingChange?.(false);
@@ -8464,6 +8907,7 @@ class AparteChatHost {
8464
8907
  if (!bubble) return;
8465
8908
  populateBubbleFromMessage(bubble, message);
8466
8909
  this._renderedIds.set(message.id, message);
8910
+ if (this._step?.messageId === message.id) bubble.setStep?.(this._step.name);
8467
8911
  });
8468
8912
  this._checkpointState.reapply();
8469
8913
  }
@@ -8582,6 +9026,7 @@ class AparteChatHost {
8582
9026
  host2["updateLastMessage"] = (c, o) => this.updateLastMessage(c, o);
8583
9027
  host2["addSegment"] = (s) => this.addSegment(s);
8584
9028
  host2["updateSegment"] = (id, u) => this.updateSegment(id, u);
9029
+ host2["setStep"] = (id, name) => this.setStep(id, name);
8585
9030
  host2["removeSegment"] = (id) => this.removeSegment(id);
8586
9031
  host2["appendToSegment"] = (id, c) => this.appendToSegment(id, c);
8587
9032
  host2["getMessages"] = () => this.getMessages();
@@ -8701,17 +9146,18 @@ function answerOf(segment) {
8701
9146
  return STOPPED_TOOL_TEXT;
8702
9147
  }
8703
9148
  const isOpenDeferred = (segment) => segment.type === "tool_call" && Boolean(segment.deferred) && (segment.status === "awaiting-approval" || segment.status === "pending");
8704
- function wireTurns(message, textOf, options = {}) {
9149
+ const isLeftOpen = (segment) => segment.type === "tool_call" && (segment.status === "pending" || segment.status === "awaiting-approval");
9150
+ function wireTurns(message, textOf2, options = {}) {
8705
9151
  const segments = message.segments ?? [];
8706
9152
  if (message.role !== "assistant" || !segments.some((s) => s.type === "tool_call")) {
8707
- const content = textOf(segments) || (typeof message.content === "string" ? message.content : "");
9153
+ const content = textOf2(segments) || (typeof message.content === "string" ? message.content : "");
8708
9154
  return content ? [{ role: message.role, content }] : [];
8709
9155
  }
8710
9156
  const out = [];
8711
9157
  let texts = [];
8712
9158
  let calls = [];
8713
9159
  const flush = () => {
8714
- const content = textOf(texts);
9160
+ const content = textOf2(texts);
8715
9161
  if (calls.length === 0) {
8716
9162
  if (content) out.push({ role: "assistant", content });
8717
9163
  } else {
@@ -8721,7 +9167,7 @@ function wireTurns(message, textOf, options = {}) {
8721
9167
  toolCalls: calls.map((c) => ({ id: c.toolCall.id, name: c.toolCall.name, input: c.toolCall.input }))
8722
9168
  });
8723
9169
  for (const c of calls) {
8724
- if (options.openDeferred && isOpenDeferred(c)) continue;
9170
+ if (options.openDeferred && isLeftOpen(c)) continue;
8725
9171
  out.push({ role: "tool", content: answerOf(c), toolCallId: c.toolCall.id, toolName: c.toolCall.name });
8726
9172
  }
8727
9173
  }
@@ -8732,7 +9178,7 @@ function wireTurns(message, textOf, options = {}) {
8732
9178
  for (const segment of segments) {
8733
9179
  if (segment.type === "tool_call") {
8734
9180
  calls.push(segment);
8735
- if (options.openDeferred && isOpenDeferred(segment)) open = true;
9181
+ if (options.openDeferred && isLeftOpen(segment)) open = true;
8736
9182
  } else {
8737
9183
  if (calls.length > 0 && !open) flush();
8738
9184
  texts.push(segment);
@@ -8755,7 +9201,7 @@ function segmentsToWireText(segments) {
8755
9201
  parts.push(`${fence}${lang}
8756
9202
  ${content ?? ""}
8757
9203
  ${fence}`);
8758
- } else if (segment.type === "thinking" || segment.type === "tool_call" || segment.type === "error") {
9204
+ } else if (segment.type === "thinking" || segment.type === "tool_call" || segment.type === "error" || segment.type === "activity") {
8759
9205
  continue;
8760
9206
  } else if (typeof content === "string" && content) {
8761
9207
  const wire = segment.wire;
@@ -8878,15 +9324,6 @@ function measureContext(input) {
8878
9324
  if (reply && unchanged) return result(nextRequestTokens(reply, k), false);
8879
9325
  return result(Math.round(k * total), true);
8880
9326
  }
8881
- function eventOrigin(e) {
8882
- return e.composedPath?.()[0] ?? e.target;
8883
- }
8884
- function rootOf(node) {
8885
- return node.getRootNode();
8886
- }
8887
- function activeElementIn(node) {
8888
- return node.getRootNode().activeElement ?? document.activeElement;
8889
- }
8890
9327
  let steppedPanelSeq = 0;
8891
9328
  let _relabels = null;
8892
9329
  function onRelabel(fn) {
@@ -9212,13 +9649,6 @@ function buildPanel(message, schema, onChange) {
9212
9649
  const dismiss = el$1("div", "aparte-elic-dismiss");
9213
9650
  panel.appendChild(dismiss);
9214
9651
  if (schema.type === "object") {
9215
- let show = function(index) {
9216
- current = index;
9217
- fields.forEach((f, i) => {
9218
- f.field.el.hidden = i !== index;
9219
- });
9220
- syncNav();
9221
- };
9222
9652
  const entries = Object.entries(schema.properties);
9223
9653
  const requiredKeys = new Set(schema.required ?? entries.map(([k]) => k));
9224
9654
  const cfg = contextConfig();
@@ -9265,36 +9695,25 @@ function buildPanel(message, schema, onChange) {
9265
9695
  chip.setAttribute("role", "tab");
9266
9696
  chip.textContent = f.header?.trim() || String(i + 1);
9267
9697
  chip.dir = "auto";
9268
- chip.addEventListener("click", () => {
9269
- show(i);
9270
- f.field.focus();
9271
- });
9272
9698
  chip.id = `${scope}-tab-${i}`;
9273
9699
  f.field.el.id = `${scope}-panel-${i}`;
9274
9700
  f.field.el.setAttribute("role", "tabpanel");
9275
9701
  f.field.el.setAttribute("aria-labelledby", chip.id);
9276
9702
  chip.setAttribute("aria-controls", f.field.el.id);
9277
- chip.addEventListener("keydown", (e) => {
9278
- const forward = getComputedStyle(steps).direction === "rtl" ? "ArrowLeft" : "ArrowRight";
9279
- const back = forward === "ArrowRight" ? "ArrowLeft" : "ArrowRight";
9280
- const step = e.key === forward ? 1 : e.key === back ? -1 : 0;
9281
- let next = -1;
9282
- if (step) next = (i + step + fields.length) % fields.length;
9283
- else if (e.key === "Home") next = 0;
9284
- else if (e.key === "End") next = fields.length - 1;
9285
- if (next < 0) return;
9286
- e.preventDefault();
9287
- show(next);
9288
- chips[next]?.focus();
9289
- });
9290
9703
  steps.appendChild(chip);
9291
9704
  return chip;
9292
9705
  });
9293
9706
  panel.insertBefore(steps, body);
9707
+ steps.addEventListener("aparte-tab-change", (e) => {
9708
+ current = chips.indexOf(e.detail.tab);
9709
+ });
9710
+ enhanceTabs(steps);
9711
+ steps.addEventListener("click", (e) => {
9712
+ const at = chips.indexOf(e.target.closest(".aparte-elic-step"));
9713
+ if (at >= 0 && at === current) fields[at].field.focus();
9714
+ });
9294
9715
  syncNav = () => {
9295
9716
  chips.forEach((chip, i) => {
9296
- chip.setAttribute("aria-selected", String(i === current));
9297
- chip.tabIndex = i === current ? 0 : -1;
9298
9717
  const answered = fields[i].field.isComplete();
9299
9718
  chip.toggleAttribute("data-answered", answered);
9300
9719
  const mark = chip.querySelector(".aparte-elic-step__mark");
@@ -9308,7 +9727,7 @@ function buildPanel(message, schema, onChange) {
9308
9727
  }
9309
9728
  });
9310
9729
  };
9311
- show(0);
9730
+ syncNav();
9312
9731
  return {
9313
9732
  ...api,
9314
9733
  focus: () => fields[current]?.field.focus()
@@ -9374,9 +9793,9 @@ function buildApprovalPanel(message, options, onChange, details, allowOther = tr
9374
9793
  row.setAttribute("aria-describedby", ask.id);
9375
9794
  }
9376
9795
  const labelled = [];
9377
- const textOf = (option) => typeof option.label === "function" ? option.label() : option.label;
9796
+ const textOf2 = (option) => typeof option.label === "function" ? option.label() : option.label;
9378
9797
  const descriptionOf = (option) => typeof option.description === "function" ? option.description() : option.description;
9379
- const bodyOf = (option) => optionBody(textOf(option), descriptionOf(option));
9798
+ const bodyOf = (option) => optionBody(textOf2(option), descriptionOf(option));
9380
9799
  for (const option of options) {
9381
9800
  const tone = option.tone ?? "affirm";
9382
9801
  const button = el("button", `aparte-btn aparte-btn--block aparte-btn--surface aparte-approval-option aparte-approval-option--${tone}`);
@@ -9697,6 +10116,7 @@ class AparteClient {
9697
10116
  * no DOM) or its own presenter, both strictly more capable than an id on an event.
9698
10117
  */
9699
10118
  async _askForApproval(event, signal, target) {
10119
+ const agentName = event.agent?.name?.trim();
9700
10120
  const answer = await requestUserInput({
9701
10121
  kind: "approval",
9702
10122
  /*
@@ -9716,7 +10136,9 @@ class AparteClient {
9716
10136
  };
9717
10137
  const name = toolNameOf(call, chat).text;
9718
10138
  const what = toolTargetOf(call, chat);
9719
- return (loc.approvalAsk ?? "Allow {tool}?").replace("{tool}", () => what ? `${name} ${what}` : name);
10139
+ const tool = what ? `${name} ${what}` : name;
10140
+ if (!agentName) return (loc.approvalAsk ?? "Allow {tool}?").replace("{tool}", () => tool);
10141
+ return (loc.approvalAskBy ?? "Allow {tool} for {agent}?").replace(/\{(agent|tool)\}/g, (_, key) => key === "agent" ? agentName : tool);
9720
10142
  },
9721
10143
  // A plain string, not a function: the arguments are the model's — its JSON, or
9722
10144
  // the tool's own formatter's reading of it — and do not change with the
@@ -9827,6 +10249,7 @@ class AparteClient {
9827
10249
  if (this._streamController !== streamController) this._streamController?.abort();
9828
10250
  this._streamController = streamController;
9829
10251
  this._turnsInFlight.add(messageId);
10252
+ this._agentNames.set(messageId, /* @__PURE__ */ new Map());
9830
10253
  const compactor = opts?.rebuild ? resolveConfig(targetElement).getCompactor() ?? this._config.getCompactor() : null;
9831
10254
  const turnIds = () => {
9832
10255
  const path = targetElement.getMessages?.() ?? [];
@@ -9859,7 +10282,7 @@ class AparteClient {
9859
10282
  break;
9860
10283
  }
9861
10284
  const approvedNow = /* @__PURE__ */ new Set();
9862
- const outcomes = stopped ? void 0 : await this._answerDeferred(targetElement, result.suspended.pending, streamController.signal, rowEvents, approvedAtLastPause, approvedNow);
10285
+ const outcomes = stopped ? void 0 : await this._answerDeferred(targetElement, messageId, result.suspended.pending, streamController.signal, rowEvents, approvedAtLastPause, approvedNow);
9863
10286
  approvedAtLastPause = approvedNow;
9864
10287
  if (!outcomes) {
9865
10288
  this._closeOpenCalls(targetElement, messageId);
@@ -9962,6 +10385,7 @@ class AparteClient {
9962
10385
  }
9963
10386
  } finally {
9964
10387
  this._turnsInFlight.delete(messageId);
10388
+ this._agentNames.delete(messageId);
9965
10389
  }
9966
10390
  }
9967
10391
  /**
@@ -9969,6 +10393,12 @@ class AparteClient {
9969
10393
  * load of their conversation must not start them again (`resumeDeferred`).
9970
10394
  */
9971
10395
  _turnsInFlight = /* @__PURE__ */ new Set();
10396
+ /**
10397
+ * The name of each sub-agent of a turn in flight, by reply then `agentId`, as its
10398
+ * `agent-start` gave it: what a paused run's question says about who asks. A pending
10399
+ * call carries only an `agentId`. Lives as long as the turn, never on the message.
10400
+ */
10401
+ _agentNames = /* @__PURE__ */ new Map();
9972
10402
  /**
9973
10403
  * Handle aparte-retry — add a sibling branch to the assistant message and re-stream
9974
10404
  * using the same conversation history minus the retried reply.
@@ -10515,6 +10945,8 @@ ${content}
10515
10945
  let toolCrash;
10516
10946
  const emitter = (event) => {
10517
10947
  adapter(event);
10948
+ if (event.type === "agent-start" && event.name) this._agentNames.get(messageId)?.set(event.agentId, event.name);
10949
+ if (event.agentId != null) return;
10518
10950
  if (event.type === "tool-failed") toolCrash = event.error;
10519
10951
  if (event.type === "run-done") finishReason = event.finishReason;
10520
10952
  if (event.type === "run-suspended") {
@@ -10533,7 +10965,7 @@ ${content}
10533
10965
  const handler = this._config.getToolHandler(name);
10534
10966
  if (!handler) return void 0;
10535
10967
  const context = { target: targetElement, config: this._config };
10536
- return (call, sig) => handler(call, sig, context);
10968
+ return (call, sig, run) => handler(call, sig, run ? { ...context, run } : context);
10537
10969
  };
10538
10970
  const hostOwnsDecision = Boolean(this.options.approvalResolver);
10539
10971
  const toolConfigLookup = (name) => {
@@ -10611,7 +11043,7 @@ ${content}
10611
11043
  * nobody answered — the turn was stopped, or the channel gave up — and there is no
10612
11044
  * resume. A channel that CRASHES fails the turn, as it does for a run in the page.
10613
11045
  */
10614
- async _answerDeferred(targetElement, pending2, signal, rowEvents, approvedBefore = /* @__PURE__ */ new Set(), approvedNow = /* @__PURE__ */ new Set()) {
11046
+ async _answerDeferred(targetElement, messageId, pending2, signal, rowEvents, approvedBefore = /* @__PURE__ */ new Set(), approvedNow = /* @__PURE__ */ new Set()) {
10615
11047
  const outcomes = {};
10616
11048
  const resolver = this._approvalResolverFor(targetElement, true);
10617
11049
  const refuseTheRest = (after) => {
@@ -10622,10 +11054,12 @@ ${content}
10622
11054
  for (const [index, p] of pending2.entries()) {
10623
11055
  if (signal.aborted) break;
10624
11056
  const call = { id: p.toolCallId, name: p.name, input: p.input ?? {} };
11057
+ const agentName = p.agentId === void 0 ? void 0 : this._agentNames.get(messageId)?.get(p.agentId);
11058
+ const asked2 = p.agentId === void 0 ? call : { ...call, agent: { id: p.agentId, ...agentName ? { name: agentName } : {} } };
10625
11059
  if (p.reason === "approval") {
10626
11060
  let decision;
10627
11061
  try {
10628
- decision = await resolver(call, signal);
11062
+ decision = await resolver(asked2, signal);
10629
11063
  } catch (error) {
10630
11064
  if (!signal.aborted && error?.name !== "AbortError") throw error;
10631
11065
  }
@@ -10641,7 +11075,7 @@ ${content}
10641
11075
  const key = approvalKey(call);
10642
11076
  if (!approvedBefore.has(key) && !approvedNow.has(key)) {
10643
11077
  try {
10644
- gate = await this._gateBrowserTool(call, signal, targetElement, rowEvents);
11078
+ gate = await this._gateBrowserTool(asked2, signal, targetElement, rowEvents);
10645
11079
  } catch (error) {
10646
11080
  if (!signal.aborted && error?.name !== "AbortError") throw error;
10647
11081
  gate = void 0;
@@ -10682,9 +11116,20 @@ ${content}
10682
11116
  async _gateBrowserTool(call, signal, targetElement, rowEvents) {
10683
11117
  const ruling = this.options.approvalResolver ? this._config.getTools().find((t) => t.name === call.name)?.needsApproval ? "ask" : "allow" : this._config.ruleOnToolCall(call).verdict;
10684
11118
  if (ruling === "allow") return null;
10685
- if (ruling === "ask") rowEvents?.({ type: "tool-awaiting-approval", toolCallId: call.id, name: call.name, input: call.input });
11119
+ if (ruling === "ask") {
11120
+ rowEvents?.({
11121
+ type: "tool-awaiting-approval",
11122
+ toolCallId: call.id,
11123
+ name: call.name,
11124
+ input: call.input,
11125
+ ...call.agent ? { agentId: call.agent.id } : {}
11126
+ });
11127
+ }
10686
11128
  const decision = await this._approvalResolverFor(targetElement)(call, signal) ?? void 0;
10687
- if (decision?.approved && ruling === "ask") targetElement.updateSegment?.(`tool-${call.id}`, { status: "pending" });
11129
+ if (decision?.approved && ruling === "ask") {
11130
+ if (call.agent) rowEvents?.({ type: "tool-approved", toolCallId: call.id, agentId: call.agent.id });
11131
+ else targetElement.updateSegment?.(`tool-${call.id}`, { status: "pending" });
11132
+ }
10688
11133
  return decision;
10689
11134
  }
10690
11135
  /**
@@ -10865,7 +11310,9 @@ ${content}
10865
11310
  dispatchLifecycleEvent(target, "aparte-message-error", { messageId, error }, this._targetIdOf(target));
10866
11311
  }
10867
11312
  }
11313
+ const RUN_LEVEL = /* @__PURE__ */ new Set(["run-start", "run-done", "run-aborted", "run-suspended"]);
10868
11314
  function createAgentStreamRunner(options) {
11315
+ let warnedAttributedEnd = false;
10869
11316
  return async (opts) => {
10870
11317
  const doFetch = options.fetch ?? fetch;
10871
11318
  const headers = typeof options.headers === "function" ? await options.headers() : options.headers ?? {};
@@ -10902,6 +11349,15 @@ function createAgentStreamRunner(options) {
10902
11349
  const known2 = Object.values(AparteErrorCode).includes(line.code ?? "") ? line.code : void 0;
10903
11350
  throw new AparteError(line.message || "The agent run failed.", known2 ?? AparteErrorCode.PROVIDER_ERROR, line.code ? { code: line.code } : void 0);
10904
11351
  }
11352
+ if (RUN_LEVEL.has(line.type) && line.agentId != null) {
11353
+ if (!warnedAttributedEnd) {
11354
+ warnedAttributedEnd = true;
11355
+ console.warn(
11356
+ `[aparte] The agent endpoint sent a "${line.type}" line carrying an agentId; it was dropped. A sub-agent never starts or ends the run: close it with "agent-end", and end the run with one "run-done" of its own.`
11357
+ );
11358
+ }
11359
+ continue;
11360
+ }
10905
11361
  if (line.type === "run-done" || line.type === "run-suspended") {
10906
11362
  usage = line.usage;
10907
11363
  ended = true;
@@ -11272,30 +11728,65 @@ function isAwaitingReply(message) {
11272
11728
  if (message.status === "streaming" || message.status === "pending") return true;
11273
11729
  return message.status === void 0 && message.role === "assistant" && !message.content?.trim() && !message.segments?.length;
11274
11730
  }
11275
- function placeFloating(anchor, floating, options = {}) {
11276
- const { gap = 4, margin = 8, side = "below", align = "start", rtl = false } = options;
11277
- const box = floating.getBoundingClientRect();
11278
- const clamp = (value, room, size) => Math.max(margin, Math.min(value, room - size - margin));
11279
- let top;
11280
- let left;
11281
- if (side === "beside") {
11282
- const after = anchor.right + gap;
11283
- const before = anchor.left - box.width - gap;
11284
- const [first, second] = rtl ? [before, after] : [after, before];
11285
- const fits = (x) => x >= margin && x + box.width <= window.innerWidth - margin;
11286
- left = fits(first) || !fits(second) ? first : second;
11287
- top = anchor.top;
11288
- } else {
11289
- const below = anchor.bottom + gap;
11290
- const above = anchor.top - box.height - gap;
11291
- const fitsBelow = below + box.height <= window.innerHeight - margin;
11292
- const fitsAbove = above >= margin;
11293
- if (side === "below") top = fitsBelow || !fitsAbove ? below : above;
11294
- else top = fitsAbove || !fitsBelow ? above : below;
11295
- left = align === "start" !== rtl ? anchor.left : anchor.right - box.width;
11731
+ function createSegmentList(opts) {
11732
+ const { messageId, config } = opts;
11733
+ let segments = (opts.segments ?? []).reduce((acc, segment) => {
11734
+ acc.push(adoptSegment(acc, segment, messageId));
11735
+ return acc;
11736
+ }, []);
11737
+ const listeners = /* @__PURE__ */ new Set();
11738
+ const changed = () => {
11739
+ for (const fn of [...listeners]) {
11740
+ try {
11741
+ fn();
11742
+ } catch (err) {
11743
+ console.error("[aparte] A segment-list listener threw", err);
11744
+ }
11745
+ }
11746
+ };
11747
+ return {
11748
+ get segments() {
11749
+ return segments;
11750
+ },
11751
+ onChange(fn) {
11752
+ listeners.add(fn);
11753
+ return () => {
11754
+ listeners.delete(fn);
11755
+ };
11756
+ },
11757
+ addSegment(segment) {
11758
+ const stamped = stampSegmentOnInsert(segments, segment, messageId, config?.getSegmentDefaults(segment.type));
11759
+ segments = [...segments, stamped];
11760
+ changed();
11761
+ },
11762
+ updateSegment(segmentId, updates) {
11763
+ const at = segments.findIndex((s) => s.id === segmentId);
11764
+ if (at === -1) return;
11765
+ const current = segments[at];
11766
+ const next = segments.slice();
11767
+ next[at] = mergeSegmentUpdate(current, stampSegmentOnUpdate(current, updates));
11768
+ segments = next;
11769
+ changed();
11770
+ },
11771
+ updateMessage() {
11772
+ },
11773
+ setUsage() {
11774
+ },
11775
+ dispatchEvent() {
11776
+ return true;
11777
+ }
11778
+ };
11779
+ }
11780
+ function pluralize(forms, n, tag) {
11781
+ let category = "other";
11782
+ try {
11783
+ category = new Intl.PluralRules(tag).select(n);
11784
+ } catch {
11296
11785
  }
11297
- floating.style.top = `${clamp(top, window.innerHeight, box.height)}px`;
11298
- floating.style.left = `${clamp(left, window.innerWidth, box.width)}px`;
11786
+ const options = forms.split("|");
11787
+ const named = (name) => options.find((form2) => form2.startsWith(`${name}:`));
11788
+ const form = named(category) ?? named("other") ?? forms;
11789
+ return form.slice(form.indexOf(":") + 1).replace("{n}", String(n));
11299
11790
  }
11300
11791
  const RENDERED_CONTENT = ".aparte-message-content, .aparte-segments, .aparte-content, .aparte-checkpoint__summary";
11301
11792
  function inRenderedContent(el2) {
@@ -11436,15 +11927,15 @@ function deferHydrationOf(ctor) {
11436
11927
  };
11437
11928
  }
11438
11929
  export {
11439
- isSafeUrl as $,
11930
+ isFormatAdapter as $,
11440
11931
  APARTE_CONFIG_CHANGE as A,
11441
11932
  contextConfig as B,
11442
11933
  copyText as C,
11443
11934
  createAgentStreamRunner as D,
11444
11935
  createAparteAgentHandler as E,
11445
11936
  createAparteChatHandler as F,
11446
- createStreamAdapter as G,
11447
- cssEscape as H,
11937
+ createSegmentList as G,
11938
+ createStreamAdapter as H,
11448
11939
  declineDefaultRenderers as I,
11449
11940
  defaultSanitizer as J,
11450
11941
  deferHydrationOf as K,
@@ -11457,72 +11948,74 @@ export {
11457
11948
  estimateWireTokens as R,
11458
11949
  SUGGESTIONS_BLOCK_LANGUAGE as S,
11459
11950
  filesToAttachments as T,
11460
- getAllRenderers as U,
11461
- getSegmentRenderer as V,
11462
- historyFromCheckpoint as W,
11463
- installDefaultRenderersOnce as X,
11464
- installDialogTriggersOnce as Y,
11465
- isAwaitingReply as Z,
11466
- isFormatAdapter as _,
11951
+ formatDuration as U,
11952
+ getAllRenderers as V,
11953
+ getSegmentRenderer as W,
11954
+ historyFromCheckpoint as X,
11955
+ installDefaultRenderersOnce as Y,
11956
+ installDialogTriggersOnce as Z,
11957
+ isAwaitingReply as _,
11467
11958
  APARTE_CONVERSATION_SCHEMA_VERSION as a,
11468
- isSegmentSettled as a0,
11469
- measureContext as a1,
11470
- overrideSegmentRenderer as a2,
11471
- parseAparteEventStream as a3,
11472
- parseMarkdownToSegments as a4,
11473
- placeFloating as a5,
11474
- populateBubbleFromMessage as a6,
11475
- readableToAsyncIterable as a7,
11476
- registerDefaultRenderers as a8,
11477
- registerSegmentRenderer as a9,
11478
- renderSourceList as aA,
11479
- mergeSegmentUpdate as aB,
11480
- formatDuration as aC,
11481
- writeStreamedMarkdown as aD,
11482
- replaceHighlighted as aE,
11483
- CheckpointStateWatcher as aF,
11484
- chatIdOf as aG,
11485
- stampSegmentActivity as aH,
11486
- stampSegmentOnInsert as aI,
11487
- stampSegmentOnUpdate as aJ,
11488
- renumberSegments as aK,
11489
- openSegmentIds as aL,
11490
- isTerminalStatus as aM,
11491
- adoptMessageSegments as aN,
11492
- APARTE_DERIVED_SEGMENTS as aO,
11493
- rememberConversationStatus as aP,
11494
- tellConversationStatus as aQ,
11495
- conversationStatusOf as aR,
11496
- visibleReply as aS,
11497
- usageTokens as aT,
11498
- rootOf as aU,
11499
- inRenderedContent as aV,
11500
- releaseDeferredHydration as aa,
11501
- renderCitations as ab,
11502
- renderCodeLanguages as ac,
11503
- requestUserInput as ad,
11504
- resolveConfig as ae,
11505
- revokeAttachmentUrls as af,
11506
- runWithConfig as ag,
11507
- segmentDuration as ah,
11508
- segmentTiming as ai,
11509
- setupSuggestionBlocks as aj,
11510
- subscribeConfigChange as ak,
11511
- toToolCallView as al,
11512
- toolRefusal as am,
11513
- unregisterSegmentRenderer as an,
11514
- uuid as ao,
11515
- eventOrigin as ap,
11516
- activeElementIn as aq,
11517
- gateGlide as ar,
11518
- chatBoundaryOf as as,
11519
- relabelCodeLanguages as at,
11520
- relabelCitations as au,
11521
- toolCallRenderer as av,
11522
- toolRendererThatDrew as aw,
11523
- isMountedRenderer as ax,
11524
- renderingVersionOf as ay,
11525
- onRenderersChange as az,
11959
+ isSafeUrl as a0,
11960
+ isSegmentSettled as a1,
11961
+ measureContext as a2,
11962
+ onRenderersChange as a3,
11963
+ overrideSegmentRenderer as a4,
11964
+ parseAparteEventStream as a5,
11965
+ parseMarkdownToSegments as a6,
11966
+ pluralize as a7,
11967
+ populateBubbleFromMessage as a8,
11968
+ readableToAsyncIterable as a9,
11969
+ renderingVersionOf as aA,
11970
+ renderSourceList as aB,
11971
+ mergeSegmentUpdate as aC,
11972
+ toolNameOf as aD,
11973
+ writeStreamedMarkdown as aE,
11974
+ replaceHighlighted as aF,
11975
+ toolRendererThatDrew as aG,
11976
+ activityRendererThatDrew as aH,
11977
+ CheckpointStateWatcher as aI,
11978
+ chatIdOf as aJ,
11979
+ stampSegmentActivity as aK,
11980
+ stampSegmentOnInsert as aL,
11981
+ stampSegmentOnUpdate as aM,
11982
+ renumberSegments as aN,
11983
+ openSegmentIds as aO,
11984
+ isTerminalStatus as aP,
11985
+ adoptMessageSegments as aQ,
11986
+ APARTE_DERIVED_SEGMENTS as aR,
11987
+ rememberConversationStatus as aS,
11988
+ tellConversationStatus as aT,
11989
+ conversationStatusOf as aU,
11990
+ visibleReply as aV,
11991
+ usageTokens as aW,
11992
+ inRenderedContent as aX,
11993
+ registerDefaultRenderers as aa,
11994
+ registerSegmentRenderer as ab,
11995
+ releaseDeferredHydration as ac,
11996
+ renderCitations as ad,
11997
+ renderCodeLanguages as ae,
11998
+ requestUserInput as af,
11999
+ resolveConfig as ag,
12000
+ revokeAttachmentUrls as ah,
12001
+ runSubAgent as ai,
12002
+ runWithConfig as aj,
12003
+ segmentDuration as ak,
12004
+ segmentTiming as al,
12005
+ setupSuggestionBlocks as am,
12006
+ startSubAgent as an,
12007
+ subscribeConfigChange as ao,
12008
+ toToolCallView as ap,
12009
+ toolRefusal as aq,
12010
+ unregisterSegmentRenderer as ar,
12011
+ uuid as as,
12012
+ gateGlide as at,
12013
+ chatBoundaryOf as au,
12014
+ relabelCodeLanguages as av,
12015
+ relabelCitations as aw,
12016
+ toolCallRenderer as ax,
12017
+ activityRenderer as ay,
12018
+ isMountedRenderer as az,
11526
12019
  APARTE_DEFAULT_BUBBLE_ACTIONS as b,
11527
12020
  APARTE_DEFAULT_HOST_HANDLERS as c,
11528
12021
  APARTE_DEFAULT_ICON_FALLBACKS as d,
@@ -11549,4 +12042,4 @@ export {
11549
12042
  collectRendererStyles as y,
11550
12043
  contentToText as z
11551
12044
  };
11552
- //# sourceMappingURL=defer-hydration-lK-7XQXf.js.map
12045
+ //# sourceMappingURL=defer-hydration-o5MFsc_Z.js.map