@aibranch/llm-meta-widget 0.12.1 → 0.12.2

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.
package/README.md CHANGED
@@ -61,7 +61,7 @@ Option 3 if it does not.
61
61
 
62
62
  ```ruby
63
63
  # Gemfile
64
- gem "llm_meta_widget", "~> 0.12.1"
64
+ gem "llm_meta_widget", "~> 0.12.2"
65
65
  ```
66
66
 
67
67
  ```bash
@@ -178,6 +178,8 @@ async function runChatLoop(opts) {
178
178
  // Called when a tool result is dropped to make room, so the panel can say
179
179
  // so rather than the context quietly thinning.
180
180
  onContextEvicted,
181
+ // Called when one oversized result is shortened, so the panel can say so.
182
+ onContextTruncated,
181
183
  // "hub" (default) talks to llm_meta_server; "ollama" talks straight to an
182
184
  // Ollama, with no server component of ours in between. The loop is the
183
185
  // same either way — only the call is swapped.
@@ -211,6 +213,7 @@ async function runChatLoop(opts) {
211
213
  const mergedLocalTools = Object.values(inlineByName);
212
214
  const rounds = [];
213
215
  const evicted = [];
216
+ const truncatedResults = [];
214
217
  const toolsTokens = estimateToolsTokens([].concat(
215
218
  singleOpts.localTools || [],
216
219
  remoteTools || [],
@@ -246,6 +249,15 @@ async function runChatLoop(opts) {
246
249
  for (let round = 0; round < maxRounds; round++) {
247
250
  if (signal?.aborted) throw new DOMException("aborted", "AbortError");
248
251
  onRoundStart?.(round);
252
+ const capped = truncateOversizedToolResults({
253
+ messages,
254
+ window: contextWindow,
255
+ truncated: truncatedResults
256
+ });
257
+ if (capped.messages !== messages) {
258
+ messages = capped.messages;
259
+ onContextTruncated?.(truncatedResults.slice());
260
+ }
249
261
  const room = evictOldToolResults({
250
262
  messages,
251
263
  window: contextWindow,
@@ -255,7 +267,7 @@ async function runChatLoop(opts) {
255
267
  });
256
268
  if (room.messages !== messages) {
257
269
  messages = room.messages;
258
- onContextEvicted?.(evicted.slice());
270
+ onContextEvicted?.({ dropped: evicted.slice(), needed: room.needed, window: room.window });
259
271
  }
260
272
  const call = provider === "ollama" ? ollamaChatCall : singleLlmCall;
261
273
  const turnResult = await call({
@@ -622,10 +634,34 @@ function estimateToolsTokens(tools) {
622
634
  })).join("");
623
635
  return estimateTextTokens(text);
624
636
  }
637
+ var MAX_TOOL_RESULT_SHARE = 0.4;
638
+ function truncateOversizedToolResults({
639
+ messages,
640
+ window: window2,
641
+ share = MAX_TOOL_RESULT_SHARE,
642
+ truncated = []
643
+ } = {}) {
644
+ if (!window2 || !Number.isFinite(window2)) return { messages, truncated };
645
+ const cap = Math.floor(window2 * share);
646
+ let out = null;
647
+ (messages || []).forEach((m, i) => {
648
+ if (m?.role !== "tool" || typeof m.content !== "string") return;
649
+ const tokens = estimateTextTokens(m.content);
650
+ if (tokens <= cap) return;
651
+ const keep = Math.max(1, Math.floor(m.content.length * cap / tokens));
652
+ out = out || messages.slice();
653
+ truncated.push({ name: m.name, fromTokens: tokens, toTokens: cap });
654
+ out[i] = Object.assign({}, m, {
655
+ content: m.content.slice(0, keep) + "\n\n[truncated: " + keep + " of " + m.content.length + " characters shown. One tool result may use at most " + Math.round(share * 100) + "% of the context window. Call the tool again with a narrower query to see more.]"
656
+ });
657
+ });
658
+ return { messages: out || messages, truncated };
659
+ }
625
660
  function evictOldToolResults({ messages, window: window2, reserve = 0, dropped = [] }) {
626
661
  if (!window2 || !Number.isFinite(window2)) return { messages, dropped };
627
662
  const budget = window2 - reserve;
628
- if (estimateTokens(messages) <= budget) return { messages, dropped };
663
+ const needed = estimateTokens(messages) + reserve;
664
+ if (estimateTokens(messages) <= budget) return { messages, dropped, needed, window: window2 };
629
665
  const out = messages.slice();
630
666
  for (let i = 0; i < out.length; i++) {
631
667
  if (estimateTokens(out) <= budget) break;
@@ -637,7 +673,7 @@ function evictOldToolResults({ messages, window: window2, reserve = 0, dropped =
637
673
  content: "[dropped to make room in the context window. Call the tool again if you still need it, with a narrower query.]"
638
674
  });
639
675
  }
640
- return { messages: out, dropped };
676
+ return { messages: out, dropped, needed, window: window2 };
641
677
  }
642
678
  function modelWindowFrom(payload, modelId) {
643
679
  for (const family of payload && payload.llms || []) {
@@ -3952,6 +3988,9 @@ function boot(cfg) {
3952
3988
  var toggleBtn = document.getElementById("llm-meta-widget-toggle");
3953
3989
  var historyEl = root.querySelector(".lmw-messages");
3954
3990
  var SCROLL_PIN_SLACK = 40;
3991
+ function thousands(n) {
3992
+ return (Math.round(n / 1e3) * 1e3).toLocaleString("en-US");
3993
+ }
3955
3994
  function atBottom() {
3956
3995
  return historyEl.scrollHeight - historyEl.scrollTop - historyEl.clientHeight <= SCROLL_PIN_SLACK;
3957
3996
  }
@@ -4643,14 +4682,27 @@ function boot(cfg) {
4643
4682
  return body;
4644
4683
  }
4645
4684
  function collapseThinkingBlock() {
4646
- if (currentThinkingBlock) {
4647
- currentThinkingBlock.classList.remove("thinking-active");
4648
- currentThinkingBlock.open = false;
4649
- var summary = currentThinkingBlock.querySelector("summary");
4650
- if (summary) summary.textContent = "\u{1F914} thinking (finished)";
4651
- }
4685
+ var block2 = currentThinkingBlock;
4652
4686
  currentThinkingBlock = null;
4653
4687
  currentThinkingBody = null;
4688
+ if (!block2) return;
4689
+ block2.classList.remove("thinking-active");
4690
+ var summary = block2.querySelector("summary");
4691
+ if (summary) summary.textContent = "\u{1F914} thinking (finished)";
4692
+ var body = block2.querySelector(".message-thinking-content");
4693
+ if (body) {
4694
+ body.style.overflow = "visible";
4695
+ body.style.maxHeight = "none";
4696
+ }
4697
+ if (typeof requestAnimationFrame !== "function") {
4698
+ block2.open = false;
4699
+ return;
4700
+ }
4701
+ requestAnimationFrame(function() {
4702
+ requestAnimationFrame(function() {
4703
+ block2.open = false;
4704
+ });
4705
+ });
4654
4706
  }
4655
4707
  function stateReaders() {
4656
4708
  var declared = window[STATE_GLOBAL] || {};
@@ -4793,10 +4845,18 @@ function boot(cfg) {
4793
4845
  contextWindow: modelWindow,
4794
4846
  provider: LLM_PROVIDER === "ollama" ? "ollama" : "hub",
4795
4847
  signal: currentAbort.signal,
4796
- onContextEvicted: function(dropped) {
4797
- var last = dropped[dropped.length - 1];
4798
- var name = last && last.name ? last.name : "tool";
4799
- appendTurn("system", "Dropped an earlier " + name + " result to make room in the model's context. Ask again if you need it.");
4848
+ onContextTruncated: function(list2) {
4849
+ var cut = list2[list2.length - 1] || {};
4850
+ appendTurn("system", "Shortened an oversized " + (cut.name || "tool") + " result to fit the context: " + thousands(cut.fromTokens || 0) + " tokens, where one result may use at most " + thousands(cut.toTokens || 0) + ". Ask again with a narrower question for the complete result.");
4851
+ },
4852
+ onContextEvicted: function(info) {
4853
+ var dropped = info.dropped || [];
4854
+ var names = dropped.map(function(d) {
4855
+ return d.name || "a tool";
4856
+ });
4857
+ var what = names.length === 1 ? "the earliest tool result (" + names[0] + ")" : "the " + names.length + " earliest tool results (" + names.join(", ") + ")";
4858
+ var sizes = info.needed && info.window ? " About " + thousands(info.needed) + " tokens were needed and " + thousands(info.window) + " fit in " + MODEL + "'s context." : "";
4859
+ appendTurn("system", "Dropped " + what + " to make room." + sizes + " Ask again, or narrow the question, for an answer based on complete tool results.");
4800
4860
  },
4801
4861
  onToolCall: function(toolCall) {
4802
4862
  announceToolCall(toolCall);
@@ -335,6 +335,8 @@ export async function runChatLoop(opts) {
335
335
  // Called when a tool result is dropped to make room, so the panel can say
336
336
  // so rather than the context quietly thinning.
337
337
  onContextEvicted,
338
+ // Called when one oversized result is shortened, so the panel can say so.
339
+ onContextTruncated,
338
340
  // "hub" (default) talks to llm_meta_server; "ollama" talks straight to an
339
341
  // Ollama, with no server component of ours in between. The loop is the
340
342
  // same either way — only the call is swapped.
@@ -377,6 +379,7 @@ export async function runChatLoop(opts) {
377
379
 
378
380
  const rounds = []
379
381
  const evicted = []
382
+ const truncatedResults = []
380
383
  // Fixed for the turn: the declared tool set does not change between rounds.
381
384
  const toolsTokens = estimateToolsTokens([].concat(
382
385
  singleOpts.localTools || [], remoteTools || [], hostWideTools || []))
@@ -422,6 +425,16 @@ export async function runChatLoop(opts) {
422
425
  onRoundStart?.(round)
423
426
 
424
427
  // The loop is the same whoever answers; only the call differs.
428
+ // One oversized result is capped first: it frees hundreds of times more
429
+ // than dropping old results, and keeps what the model asked for.
430
+ const capped = truncateOversizedToolResults({
431
+ messages, window: contextWindow, truncated: truncatedResults
432
+ });
433
+ if (capped.messages !== messages) {
434
+ messages = capped.messages;
435
+ onContextTruncated?.(truncatedResults.slice());
436
+ }
437
+
425
438
  // Make room before sending, rather than after being refused. Only old
426
439
  // tool results are given up; see evictOldToolResults.
427
440
  const room = evictOldToolResults({
@@ -431,7 +444,7 @@ export async function runChatLoop(opts) {
431
444
  });
432
445
  if (room.messages !== messages) {
433
446
  messages = room.messages;
434
- onContextEvicted?.(evicted.slice());
447
+ onContextEvicted?.({ dropped: evicted.slice(), needed: room.needed, window: room.window });
435
448
  }
436
449
 
437
450
  const call = provider === "ollama" ? ollamaChatCall : singleLlmCall
@@ -1003,6 +1016,55 @@ export function estimateToolsTokens(tools) {
1003
1016
  return estimateTextTokens(text)
1004
1017
  }
1005
1018
 
1019
+ // A single tool result may use at most this share of the window.
1020
+ //
1021
+ // Measured over 179 real tool results (2026-10-17): the median is 2.1% of the
1022
+ // window and the 90th percentile 20%, but one `togovar_search_variant` result
1023
+ // came to 94% — 120,667 tokens — and alone could not coexist with a
1024
+ // conversation. All six over-budget requests in that sample were caused by one
1025
+ // oversized result, so capping it clears every one of them while touching only
1026
+ // 4.5% of results at all.
1027
+ //
1028
+ // 40% keeps a useful prefix of even the worst result (42% of it) and still
1029
+ // leaves most of the window for the conversation, the schemas and the answer.
1030
+ export const MAX_TOOL_RESULT_SHARE = 0.4
1031
+
1032
+ // Shortens any single tool result that exceeds that share.
1033
+ //
1034
+ // This runs BEFORE eviction, because it is strictly the better move: on the
1035
+ // audited turn it frees ~69,000 tokens from one result, where dropping the
1036
+ // oldest results freed 160 and lost two results the model had asked for. The
1037
+ // model is told what happened, in the result itself, so it can narrow its
1038
+ // query instead of assuming it received everything.
1039
+ export function truncateOversizedToolResults({ messages, window,
1040
+ share = MAX_TOOL_RESULT_SHARE,
1041
+ truncated = [] } = {}) {
1042
+ if (!window || !Number.isFinite(window)) return { messages, truncated }
1043
+
1044
+ const cap = Math.floor(window * share)
1045
+ let out = null
1046
+
1047
+ ;(messages || []).forEach((m, i) => {
1048
+ if (m?.role !== "tool" || typeof m.content !== "string") return
1049
+ const tokens = estimateTextTokens(m.content)
1050
+ if (tokens <= cap) return
1051
+
1052
+ // Scale the cut by the measured ratio rather than a fixed chars-per-token,
1053
+ // so a dense result is cut by what it actually costs.
1054
+ const keep = Math.max(1, Math.floor(m.content.length * cap / tokens))
1055
+ out = out || messages.slice()
1056
+ truncated.push({ name: m.name, fromTokens: tokens, toTokens: cap })
1057
+ out[i] = Object.assign({}, m, {
1058
+ content: m.content.slice(0, keep) +
1059
+ "\n\n[truncated: " + keep + " of " + m.content.length + " characters shown. " +
1060
+ "One tool result may use at most " + Math.round(share * 100) +
1061
+ "% of the context window. Call the tool again with a narrower query to see more.]"
1062
+ })
1063
+ })
1064
+
1065
+ return { messages: out || messages, truncated }
1066
+ }
1067
+
1006
1068
  // Makes room for the next round by dropping the OLDEST tool results, which is
1007
1069
  // the one eviction a chat loop can justify: the model has already read them and
1008
1070
  // said what it made of them in the assistant turn that follows, so its own
@@ -1021,7 +1083,12 @@ export function evictOldToolResults({ messages, window, reserve = 0, dropped = [
1021
1083
  if (!window || !Number.isFinite(window)) return { messages, dropped }
1022
1084
 
1023
1085
  const budget = window - reserve
1024
- if (estimateTokens(messages) <= budget) return { messages, dropped }
1086
+ // What the whole turn would have needed, against what the model holds. The
1087
+ // panel shows both, because "an old result was dropped" on its own tells a
1088
+ // reader nothing about whether to retry, shorten the question, or change
1089
+ // model.
1090
+ const needed = estimateTokens(messages) + reserve
1091
+ if (estimateTokens(messages) <= budget) return { messages, dropped, needed, window }
1025
1092
 
1026
1093
  const out = messages.slice()
1027
1094
  for (let i = 0; i < out.length; i++) {
@@ -1036,7 +1103,7 @@ export function evictOldToolResults({ messages, window, reserve = 0, dropped = [
1036
1103
  "if you still need it, with a narrower query.]"
1037
1104
  })
1038
1105
  }
1039
- return { messages: out, dropped }
1106
+ return { messages: out, dropped, needed, window }
1040
1107
  }
1041
1108
 
1042
1109
  export function modelWindowFrom(payload, modelId) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aibranch/llm-meta-widget",
3
- "version": "0.12.1",
3
+ "version": "0.12.2",
4
4
  "//version": "Must stay in step with lib/llm_meta_widget/version.rb. Two independently versioned copies of the same client is the drift docs/custom-element-distribution.md warns about: bump both, release both.",
5
5
  "description": "Embeddable browser chat widget: a custom element that discovers tools at page, origin and hub scope and dispatches each tool call to the right one. Two lines of HTML on any host, Rails or not.",
6
6
  "keywords": [