@runappsai/agent 0.1.10 → 0.1.11

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/dist/chat.js CHANGED
@@ -15,6 +15,7 @@ import { escapeHTML } from "./markdown.js";
15
15
  import { VirtualList } from "./vlist.js";
16
16
  import { downloadBlob, h, I, modal, modalConfirm, renderMD } from "./dom.js";
17
17
  import { selectBox, SELECT_CSS } from "./select.js";
18
+ import { DEFAULT_COMPACTION, resolveSettings } from "./compaction.js";
18
19
  import { filesPanel, freePath } from "./files-panel.js";
19
20
  import { debugPanel } from "./debug-panel.js";
20
21
  import { tokenCSS, tokenProp } from "./chat-theme.js";
@@ -41,7 +42,7 @@ const STRINGS = {
41
42
  actRead: "read {n} file(s)", actList: "listed {n} folder(s)", actSearch: "searched {n} time(s)", actWrite: "wrote {n} file(s)", actEdit: "edited {n} file(s)", actDelete: "deleted {n} file(s)", actRun: "ran {n} snippet(s)", actAsk: "asked you {n} time(s)", actOther: "used {name}", actWeb: "searched the web {n} time(s)", actBrowse: "read {n} web page(s)", ingWeb: "Searching the web", ingBrowse: "Reading",
42
43
  web: "Web", webOn: "Web search: on", webOff: "Web search: off", webHint: "When on, the AI can search the web and read pages for facts and recent news; each search and each page read is billed",
43
44
  runCode: "Run code", ingRead: "Reading", ingList: "Listing", ingSearch: "Searching", ingWrite: "Writing", ingEdit: "Editing", ingDelete: "Deleting", ingRun: "Running code", ingAsk: "Asking you", ingOther: "Running", current: "Current", jumpEnd: "Jump to the latest",
44
- sTabModel: "Model", debug: "Debug", dCalls: "Calls", dRequests: "Requests", dEvents: "Events", dContext: "Context", dTools: "Tools", dClear: "Clear the record", dFilter: "Filter by type",
45
+ sTabModel: "Model", sTabContext: "Context", sCompact: "When the context is nearly full", sCompactSummary: "Summarise older turns (one extra model call)", sCompactTrim: "Only trim: drop old tool results, then the oldest turns", sCompactAt: "Start when fewer tokens than this are left", sKeepRecent: "Keep this many of the newest tokens word for word", sDefaultN: "Default ({n})", sCompactNote: "{model}: starts with {at} tokens left and keeps about {keep} word for word (capped at 20% / 40% of its {window} window)", sCompactNoteTrim: "{model}: trims with fewer than {at} tokens left (capped at 20% of its {window} window)", autoTrim: "Auto-trim", debug: "Debug", dCalls: "Calls", dRequests: "Requests", dEvents: "Events", dContext: "Context", dTools: "Tools", dClear: "Clear the record", dFilter: "Filter by type",
45
46
  dNoCalls: "No tool calls yet.", dNoRequests: "No model requests yet. Each call to the model is listed here with what was sent and what came back.", dNoEvents: "No events yet.",
46
47
  dSystem: "System prompt", dMessages: "Messages sent to the model", dPayload: "Request", dResponse: "Response", dRun: "Run", dTurn: "Turn {n}", sent: "sent", justNow: "Just now", minutesAgo: "{n} min ago", hoursAgo: "{n} h ago", context: "context", copy: "Copy", copied: "Copied", rewind: "Rewind to here", rewindTitle: "Rewind to this message", regen: "Answer again", regenTitle: "Answer this question again", regenMsg: "This answer and what follows are dropped and the question is sent again.", delTurn: "Delete", delTurnTitle: "Delete this question and its answer?", delTurnMsg: "They are removed from the conversation; files stay as they are.", replyCost: "Cost: {cost}", replyUsage: "{in} in · {out} out · {calls} calls",
47
48
  rewindMsg: "The conversation after it is dropped and the message goes back into the composer.", rewindFiles: "Also restore the directory's files to that moment", rewindGone: "This message is no longer in the conversation.", rewindSnapshot: "{n} files ({size}) as they were at {time}", rewindPartial: "Files over 2 MB were not in the snapshot and stay as they are.", rewindGoneFile: "{path} is no longer in the directory.",
@@ -81,7 +82,7 @@ const STRINGS = {
81
82
  actRead: "读取了 {n} 个文件", actList: "查看了 {n} 个目录", actSearch: "搜索了 {n} 次", actWrite: "写入了 {n} 个文件", actEdit: "修改了 {n} 个文件", actDelete: "删除了 {n} 个文件", actRun: "运行了 {n} 段代码", actAsk: "询问了你 {n} 次", actOther: "调用了 {name}", actWeb: "联网搜索了 {n} 次", actBrowse: "阅读了 {n} 个网页", ingWeb: "正在联网搜索", ingBrowse: "正在阅读",
82
83
  web: "联网", webOn: "联网搜索:已开启", webOff: "联网搜索:已关闭", webHint: "开启后 AI 可以搜索和阅读网页,查资料和最新信息;每次搜索、每读一个网页按次计费",
83
84
  runCode: "运行代码", ingRead: "正在读取", ingList: "正在查看", ingSearch: "正在搜索", ingWrite: "正在写入", ingEdit: "正在修改", ingDelete: "正在删除", ingRun: "正在运行代码", ingAsk: "正在询问你", ingOther: "正在执行", current: "当前", jumpEnd: "回到最新",
84
- sTabModel: "模型", debug: "调试", dCalls: "调用", dRequests: "请求", dEvents: "事件", dContext: "上下文", dTools: "工具", dClear: "清空记录", dFilter: "按类型过滤",
85
+ sTabModel: "模型", sTabContext: "上下文", sCompact: "上下文快满时", sCompactSummary: "把较早的对话写成摘要(多一次模型调用)", sCompactTrim: "只裁剪:先删旧的工具结果,再删最早的对话", sCompactAt: "剩余少于多少 tokens 时开始", sKeepRecent: "原样保留最近多少 tokens", sDefaultN: "默认({n})", sCompactNote: "{model}:剩余 {at} tokens 时开始,原样保留约 {keep} tokens(最多为上下文 {window} 的 20% / 40%)", sCompactNoteTrim: "{model}:剩余少于 {at} tokens 时裁剪(最多为上下文 {window} 的 20%)", autoTrim: "自动裁剪", debug: "调试", dCalls: "调用", dRequests: "请求", dEvents: "事件", dContext: "上下文", dTools: "工具", dClear: "清空记录", dFilter: "按类型过滤",
85
86
  dNoCalls: "还没有工具调用。", dNoRequests: "还没有模型请求。每次调用模型都会记在这里,包括发了什么、收到什么。", dNoEvents: "还没有事件。",
86
87
  dSystem: "系统提示词", dMessages: "发给模型的消息", dPayload: "请求内容", dResponse: "响应", dRun: "运行", dTurn: "第 {n} 轮", sent: "已发送", justNow: "刚刚", minutesAgo: "{n} 分钟前", hoursAgo: "{n} 小时前", context: "上下文", copy: "复制", copied: "已复制", rewind: "回退到这里", rewindTitle: "回退到这条消息", regen: "重新回答", regenTitle: "重新回答这个问题", regenMsg: "这个回答及之后的对话会被删除,问题重新发送。", delTurn: "删除", delTurnTitle: "删除这一轮问答?", delTurnMsg: "这条提问和它的回答会从对话中删除,文件不受影响。", replyCost: "费用:{cost}", replyUsage: "输入 {in} · 输出 {out} · {calls} 次调用",
87
88
  rewindMsg: "它之后的对话会被删除,消息内容放回输入框。", rewindFiles: "同时把目录里的文件恢复到那一刻", rewindGone: "这条消息已不在对话里(可能已被压缩)。", rewindSnapshot: "{time} 时的 {n} 个文件({size})", rewindPartial: "超过 2 MB 的文件没进快照,会保持原样。", rewindGoneFile: "{path} 已不在目录里。",
@@ -174,7 +175,7 @@ const CSS = tokenCSS() + `
174
175
  .ra-set .ra-fld{display:flex;flex-direction:column;gap:5px;font-size:12px;color:var(--ra-fg-muted)}
175
176
  .ra-set input[type=number]{font:inherit;font-size:13px;color:var(--ra-fg);background:var(--ra-bg);border:1px solid var(--ra-border);border-radius:8px;padding:6px 12px;min-height:34px;box-sizing:border-box;outline:0;width:100%;margin:0}
176
177
  .ra-set input:focus{border-color:var(--ra-accent);box-shadow:0 0 0 3px var(--ra-accent-subtle)}
177
- .ra-set .ra-row{display:flex;gap:8px;align-items:center}
178
+ .ra-set .ra-row{display:flex;gap:8px;align-items:center;padding:0}
178
179
  .ra-set .ra-row>*{flex:1;min-width:0}
179
180
  .ra-set .ra-lim{font-size:11px;color:var(--ra-fg-muted);margin-top:-4px}
180
181
  .ra-set .ra-btns{justify-content:space-between}
@@ -2981,6 +2982,8 @@ export function renderChat(target, opts) {
2981
2982
  }
2982
2983
  }
2983
2984
  });
2985
+ // The app's own compaction: what "default" means in the settings.
2986
+ const hostCompaction = { summarize: agentOpts.compaction !== false, ...(typeof agentOpts.compaction === "object" ? agentOpts.compaction : {}) };
2984
2987
  const SET_KEY = `__runapps_agent_chat:${project}:settings`;
2985
2988
  const readSettings = () => { try {
2986
2989
  return JSON.parse(localStorage.getItem(SET_KEY) || "{}");
@@ -3013,7 +3016,7 @@ export function renderChat(target, opts) {
3013
3016
  /** Puts the user's settings on an agent (every open session gets the same ones). */
3014
3017
  const applyTo = (ag, s, p) => {
3015
3018
  const hostEffort = agentOpts.extra?.reasoning_effort;
3016
- ag.configure({ model: s.model ?? agentOpts.model, maxTurns: s.maxTurns ?? agentOpts.maxTurns ?? 100, maxTokens: s.maxTokens ?? (typeof agentOpts.maxTokens === "number" ? agentOpts.maxTokens : "auto"), permissions: p ?? agentOpts.permissions ?? "ask", reasoningEffort: s.reasoningEffort ?? (typeof hostEffort === "string" ? hostEffort : null) });
3019
+ ag.configure({ model: s.model ?? agentOpts.model, maxTurns: s.maxTurns ?? agentOpts.maxTurns ?? 100, maxTokens: s.maxTokens ?? (typeof agentOpts.maxTokens === "number" ? agentOpts.maxTokens : "auto"), permissions: p ?? agentOpts.permissions ?? "ask", reasoningEffort: s.reasoningEffort ?? (typeof hostEffort === "string" ? hostEffort : null), compaction: { summarize: s.summarize ?? hostCompaction.summarize, reserveTokens: s.reserveTokens ?? hostCompaction.reserveTokens, keepRecentTokens: s.keepRecentTokens ?? hostCompaction.keepRecentTokens } });
3017
3020
  modelEl.textContent = ag.model ?? "";
3018
3021
  modelEl.style.display = ag.model ? "" : "none";
3019
3022
  };
@@ -3127,6 +3130,50 @@ export function renderChat(target, opts) {
3127
3130
  own.append(field(t.sModel, modelSel.el), lim, field(t.sEffort, effortSel.el), effortNote, field(t.sMaxTurns, turns), field(t.sMaxTokens, tokRow));
3128
3131
  if (permissionsSetting !== false)
3129
3132
  own.append(field(t.sPerms, perm.el));
3133
+ // Context: how the conversation is kept within the model's window.
3134
+ const cc = cur.compaction;
3135
+ const sumSel = sel([{ value: "summary", label: t.sCompactSummary }, { value: "trim", label: t.sCompactTrim }], cc.summarize === false ? "trim" : "summary");
3136
+ const numPick = (value, def) => {
3137
+ const mode = sel([{ value: "auto", label: t.sDefaultN.replace("{n}", fmtTokens(def)) }, { value: "n", label: t.sCustomN }], value !== undefined && value !== def ? "n" : "auto");
3138
+ const input = h("input");
3139
+ input.type = "number";
3140
+ input.min = "1024";
3141
+ input.step = "1024";
3142
+ input.value = String(value ?? def);
3143
+ const row = h("div", "ra-row");
3144
+ row.append(mode.el, input);
3145
+ const sync = () => { input.style.display = mode.value === "n" ? "" : "none"; };
3146
+ mode.el.addEventListener("change", sync);
3147
+ sync();
3148
+ /** The number chosen, or undefined for the default. */
3149
+ const read = () => { if (mode.value !== "n")
3150
+ return undefined; const v = parseInt(input.value, 10); return Number.isFinite(v) && v >= 1024 ? v : undefined; };
3151
+ return { row, read, mode, input };
3152
+ };
3153
+ const atPick = numPick(cc.reserveTokens, hostCompaction.reserveTokens ?? DEFAULT_COMPACTION.reserveTokens);
3154
+ const keepPick = numPick(cc.keepRecentTokens, hostCompaction.keepRecentTokens ?? DEFAULT_COMPACTION.keepRecentTokens);
3155
+ const keepField = field(t.sKeepRecent, keepPick.row);
3156
+ const compactNote = h("div", "ra-lim");
3157
+ const showCompact = () => {
3158
+ const summary = sumSel.value === "summary";
3159
+ keepField.style.display = summary ? "" : "none";
3160
+ // What the choice comes to with the model picked above: the thresholds are capped by its window.
3161
+ const m = chosenModel();
3162
+ const inCap = agentOpts.maxInputTokens;
3163
+ const known = typeof m?.max_input_tokens === "number" && m.max_input_tokens > 0 ? m.max_input_tokens : 128_000;
3164
+ const window = typeof inCap === "number" ? Math.min(inCap, known) : known;
3165
+ const r = resolveSettings(window, { reserveTokens: atPick.read() ?? hostCompaction.reserveTokens, keepRecentTokens: keepPick.read() ?? hostCompaction.keepRecentTokens });
3166
+ const name = m?.id ?? (modelSel.value || t.sDefault);
3167
+ compactNote.textContent = (summary ? t.sCompactNote.replace("{keep}", fmtTokens(r.keepRecentTokens)) : t.sCompactNoteTrim)
3168
+ .replace("{model}", name).replace("{at}", fmtTokens(r.reserveTokens)).replace("{window}", fmtTokens(window));
3169
+ };
3170
+ for (const el of [sumSel.el, modelSel.el, atPick.mode.el, keepPick.mode.el])
3171
+ el.addEventListener("change", showCompact);
3172
+ for (const el of [atPick.input, keepPick.input])
3173
+ el.addEventListener("input", showCompact);
3174
+ showCompact();
3175
+ const ctxPane = h("div", "ra-pane");
3176
+ ctxPane.append(field(t.sCompact, sumSel.el), field(t.sCompactAt, atPick.row), keepField, compactNote);
3130
3177
  // The host's own settings, each tab a pane: drawn here, read back on Apply.
3131
3178
  const hostReads = [];
3132
3179
  const hostPane = (tab) => {
@@ -3162,12 +3209,12 @@ export function renderChat(target, opts) {
3162
3209
  }
3163
3210
  return pane;
3164
3211
  };
3165
- const panes = [own, ...(settingsTabs ?? []).map(hostPane)];
3212
+ const panes = [own, ctxPane, ...(settingsTabs ?? []).map(hostPane)];
3166
3213
  if (panes.length > 1) {
3167
3214
  // Tabs: the chat's own first, then the host's; the panel reopens on the tab last shown.
3168
3215
  const bar = h("div", "ra-tabs");
3169
3216
  bar.setAttribute("role", "tablist");
3170
- const tabs = [t.sTabModel, ...(settingsTabs ?? []).map((x) => x.label)].map((label, i) => {
3217
+ const tabs = [t.sTabModel, t.sTabContext, ...(settingsTabs ?? []).map((x) => x.label)].map((label, i) => {
3171
3218
  const b = h("button", "ra-tab", label);
3172
3219
  b.type = "button";
3173
3220
  b.setAttribute("role", "tab");
@@ -3229,6 +3276,15 @@ export function renderChat(target, opts) {
3229
3276
  next.reasoningEffort = effortSel.value;
3230
3277
  if (perm.value === "ask" || perm.value === "auto")
3231
3278
  permChoice = perm.value;
3279
+ const summarize = sumSel.value === "summary";
3280
+ if (summarize !== hostCompaction.summarize)
3281
+ next.summarize = summarize;
3282
+ const at = atPick.read();
3283
+ if (at !== undefined)
3284
+ next.reserveTokens = at;
3285
+ const keep = keepPick.read();
3286
+ if (keep !== undefined)
3287
+ next.keepRecentTokens = keep;
3232
3288
  for (const read of hostReads)
3233
3289
  read();
3234
3290
  saveSettings(next);
@@ -3763,14 +3819,13 @@ export function renderChat(target, opts) {
3763
3819
  const price = priceOf(info);
3764
3820
  const pct = Math.round((c.used / c.window) * 100);
3765
3821
  const u = a.usage;
3766
- const comp = agentOpts.compaction;
3767
3822
  const lines = [
3768
3823
  `- ${t.sModel}: ${a.model || (await loadModels()).find((m) => m.is_default)?.id || t.sDefault}`,
3769
3824
  `- ${t.context}: ${pct < 1 && c.used ? "<1" : pct}% · ${fmtTokens(c.used)} / ${fmtTokens(c.window)} tokens · ${t.sMaxTokens} ${fmtTokens(lim.output)}`,
3770
3825
  price ? `- ${t.sPrice}: ${price}` : "",
3771
3826
  `- ${t.messagesLabel}: ${a.messages.length}`,
3772
3827
  u.calls ? `- ${fill(t.usageLine.replace("{cost}", fmtCost(u.total_cost, info?.price?.currency)).replace("{tokens}", fmtTokens(u.prompt_tokens + u.completion_tokens)).replace("{calls}", String(u.calls)))}` : "",
3773
- comp === false ? "" : `- ${t.autoCompact}: ${t.autoCompactAt.replace("{n}", fmtTokens(Math.min(16_384, Math.floor(c.window * 0.2))))}`,
3828
+ `- ${compactLine(a, c.window)}`,
3774
3829
  a.workspace ? `- ${t.directory}: \`${a.workspace.id}\`` : "",
3775
3830
  ].filter(Boolean);
3776
3831
  addNote(t.context, lines.join("\n"));
@@ -3852,6 +3907,8 @@ export function renderChat(target, opts) {
3852
3907
  });
3853
3908
  };
3854
3909
  const cap = (x) => x.charAt(0).toUpperCase() + x.slice(1);
3910
+ /** "Auto-compaction: when less than 16k tokens are left" (or Auto-trim), as the agent will do it now. */
3911
+ const compactLine = (a, window) => { const c = a.compactionFor(window); return `${c.summarize ? t.autoCompact : t.autoTrim}: ${t.autoCompactAt.replace("{n}", fmtTokens(c.reserveTokens))}`; };
3855
3912
  const pctOf = (used, window) => { const p = used / window; return used && p < 0.01 ? "<1%" : `${Math.round(Math.min(1, p) * 100)}%`; };
3856
3913
  /** The usage panel: how full the context is, what the conversation has cost, and Compact now. */
3857
3914
  const fillUsage = (panel, a, c) => {
@@ -3872,8 +3929,7 @@ export function renderChat(target, opts) {
3872
3929
  grid.append(cell);
3873
3930
  }
3874
3931
  panel.replaceChildren(head, bar, sub, grid);
3875
- if (agentOpts.compaction !== false)
3876
- panel.append(h("div", "ra-unote", `${t.autoCompact}: ${t.autoCompactAt.replace("{n}", fmtTokens(Math.min(16_384, Math.floor(c.window * 0.2))))}`));
3932
+ panel.append(h("div", "ra-unote", compactLine(a, c.window)));
3877
3933
  const foot = h("div", "ra-mf");
3878
3934
  const compactBtn = h("button", "ra-btn xs ghost");
3879
3935
  compactBtn.type = "button";
@@ -5,6 +5,16 @@ export interface CompactionSettings {
5
5
  /** Keep about this many tokens of recent turns verbatim (default 20 000, at most 40 % of the window). */
6
6
  keepRecentTokens: number;
7
7
  }
8
+ /**
9
+ * Compaction as a user may change it mid-conversation
10
+ * (`agent.configure({ compaction })`, `agent.settings.compaction`):
11
+ * `summarize: false` only trims (old tool results elided, oldest turns
12
+ * dropped), never asking the model for a summary; a threshold left out
13
+ * (or set to undefined in `configure`) is the default.
14
+ */
15
+ export interface CompactionChoice extends Partial<CompactionSettings> {
16
+ summarize?: boolean;
17
+ }
8
18
  export declare const DEFAULT_COMPACTION: CompactionSettings;
9
19
  export declare const COMPACTION_SUMMARY_PREFIX = "The conversation history before this point was compacted into the following summary:\n\n<summary>\n";
10
20
  export declare const COMPACTION_SUMMARY_SUFFIX = "\n</summary>";
package/dist/index.cjs CHANGED
@@ -24,6 +24,7 @@ var src_exports = {};
24
24
  __export(src_exports, {
25
25
  Agent: () => Agent,
26
26
  ContextOverflowError: () => ContextOverflowError,
27
+ DEFAULT_COMPACTION: () => DEFAULT_COMPACTION,
27
28
  DEFAULT_SKILLS_DIR: () => DEFAULT_SKILLS_DIR,
28
29
  DEFAULT_USER_SKILLS_DIR: () => DEFAULT_USER_SKILLS_DIR,
29
30
  MCPError: () => MCPError,
@@ -3673,6 +3674,10 @@ var Agent = class {
3673
3674
  __publicField(this, "opts");
3674
3675
  /** `webTools` as configured (a function is read every turn). */
3675
3676
  __publicField(this, "web");
3677
+ /** Whether the loop summarises older turns (else it only trims them): `compaction !== false`, or `configure({ compaction })`. */
3678
+ __publicField(this, "compactSummaries");
3679
+ /** The compaction thresholds set (an unset one is the default): the `compaction` object, or `configure({ compaction })`. */
3680
+ __publicField(this, "compactThresholds");
3676
3681
  /** The platform's web tools, loaded the first time they are offered. */
3677
3682
  __publicField(this, "webCache", null);
3678
3683
  __publicField(this, "history", []);
@@ -3699,6 +3704,8 @@ var Agent = class {
3699
3704
  __publicField(this, "persist");
3700
3705
  this.provider = toProvider(provider);
3701
3706
  this.opts = opts;
3707
+ this.compactSummaries = opts.compaction !== false;
3708
+ this.compactThresholds = typeof opts.compaction === "object" ? { ...opts.compaction } : {};
3702
3709
  this.id = opts.id || `agent_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
3703
3710
  this.ui = opts.ui ?? domUI();
3704
3711
  this.workspace = opts.workspace ?? null;
@@ -3826,10 +3833,20 @@ var Agent = class {
3826
3833
  get settings() {
3827
3834
  const p = this.opts.permissions ?? "ask";
3828
3835
  const re = this.opts.extra?.reasoning_effort;
3829
- return { model: this.opts.model, maxTurns: this.opts.maxTurns ?? DEFAULT_MAX_TURNS, maxTokens: typeof this.opts.maxTokens === "number" ? this.opts.maxTokens : "auto", permissions: typeof p === "function" ? "custom" : p, reasoningEffort: typeof re === "string" ? re : void 0 };
3836
+ return { model: this.opts.model, maxTurns: this.opts.maxTurns ?? DEFAULT_MAX_TURNS, maxTokens: typeof this.opts.maxTokens === "number" ? this.opts.maxTokens : "auto", permissions: typeof p === "function" ? "custom" : p, reasoningEffort: typeof re === "string" ? re : void 0, compaction: { summarize: this.compactSummaries, ...this.compactThresholds } };
3830
3837
  }
3831
3838
  /** Changes settings for the runs that follow (a run in progress keeps its own). `undefined` leaves a field alone; `reasoningEffort: null` takes the model's default. */
3832
3839
  configure(patch) {
3840
+ if (patch.compaction) {
3841
+ const c = patch.compaction;
3842
+ if (typeof c.summarize === "boolean") this.compactSummaries = c.summarize;
3843
+ for (const k of ["reserveTokens", "keepRecentTokens"]) {
3844
+ if (!(k in c)) continue;
3845
+ const v = c[k];
3846
+ if (typeof v === "number" && Number.isFinite(v) && v > 0) this.compactThresholds[k] = Math.floor(v);
3847
+ else delete this.compactThresholds[k];
3848
+ }
3849
+ }
3833
3850
  if ("model" in patch) this.model = patch.model || void 0;
3834
3851
  if (typeof patch.webTools === "boolean") this.web = patch.webTools;
3835
3852
  if ("reasoningEffort" in patch) {
@@ -3842,6 +3859,15 @@ var Agent = class {
3842
3859
  if (patch.maxTokens !== void 0) this.opts.maxTokens = patch.maxTokens;
3843
3860
  if (patch.permissions !== void 0) this.opts.permissions = patch.permissions;
3844
3861
  }
3862
+ /**
3863
+ * Compaction as it applies to a window of `window` tokens: whether older
3864
+ * turns are summarised (else only trimmed), at how many tokens left it
3865
+ * starts (`reserveTokens`) and how much of the newest it keeps verbatim
3866
+ * (`keepRecentTokens`), each capped by the window (20 % / 40 %).
3867
+ */
3868
+ compactionFor(window) {
3869
+ return { summarize: this.compactSummaries, ...resolveSettings(window, this.compactThresholds) };
3870
+ }
3845
3871
  /** A snapshot to save (`restore` continues it). Taken at the last complete turn. */
3846
3872
  export() {
3847
3873
  const messages = this.history.slice(0, this.committed);
@@ -4049,7 +4075,7 @@ var Agent = class {
4049
4075
  const maxTurns = this.opts.maxTurns ?? DEFAULT_MAX_TURNS;
4050
4076
  const { output: maxTokens, input: catalogueWindow } = await this.limits();
4051
4077
  let window = catalogueWindow;
4052
- let compaction = resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {});
4078
+ let compaction = resolveSettings(window, this.compactThresholds);
4053
4079
  let overflowRetries = 0;
4054
4080
  try {
4055
4081
  if (prefaceError) throw prefaceError;
@@ -4069,7 +4095,7 @@ var Agent = class {
4069
4095
  const fixed = this.fixedText(system);
4070
4096
  const tokensBefore = estimateTokens(this.history, fixed);
4071
4097
  if (shouldCompact(tokensBefore, window, compaction)) {
4072
- const summarized = this.opts.compaction === false ? false : await this.compactWith(compaction, runId, signal);
4098
+ const summarized = !this.compactSummaries ? false : await this.compactWith(compaction, runId, signal);
4073
4099
  const after = estimateTokens(this.history, fixed);
4074
4100
  if (!summarized || shouldCompact(after, window, compaction)) {
4075
4101
  const pinned = this.history.length && summaryOf(this.history[0]) !== null ? [this.history[0]] : [];
@@ -4110,7 +4136,7 @@ var Agent = class {
4110
4136
  const limit = overflowLimit(err);
4111
4137
  if (limit !== void 0 && limit < window) {
4112
4138
  window = limit;
4113
- compaction = resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {});
4139
+ compaction = resolveSettings(window, this.compactThresholds);
4114
4140
  }
4115
4141
  let smaller = false;
4116
4142
  while (!smaller && overflowRetries < 2) smaller = await this.squeeze(window, overflowRetries++, compaction, fixed, runId, signal);
@@ -4300,7 +4326,7 @@ var Agent = class {
4300
4326
  compact(focus) {
4301
4327
  return this.exclusive("compact", async (signal) => {
4302
4328
  const window = await this.contextTokens();
4303
- const settings = this.squeezed(resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {}));
4329
+ const settings = this.squeezed(resolveSettings(window, this.compactThresholds));
4304
4330
  const done = await this.compactWith(settings, void 0, signal, focus);
4305
4331
  if (done) await this.saveSession();
4306
4332
  return done;
@@ -4318,7 +4344,7 @@ var Agent = class {
4318
4344
  const toSummarize = first === null ? rest : rest.slice(1);
4319
4345
  if (!toSummarize.length) return first;
4320
4346
  const window = await this.contextTokens();
4321
- const settings = resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {});
4347
+ const settings = resolveSettings(window, this.compactThresholds);
4322
4348
  this.emit("compaction_start", {});
4323
4349
  try {
4324
4350
  return await this.writeSummary({ toSummarize, previousSummary: first ?? void 0, kept: [] }, settings, void 0, signal);
@@ -4372,7 +4398,7 @@ var Agent = class {
4372
4398
  */
4373
4399
  async squeeze(window, round2, settings, fixed, runId, signal) {
4374
4400
  const before = estimateTokens(this.history, fixed);
4375
- if (round2 === 0 && this.opts.compaction !== false) await this.compactWith(this.squeezed(settings), runId, signal);
4401
+ if (round2 === 0 && this.compactSummaries) await this.compactWith(this.squeezed(settings), runId, signal);
4376
4402
  const pinned = this.history.length && summaryOf(this.history[0]) !== null ? [this.history[0]] : [];
4377
4403
  const rest = this.history.slice(pinned.length);
4378
4404
  const budget = Math.floor(window * (round2 === 0 ? 0.7 : 0.4)) - estimateTokens(pinned);
package/dist/index.d.ts CHANGED
@@ -19,7 +19,7 @@ export declare function createAgent(provider: ModelProvider | RunAppsClientLike,
19
19
  */
20
20
  export declare function openWorkspace(provider: ModelProvider | RunAppsClientLike | null, opts?: WorkspaceOptions): Promise<Workspace>;
21
21
  export { Workspace, memoryFS, normalizePath, guessType, decodeText, titleOf, UNTITLED, DEFAULT_SKILLS_DIR, DEFAULT_USER_SKILLS_DIR, type SkillSource, type LazySkill, type WorkspaceOptions, type WorkspaceRead, type WorkspaceChange, type SessionStore, type WorkspaceStore, type WorkspaceStoreFactory, type FileRecord } from "./workspace.js";
22
- export { planCut, serializeConversation, splitForSummary, summaryOf, summaryMessage, type CompactionSettings, type CutPlan } from "./compaction.js";
22
+ export { planCut, serializeConversation, splitForSummary, summaryOf, summaryMessage, DEFAULT_COMPACTION, type CompactionChoice, type CompactionSettings, type CutPlan } from "./compaction.js";
23
23
  export { parseCommandArgs, substituteArgs, listTemplates, expandSlash, type PromptTemplate } from "./templates.js";
24
24
  export { applyEdits, normalizeForFuzzyMatch, type TextEdit } from "./edit.js";
25
25
  export { defineTool, normalizeResult } from "./tool.js";
package/dist/index.js CHANGED
@@ -27,7 +27,7 @@ export function openWorkspace(provider, opts = {}) {
27
27
  return Workspace.open(p, { ...opts, project: opts.project ?? p?.name ?? undefined });
28
28
  }
29
29
  export { Workspace, memoryFS, normalizePath, guessType, decodeText, titleOf, UNTITLED, DEFAULT_SKILLS_DIR, DEFAULT_USER_SKILLS_DIR } from "./workspace.js";
30
- export { planCut, serializeConversation, splitForSummary, summaryOf, summaryMessage } from "./compaction.js";
30
+ export { planCut, serializeConversation, splitForSummary, summaryOf, summaryMessage, DEFAULT_COMPACTION } from "./compaction.js";
31
31
  export { parseCommandArgs, substituteArgs, listTemplates, expandSlash } from "./templates.js";
32
32
  export { applyEdits, normalizeForFuzzyMatch } from "./edit.js";
33
33
  export { defineTool, normalizeResult } from "./tool.js";
package/dist/ui.cjs CHANGED
@@ -884,6 +884,15 @@ var SELECT_CSS = `
884
884
  :is(.ra-chat,.ra-ui) .ra-selnone{padding:8px;color:var(--ra-fg-muted)}
885
885
  `;
886
886
 
887
+ // src/compaction.ts
888
+ var DEFAULT_COMPACTION = { reserveTokens: 16384, keepRecentTokens: 2e4 };
889
+ function resolveSettings(window2, s = {}) {
890
+ return {
891
+ reserveTokens: Math.min(s.reserveTokens ?? DEFAULT_COMPACTION.reserveTokens, Math.floor(window2 * 0.2)),
892
+ keepRecentTokens: Math.min(s.keepRecentTokens ?? DEFAULT_COMPACTION.keepRecentTokens, Math.floor(window2 * 0.4))
893
+ };
894
+ }
895
+
887
896
  // src/files-panel.ts
888
897
  var import_index = require("./index.cjs");
889
898
  var IMAGE_RE = /\.(png|jpe?g|gif|webp|svg|bmp|avif)$/i;
@@ -2106,6 +2115,16 @@ var STRINGS = {
2106
2115
  current: "Current",
2107
2116
  jumpEnd: "Jump to the latest",
2108
2117
  sTabModel: "Model",
2118
+ sTabContext: "Context",
2119
+ sCompact: "When the context is nearly full",
2120
+ sCompactSummary: "Summarise older turns (one extra model call)",
2121
+ sCompactTrim: "Only trim: drop old tool results, then the oldest turns",
2122
+ sCompactAt: "Start when fewer tokens than this are left",
2123
+ sKeepRecent: "Keep this many of the newest tokens word for word",
2124
+ sDefaultN: "Default ({n})",
2125
+ sCompactNote: "{model}: starts with {at} tokens left and keeps about {keep} word for word (capped at 20% / 40% of its {window} window)",
2126
+ sCompactNoteTrim: "{model}: trims with fewer than {at} tokens left (capped at 20% of its {window} window)",
2127
+ autoTrim: "Auto-trim",
2109
2128
  debug: "Debug",
2110
2129
  dCalls: "Calls",
2111
2130
  dRequests: "Requests",
@@ -2364,6 +2383,16 @@ var STRINGS = {
2364
2383
  current: "\u5F53\u524D",
2365
2384
  jumpEnd: "\u56DE\u5230\u6700\u65B0",
2366
2385
  sTabModel: "\u6A21\u578B",
2386
+ sTabContext: "\u4E0A\u4E0B\u6587",
2387
+ sCompact: "\u4E0A\u4E0B\u6587\u5FEB\u6EE1\u65F6",
2388
+ sCompactSummary: "\u628A\u8F83\u65E9\u7684\u5BF9\u8BDD\u5199\u6210\u6458\u8981\uFF08\u591A\u4E00\u6B21\u6A21\u578B\u8C03\u7528\uFF09",
2389
+ sCompactTrim: "\u53EA\u88C1\u526A\uFF1A\u5148\u5220\u65E7\u7684\u5DE5\u5177\u7ED3\u679C\uFF0C\u518D\u5220\u6700\u65E9\u7684\u5BF9\u8BDD",
2390
+ sCompactAt: "\u5269\u4F59\u5C11\u4E8E\u591A\u5C11 tokens \u65F6\u5F00\u59CB",
2391
+ sKeepRecent: "\u539F\u6837\u4FDD\u7559\u6700\u8FD1\u591A\u5C11 tokens",
2392
+ sDefaultN: "\u9ED8\u8BA4\uFF08{n}\uFF09",
2393
+ sCompactNote: "{model}\uFF1A\u5269\u4F59 {at} tokens \u65F6\u5F00\u59CB\uFF0C\u539F\u6837\u4FDD\u7559\u7EA6 {keep} tokens\uFF08\u6700\u591A\u4E3A\u4E0A\u4E0B\u6587 {window} \u7684 20% / 40%\uFF09",
2394
+ sCompactNoteTrim: "{model}\uFF1A\u5269\u4F59\u5C11\u4E8E {at} tokens \u65F6\u88C1\u526A\uFF08\u6700\u591A\u4E3A\u4E0A\u4E0B\u6587 {window} \u7684 20%\uFF09",
2395
+ autoTrim: "\u81EA\u52A8\u88C1\u526A",
2367
2396
  debug: "\u8C03\u8BD5",
2368
2397
  dCalls: "\u8C03\u7528",
2369
2398
  dRequests: "\u8BF7\u6C42",
@@ -2569,7 +2598,7 @@ var CSS = tokenCSS() + `
2569
2598
  .ra-set .ra-fld{display:flex;flex-direction:column;gap:5px;font-size:12px;color:var(--ra-fg-muted)}
2570
2599
  .ra-set input[type=number]{font:inherit;font-size:13px;color:var(--ra-fg);background:var(--ra-bg);border:1px solid var(--ra-border);border-radius:8px;padding:6px 12px;min-height:34px;box-sizing:border-box;outline:0;width:100%;margin:0}
2571
2600
  .ra-set input:focus{border-color:var(--ra-accent);box-shadow:0 0 0 3px var(--ra-accent-subtle)}
2572
- .ra-set .ra-row{display:flex;gap:8px;align-items:center}
2601
+ .ra-set .ra-row{display:flex;gap:8px;align-items:center;padding:0}
2573
2602
  .ra-set .ra-row>*{flex:1;min-width:0}
2574
2603
  .ra-set .ra-lim{font-size:11px;color:var(--ra-fg-muted);margin-top:-4px}
2575
2604
  .ra-set .ra-btns{justify-content:space-between}
@@ -5171,6 +5200,7 @@ ${c.text}` })));
5171
5200
  }
5172
5201
  }
5173
5202
  });
5203
+ const hostCompaction = { summarize: agentOpts.compaction !== false, ...typeof agentOpts.compaction === "object" ? agentOpts.compaction : {} };
5174
5204
  const SET_KEY = `__runapps_agent_chat:${project}:settings`;
5175
5205
  const readSettings = () => {
5176
5206
  try {
@@ -5200,7 +5230,7 @@ ${c.text}` })));
5200
5230
  };
5201
5231
  const applyTo = (ag, s, p) => {
5202
5232
  const hostEffort = agentOpts.extra?.reasoning_effort;
5203
- ag.configure({ model: s.model ?? agentOpts.model, maxTurns: s.maxTurns ?? agentOpts.maxTurns ?? 100, maxTokens: s.maxTokens ?? (typeof agentOpts.maxTokens === "number" ? agentOpts.maxTokens : "auto"), permissions: p ?? agentOpts.permissions ?? "ask", reasoningEffort: s.reasoningEffort ?? (typeof hostEffort === "string" ? hostEffort : null) });
5233
+ ag.configure({ model: s.model ?? agentOpts.model, maxTurns: s.maxTurns ?? agentOpts.maxTurns ?? 100, maxTokens: s.maxTokens ?? (typeof agentOpts.maxTokens === "number" ? agentOpts.maxTokens : "auto"), permissions: p ?? agentOpts.permissions ?? "ask", reasoningEffort: s.reasoningEffort ?? (typeof hostEffort === "string" ? hostEffort : null), compaction: { summarize: s.summarize ?? hostCompaction.summarize, reserveTokens: s.reserveTokens ?? hostCompaction.reserveTokens, keepRecentTokens: s.keepRecentTokens ?? hostCompaction.keepRecentTokens } });
5204
5234
  modelEl.textContent = ag.model ?? "";
5205
5235
  modelEl.style.display = ag.model ? "" : "none";
5206
5236
  };
@@ -5315,6 +5345,49 @@ ${c.text}` })));
5315
5345
  const own = h("div", "ra-pane");
5316
5346
  own.append(field(t.sModel, modelSel.el), lim, field(t.sEffort, effortSel.el), effortNote, field(t.sMaxTurns, turns), field(t.sMaxTokens, tokRow));
5317
5347
  if (permissionsSetting !== false) own.append(field(t.sPerms, perm.el));
5348
+ const cc = cur.compaction;
5349
+ const sumSel = sel([{ value: "summary", label: t.sCompactSummary }, { value: "trim", label: t.sCompactTrim }], cc.summarize === false ? "trim" : "summary");
5350
+ const numPick = (value, def) => {
5351
+ const mode = sel([{ value: "auto", label: t.sDefaultN.replace("{n}", fmtTokens(def)) }, { value: "n", label: t.sCustomN }], value !== void 0 && value !== def ? "n" : "auto");
5352
+ const input = h("input");
5353
+ input.type = "number";
5354
+ input.min = "1024";
5355
+ input.step = "1024";
5356
+ input.value = String(value ?? def);
5357
+ const row = h("div", "ra-row");
5358
+ row.append(mode.el, input);
5359
+ const sync = () => {
5360
+ input.style.display = mode.value === "n" ? "" : "none";
5361
+ };
5362
+ mode.el.addEventListener("change", sync);
5363
+ sync();
5364
+ const read = () => {
5365
+ if (mode.value !== "n") return void 0;
5366
+ const v = parseInt(input.value, 10);
5367
+ return Number.isFinite(v) && v >= 1024 ? v : void 0;
5368
+ };
5369
+ return { row, read, mode, input };
5370
+ };
5371
+ const atPick = numPick(cc.reserveTokens, hostCompaction.reserveTokens ?? DEFAULT_COMPACTION.reserveTokens);
5372
+ const keepPick = numPick(cc.keepRecentTokens, hostCompaction.keepRecentTokens ?? DEFAULT_COMPACTION.keepRecentTokens);
5373
+ const keepField = field(t.sKeepRecent, keepPick.row);
5374
+ const compactNote = h("div", "ra-lim");
5375
+ const showCompact = () => {
5376
+ const summary = sumSel.value === "summary";
5377
+ keepField.style.display = summary ? "" : "none";
5378
+ const m = chosenModel();
5379
+ const inCap = agentOpts.maxInputTokens;
5380
+ const known = typeof m?.max_input_tokens === "number" && m.max_input_tokens > 0 ? m.max_input_tokens : 128e3;
5381
+ const window2 = typeof inCap === "number" ? Math.min(inCap, known) : known;
5382
+ const r = resolveSettings(window2, { reserveTokens: atPick.read() ?? hostCompaction.reserveTokens, keepRecentTokens: keepPick.read() ?? hostCompaction.keepRecentTokens });
5383
+ const name = m?.id ?? (modelSel.value || t.sDefault);
5384
+ compactNote.textContent = (summary ? t.sCompactNote.replace("{keep}", fmtTokens(r.keepRecentTokens)) : t.sCompactNoteTrim).replace("{model}", name).replace("{at}", fmtTokens(r.reserveTokens)).replace("{window}", fmtTokens(window2));
5385
+ };
5386
+ for (const el of [sumSel.el, modelSel.el, atPick.mode.el, keepPick.mode.el]) el.addEventListener("change", showCompact);
5387
+ for (const el of [atPick.input, keepPick.input]) el.addEventListener("input", showCompact);
5388
+ showCompact();
5389
+ const ctxPane = h("div", "ra-pane");
5390
+ ctxPane.append(field(t.sCompact, sumSel.el), field(t.sCompactAt, atPick.row), keepField, compactNote);
5318
5391
  const hostReads = [];
5319
5392
  const hostPane = (tab) => {
5320
5393
  const pane = h("div", "ra-pane");
@@ -5348,11 +5421,11 @@ ${c.text}` })));
5348
5421
  }
5349
5422
  return pane;
5350
5423
  };
5351
- const panes = [own, ...(settingsTabs ?? []).map(hostPane)];
5424
+ const panes = [own, ctxPane, ...(settingsTabs ?? []).map(hostPane)];
5352
5425
  if (panes.length > 1) {
5353
5426
  const bar2 = h("div", "ra-tabs");
5354
5427
  bar2.setAttribute("role", "tablist");
5355
- const tabs = [t.sTabModel, ...(settingsTabs ?? []).map((x) => x.label)].map((label, i) => {
5428
+ const tabs = [t.sTabModel, t.sTabContext, ...(settingsTabs ?? []).map((x) => x.label)].map((label, i) => {
5356
5429
  const b = h("button", "ra-tab", label);
5357
5430
  b.type = "button";
5358
5431
  b.setAttribute("role", "tab");
@@ -5406,6 +5479,12 @@ ${c.text}` })));
5406
5479
  }
5407
5480
  if (effortSel.value && !effortSel.disabled) next.reasoningEffort = effortSel.value;
5408
5481
  if (perm.value === "ask" || perm.value === "auto") permChoice = perm.value;
5482
+ const summarize = sumSel.value === "summary";
5483
+ if (summarize !== hostCompaction.summarize) next.summarize = summarize;
5484
+ const at = atPick.read();
5485
+ if (at !== void 0) next.reserveTokens = at;
5486
+ const keep = keepPick.read();
5487
+ if (keep !== void 0) next.keepRecentTokens = keep;
5409
5488
  for (const read of hostReads) read();
5410
5489
  saveSettings(next);
5411
5490
  closeMenu();
@@ -5912,14 +5991,13 @@ ${c.text}` })));
5912
5991
  const price = priceOf(info);
5913
5992
  const pct = Math.round(c.used / c.window * 100);
5914
5993
  const u = a.usage;
5915
- const comp2 = agentOpts.compaction;
5916
5994
  const lines = [
5917
5995
  `- ${t.sModel}: ${a.model || (await loadModels()).find((m) => m.is_default)?.id || t.sDefault}`,
5918
5996
  `- ${t.context}: ${pct < 1 && c.used ? "<1" : pct}% \xB7 ${fmtTokens(c.used)} / ${fmtTokens(c.window)} tokens \xB7 ${t.sMaxTokens} ${fmtTokens(lim.output)}`,
5919
5997
  price ? `- ${t.sPrice}: ${price}` : "",
5920
5998
  `- ${t.messagesLabel}: ${a.messages.length}`,
5921
5999
  u.calls ? `- ${fill(t.usageLine.replace("{cost}", fmtCost(u.total_cost, info?.price?.currency)).replace("{tokens}", fmtTokens(u.prompt_tokens + u.completion_tokens)).replace("{calls}", String(u.calls)))}` : "",
5922
- comp2 === false ? "" : `- ${t.autoCompact}: ${t.autoCompactAt.replace("{n}", fmtTokens(Math.min(16384, Math.floor(c.window * 0.2))))}`,
6000
+ `- ${compactLine(a, c.window)}`,
5923
6001
  a.workspace ? `- ${t.directory}: \`${a.workspace.id}\`` : ""
5924
6002
  ].filter(Boolean);
5925
6003
  addNote(t.context, lines.join("\n"));
@@ -5986,6 +6064,10 @@ ${c.text}` })));
5986
6064
  });
5987
6065
  };
5988
6066
  const cap2 = (x) => x.charAt(0).toUpperCase() + x.slice(1);
6067
+ const compactLine = (a, window2) => {
6068
+ const c = a.compactionFor(window2);
6069
+ return `${c.summarize ? t.autoCompact : t.autoTrim}: ${t.autoCompactAt.replace("{n}", fmtTokens(c.reserveTokens))}`;
6070
+ };
5989
6071
  const pctOf = (used, window2) => {
5990
6072
  const p = used / window2;
5991
6073
  return used && p < 0.01 ? "<1%" : `${Math.round(Math.min(1, p) * 100)}%`;
@@ -6008,7 +6090,7 @@ ${c.text}` })));
6008
6090
  grid.append(cell);
6009
6091
  }
6010
6092
  panel2.replaceChildren(head2, bar2, sub, grid);
6011
- if (agentOpts.compaction !== false) panel2.append(h("div", "ra-unote", `${t.autoCompact}: ${t.autoCompactAt.replace("{n}", fmtTokens(Math.min(16384, Math.floor(c.window * 0.2))))}`));
6093
+ panel2.append(h("div", "ra-unote", compactLine(a, c.window)));
6012
6094
  const foot = h("div", "ra-mf");
6013
6095
  const compactBtn = h("button", "ra-btn xs ghost");
6014
6096
  compactBtn.type = "button";
package/docs/agent.md CHANGED
@@ -164,6 +164,8 @@ createAgent(provider, {
164
164
  await agent.compact("keep every API name we discussed"); // now, with a focus
165
165
  ```
166
166
 
167
+ A user can change compaction mid-conversation, from the next turn on: `agent.configure({ compaction: { summarize, reserveTokens, keepRecentTokens } })`. `summarize: false` only shortens and drops (as `compaction: false`), `true` summarises again (with your function, if you gave one); a threshold named without a number (`reserveTokens: undefined`) goes back to the default. `agent.settings.compaction` reads the choice back, and `agent.compactionFor(window)` says what it comes to for a window: the thresholds are capped at 20 % / 40 % of it. The chat UI's settings have a *Context* tab for this.
168
+
167
169
  ### When a request does not fit
168
170
 
169
171
  A provider may refuse a request as larger than the model takes, in its own words (`isContextOverflow(err)` recognises them; a status of 413 counts too). The agent then makes it smaller by itself and sends it again: it summarises what is older than the latest turn and trims to 70% of the window, then, if refused again, to 40%, the big results of the latest turn included. A refusal that states the real limit corrects the window for the rest of the run. A request more than twice a window the catalogue vouches for is treated as refused without being sent.
@@ -247,4 +249,4 @@ Both live in the workspace's directory: shared by every conversation that uses t
247
249
  | `webTools` | `false` | RunApps (SDK 0.19+): the platform's `web_search` and `web_fetch` beside your tools, billed per call (see [Tools](tools.md#web-search-and-reading-pages)). A function is read every turn. |
248
250
  | `serverTools` | | Deprecated, use `webTools`: the gateway runs the tools inside the chat call, for an agent with no tools of its own. |
249
251
 
250
- Change settings on a live agent with `agent.configure({ model, maxTurns, maxTokens, permissions, reasoningEffort, webTools })`; `agent.settings` reads them back, `agent.webTools` says whether the web tools are on and `agent.webToolsAvailable` whether the provider has them.
252
+ Change settings on a live agent with `agent.configure({ model, maxTurns, maxTokens, permissions, reasoningEffort, webTools, compaction })`; `agent.settings` reads them back, `agent.webTools` says whether the web tools are on and `agent.webToolsAvailable` whether the provider has them.
package/docs/chat-ui.md CHANGED
@@ -31,7 +31,7 @@
31
31
  - **Files** — the header's *Files* button opens the directory: a tree, an editor (⌘S, word wrap, Markdown preview), picture and PDF previews, upload, new file, download (folders as zip). File paths in replies open there. Live: changes by the agent show at once.
32
32
  - **Skills** — the *Skills* button lists the skills (with a count), uploads zips, removes the user's own.
33
33
  - **Chats** — the conversation list (the open one first), new chat, delete. Conversations keep running when you switch away (up to three in the background).
34
- - **Settings** — the gear: model (with context and output limits, and which models see pictures), thinking level when the model has one, max turns, max output, tool permissions. Kept per app in the browser and applied to every conversation; only what differs from the app's defaults is kept, and a saved model the catalogue no longer lists is dropped (the default applies again).
34
+ - **Settings** — the gear: model (with context and output limits, and which models see pictures), thinking level when the model has one, max turns, max output, tool permissions; and a *Context* tab for compaction — summarise older turns or only trim, how many tokens left starts it, how much of the newest stays word for word (each "Default" or a number, with what that comes to for the chosen model). Kept per app in the browser and applied to every conversation; only what differs from the app's defaults is kept, and a saved model the catalogue no longer lists is dropped (the default applies again).
35
35
  - **Reply actions** — hover a reply: copy its answer, *answer again* (rewinds to its question, with the same restore choices, and sends it again), delete the question and its answer; on the right what the reply cost (its `runUsage`, in the model's `price.currency`), the tokens and calls in its tooltip.
36
36
  - **Rewind** — hover a user message: when it was sent, copy, *rewind to here* (the conversation after it is dropped, the message goes back into the composer, and the directory's files can be restored to that moment).
37
37
  - **How a run ended** — *Stopped.*, the turn limit with *Continue*, an error with *Retry*, a request too large for the model with what solves it (below); kept across reloads until the next run.
@@ -211,7 +211,7 @@ chat.updateComposerAction("analyze", { disabled: true, label: "Backtest running
211
211
 
212
212
  `iconOnly: true` draws only the icon, with the label as its tooltip.
213
213
 
214
- `settingsTabs` adds tabs of yours to the gear's panel, after the chat's own "Model" tab, so a host needs no second settings button and the panel stays short. In a tab the chat draws a `toggle` or a `select`, reads it back when the user presses Apply (calling `onChange` only for a value that changed) and puts back `default` on Reset; you keep the value and act on it. An element goes in as it is. The panel reopens on the tab last shown.
214
+ `settingsTabs` adds tabs of yours to the gear's panel, after the chat's own "Model" and "Context" tabs, so a host needs no second settings button and the panel stays short. In a tab the chat draws a `toggle` or a `select`, reads it back when the user presses Apply (calling `onChange` only for a value that changed) and puts back `default` on Reset; you keep the value and act on it. An element goes in as it is. The panel reopens on the tab last shown.
215
215
 
216
216
  ```js
217
217
  renderChat(host, {
package/docs/reference.md CHANGED
@@ -44,7 +44,8 @@ Three entry points:
44
44
  | `queued`, `dequeue(message)`, `clearQueue()` | What waits. |
45
45
  | `on(event, handler)` / `on("*", (name, event) => …)` | Subscribe; returns an unsubscribe function. |
46
46
  | `ready()` | Resolves once a saved session is loaded. |
47
- | `configure(patch)`, `settings` | `model`, `maxTurns`, `maxTokens`, `permissions`, `reasoningEffort`. |
47
+ | `configure(patch)`, `settings` | `model`, `maxTurns`, `maxTokens`, `permissions`, `reasoningEffort`, `webTools`, `compaction` (`{ summarize, reserveTokens, keepRecentTokens }`). |
48
+ | `compactionFor(window)` | Compaction as it applies to a window of that many tokens: `{ summarize, reserveTokens, keepRecentTokens }`, thresholds capped. |
48
49
  | `limits()` → `{ input, output }`, `context()` → `{ used, window }` | Model limits, context use. |
49
50
  | `useSkill(name)` | Load a skill for the next prompt. |
50
51
  | `systemPrompt()` | The system prompt as it would be sent. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runappsai/agent",
3
- "version": "0.1.10",
3
+ "version": "0.1.11",
4
4
  "type": "module",
5
5
  "description": "Agent harness: the model ↔ tool loop with a workspace, skills, sessions, compaction, a sandbox and a chat UI. Bring any OpenAI-compatible model provider (RunApps included); no runtime dependencies.",
6
6
  "license": "MIT",