@aibranch/llm-meta-widget 0.11.1 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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.11.1"
64
+ gem "llm_meta_widget", "~> 0.12.1"
65
65
  ```
66
66
 
67
67
  ```bash
@@ -152,17 +152,17 @@ The widget is a custom element in a single self-contained ES module, so the
152
152
  whole integration is two lines of HTML:
153
153
 
154
154
  ```html
155
- <script type="module" src="https://cdn.jsdelivr.net/npm/@aibranch/llm-meta-widget@0.11"></script>
155
+ <script type="module" src="https://cdn.jsdelivr.net/npm/@aibranch/llm-meta-widget@0.12"></script>
156
156
  <llm-meta-widget llm-url="https://your-meta-server.example"
157
157
  model="gpt-oss-120b"
158
158
  greeting="Hi — ask me anything about this page."></llm-meta-widget>
159
159
  ```
160
160
 
161
- **`@0.11` is a version range, and it stops at 0.11.x on purpose.** You receive
161
+ **`@0.12` is a version range, and it stops at 0.12.x on purpose.** You receive
162
162
  bug fixes without editing your page, and a release that breaks your page cannot
163
163
  arrive on its own.
164
164
 
165
- Moving to 0.12 is therefore a change you make yourself. Read
165
+ Moving to 0.13 is therefore a change you make yourself. Read
166
166
  [CHANGELOG.md](CHANGELOG.md) before you do, because this is where what your page
167
167
  must provide can change. For example, 0.10.0 changed how the widget finds a page
168
168
  card: by media type rather than by element id. A page that declared its card the
@@ -698,8 +698,12 @@ the model's context. The widget reads two optional fields the
698
698
  `_meta`; the widget still reads that when `size` is absent, but it will be
699
699
  removed, so emit `size`.
700
700
  The widget decides whether it can afford the resource *before* fetching it. If
701
- the resource is over its budget of 8 KB, the bytes never cross the wire, and
702
- the LLM asks for what it needs through your tools instead.
701
+ the resource is over that budget, the bytes never cross the wire, and the LLM
702
+ asks for what it needs through your tools instead.
703
+ The budget is a share of the model's own context window, which the widget
704
+ reads from the hub: about 8 KB for a 32,000-token model, about 32 KB for a
705
+ 128,000-token one, and at most 64 KB. When the hub does not report a window,
706
+ the budget is 8 KB.
703
707
  - **`volatility`** — `"stable"` (read once, re-used) or `"volatile"` (re-read
704
708
  on every turn that uses it).
705
709
  - **`autoAttach`** — may the widget put this in the model's context without
@@ -168,6 +168,16 @@ async function runChatLoop(opts) {
168
168
  remoteTools = [],
169
169
  hostWideTools = [],
170
170
  maxRounds = 10,
171
+ // The model's own context window, from /api/llms. Without it the loop
172
+ // cannot know how much room is left, so it budgets nothing and a long
173
+ // tool-heavy turn is refused by the provider instead of degrading.
174
+ contextWindow = null,
175
+ // Tokens held back for the answer: a request that fills the window leaves
176
+ // nothing to generate into.
177
+ outputReserve = 2048,
178
+ // Called when a tool result is dropped to make room, so the panel can say
179
+ // so rather than the context quietly thinning.
180
+ onContextEvicted,
171
181
  // "hub" (default) talks to llm_meta_server; "ollama" talks straight to an
172
182
  // Ollama, with no server component of ours in between. The loop is the
173
183
  // same either way — only the call is swapped.
@@ -189,7 +199,7 @@ async function runChatLoop(opts) {
189
199
  onPhase,
190
200
  ...singleOpts
191
201
  } = opts;
192
- const messages = [...singleOpts.messages || []];
202
+ let messages = [...singleOpts.messages || []];
193
203
  const remoteByName = Object.fromEntries((remoteTools || []).map((t) => [t.name, t]));
194
204
  const hostWideByName = Object.fromEntries((hostWideTools || []).map((t) => [t.name, t]));
195
205
  const toolIds = [...singleOpts.toolIds || [], ...(remoteTools || []).map((t) => t.id)];
@@ -200,6 +210,12 @@ async function runChatLoop(opts) {
200
210
  }
201
211
  const mergedLocalTools = Object.values(inlineByName);
202
212
  const rounds = [];
213
+ const evicted = [];
214
+ const toolsTokens = estimateToolsTokens([].concat(
215
+ singleOpts.localTools || [],
216
+ remoteTools || [],
217
+ hostWideTools || []
218
+ ));
203
219
  const allDispatched = [];
204
220
  const allSkipped = [];
205
221
  let lastResult = null;
@@ -230,6 +246,17 @@ async function runChatLoop(opts) {
230
246
  for (let round = 0; round < maxRounds; round++) {
231
247
  if (signal?.aborted) throw new DOMException("aborted", "AbortError");
232
248
  onRoundStart?.(round);
249
+ const room = evictOldToolResults({
250
+ messages,
251
+ window: contextWindow,
252
+ dropped: evicted,
253
+ // The tools take their share of the window before any message does.
254
+ reserve: outputReserve + toolsTokens
255
+ });
256
+ if (room.messages !== messages) {
257
+ messages = room.messages;
258
+ onContextEvicted?.(evicted.slice());
259
+ }
233
260
  const call = provider === "ollama" ? ollamaChatCall : singleLlmCall;
234
261
  const turnResult = await call({
235
262
  ...singleOpts,
@@ -561,6 +588,70 @@ function parseSseFrame(raw) {
561
588
  }
562
589
  var STATIC_PRIMITIVES_META = "io.modelcontextprotocol/static-primitives";
563
590
  var PAGE_CARD_MEDIA_TYPE = "application/mcp-static-primitives+json";
591
+ var RESOURCE_SHARE_OF_WINDOW = 0.0625;
592
+ var RESOURCE_BYTES_PER_TOKEN = 4;
593
+ function resourceBudgetBytes(window2, { floor = 8e3, cap = 64e3 } = {}) {
594
+ if (!window2 || !Number.isFinite(window2)) return floor;
595
+ const share = Math.round(window2 * RESOURCE_SHARE_OF_WINDOW * RESOURCE_BYTES_PER_TOKEN);
596
+ return Math.min(cap, Math.max(floor, share));
597
+ }
598
+ var PROSE_CHARS_PER_TOKEN = 3.5;
599
+ var DENSE_CHARS_PER_TOKEN = 1.6;
600
+ var CJK_CHARS_PER_TOKEN = 1;
601
+ var MESSAGE_OVERHEAD_TOKENS = 4;
602
+ var CJK_PATTERN = /[\u3000-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af\uf900-\ufaff\uff00-\uffef]/g;
603
+ var PROSE_PATTERN = /[A-Za-z \n\t]/g;
604
+ function estimateTextTokens(text) {
605
+ const str = typeof text === "string" ? text : String(text ?? "");
606
+ const cjk = (str.match(CJK_PATTERN) || []).length;
607
+ const prose = (str.match(PROSE_PATTERN) || []).length;
608
+ const dense = str.length - cjk - prose;
609
+ return Math.ceil(cjk / CJK_CHARS_PER_TOKEN + prose / PROSE_CHARS_PER_TOKEN + dense / DENSE_CHARS_PER_TOKEN);
610
+ }
611
+ function estimateTokens(messages) {
612
+ return (messages || []).reduce((sum, m) => {
613
+ const content = typeof m?.content === "string" ? m.content : JSON.stringify(m?.content ?? "");
614
+ return sum + estimateTextTokens(content) + MESSAGE_OVERHEAD_TOKENS;
615
+ }, 0);
616
+ }
617
+ function estimateToolsTokens(tools) {
618
+ const text = (tools || []).map((t) => JSON.stringify({
619
+ name: t?.name,
620
+ description: t?.description,
621
+ schema: t?.input_schema || t?.inputSchema
622
+ })).join("");
623
+ return estimateTextTokens(text);
624
+ }
625
+ function evictOldToolResults({ messages, window: window2, reserve = 0, dropped = [] }) {
626
+ if (!window2 || !Number.isFinite(window2)) return { messages, dropped };
627
+ const budget = window2 - reserve;
628
+ if (estimateTokens(messages) <= budget) return { messages, dropped };
629
+ const out = messages.slice();
630
+ for (let i = 0; i < out.length; i++) {
631
+ if (estimateTokens(out) <= budget) break;
632
+ const m = out[i];
633
+ if (m?.role !== "tool") continue;
634
+ if (typeof m.content === "string" && m.content.startsWith("[dropped")) continue;
635
+ dropped.push({ name: m.name, tokens: estimateTokens([m]) });
636
+ out[i] = Object.assign({}, m, {
637
+ content: "[dropped to make room in the context window. Call the tool again if you still need it, with a narrower query.]"
638
+ });
639
+ }
640
+ return { messages: out, dropped };
641
+ }
642
+ function modelWindowFrom(payload, modelId) {
643
+ for (const family of payload && payload.llms || []) {
644
+ const entries = [].concat(family.available_models || [], family.models || []);
645
+ for (const entry of entries) {
646
+ if (!entry) continue;
647
+ const id = entry.value || entry.name;
648
+ if (id !== modelId) continue;
649
+ const window2 = Number(entry.max_input_tokens);
650
+ return Number.isFinite(window2) && window2 > 0 ? window2 : null;
651
+ }
652
+ }
653
+ return null;
654
+ }
564
655
  var PAGE_GLOBAL_TRANSPORT = "page-global";
565
656
  function declaredPageGlobal(card) {
566
657
  for (const remote of card && card.remotes || []) {
@@ -3237,12 +3328,28 @@ var conversation_default = `/*
3237
3328
  white-space: pre;
3238
3329
  }
3239
3330
  .llm-meta-conversation .message-content pre code { background: none; padding: 0; }
3331
+ /* The scroller is the WRAPPER, not the table: a table that is itself the
3332
+ * scrolling box gets capped at the bubble width and squeezes its columns
3333
+ * instead of overflowing, and .message's word-wrap then breaks every word
3334
+ * one character per line. The wrapper is capped; the table inside keeps its
3335
+ * natural width and scrolls sideways. */
3336
+ .llm-meta-conversation .message-content .lmw-table-scroll {
3337
+ overflow-x: auto;
3338
+ margin: 0.5em 0;
3339
+ }
3240
3340
  .llm-meta-conversation .message-content table {
3241
3341
  border-collapse: collapse;
3242
- margin: 0.5em 0;
3243
- display: block;
3244
- overflow-x: auto;
3245
- max-width: 100%;
3342
+ /* min-width so a narrow table still fills the bubble, width:max-content so
3343
+ * a wide one is laid out at its natural size and the wrapper scrolls. */
3344
+ width: max-content;
3345
+ min-width: 100%;
3346
+ }
3347
+ /* Inside a table, breaking mid-token is what produced the one-letter columns;
3348
+ * cells keep their words whole and the wrapper scrolls instead. */
3349
+ .llm-meta-conversation .message-content th,
3350
+ .llm-meta-conversation .message-content td {
3351
+ word-wrap: normal;
3352
+ overflow-wrap: normal;
3246
3353
  }
3247
3354
  .llm-meta-conversation .message-content th,
3248
3355
  .llm-meta-conversation .message-content td {
@@ -3844,6 +3951,13 @@ function boot(cfg) {
3844
3951
  var root = document.getElementById("llm-meta-widget-chat");
3845
3952
  var toggleBtn = document.getElementById("llm-meta-widget-toggle");
3846
3953
  var historyEl = root.querySelector(".lmw-messages");
3954
+ var SCROLL_PIN_SLACK = 40;
3955
+ function atBottom() {
3956
+ return historyEl.scrollHeight - historyEl.scrollTop - historyEl.clientHeight <= SCROLL_PIN_SLACK;
3957
+ }
3958
+ function pinToBottom() {
3959
+ historyEl.scrollTop = historyEl.scrollHeight;
3960
+ }
3847
3961
  var formEl = root.querySelector(".lmw-form");
3848
3962
  var inputEl = root.querySelector(".lmw-input");
3849
3963
  var clearBtn = root.querySelector(".lmw-clear");
@@ -4069,6 +4183,8 @@ function boot(cfg) {
4069
4183
  tasks.push(fetch(LLM_BASE + "/api/llms", { headers: { "Accept": "application/json" } }).then(function(r) {
4070
4184
  return r.ok ? r.json() : { llms: [] };
4071
4185
  }).then(function(payload) {
4186
+ llmsPayload = payload;
4187
+ modelWindow = modelWindowFrom(payload, MODEL);
4072
4188
  var flat = [];
4073
4189
  (payload.llms || []).forEach(function(llm) {
4074
4190
  if (llm.family !== "ollama") return;
@@ -4189,6 +4305,7 @@ function boot(cfg) {
4189
4305
  if (modelPicker) {
4190
4306
  modelPicker.addEventListener("change", function() {
4191
4307
  MODEL = modelPicker.value;
4308
+ modelWindow = modelWindowFrom(llmsPayload, MODEL);
4192
4309
  });
4193
4310
  }
4194
4311
  if (toolsPicker) {
@@ -4213,16 +4330,29 @@ function boot(cfg) {
4213
4330
  var hostWidePrompts = pageCard.prompts.map(function(p) {
4214
4331
  return Object.assign({}, p, { source: "page" });
4215
4332
  });
4333
+ var modelWindow = null;
4334
+ var llmsPayload = null;
4216
4335
  var resourceContext = null;
4217
4336
  var resourcePlan = null;
4218
- var RESOURCE_BUDGET_BYTES = 8e3;
4219
- var pageResourcePlans = planPageResources({
4220
- entries: pageCard.resources,
4221
- budgetBytes: RESOURCE_BUDGET_BYTES,
4222
- onSkip: function(plan) {
4223
- console.info("[llm_meta_widget] not attaching " + plan.uri + " (" + plan.reason + ", size=" + plan.size + ")");
4337
+ function resourceBudget() {
4338
+ return resourceBudgetBytes(modelWindow);
4339
+ }
4340
+ var pageResourcePlans = null;
4341
+ var pageResourcePlansBudget = null;
4342
+ function pageResourcePlansNow() {
4343
+ var budget = resourceBudget();
4344
+ if (pageResourcePlans === null || budget !== pageResourcePlansBudget) {
4345
+ pageResourcePlansBudget = budget;
4346
+ pageResourcePlans = planPageResources({
4347
+ entries: pageCard.resources,
4348
+ budgetBytes: budget,
4349
+ onSkip: function(plan) {
4350
+ console.info("[llm_meta_widget] not attaching " + plan.uri + " (" + plan.reason + ", size=" + plan.size + ")");
4351
+ }
4352
+ });
4224
4353
  }
4225
- });
4354
+ return pageResourcePlans;
4355
+ }
4226
4356
  var pageResourceCache = {};
4227
4357
  restoreConversation();
4228
4358
  var promptsEl = root.querySelector(".lmw-prompts");
@@ -4243,7 +4373,7 @@ function boot(cfg) {
4243
4373
  if (resourcePlan === null) {
4244
4374
  var loaded = await loadHostResource({
4245
4375
  endpoint,
4246
- budgetBytes: RESOURCE_BUDGET_BYTES,
4376
+ budgetBytes: resourceBudget(),
4247
4377
  list: listMcpResources,
4248
4378
  read: readMcpResource,
4249
4379
  onSkip: function(plan) {
@@ -4305,7 +4435,7 @@ function boot(cfg) {
4305
4435
  });
4306
4436
  if (body.parentNode) body.parentNode.appendChild(row);
4307
4437
  });
4308
- historyEl.scrollTop = historyEl.scrollHeight;
4438
+ pinToBottom();
4309
4439
  return true;
4310
4440
  }
4311
4441
  function renderWelcome() {
@@ -4380,6 +4510,7 @@ function boot(cfg) {
4380
4510
  }
4381
4511
  var pendingTurnLabel = null;
4382
4512
  function appendTurn(role, text, turnLabel) {
4513
+ var following = atBottom();
4383
4514
  var welcome = historyEl.querySelector(".lmw-welcome");
4384
4515
  if (welcome) welcome.remove();
4385
4516
  var div = document.createElement("div");
@@ -4406,7 +4537,7 @@ function boot(cfg) {
4406
4537
  div.appendChild(document.createTextNode(" "));
4407
4538
  div.appendChild(body);
4408
4539
  historyEl.appendChild(div);
4409
- historyEl.scrollTop = historyEl.scrollHeight;
4540
+ if (role === "user" || following) pinToBottom();
4410
4541
  body.roleLabel = label;
4411
4542
  return body;
4412
4543
  }
@@ -4416,6 +4547,17 @@ function boot(cfg) {
4416
4547
  } catch (e) {
4417
4548
  el.textContent = mdText;
4418
4549
  }
4550
+ wrapTablesForScrolling(el);
4551
+ }
4552
+ function wrapTablesForScrolling(el) {
4553
+ var tables = el.querySelectorAll("table");
4554
+ for (var i = 0; i < tables.length; i++) {
4555
+ var table = tables[i];
4556
+ var wrap = document.createElement("div");
4557
+ wrap.className = "lmw-table-scroll";
4558
+ table.parentNode.insertBefore(wrap, table);
4559
+ wrap.appendChild(table);
4560
+ }
4419
4561
  }
4420
4562
  function roleLabel(role) {
4421
4563
  if (role === "user") return "\u{1F464} You";
@@ -4445,6 +4587,7 @@ function boot(cfg) {
4445
4587
  return liveChips;
4446
4588
  }
4447
4589
  function announceToolCall(toolCall) {
4590
+ var following = atBottom();
4448
4591
  var row = chipRow();
4449
4592
  if (!row) return;
4450
4593
  var chip = document.createElement("span");
@@ -4453,7 +4596,7 @@ function boot(cfg) {
4453
4596
  chip.dataset.tool = toolCall.name;
4454
4597
  row.appendChild(chip);
4455
4598
  pendingChips.push(chip);
4456
- historyEl.scrollTop = historyEl.scrollHeight;
4599
+ if (following) pinToBottom();
4457
4600
  }
4458
4601
  function resolveToolCall(outcome) {
4459
4602
  var idx = pendingChips.findIndex(function(c) {
@@ -4469,6 +4612,7 @@ function boot(cfg) {
4469
4612
  var currentThinkingBody = null;
4470
4613
  var activeAssistantBody = null;
4471
4614
  function ensureThinkingBlock() {
4615
+ var following = atBottom();
4472
4616
  if (currentThinkingBody) return currentThinkingBody;
4473
4617
  var details = document.createElement("details");
4474
4618
  details.className = "message-thinking";
@@ -4493,7 +4637,7 @@ function boot(cfg) {
4493
4637
  } else {
4494
4638
  historyEl.appendChild(details);
4495
4639
  }
4496
- historyEl.scrollTop = historyEl.scrollHeight;
4640
+ if (following) pinToBottom();
4497
4641
  currentThinkingBlock = details;
4498
4642
  currentThinkingBody = body;
4499
4643
  return body;
@@ -4573,13 +4717,13 @@ function boot(cfg) {
4573
4717
  cached: resourceContext,
4574
4718
  endpoint: resourcePlan && resourcePlan.endpoint,
4575
4719
  read: readMcpResource,
4576
- budgetBytes: RESOURCE_BUDGET_BYTES
4720
+ budgetBytes: resourceBudget()
4577
4721
  });
4578
4722
  resourceContext = turn.cached;
4579
4723
  var page = await pageResourceLinesForTurn({
4580
- plans: pageResourcePlans,
4724
+ plans: pageResourcePlansNow(),
4581
4725
  resources: handlers.resources,
4582
- budgetBytes: RESOURCE_BUDGET_BYTES,
4726
+ budgetBytes: resourceBudget(),
4583
4727
  cache: pageResourceCache
4584
4728
  });
4585
4729
  pageResourceCache = page.cache;
@@ -4646,8 +4790,14 @@ function boot(cfg) {
4646
4790
  hostWideTools,
4647
4791
  aiActions: handlers.tools,
4648
4792
  maxRounds: MAX_ROUNDS,
4793
+ contextWindow: modelWindow,
4649
4794
  provider: LLM_PROVIDER === "ollama" ? "ollama" : "hub",
4650
4795
  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.");
4800
+ },
4651
4801
  onToolCall: function(toolCall) {
4652
4802
  announceToolCall(toolCall);
4653
4803
  persistConversation();
@@ -4666,19 +4816,21 @@ function boot(cfg) {
4666
4816
  collapseThinkingBlock();
4667
4817
  },
4668
4818
  onThinkingDelta: function(delta) {
4819
+ var following = atBottom();
4669
4820
  var body = ensureThinkingBlock();
4670
4821
  body.appendChild(document.createTextNode(delta));
4671
4822
  body.scrollTop = body.scrollHeight;
4672
- historyEl.scrollTop = historyEl.scrollHeight;
4823
+ if (following) pinToBottom();
4673
4824
  },
4674
4825
  onTextDelta: function(delta) {
4826
+ var following = atBottom();
4675
4827
  markDone(assistantBody.roleLabel);
4676
4828
  collapseThinkingBlock();
4677
4829
  assistantMarkdown += delta;
4678
4830
  renderMarkdownInto(assistantBody, assistantMarkdown);
4679
4831
  liveTurn.content = assistantMarkdown;
4680
4832
  persistSoon();
4681
- historyEl.scrollTop = historyEl.scrollHeight;
4833
+ if (following) pinToBottom();
4682
4834
  }
4683
4835
  });
4684
4836
  liveTurn.content = result.content;
@@ -325,6 +325,16 @@ export async function runChatLoop(opts) {
325
325
  remoteTools = [],
326
326
  hostWideTools = [],
327
327
  maxRounds = 10,
328
+ // The model's own context window, from /api/llms. Without it the loop
329
+ // cannot know how much room is left, so it budgets nothing and a long
330
+ // tool-heavy turn is refused by the provider instead of degrading.
331
+ contextWindow = null,
332
+ // Tokens held back for the answer: a request that fills the window leaves
333
+ // nothing to generate into.
334
+ outputReserve = 2048,
335
+ // Called when a tool result is dropped to make room, so the panel can say
336
+ // so rather than the context quietly thinning.
337
+ onContextEvicted,
328
338
  // "hub" (default) talks to llm_meta_server; "ollama" talks straight to an
329
339
  // Ollama, with no server component of ours in between. The loop is the
330
340
  // same either way — only the call is swapped.
@@ -347,7 +357,7 @@ export async function runChatLoop(opts) {
347
357
  ...singleOpts
348
358
  } = opts
349
359
 
350
- const messages = [ ...(singleOpts.messages || []) ]
360
+ let messages = [ ...(singleOpts.messages || []) ]
351
361
  const remoteByName = Object.fromEntries((remoteTools || []).map((t) => [ t.name, t ]))
352
362
  // Class 2: host-wide MCP tools (well-known). Map name→{endpoint, ...} for
353
363
  // dispatch. If the same name appears in aiActions, Class 3 wins there
@@ -366,6 +376,10 @@ export async function runChatLoop(opts) {
366
376
  const mergedLocalTools = Object.values(inlineByName)
367
377
 
368
378
  const rounds = []
379
+ const evicted = []
380
+ // Fixed for the turn: the declared tool set does not change between rounds.
381
+ const toolsTokens = estimateToolsTokens([].concat(
382
+ singleOpts.localTools || [], remoteTools || [], hostWideTools || []))
369
383
  const allDispatched = []
370
384
  const allSkipped = []
371
385
  let lastResult = null
@@ -408,6 +422,18 @@ export async function runChatLoop(opts) {
408
422
  onRoundStart?.(round)
409
423
 
410
424
  // The loop is the same whoever answers; only the call differs.
425
+ // Make room before sending, rather than after being refused. Only old
426
+ // tool results are given up; see evictOldToolResults.
427
+ const room = evictOldToolResults({
428
+ messages, window: contextWindow, dropped: evicted,
429
+ // The tools take their share of the window before any message does.
430
+ reserve: outputReserve + toolsTokens
431
+ });
432
+ if (room.messages !== messages) {
433
+ messages = room.messages;
434
+ onContextEvicted?.(evicted.slice());
435
+ }
436
+
411
437
  const call = provider === "ollama" ? ollamaChatCall : singleLlmCall
412
438
  const turnResult = await call({
413
439
  ...singleOpts,
@@ -891,6 +917,142 @@ export const PAGE_CARD_MEDIA_TYPE = "application/mcp-static-primitives+json"
891
917
  // card, find the handlers and dispatch. The three legacy globals
892
918
  // (aiActions/aiPrompts/aiResources) are names only this widget knows, and are
893
919
  // configurable per page, so nothing outside could rely on them.
920
+ // How much room a model has, read from /api/llms — the one call the widget
921
+ // already makes before a turn. Scans every family, because the picker shows
922
+ // only the local ones while the configured model is often hosted, and the two
923
+ // families use different shapes for the same thing (`value` vs `name`).
924
+ //
925
+ // Returns null when the hub does not say. Null means "no budget to work with",
926
+ // which is not the same as zero, and every caller below treats it as "do not
927
+ // guess" rather than "no room".
928
+ // How many bytes of reference resources a turn may attach, derived from the
929
+ // model's window instead of guessed. The old fixed 8000 was chosen as "~2k
930
+ // tokens, beyond which a resource crowds out the conversation on a 32k local
931
+ // model" — which is 6.25% of that window, so the same share reproduces 8000 at
932
+ // 32k exactly and gives a 128k model the 32 KB it can afford.
933
+ //
934
+ // The floor keeps the previous behaviour whenever the window is unknown. The
935
+ // cap is there because these bytes are fetched and inlined on every turn: the
936
+ // largest real catalog (PubDictionaries, 218 dictionaries) is ~35 KB, so 64 KB
937
+ // is already generous and a 1M-token model does not need 250 KB of it.
938
+ export const RESOURCE_SHARE_OF_WINDOW = 0.0625
939
+
940
+ // Bytes per token for SIZING that budget — not the estimator above, which
941
+ // measures real text. Kept at four so the budget stays exactly what it was
942
+ // (8 KB on a 32k model): how many tokens those bytes become depends on the
943
+ // resource, and re-sizing budgets is not this constant's job.
944
+ export const RESOURCE_BYTES_PER_TOKEN = 4
945
+
946
+ export function resourceBudgetBytes(window, { floor = 8000, cap = 64_000 } = {}) {
947
+ if (!window || !Number.isFinite(window)) return floor
948
+ const share = Math.round(window * RESOURCE_SHARE_OF_WINDOW * RESOURCE_BYTES_PER_TOKEN)
949
+ return Math.min(cap, Math.max(floor, share))
950
+ }
951
+
952
+ // A rough token count, the same three classes the hub's estimator uses.
953
+ //
954
+ // One ratio cannot describe both prose and a tool result. Letters and spaces
955
+ // tokenize at roughly 3.5 characters each; digits, punctuation and symbols go
956
+ // much denser, and a JSON tool result is mostly those.
957
+ //
958
+ // Measured against a real refusal (2026-10-17): a 289,101-character request
959
+ // the provider counted as 135,291 tokens was 33% letters, 16% digits and 45%
960
+ // punctuation. At a flat four characters per token that is 72,275 — 53% of the
961
+ // truth — so nothing was evicted and the provider refused the turn instead.
962
+ // These classes put it at 106%: high, which is the safe direction here, since
963
+ // underestimating means the turn dies while overestimating only gives up an
964
+ // old tool result slightly early.
965
+ export const PROSE_CHARS_PER_TOKEN = 3.5
966
+ export const DENSE_CHARS_PER_TOKEN = 1.6
967
+ export const CJK_CHARS_PER_TOKEN = 1
968
+ export const MESSAGE_OVERHEAD_TOKENS = 4
969
+
970
+ const CJK_PATTERN = /[\u3000-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7af\uf900-\ufaff\uff00-\uffef]/g
971
+ const PROSE_PATTERN = /[A-Za-z \n\t]/g
972
+
973
+ export function estimateTextTokens(text) {
974
+ const str = typeof text === "string" ? text : String(text ?? "")
975
+ const cjk = (str.match(CJK_PATTERN) || []).length
976
+ const prose = (str.match(PROSE_PATTERN) || []).length
977
+ const dense = str.length - cjk - prose
978
+ return Math.ceil(cjk / CJK_CHARS_PER_TOKEN +
979
+ prose / PROSE_CHARS_PER_TOKEN +
980
+ dense / DENSE_CHARS_PER_TOKEN)
981
+ }
982
+
983
+ export function estimateTokens(messages) {
984
+ return (messages || []).reduce((sum, m) => {
985
+ const content = typeof m?.content === "string" ? m.content : JSON.stringify(m?.content ?? "")
986
+ return sum + estimateTextTokens(content) + MESSAGE_OVERHEAD_TOKENS
987
+ }, 0)
988
+ }
989
+
990
+ // What the declared tools cost in the window. They are part of every request:
991
+ // names, descriptions and JSON schemas. On the hub path the browser sends only
992
+ // `tool_ids` and the hub expands the schemas, but the browser listed those
993
+ // tools to build its picker, so it still has what it needs to price them.
994
+ //
995
+ // This is not a detail. TogoMCP declares around twenty tools, which is a few
996
+ // thousand tokens standing in the window before the conversation starts; a
997
+ // budget counting only messages runs low and evicts too late to help.
998
+ export function estimateToolsTokens(tools) {
999
+ const text = (tools || []).map((t) => JSON.stringify({
1000
+ name: t?.name, description: t?.description, schema: t?.input_schema || t?.inputSchema
1001
+ })).join("")
1002
+ // Counted with the same classes: a schema is JSON, which is the dense case.
1003
+ return estimateTextTokens(text)
1004
+ }
1005
+
1006
+ // Makes room for the next round by dropping the OLDEST tool results, which is
1007
+ // the one eviction a chat loop can justify: the model has already read them and
1008
+ // said what it made of them in the assistant turn that follows, so its own
1009
+ // summary survives. Nothing else is touched — not the system prompt, not the
1010
+ // questions, not the assistant's words.
1011
+ //
1012
+ // Each dropped result leaves a marker in its place, because a tool message must
1013
+ // still answer its tool_call_id: a provider that sees a call with no result
1014
+ // rejects the request, and a model that sees no mention of the result would
1015
+ // happily call the same tool again.
1016
+ //
1017
+ // Returns the messages unchanged when the window is unknown. Guessing a window
1018
+ // would be worse than not budgeting: too low throws away context the turn
1019
+ // needed, and too high fails at the provider anyway.
1020
+ export function evictOldToolResults({ messages, window, reserve = 0, dropped = [] }) {
1021
+ if (!window || !Number.isFinite(window)) return { messages, dropped }
1022
+
1023
+ const budget = window - reserve
1024
+ if (estimateTokens(messages) <= budget) return { messages, dropped }
1025
+
1026
+ const out = messages.slice()
1027
+ for (let i = 0; i < out.length; i++) {
1028
+ if (estimateTokens(out) <= budget) break
1029
+ const m = out[i]
1030
+ if (m?.role !== "tool") continue
1031
+ if (typeof m.content === "string" && m.content.startsWith("[dropped")) continue
1032
+
1033
+ dropped.push({ name: m.name, tokens: estimateTokens([ m ]) })
1034
+ out[i] = Object.assign({}, m, {
1035
+ content: "[dropped to make room in the context window. Call the tool again " +
1036
+ "if you still need it, with a narrower query.]"
1037
+ })
1038
+ }
1039
+ return { messages: out, dropped }
1040
+ }
1041
+
1042
+ export function modelWindowFrom(payload, modelId) {
1043
+ for (const family of (payload && payload.llms) || []) {
1044
+ const entries = [].concat(family.available_models || [], family.models || [])
1045
+ for (const entry of entries) {
1046
+ if (!entry) continue
1047
+ const id = entry.value || entry.name
1048
+ if (id !== modelId) continue
1049
+ const window = Number(entry.max_input_tokens)
1050
+ return Number.isFinite(window) && window > 0 ? window : null
1051
+ }
1052
+ }
1053
+ return null
1054
+ }
1055
+
894
1056
  export const PAGE_GLOBAL_TRANSPORT = "page-global"
895
1057
 
896
1058
  export function declaredPageGlobal(card) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aibranch/llm-meta-widget",
3
- "version": "0.11.1",
3
+ "version": "0.12.1",
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": [