@dudko.dev/agent-web 0.0.50 → 0.0.51

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 (38) hide show
  1. package/README.md +49 -4
  2. package/dist/agent-web.js +159 -151
  3. package/dist/agent-web.js.map +1 -1
  4. package/dist/{chunk-3V27UZT6.js → chunk-DOWC4CFZ.js} +257 -3
  5. package/dist/chunk-DOWC4CFZ.js.map +1 -0
  6. package/dist/{chunk-6XHCPSZE.js → chunk-EUJWS42C.js} +56 -5
  7. package/dist/{chunk-6XHCPSZE.js.map → chunk-EUJWS42C.js.map} +1 -1
  8. package/dist/{chunk-IT77BVAD.js → chunk-HXUR2SG5.js} +2 -2
  9. package/dist/{chunk-JTZEUPIG.js → chunk-NUL6QEAX.js} +49 -49
  10. package/dist/chunk-NUL6QEAX.js.map +1 -0
  11. package/dist/chunk-R5VCITT3.js +192 -0
  12. package/dist/chunk-R5VCITT3.js.map +1 -0
  13. package/dist/{chunk-7Y5UC6L7.js → chunk-SVGIGIRR.js} +3 -3
  14. package/dist/fit-reference-worker.cjs +158 -0
  15. package/dist/fit-reference-worker.cjs.map +1 -0
  16. package/dist/fit-reference-worker.d.cts +1 -0
  17. package/dist/fit-reference-worker.d.ts +1 -0
  18. package/dist/fit-reference-worker.js +16 -0
  19. package/dist/fit-reference-worker.js.map +1 -0
  20. package/dist/index.cjs +1140 -360
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +82 -72
  23. package/dist/index.d.ts +82 -72
  24. package/dist/index.js +365 -84
  25. package/dist/index.js.map +1 -1
  26. package/dist/mcp.js +2 -2
  27. package/dist/media-fit-worker-CFK2z8LF.d.cts +149 -0
  28. package/dist/media-fit-worker-CFK2z8LF.d.ts +149 -0
  29. package/dist/{sandbox-IGTCMOOX.js → sandbox-X6T4ZOEQ.js} +3 -3
  30. package/dist/secrets.js +3 -3
  31. package/dist/{webllm-BEL5A4OF.js → webllm-EZSJGU6P.js} +2 -2
  32. package/package.json +14 -2
  33. package/dist/chunk-3V27UZT6.js.map +0 -1
  34. package/dist/chunk-JTZEUPIG.js.map +0 -1
  35. /package/dist/{chunk-IT77BVAD.js.map → chunk-HXUR2SG5.js.map} +0 -0
  36. /package/dist/{chunk-7Y5UC6L7.js.map → chunk-SVGIGIRR.js.map} +0 -0
  37. /package/dist/{sandbox-IGTCMOOX.js.map → sandbox-X6T4ZOEQ.js.map} +0 -0
  38. /package/dist/{webllm-BEL5A4OF.js.map → webllm-EZSJGU6P.js.map} +0 -0
@@ -174,6 +174,253 @@ var generateStructured = async (model, schema, opts = {}) => {
174
174
  };
175
175
  };
176
176
 
177
+ // src/memory/action-record.ts
178
+ var ACTION_RECORD_MAX_CHARS = 300;
179
+ var ACTION_RECORD_ITEM_CHARS = 60;
180
+ var SHORT_ITEM_CHARS = 40;
181
+ var ACTION_RECORD_DETAILS = 3;
182
+ var ACTION_RECORD_CARRY_CHARS = 900;
183
+ var OPEN = "[done: ";
184
+ var ACTION_RECORD_NOTE = `NOTE: a "[done: ...]" line at the end of an assistant message (or of a summary) is the runner's own record of what that turn actually did - the tools it called and how each call ended, the files it wrote or deleted, the media it made and whether reference pictures were used; it outweighs anything an answer said about that turn.`;
185
+ var ACTION_RECORD_STOPPED = "(The run was stopped before it answered.)";
186
+ var ACTION_RECORD_FAILED = "(The run failed before it answered.)";
187
+ var NO_ANSWER = "(No answer was written.)";
188
+ var CONTROL = /[\u0000-\u001f\u007f-\u009f]/g;
189
+ var INVISIBLE = /[\u00ad\u034f\u061c\u115f\u1160\u17b4\u17b5\u180b-\u180f\u200b-\u200f\u2028-\u202e\u2060-\u206f\u3164\ufe00-\ufe0f\ufeff\uffa0\ufff0-\ufffb]|\udb40[\udc00-\udc7f]/g;
190
+ var cleanActionText = (value, max = ACTION_RECORD_ITEM_CHARS) => {
191
+ const text = (typeof value === "string" ? value : String(value ?? "")).replace(CONTROL, " ").replace(INVISIBLE, "").replace(/\[/g, "(").replace(/\]/g, ")").replace(/;/g, ",").replace(/\s+/g, " ").trim();
192
+ if (!text) return "?";
193
+ return clipChars(text, Math.max(2, max));
194
+ };
195
+ var clipChars = (text, max) => {
196
+ if (text.length <= max) return text;
197
+ const chars = Array.from(text);
198
+ let head = "";
199
+ let tail = "";
200
+ const room = max - 1;
201
+ const headRoom = Math.ceil(room / 3);
202
+ for (const c of chars) {
203
+ if (head.length + c.length > headRoom) break;
204
+ head += c;
205
+ }
206
+ for (let i = chars.length - 1; i >= 0; i -= 1) {
207
+ if (head.length + tail.length + chars[i].length > room) break;
208
+ tail = chars[i] + tail;
209
+ }
210
+ return `${head}\u2026${tail}`;
211
+ };
212
+ var LOOKALIKE = /\[(\s*done\s*:)/gi;
213
+ var neutralizeActionRecords = (text) => text.replace(LOOKALIKE, "($1");
214
+ var RECORD = /^\[done: [^\]\n]*\]$/;
215
+ var ANY_RECORD = /(?:^|\n)\[done: [^\]\n]*\]/;
216
+ var ACTION_RECORD_TAIL = /(?:\n\[done: [^\]\n]*\])+$/;
217
+ var hasActionRecord = (content) => ANY_RECORD.test(content);
218
+ var withActionRecord = (text, record, ended) => {
219
+ const answer = neutralizeActionRecords(text ?? "").trim();
220
+ if (!record || !RECORD.test(record)) return answer;
221
+ const said = answer || (ended === "stopped" ? ACTION_RECORD_STOPPED : ended === "failed" ? ACTION_RECORD_FAILED : NO_ANSWER);
222
+ return `${said}
223
+ ${record}`;
224
+ };
225
+ var carriedActionRecords = (contents) => {
226
+ const marks = [];
227
+ for (const content of contents) {
228
+ const tail = ACTION_RECORD_TAIL.exec(content ?? "")?.[0];
229
+ if (tail) marks.push(...tail.split("\n").filter((line) => RECORD.test(line)));
230
+ }
231
+ const kept = [];
232
+ let used = 0;
233
+ for (let i = marks.length - 1; i >= 0; i -= 1) {
234
+ if (used + marks[i].length + 1 > ACTION_RECORD_CARRY_CHARS) break;
235
+ kept.unshift(marks[i]);
236
+ used += marks[i].length + 1;
237
+ }
238
+ return kept.map((m) => `
239
+ ${m}`).join("");
240
+ };
241
+ var QUIET = /* @__PURE__ */ new Set(["find_tools", "load_skill", "read_skill_file"]);
242
+ var MEDIA = /* @__PURE__ */ new Set(["generate_image", "generate_speech"]);
243
+ var HELPER = "spawn_subagent";
244
+ var ASK = "ask_user";
245
+ var CODE = "run_js";
246
+ var isObject = (value) => typeof value === "object" && value !== null;
247
+ var stringAt = (value, key) => {
248
+ if (!isObject(value)) return void 0;
249
+ const v = value[key];
250
+ return typeof v === "string" && v.trim() ? v : void 0;
251
+ };
252
+ var isDenied = (output) => isObject(output) && output.name === "ToolDeniedError" || typeof output === "string" && output.startsWith("Tool call denied by the user");
253
+ var isReplayed = (output) => typeof output === "string" && output.startsWith("[not run again:");
254
+ var askOutcome = (output) => {
255
+ const text = typeof output === "string" ? output : "";
256
+ if (text.startsWith("The user chose: ") || text.startsWith("The user did not pick an option and answered in their own words")) {
257
+ return "answered";
258
+ }
259
+ if (text.startsWith("The user chose not to answer")) return "declined";
260
+ return "not answered";
261
+ };
262
+ var mediaDetail = (output) => {
263
+ const path = stringAt(output, "path");
264
+ if (!path) return void 0;
265
+ const refs = isObject(output) && isObject(output.references) ? output.references : void 0;
266
+ const paths = refs && Array.isArray(refs.paths) ? refs.paths.filter((p) => typeof p === "string") : [];
267
+ if (!refs || paths.length === 0) return cleanActionText(path);
268
+ const shown = paths.slice(0, 2).map((p) => cleanActionText(p, SHORT_ITEM_CHARS));
269
+ const more = paths.length > 2 ? ` +${paths.length - 2}` : "";
270
+ const word = paths.length === 1 ? "reference" : "references";
271
+ return `${cleanActionText(path)} (${word} ${shown.join(", ")}${more} ${refs.used === true ? "used" : "NOT used"})`;
272
+ };
273
+ var fileDetail = (op, call) => {
274
+ if (op === "write") {
275
+ const path2 = stringAt(call.output, "written") ?? stringAt(call.input, "path");
276
+ return path2 ? cleanActionText(path2) : void 0;
277
+ }
278
+ const path = stringAt(call.input, "path");
279
+ if (!path) return void 0;
280
+ const missing = isObject(call.output) && call.output.deleted === false;
281
+ return `${cleanActionText(path)}${missing ? " (not found)" : ""}`;
282
+ };
283
+ var statusOf = (g) => {
284
+ const ends = [
285
+ ["failed", g.failed],
286
+ ["denied", g.denied],
287
+ ["unfinished", g.unfinished]
288
+ ].filter(([, n]) => n > 0);
289
+ if (ends.length === 0) return "";
290
+ if (ends.length === 1 && ends[0][1] === g.calls) return ` ${ends[0][0]}`;
291
+ return ` (${ends.map(([word, n]) => `${n} ${word}`).join(", ")})`;
292
+ };
293
+ var detailsOf = (g) => {
294
+ if (g.details.length === 0) return "";
295
+ const shown = g.details.slice(0, ACTION_RECORD_DETAILS);
296
+ const rest = g.details.length - shown.length;
297
+ const list = `${shown.join(", ")}${rest > 0 ? `, +${rest} more` : ""}`;
298
+ switch (g.kind) {
299
+ case "media":
300
+ return ` \u2192 ${list}`;
301
+ case "file":
302
+ return ` ${list}`;
303
+ case "code":
304
+ return ` (wrote ${list})`;
305
+ default:
306
+ return ` (${list})`;
307
+ }
308
+ };
309
+ var render = (g) => `${g.label}${g.calls > 1 ? ` \xD7${g.calls}` : ""}${statusOf(g)}${detailsOf(g)}`;
310
+ var createActionRecorder = (options = {}) => {
311
+ const groups = /* @__PURE__ */ new Map();
312
+ const pending = [];
313
+ const newGroup = (name, kind) => ({
314
+ label: cleanActionText(name),
315
+ kind,
316
+ calls: 0,
317
+ failed: 0,
318
+ denied: 0,
319
+ unfinished: 0,
320
+ details: []
321
+ });
322
+ const group = (name, kind) => {
323
+ let g = groups.get(name);
324
+ if (!g) {
325
+ g = newGroup(name, kind);
326
+ groups.set(name, g);
327
+ }
328
+ return g;
329
+ };
330
+ const detail = (g, text) => {
331
+ if (text && !g.details.includes(text)) g.details.push(text);
332
+ };
333
+ const kindOf = (name) => {
334
+ if (MEDIA.has(name)) return { kind: "media" };
335
+ if (name === HELPER) return { kind: "helper" };
336
+ if (name === ASK) return { kind: "ask" };
337
+ if (name === CODE) return { kind: "code" };
338
+ const op = options.fileOp?.(name);
339
+ return op ? { kind: "file", op } : { kind: "call" };
340
+ };
341
+ const add = (call) => {
342
+ const name = typeof call?.name === "string" ? call.name : String(call?.name ?? "");
343
+ if (!name || QUIET.has(name) || isReplayed(call.output)) return;
344
+ const { kind, op } = kindOf(name);
345
+ const g = group(name, kind);
346
+ g.calls += 1;
347
+ if (call.ok !== true) {
348
+ if (isDenied(call.output)) g.denied += 1;
349
+ else g.failed += 1;
350
+ return;
351
+ }
352
+ switch (kind) {
353
+ case "media":
354
+ detail(g, mediaDetail(call.output));
355
+ break;
356
+ case "file":
357
+ detail(g, fileDetail(op, call));
358
+ break;
359
+ case "helper": {
360
+ const who = stringAt(call.input, "role") ?? stringAt(call.input, "task");
361
+ detail(g, who ? cleanActionText(who, SHORT_ITEM_CHARS) : void 0);
362
+ break;
363
+ }
364
+ case "ask":
365
+ detail(g, askOutcome(call.output));
366
+ break;
367
+ }
368
+ };
369
+ return {
370
+ observe: (event) => {
371
+ if (!isObject(event)) return;
372
+ if (event.type === "step.tool-call") {
373
+ pending.push({ name: String(event.name ?? ""), input: event.input });
374
+ } else if (event.type === "step.tool-result") {
375
+ const name = String(event.name ?? "");
376
+ const at = pending.findIndex((p) => p.name === name);
377
+ const input = at >= 0 ? pending.splice(at, 1)[0].input : void 0;
378
+ add({ name, input, output: event.output, ok: event.ok === true });
379
+ } else if (event.type === "file.written" && pending.some((p) => p.name === CODE)) {
380
+ const path = stringAt(event, "path");
381
+ if (path) detail(group(CODE, "code"), cleanActionText(path));
382
+ }
383
+ },
384
+ add,
385
+ record: () => {
386
+ const open = /* @__PURE__ */ new Map();
387
+ for (const p of pending) {
388
+ if (p.name && !QUIET.has(p.name)) open.set(p.name, (open.get(p.name) ?? 0) + 1);
389
+ }
390
+ const all = [];
391
+ for (const [name, g] of groups) {
392
+ const n = open.get(name) ?? 0;
393
+ open.delete(name);
394
+ all.push(n ? { ...g, calls: g.calls + n, unfinished: g.unfinished + n } : g);
395
+ }
396
+ for (const [name, n] of open) {
397
+ all.push({ ...newGroup(name, kindOf(name).kind), calls: n, unfinished: n });
398
+ }
399
+ const parts = all.filter((g) => g.calls > 0 || g.details.length > 0).map(render);
400
+ if (parts.length === 0) return void 0;
401
+ const shown = [];
402
+ for (let i = 0; i < parts.length; i += 1) {
403
+ const left = parts.length - i - 1;
404
+ const next = `${OPEN}${[...shown, parts[i]].join("; ")}${left ? `; and ${left} more` : ""}]`;
405
+ if (next.length > ACTION_RECORD_MAX_CHARS) break;
406
+ shown.push(parts[i]);
407
+ }
408
+ if (shown.length === 0) {
409
+ const left = parts.length - 1;
410
+ const tail = left ? `; and ${left} more` : "";
411
+ shown.push(clipChars(parts[0], ACTION_RECORD_MAX_CHARS - OPEN.length - tail.length - 1));
412
+ }
413
+ const omitted = parts.length - shown.length;
414
+ return `${OPEN}${shown.join("; ")}${omitted ? `; and ${omitted} more` : ""}]`;
415
+ }
416
+ };
417
+ };
418
+ var actionRecordOf = (value) => {
419
+ if (!isObject(value)) return void 0;
420
+ const record = value.actionRecord;
421
+ return typeof record === "string" && RECORD.test(record) ? record : void 0;
422
+ };
423
+
177
424
  // src/memory/compress.ts
178
425
  var DEFAULT_COMPACTION_THRESHOLD_RATIO = 0.85;
179
426
  var ratioOf = (r) => typeof r === "number" && r > 0 && r <= 1 ? r : DEFAULT_COMPACTION_THRESHOLD_RATIO;
@@ -235,7 +482,7 @@ var newestWithin = (lines, maxTokens) => {
235
482
  }
236
483
  return kept.join("\n");
237
484
  };
238
- var SUMMARY_SYSTEM = "Summarize the following conversation into a compact set of durable facts, decisions, identifiers, open tasks and user preferences. Keep names, numbers and IDs verbatim. Output plain text only.";
485
+ var SUMMARY_SYSTEM = `Summarize the following conversation into a compact set of durable facts, decisions, identifiers, open tasks and user preferences. Keep names, numbers and IDs verbatim. A "[done: ...]" line is the agent's own record of what that turn actually did (tools called and how they ended, files written or deleted, media made and whether reference pictures were used): keep those facts, paths verbatim, over anything an answer said about that turn. Output plain text only.`;
239
486
  var compressHistory = async (messages, model, opts = {}) => {
240
487
  const keepRecent = opts.keepRecent ?? 6;
241
488
  if (messages.length <= keepRecent + 1) return messages;
@@ -270,7 +517,7 @@ var compressHistory = async (messages, model, opts = {}) => {
270
517
  const summaryMsg = {
271
518
  role: "system",
272
519
  content: `Summary of earlier conversation:
273
- ${clean}`,
520
+ ${neutralizeActionRecords(clean)}${carriedActionRecords(head.map((m) => m.content))}`,
274
521
  ts: head[0]?.ts
275
522
  };
276
523
  return [summaryMsg, ...tail];
@@ -479,6 +726,13 @@ export {
479
726
  generate,
480
727
  stream,
481
728
  generateStructured,
729
+ ACTION_RECORD_MAX_CHARS,
730
+ ACTION_RECORD_NOTE,
731
+ neutralizeActionRecords,
732
+ hasActionRecord,
733
+ withActionRecord,
734
+ createActionRecorder,
735
+ actionRecordOf,
482
736
  DEFAULT_COMPACTION_THRESHOLD_RATIO,
483
737
  resolveCompaction,
484
738
  estimateTokens,
@@ -511,4 +765,4 @@ export {
511
765
  unloadWebLLMModel,
512
766
  createWebLLMModel
513
767
  };
514
- //# sourceMappingURL=chunk-3V27UZT6.js.map
768
+ //# sourceMappingURL=chunk-DOWC4CFZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/providers/webllm.ts","../src/context-window.ts","../src/images.ts","../src/llm/generate.ts","../src/llm/util.ts","../src/memory/action-record.ts","../src/memory/compress.ts"],"sourcesContent":["import { generateText, type LanguageModel } from 'ai'\nimport { withWebLLMContextWindow, type WebLLMAppConfigLike } from '../context-window.js'\n\n/** WebGPU feature-detect — WebLLM requires it. Call before offering local models. */\nexport const isWebGPUAvailable = (): boolean =>\n typeof navigator !== 'undefined' && 'gpu' in navigator\n\nexport interface WebLLMModelOptions {\n /**\n * Progress callback for weight download / engine init. `report.progress` is\n * 0..1. Forwarded to WebLLM's `initProgressCallback`.\n */\n initProgressCallback?: (report: { progress: number; text: string }) => void\n /**\n * Download the weights and initialize the engine NOW (default true).\n *\n * The underlying provider initializes lazily on the first generation — with\n * a multi-GB model that means the download would silently happen on the\n * user's first message, with `initProgressCallback` never firing at a moment\n * the host can show it. Preloading runs a 1-token warm-up so the returned\n * model is truly ready and progress is reported during creation. Re-creating\n * an already-downloaded model is fast (weights live in the browser cache).\n *\n * Set to `false` to keep the lazy behavior.\n */\n preload?: boolean\n /**\n * The context window to load the model with, in tokens. WebLLM loads its\n * prebuilt models with 4096 (to save VRAM), far below what Qwen3 or Llama\n * 3.x were trained on; a larger window costs KV-cache memory, not a new\n * download. Applied through `engineConfig.appConfig` (WebLLM's prebuilt\n * config with this model's `context_window_size` overridden) unless you pass\n * an `appConfig` of your own; see `withWebLLMContextWindow`.\n */\n contextWindowTokens?: number\n /** Any other @browser-ai/web-llm setting (temperature, worker handler, …). */\n [k: string]: unknown\n}\n\n/**\n * Force a model to download its weights and initialize its engine by running\n * a 1-token generation. Exposed for hosts that create models with\n * `preload: false` and want to warm them up later (e.g. behind their own UI).\n */\nexport const preloadWebLLMModel = async (model: LanguageModel): Promise<void> => {\n await generateText({ model, prompt: 'ok', maxOutputTokens: 1 })\n}\n\n/**\n * Best-effort release of a model's GPU memory (call when switching models —\n * an abandoned engine otherwise holds its buffers until the page reloads).\n *\n * `@browser-ai/web-llm` keeps its MLCEngine private and exposes no public\n * `unload()`, so this reaches into the instance defensively; it is a no-op on\n * an uninitialized model or if the provider's internals change shape.\n */\nexport const unloadWebLLMModel = async (model: LanguageModel): Promise<void> => {\n const engine = (model as { engine?: { unload?: () => Promise<void> } }).engine\n try {\n await engine?.unload?.()\n } catch {\n /* best-effort */\n }\n}\n\n/**\n * Build an AI SDK `LanguageModel` backed by WebLLM (WebGPU) via the community\n * provider `@browser-ai/web-llm` (an optional peer, dynamically imported so it\n * is code-split and never loads until a local model is actually used). Accepts\n * any WebLLM prebuilt model id, e.g. \"Llama-3.2-3B-Instruct-q4f16_1-MLC\".\n *\n * By default the weights are downloaded eagerly with progress (see\n * `WebLLMModelOptions.preload`).\n */\nexport const createWebLLMModel = async (\n model: string,\n options?: WebLLMModelOptions,\n): Promise<LanguageModel> => {\n let mod: typeof import('@browser-ai/web-llm')\n try {\n mod = await import('@browser-ai/web-llm')\n } catch {\n throw new Error(\n 'Local models require \"@browser-ai/web-llm\" and its peer \"@mlc-ai/web-llm\". Install: npm install @browser-ai/web-llm @mlc-ai/web-llm',\n )\n }\n const { preload = true, contextWindowTokens, ...settings } = options ?? {}\n if (contextWindowTokens) {\n const engineConfig = (settings.engineConfig ?? {}) as { appConfig?: WebLLMAppConfigLike }\n let base = engineConfig.appConfig\n if (!base) {\n try {\n const spec = '@mlc-ai/web-llm'\n base = (\n (await import(/* webpackIgnore: true */ /* @vite-ignore */ spec)) as {\n prebuiltAppConfig: WebLLMAppConfigLike\n }\n ).prebuiltAppConfig\n } catch {\n throw new Error(\n 'contextWindowTokens needs \"@mlc-ai/web-llm\" (for its prebuilt model list), or pass engineConfig.appConfig yourself.',\n )\n }\n }\n settings.engineConfig = {\n ...engineConfig,\n appConfig: withWebLLMContextWindow(base, model, contextWindowTokens),\n }\n }\n // webLLM(modelId, settings) returns a LanguageModel. The model id is a strict\n // union in the provider's types; we accept any string and cast at the seam.\n const languageModel = mod.webLLM(\n model as Parameters<typeof mod.webLLM>[0],\n settings as Parameters<typeof mod.webLLM>[1],\n )\n if (preload) await preloadWebLLMModel(languageModel)\n return languageModel\n}\n","import { asSchema, type ToolSet } from 'ai'\nimport { modelLabel } from './images.js'\nimport {\n estimateTokens,\n type CompactionConfig,\n type ResolvedCompaction,\n} from './memory/compress.js'\n\n/**\n * The model's context window is a hard limit: a prompt that does not fit is\n * refused outright (WebLLM: \"Prompt tokens exceed context window size\"). The\n * agent sizes everything that grows — compaction thresholds, tool-result\n * clearing, the cap on one tool result, whether tools are listed or searched —\n * from the window, so it has to be the model's real one.\n *\n * Cloud windows are large and the host states them (`compaction.\n * contextWindowTokens`); a local WebLLM model's window is small (4096 tokens\n * by default — WebLLM's choice to save VRAM, not the model's limit) and is read\n * from the model itself.\n */\n\ninterface WebLLMRecordLike {\n model_id: string\n overrides?: { context_window_size?: number } & Record<string, unknown>\n}\n\n/** The shape of a WebLLM `AppConfig` this module touches. */\nexport interface WebLLMAppConfigLike {\n model_list: WebLLMRecordLike[]\n}\n\n/** WebLLM's default window for its prebuilt models. */\nexport const WEBLLM_DEFAULT_CONTEXT_WINDOW = 4096\n\n/**\n * A copy of a WebLLM app config (e.g. `prebuiltAppConfig` from\n * `@mlc-ai/web-llm`) with one model's context window set. Pass it as\n * `engineConfig.appConfig` when building the model: the weights are the same,\n * only the KV cache (VRAM) grows with the window. Models trained on long\n * contexts (Qwen3, Llama 3.x) take far more than the default 4096; models\n * trained on 4k (Llama 2) don't.\n */\nexport const withWebLLMContextWindow = <T extends WebLLMAppConfigLike>(\n appConfig: T,\n modelId: string,\n tokens: number,\n): T => ({\n ...appConfig,\n model_list: appConfig.model_list.map((r) =>\n r.model_id === modelId\n ? { ...r, overrides: { ...r.overrides, context_window_size: tokens } }\n : r,\n ),\n})\n\ninterface WebLLMModelLike {\n provider?: string\n modelId?: string\n engine?: {\n loadedModelIdToPipeline?: { get?: (id: string) => { contextWindowSize?: number } | undefined }\n }\n config?: { options?: { engineConfig?: { appConfig?: WebLLMAppConfigLike } } }\n}\n\n/**\n * The context window of a WebLLM model (`@browser-ai/web-llm`), or undefined\n * for any other model. Read from the loaded engine when it runs in this\n * thread, else from the app config it was built with, else WebLLM's defaults\n * (1024 for its \"-1k\" builds, 4096 otherwise). The provider keeps these\n * private, so this reaches in defensively.\n */\nexport const webLLMContextWindow = (model: unknown): number | undefined => {\n const m = model as WebLLMModelLike | undefined\n if (!m || typeof m !== 'object' || m.provider !== 'web-llm') return undefined\n const id = String(m.modelId ?? '')\n try {\n const live = m.engine?.loadedModelIdToPipeline?.get?.(id)?.contextWindowSize\n if (typeof live === 'number' && live > 0) return live\n } catch {\n /* the engine lives in a worker, or changed shape */\n }\n const record = m.config?.options?.engineConfig?.appConfig?.model_list?.find(\n (r) => r.model_id === id,\n )\n const configured = record?.overrides?.context_window_size\n if (typeof configured === 'number' && configured > 0) return configured\n return /-1k$/i.test(id) ? 1024 : WEBLLM_DEFAULT_CONTEXT_WINDOW\n}\n\n/**\n * The model's own context window when it can be known (local models), else\n * undefined: WebLLM's (see above), or the browser's built-in model's\n * (`@browser-ai/core` reports it once its session exists).\n */\nexport const contextWindowOf = (model: unknown): number | undefined => {\n const webllm = webLLMContextWindow(model)\n if (webllm !== undefined) return webllm\n const m = model as { provider?: string; getContextWindow?: () => number | undefined } | undefined\n if (m && typeof m === 'object' && m.provider === 'browser-ai') {\n try {\n const w = m.getContextWindow?.()\n return typeof w === 'number' && w > 0 ? w : undefined\n } catch {\n return undefined\n }\n }\n return undefined\n}\n\n/**\n * Fit the compaction settings to the model's window: the window in use is the\n * configured one, never larger than the model's own, and every size derived\n * from it shrinks with it — also a size the host set for a larger window.\n */\nexport const fitCompactionToWindow = (\n resolved: ResolvedCompaction,\n configured: CompactionConfig | undefined,\n modelWindow: number | undefined,\n): ResolvedCompaction => {\n const window = Math.min(\n configured?.contextWindowTokens ?? modelWindow ?? resolved.contextWindowTokens,\n modelWindow ?? Infinity,\n )\n if (window === resolved.contextWindowTokens && modelWindow === undefined) return resolved\n const quarter = Math.floor(window / 4)\n const clearAfter = configured?.clearToolResultsAfterTokens\n return {\n ...resolved,\n contextWindowTokens: window,\n // A threshold the host set for a larger window comes down with the window: never past 95%\n // of what the model really has (the answer and a step's growth need the rest).\n thresholdTokens: Math.min(\n configured?.thresholdTokens ?? Math.floor(window * resolved.thresholdRatio),\n Math.floor(window * 0.95),\n ),\n // 0 = never stays never.\n clearToolResultsAfterTokens: clearAfter === 0 ? 0 : Math.min(clearAfter ?? quarter, quarter),\n // One result may take a quarter of the window (~4 chars per token).\n maxToolOutputChars:\n configured?.maxToolOutputChars === 0\n ? 0\n : Math.min(configured?.maxToolOutputChars ?? 20_000, window),\n // A small window holds fewer verbatim results.\n keepToolResults:\n configured?.keepToolResults ?? Math.max(1, Math.min(3, Math.floor(window / 8192))),\n }\n}\n\n/**\n * Estimated tokens of the tool definitions a model is sent (name, description,\n * JSON schema of the input) — for tools natively, or rendered into the prompt.\n */\nexport const toolDefinitionTokens = async (tools: ToolSet): Promise<number> => {\n const sizes = await Promise.all(\n Object.entries(tools).map(async ([name, t]) => {\n let parameters: unknown\n try {\n parameters = await asSchema(t.inputSchema as never).jsonSchema\n } catch {\n parameters = undefined\n }\n return estimateTokens(JSON.stringify({ name, description: t.description ?? '', parameters }))\n }),\n )\n return sizes.reduce((a, b) => a + b, 0)\n}\n\n/** What every call carries whatever the transcript: stage instructions, the goal, the plan, the state. */\nexport const BASE_PROMPT_TOKENS = 1500\n/** Under tool search the model is sent only the built-ins and the tools found so far. */\nexport const SEARCH_TOOLS_ALLOWANCE = 3000\n\n/**\n * The tokens of a call's prompt that do not come from the transcript or the step log - the\n * stage instructions, the tool definitions, the skills - so that compaction can judge how full the\n * window really is (history + log alone say nothing about a 15k-token tool catalogue).\n */\nexport const promptOverheadTokens = (p: {\n systemPrompt?: string\n /** `toolDefinitionTokens` of everything the agent could offer. */\n toolTokens: number\n /** Tool search: only a few definitions are sent at a time. */\n searching: boolean\n /** The rendered skills index and the active skills' instructions. */\n skillsText: string\n /** The MCP servers' instructions section, when the prompts carry one. */\n mcpInstructions?: string\n}): number =>\n BASE_PROMPT_TOKENS +\n estimateTokens(p.mcpInstructions ?? '') +\n estimateTokens(p.systemPrompt ?? '') +\n (p.searching ? Math.min(p.toolTokens, SEARCH_TOOLS_ALLOWANCE) : p.toolTokens) +\n estimateTokens(p.skillsText)\n\n/** 'auto' switches to tool search once the definitions would take this share of the window. */\nexport const TOOL_SEARCH_WINDOW_SHARE = 0.25\n\n/** Raised when a prompt does not fit the model's context window. */\nexport class ContextWindowExceededError extends Error {\n /** The prompt's size as the provider counted it, when it said. */\n readonly promptTokens?: number\n /** The model's window as the provider reported it, when it said. */\n readonly contextWindowTokens?: number\n constructor(model: string, promptTokens?: number, contextWindowTokens?: number) {\n const sizes =\n promptTokens && contextWindowTokens\n ? ` (${promptTokens} tokens; the window is ${contextWindowTokens})`\n : ''\n super(\n `The conversation no longer fits the context window of \"${model}\"${sizes}. Start a new chat or compact this one, connect fewer tools, or switch to a model with a larger window.`,\n )\n this.name = 'ContextWindowExceededError'\n this.promptTokens = promptTokens\n this.contextWindowTokens = contextWindowTokens\n }\n\n toJSON(): string {\n return this.message\n }\n}\n\n// What providers say when the prompt is too long: WebLLM, OpenAI\n// (context_length_exceeded), Anthropic, Gemini, llama.cpp, vLLM / OpenRouter.\nconst OVERFLOW_RE =\n /prompt tokens exceed context window|context window size|context_length_exceeded|maximum context length|prompt is too long|input token count.*exceeds|exceeds the maximum number of tokens|exceeds the available context size|context length exceeded|too many tokens in (the )?(prompt|input)/i\nconst WEBLLM_SIZES_RE = /number of prompt tokens:\\s*(\\d+);\\s*context window size:\\s*(\\d+)/i\n\n/**\n * The clear error to raise when a provider refused a prompt for its length\n * (else undefined) — instead of the provider's raw text.\n */\nexport const contextOverflowOf = (\n err: unknown,\n model: unknown,\n): ContextWindowExceededError | undefined => {\n if (err instanceof ContextWindowExceededError) return err\n const text = err instanceof Error ? `${err.name} ${err.message}` : String(err)\n if (!OVERFLOW_RE.test(text)) return undefined\n const sizes = WEBLLM_SIZES_RE.exec(text)\n return new ContextWindowExceededError(\n modelLabel(model),\n sizes ? Number(sizes[1]) : undefined,\n sizes ? Number(sizes[2]) : (webLLMContextWindow(model) ?? undefined),\n )\n}\n","import type { FilePart } from 'ai'\n\n/**\n * Attachments sent with a run: images, PDFs and other files the provider can\n * read, given as bytes / base64 / a data URL — or as an http(s) URL, which\n * providers that accept links (Gemini, Claude, OpenAI) fetch themselves and the\n * AI SDK downloads for the rest (from the browser: subject to CORS).\n */\nexport interface RunFile {\n /** Base64 (no prefix), a data URL (\"data:image/png;base64,…\"), raw bytes, or an http(s) URL. */\n data: string | Uint8Array | URL\n /** e.g. \"image/png\", \"application/pdf\" — read from a data URL when omitted. */\n mediaType?: string\n /** Shown in the transcript, in memory and in errors. */\n name?: string\n}\n\n/** An image attachment (same shape; kept as its own name for clarity). */\nexport type RunImage = RunFile\n\n/** The kinds of attachment the agent reasons about separately. */\nexport type AttachmentKind = 'image' | 'pdf' | 'file'\n\nconst DATA_URL_RE = /^data:([^;,]+)?;base64,(.*)$/s\nconst HTTP_RE = /^https?:\\/\\//i\n\n/** The media type of an attachment (declared, from a data URL, or from a URL's extension). */\nexport const mediaTypeOf = (f: RunFile): string | undefined => {\n if (f.mediaType) return f.mediaType\n if (typeof f.data === 'string') {\n const m = DATA_URL_RE.exec(f.data)\n if (m?.[1]) return m[1]\n }\n const url = f.data instanceof URL ? f.data.href : typeof f.data === 'string' ? f.data : ''\n if (HTTP_RE.test(url) || f.name) {\n const ext = (f.name ?? new URL(url, 'http://x').pathname).split('.').pop()?.toLowerCase()\n if (ext === 'pdf') return 'application/pdf'\n if (ext && ['png', 'jpg', 'jpeg', 'gif', 'webp'].includes(ext)) {\n return `image/${ext === 'jpg' ? 'jpeg' : ext}`\n }\n }\n return undefined\n}\n\nexport const attachmentKind = (f: RunFile): AttachmentKind => {\n const mt = mediaTypeOf(f) ?? ''\n if (mt.startsWith('image/')) return 'image'\n if (mt === 'application/pdf') return 'pdf'\n return 'file'\n}\n\nconst KIND_LABEL: Record<AttachmentKind, string> = {\n image: 'images',\n pdf: 'PDF files',\n file: 'file attachments',\n}\n\nconst KIND_HINT: Record<AttachmentKind, string> = {\n image:\n 'Remove the image, or switch to a vision-capable model such as Gemini, Claude or GPT-4o/GPT-5.',\n pdf: 'Convert the PDF to text first (e.g. PDF → Markdown), or switch to a model that reads PDFs such as Gemini, Claude or GPT-4o/GPT-5.',\n file: 'Paste its text instead, or switch to a model that accepts this file type.',\n}\n\n/** Raised when attachments are sent to a model that cannot take them. */\nexport class AttachmentsNotSupportedError extends Error {\n readonly kind: AttachmentKind\n constructor(model: string, kind: AttachmentKind, detail?: string) {\n super(\n `The model \"${model}\" can't take ${KIND_LABEL[kind]}${detail ? ` (${detail})` : ''}. ${KIND_HINT[kind]}`,\n )\n this.name = 'AttachmentsNotSupportedError'\n this.kind = kind\n }\n\n toJSON(): string {\n return this.message\n }\n}\n\n/** The image flavour of {@link AttachmentsNotSupportedError}. */\nexport class ImagesNotSupportedError extends AttachmentsNotSupportedError {\n constructor(model: string, detail?: string) {\n super(model, 'image', detail)\n this.name = 'ImagesNotSupportedError'\n }\n}\n\n/** The error for a kind: images get the dedicated class. */\nexport const unsupportedAttachment = (\n model: string,\n kind: AttachmentKind,\n detail?: string,\n): AttachmentsNotSupportedError =>\n kind === 'image'\n ? new ImagesNotSupportedError(model, detail)\n : new AttachmentsNotSupportedError(model, kind, detail)\n\nconst dataOf = (f: RunFile): string | Uint8Array | URL => {\n if (typeof f.data === 'string') {\n const m = DATA_URL_RE.exec(f.data)\n if (m) return m[2]\n if (HTTP_RE.test(f.data)) return new URL(f.data)\n }\n return f.data\n}\n\n/**\n * An AI SDK file part (images included — the v7 SDK deprecates the separate\n * image part). An http(s) URL is passed as a URL: providers that accept links\n * fetch it themselves, and the SDK downloads it for the rest.\n */\nexport const toFilePart = (f: RunFile): FilePart => {\n const kind = attachmentKind(f)\n const mediaType = mediaTypeOf(f) ?? (kind === 'image' ? 'image' : 'application/octet-stream')\n return {\n type: 'file',\n data: dataOf(f),\n mediaType,\n ...(f.name ? { filename: f.name } : {}),\n }\n}\n\n/** Back-compat name. */\nexport const toImagePart = toFilePart\n\n/** A short, human label of a model for messages. */\nexport const modelLabel = (model: unknown): string => {\n if (typeof model === 'string') return model\n const m = model as { provider?: string; modelId?: string } | undefined\n return m?.modelId ? `${m.modelId}${m.provider ? ` (${m.provider})` : ''}` : 'this model'\n}\n\nconst REFUSAL_RE =\n /image|vision|multimodal|multi-modal|media type|mediatype|pdf|document|unsupported (file|content|part|mime)|does not support (file|content)|invalid content type|image_url|inline_?data|file_?data/i\n\n/** Does a provider error look like a refusal of attachment input? */\nexport const isAttachmentRefusal = (err: unknown): boolean =>\n REFUSAL_RE.test(err instanceof Error ? `${err.name} ${err.message}` : String(err))\n\n/** Back-compat name. */\nexport const isImageRefusal = isAttachmentRefusal\n","import {\n NoObjectGeneratedError,\n Output,\n generateText,\n streamText,\n type LanguageModel,\n type ModelMessage,\n type SystemModelMessage,\n type ToolSet,\n} from 'ai'\nimport type { ZodType } from 'zod'\nimport type { ProviderOptionsMap, ThinkingLevel } from '../thinking.js'\nimport { promptOf, timeoutSignal } from './util.js'\n\n/** Options shared by the low-level generation helpers. Provide `prompt` OR `messages`. */\nexport interface GenerateOptions {\n /** The system prompt — a string, or a SystemModelMessage (e.g. with a cache breakpoint). */\n system?: string | SystemModelMessage\n prompt?: string\n messages?: ModelMessage[]\n tools?: ToolSet\n maxOutputTokens?: number\n temperature?: number\n /** Portable thinking level (see `resolveThinking`). */\n reasoning?: ThinkingLevel\n /** Provider-keyed options (thinking budgets, cache keys, …). */\n providerOptions?: ProviderOptionsMap\n abortSignal?: AbortSignal\n /** Time-box the call; combined with `abortSignal` (0/undefined = no timeout). */\n timeoutMs?: number\n}\n\n/** The settings every helper forwards; omits undefined keys the SDK would reject. */\nconst callSettings = (opts: GenerateOptions) => ({\n ...(opts.system !== undefined ? { instructions: opts.system } : {}),\n maxOutputTokens: opts.maxOutputTokens,\n temperature: opts.temperature,\n ...(opts.reasoning ? { reasoning: opts.reasoning } : {}),\n ...(opts.providerOptions ? { providerOptions: opts.providerOptions as never } : {}),\n abortSignal: timeoutSignal(opts.abortSignal, opts.timeoutMs),\n})\n\n/**\n * One-shot text generation. Thin, provider-agnostic wrapper over the AI SDK's\n * `generateText` — the same call works against a cloud model, a local WebLLM\n * model, or Chrome/Edge built-in AI. Returns the full AI SDK result (`.text`,\n * `.usage`, `.toolCalls`, `.steps`, …).\n */\nexport const generate = (\n model: LanguageModel,\n opts: GenerateOptions = {},\n): ReturnType<typeof generateText> =>\n generateText({\n model,\n ...callSettings(opts),\n ...promptOf(opts),\n tools: opts.tools,\n })\n\n/** Streaming text generation. Returns the AI SDK `streamText` result (`.textStream`, `.fullStream`). */\nexport const stream = (\n model: LanguageModel,\n opts: GenerateOptions = {},\n): ReturnType<typeof streamText> =>\n streamText({\n model,\n ...callSettings(opts),\n ...promptOf(opts),\n tools: opts.tools,\n })\n\ntype TextResult = Awaited<ReturnType<typeof generateText>>\n\n/** What `generateStructured` returns: the validated object and the call's metadata. */\nexport interface StructuredResult<OBJECT> {\n object: OBJECT\n /** The raw text the object was parsed from. */\n text: string\n usage: TextResult['usage']\n finishReason: TextResult['finishReason']\n warnings: TextResult['warnings']\n request: TextResult['request']\n response: TextResult['response']\n providerMetadata: TextResult['providerMetadata']\n}\n\n/**\n * Structured output constrained to a Zod schema: the AI SDK's `generateText` with\n * `Output.object` (v7's replacement for the deprecated `generateObject` — the same request, a\n * JSON response format carrying the schema). Cloud models and WebLLM both support this; tiny\n * local models can be unreliable — the agent's prompted mode is the fallback.\n *\n * Returns `.object` and `.usage` (plus `.text`, `.finishReason`, `.warnings`, `.request`,\n * `.response`, `.providerMetadata`). An answer that is not the object — unparsable, off the\n * schema, or no text at all — throws `NoObjectGeneratedError` carrying the `usage` and the\n * `finishReason` of the attempt, so the spend of a failed attempt can still be counted\n * (`usageOfError`).\n */\nexport const generateStructured = async <OBJECT>(\n model: LanguageModel,\n schema: ZodType<OBJECT>,\n opts: GenerateOptions = {},\n): Promise<StructuredResult<OBJECT>> => {\n const result = await generateText({\n model,\n output: Output.object({ schema }),\n ...callSettings(opts),\n ...promptOf(opts),\n })\n let object: OBJECT\n try {\n object = result.output as OBJECT\n } catch (err) {\n // The model stopped without any text (cut off inside its reasoning, a content filter): the\n // SDK has nothing to parse and throws an error that knows neither the usage nor the reason.\n throw new NoObjectGeneratedError({\n message: 'No object generated: the model did not return a response.',\n cause: err instanceof Error ? err : undefined,\n text: result.text,\n response: result.response,\n usage: result.usage,\n finishReason: result.finishReason,\n })\n }\n return {\n object,\n text: result.text,\n usage: result.usage,\n finishReason: result.finishReason,\n warnings: result.warnings,\n request: result.request,\n response: result.response,\n providerMetadata: result.providerMetadata,\n }\n}\n","import type { ModelMessage } from 'ai'\nimport type { IUsage } from '../agent/loop-types.js'\n\n/** Truncate to `max` characters, ellipsising the overflow. */\nexport const clip = (s: string, max: number): string =>\n s.length > max ? `${s.slice(0, max - 1)}…` : s\n\n/**\n * The AI SDK prompt is `{ prompt } XOR { messages }` — passing both keys (even\n * with one undefined) breaks the discriminated union. Pick exactly one.\n */\nexport const promptOf = (opts: {\n prompt?: string\n messages?: ModelMessage[]\n}): { prompt: string } | { messages: ModelMessage[] } =>\n opts.messages ? { messages: opts.messages } : { prompt: opts.prompt ?? '' }\n\n/** The AI SDK usage shape, every field optional (providers omit what they don't report). */\nexport interface SdkUsageLike {\n inputTokens?: number\n outputTokens?: number\n totalTokens?: number\n inputTokenDetails?: { cacheReadTokens?: number; cacheWriteTokens?: number }\n outputTokenDetails?: { reasoningTokens?: number }\n /** Pre-v6 flat fields, still emitted by some providers. */\n reasoningTokens?: number\n cachedInputTokens?: number\n}\n\n/** Normalise the AI SDK usage shape (fields can be undefined) into IUsage. */\n/**\n * What a call that FAILED still cost. The AI SDK puts the usage on the error it throws when a\n * structured answer cannot be parsed (`NoObjectGeneratedError.usage`); the tokens were spent\n * all the same, and a fallback call must not hide them.\n */\nexport const usageOfError = (err: unknown): IUsage => {\n const u = (err as { usage?: SdkUsageLike } | null | undefined)?.usage\n return normalizeUsage(u && typeof u === 'object' ? u : undefined)\n}\n\nexport const normalizeUsage = (u?: SdkUsageLike): IUsage => {\n const inputTokens = u?.inputTokens ?? 0\n const outputTokens = u?.outputTokens ?? 0\n return {\n inputTokens,\n outputTokens,\n totalTokens: u?.totalTokens ?? inputTokens + outputTokens,\n reasoningTokens: u?.outputTokenDetails?.reasoningTokens ?? u?.reasoningTokens ?? 0,\n cachedInputTokens: u?.inputTokenDetails?.cacheReadTokens ?? u?.cachedInputTokens ?? 0,\n cacheWriteTokens: u?.inputTokenDetails?.cacheWriteTokens ?? 0,\n }\n}\n\n/**\n * Combine the caller's AbortSignal with a timeout so a hung generation can't\n * freeze a run. Returns the original signal when no timeout is set. Uses the\n * standard `AbortSignal.timeout`/`AbortSignal.any` (Node ≥ 20, modern browsers).\n */\nexport const timeoutSignal = (signal?: AbortSignal, ms?: number): AbortSignal | undefined => {\n if (!ms || ms <= 0) return signal\n const timeout = AbortSignal.timeout(ms)\n if (!signal) return timeout\n return typeof AbortSignal.any === 'function' ? AbortSignal.any([signal, timeout]) : signal\n}\n","// The runner's record of what a turn DID, kept with the assistant's answer in the conversation as\n// a mark - \"[done: ...]\" on its own last line, the way a user's message keeps \"[attached: ...]\".\n// Without it a later turn knows only what an earlier answer SAID it did, and a vague or wrong\n// answer (\"the photo was not passed\") becomes the agent's belief about its own past.\n//\n// Written by the runner from the run's own events (a call's name, arguments and result, as the\n// executor reported them), never by a model: a \"[done: ...]\" anyone else wrote - a model's answer,\n// a summary, the user's own text - is made harmless before it is kept (`neutralizeActionRecords`),\n// so only the runner's record looks like one. Every name and path in it is the model's or a tool's\n// text: cleaned to one short line (`cleanActionText`), and it is data, never instructions.\n//\n// Pure, no imports: the same file in both packages, byte for byte (the Node package's\n// tests/action-record.test.ts compares them and tests every rule).\n\n/** The whole record at most, in characters (UTF-16 code units, as `.length` counts them). */\nexport const ACTION_RECORD_MAX_CHARS = 300\n/** One name, path or role in it at most. */\nexport const ACTION_RECORD_ITEM_CHARS = 60\n/** A reference picture's path, and a helper's role, at most. */\nconst SHORT_ITEM_CHARS = 40\n/** The details (paths, roles, answers) shown per tool; the rest are counted (\"+2 more\"). */\nexport const ACTION_RECORD_DETAILS = 3\n/** What a compaction summary keeps of the records of the turns it folds in (the newest first). */\nexport const ACTION_RECORD_CARRY_CHARS = 900\n\nconst OPEN = '[done: '\n\n/**\n * The one sentence a stage reads with a conversation that carries a record. In the USER prompt,\n * next to the conversation, and only when a record is in it: a system prompt stays as it was.\n */\nexport const ACTION_RECORD_NOTE =\n 'NOTE: a \"[done: ...]\" line at the end of an assistant message (or of a summary) is the runner\\'s own record of what that turn actually did - the tools it called and how each call ended, the files it wrote or deleted, the media it made and whether reference pictures were used; it outweighs anything an answer said about that turn.'\n\n/** What is kept for a run that ended without an answer, above its record. */\nexport const ACTION_RECORD_STOPPED = '(The run was stopped before it answered.)'\nexport const ACTION_RECORD_FAILED = '(The run failed before it answered.)'\nconst NO_ANSWER = '(No answer was written.)'\n\n// ── text ────────────────────────────────────────────────────────────────────\n\n// Control characters (a line break among them) become a space; the invisible and the\n// direction-changing ones a line can hide behind go - soft hyphen, zero widths, joiners, marks,\n// isolates and overrides, the line and paragraph separators, variation selectors, the byte-order\n// mark, interlinear annotations, the Hangul fillers and the TAG block (U+E0000-E007F, as a pair).\nconst CONTROL = /[\\u0000-\\u001f\\u007f-\\u009f]/g\nconst INVISIBLE =\n /[\\u00ad\\u034f\\u061c\\u115f\\u1160\\u17b4\\u17b5\\u180b-\\u180f\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u206f\\u3164\\ufe00-\\ufe0f\\ufeff\\uffa0\\ufff0-\\ufffb]|\\udb40[\\udc00-\\udc7f]/g\n\n/**\n * One name, path or role, as a record may show it: one line, no control or invisible character,\n * no bracket (a \"]\" would end the mark), no \";\" (the separator), whitespace collapsed, at most\n * `max` characters - the head and the tail kept around an ellipsis (a path's file name is at its\n * end). Never empty: \"?\" stands for nothing.\n */\nexport const cleanActionText = (value: unknown, max: number = ACTION_RECORD_ITEM_CHARS): string => {\n const text = (typeof value === 'string' ? value : String(value ?? ''))\n .replace(CONTROL, ' ')\n .replace(INVISIBLE, '')\n .replace(/\\[/g, '(')\n .replace(/\\]/g, ')')\n .replace(/;/g, ',')\n .replace(/\\s+/g, ' ')\n .trim()\n if (!text) return '?'\n return clipChars(text, Math.max(2, max))\n}\n\n// At most `max` UTF-16 units, cut between code points: the head, an ellipsis, the tail.\nconst clipChars = (text: string, max: number): string => {\n if (text.length <= max) return text\n const chars = Array.from(text)\n let head = ''\n let tail = ''\n const room = max - 1\n const headRoom = Math.ceil(room / 3)\n for (const c of chars) {\n if (head.length + c.length > headRoom) break\n head += c\n }\n for (let i = chars.length - 1; i >= 0; i -= 1) {\n if (head.length + tail.length + chars[i].length > room) break\n tail = chars[i] + tail\n }\n return `${head}…${tail}`\n}\n\n// \"[done:\" (any case, any spacing) written by anyone but the runner.\nconst LOOKALIKE = /\\[(\\s*done\\s*:)/gi\n\n/**\n * A text kept in the conversation - a model's answer, a summary, the user's message - with every\n * \"[done:\" in it made \"(done:\": only the runner's own record has the mark's shape.\n */\nexport const neutralizeActionRecords = (text: string): string => text.replace(LOOKALIKE, '($1')\n\nconst RECORD = /^\\[done: [^\\]\\n]*\\]$/\nconst ANY_RECORD = /(?:^|\\n)\\[done: [^\\]\\n]*\\]/\n\n/** The record lines that end a stored message (one, or several: a summary keeps them). */\nexport const ACTION_RECORD_TAIL = /(?:\\n\\[done: [^\\]\\n]*\\])+$/\n\n/** True when a stored message carries a record. */\nexport const hasActionRecord = (content: string): boolean => ANY_RECORD.test(content)\n\n/**\n * What the conversation keeps of an assistant's turn: its answer - with any look-alike made\n * harmless - and the runner's record on the last line. A turn without an answer (`text` empty:\n * the run was stopped, or failed) keeps a fixed sentence saying so above its record. Without a\n * record (no tool ran) it is the answer alone; `record` must be the runner's (`[done: ...]`).\n */\nexport const withActionRecord = (\n text: string,\n record?: string,\n ended?: 'stopped' | 'failed',\n): string => {\n const answer = neutralizeActionRecords(text ?? '').trim()\n if (!record || !RECORD.test(record)) return answer\n const said =\n answer ||\n (ended === 'stopped'\n ? ACTION_RECORD_STOPPED\n : ended === 'failed'\n ? ACTION_RECORD_FAILED\n : NO_ANSWER)\n return `${said}\\n${record}`\n}\n\n/**\n * The records of the messages a compaction folds into a summary, one a line, each after a line\n * break - the newest that fit `ACTION_RECORD_CARRY_CHARS`. Kept after the summary as they are: the\n * model that writes a summary may drop them or bend them.\n */\nexport const carriedActionRecords = (contents: string[]): string => {\n const marks: string[] = []\n for (const content of contents) {\n const tail = ACTION_RECORD_TAIL.exec(content ?? '')?.[0]\n if (tail) marks.push(...tail.split('\\n').filter((line) => RECORD.test(line)))\n }\n const kept: string[] = []\n let used = 0\n for (let i = marks.length - 1; i >= 0; i -= 1) {\n if (used + marks[i].length + 1 > ACTION_RECORD_CARRY_CHARS) break\n kept.unshift(marks[i])\n used += marks[i].length + 1\n }\n return kept.map((m) => `\\n${m}`).join('')\n}\n\n// ── the record ──────────────────────────────────────────────────────────────\n\n/** A tool call as the executor reported it: name, arguments, result (or error), success. */\nexport interface IActionCall {\n name: string\n input?: unknown\n output?: unknown\n ok: boolean\n}\n\n/** What a tool does to a workspace file (the browser package's file tools). */\nexport type ActionFileOp = 'write' | 'delete'\n\nexport interface IActionRecorderOptions {\n /** The tools that write or delete a file, and which: their path is kept. */\n fileOp?: (name: string) => ActionFileOp | undefined\n}\n\nexport interface IActionRecorder {\n /**\n * An event of the run, as it is emitted: `step.tool-call` / `step.tool-result` (paired by tool\n * name, first in first out - as the executor pairs them), and `file.written` while `run_js` runs\n * (the files its program wrote). A helper's events come wrapped in `subagent.event` and are not\n * looked into: the record names the helper; what it did is its own run's.\n */\n observe(event: unknown): void\n /** A call made before this attempt (a resumed run's trace). */\n add(call: IActionCall): void\n /** The record, \"[done: ...]\" - undefined while no call has run. */\n record(): string | undefined\n}\n\n// Tools that only read the agent's own catalogue or instructions: nothing a later turn asks about.\nconst QUIET = new Set(['find_tools', 'load_skill', 'read_skill_file'])\nconst MEDIA = new Set(['generate_image', 'generate_speech'])\nconst HELPER = 'spawn_subagent'\nconst ASK = 'ask_user'\nconst CODE = 'run_js'\n\ntype Kind = 'call' | 'media' | 'file' | 'helper' | 'ask' | 'code'\n\ninterface IGroup {\n label: string\n kind: Kind\n calls: number\n failed: number\n denied: number\n unfinished: number\n details: string[]\n}\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null\n\nconst stringAt = (value: unknown, key: string): string | undefined => {\n if (!isObject(value)) return undefined\n const v = value[key]\n return typeof v === 'string' && v.trim() ? v : undefined\n}\n\n// The approval gate's refusal: its error (both packages name it so), or its message once a trace\n// went through JSON.\nconst isDenied = (output: unknown): boolean =>\n (isObject(output) && output.name === 'ToolDeniedError') ||\n (typeof output === 'string' && output.startsWith('Tool call denied by the user'))\n\n// A write a stronger tier did not run again (executorTiers): the earlier attempt's call counted.\nconst isReplayed = (output: unknown): boolean =>\n typeof output === 'string' && output.startsWith('[not run again:')\n\n// How an ask_user call ended, by the result the model read (ask-user-shared.ts's texts) - never\n// the person's own words.\nconst askOutcome = (output: unknown): string => {\n const text = typeof output === 'string' ? output : ''\n if (\n text.startsWith('The user chose: ') ||\n text.startsWith('The user did not pick an option and answered in their own words')\n ) {\n return 'answered'\n }\n if (text.startsWith('The user chose not to answer')) return 'declined'\n return 'not answered'\n}\n\nconst mediaDetail = (output: unknown): string | undefined => {\n const path = stringAt(output, 'path')\n if (!path) return undefined\n const refs = isObject(output) && isObject(output.references) ? output.references : undefined\n const paths =\n refs && Array.isArray(refs.paths) ? refs.paths.filter((p) => typeof p === 'string') : []\n if (!refs || paths.length === 0) return cleanActionText(path)\n const shown = paths.slice(0, 2).map((p) => cleanActionText(p, SHORT_ITEM_CHARS))\n const more = paths.length > 2 ? ` +${paths.length - 2}` : ''\n const word = paths.length === 1 ? 'reference' : 'references'\n return `${cleanActionText(path)} (${word} ${shown.join(', ')}${more} ${refs.used === true ? 'used' : 'NOT used'})`\n}\n\nconst fileDetail = (op: ActionFileOp, call: IActionCall): string | undefined => {\n if (op === 'write') {\n const path = stringAt(call.output, 'written') ?? stringAt(call.input, 'path')\n return path ? cleanActionText(path) : undefined\n }\n const path = stringAt(call.input, 'path')\n if (!path) return undefined\n const missing = isObject(call.output) && call.output.deleted === false\n return `${cleanActionText(path)}${missing ? ' (not found)' : ''}`\n}\n\nconst statusOf = (g: IGroup): string => {\n const ends = (\n [\n ['failed', g.failed],\n ['denied', g.denied],\n ['unfinished', g.unfinished],\n ] as const\n ).filter(([, n]) => n > 0)\n if (ends.length === 0) return ''\n if (ends.length === 1 && ends[0][1] === g.calls) return ` ${ends[0][0]}`\n return ` (${ends.map(([word, n]) => `${n} ${word}`).join(', ')})`\n}\n\nconst detailsOf = (g: IGroup): string => {\n if (g.details.length === 0) return ''\n const shown = g.details.slice(0, ACTION_RECORD_DETAILS)\n const rest = g.details.length - shown.length\n const list = `${shown.join(', ')}${rest > 0 ? `, +${rest} more` : ''}`\n switch (g.kind) {\n case 'media':\n return ` → ${list}`\n case 'file':\n return ` ${list}`\n case 'code':\n return ` (wrote ${list})`\n default:\n return ` (${list})`\n }\n}\n\nconst render = (g: IGroup): string =>\n `${g.label}${g.calls > 1 ? ` ×${g.calls}` : ''}${statusOf(g)}${detailsOf(g)}`\n\n/**\n * The record of one run: fed the run's events (and, resuming, the calls of its earlier attempts),\n * it says per tool, in the order they were first used, how many calls ran (`×n`), how they ended\n * (`failed`, `denied` - the approval gate said no -, `unfinished` - no result came, the run\n * stopped first) and, for the calls that matter later, what they made: a file's path (the file\n * tools), a picture's or a sound's path and, for generate_image, its reference pictures and\n * whether they were `used` or `NOT used`; which helper (`spawn_subagent`, by its role); whether a\n * question was answered (`ask_user`: answered, declined or not answered - never what was said);\n * the files a program wrote (`run_js`). Capped at `ACTION_RECORD_MAX_CHARS` (\"; and n more\").\n */\nexport const createActionRecorder = (options: IActionRecorderOptions = {}): IActionRecorder => {\n const groups = new Map<string, IGroup>()\n const pending: { name: string; input: unknown }[] = []\n\n const newGroup = (name: string, kind: Kind): IGroup => ({\n label: cleanActionText(name),\n kind,\n calls: 0,\n failed: 0,\n denied: 0,\n unfinished: 0,\n details: [],\n })\n const group = (name: string, kind: Kind): IGroup => {\n let g = groups.get(name)\n if (!g) {\n g = newGroup(name, kind)\n groups.set(name, g)\n }\n return g\n }\n const detail = (g: IGroup, text: string | undefined): void => {\n if (text && !g.details.includes(text)) g.details.push(text)\n }\n const kindOf = (name: string): { kind: Kind; op?: ActionFileOp } => {\n if (MEDIA.has(name)) return { kind: 'media' }\n if (name === HELPER) return { kind: 'helper' }\n if (name === ASK) return { kind: 'ask' }\n if (name === CODE) return { kind: 'code' }\n const op = options.fileOp?.(name)\n return op ? { kind: 'file', op } : { kind: 'call' }\n }\n\n const add = (call: IActionCall): void => {\n const name = typeof call?.name === 'string' ? call.name : String(call?.name ?? '')\n if (!name || QUIET.has(name) || isReplayed(call.output)) return\n const { kind, op } = kindOf(name)\n const g = group(name, kind)\n g.calls += 1\n if (call.ok !== true) {\n if (isDenied(call.output)) g.denied += 1\n else g.failed += 1\n return\n }\n switch (kind) {\n case 'media':\n detail(g, mediaDetail(call.output))\n break\n case 'file':\n detail(g, fileDetail(op as ActionFileOp, call))\n break\n case 'helper': {\n const who = stringAt(call.input, 'role') ?? stringAt(call.input, 'task')\n detail(g, who ? cleanActionText(who, SHORT_ITEM_CHARS) : undefined)\n break\n }\n case 'ask':\n detail(g, askOutcome(call.output))\n break\n }\n }\n\n return {\n observe: (event) => {\n if (!isObject(event)) return\n if (event.type === 'step.tool-call') {\n pending.push({ name: String(event.name ?? ''), input: event.input })\n } else if (event.type === 'step.tool-result') {\n const name = String(event.name ?? '')\n const at = pending.findIndex((p) => p.name === name)\n const input = at >= 0 ? pending.splice(at, 1)[0].input : undefined\n add({ name, input, output: event.output, ok: event.ok === true })\n } else if (event.type === 'file.written' && pending.some((p) => p.name === CODE)) {\n const path = stringAt(event, 'path')\n if (path) detail(group(CODE, 'code'), cleanActionText(path))\n }\n },\n add,\n record: () => {\n // A call that never got its result: the run stopped (or parked) while it ran.\n const open = new Map<string, number>()\n for (const p of pending) {\n if (p.name && !QUIET.has(p.name)) open.set(p.name, (open.get(p.name) ?? 0) + 1)\n }\n const all: IGroup[] = []\n for (const [name, g] of groups) {\n const n = open.get(name) ?? 0\n open.delete(name)\n all.push(n ? { ...g, calls: g.calls + n, unfinished: g.unfinished + n } : g)\n }\n for (const [name, n] of open) {\n all.push({ ...newGroup(name, kindOf(name).kind), calls: n, unfinished: n })\n }\n // A group with no call - files a program wrote while its call never ended - still counts.\n const parts = all.filter((g) => g.calls > 0 || g.details.length > 0).map(render)\n if (parts.length === 0) return undefined\n const shown: string[] = []\n for (let i = 0; i < parts.length; i += 1) {\n const left = parts.length - i - 1\n const next = `${OPEN}${[...shown, parts[i]].join('; ')}${left ? `; and ${left} more` : ''}]`\n if (next.length > ACTION_RECORD_MAX_CHARS) break\n shown.push(parts[i])\n }\n if (shown.length === 0) {\n // One part longer than the whole record: its head, cut to fit.\n const left = parts.length - 1\n const tail = left ? `; and ${left} more` : ''\n shown.push(clipChars(parts[0], ACTION_RECORD_MAX_CHARS - OPEN.length - tail.length - 1))\n }\n const omitted = parts.length - shown.length\n return `${OPEN}${shown.join('; ')}${omitted ? `; and ${omitted} more` : ''}]`\n },\n }\n}\n\n/** The record of a run's result, or of the error a run threw (the Node package): or undefined. */\nexport const actionRecordOf = (value: unknown): string | undefined => {\n if (!isObject(value)) return undefined\n const record = value.actionRecord\n return typeof record === 'string' && RECORD.test(record) ? record : undefined\n}\n","import type { LanguageModel } from 'ai'\nimport { generate } from '../llm/generate.js'\nimport { normalizeUsage } from '../llm/util.js'\nimport type { IUsage } from '../agent/loop-types.js'\nimport { carriedActionRecords, neutralizeActionRecords } from './action-record.js'\nimport type { StoredMessage } from './store.js'\n\n/**\n * Context compaction. A model's window is finite and every token in it is paid\n * for on every call, so long transcripts and long runs are folded into a\n * summary: the oldest material is summarised by a model, the most recent is\n * kept verbatim.\n */\nexport interface CompactionConfig {\n /** Compact automatically before planning and between steps (default true). */\n auto?: boolean\n /** The model's context window, in tokens (default 128 000). */\n contextWindowTokens?: number\n /**\n * Compact once the estimated context - the fixed prompt (system, tools, skills), the transcript\n * and the run's step log together - exceeds this many tokens. Default: `thresholdRatio` of the\n * window.\n */\n thresholdTokens?: number\n /**\n * The same threshold as a share of the window, 0 < ratio <= 1 (default 0.85). `thresholdTokens`\n * wins when both are set; it follows the window if the model turns out to have a smaller one.\n */\n thresholdRatio?: number\n /** Transcript messages kept verbatim (default 4). */\n keepRecentTurns?: number\n /** Executed steps kept verbatim in the run's trace (default 3). */\n keepRecentSteps?: number\n /** Output cap of a summary call (default 1024). */\n summaryMaxTokens?: number\n /** Cap on ONE tool result as the model sees it, in chars (default 20 000; 0 = no cap). */\n maxToolOutputChars?: number\n /**\n * Inside one step's tool loop: once its context passes this many tokens,\n * replace the oldest tool results with one-line stubs (context editing;\n * default: a quarter of the window; 0 = never).\n */\n clearToolResultsAfterTokens?: number\n /** Most recent tool results kept verbatim when clearing (default 3). */\n keepToolResults?: number\n}\n\nexport interface ResolvedCompaction {\n auto: boolean\n contextWindowTokens: number\n thresholdTokens: number\n thresholdRatio: number\n keepRecentTurns: number\n keepRecentSteps: number\n summaryMaxTokens: number\n maxToolOutputChars: number\n clearToolResultsAfterTokens: number\n keepToolResults: number\n}\n\n/**\n * Compaction starts at this share of the window unless configured. The estimate leans high (see\n * `estimateTokens`), so on a Claude model this is roughly 70-75% really used - the rest is room\n * for the answer and for what one step adds before the next check.\n */\nexport const DEFAULT_COMPACTION_THRESHOLD_RATIO = 0.85\n\nconst ratioOf = (r: number | undefined): number =>\n typeof r === 'number' && r > 0 && r <= 1 ? r : DEFAULT_COMPACTION_THRESHOLD_RATIO\n\nexport const resolveCompaction = (c: CompactionConfig | undefined): ResolvedCompaction => {\n const contextWindowTokens = c?.contextWindowTokens ?? 128_000\n const thresholdRatio = ratioOf(c?.thresholdRatio)\n return {\n auto: c?.auto ?? true,\n contextWindowTokens,\n thresholdTokens: c?.thresholdTokens ?? Math.floor(contextWindowTokens * thresholdRatio),\n thresholdRatio,\n keepRecentTurns: c?.keepRecentTurns ?? 4,\n keepRecentSteps: c?.keepRecentSteps ?? 3,\n summaryMaxTokens: c?.summaryMaxTokens ?? 1024,\n maxToolOutputChars: c?.maxToolOutputChars ?? 20_000,\n clearToolResultsAfterTokens:\n c?.clearToolResultsAfterTokens ?? Math.floor(contextWindowTokens / 4),\n keepToolResults: c?.keepToolResults ?? 3,\n }\n}\n\n// Chinese / Japanese / Korean characters and the halves of a surrogate pair (emoji): about a\n// token each. Other non-ASCII text (Cyrillic, Greek, accented Latin...) about two characters.\nconst isWide = (c: number): boolean =>\n (c >= 0x3040 && c <= 0x9fff) || (c >= 0xac00 && c <= 0xd7af) || (c >= 0xd800 && c <= 0xdfff)\n\n/**\n * Cheap, provider-independent token estimate, by kind of character - because text is not one\n * thing: letters run ~2.5 to a token (prose is kinder; code, markdown and JSON are not), digits\n * and punctuation about one each (JSON, tables, ids), a space a quarter, a newline one, other\n * scripts (Russian...) two characters, CJK and emoji one. Calibrated against Claude's tokenizer,\n * the most token-hungry in use, over prose, markdown, code, JSON, a table, Russian and a mix: it\n * comes out 1.1-1.4x the real count and never below it (a flat \"4 characters a token\" was\n * 0.4-0.7x for everything but Russian). It errs high ON PURPOSE: it decides when to compact, and\n * compacting a little early is cheap while overflowing the window is a failed run. A tokenizer\n * that packs tighter (OpenAI, Gemini) makes it higher still - then raise `thresholdRatio`.\n */\nexport const estimateTokens = (text: string): number => {\n const s = text ?? ''\n let letters = 0\n let digits = 0\n let spaces = 0\n let newlines = 0\n let punct = 0\n let other = 0\n let wide = 0\n for (let i = 0; i < s.length; i += 1) {\n const c = s.charCodeAt(i)\n if (c < 128) {\n if ((c >= 97 && c <= 122) || (c >= 65 && c <= 90)) letters += 1\n else if (c >= 48 && c <= 57) digits += 1\n else if (c === 32 || c === 9) spaces += 1\n else if (c === 10) newlines += 1\n else punct += 1\n } else if (isWide(c)) wide += 1\n else other += 1\n }\n // In thousandths of a token, so the arithmetic is exact: 1.1 x (letters / 2.5 + digits +\n // punctuation x 1.1 + spaces / 4 + newlines + other / 2 + wide).\n return Math.ceil(\n (440 * letters +\n 1100 * digits +\n 1210 * punct +\n 275 * spaces +\n 1100 * newlines +\n 550 * other +\n 1100 * wide) /\n 1000,\n )\n}\n\nconst messageTokens = (msgs: StoredMessage[]): number =>\n msgs.reduce((n, m) => n + estimateTokens(`${m.role}: ${m.content}\\n`), 0)\n\n/**\n * The lines joined, keeping the NEWEST ones that fit `maxTokens` (estimated); with no budget the\n * historical cut: the last 48 000 characters.\n */\nconst newestWithin = (lines: string[], maxTokens: number | undefined): string => {\n if (maxTokens === undefined) return lines.join('\\n').slice(-48_000)\n const kept: string[] = []\n let used = 0\n for (let i = lines.length - 1; i >= 0; i -= 1) {\n const t = estimateTokens(lines[i]) + 1\n if (used + t > maxTokens) {\n // A single line larger than the budget: its tail, rather than nothing.\n if (kept.length === 0) kept.push(lines[i].slice(-Math.max(1, maxTokens) * 2))\n break\n }\n kept.unshift(lines[i])\n used += t\n }\n return kept.join('\\n')\n}\n\nexport interface CompressOptions {\n /** Compress once the transcript exceeds this many characters (0 = never). */\n maxChars?: number\n /** Compress once the transcript's estimated tokens exceed this (wins over maxChars). */\n thresholdTokens?: number\n /** How many most-recent messages to keep verbatim. */\n keepRecent?: number\n /** Output cap of the summary call. */\n summaryMaxTokens?: number\n /**\n * The most the summariser is shown, in estimated tokens (the newest part is kept). Default: a\n * fixed 48 000 characters. The agent passes a share of the window, so a long transcript is\n * summarised whole instead of cut to its last few pages first.\n */\n maxInputTokens?: number\n /** Compact even when below the threshold (manual \"compact now\"). */\n force?: boolean\n /** Time-box the summarisation call so it can never hang the caller. */\n timeoutMs?: number\n abortSignal?: AbortSignal\n /** Receives the summary call's token usage. */\n onUsage?: (usage: IUsage) => void\n}\n\nconst SUMMARY_SYSTEM =\n 'Summarize the following conversation into a compact set of durable facts, decisions, ' +\n 'identifiers, open tasks and user preferences. Keep names, numbers and IDs verbatim. ' +\n 'A \"[done: ...]\" line is the agent\\'s own record of what that turn actually did (tools called ' +\n 'and how they ended, files written or deleted, media made and whether reference pictures were ' +\n 'used): keep those facts, paths verbatim, over anything an answer said about that turn. ' +\n 'Output plain text only.'\n\n/**\n * When the transcript grows too long, summarise everything except the last\n * `keepRecent` messages into a single system message (via the model), so the\n * session stays within the model's context window. Returns the same array\n * unchanged when no compression is needed; never throws.\n */\nexport const compressHistory = async (\n messages: StoredMessage[],\n model: LanguageModel,\n opts: CompressOptions = {},\n): Promise<StoredMessage[]> => {\n const keepRecent = opts.keepRecent ?? 6\n if (messages.length <= keepRecent + 1) return messages\n if (!opts.force) {\n if (opts.thresholdTokens !== undefined) {\n if (opts.thresholdTokens <= 0 || messageTokens(messages) <= opts.thresholdTokens) {\n return messages\n }\n } else {\n const maxChars = opts.maxChars ?? 12_000\n const chars = messages.reduce((n, m) => n + m.content.length, 0)\n if (maxChars <= 0 || chars <= maxChars) return messages\n }\n }\n const head = messages.slice(0, messages.length - keepRecent)\n const tail = messages.slice(messages.length - keepRecent)\n // The newest part of the head matters most; keep the tail end of it when it\n // has to be cut to fit the summariser's own window.\n const transcript = newestWithin(\n head.map((m) => `${m.role}: ${m.content}`),\n opts.maxInputTokens,\n )\n try {\n const result = await generate(model, {\n system: SUMMARY_SYSTEM,\n prompt: transcript,\n maxOutputTokens: opts.summaryMaxTokens ?? 400,\n timeoutMs: opts.timeoutMs,\n abortSignal: opts.abortSignal,\n })\n opts.onUsage?.(normalizeUsage(result.usage))\n const clean = (result.text || '').trim()\n if (!clean) return messages\n // The model's summary may drop or bend the runner's records of the turns it folds in: the\n // newest of them are kept after it as they are (and a look-alike it wrote is made harmless).\n const summaryMsg: StoredMessage = {\n role: 'system',\n content: `Summary of earlier conversation:\\n${neutralizeActionRecords(clean)}${carriedActionRecords(head.map((m) => m.content))}`,\n ts: head[0]?.ts,\n }\n return [summaryMsg, ...tail]\n } catch {\n return messages\n }\n}\n\n/** Alias with the sibling package's name; same behaviour as compressHistory. */\nexport const compactHistory = compressHistory\n\nconst TRACE_SYSTEM =\n 'Summarize these completed agent steps into a compact progress note: what was done, ' +\n 'what was found (keep names, numbers and IDs verbatim) and what failed. Plain text only.'\n\n/**\n * Fold the oldest entries of a run's step log into one summary entry, keeping\n * the last `keepRecent` verbatim. Returns the input unchanged when it fits the\n * threshold or on any failure; never throws.\n */\nexport const compactSteps = async (\n done: string[],\n model: LanguageModel,\n opts: CompressOptions & { thresholdTokens: number },\n): Promise<string[]> => {\n const keepRecent = opts.keepRecent ?? 3\n if (done.length <= keepRecent + 1) return done\n if (!opts.force && estimateTokens(done.join('\\n')) <= opts.thresholdTokens) return done\n const head = done.slice(0, done.length - keepRecent)\n try {\n const result = await generate(model, {\n system: TRACE_SYSTEM,\n prompt: newestWithin(\n head.map((d, i) => `${i + 1}. ${d}`),\n opts.maxInputTokens ?? 1e9,\n ),\n maxOutputTokens: opts.summaryMaxTokens ?? 600,\n timeoutMs: opts.timeoutMs,\n abortSignal: opts.abortSignal,\n })\n opts.onUsage?.(normalizeUsage(result.usage))\n const clean = (result.text || '').trim()\n if (!clean) return done\n return [`Summary of ${head.length} earlier step(s): ${clean}`, ...done.slice(head.length)]\n } catch {\n return done\n }\n}\n\nexport { messageTokens as estimateMessagesTokens }\n"],"mappings":";AAAA,SAAS,gBAAAA,qBAAwC;;;ACAjD,SAAS,gBAA8B;;;ACuBvC,IAAM,cAAc;AACpB,IAAM,UAAU;AAGT,IAAM,cAAc,CAAC,MAAmC;AAC7D,MAAI,EAAE,UAAW,QAAO,EAAE;AAC1B,MAAI,OAAO,EAAE,SAAS,UAAU;AAC9B,UAAM,IAAI,YAAY,KAAK,EAAE,IAAI;AACjC,QAAI,IAAI,CAAC,EAAG,QAAO,EAAE,CAAC;AAAA,EACxB;AACA,QAAM,MAAM,EAAE,gBAAgB,MAAM,EAAE,KAAK,OAAO,OAAO,EAAE,SAAS,WAAW,EAAE,OAAO;AACxF,MAAI,QAAQ,KAAK,GAAG,KAAK,EAAE,MAAM;AAC/B,UAAM,OAAO,EAAE,QAAQ,IAAI,IAAI,KAAK,UAAU,EAAE,UAAU,MAAM,GAAG,EAAE,IAAI,GAAG,YAAY;AACxF,QAAI,QAAQ,MAAO,QAAO;AAC1B,QAAI,OAAO,CAAC,OAAO,OAAO,QAAQ,OAAO,MAAM,EAAE,SAAS,GAAG,GAAG;AAC9D,aAAO,SAAS,QAAQ,QAAQ,SAAS,GAAG;AAAA,IAC9C;AAAA,EACF;AACA,SAAO;AACT;AAEO,IAAM,iBAAiB,CAAC,MAA+B;AAC5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,IAAM,oBAAoB,MAC/B,OAAO,cAAc,eAAe,SAAS;AAuCxC,IAAM,qBAAqB,OAAO,UAAwC;AAC/E,QAAMC,cAAa,EAAE,OAAO,QAAQ,MAAM,iBAAiB,EAAE,CAAC;AAChE;AAUO,IAAM,oBAAoB,OAAO,UAAwC;AAC9E,QAAM,SAAU,MAAwD;AACxE,MAAI;AACF,UAAM,QAAQ,SAAS;AAAA,EACzB,QAAQ;AAAA,EAER;AACF;AAWO,IAAM,oBAAoB,OAC/B,OACA,YAC2B;AAC3B,MAAI;AACJ,MAAI;AACF,UAAM,MAAM,OAAO,qBAAqB;AAAA,EAC1C,QAAQ;AACN,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,QAAM,EAAE,UAAU,MAAM,qBAAqB,GAAG,SAAS,IAAI,WAAW,CAAC;AACzE,MAAI,qBAAqB;AACvB,UAAM,eAAgB,SAAS,gBAAgB,CAAC;AAChD,QAAI,OAAO,aAAa;AACxB,QAAI,CAAC,MAAM;AACT,UAAI;AACF,cAAM,OAAO;AACb,gBACG,MAAM;AAAA;AAAA;AAAA,UAAoD;AAAA,WAG3D;AAAA,MACJ,QAAQ;AACN,cAAM,IAAI;AAAA,UACR;AAAA,QACF;AAAA,MACF;AAAA,IACF;AACA,aAAS,eAAe;AAAA,MACtB,GAAG;AAAA,MACH,WAAW,wBAAwB,MAAM,OAAO,mBAAmB;AAAA,IACrE;AAAA,EACF;AAGA,QAAM,gBAAgB,IAAI;AAAA,IACxB;AAAA,IACA;AAAA,EACF;AACA,MAAI,QAAS,OAAM,mBAAmB,aAAa;AACnD,SAAO;AACT;","names":["generateText","path","generateText"]}
@@ -6,7 +6,7 @@ import {
6
6
  currentTab,
7
7
  openAgentWebDB,
8
8
  postStorageChangeFrom
9
- } from "./chunk-JTZEUPIG.js";
9
+ } from "./chunk-NUL6QEAX.js";
10
10
 
11
11
  // src/limits.ts
12
12
  var over = (value, cap2) => typeof cap2 === "number" && cap2 > 0 && (value ?? 0) >= cap2;
@@ -824,6 +824,43 @@ var bind = (t, binding) => {
824
824
  return t;
825
825
  };
826
826
  var fileToolBindingOf = (t) => t && typeof t === "object" ? t[FILE_TOOL] : void 0;
827
+ var lineRangeOf = (startLine, endLine) => {
828
+ if (startLine === void 0 && endLine === void 0) return void 0;
829
+ const whole = (v) => typeof v === "number" && Number.isInteger(v) && v >= 1;
830
+ if (startLine !== void 0 && !whole(startLine))
831
+ throw new Error("startLine is a whole number, 1 or more (1 is the first line)");
832
+ if (endLine !== void 0 && !whole(endLine))
833
+ throw new Error("endLine is a whole number, 1 or more");
834
+ const from = startLine ?? 1;
835
+ const to = endLine;
836
+ if (to !== void 0 && to < from)
837
+ throw new Error(`endLine (${to}) is before startLine (${from})`);
838
+ return { from, ...to !== void 0 ? { to } : {} };
839
+ };
840
+ var readLines = (path, text, range, maxChars) => {
841
+ const lines = text.split("\n");
842
+ const count = lines.length > 1 && lines[lines.length - 1] === "" ? lines.length - 1 : lines.length;
843
+ if (range.from > count)
844
+ throw new Error(
845
+ `"${path}" has ${count} line${count === 1 ? "" : "s"}; startLine ${range.from} is past its end`
846
+ );
847
+ const last = Math.min(range.to ?? count, count);
848
+ const out = [];
849
+ let size = 0;
850
+ let line = range.from;
851
+ for (; line <= last; line++) {
852
+ const next = lines[line - 1];
853
+ if (size + next.length + 1 > maxChars && out.length > 0) break;
854
+ out.push(next.length > maxChars ? `${next.slice(0, maxChars)}\u2026 [line cut]` : next);
855
+ size += next.length + 1;
856
+ }
857
+ const shown = line - 1;
858
+ const head = `[${path}, lines ${range.from}-${shown} of ${count}]`;
859
+ const tail = shown < last ? `
860
+ \u2026 [truncated at ${maxChars} chars: read on from line ${shown + 1}]` : "";
861
+ return `${head}
862
+ ${out.join("\n")}${tail}`;
863
+ };
827
864
  var createFileTools = (vfs, opts = {}) => {
828
865
  const p = opts.prefix ?? "fs_";
829
866
  const maxRead = opts.maxReadChars ?? 5e4;
@@ -845,14 +882,27 @@ var createFileTools = (vfs, opts = {}) => {
845
882
  ),
846
883
  [`${p}read`]: markReadOnly(
847
884
  tool({
848
- description: "Read a text file from the workspace by its path.",
885
+ description: "Read a text file from the workspace by its path. For part of a long file, pass a line range: startLine (1 is the first line) and endLine (inclusive; to the end when left out).",
849
886
  inputSchema: jsonSchema({
850
887
  type: "object",
851
- properties: { path: { type: "string", description: 'Absolute path, e.g. "/notes.md"' } },
888
+ properties: {
889
+ path: { type: "string", description: 'Absolute path, e.g. "/notes.md"' },
890
+ startLine: {
891
+ type: "integer",
892
+ minimum: 1,
893
+ description: "The first line to read (1-based). Leave out for the whole file."
894
+ },
895
+ endLine: {
896
+ type: "integer",
897
+ minimum: 1,
898
+ description: "The last line to read (inclusive). Leave out to read to the end."
899
+ }
900
+ },
852
901
  required: ["path"],
853
902
  additionalProperties: false
854
903
  }),
855
- execute: async ({ path }) => {
904
+ execute: async ({ path, startLine, endLine }) => {
905
+ const range = lineRangeOf(startLine, endLine);
856
906
  const f = await vfs.read(path);
857
907
  if (!f) {
858
908
  const known = (await vfs.list()).map((x) => x.path).slice(0, 30);
@@ -862,6 +912,7 @@ var createFileTools = (vfs, opts = {}) => {
862
912
  return `"${f.path}" is a binary file (${f.mimeType}, ${f.size} bytes) and cannot be read as text.`;
863
913
  }
864
914
  const text = f.encoding === "base64" ? atob(f.content) : f.content;
915
+ if (range) return readLines(f.path, text, range, maxRead);
865
916
  return text.length > maxRead ? `${text.slice(0, maxRead)}\u2026 [truncated ${text.length - maxRead} chars]` : text;
866
917
  }
867
918
  })
@@ -964,4 +1015,4 @@ export {
964
1015
  fileToolBindingOf,
965
1016
  createFileTools
966
1017
  };
967
- //# sourceMappingURL=chunk-6XHCPSZE.js.map
1018
+ //# sourceMappingURL=chunk-EUJWS42C.js.map