@aparte/core 0.25.0 → 0.27.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 (108) hide show
  1. package/dist/client/agent-runner.d.ts.map +1 -1
  2. package/dist/client/aparte-client.d.ts +37 -76
  3. package/dist/client/aparte-client.d.ts.map +1 -1
  4. package/dist/client/stream-adapter.d.ts.map +1 -1
  5. package/dist/client/wire-history.d.ts +78 -0
  6. package/dist/client/wire-history.d.ts.map +1 -1
  7. package/dist/components/bubble/aparte-chat-bubble.d.ts +90 -4
  8. package/dist/components/bubble/aparte-chat-bubble.d.ts.map +1 -1
  9. package/dist/components/bubble/bubble-sync.d.ts +5 -1
  10. package/dist/components/bubble/bubble-sync.d.ts.map +1 -1
  11. package/dist/components/bubble/checkpoint-separator.d.ts +40 -0
  12. package/dist/components/bubble/checkpoint-separator.d.ts.map +1 -0
  13. package/dist/components/composer/accepts-file.d.ts +10 -0
  14. package/dist/components/composer/accepts-file.d.ts.map +1 -0
  15. package/dist/components/composer/aparte-composer-add-attachment.d.ts +5 -1
  16. package/dist/components/composer/aparte-composer-add-attachment.d.ts.map +1 -1
  17. package/dist/components/composer/aparte-composer-attachments.d.ts +9 -4
  18. package/dist/components/composer/aparte-composer-attachments.d.ts.map +1 -1
  19. package/dist/components/composer/aparte-composer-input.d.ts.map +1 -1
  20. package/dist/components/context/aparte-context.d.ts +172 -25
  21. package/dist/components/context/aparte-context.d.ts.map +1 -1
  22. package/dist/components/elicitation/aparte-elicitation.d.ts +2 -2
  23. package/dist/components/index.d.ts +2 -0
  24. package/dist/components/index.d.ts.map +1 -1
  25. package/dist/components/launcher/aparte-launcher.d.ts +167 -0
  26. package/dist/components/launcher/aparte-launcher.d.ts.map +1 -0
  27. package/dist/components/launcher/index.d.ts +3 -0
  28. package/dist/components/launcher/index.d.ts.map +1 -0
  29. package/dist/components/viewport/aparte-chat-viewport.d.ts +7 -0
  30. package/dist/components/viewport/aparte-chat-viewport.d.ts.map +1 -1
  31. package/dist/config/aparte-config.d.ts +23 -1
  32. package/dist/config/aparte-config.d.ts.map +1 -1
  33. package/dist/config/error-renderer.d.ts +21 -10
  34. package/dist/config/error-renderer.d.ts.map +1 -1
  35. package/dist/config/icon-provider.d.ts +2 -0
  36. package/dist/config/icon-provider.d.ts.map +1 -1
  37. package/dist/config/locale.d.ts +85 -5
  38. package/dist/config/locale.d.ts.map +1 -1
  39. package/dist/context/checkpoint-state.d.ts +70 -0
  40. package/dist/context/checkpoint-state.d.ts.map +1 -0
  41. package/dist/context/checkpoint.d.ts +28 -0
  42. package/dist/context/checkpoint.d.ts.map +1 -0
  43. package/dist/context/measure.d.ts +148 -0
  44. package/dist/context/measure.d.ts.map +1 -0
  45. package/dist/context/restore.d.ts +24 -0
  46. package/dist/context/restore.d.ts.map +1 -0
  47. package/dist/conversations/conversation-controller.d.ts +13 -4
  48. package/dist/conversations/conversation-controller.d.ts.map +1 -1
  49. package/dist/conversations/conversation-manager.d.ts +6 -0
  50. package/dist/conversations/conversation-manager.d.ts.map +1 -1
  51. package/dist/custom-elements.json +13893 -11714
  52. package/dist/{defer-hydration-BwMqeRHq.js → defer-hydration-DSZE-bKi.js} +788 -269
  53. package/dist/defer-hydration-DSZE-bKi.js.map +1 -0
  54. package/dist/generated/element-attributes.d.ts +21 -3
  55. package/dist/generated/element-attributes.d.ts.map +1 -1
  56. package/dist/{glyphs-2bym5jl5.js → glyphs-DFp-825O.js} +33 -30
  57. package/dist/{glyphs-2bym5jl5.js.map → glyphs-DFp-825O.js.map} +1 -1
  58. package/dist/host/aparte-chat-host.d.ts +19 -2
  59. package/dist/host/aparte-chat-host.d.ts.map +1 -1
  60. package/dist/icons/extended.d.ts +2 -2
  61. package/dist/icons/extended.d.ts.map +1 -1
  62. package/dist/icons/glyphs.d.ts +3 -0
  63. package/dist/icons/glyphs.d.ts.map +1 -1
  64. package/dist/icons.js +29 -30
  65. package/dist/icons.js.map +1 -1
  66. package/dist/index.css +1 -1
  67. package/dist/index.d.ts +8 -1
  68. package/dist/index.d.ts.map +1 -1
  69. package/dist/index.js +1140 -95
  70. package/dist/index.js.map +1 -1
  71. package/dist/index.node.d.ts +6 -2
  72. package/dist/index.node.d.ts.map +1 -1
  73. package/dist/index.node.js +33 -29
  74. package/dist/index.node.js.map +1 -1
  75. package/dist/interop/element-props.d.ts +1 -1
  76. package/dist/interop/element-props.d.ts.map +1 -1
  77. package/dist/renderers/segments/error.d.ts.map +1 -1
  78. package/dist/renderers/segments/tool-call.d.ts.map +1 -1
  79. package/dist/transport/agent-handler.d.ts.map +1 -1
  80. package/dist/transport/backend-handler.d.ts.map +1 -1
  81. package/dist/transport/types.d.ts +24 -4
  82. package/dist/transport/types.d.ts.map +1 -1
  83. package/dist/types/chat.d.ts +16 -1
  84. package/dist/types/chat.d.ts.map +1 -1
  85. package/dist/types/compactor.d.ts +104 -0
  86. package/dist/types/compactor.d.ts.map +1 -0
  87. package/dist/types/element-map.d.ts +2 -0
  88. package/dist/types/element-map.d.ts.map +1 -1
  89. package/dist/types/errors.d.ts +9 -0
  90. package/dist/types/errors.d.ts.map +1 -1
  91. package/dist/types/event-map.d.ts +2 -0
  92. package/dist/types/event-map.d.ts.map +1 -1
  93. package/dist/types/events.d.ts +50 -3
  94. package/dist/types/events.d.ts.map +1 -1
  95. package/dist/types/index.d.ts +4 -3
  96. package/dist/types/index.d.ts.map +1 -1
  97. package/dist/types/model-provider.d.ts +3 -0
  98. package/dist/types/model-provider.d.ts.map +1 -1
  99. package/dist/types/models.d.ts +43 -3
  100. package/dist/types/models.d.ts.map +1 -1
  101. package/dist/types/segments.d.ts +13 -5
  102. package/dist/types/segments.d.ts.map +1 -1
  103. package/dist/types/tools.d.ts +6 -1
  104. package/dist/types/tools.d.ts.map +1 -1
  105. package/dist/utils/error-sentence.d.ts +21 -0
  106. package/dist/utils/error-sentence.d.ts.map +1 -0
  107. package/package.json +2 -2
  108. package/dist/defer-hydration-BwMqeRHq.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import { toolRefusal as toolRefusal$1, unansweredTail, runStreamAgent } from "@aparte/engine";
2
- import { A as APARTE_ICON_GLYPHS } from "./glyphs-2bym5jl5.js";
2
+ import { A as APARTE_ICON_GLYPHS } from "./glyphs-DFp-825O.js";
3
3
  function contentToText(content) {
4
4
  if (typeof content === "string") return content;
5
5
  return content.filter((p) => p.type === "text").map((p) => p.text).join("");
@@ -18,6 +18,7 @@ var AparteErrorCode = /* @__PURE__ */ ((AparteErrorCode2) => {
18
18
  AparteErrorCode2["PROVIDER_ERROR"] = "PROVIDER_ERROR";
19
19
  AparteErrorCode2["PROVIDER_UNAVAILABLE"] = "PROVIDER_UNAVAILABLE";
20
20
  AparteErrorCode2["PROVIDER_POLICY"] = "PROVIDER_POLICY";
21
+ AparteErrorCode2["PROVIDER_MISCONFIGURED"] = "PROVIDER_MISCONFIGURED";
21
22
  AparteErrorCode2["MAX_TURNS_EXCEEDED"] = "MAX_TURNS_EXCEEDED";
22
23
  AparteErrorCode2["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
23
24
  return AparteErrorCode2;
@@ -58,9 +59,14 @@ class AparteError extends Error {
58
59
  if (error instanceof AparteError) return error;
59
60
  const message = error instanceof Error ? error.message : String(error);
60
61
  const status = error?.status || error?.statusCode || defaultStatus;
61
- const code = defaultCode !== "UNKNOWN_ERROR" ? defaultCode : AparteError.codeForStatus(status) ?? AparteError.codeForFailure(error) ?? defaultCode;
62
+ const carried = error?.code;
63
+ const code = defaultCode !== "UNKNOWN_ERROR" ? defaultCode : AparteError.carriedCode(carried) ?? AparteError.codeForStatus(status) ?? AparteError.codeForFailure(error) ?? defaultCode;
62
64
  return new AparteError(message, code, void 0, error, status);
63
65
  }
66
+ /** The value as an {@link AparteErrorCode}, when it is one — a Node `ECONNRESET` or a vendor's own string is not. */
67
+ static carriedCode(value) {
68
+ return typeof value === "string" && Object.values(AparteErrorCode).includes(value) ? value : void 0;
69
+ }
64
70
  /**
65
71
  * What a thrown, statusless error says about itself. `fetch` rejects a network
66
72
  * failure with a TypeError whose message names the fetch ("Failed to fetch",
@@ -104,7 +110,26 @@ const APARTE_DEFAULT_LOCALE = {
104
110
  scrollToBottom: "Scroll to bottom",
105
111
  suggestionsLabel: "Suggested prompts",
106
112
  contextLabel: "Context window",
113
+ contextSystem: "System prompt",
114
+ contextTools: "Tools",
115
+ contextSummary: "Summary",
116
+ contextMessages: "Messages",
117
+ contextOther: "Other",
118
+ contextFree: "Free",
119
+ contextTotal: "Total",
120
+ contextReclaim: "Compacting now would free ~{n} tokens",
121
+ contextCompactNow: "Compact now",
107
122
  compactionSummaryTitle: "Conversation summary",
123
+ checkpointCount: "{n} messages summarised for the model",
124
+ checkpointCountOne: "1 message summarised for the model",
125
+ checkpointLegacy: "Earlier messages were summarised",
126
+ checkpointGroup: "Context summary",
127
+ checkpointShow: "Show summary",
128
+ checkpointHide: "Hide summary",
129
+ checkpointRestore: "Restore",
130
+ checkpointRestoreConfirm: "Send the original messages to the model again?",
131
+ checkpointPending: "Summarising the context…",
132
+ checkpointFailed: "Couldn't summarise the context",
108
133
  toolRunning: "Running",
109
134
  toolCompleted: "Done",
110
135
  toolRejected: "Rejected",
@@ -143,7 +168,15 @@ const APARTE_DEFAULT_LOCALE = {
143
168
  generating: "Generating…",
144
169
  rebuildingPreview: "Rebuilding preview…",
145
170
  typing: "Typing",
171
+ responseCutOff: "Cut off at the model's length limit.",
146
172
  error: "Error",
173
+ errorUnreachable: "The assistant can’t be reached right now. Try again in a moment.",
174
+ errorTimeout: "The answer took too long. Try again in a moment.",
175
+ errorRefused: "The assistant isn’t allowed to answer right now.",
176
+ errorRateLimited: "Too many requests right now. Try again in a moment.",
177
+ errorTooLong: "This conversation is too long for the model. Start a new one.",
178
+ errorFailed: "The assistant couldn’t answer. Try again in a moment.",
179
+ errorNoAnswer: "The assistant couldn’t answer this request.",
147
180
  running: "Running...",
148
181
  run: "Run",
149
182
  file: "File",
@@ -189,6 +222,8 @@ const APARTE_DEFAULT_LOCALE = {
189
222
  scrollRailLabel: "Conversation outline",
190
223
  sidebarLabel: "Conversations",
191
224
  splitHandleLabel: "Resize the panes",
225
+ launcherOpen: "Open the chat",
226
+ launcherClose: "Close the chat",
192
227
  transcript: "Transcript"
193
228
  };
194
229
  function isFormatAdapter(p) {
@@ -199,15 +234,19 @@ function readAuth(auth) {
199
234
  if (auth && typeof auth === "object") return { key: auth["apiKey"], endpoint: auth["endpoint"] };
200
235
  return {};
201
236
  }
202
- async function vendorErrorMessage(response, label = "HTTP") {
203
- const body = await response.json().catch(() => ({}));
237
+ function messageOf(body, status, label) {
204
238
  const raw = body?.error;
205
239
  const msg = typeof raw === "object" ? raw?.message : raw;
206
- return typeof msg === "string" && msg ? msg : `${label} ${response.status}`;
240
+ return typeof msg === "string" && msg ? msg : `${label} ${status}`;
241
+ }
242
+ function isAparteErrorCode(value) {
243
+ return typeof value === "string" && Object.values(AparteErrorCode).includes(value);
207
244
  }
208
- async function vendorError(response, label = "HTTP") {
209
- const message = await vendorErrorMessage(response, label);
210
- const code = AparteError.codeForStatus(response.status) ?? AparteErrorCode.UNKNOWN_ERROR;
245
+ async function vendorError(response, label = "HTTP", adapter) {
246
+ const body = await response.json().catch(() => void 0);
247
+ const message = messageOf(body, response.status, label);
248
+ const forwarded = body?.error?.code;
249
+ const code = adapter?.classifyError?.(response.status, body) ?? (isAparteErrorCode(forwarded) ? forwarded : void 0) ?? AparteError.codeForStatus(response.status) ?? AparteErrorCode.UNKNOWN_ERROR;
211
250
  return new AparteError(message, code, void 0, void 0, response.status);
212
251
  }
213
252
  async function parseNonStreamText(provider, response, providerId) {
@@ -250,7 +289,7 @@ class AparteDirectTransport {
250
289
  signal: ctx.signal
251
290
  });
252
291
  if (!response.ok) {
253
- throw await vendorError(response);
292
+ throw await vendorError(response, "HTTP", provider);
254
293
  }
255
294
  if (request.stream === false) {
256
295
  return parseNonStreamText(provider, response, ctx.providerId);
@@ -878,12 +917,18 @@ function createAparteChatHandler(options) {
878
917
  const raw = await vendor.text().catch(() => "");
879
918
  let code;
880
919
  let type;
920
+ let body;
881
921
  try {
882
- const parsed = JSON.parse(raw);
922
+ body = JSON.parse(raw);
923
+ const parsed = body;
883
924
  code = parsed?.error?.code;
884
925
  type = parsed?.error?.type;
885
926
  } catch {
886
927
  }
928
+ try {
929
+ code = adapter.classifyError?.(vendor.status, body) ?? code;
930
+ } catch {
931
+ }
887
932
  return new Response(
888
933
  JSON.stringify({
889
934
  error: {
@@ -897,7 +942,12 @@ function createAparteChatHandler(options) {
897
942
  }
898
943
  if (request.stream === false) {
899
944
  const json = await vendor.json().catch(() => ({}));
900
- const text = typeof adapter.parseText === "function" ? adapter.parseText(json) : "";
945
+ let text;
946
+ try {
947
+ text = typeof adapter.parseText === "function" ? adapter.parseText(json) : "";
948
+ } catch {
949
+ return jsonError$1(502, "The vendor answered with an error.");
950
+ }
901
951
  return new Response(JSON.stringify({ text }), {
902
952
  headers: { "Content-Type": "application/json" }
903
953
  });
@@ -915,7 +965,7 @@ function createAparteChatHandler(options) {
915
965
  controller.close();
916
966
  return;
917
967
  }
918
- controller.enqueue(encoder2.encode(JSON.stringify(value) + "\n"));
968
+ controller.enqueue(encoder2.encode(JSON.stringify(relayable(value)) + "\n"));
919
969
  } catch (err) {
920
970
  controller.error(err);
921
971
  }
@@ -927,6 +977,13 @@ function createAparteChatHandler(options) {
927
977
  return new Response(ndjson, { headers: { "Content-Type": "application/x-ndjson" } });
928
978
  };
929
979
  }
980
+ function relayable(event) {
981
+ const e = event;
982
+ if (e?.type !== "error") return event;
983
+ console.error("[aparte] the vendor streamed an error", event);
984
+ const code = typeof e.code === "string" && Object.values(AparteErrorCode).includes(e.code) ? e.code : void 0;
985
+ return { type: "error", message: "The vendor reported an error.", ...code ? { code } : {} };
986
+ }
930
987
  function jsonError$1(status, message) {
931
988
  return new Response(JSON.stringify({ error: { message } }), {
932
989
  status,
@@ -1248,7 +1305,10 @@ function createStreamAdapter(opts) {
1248
1305
  break;
1249
1306
  }
1250
1307
  case "run-done":
1251
- target.updateMessage?.(messageId, { status: "completed" });
1308
+ target.updateMessage?.(messageId, {
1309
+ status: "completed",
1310
+ ...e.finishReason ? { finishReason: e.finishReason } : {}
1311
+ });
1252
1312
  if (e.usage) {
1253
1313
  try {
1254
1314
  target.setUsage?.(messageId, e.usage);
@@ -1519,10 +1579,11 @@ function createAparteAgentHandler(options) {
1519
1579
  console.error("[aparte] agent run failed", error);
1520
1580
  await pendingWrite?.catch(() => {
1521
1581
  });
1582
+ const named = AparteError.from(error).code;
1522
1583
  write({
1523
1584
  type: "run-error",
1524
1585
  message: "The agent run failed.",
1525
- code: error instanceof AparteError ? error.code : "AGENT_RUN_FAILED"
1586
+ code: named === AparteErrorCode.UNKNOWN_ERROR ? "AGENT_RUN_FAILED" : named
1526
1587
  });
1527
1588
  close();
1528
1589
  });
@@ -2023,6 +2084,8 @@ class AparteConfig {
2023
2084
  _modelPreferenceProvider;
2024
2085
  // Per-call approval policy (a mode: plan / ask / auto). `null` = the tools' own flags.
2025
2086
  _approvalPolicy = null;
2087
+ // What makes the context smaller — `@aparte/plugin-compaction` registers itself here. `null` = nothing does.
2088
+ _compactor = null;
2026
2089
  // Conversation persistence (optional, agnostic)
2027
2090
  _conversationManager;
2028
2091
  /*
@@ -2513,7 +2576,11 @@ class AparteConfig {
2513
2576
  try {
2514
2577
  const auth = await this.getKey(providerId);
2515
2578
  const models = await provider.fetchModels(auth);
2579
+ const held = this._fetchedModels.get(providerId);
2580
+ if (models.length === 0 && held?.length) return held;
2581
+ const windowBefore = this.getCurrentModel()?.contextWindow;
2516
2582
  this._fetchedModels.set(providerId, models);
2583
+ if (this.getCurrentModel()?.contextWindow !== windowBefore) this._notify();
2517
2584
  return models;
2518
2585
  } catch (error) {
2519
2586
  console.warn(`[AparteConfig] Failed to refresh models for ${providerId}`, error);
@@ -2637,6 +2704,26 @@ class AparteConfig {
2637
2704
  getApprovalPolicy() {
2638
2705
  return this._approvalPolicy;
2639
2706
  }
2707
+ /**
2708
+ * Register what makes the context smaller: the gauge's Compact now, a separator's
2709
+ * Retry and the client's pre-flight and overflow retry call it. `null` removes it.
2710
+ *
2711
+ * `@aparte/plugin-compaction`'s `setupCompaction()` registers itself here; core never
2712
+ * compacts on its own, so a page without a compactor has a gauge that measures and a
2713
+ * separator whose Retry falls back to the `aparte-compact` event. A chat reads the one
2714
+ * on ITS config first (`resolveConfig(chat).getCompactor()`), then the client's.
2715
+ *
2716
+ * Notifies like every other registration: a mounted gauge has to hear that "Compact
2717
+ * now" became possible after it was drawn, or went away.
2718
+ */
2719
+ setCompactor(compactor) {
2720
+ this._compactor = compactor;
2721
+ this._notify();
2722
+ }
2723
+ /** The registered compactor, or `null`. */
2724
+ getCompactor() {
2725
+ return this._compactor;
2726
+ }
2640
2727
  /**
2641
2728
  * What the policy says about one call, with the tool's own `needsApproval` as the
2642
2729
  * answer when it has no opinion. The one place the two are combined, so the client's
@@ -3045,8 +3132,13 @@ class AparteConfig {
3045
3132
  * aparteGlobalConfig.registerToolDisplay('*', { hidden: true });
3046
3133
  *
3047
3134
  * @example
3135
+ * // An agent's chat: the spinner, "Running" and "Done" (the default is quiet), on every
3136
+ * // tool without an entry of its own — a tool with one says `quiet: false` there too.
3137
+ * aparteGlobalConfig.registerToolDisplay('*', { quiet: false });
3138
+ *
3139
+ * @example
3048
3140
  * // The line, and no raw JSON behind it: nothing, or a detail of the app's own.
3049
- * aparteGlobalConfig.registerToolDisplay('read_file', { label: 'Reading a file', details: false });
3141
+ * aparteGlobalConfig.registerToolDisplay('read_file', { label: 'Read a file', details: false });
3050
3142
  * aparteGlobalConfig.registerToolDisplay('web_search', {
3051
3143
  * label: 'Searched the web',
3052
3144
  * details: (segment) => sourcesList(segment.result),
@@ -3377,6 +3469,7 @@ class AparteConfig {
3377
3469
  this._elicitationFieldRenderer = void 0;
3378
3470
  this._modelPreferenceProvider = void 0;
3379
3471
  this._approvalPolicy = null;
3472
+ this._compactor = null;
3380
3473
  this._bubbleActionsConfig = { ...APARTE_DEFAULT_BUBBLE_ACTIONS };
3381
3474
  this._hostHandlers = { ...APARTE_DEFAULT_HOST_HANDLERS };
3382
3475
  this._notify();
@@ -3737,13 +3830,42 @@ const codeRenderer = {
3737
3830
  },
3738
3831
  getStyles: () => ``
3739
3832
  };
3833
+ function errorSentence(code, t) {
3834
+ switch (code) {
3835
+ case AparteErrorCode.NET_OFFLINE:
3836
+ case AparteErrorCode.NET_ERROR:
3837
+ return t("errorUnreachable");
3838
+ case AparteErrorCode.NET_TIMEOUT:
3839
+ return t("errorTimeout");
3840
+ case AparteErrorCode.CONFIG_INVALID_KEY:
3841
+ return t("errorRefused");
3842
+ case AparteErrorCode.USAGE_RATE_LIMIT:
3843
+ return t("errorRateLimited");
3844
+ case AparteErrorCode.USAGE_CONTEXT_EXCEEDED:
3845
+ return t("errorTooLong");
3846
+ case AparteErrorCode.PROVIDER_ERROR:
3847
+ case AparteErrorCode.PROVIDER_UNAVAILABLE:
3848
+ return t("errorFailed");
3849
+ case AparteErrorCode.USAGE_BAD_REQUEST:
3850
+ case AparteErrorCode.PROVIDER_POLICY:
3851
+ case AparteErrorCode.PROVIDER_MISCONFIGURED:
3852
+ case AparteErrorCode.CONFIG_INVALID_MODEL:
3853
+ case AparteErrorCode.UNKNOWN_ERROR:
3854
+ return t("errorNoAnswer");
3855
+ default:
3856
+ return void 0;
3857
+ }
3858
+ }
3740
3859
  const errorRenderer = {
3741
3860
  type: "error",
3742
3861
  render: (segment) => {
3743
- const custom = contextConfig().getErrorRenderer?.();
3862
+ const cfg = contextConfig();
3863
+ const sentence = errorSentence(segment.code, (key) => cfg.t(key));
3864
+ const custom = cfg.getErrorRenderer?.();
3744
3865
  if (custom) {
3745
3866
  const out = custom({
3746
3867
  message: segment.content,
3868
+ ...sentence !== void 0 ? { sentence } : {},
3747
3869
  ...segment.details !== void 0 ? { details: segment.details } : {},
3748
3870
  ...segment.code !== void 0 ? { code: segment.code } : {}
3749
3871
  });
@@ -3753,28 +3875,35 @@ const errorRenderer = {
3753
3875
  }
3754
3876
  return out;
3755
3877
  }
3878
+ const message = sentence ?? segment.content;
3756
3879
  return `
3757
3880
  <div class="aparte-segment aparte-alert aparte-alert--danger aparte-segment-error" data-segment-id="${escapeHtml(segment.id)}"${segment.code ? ` data-error-code="${escapeAttr(segment.code)}"` : ""}>
3758
- <span class="aparte-alert__icon">${contextConfig().getIcon("error") || "⚠"}</span>
3881
+ <span class="aparte-alert__icon">${cfg.getIcon("error") || "⚠"}</span>
3759
3882
  <div class="aparte-alert__body">
3760
- <div class="aparte-alert__title">${escapeHtml(contextConfig().t("error"))}</div>
3761
- <div class="aparte-alert__message">${escapeHtml(segment.content)}</div>
3883
+ <div class="aparte-alert__title">${escapeHtml(cfg.t("error"))}</div>
3884
+ <div class="aparte-alert__message">${escapeHtml(message)}</div>
3762
3885
  ${segment.details ? `<pre class="aparte-segment-error__details">${escapeHtml(segment.details)}</pre>` : ""}
3763
3886
  </div>
3764
3887
  </div>
3765
3888
  `;
3766
3889
  },
3767
3890
  /**
3768
- * The icon and the heading (`locale.error`).
3891
+ * The icon, the heading (`locale.error`) and a sentence chosen by the code.
3769
3892
  *
3770
- * Not the message: that is the model's or the transport's text, in whatever
3771
- * language it arrived in. Relabelling it would be inventing content.
3893
+ * Not a message the error keeps as its own: that is the app's, a setup error's or the
3894
+ * turn limit's text, in the language it was written in. Relabelling it would be
3895
+ * inventing content.
3772
3896
  */
3773
- relabel: (element) => {
3897
+ relabel: (element, segment) => {
3898
+ const cfg = contextConfig();
3899
+ if (cfg.getErrorRenderer?.()) return;
3774
3900
  const wrap = element.querySelector(".aparte-alert__icon");
3775
- if (wrap) wrap.innerHTML = contextConfig().getIcon("error") || "⚠";
3901
+ if (wrap) wrap.innerHTML = cfg.getIcon("error") || "⚠";
3776
3902
  const title = element.querySelector(".aparte-alert__title");
3777
- if (title) title.textContent = contextConfig().t("error");
3903
+ if (title) title.textContent = cfg.t("error");
3904
+ const sentence = errorSentence(segment.code, (key) => cfg.t(key));
3905
+ const message = element.querySelector(".aparte-alert__message");
3906
+ if (message && sentence !== void 0) message.textContent = sentence;
3778
3907
  },
3779
3908
  getStyles: () => ``
3780
3909
  };
@@ -4033,7 +4162,7 @@ function iconOf(segment) {
4033
4162
  const key = cfg.getToolDisplay(segment.toolCall?.name ?? "")?.icon;
4034
4163
  return (key ? cfg.getIcon(key) : void 0) || cfg.getIcon("tool");
4035
4164
  }
4036
- const isQuiet = (segment) => contextConfig().getToolDisplay(segment.toolCall?.name ?? "")?.quiet === true;
4165
+ const isQuiet = (segment) => contextConfig().getToolDisplay(segment.toolCall?.name ?? "")?.quiet ?? true;
4037
4166
  function quietOf(segment) {
4038
4167
  const status = segment.status ?? "pending";
4039
4168
  const quiet = isQuiet(segment);
@@ -4520,13 +4649,25 @@ function populateBubbleFromMessage(bubble, message, siblingInfo) {
4520
4649
  if (message.usage !== void 0) {
4521
4650
  bubble.setUsage?.(message.usage);
4522
4651
  }
4652
+ bubble.setFinishReason?.(message.finishReason);
4653
+ bubble.setContextSummary?.(message.contextSummary, { legacy: message.compaction === true });
4523
4654
  }
4524
4655
  const APARTE_CONVERSATION_SCHEMA_VERSION = 2;
4525
4656
  const APARTE_DERIVED_SEGMENTS = Symbol.for("aparte.derivedSegments");
4526
4657
  function applyRetention(messages, tree, maxMessages) {
4527
4658
  if (maxMessages <= 0 || messages.length <= maxMessages) return { messages, tree };
4528
- const trimmedFlat = messages.slice(messages.length - maxMessages);
4529
- const cutoffId = trimmedFlat[0]?.id;
4659
+ const cutIndex = messages.length - maxMessages;
4660
+ const trimmedFlat = messages.slice(cutIndex);
4661
+ const first = trimmedFlat[0];
4662
+ const cutoffId = first?.id;
4663
+ let inherited;
4664
+ for (let i = messages.length - 1; i >= 0; i--) {
4665
+ const own = messages[i].contextSummary;
4666
+ if (!own) continue;
4667
+ if (i < cutIndex) inherited = { ...own, count: own.count + (cutIndex - i) };
4668
+ break;
4669
+ }
4670
+ if (first && inherited) trimmedFlat[0] = { ...first, contextSummary: inherited };
4530
4671
  if (!cutoffId || !tree) return { messages: trimmedFlat, tree };
4531
4672
  const treeIds = new Set(tree.messages.map((m) => m.message.id));
4532
4673
  if (!treeIds.has(cutoffId)) return { messages: trimmedFlat, tree };
@@ -4548,7 +4689,7 @@ function applyRetention(messages, tree, maxMessages) {
4548
4689
  }
4549
4690
  const trimmedTree = {
4550
4691
  headId: tree.headId,
4551
- messages: tree.messages.filter((m) => keep.has(m.message.id)).map((m) => m.message.id === cutoffId ? { message: m.message, parentId: null } : m)
4692
+ messages: tree.messages.filter((m) => keep.has(m.message.id)).map((m) => m.message.id === cutoffId ? { message: inherited ? { ...m.message, contextSummary: inherited } : m.message, parentId: null } : m)
4552
4693
  };
4553
4694
  return { messages: trimmedFlat, tree: trimmedTree };
4554
4695
  }
@@ -4579,6 +4720,7 @@ function treeContentOf(tree) {
4579
4720
  const byId = [...tree.messages].sort((a, b) => a.message.id < b.message.id ? -1 : a.message.id > b.message.id ? 1 : 0);
4580
4721
  return stableStringify(byId.map((entry) => ({ parentId: entry.parentId, message: asContent(entry.message) })));
4581
4722
  }
4723
+ const isTitleSource = (m) => m.role === "user" && !m.compaction;
4582
4724
  class AparteConversationManager {
4583
4725
  _adapter;
4584
4726
  _conversations = [];
@@ -4787,7 +4929,7 @@ class AparteConversationManager {
4787
4929
  async _append(convId, msg) {
4788
4930
  const conv = await this._full(convId);
4789
4931
  if (!conv) return;
4790
- const isFirstUserMsg = msg.role === "user" && conv.messages.every((m) => m.role !== "user");
4932
+ const isFirstUserMsg = msg.role === "user" && !msg.compaction && conv.messages.every((m) => m.role !== "user" || m.compaction);
4791
4933
  const title = isFirstUserMsg ? await this._title(msg) : null;
4792
4934
  const fresh = this._find(convId);
4793
4935
  if (!fresh) return;
@@ -4815,7 +4957,7 @@ class AparteConversationManager {
4815
4957
  console.warn(`[AparteConversationManager] updateMessages('${convId}') before its messages were loaded: ignored.`);
4816
4958
  return;
4817
4959
  }
4818
- const firstUser = messages.find((m) => m.role === "user");
4960
+ const firstUser = messages.find(isTitleSource);
4819
4961
  if (this._retention) {
4820
4962
  ({ messages, tree } = applyRetention(messages, tree, this._retention.maxMessages));
4821
4963
  }
@@ -4836,7 +4978,7 @@ class AparteConversationManager {
4836
4978
  }
4837
4979
  let title;
4838
4980
  if (conv.autoTitle) {
4839
- const before = conv.messages.find((m) => m.role === "user");
4981
+ const before = conv.messages.find(isTitleSource);
4840
4982
  if (firstUser && (firstUser.content ?? "") !== (before?.content ?? "")) {
4841
4983
  title = await this._title(firstUser);
4842
4984
  }
@@ -5209,7 +5351,7 @@ class AparteConversationController {
5209
5351
  this._onCompactDone = (e) => {
5210
5352
  const detail = e.detail;
5211
5353
  if (detail?.targetId && detail.targetId !== this._binding.hostId) return;
5212
- queueMicrotask(() => this._persistOnceSummarised(detail?.summary, 0));
5354
+ queueMicrotask(() => this._persistOnceSummarised(detail ?? {}, 0));
5213
5355
  };
5214
5356
  if (typeof window !== "undefined") {
5215
5357
  window.addEventListener("aparte-conversation-select", this._onSelectConversation);
@@ -5414,20 +5556,40 @@ class AparteConversationController {
5414
5556
  * that was partially written before a switch or component destruction.
5415
5557
  */
5416
5558
  /**
5417
- * Save once the binding holds the summary a compaction announced. A transcript kept in
5418
- * a framework store reaches the binding only when that framework renders, so a save on
5419
- * the microtask wrote the conversation as it stood before the compaction. Bounded: a
5420
- * run with no summary (skipped), or a binding that never shows it, is saved as it is.
5421
- */
5422
- _persistOnceSummarised(summary, waits) {
5423
- const holds = !summary || this._binding.getMessages().some(
5424
- (m) => m.compaction === true && typeof m.content === "string" && m.content.endsWith(summary)
5425
- );
5559
+ * Save once the binding holds what a compaction (or a Restore) announced. A transcript
5560
+ * kept in a framework store reaches the binding only when that framework renders, so a
5561
+ * save on the microtask wrote the conversation as it stood before the change. Bounded:
5562
+ * a run that changed nothing (skipped), or a binding that never shows the change, is
5563
+ * saved as it is.
5564
+ *
5565
+ * What "holds" means follows what the run said it did:
5566
+ * - a checkpoint — `messageId` names the message carrying it, and it holds once that
5567
+ * message carries a `contextSummary` with its `createdAt` (a summary without the
5568
+ * stamp is a half-written one);
5569
+ * - a Restore — it holds once no message of the path carries a checkpoint any more;
5570
+ * - an older host's summary MESSAGE (`compaction: true`, ending with the summary).
5571
+ * A run that names none of these has nothing to wait for.
5572
+ */
5573
+ _persistOnceSummarised(detail, waits) {
5574
+ const messages = this._binding.getMessages();
5575
+ let holds = true;
5576
+ if (detail.restored) {
5577
+ holds = !messages.some((m) => m.contextSummary !== void 0);
5578
+ } else if (detail.messageId || detail.summary) {
5579
+ const { messageId, summary } = detail;
5580
+ const checkpointed = !!messageId && messages.some(
5581
+ (m) => m.id === messageId && typeof m.contextSummary?.createdAt === "number"
5582
+ );
5583
+ const summaryMessage = !!summary && messages.some(
5584
+ (m) => m.compaction === true && typeof m.content === "string" && m.content.endsWith(summary)
5585
+ );
5586
+ holds = checkpointed || summaryMessage;
5587
+ }
5426
5588
  if (holds || !this._binding.afterRender || waits >= MAX_COMPACTION_SAVE_WAITS) {
5427
5589
  this._persistActive();
5428
5590
  return;
5429
5591
  }
5430
- this._binding.afterRender(() => this._persistOnceSummarised(summary, waits + 1));
5592
+ this._binding.afterRender(() => this._persistOnceSummarised(detail, waits + 1));
5431
5593
  }
5432
5594
  _persistActive() {
5433
5595
  if (!this._activeId) return;
@@ -5505,16 +5667,126 @@ function gateGlide(el2) {
5505
5667
  el2.addEventListener("aparte-send", lift);
5506
5668
  return off;
5507
5669
  }
5670
+ function chatIdOf(el2) {
5671
+ let node = el2.parentElement;
5672
+ while (node) {
5673
+ const isHost = node.tagName.toLowerCase() === "aparte-chat" || node.hasAttribute("data-aparte-chat");
5674
+ if (isHost && node.id) return node.id;
5675
+ node = node.parentElement;
5676
+ }
5677
+ return void 0;
5678
+ }
5679
+ class CheckpointStateWatcher {
5680
+ constructor(_options) {
5681
+ this._options = _options;
5682
+ }
5683
+ _messageId = null;
5684
+ _state = null;
5685
+ _reason = "";
5686
+ /** The bubble the attributes were last written to, so they can be taken off it even after it left the lookup. */
5687
+ _marked = null;
5688
+ /** Listen on `window` for the three events; returns the function that stops. */
5689
+ start() {
5690
+ const mine = (targetId) => {
5691
+ if (this._options.active && !this._options.active()) return false;
5692
+ return !targetId || targetId === this._options.ownId();
5693
+ };
5694
+ const mineMessage = (messageId) => !!messageId && this._options.owns(messageId);
5695
+ const onStart = (e) => {
5696
+ const detail = e.detail;
5697
+ if (!mine(detail?.targetId) || !mineMessage(detail?.messageId)) return;
5698
+ this.clear();
5699
+ this._set(detail.messageId, "pending", "");
5700
+ };
5701
+ const onDone = (e) => {
5702
+ const detail = e.detail;
5703
+ if (!mine(detail?.targetId) || detail?.skipped) return;
5704
+ if (detail?.messageId && detail.messageId === this._messageId) this.clear();
5705
+ };
5706
+ const onError = (e) => {
5707
+ const detail = e.detail;
5708
+ if (!mine(detail?.targetId) || !mineMessage(detail?.messageId)) return;
5709
+ if (detail.aborted) {
5710
+ if (detail.messageId === this._messageId) this.clear();
5711
+ return;
5712
+ }
5713
+ if (detail.messageId !== this._messageId) this.clear();
5714
+ this._set(detail.messageId, "failed", detail.error ?? "");
5715
+ };
5716
+ window.addEventListener("aparte-compact-start", onStart);
5717
+ window.addEventListener("aparte-compact-done", onDone);
5718
+ window.addEventListener("aparte-compact-error", onError);
5719
+ return () => {
5720
+ window.removeEventListener("aparte-compact-start", onStart);
5721
+ window.removeEventListener("aparte-compact-done", onDone);
5722
+ window.removeEventListener("aparte-compact-error", onError);
5723
+ };
5724
+ }
5725
+ /** Take the state off the bubble and forget it. */
5726
+ clear() {
5727
+ const bubble = this._marked ?? (this._messageId ? this._options.bubbleOf(this._messageId) : null);
5728
+ this._messageId = null;
5729
+ this._state = null;
5730
+ this._reason = "";
5731
+ this._marked = null;
5732
+ bubble?.removeAttribute("data-checkpoint");
5733
+ bubble?.removeAttribute("data-checkpoint-reason");
5734
+ }
5735
+ /** Write the remembered state onto the bubble, which may have been created since. */
5736
+ reapply() {
5737
+ if (!this._messageId || !this._state) return;
5738
+ this._write(this._messageId, this._state, this._reason);
5739
+ }
5740
+ _set(messageId, state, reason) {
5741
+ this._messageId = messageId;
5742
+ this._state = state;
5743
+ this._reason = reason;
5744
+ this._write(messageId, state, reason);
5745
+ }
5746
+ _write(messageId, state, reason) {
5747
+ const bubble = this._options.bubbleOf(messageId);
5748
+ if (!bubble) return;
5749
+ if (this._marked && this._marked !== bubble) {
5750
+ this._marked.removeAttribute("data-checkpoint");
5751
+ this._marked.removeAttribute("data-checkpoint-reason");
5752
+ }
5753
+ this._marked = bubble;
5754
+ if (reason) bubble.setAttribute("data-checkpoint-reason", reason);
5755
+ else bubble.removeAttribute("data-checkpoint-reason");
5756
+ if (bubble.getAttribute("data-checkpoint") !== state) bubble.setAttribute("data-checkpoint", state);
5757
+ }
5758
+ }
5508
5759
  const MAX_SIBLING_RETRIES = 6;
5509
5760
  const TREE_OWNED_FIELDS = /* @__PURE__ */ new Set(["id", "branches", "activeBranchIndex", "isStreaming"]);
5510
5761
  const ALWAYS_PRESENT_FIELDS = /* @__PURE__ */ new Set(["content", "segments", "status"]);
5762
+ const RENDERED_FIELDS = ["content", "segments", "attachments", "usage", "finishReason", "contextSummary", "compaction"];
5511
5763
  class AparteChatHost {
5512
5764
  binding;
5513
5765
  options;
5514
5766
  /** Id of the assistant message currently streaming (null when idle). */
5515
5767
  _streamingId = null;
5516
- /** Message ids already reconciled onto a bubble (skip-rerender cache). */
5517
- _renderedIds = /* @__PURE__ */ new Set();
5768
+ /**
5769
+ * The message object each bubble was last drawn from, by id (skip-rerender cache).
5770
+ *
5771
+ * An id alone could not say whether the list had changed under a bubble: a framework
5772
+ * that owns the transcript (a controlled `messages` prop, a v-model, a store behind a
5773
+ * compaction target) never goes through {@link updateMessage}, it hands over a list
5774
+ * with a NEW object for the message it changed, and a checkpoint written that way to a
5775
+ * message that was not the last never reached its bubble. Immutable updates always
5776
+ * produce a new object, so the reference is the signal; the same object again means
5777
+ * nothing changed and the bubble is left alone.
5778
+ */
5779
+ _renderedIds = /* @__PURE__ */ new Map();
5780
+ /**
5781
+ * Says on the bubble what a compaction is doing to the message it will sit on. The
5782
+ * viewport answers for this in a chat with no framework; here the framework owns the
5783
+ * list and the host is the one that knows which bubble is whose.
5784
+ */
5785
+ _checkpointState = new CheckpointStateWatcher({
5786
+ ownId: () => this.binding.hostId,
5787
+ bubbleOf: (id) => this._bubbleById(id),
5788
+ owns: (id) => this.binding.getMessages().some((m) => m.id === id)
5789
+ });
5518
5790
  /** Sibling info from the last path-change, applied after the next render. */
5519
5791
  _pendingSiblings;
5520
5792
  /** How many render passes the sibling write has waited for — see `_applyPendingSiblings`. */
@@ -5600,6 +5872,7 @@ class AparteChatHost {
5600
5872
  }
5601
5873
  this._installHostMethods(host2);
5602
5874
  this._installLifecycleListeners(host2);
5875
+ this._teardown.push(this._checkpointState.start());
5603
5876
  this._teardown.push(gateGlide(host2));
5604
5877
  this._installViewportListeners();
5605
5878
  this._createController(host2);
@@ -5713,6 +5986,7 @@ class AparteChatHost {
5713
5986
  this._setStreamingId(null);
5714
5987
  this.binding.onTypingChange?.(false);
5715
5988
  this._renderedIds.clear();
5989
+ this._checkpointState.clear();
5716
5990
  this.binding.resetComposer?.();
5717
5991
  }
5718
5992
  // ── host method surface (also installed on the host element) ───────────
@@ -5762,6 +6036,13 @@ class AparteChatHost {
5762
6036
  if (updates.status) {
5763
6037
  this._bubbleById(messageId)?.updateMessage?.({ status: updates.status });
5764
6038
  }
6039
+ if (index !== msgs.length - 1 && RENDERED_FIELDS.some((key) => key in updates)) {
6040
+ this._renderedIds.delete(messageId);
6041
+ const bubble = this._bubbleById(messageId);
6042
+ if (bubble && ("contextSummary" in updates || "compaction" in updates)) {
6043
+ bubble.setContextSummary?.(merged.contextSummary, { legacy: merged.compaction === true });
6044
+ }
6045
+ }
5765
6046
  if (isTerminalStatus(merged.status) && merged.segments) {
5766
6047
  for (const id of openSegmentIds(merged.segments)) {
5767
6048
  this.updateSegment(id, { isStreaming: false });
@@ -6060,18 +6341,20 @@ class AparteChatHost {
6060
6341
  /**
6061
6342
  * Reconcile rendered bubbles with the current message list. The framework
6062
6343
  * calls this from its reactive message-change hook after rendering; the
6063
- * last message is always re-synced (streaming), others only once.
6344
+ * last message is always re-synced (streaming), the others whenever the list
6345
+ * holds a different object for them than the one they were drawn from.
6064
6346
  */
6065
6347
  syncBubbles() {
6066
6348
  const msgs = this.binding.getMessages();
6067
6349
  msgs.forEach((message, index) => {
6068
6350
  const isLast = index === msgs.length - 1;
6069
- if (this._renderedIds.has(message.id) && !isLast) return;
6351
+ if (this._renderedIds.get(message.id) === message && !isLast) return;
6070
6352
  const bubble = this._bubbleById(message.id);
6071
6353
  if (!bubble) return;
6072
6354
  populateBubbleFromMessage(bubble, message);
6073
- this._renderedIds.add(message.id);
6355
+ this._renderedIds.set(message.id, message);
6074
6356
  });
6357
+ this._checkpointState.reapply();
6075
6358
  }
6076
6359
  /**
6077
6360
  * Rebuild the viewport's internal repo from the message list before branch
@@ -6190,6 +6473,7 @@ class AparteChatHost {
6190
6473
  host2["removeSegment"] = (id) => this.removeSegment(id);
6191
6474
  host2["appendToSegment"] = (id, c) => this.appendToSegment(id, c);
6192
6475
  host2["getMessages"] = () => this.getMessages();
6476
+ host2["getMessage"] = (id) => this.binding.getMessages().find((m) => m.id === id);
6193
6477
  host2["addBranch"] = (id) => this.addBranch(id);
6194
6478
  host2["addSiblingOf"] = (id, m) => this.addSiblingOf(id, m);
6195
6479
  host2["truncateFrom"] = (id) => this.truncateFrom(id);
@@ -6264,6 +6548,37 @@ class AparteChatHost {
6264
6548
  });
6265
6549
  }
6266
6550
  }
6551
+ function historyFromCheckpoint(path) {
6552
+ for (let i = path.length - 1; i >= 0; i--) {
6553
+ const summary = path[i].contextSummary?.summary;
6554
+ if (summary !== void 0) return { summary, messages: path.slice(i) };
6555
+ }
6556
+ return { messages: path };
6557
+ }
6558
+ const COMPACTION_PREAMBLE = "The earlier part of this conversation was compacted. This is a summary of what came before; continue from it.";
6559
+ const underPreamble = (text) => `${COMPACTION_PREAMBLE}
6560
+
6561
+ ${text}`;
6562
+ function mergeAdjacentUserMessages(messages) {
6563
+ const asParts = (c) => typeof c === "string" ? [{ type: "text", text: c }] : c;
6564
+ const out = [];
6565
+ for (const m of messages) {
6566
+ const prev = out[out.length - 1];
6567
+ if (m.role !== "user" || prev?.role !== "user") {
6568
+ out.push(m);
6569
+ } else if (typeof prev.content === "string" && typeof m.content === "string") {
6570
+ out[out.length - 1] = { ...prev, content: `${prev.content}
6571
+
6572
+ ${m.content}` };
6573
+ } else {
6574
+ out[out.length - 1] = {
6575
+ ...prev,
6576
+ content: [...asParts(prev.content), { type: "text", text: "\n\n" }, ...asParts(m.content)]
6577
+ };
6578
+ }
6579
+ }
6580
+ return out;
6581
+ }
6267
6582
  const STOPPED_TOOL_TEXT = "The tool call was stopped before it ran.";
6268
6583
  const EMPTY_TOOL_TEXT = "The tool returned no output.";
6269
6584
  function answerOf(segment) {
@@ -6314,6 +6629,139 @@ function wireTurns(message, textOf, options = {}) {
6314
6629
  flush();
6315
6630
  return out;
6316
6631
  }
6632
+ const isInFlight = (m) => m.status === "streaming" || m.status === "pending";
6633
+ function segmentsToWireText(segments) {
6634
+ if (!segments?.length) return "";
6635
+ const fence = "```";
6636
+ const parts = [];
6637
+ for (const segment of segments) {
6638
+ const content = segment.content;
6639
+ if (segment.type === "text") {
6640
+ if (content) parts.push(content);
6641
+ } else if (segment.type === "code") {
6642
+ const lang = segment.language ?? "";
6643
+ parts.push(`${fence}${lang}
6644
+ ${content ?? ""}
6645
+ ${fence}`);
6646
+ } else if (segment.type === "thinking" || segment.type === "tool_call" || segment.type === "error") {
6647
+ continue;
6648
+ } else if (typeof content === "string" && content) {
6649
+ parts.push(content);
6650
+ } else {
6651
+ const fallback = segment.fallback;
6652
+ if (fallback) parts.push(fallback);
6653
+ }
6654
+ }
6655
+ return parts.join("\n").trim();
6656
+ }
6657
+ function extractWireText(message) {
6658
+ const rendered = segmentsToWireText(message.segments);
6659
+ if (rendered) return rendered;
6660
+ if (typeof message.content === "string" && message.content) return message.content;
6661
+ return "";
6662
+ }
6663
+ function messageWireText(message) {
6664
+ const text = extractWireText(message);
6665
+ return message.compaction ? underPreamble(text) : text;
6666
+ }
6667
+ function wireMessages(messages) {
6668
+ return messages.filter((m) => {
6669
+ if (m.role !== "user" && m.role !== "assistant") return false;
6670
+ return m.status !== "error" && !isInFlight(m);
6671
+ }).flatMap((m) => {
6672
+ if (m.role === "assistant" && m.segments?.some((s) => s.type === "tool_call")) {
6673
+ return wireTurns(m, segmentsToWireText);
6674
+ }
6675
+ const content = messageWireText(m);
6676
+ return content ? [{ role: m.role, content }] : [];
6677
+ });
6678
+ }
6679
+ function estimateTokens(text) {
6680
+ if (!text) return 0;
6681
+ return Math.ceil(text.length / 3.8);
6682
+ }
6683
+ const estimateJson = (value) => {
6684
+ if (!value) return 0;
6685
+ try {
6686
+ return estimateTokens(JSON.stringify(value));
6687
+ } catch {
6688
+ return 0;
6689
+ }
6690
+ };
6691
+ function estimateChatTokens(messages) {
6692
+ let total = 0;
6693
+ for (const message of messages) {
6694
+ total += estimateTokens(contentToText(message.content));
6695
+ if (message.toolCalls?.length) total += estimateJson(message.toolCalls);
6696
+ }
6697
+ return total;
6698
+ }
6699
+ function carriesNonTextParts(messages) {
6700
+ return messages.some((m) => typeof m.content !== "string" && m.content.some((p) => p.type !== "text"));
6701
+ }
6702
+ function estimateRequestTokens(request) {
6703
+ const declared = (request.tools ?? []).map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema }));
6704
+ return estimateChatTokens(request.messages) + (declared.length ? estimateJson(declared) : 0);
6705
+ }
6706
+ function estimateWireTokens(messages) {
6707
+ return estimateChatTokens(wireMessages(messages));
6708
+ }
6709
+ const usageTokens = (usage) => usage.totalTokens ?? usage.inputTokens + usage.outputTokens;
6710
+ function toolsForCurrentModel(config) {
6711
+ const capabilities = config.getCurrentModel()?.capabilities;
6712
+ const declinesTools = capabilities ? !capabilities.includes("function_calling") : false;
6713
+ return declinesTools ? [] : config.getTools();
6714
+ }
6715
+ function windowOf(config, windowOverride) {
6716
+ if (typeof windowOverride === "number" && Number.isFinite(windowOverride) && windowOverride > 0) return windowOverride;
6717
+ const declared = config.getCurrentModel()?.contextWindow;
6718
+ return declared && declared > 0 ? declared : void 0;
6719
+ }
6720
+ const hasSegment = (message, type) => message.segments?.some((s) => s.type === type) === true;
6721
+ function calibration(reply) {
6722
+ const sent = reply.usage?.inputTokens;
6723
+ const recorded = reply.contextEstimate;
6724
+ if (hasSegment(reply, "tool_call")) return 1;
6725
+ return sent && recorded && sent > 0 && recorded > 0 ? Math.min(3, Math.max(0.5, sent / recorded)) : 1;
6726
+ }
6727
+ function nextRequestTokens(reply, k) {
6728
+ const usage = reply.usage;
6729
+ if (!hasSegment(reply, "thinking") || !(usage.inputTokens > 0)) return usageTokens(usage);
6730
+ const segments = reply.segments ?? [];
6731
+ const lastCall = segments.map((s) => s.type).lastIndexOf("tool_call");
6732
+ const said = Math.round(k * estimateTokens(segmentsToWireText(segments.slice(lastCall + 1))));
6733
+ return usage.inputTokens + (usage.outputTokens > 0 ? Math.min(said, usage.outputTokens) : said);
6734
+ }
6735
+ function measureContext(input) {
6736
+ const { messages, config } = input;
6737
+ const view = historyFromCheckpoint(messages);
6738
+ const system = estimateTokens(config.resolveSystemPrompt()) + estimateTokens(config.resolveToolSystemPrompts());
6739
+ const declared = toolsForCurrentModel(config).map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema }));
6740
+ const tools = declared.length ? estimateJson(declared) : 0;
6741
+ const summary = view.summary === void 0 ? 0 : estimateTokens(underPreamble(view.summary));
6742
+ const parts = { system, tools, summary, messages: estimateWireTokens(view.messages) };
6743
+ const total = system + tools + summary + parts.messages;
6744
+ let replyIndex = -1;
6745
+ for (let i = messages.length - 1; i >= 0; i--) {
6746
+ if (messages[i].role === "assistant" && messages[i].usage) {
6747
+ replyIndex = i;
6748
+ break;
6749
+ }
6750
+ }
6751
+ const reply = replyIndex >= 0 ? messages[replyIndex] : void 0;
6752
+ const window2 = windowOf(config, input.windowOverride);
6753
+ const result = (used, estimated) => ({
6754
+ ...window2 !== void 0 ? { window: window2 } : {},
6755
+ used,
6756
+ estimated,
6757
+ parts,
6758
+ other: Math.max(0, used - total)
6759
+ });
6760
+ const unchanged = reply !== void 0 && !input.viewChanged && replyIndex === messages.length - 1 && !messages.some((m) => m.contextSummary !== void 0 && m.contextSummary.createdAt > reply.timestamp);
6761
+ const k = reply ? calibration(reply) : 1;
6762
+ if (reply && unchanged) return result(nextRequestTokens(reply, k), false);
6763
+ return result(Math.round(k * total), true);
6764
+ }
6317
6765
  function eventOrigin(e) {
6318
6766
  return e.composedPath?.()[0] ?? e.target;
6319
6767
  }
@@ -6850,10 +7298,10 @@ function buildApprovalPanel(message, options, onChange, details) {
6850
7298
  function requestUserInput(request) {
6851
7299
  return resolveConfig(request.target ?? null).requestUserInput(request);
6852
7300
  }
6853
- const COMPACTION_PREAMBLE = "The earlier part of this conversation was compacted. This is a summary of what came before; continue from it.";
6854
7301
  const NOT_RUN_AFTER_A_REFUSAL = "Not run: an earlier call of the same step was refused.";
6855
7302
  const approvalKey = (call) => JSON.stringify([call.id, call.name, call.input]);
6856
7303
  const warnedUninlinedFiles = /* @__PURE__ */ new Set();
7304
+ const claimedConfigs = /* @__PURE__ */ new Map();
6857
7305
  const CHAT_SELECTOR = "aparte-chat, aparte-chat-viewport, [data-aparte-chat]";
6858
7306
  function remoteProvider(id) {
6859
7307
  return {
@@ -6879,6 +7327,28 @@ class AparteClient {
6879
7327
  _boundEditHandler = null;
6880
7328
  _releaseKeyResolver = null;
6881
7329
  _isAborted = false;
7330
+ /** Provider and model pairs whose window was already read again after a turn (see `_readWindowAfterTurn`). */
7331
+ _windowReadFor = /* @__PURE__ */ new Set();
7332
+ /**
7333
+ * The current model's window, read again once after a turn when it had none.
7334
+ *
7335
+ * A local server that loads a model on its first request — LM Studio's just-in-time
7336
+ * loading, Ollama — has no loaded window to report when the model list is fetched at
7337
+ * start-up, so the model comes without one, and the gauge and the compaction have
7338
+ * nothing to measure against. After a reply the model is loaded, and the provider's
7339
+ * own probe finds it. Once per provider and model: a server that never says costs one
7340
+ * request, not one per turn. The config announces the window when it appears.
7341
+ */
7342
+ async _readWindowAfterTurn() {
7343
+ const config = this._config;
7344
+ const model = config.getCurrentModel();
7345
+ const providerId = config.getModelConfig().defaultProvider;
7346
+ if (!model || model.contextWindow || !providerId) return;
7347
+ const key = `${providerId}\0${model.id}`;
7348
+ if (this._windowReadFor.has(key)) return;
7349
+ this._windowReadFor.add(key);
7350
+ await config.refreshProviderModels(providerId);
7351
+ }
6882
7352
  /**
6883
7353
  * Does this window event belong to this client?
6884
7354
  *
@@ -6895,7 +7365,12 @@ class AparteClient {
6895
7365
  const detail = e.detail;
6896
7366
  const scope = this.options.scopeToTargetId;
6897
7367
  if (scope) return detail?.targetId === scope;
6898
- if (this._config === aparteGlobalConfig) return true;
7368
+ if (this._config === aparteGlobalConfig) {
7369
+ if (claimedConfigs.size === 0) return true;
7370
+ const claimed = this._resolveTarget(detail?.targetId, e);
7371
+ const owner2 = claimed ? resolveConfig(claimed) : aparteGlobalConfig;
7372
+ return owner2 === aparteGlobalConfig || !claimedConfigs.has(owner2);
7373
+ }
6899
7374
  const target = this._resolveTarget(detail?.targetId, e);
6900
7375
  if (!target) return true;
6901
7376
  const owner = resolveConfig(target);
@@ -6906,6 +7381,8 @@ class AparteClient {
6906
7381
  options;
6907
7382
  /** Config read by this client — an instance config, or the global default. */
6908
7383
  _config;
7384
+ /** Whether this client, started on an instance config, counts in `claimedConfigs`. */
7385
+ _claims = false;
6909
7386
  /**
6910
7387
  * A `keyResolver` becomes a key source on the client's config at once, before `start()`,
6911
7388
  * so everything that needs a key can use it — the model selector's list included.
@@ -6975,6 +7452,10 @@ class AparteClient {
6975
7452
  */
6976
7453
  start() {
6977
7454
  this._registerKeyResolver();
7455
+ if (this._config !== aparteGlobalConfig && !this._claims) {
7456
+ this._claims = true;
7457
+ claimedConfigs.set(this._config, (claimedConfigs.get(this._config) ?? 0) + 1);
7458
+ }
6978
7459
  if (!this._boundHandler) {
6979
7460
  this._setupListeners();
6980
7461
  }
@@ -7020,6 +7501,12 @@ class AparteClient {
7020
7501
  */
7021
7502
  stop() {
7022
7503
  this.abort();
7504
+ if (this._claims) {
7505
+ this._claims = false;
7506
+ const left = (claimedConfigs.get(this._config) ?? 1) - 1;
7507
+ if (left > 0) claimedConfigs.set(this._config, left);
7508
+ else claimedConfigs.delete(this._config);
7509
+ }
7023
7510
  this._releaseKeyResolver?.();
7024
7511
  this._releaseKeyResolver = null;
7025
7512
  if (!this._listening || !this._boundHandler) return;
@@ -7160,19 +7647,23 @@ class AparteClient {
7160
7647
  async _streamTurn(targetElement, messageId, provider, messages, modelId, authConfig, opts) {
7161
7648
  const chatId = this._targetIdOf(targetElement);
7162
7649
  const registeredTools = this._toolsForCurrentModel();
7163
- let baseRequest = {
7164
- messages,
7165
- modelId,
7166
- stream: true,
7167
- tools: registeredTools.length ? registeredTools : void 0,
7168
- ...opts?.temperature !== void 0 ? { temperature: opts.temperature } : {}
7650
+ const buildRequest = async (requestMessages2) => {
7651
+ let built = {
7652
+ messages: requestMessages2,
7653
+ modelId,
7654
+ stream: true,
7655
+ tools: registeredTools.length ? registeredTools : void 0,
7656
+ ...opts?.temperature !== void 0 ? { temperature: opts.temperature } : {}
7657
+ };
7658
+ if (this.options.requestInterceptor) {
7659
+ built = await this.options.requestInterceptor(built);
7660
+ }
7661
+ if (built.toolChoice === "none") {
7662
+ built = { ...built, tools: void 0 };
7663
+ }
7664
+ return built;
7169
7665
  };
7170
- if (this.options.requestInterceptor) {
7171
- baseRequest = await this.options.requestInterceptor(baseRequest);
7172
- }
7173
- if (baseRequest.toolChoice === "none") {
7174
- baseRequest = { ...baseRequest, tools: void 0 };
7175
- }
7666
+ let baseRequest = await buildRequest(messages);
7176
7667
  if (this._isAborted) {
7177
7668
  dispatchLifecycleEvent(targetElement, "aparte-message-aborted", { messageId }, chatId);
7178
7669
  this._updateMessage(targetElement, messageId, { status: "completed" });
@@ -7193,8 +7684,24 @@ class AparteClient {
7193
7684
  if (this._streamController !== streamController) this._streamController?.abort();
7194
7685
  this._streamController = streamController;
7195
7686
  this._turnsInFlight.add(messageId);
7196
- try {
7197
- let result = opts?.resume ? { usage: void 0, suspended: opts.resume } : await this._streamLoop(targetElement, messageId, provider, baseRequest, authConfig, streamController);
7687
+ const compactor = opts?.rebuild ? resolveConfig(targetElement).getCompactor() ?? this._config.getCompactor() : null;
7688
+ const turnIds = () => {
7689
+ const path = targetElement.getMessages?.() ?? [];
7690
+ const at = path.findIndex((m) => m.id === messageId);
7691
+ const asked = at > 0 ? path[at - 1] : void 0;
7692
+ return asked?.role === "user" ? [asked.id, messageId] : [messageId];
7693
+ };
7694
+ const requestMessages = () => opts?.resume ? this._resumeMessages(targetElement, messageId, baseRequest.messages) : baseRequest.messages;
7695
+ const requestEstimate = () => estimateRequestTokens({ messages: requestMessages(), tools: baseRequest.tools });
7696
+ const recordedEstimate = () => carriesNonTextParts(requestMessages()) ? void 0 : requestEstimate();
7697
+ const endStopped = () => {
7698
+ this._closeOpenCalls(targetElement, messageId);
7699
+ dispatchLifecycleEvent(targetElement, "aparte-message-aborted", { messageId }, chatId);
7700
+ this._updateMessage(targetElement, messageId, { status: "completed" });
7701
+ };
7702
+ const isStopped = () => this._isAborted || streamController.signal.aborted;
7703
+ const runOnce = async () => {
7704
+ let result = opts?.resume ? { usage: void 0, suspended: opts.resume } : await this._streamLoop(targetElement, messageId, provider, baseRequest, authConfig, streamController, void 0, opts?.files);
7198
7705
  const maxResumes = this.options.maxTurns ?? 10;
7199
7706
  let resumes = 0;
7200
7707
  let approvedAtLastPause = /* @__PURE__ */ new Set();
@@ -7236,21 +7743,80 @@ class AparteClient {
7236
7743
  );
7237
7744
  }
7238
7745
  const usage = result.usage;
7746
+ const finishReason = result.finishReason;
7239
7747
  if (this._isAborted || streamController.signal.aborted) {
7240
7748
  this._closeOpenCalls(targetElement, messageId);
7241
7749
  this._updateMessage(targetElement, messageId, { status: "completed" });
7242
7750
  } else {
7243
- dispatchLifecycleEvent(targetElement, "aparte-message-done", { messageId, role: "assistant", usage }, chatId);
7751
+ dispatchLifecycleEvent(targetElement, "aparte-message-done", { messageId, role: "assistant", usage, ...finishReason ? { finishReason } : {} }, chatId);
7752
+ void this._readWindowAfterTurn();
7244
7753
  }
7245
- } catch (error) {
7246
- this._closeOpenCalls(targetElement, messageId);
7247
- if (this._isAborted || streamController.signal.aborted) {
7248
- dispatchLifecycleEvent(targetElement, "aparte-message-aborted", { messageId }, chatId);
7249
- this._updateMessage(targetElement, messageId, { status: "completed" });
7250
- return;
7754
+ };
7755
+ const resendAfterOverflow = async (error) => {
7756
+ if (error.code !== AparteErrorCode.USAGE_CONTEXT_EXCEEDED || !compactor || !opts?.rebuild) return "stands";
7757
+ const segments = targetElement.getMessage?.(messageId)?.segments ?? targetElement.getMessages?.()?.find((m) => m.id === messageId)?.segments ?? [];
7758
+ if (segments.some((s) => s.type === "text" || s.type === "tool_call")) return "stands";
7759
+ try {
7760
+ const outcome = await compactor.compact({
7761
+ target: targetElement,
7762
+ ...chatId ? { targetId: chatId } : {},
7763
+ force: true,
7764
+ reason: "overflow",
7765
+ exclude: turnIds(),
7766
+ signal: streamController.signal
7767
+ });
7768
+ if (isStopped()) return "stopped";
7769
+ if (!outcome.ok || outcome.skipped) return "stands";
7770
+ baseRequest = await buildRequest(await opts.rebuild());
7771
+ } catch {
7772
+ return "stands";
7773
+ }
7774
+ this._updateMessage(targetElement, messageId, { status: "pending" });
7775
+ return "resend";
7776
+ };
7777
+ try {
7778
+ for (let attempt = 0; ; attempt++) {
7779
+ try {
7780
+ if (attempt === 0 && compactor?.beforeSend && opts?.rebuild) {
7781
+ let compacted = false;
7782
+ try {
7783
+ compacted = await compactor.beforeSend({
7784
+ target: targetElement,
7785
+ ...chatId ? { targetId: chatId } : {},
7786
+ exclude: turnIds(),
7787
+ requestTokens: requestEstimate(),
7788
+ signal: streamController.signal
7789
+ });
7790
+ } catch (failure) {
7791
+ console.warn("[AparteClient] The compactor threw before a send; sending the request as built.", failure);
7792
+ }
7793
+ if (isStopped()) {
7794
+ endStopped();
7795
+ return;
7796
+ }
7797
+ if (compacted) baseRequest = await buildRequest(await opts.rebuild());
7798
+ }
7799
+ this._updateMessage(targetElement, messageId, { contextEstimate: recordedEstimate() });
7800
+ await runOnce();
7801
+ return;
7802
+ } catch (error) {
7803
+ this._closeOpenCalls(targetElement, messageId);
7804
+ if (isStopped()) {
7805
+ dispatchLifecycleEvent(targetElement, "aparte-message-aborted", { messageId }, chatId);
7806
+ this._updateMessage(targetElement, messageId, { status: "completed" });
7807
+ return;
7808
+ }
7809
+ const aparteError = AparteError.from(error, AparteErrorCode.UNKNOWN_ERROR);
7810
+ const next = attempt === 0 ? await resendAfterOverflow(aparteError) : "stands";
7811
+ if (next === "resend") continue;
7812
+ if (next === "stopped") {
7813
+ endStopped();
7814
+ return;
7815
+ }
7816
+ this._handleLifecycleError(targetElement, messageId, aparteError);
7817
+ return;
7818
+ }
7251
7819
  }
7252
- const aparteError = AparteError.from(error, AparteErrorCode.UNKNOWN_ERROR);
7253
- this._handleLifecycleError(targetElement, messageId, aparteError);
7254
7820
  } finally {
7255
7821
  this._turnsInFlight.delete(messageId);
7256
7822
  }
@@ -7265,29 +7831,12 @@ class AparteClient {
7265
7831
  * using the same conversation history minus the retried reply.
7266
7832
  */
7267
7833
  /**
7268
- * The registered tools, unless the current model says it cannot call one.
7269
- *
7270
- * Single source for the gate, so send / retry / edit cannot drift.
7271
- *
7272
- * The question is "did this model say it cannot", not "did it say it can": the
7273
- * app sets a model id by hand (`setModelConfig`) or a selector sets it from a
7274
- * fetched list, and in both cases the model's declared capabilities are commonly
7275
- * unknown. `undefined` capabilities read as "can", or `tools: []` would go on
7276
- * the wire while `getTools()` held the tool the app had explicitly registered,
7277
- * and the model would answer that it had no such tool. Registering a tool is an explicit act by the app; silently dropping it
7278
- * because a `/models` listing is terse is the library second-guessing the
7279
- * developer. A model that declares its capabilities and omits function calling
7280
- * is still honoured — that is a statement, and it is respected.
7281
- *
7282
- * Failure modes, both ways round: over-sending means a model that cannot use
7283
- * tools does not call one, or its own endpoint rejects the array with an error
7284
- * the developer can read. Under-sending would be silent, total, and look like a
7285
- * lying model.
7834
+ * The registered tools, unless the current model says it cannot call one — the gate
7835
+ * lives in `toolsForCurrentModel` (with its reasoning), where the context measure reads
7836
+ * the same rule, so send / retry / edit and the gauge cannot drift.
7286
7837
  */
7287
7838
  _toolsForCurrentModel() {
7288
- const capabilities = this._config.getCurrentModel()?.capabilities;
7289
- const declinesTools = capabilities ? !capabilities.includes("function_calling") : false;
7290
- return declinesTools ? [] : this._config.getTools();
7839
+ return toolsForCurrentModel(this._config);
7291
7840
  }
7292
7841
  async _handleRetry(event) {
7293
7842
  const { messageId, targetId } = event.detail ?? {};
@@ -7322,10 +7871,16 @@ class AparteClient {
7322
7871
  targetElement,
7323
7872
  newMessageId,
7324
7873
  provider,
7325
- [...systemMessages, ...chatMessages],
7874
+ [...systemMessages, ...mergeAdjacentUserMessages(chatMessages)],
7326
7875
  config.defaultModel || "",
7327
7876
  authConfig,
7328
- { temperature: 0.4 }
7877
+ {
7878
+ temperature: 0.4,
7879
+ rebuild: async () => [
7880
+ ...this._systemMessages(),
7881
+ ...mergeAdjacentUserMessages(this._messagesToChatMessages(this._current(targetElement, historyMessages)))
7882
+ ]
7883
+ }
7329
7884
  );
7330
7885
  }
7331
7886
  /**
@@ -7388,11 +7943,27 @@ class AparteClient {
7388
7943
  targetElement,
7389
7944
  newMessageId,
7390
7945
  provider,
7391
- [...systemMessages, ...chatMessages],
7946
+ [...systemMessages, ...mergeAdjacentUserMessages(chatMessages)],
7392
7947
  config.defaultModel || "",
7393
- authConfig
7948
+ authConfig,
7949
+ {
7950
+ rebuild: async () => [
7951
+ ...this._systemMessages(),
7952
+ ...mergeAdjacentUserMessages(this._messagesToChatMessages(this._current(targetElement, historyMessages)))
7953
+ ]
7954
+ }
7394
7955
  );
7395
7956
  }
7957
+ /**
7958
+ * These messages as the transcript holds them NOW. A retry or an edit slices the path
7959
+ * before it streams; a compaction that runs during the turn writes its checkpoint onto
7960
+ * one of those messages in the transcript, and the slice still holds the objects as they
7961
+ * were. Looked up by id, tree-wide, because a retry has moved the path since.
7962
+ */
7963
+ _current(target, messages) {
7964
+ const live2 = new Map((target.getMessages?.() ?? []).map((m) => [m.id, m]));
7965
+ return messages.map((m) => target.getMessage?.(m.id) ?? live2.get(m.id) ?? m);
7966
+ }
7396
7967
  /**
7397
7968
  * The chain the gesture really came up, nearest node first.
7398
7969
  *
@@ -7526,29 +8097,17 @@ class AparteClient {
7526
8097
  * imitating.
7527
8098
  */
7528
8099
  _messagesToChatMessages(messages) {
7529
- return this._wireHistory(messages);
8100
+ const { summary, messages: kept } = historyFromCheckpoint(messages);
8101
+ return [...this._summaryMessage(summary), ...wireMessages(kept)];
7530
8102
  }
7531
8103
  /**
7532
- * The one rule for what a message contributes to the wire.
7533
- *
7534
- * Not the slice — the contribution: a role the wire has (`user`/`assistant`), a
7535
- * turn that neither failed nor is still in flight, and text that is not empty.
7536
- *
7537
- * `_wireText` (not `m.content`): assistant replies stream their text into
7538
- * `segments`, leaving `content` as '', so without flattening every reply would be
7539
- * empty here and the drop below would swallow the whole transcript.
7540
- */
7541
- _wireHistory(messages) {
7542
- return messages.filter((m) => {
7543
- if (m.role !== "user" && m.role !== "assistant") return false;
7544
- return m.status !== "error" && !AparteClient._inFlight(m);
7545
- }).flatMap((m) => {
7546
- if (m.role === "assistant" && m.segments?.some((s) => s.type === "tool_call")) {
7547
- return wireTurns(m, (segments) => this._segmentsToText(segments));
7548
- }
7549
- const content = this._wireText(m);
7550
- return content ? [{ role: m.role, content }] : [];
7551
- });
8104
+ * What the model reads in place of everything before a checkpoint: the summary, as a
8105
+ * `user` message under the same preamble a legacy compaction message gets, so it is
8106
+ * context and not something the person said. It may sit right before a user turn;
8107
+ * `mergeAdjacentUserMessages` joins the two where the history is assembled.
8108
+ */
8109
+ _summaryMessage(summary) {
8110
+ return summary === void 0 ? [] : [{ role: "user", content: underPreamble(summary) }];
7552
8111
  }
7553
8112
  /** The "no model selected" warning is said once per client, not once per dropped send. */
7554
8113
  _warnedNoModel = false;
@@ -7638,12 +8197,14 @@ class AparteClient {
7638
8197
  });
7639
8198
  let authConfig;
7640
8199
  let messages;
8200
+ let fileParts;
8201
+ const rawFiles = Array.isArray(event.detail?.files) ? event.detail.files : [];
7641
8202
  try {
7642
8203
  authConfig = providerId ? await this._resolveAuth(providerId) : void 0;
7643
- const rawFiles = Array.isArray(event.detail?.files) ? event.detail.files : [];
7644
8204
  const filesToInject = this._selectFilesToInject(rawFiles);
7645
8205
  const contentParts = filesToInject.length > 0 ? await this._filesToContentParts(filesToInject) : [];
7646
- messages = this._buildMessages(content, targetElement, contentParts.length > 0 ? contentParts : void 0);
8206
+ fileParts = contentParts.length > 0 ? contentParts : void 0;
8207
+ messages = this._buildMessages(content, targetElement, fileParts);
7647
8208
  } catch (error) {
7648
8209
  this._handleLifecycleError(targetElement, messageId, AparteError.from(error, AparteErrorCode.UNKNOWN_ERROR));
7649
8210
  return;
@@ -7654,7 +8215,11 @@ class AparteClient {
7654
8215
  provider,
7655
8216
  messages,
7656
8217
  modelId || config.defaultModel || "",
7657
- authConfig
8218
+ authConfig,
8219
+ {
8220
+ rebuild: async () => this._buildMessages(content, targetElement, fileParts),
8221
+ ...rawFiles.length > 0 ? { files: rawFiles } : {}
8222
+ }
7658
8223
  );
7659
8224
  }
7660
8225
  /**
@@ -7671,101 +8236,18 @@ class AparteClient {
7671
8236
  }
7672
8237
  const userMsg = parts && parts.length > 0 ? [{ type: "text", text: userContent }, ...parts] : userContent;
7673
8238
  messages.push({ role: "user", content: userMsg });
7674
- return messages;
8239
+ return mergeAdjacentUserMessages(messages);
7675
8240
  }
7676
- /**
7677
- * A turn that has not finished yet. `status` is OPTIONAL on `AparteMessage`, so
7678
- * the question the history gates can ask is "is this still in flight?", never
7679
- * "is this completed?".
7680
- *
7681
- * The gates below ask the first, because a host that SEEDS a transcript
7682
- * — restoring a saved conversation, hydrating a server-rendered one — has no
7683
- * reason to invent a status for turns that are already over. Asking "is this
7684
- * completed?" would leave the cutoff at 0 and slice away the whole transcript: the
7685
- * model would get the new question with no context, and nothing in the UI would say
7686
- * so, because the viewport still shows every message.
7687
- */
7688
- static _inFlight(m) {
7689
- return m.status === "streaming" || m.status === "pending";
7690
- }
7691
- _toHistoryMessages(messages) {
8241
+ _toHistoryMessages(path) {
8242
+ const { summary, messages } = historyFromCheckpoint(path);
7692
8243
  let cutoff = 0;
7693
8244
  for (let i = 0; i < messages.length; i++) {
7694
8245
  const m = messages[i];
7695
- if (m.role === "assistant" && m.status !== "error" && !AparteClient._inFlight(m)) {
8246
+ if (m.role === "assistant" && m.status !== "error" && !isInFlight(m)) {
7696
8247
  cutoff = i + 1;
7697
8248
  }
7698
8249
  }
7699
- return this._wireHistory(messages.slice(0, cutoff));
7700
- }
7701
- /**
7702
- * A message's text as the MODEL should read it — the one mapper both history
7703
- * paths use, so the compaction preamble cannot be applied on retry and edit and
7704
- * forgotten on the ordinary send, which is what the first review of this feature
7705
- * caught: the summary went out on every normal turn as something the user said.
7706
- */
7707
- _wireText(message) {
7708
- const text = this._extractText(message);
7709
- return message.compaction ? `${COMPACTION_PREAMBLE}
7710
-
7711
- ${text}` : text;
7712
- }
7713
- /**
7714
- * What the model is told it said last turn — reconstructed from what was
7715
- * RENDERED, not from the raw-text field.
7716
- *
7717
- * The segments are what the reader saw, so they come first. `content` is the
7718
- * fallback, and that is not vestigial: a non-streaming transport writes the whole
7719
- * reply there and creates no segments at all.
7720
- */
7721
- _extractText(message) {
7722
- const rendered = this._segmentsToText(message.segments);
7723
- if (rendered) return rendered;
7724
- if (typeof message.content === "string" && message.content) return message.content;
7725
- return "";
7726
- }
7727
- /**
7728
- * Segments → the text a model can read back.
7729
- *
7730
- * Fences and the language tag are kept. Without them the model re-reads its own
7731
- * code as prose — which is how it starts explaining a snippet it believes it
7732
- * wrote in English.
7733
- *
7734
- * A type core does not know — a registered block grammar's (an artifact, a
7735
- * citation, a file), a consumer's custom segment — follows one rule: its
7736
- * `content` if it has one, else its `fallback`, else nothing. Dropping such a
7737
- * segment would make a document the model had just produced invisible on the very
7738
- * next turn, so it could not be asked to change the thing it had built. An artifact
7739
- * is a plugin's type like any other and follows this rule.
7740
- *
7741
- * `thinking` and `tool_call` stay out on purpose — the first is the model's own
7742
- * scratchpad, and most APIs neither want it back nor bill for it kindly; the
7743
- * second is not text: `_wireHistory` sends a reply's calls as the assistant's
7744
- * `toolCalls` and the `tool` messages answering them (`wire-history.ts`).
7745
- */
7746
- _segmentsToText(segments) {
7747
- if (!segments?.length) return "";
7748
- const fence = "```";
7749
- const parts = [];
7750
- for (const segment of segments) {
7751
- const content = segment.content;
7752
- if (segment.type === "text") {
7753
- if (content) parts.push(content);
7754
- } else if (segment.type === "code") {
7755
- const lang = segment.language ?? "";
7756
- parts.push(`${fence}${lang}
7757
- ${content ?? ""}
7758
- ${fence}`);
7759
- } else if (segment.type === "thinking" || segment.type === "tool_call" || segment.type === "error") {
7760
- continue;
7761
- } else if (typeof content === "string" && content) {
7762
- parts.push(content);
7763
- } else {
7764
- const fallback = segment.fallback;
7765
- if (fallback) parts.push(fallback);
7766
- }
7767
- }
7768
- return parts.join("\n").trim();
8250
+ return [...this._summaryMessage(summary), ...wireMessages(messages.slice(0, cutoff))];
7769
8251
  }
7770
8252
  /**
7771
8253
  * Which of the send's pending files get inlined into the request: the
@@ -7846,11 +8328,11 @@ ${content}
7846
8328
  * adapter, or the runner a host injected — after the fetch-level abort bookkeeping.
7847
8329
  */
7848
8330
  /** One run of the loop: its usage, and whether it paused (a server loop). */
7849
- async _streamLoop(targetElement, messageId, provider, baseRequest, authConfig, streamController = new AbortController(), deferral) {
8331
+ async _streamLoop(targetElement, messageId, provider, baseRequest, authConfig, streamController = new AbortController(), deferral, files) {
7850
8332
  if (this._streamController !== streamController) this._streamController?.abort();
7851
8333
  this._streamController = streamController;
7852
8334
  const runner = this.options.streamRunner ?? runStreamAgent;
7853
- return this._runViaStreamRunner(runner, targetElement, messageId, provider, baseRequest, authConfig, streamController, deferral);
8335
+ return this._runViaStreamRunner(runner, targetElement, messageId, provider, baseRequest, authConfig, streamController, deferral, files);
7854
8336
  }
7855
8337
  /**
7856
8338
  * Run the loop through a {@link AparteStreamRunner} — the engine's by default —
@@ -7861,7 +8343,7 @@ ${content}
7861
8343
  * produces is pinned by the `stream-parity` suite's snapshots, recorded while
7862
8344
  * the inline loop it replaced still ran beside it.
7863
8345
  */
7864
- async _runViaStreamRunner(streamRunner, targetElement, messageId, provider, baseRequest, authConfig, streamController, deferral) {
8346
+ async _runViaStreamRunner(streamRunner, targetElement, messageId, provider, baseRequest, authConfig, streamController, deferral, files) {
7865
8347
  const signal = streamController.signal;
7866
8348
  const chatId = this._targetIdOf(targetElement);
7867
8349
  const adapter = createStreamAdapter({
@@ -7872,8 +8354,12 @@ ${content}
7872
8354
  });
7873
8355
  const prefixSegments = baseRequest._meta?.["prefixSegments"];
7874
8356
  let suspended;
8357
+ let finishReason;
8358
+ let toolCrash;
7875
8359
  const emitter = (event) => {
7876
8360
  adapter(event);
8361
+ if (event.type === "tool-failed") toolCrash = event.error;
8362
+ if (event.type === "run-done") finishReason = event.finishReason;
7877
8363
  if (event.type === "run-suspended") {
7878
8364
  const ticket = event.ticket;
7879
8365
  suspended = { pending: event.pending, ...typeof ticket === "string" ? { ticket } : {} };
@@ -7905,10 +8391,16 @@ ${content}
7905
8391
  };
7906
8392
  };
7907
8393
  const approvalResolver = this._approvalResolverFor(targetElement);
8394
+ const asToolCrash = (error) => {
8395
+ if (toolCrash === void 0 || error instanceof AparteError) return error;
8396
+ const text = error instanceof Error ? error.message || error.name : typeof error === "string" ? error : String(error);
8397
+ return text === toolCrash ? new AparteError(text, AparteErrorCode.UNKNOWN_ERROR, void 0, error) : error;
8398
+ };
7908
8399
  const usage = await streamRunner({
7909
8400
  messageId,
7910
8401
  ...provider.id ? { providerId: provider.id } : {},
7911
8402
  ...deferral ? { deferral } : {},
8403
+ ...files && files.length > 0 ? { files } : {},
7912
8404
  baseRequest,
7913
8405
  transportCall,
7914
8406
  toolLookup,
@@ -7925,8 +8417,14 @@ ${content}
7925
8417
  // The id conventions the loop always had: prefixed artifact ids, but a
7926
8418
  // BARE uuid for the synthetic tool (the adapter renders `tool-<id>`).
7927
8419
  idGen: (prefix) => prefix === "synthetic-tool" ? uuid() : `${prefix}-${uuid()}`
8420
+ }).catch((error) => {
8421
+ throw asToolCrash(error);
7928
8422
  });
7929
- return { usage: usage ?? void 0, ...suspended ? { suspended } : {} };
8423
+ return {
8424
+ usage: usage ?? void 0,
8425
+ ...finishReason ? { finishReason } : {},
8426
+ ...suspended ? { suspended } : {}
8427
+ };
7930
8428
  }
7931
8429
  /**
7932
8430
  * The approval channel a run asks through — and the one a paused server run's calls
@@ -8077,7 +8575,7 @@ ${content}
8077
8575
  */
8078
8576
  _resumeMessages(targetElement, messageId, sent) {
8079
8577
  const reply = targetElement.getMessages?.().find((m) => m.id === messageId);
8080
- return [...sent, ...reply ? wireTurns(reply, (segments) => this._segmentsToText(segments), { openDeferred: true }) : []];
8578
+ return [...sent, ...reply ? wireTurns(reply, segmentsToWireText, { openDeferred: true }) : []];
8081
8579
  }
8082
8580
  /**
8083
8581
  * What the send of a reloaded turn put before its reply, rebuilt the way
@@ -8092,7 +8590,11 @@ ${content}
8092
8590
  const askedAt = before.map((m) => m.role).lastIndexOf("user");
8093
8591
  const historyOption = this.options.history ?? "viewport";
8094
8592
  const history = historyOption === "viewport" ? this._toHistoryMessages(before) : typeof historyOption === "function" ? historyOption(before) : [];
8095
- return [...this._systemMessages(), ...history, ...askedAt >= 0 ? this._wireHistory([before[askedAt]]) : []];
8593
+ return mergeAdjacentUserMessages([
8594
+ ...this._systemMessages(),
8595
+ ...history,
8596
+ ...askedAt >= 0 ? wireMessages([before[askedAt]]) : []
8597
+ ]);
8096
8598
  }
8097
8599
  /**
8098
8600
  * A new message closes a wait nobody answered. The paused calls of the last reply are
@@ -8153,6 +8655,11 @@ ${content}
8153
8655
  const base = this._resumeBase(messages, messages.indexOf(last));
8154
8656
  await this._streamTurn(targetElement, last.id, provider, base, recorded?.modelId ?? config.defaultModel ?? "", authConfig, {
8155
8657
  resume: { pending: pending2, ticket },
8658
+ rebuild: async () => {
8659
+ const now = targetElement.getMessages?.() ?? [];
8660
+ const at = now.findIndex((m) => m.id === last.id);
8661
+ return at >= 0 ? this._resumeBase(now, at) : base;
8662
+ },
8156
8663
  ...recorded?.temperature !== void 0 ? { temperature: recorded.temperature } : {}
8157
8664
  });
8158
8665
  } finally {
@@ -8180,6 +8687,9 @@ ${content}
8180
8687
  content: error.message,
8181
8688
  code: error.code
8182
8689
  };
8690
+ if (errorSentence(error.code, (key) => this._config.t(key)) !== void 0) {
8691
+ console.warn(`[aparte] A turn failed (${error.code}): ${error.message}`);
8692
+ }
8183
8693
  if (target.updateMessage) {
8184
8694
  const rendered = target.getMessage?.(messageId)?.segments ?? target.getMessages?.()?.find((m) => m.id === messageId)?.segments ?? [];
8185
8695
  target.updateMessage(messageId, {
@@ -8232,7 +8742,8 @@ function createAgentStreamRunner(options) {
8232
8742
  let ended = false;
8233
8743
  for await (const line of readNdjson(response.body, opts.signal)) {
8234
8744
  if (line.type === "run-error") {
8235
- throw new AparteError(line.message || "The agent run failed.", AparteErrorCode.PROVIDER_ERROR, line.code ? { code: line.code } : void 0);
8745
+ const known2 = Object.values(AparteErrorCode).includes(line.code ?? "") ? line.code : void 0;
8746
+ throw new AparteError(line.message || "The agent run failed.", known2 ?? AparteErrorCode.PROVIDER_ERROR, line.code ? { code: line.code } : void 0);
8236
8747
  }
8237
8748
  if (line.type === "run-done" || line.type === "run-suspended") {
8238
8749
  usage = line.usage;
@@ -8558,6 +9069,7 @@ const APARTE_DEFAULT_UI_EVENTS = [
8558
9069
  "aparte-scroll-rail-jump",
8559
9070
  "aparte-sidebar-toggle",
8560
9071
  "aparte-split-resize",
9072
+ "aparte-launcher-toggle",
8561
9073
  // the turn's lifecycle, dispatched on the HOST element by `dispatchLifecycleEvent`
8562
9074
  "aparte-message-start",
8563
9075
  "aparte-message-done",
@@ -8727,7 +9239,7 @@ function deferHydrationOf(ctor) {
8727
9239
  };
8728
9240
  }
8729
9241
  export {
8730
- parseMarkdownToSegments as $,
9242
+ isSegmentSettled as $,
8731
9243
  APARTE_CONFIG_CHANGE as A,
8732
9244
  contextConfig as B,
8733
9245
  copyText as C,
@@ -8744,57 +9256,64 @@ export {
8744
9256
  detachConfig as N,
8745
9257
  escapeAttr as O,
8746
9258
  escapeHtml as P,
8747
- filesToAttachments as Q,
8748
- getAllRenderers as R,
8749
- getSegmentRenderer as S,
8750
- installDefaultRenderersOnce as T,
8751
- installDialogTriggersOnce as U,
8752
- isAwaitingReply as V,
8753
- isFormatAdapter as W,
8754
- isSafeUrl as X,
8755
- isSegmentSettled as Y,
8756
- overrideSegmentRenderer as Z,
8757
- parseAparteEventStream as _,
9259
+ estimateTokens as Q,
9260
+ estimateWireTokens as R,
9261
+ filesToAttachments as S,
9262
+ getAllRenderers as T,
9263
+ getSegmentRenderer as U,
9264
+ historyFromCheckpoint as V,
9265
+ installDefaultRenderersOnce as W,
9266
+ installDialogTriggersOnce as X,
9267
+ isAwaitingReply as Y,
9268
+ isFormatAdapter as Z,
9269
+ isSafeUrl as _,
8758
9270
  APARTE_CONVERSATION_SCHEMA_VERSION as a,
8759
- populateBubbleFromMessage as a0,
8760
- readableToAsyncIterable as a1,
8761
- registerDefaultRenderers as a2,
8762
- registerSegmentRenderer as a3,
8763
- releaseDeferredHydration as a4,
8764
- requestUserInput as a5,
8765
- resolveConfig as a6,
8766
- revokeAttachmentUrls as a7,
8767
- runWithConfig as a8,
8768
- segmentDuration as a9,
8769
- conversationStatusOf as aA,
8770
- chatBoundaryOf as aB,
8771
- rootOf as aC,
8772
- segmentTiming as aa,
8773
- subscribeConfigChange as ab,
8774
- toToolCallView as ac,
8775
- toolRefusal as ad,
8776
- unregisterSegmentRenderer as ae,
8777
- uuid as af,
8778
- eventOrigin as ag,
8779
- activeElementIn as ah,
8780
- gateGlide as ai,
8781
- toolCallRenderer as aj,
8782
- toolRendererThatDrew as ak,
8783
- isMountedRenderer as al,
8784
- renderingVersionOf as am,
8785
- onRenderersChange as an,
8786
- mergeSegmentUpdate as ao,
8787
- writeStreamedMarkdown as ap,
8788
- stampSegmentActivity as aq,
8789
- stampSegmentOnInsert as ar,
8790
- stampSegmentOnUpdate as as,
8791
- renumberSegments as at,
8792
- openSegmentIds as au,
8793
- isTerminalStatus as av,
8794
- adoptMessageSegments as aw,
8795
- APARTE_DERIVED_SEGMENTS as ax,
8796
- rememberConversationStatus as ay,
8797
- tellConversationStatus as az,
9271
+ measureContext as a0,
9272
+ overrideSegmentRenderer as a1,
9273
+ parseAparteEventStream as a2,
9274
+ parseMarkdownToSegments as a3,
9275
+ populateBubbleFromMessage as a4,
9276
+ readableToAsyncIterable as a5,
9277
+ registerDefaultRenderers as a6,
9278
+ registerSegmentRenderer as a7,
9279
+ releaseDeferredHydration as a8,
9280
+ requestUserInput as a9,
9281
+ renumberSegments as aA,
9282
+ openSegmentIds as aB,
9283
+ isTerminalStatus as aC,
9284
+ adoptMessageSegments as aD,
9285
+ APARTE_DERIVED_SEGMENTS as aE,
9286
+ rememberConversationStatus as aF,
9287
+ tellConversationStatus as aG,
9288
+ conversationStatusOf as aH,
9289
+ usageTokens as aI,
9290
+ rootOf as aJ,
9291
+ resolveConfig as aa,
9292
+ revokeAttachmentUrls as ab,
9293
+ runWithConfig as ac,
9294
+ segmentDuration as ad,
9295
+ segmentTiming as ae,
9296
+ subscribeConfigChange as af,
9297
+ toToolCallView as ag,
9298
+ toolRefusal as ah,
9299
+ unregisterSegmentRenderer as ai,
9300
+ uuid as aj,
9301
+ eventOrigin as ak,
9302
+ activeElementIn as al,
9303
+ gateGlide as am,
9304
+ chatBoundaryOf as an,
9305
+ toolCallRenderer as ao,
9306
+ toolRendererThatDrew as ap,
9307
+ isMountedRenderer as aq,
9308
+ renderingVersionOf as ar,
9309
+ onRenderersChange as as,
9310
+ mergeSegmentUpdate as at,
9311
+ writeStreamedMarkdown as au,
9312
+ CheckpointStateWatcher as av,
9313
+ chatIdOf as aw,
9314
+ stampSegmentActivity as ax,
9315
+ stampSegmentOnInsert as ay,
9316
+ stampSegmentOnUpdate as az,
8798
9317
  APARTE_DEFAULT_BUBBLE_ACTIONS as b,
8799
9318
  APARTE_DEFAULT_HOST_HANDLERS as c,
8800
9319
  APARTE_DEFAULT_ICON_FALLBACKS as d,
@@ -8821,4 +9340,4 @@ export {
8821
9340
  collectRendererStyles as y,
8822
9341
  contentToText as z
8823
9342
  };
8824
- //# sourceMappingURL=defer-hydration-BwMqeRHq.js.map
9343
+ //# sourceMappingURL=defer-hydration-DSZE-bKi.js.map