@runappsai/agent 0.1.3 → 0.1.5

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.d.ts CHANGED
@@ -136,6 +136,8 @@ export interface ChatOptions extends Omit<AgentOptions, "workspace"> {
136
136
  * input and Tab takes it. Off by default.
137
137
  */
138
138
  nextPrompt?: boolean;
139
+ /** Opens your own tool settings: offered when the connected tools alone leave no room for a request. */
140
+ toolSettings?: () => void;
139
141
  /** Buttons of your own for the header, placed before the settings gear. */
140
142
  headerActions?: HTMLElement[];
141
143
  /**
package/dist/chat.js CHANGED
@@ -32,7 +32,9 @@ const STRINGS = {
32
32
  enter: "to send", newline: "new line", hintIdle: "↵ {enter} · ⇧↵ {newline}", hintNext: "Tab to use the suggestion · ↵ {enter}", hintBusy: "↵ steer · {mod}↵ follow-up · ⇧↵ {newline}", empty: "Start a conversation", history: "Chats", newChat: "New chat", clearChat: "Clear", confirmClear: "Clear this conversation? Its messages are removed; the files stay.", noSessions: "No other conversations yet", notSaved: "not saved yet",
33
33
  compacted: "Context compacted", trimmed: "Earlier conversation trimmed to fit the context", allow: "Allow", decline: "Decline", cancel: "Cancel", submit: "Submit", ok: "OK",
34
34
  other: "Other…", typeAnswer: "Type your answer", args: "Arguments", result: "Result", error: "Error", declined: "declined", blocked: "blocked", skipped: "skipped",
35
- open: "Open in editor", stopped: "Stopped.", maxTurns: "Paused at the turn limit ({n})", retry: "Retry", messages: "messages", skill: "Skill", template: "Template",
35
+ open: "Open in editor", stopped: "Stopped.", maxTurns: "Paused at the turn limit ({n})", retry: "Retry", messages: "messages",
36
+ ovAttachments: "The attachments on this message are too large for the model.", ovMessage: "This message is too long for the model.", ovHistory: "This conversation has grown too long for the model.", ovTools: "The connected tools take up too much of the model's context.", ovModel: "This request does not fit the current model.",
37
+ ovDropFiles: "Resend without attachments", ovEdit: "Edit the message", ovCompact: "Compact and continue", ovNew: "Continue in a new chat", ovToolSettings: "Tool settings", ovUseModel: "Retry with {name}", ovNoText: "The message had only attachments: type what you want to ask.", ovNoSummary: "Could not summarise the conversation; the new chat starts without it.", skill: "Skill", template: "Template",
36
38
  delete: "Delete", deleteAll: "Delete all", confirmDelete: "Delete this conversation and its files?", confirmDeleteAll: "Delete every conversation, this one included, and their files?", untitled: "New conversation",
37
39
  attach: "Attach files", drop: "Drop files to attach", tooLarge: "is too large (max 20 MB)", remove: "Remove",
38
40
  toolsRunning: "Running", toolsDone: "Ran {n} tool calls", toolsDone1: "Ran 1 tool call", toolsFailed: "{n} failed",
@@ -69,7 +71,9 @@ const STRINGS = {
69
71
  enter: "发送", newline: "换行", hintIdle: "↵ {enter} · ⇧↵ {newline}", hintNext: "Tab 使用建议 · ↵ {enter}", hintBusy: "↵ 插入 · {mod}↵ 排队 · ⇧↵ {newline}", empty: "开始对话", history: "会话", newChat: "新对话", clearChat: "清除", confirmClear: "清除这次对话?消息会被删除,文件保留。", noSessions: "还没有其它对话", notSaved: "尚未保存",
70
72
  compacted: "上下文已压缩", trimmed: "较早的对话已裁剪以适应上下文", allow: "允许", decline: "拒绝", cancel: "取消", submit: "提交", ok: "确定",
71
73
  other: "其他…", typeAnswer: "请输入", args: "参数", result: "结果", error: "错误", declined: "已拒绝", blocked: "已拦截", skipped: "已跳过",
72
- open: "在编辑器中打开", stopped: "已停止。", maxTurns: "已达最大轮数 {n},暂停", retry: "重试", messages: "条消息", skill: "Skill", template: "模板",
74
+ open: "在编辑器中打开", stopped: "已停止。", maxTurns: "已达最大轮数 {n},暂停", retry: "重试", messages: "条消息",
75
+ ovAttachments: "这条消息的附件太大,超出了模型能处理的长度。", ovMessage: "这条消息太长,超出了模型能处理的长度。", ovHistory: "这段对话太长,模型放不下了。", ovTools: "已连接的工具太多,占满了模型的上下文。", ovModel: "当前模型放不下这次请求。",
76
+ ovDropFiles: "去掉附件后重发", ovEdit: "修改这条消息", ovCompact: "压缩后继续", ovNew: "开新对话继续", ovToolSettings: "打开工具设置", ovUseModel: "换用 {name} 重试", ovNoText: "这条消息只有附件,请输入想问的内容。", ovNoSummary: "这段对话没能生成摘要,新对话不会带上之前的内容。", skill: "Skill", template: "模板",
73
77
  delete: "删除", deleteAll: "全部删除", confirmDelete: "删除这个对话和它的文件?", confirmDeleteAll: "删除所有对话(包括当前这个)和它们的文件?", untitled: "新对话",
74
78
  attach: "添加附件", drop: "松开即可添加附件", tooLarge: "太大了(最大 20 MB)", remove: "移除",
75
79
  toolsRunning: "正在执行", toolsDone: "执行了 {n} 个工具调用", toolsDone1: "执行了 1 个工具调用", toolsFailed: "{n} 个失败",
@@ -389,6 +393,10 @@ const CSS = tokenCSS() + `
389
393
  .ra-card .ra-md{font-size:13px}
390
394
  .ra-err{border:1px solid var(--ra-red);background:var(--ra-red-subtle);border-radius:6px;padding:8px;font-size:14px;color:var(--ra-red);white-space:pre-wrap;word-break:break-word}
391
395
  .ra-err .ra-btn{margin-top:6px}
396
+ .ra-chat .ra-over{border-color:var(--ra-warn-border);background:var(--ra-warn-bg);color:var(--ra-warn-fg)}
397
+ .ra-over .ra-acts{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}
398
+ .ra-chat .ra-over .ra-btn{margin:0;border-color:var(--ra-warn-border);background:transparent;color:inherit}
399
+ .ra-chat .ra-over .ra-btn:hover{background:var(--ra-warn-border)}
392
400
  .ra-ask{flex-shrink:0;max-height:45%;overflow-y:auto}
393
401
  .ra-ask .ra-col{display:flex;flex-direction:column;gap:8px;padding-top:8px;padding-bottom:8px}
394
402
  .ra-q{border:1px solid var(--ra-accent-muted);border-radius:8px;padding:12px;background:var(--ra-subtle);display:flex;flex-direction:column;gap:10px}
@@ -988,7 +996,7 @@ export function renderChat(target, opts) {
988
996
  injectStyles();
989
997
  const lang = pickLocale(opts.locale);
990
998
  const t = STRINGS[lang];
991
- const { client: clientOpt, provider: providerOpt, agent: givenAgent, workspace: wsOpt, resume: resumeOpt, palette: paletteOpt, vars: varsOpt, className, debug: debugOpt, settings: _settingsOpt, skillsMenu, title, placeholder, emptyState, suggestions, sessions, locale: _l, theme, showUsage, attachments: attachOpt, uploadsDir: uploadsOpt, onOpenFile, onLink, onSession, files: filesOpt, headerActions, headerEnd, settingsTabs, composerTop, composerActions, permissionsSetting, rewindState, nextPrompt, ...agentOpts } = opts;
999
+ const { toolSettings, client: clientOpt, provider: providerOpt, agent: givenAgent, workspace: wsOpt, resume: resumeOpt, palette: paletteOpt, vars: varsOpt, className, debug: debugOpt, settings: _settingsOpt, skillsMenu, title, placeholder, emptyState, suggestions, sessions, locale: _l, theme, showUsage, attachments: attachOpt, uploadsDir: uploadsOpt, onOpenFile, onLink, onSession, files: filesOpt, headerActions, headerEnd, settingsTabs, composerTop, composerActions, permissionsSetting, rewindState, nextPrompt, ...agentOpts } = opts;
992
1000
  const uploadsDir = "/" + (uploadsOpt ?? "/uploads").replace(/^\/+|\/+$/g, "");
993
1001
  const provider = providerOpt ? toProvider(providerOpt) : clientOpt ? toProvider(clientOpt) : givenAgent?.provider ?? null;
994
1002
  const project = provider?.name ?? agentOpts.appName ?? "app";
@@ -1067,6 +1075,9 @@ export function renderChat(target, opts) {
1067
1075
  clearBtn.type = "button";
1068
1076
  clearBtn.innerHTML = I.eraser() + `<span>${escapeHTML(t.clearChat)}</span>`;
1069
1077
  clearBtn.style.display = "none";
1078
+ // One conversation, no list of them (sessions: false, or the host's own agent): Clear stands in for New chat, and shows only when there is something to clear.
1079
+ let oneChat = false;
1080
+ const syncClear = () => { clearBtn.style.display = oneChat && agent?.messages.length ? "" : "none"; };
1070
1081
  // How full the context is, as a ring; a click opens the numbers and the spending.
1071
1082
  const useBtn = h("button", "ra-btn ghost ra-usebtn");
1072
1083
  useBtn.type = "button";
@@ -2388,6 +2399,7 @@ export function renderChat(target, opts) {
2388
2399
  flush(true);
2389
2400
  if (!messages.length)
2390
2401
  showEmpty();
2402
+ syncClear();
2391
2403
  list.scrollToBottom();
2392
2404
  };
2393
2405
  /* --- composer --- */
@@ -3400,6 +3412,201 @@ export function renderChat(target, opts) {
3400
3412
  }
3401
3413
  return out.join("\n");
3402
3414
  };
3415
+ const useModel = (m) => {
3416
+ const next = { ...userSettings };
3417
+ if (m.is_default && !agentOpts.model)
3418
+ delete next.model;
3419
+ else
3420
+ next.model = m.id;
3421
+ // A thinking level the new model does not have would be refused.
3422
+ const eff = effortOf(m);
3423
+ if (next.reasoningEffort && !eff?.levels.includes(next.reasoningEffort))
3424
+ delete next.reasoningEffort;
3425
+ saveSettings(next);
3426
+ };
3427
+ /** Summarises older turns now; true when a summary replaced them. */
3428
+ const compactNow = async (focus) => {
3429
+ const a = agent;
3430
+ if (a.busy) {
3431
+ ui.notify(t.busyCmd, "warning");
3432
+ return false;
3433
+ }
3434
+ compacting = true;
3435
+ try {
3436
+ // The compaction events show it running and draw the summary; Stop aborts it.
3437
+ const done = await a.compact(focus);
3438
+ if (!done)
3439
+ ui.notify(t.nothingToCompact);
3440
+ return done;
3441
+ }
3442
+ catch (err) {
3443
+ if (!/abort/i.test(err.message ?? "") && err.name !== "AbortError")
3444
+ throw err;
3445
+ ui.notify(t.stopped);
3446
+ return false;
3447
+ }
3448
+ finally {
3449
+ compacting = false;
3450
+ // The agent lets go of the compaction a tick after it resolves (and then starts any message queued meanwhile).
3451
+ if (agent === a) {
3452
+ closeActive();
3453
+ showUsage_(a);
3454
+ setTimeout(() => { if (agent === a && !a.busy)
3455
+ setBusy(false); }, 0);
3456
+ }
3457
+ }
3458
+ };
3459
+ /** The latest message the user wrote, and its words without what was attached. */
3460
+ const latestAsked = (a) => {
3461
+ const list = a.messages;
3462
+ let index = list.length - 1;
3463
+ while (index >= 0 && !(list[index].role === "user" && summaryOf(list[index]) === null))
3464
+ index--;
3465
+ const msg = list[index];
3466
+ if (!msg)
3467
+ return null;
3468
+ const typed = msg.typed ?? textOfContent(msg.content).replace(/\s*\[attachments\][\s\S]*$/, "").replace(/(^|\n)\[context\] [\s\S]*$/, "");
3469
+ const files = Array.isArray(msg.content) ? msg.content.length > 1 : /(^|\n)\[attachments\]/.test(String(msg.content ?? ""));
3470
+ return { index, msg, text: typed.trim(), files };
3471
+ };
3472
+ /** The smallest model that can take the request, else the largest that is larger than this one. */
3473
+ const roomierModel = async (a, used, window) => {
3474
+ const current = a.model || (await a.modelInfo())?.id;
3475
+ const asked = latestAsked(a)?.msg.content;
3476
+ const pictures = Array.isArray(asked) && asked.some((p) => p.type === "image_url");
3477
+ const larger = (await loadModels())
3478
+ .filter((m) => m.id !== current && (m.max_input_tokens ?? 0) > window && (!pictures || modelAccepts(m, "image") !== false))
3479
+ .sort((x, y) => x.max_input_tokens - y.max_input_tokens);
3480
+ return larger.find((m) => m.max_input_tokens >= used * 1.2) ?? larger[larger.length - 1];
3481
+ };
3482
+ /** Rewinds past the latest message, to send it again or change it. */
3483
+ const takeBack = async (a) => {
3484
+ const asked = latestAsked(a);
3485
+ if (!asked)
3486
+ return null;
3487
+ await a.rewind(asked.index);
3488
+ if (agent === a) {
3489
+ renderHistory(a.messages);
3490
+ showUsage_(a);
3491
+ }
3492
+ return asked;
3493
+ };
3494
+ const sendText = async (a, text) => {
3495
+ if (agent === a && !a.busy)
3496
+ awaitingRow = addUser(text);
3497
+ await a.prompt(text);
3498
+ };
3499
+ /** Carries on in a new conversation that starts from a summary of this one; the latest message goes along. */
3500
+ const continueInNew = async (a) => {
3501
+ const asked = latestAsked(a);
3502
+ compacting = true;
3503
+ let summary = null;
3504
+ try {
3505
+ summary = await a.summarize(asked?.msg);
3506
+ }
3507
+ finally {
3508
+ compacting = false;
3509
+ closeActive();
3510
+ }
3511
+ await new Promise((r) => setTimeout(r, 0));
3512
+ await (oneChat ? clearConversation() : newSession().then(() => undefined));
3513
+ const b = agent;
3514
+ if (summary) {
3515
+ await b.seed(summary);
3516
+ renderHistory(b.messages);
3517
+ showUsage_(b);
3518
+ }
3519
+ else if (a.messages.length > 1)
3520
+ ui.notify(t.ovNoSummary, "warning");
3521
+ setBusy(false);
3522
+ if (!asked)
3523
+ return;
3524
+ // What was attached may be what did not fit: it goes back into the composer, for the user to decide.
3525
+ if (asked.files) {
3526
+ await reattach(asked.msg);
3527
+ ta.value = asked.text;
3528
+ syncSend();
3529
+ ta.focus();
3530
+ }
3531
+ else if (asked.text)
3532
+ await sendText(b, asked.text);
3533
+ };
3534
+ /** A request that does not fit the model: says why in the chat's language and offers what solves it, one click each. */
3535
+ const addOverflow = async (a, ov) => {
3536
+ const go = async () => { await new Promise((r) => setTimeout(r, 0)); await a.continue(); };
3537
+ const before = a.messages.slice(0, latestAsked(a)?.index ?? 0);
3538
+ // Turns not yet in a summary can still be compacted; a new chat helps only when there is something to leave behind.
3539
+ const older = before.some((m) => summaryOf(m) === null);
3540
+ const actions = [];
3541
+ const editMessage = { label: t.ovEdit, run: async () => { const asked = await takeBack(a); if (asked) {
3542
+ ta.value = asked.text;
3543
+ syncSend();
3544
+ ta.focus();
3545
+ } } };
3546
+ const compact = { label: t.ovCompact, run: async () => { await compactNow(); await go(); } };
3547
+ const fresh = { label: t.ovNew, run: () => continueInNew(a) };
3548
+ if (ov.cause === "attachments")
3549
+ actions.push({ label: t.ovDropFiles, run: async () => {
3550
+ const asked = await takeBack(a);
3551
+ if (!asked)
3552
+ return;
3553
+ if (asked.text)
3554
+ await sendText(a, asked.text);
3555
+ else {
3556
+ ui.notify(t.ovNoText, "warning");
3557
+ ta.focus();
3558
+ }
3559
+ } });
3560
+ else if (ov.cause === "message")
3561
+ actions.push(editMessage);
3562
+ else if (ov.cause === "tools") {
3563
+ if (toolSettings)
3564
+ actions.push({ label: t.ovToolSettings, run: async () => toolSettings() });
3565
+ }
3566
+ else if (ov.cause === "history") {
3567
+ if (older)
3568
+ actions.push(compact);
3569
+ actions.push(fresh);
3570
+ }
3571
+ else {
3572
+ if (older)
3573
+ actions.push(compact);
3574
+ if (before.length)
3575
+ actions.push(fresh);
3576
+ actions.push(editMessage);
3577
+ }
3578
+ const roomier = await roomierModel(a, ov.used, ov.window).catch(() => undefined);
3579
+ if (roomier)
3580
+ actions.push({ label: t.ovUseModel.replace("{name}", roomier.id), run: async () => { useModel(roomier); await go(); } });
3581
+ if (agent !== a)
3582
+ return;
3583
+ const text = { attachments: t.ovAttachments, message: t.ovMessage, tools: t.ovTools, history: t.ovHistory, model: t.ovModel }[ov.cause];
3584
+ const row = {
3585
+ render: () => {
3586
+ const card = h("div", "ra-err ra-over", text);
3587
+ card.setAttribute("role", "alert");
3588
+ const bar = h("div", "ra-acts");
3589
+ for (const act of actions) {
3590
+ const b = h("button", "ra-btn xs", act.label);
3591
+ b.type = "button";
3592
+ b.addEventListener("click", () => {
3593
+ if (a.busy) {
3594
+ ui.notify(t.busyCmd, "warning");
3595
+ return;
3596
+ }
3597
+ list.remove(row);
3598
+ void act.run().catch((err) => { addError(err.message); setBusy(false); });
3599
+ });
3600
+ bar.append(b);
3601
+ }
3602
+ if (actions.length)
3603
+ card.append(bar);
3604
+ return card;
3605
+ },
3606
+ };
3607
+ addRow(row);
3608
+ list.schedule();
3609
+ };
3403
3610
  const pickModel = (models, q) => {
3404
3611
  const l = q.toLowerCase();
3405
3612
  const exact = models.find((m) => m.id.toLowerCase() === l);
@@ -3413,36 +3620,9 @@ export function renderChat(target, opts) {
3413
3620
  const lines = builtinCommands().map((c) => `- \`/${c.name}${c.args ? ` ${c.args}` : ""}\` — ${c.description}`);
3414
3621
  addNote(t.cmdsTitle, [...lines, "", t.cmdsMore].join("\n"));
3415
3622
  } },
3416
- { name: "new", aliases: ["clear"], run: () => { closeMenu(); return clearBtn.style.display === "none" ? newSession().then(() => undefined) : clearConversation(); } },
3623
+ { name: "new", aliases: ["clear"], run: () => { closeMenu(); return oneChat ? clearConversation() : newSession().then(() => undefined); } },
3417
3624
  { name: "resume", run: () => openMenu() },
3418
- { name: "compact", args: t.cmdArgs.compact, run: async (focus) => {
3419
- const a = agent;
3420
- if (a.busy) {
3421
- ui.notify(t.busyCmd, "warning");
3422
- return;
3423
- }
3424
- compacting = true;
3425
- try {
3426
- // The compaction events show it running and draw the summary; Stop aborts it.
3427
- if (!(await a.compact(focus)))
3428
- ui.notify(t.nothingToCompact);
3429
- }
3430
- catch (err) {
3431
- if (!/abort/i.test(err.message ?? "") && err.name !== "AbortError")
3432
- throw err;
3433
- ui.notify(t.stopped);
3434
- }
3435
- finally {
3436
- compacting = false;
3437
- // The agent lets go of the compaction a tick after it resolves (and then starts any message queued meanwhile).
3438
- if (agent === a) {
3439
- closeActive();
3440
- showUsage_(a);
3441
- setTimeout(() => { if (agent === a && !a.busy)
3442
- setBusy(false); }, 0);
3443
- }
3444
- }
3445
- } },
3625
+ { name: "compact", args: t.cmdArgs.compact, run: async (focus) => { await compactNow(focus); } },
3446
3626
  { name: "continue", run: async () => {
3447
3627
  if (agent.busy) {
3448
3628
  ui.notify(t.busyCmd, "warning");
@@ -3462,16 +3642,7 @@ export function renderChat(target, opts) {
3462
3642
  ui.notify(t.unknownModel.replace("{name}", q), "warning");
3463
3643
  return;
3464
3644
  }
3465
- const next = { ...userSettings };
3466
- if (m.is_default && !agentOpts.model)
3467
- delete next.model;
3468
- else
3469
- next.model = m.id;
3470
- // A thinking level the new model does not have would be refused.
3471
- const eff = effortOf(m);
3472
- if (next.reasoningEffort && !eff?.levels.includes(next.reasoningEffort))
3473
- delete next.reasoningEffort;
3474
- saveSettings(next);
3645
+ useModel(m);
3475
3646
  ui.notify(t.modelSet.replace("{name}", m.id));
3476
3647
  } },
3477
3648
  { name: "effort", args: t.cmdArgs.effort, run: async (q) => {
@@ -3536,8 +3707,8 @@ export function renderChat(target, opts) {
3536
3707
  ];
3537
3708
  /** The built-ins this chat offers now (the files, settings and debug ones only where their button shows). */
3538
3709
  const builtinCommands = () => builtins
3539
- .filter((b) => (b.name !== "files" || (!!agent?.workspace && filesOpt !== false)) && (b.name !== "settings" || hasSettings) && (b.name !== "debug" || debugOn) && (b.name !== "resume" || (!givenAgent && !!agent?.workspace && clearBtn.style.display === "none")))
3540
- .map((b) => ({ name: b.name, description: b.name === "new" && clearBtn.style.display !== "none" ? t.confirmClear.split(/[??]/)[0] : t.cmd[b.name] ?? "", kind: t.command, args: b.args, builtin: true }));
3710
+ .filter((b) => (b.name !== "files" || (!!agent?.workspace && filesOpt !== false)) && (b.name !== "settings" || hasSettings) && (b.name !== "debug" || debugOn) && (b.name !== "resume" || (!givenAgent && !!agent?.workspace && !oneChat)))
3711
+ .map((b) => ({ name: b.name, description: b.name === "new" && oneChat ? t.confirmClear.split(/[??]/)[0] : t.cmd[b.name] ?? "", kind: t.command, args: b.args, builtin: true }));
3541
3712
  /** `/name [arg]` naming a built-in: run it here (nothing goes to the model). */
3542
3713
  const runBuiltin = (text) => {
3543
3714
  const m = /^\/(\S+)(?:\s+([\s\S]*))?$/.exec(text);
@@ -3657,7 +3828,9 @@ export function renderChat(target, opts) {
3657
3828
  catch (e) {
3658
3829
  ui.notify(e.message, "error");
3659
3830
  } };
3660
- if (end.reason === "error")
3831
+ if (end.overflow)
3832
+ void addOverflow(a, end.overflow);
3833
+ else if (end.reason === "error")
3661
3834
  addError(end.error ?? t.error, a.messages.length ? go : undefined);
3662
3835
  else if (end.reason === "max_turns")
3663
3836
  addWarn(t.maxTurns.replace("{n}", String(a.settings.maxTurns)), { label: t.continueRun, onClick: go }, t.maxTurnsHint);
@@ -3693,7 +3866,8 @@ export function renderChat(target, opts) {
3693
3866
  // A host's own agent has no sessions to switch between: the chat cannot make a new one.
3694
3867
  const hasSessions = !givenAgent && (sessions ?? !!a.workspace);
3695
3868
  histBtn.style.display = newBtn.style.display = hasSessions && a.workspace ? "" : "none";
3696
- clearBtn.style.display = hasSessions && a.workspace ? "none" : "";
3869
+ oneChat = !(hasSessions && a.workspace);
3870
+ syncClear();
3697
3871
  filesBtn.style.display = a.workspace && filesOpt !== false ? "" : "none";
3698
3872
  skillsBtn.style.display = a.workspace && skillsMenu !== false ? "" : "none";
3699
3873
  panel.setWorkspace(a.workspace);
@@ -3708,6 +3882,7 @@ export function renderChat(target, opts) {
3708
3882
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
3709
3883
  const on = (name, fn) => unsub.push(a.on(name, fn));
3710
3884
  on("run_start", (ev) => {
3885
+ syncClear();
3711
3886
  // A prompt sent from here was drawn then (awaitingRow); one from a queued follow-up or the host is drawn now; continue() has none.
3712
3887
  if (ev.message) {
3713
3888
  if (awaitingRow && !awaitingRow.msg) {
@@ -3878,7 +4053,7 @@ export function renderChat(target, opts) {
3878
4053
  list.schedule();
3879
4054
  }
3880
4055
  ui.cancelAll();
3881
- addEnd(a, r.reason === "done" ? null : { reason: r.reason, error: r.error?.message, at: Date.now() });
4056
+ addEnd(a, r.reason === "done" ? null : a.lastEnd ?? { reason: r.reason, error: r.error?.message, at: Date.now() });
3882
4057
  setBusy(false);
3883
4058
  showUsage_(a);
3884
4059
  void refreshCommands();
package/dist/context.d.ts CHANGED
@@ -39,6 +39,7 @@ export declare function fitBudget(messages: ChatMessage[], opts: {
39
39
  keepTurns: number;
40
40
  system?: string;
41
41
  elideAbove?: number;
42
+ keepResults?: number;
42
43
  }): FitResult;
43
44
  /** Splits at each user message that is not a tool result. */
44
45
  export declare function groupTurns(messages: ChatMessage[]): ChatMessage[][];
package/dist/context.js CHANGED
@@ -132,7 +132,7 @@ export function fitBudget(messages, opts) {
132
132
  if (over() && turns.length === 1) {
133
133
  const turn = turns[0];
134
134
  const toolIdx = turn.map((m, i) => (m.role === "tool" ? i : -1)).filter((i) => i >= 0);
135
- for (const i of toolIdx.slice(0, Math.max(0, toolIdx.length - 3))) {
135
+ for (const i of toolIdx.slice(0, Math.max(0, toolIdx.length - (opts.keepResults ?? 3)))) {
136
136
  if (!over())
137
137
  break;
138
138
  const m = turn[i];