@runappsai/agent 0.1.3 → 0.1.4

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";
@@ -3400,6 +3408,201 @@ export function renderChat(target, opts) {
3400
3408
  }
3401
3409
  return out.join("\n");
3402
3410
  };
3411
+ const useModel = (m) => {
3412
+ const next = { ...userSettings };
3413
+ if (m.is_default && !agentOpts.model)
3414
+ delete next.model;
3415
+ else
3416
+ next.model = m.id;
3417
+ // A thinking level the new model does not have would be refused.
3418
+ const eff = effortOf(m);
3419
+ if (next.reasoningEffort && !eff?.levels.includes(next.reasoningEffort))
3420
+ delete next.reasoningEffort;
3421
+ saveSettings(next);
3422
+ };
3423
+ /** Summarises older turns now; true when a summary replaced them. */
3424
+ const compactNow = async (focus) => {
3425
+ const a = agent;
3426
+ if (a.busy) {
3427
+ ui.notify(t.busyCmd, "warning");
3428
+ return false;
3429
+ }
3430
+ compacting = true;
3431
+ try {
3432
+ // The compaction events show it running and draw the summary; Stop aborts it.
3433
+ const done = await a.compact(focus);
3434
+ if (!done)
3435
+ ui.notify(t.nothingToCompact);
3436
+ return done;
3437
+ }
3438
+ catch (err) {
3439
+ if (!/abort/i.test(err.message ?? "") && err.name !== "AbortError")
3440
+ throw err;
3441
+ ui.notify(t.stopped);
3442
+ return false;
3443
+ }
3444
+ finally {
3445
+ compacting = false;
3446
+ // The agent lets go of the compaction a tick after it resolves (and then starts any message queued meanwhile).
3447
+ if (agent === a) {
3448
+ closeActive();
3449
+ showUsage_(a);
3450
+ setTimeout(() => { if (agent === a && !a.busy)
3451
+ setBusy(false); }, 0);
3452
+ }
3453
+ }
3454
+ };
3455
+ /** The latest message the user wrote, and its words without what was attached. */
3456
+ const latestAsked = (a) => {
3457
+ const list = a.messages;
3458
+ let index = list.length - 1;
3459
+ while (index >= 0 && !(list[index].role === "user" && summaryOf(list[index]) === null))
3460
+ index--;
3461
+ const msg = list[index];
3462
+ if (!msg)
3463
+ return null;
3464
+ const typed = msg.typed ?? textOfContent(msg.content).replace(/\s*\[attachments\][\s\S]*$/, "").replace(/(^|\n)\[context\] [\s\S]*$/, "");
3465
+ const files = Array.isArray(msg.content) ? msg.content.length > 1 : /(^|\n)\[attachments\]/.test(String(msg.content ?? ""));
3466
+ return { index, msg, text: typed.trim(), files };
3467
+ };
3468
+ /** The smallest model that can take the request, else the largest that is larger than this one. */
3469
+ const roomierModel = async (a, used, window) => {
3470
+ const current = a.model || (await a.modelInfo())?.id;
3471
+ const asked = latestAsked(a)?.msg.content;
3472
+ const pictures = Array.isArray(asked) && asked.some((p) => p.type === "image_url");
3473
+ const larger = (await loadModels())
3474
+ .filter((m) => m.id !== current && (m.max_input_tokens ?? 0) > window && (!pictures || modelAccepts(m, "image") !== false))
3475
+ .sort((x, y) => x.max_input_tokens - y.max_input_tokens);
3476
+ return larger.find((m) => m.max_input_tokens >= used * 1.2) ?? larger[larger.length - 1];
3477
+ };
3478
+ /** Rewinds past the latest message, to send it again or change it. */
3479
+ const takeBack = async (a) => {
3480
+ const asked = latestAsked(a);
3481
+ if (!asked)
3482
+ return null;
3483
+ await a.rewind(asked.index);
3484
+ if (agent === a) {
3485
+ renderHistory(a.messages);
3486
+ showUsage_(a);
3487
+ }
3488
+ return asked;
3489
+ };
3490
+ const sendText = async (a, text) => {
3491
+ if (agent === a && !a.busy)
3492
+ awaitingRow = addUser(text);
3493
+ await a.prompt(text);
3494
+ };
3495
+ /** Carries on in a new conversation that starts from a summary of this one; the latest message goes along. */
3496
+ const continueInNew = async (a) => {
3497
+ const asked = latestAsked(a);
3498
+ compacting = true;
3499
+ let summary = null;
3500
+ try {
3501
+ summary = await a.summarize(asked?.msg);
3502
+ }
3503
+ finally {
3504
+ compacting = false;
3505
+ closeActive();
3506
+ }
3507
+ await new Promise((r) => setTimeout(r, 0));
3508
+ await (clearBtn.style.display === "none" ? newSession().then(() => undefined) : clearConversation());
3509
+ const b = agent;
3510
+ if (summary) {
3511
+ await b.seed(summary);
3512
+ renderHistory(b.messages);
3513
+ showUsage_(b);
3514
+ }
3515
+ else if (a.messages.length > 1)
3516
+ ui.notify(t.ovNoSummary, "warning");
3517
+ setBusy(false);
3518
+ if (!asked)
3519
+ return;
3520
+ // What was attached may be what did not fit: it goes back into the composer, for the user to decide.
3521
+ if (asked.files) {
3522
+ await reattach(asked.msg);
3523
+ ta.value = asked.text;
3524
+ syncSend();
3525
+ ta.focus();
3526
+ }
3527
+ else if (asked.text)
3528
+ await sendText(b, asked.text);
3529
+ };
3530
+ /** A request that does not fit the model: says why in the chat's language and offers what solves it, one click each. */
3531
+ const addOverflow = async (a, ov) => {
3532
+ const go = async () => { await new Promise((r) => setTimeout(r, 0)); await a.continue(); };
3533
+ const before = a.messages.slice(0, latestAsked(a)?.index ?? 0);
3534
+ // Turns not yet in a summary can still be compacted; a new chat helps only when there is something to leave behind.
3535
+ const older = before.some((m) => summaryOf(m) === null);
3536
+ const actions = [];
3537
+ const editMessage = { label: t.ovEdit, run: async () => { const asked = await takeBack(a); if (asked) {
3538
+ ta.value = asked.text;
3539
+ syncSend();
3540
+ ta.focus();
3541
+ } } };
3542
+ const compact = { label: t.ovCompact, run: async () => { await compactNow(); await go(); } };
3543
+ const fresh = { label: t.ovNew, run: () => continueInNew(a) };
3544
+ if (ov.cause === "attachments")
3545
+ actions.push({ label: t.ovDropFiles, run: async () => {
3546
+ const asked = await takeBack(a);
3547
+ if (!asked)
3548
+ return;
3549
+ if (asked.text)
3550
+ await sendText(a, asked.text);
3551
+ else {
3552
+ ui.notify(t.ovNoText, "warning");
3553
+ ta.focus();
3554
+ }
3555
+ } });
3556
+ else if (ov.cause === "message")
3557
+ actions.push(editMessage);
3558
+ else if (ov.cause === "tools") {
3559
+ if (toolSettings)
3560
+ actions.push({ label: t.ovToolSettings, run: async () => toolSettings() });
3561
+ }
3562
+ else if (ov.cause === "history") {
3563
+ if (older)
3564
+ actions.push(compact);
3565
+ actions.push(fresh);
3566
+ }
3567
+ else {
3568
+ if (older)
3569
+ actions.push(compact);
3570
+ if (before.length)
3571
+ actions.push(fresh);
3572
+ actions.push(editMessage);
3573
+ }
3574
+ const roomier = await roomierModel(a, ov.used, ov.window).catch(() => undefined);
3575
+ if (roomier)
3576
+ actions.push({ label: t.ovUseModel.replace("{name}", roomier.id), run: async () => { useModel(roomier); await go(); } });
3577
+ if (agent !== a)
3578
+ return;
3579
+ const text = { attachments: t.ovAttachments, message: t.ovMessage, tools: t.ovTools, history: t.ovHistory, model: t.ovModel }[ov.cause];
3580
+ const row = {
3581
+ render: () => {
3582
+ const card = h("div", "ra-err ra-over", text);
3583
+ card.setAttribute("role", "alert");
3584
+ const bar = h("div", "ra-acts");
3585
+ for (const act of actions) {
3586
+ const b = h("button", "ra-btn xs", act.label);
3587
+ b.type = "button";
3588
+ b.addEventListener("click", () => {
3589
+ if (a.busy) {
3590
+ ui.notify(t.busyCmd, "warning");
3591
+ return;
3592
+ }
3593
+ list.remove(row);
3594
+ void act.run().catch((err) => { addError(err.message); setBusy(false); });
3595
+ });
3596
+ bar.append(b);
3597
+ }
3598
+ if (actions.length)
3599
+ card.append(bar);
3600
+ return card;
3601
+ },
3602
+ };
3603
+ addRow(row);
3604
+ list.schedule();
3605
+ };
3403
3606
  const pickModel = (models, q) => {
3404
3607
  const l = q.toLowerCase();
3405
3608
  const exact = models.find((m) => m.id.toLowerCase() === l);
@@ -3415,34 +3618,7 @@ export function renderChat(target, opts) {
3415
3618
  } },
3416
3619
  { name: "new", aliases: ["clear"], run: () => { closeMenu(); return clearBtn.style.display === "none" ? newSession().then(() => undefined) : clearConversation(); } },
3417
3620
  { 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
- } },
3621
+ { name: "compact", args: t.cmdArgs.compact, run: async (focus) => { await compactNow(focus); } },
3446
3622
  { name: "continue", run: async () => {
3447
3623
  if (agent.busy) {
3448
3624
  ui.notify(t.busyCmd, "warning");
@@ -3462,16 +3638,7 @@ export function renderChat(target, opts) {
3462
3638
  ui.notify(t.unknownModel.replace("{name}", q), "warning");
3463
3639
  return;
3464
3640
  }
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);
3641
+ useModel(m);
3475
3642
  ui.notify(t.modelSet.replace("{name}", m.id));
3476
3643
  } },
3477
3644
  { name: "effort", args: t.cmdArgs.effort, run: async (q) => {
@@ -3657,7 +3824,9 @@ export function renderChat(target, opts) {
3657
3824
  catch (e) {
3658
3825
  ui.notify(e.message, "error");
3659
3826
  } };
3660
- if (end.reason === "error")
3827
+ if (end.overflow)
3828
+ void addOverflow(a, end.overflow);
3829
+ else if (end.reason === "error")
3661
3830
  addError(end.error ?? t.error, a.messages.length ? go : undefined);
3662
3831
  else if (end.reason === "max_turns")
3663
3832
  addWarn(t.maxTurns.replace("{n}", String(a.settings.maxTurns)), { label: t.continueRun, onClick: go }, t.maxTurnsHint);
@@ -3878,7 +4047,7 @@ export function renderChat(target, opts) {
3878
4047
  list.schedule();
3879
4048
  }
3880
4049
  ui.cancelAll();
3881
- addEnd(a, r.reason === "done" ? null : { reason: r.reason, error: r.error?.message, at: Date.now() });
4050
+ addEnd(a, r.reason === "done" ? null : a.lastEnd ?? { reason: r.reason, error: r.error?.message, at: Date.now() });
3882
4051
  setBusy(false);
3883
4052
  showUsage_(a);
3884
4053
  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];
package/dist/index.cjs CHANGED
@@ -23,6 +23,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
23
23
  var src_exports = {};
24
24
  __export(src_exports, {
25
25
  Agent: () => Agent,
26
+ ContextOverflowError: () => ContextOverflowError,
26
27
  DEFAULT_SKILLS_DIR: () => DEFAULT_SKILLS_DIR,
27
28
  DEFAULT_USER_SKILLS_DIR: () => DEFAULT_USER_SKILLS_DIR,
28
29
  MCPError: () => MCPError,
@@ -50,6 +51,7 @@ __export(src_exports, {
50
51
  formatPdfText: () => formatPdfText,
51
52
  groupTurns: () => groupTurns,
52
53
  guessType: () => guessType,
54
+ isContextOverflow: () => isContextOverflow,
53
55
  isPdf: () => isPdf,
54
56
  listTemplates: () => listTemplates,
55
57
  listZip: () => listZip,
@@ -108,6 +110,40 @@ var ProviderError = class extends Error {
108
110
  return this.status;
109
111
  }
110
112
  };
113
+ var OVERFLOW_MESSAGES = {
114
+ attachments: "The attachments on this message are too large for the model's context",
115
+ message: "This message is too long for the model's context",
116
+ tools: "The connected tools take up too much of the model's context",
117
+ history: "This conversation is too long for the model's context",
118
+ model: "This request does not fit the model's context"
119
+ };
120
+ var ContextOverflowError = class extends ProviderError {
121
+ constructor(overflow, detail, status = 400) {
122
+ super(status, OVERFLOW_MESSAGES[overflow.cause], { code: "context_overflow" });
123
+ __publicField(this, "overflow");
124
+ __publicField(this, "detail");
125
+ this.name = "ContextOverflowError";
126
+ this.overflow = overflow;
127
+ this.detail = detail;
128
+ }
129
+ };
130
+ var OVERFLOW_TEXT = /context[_ ]length|context[_ ]window|maximum context|(?:prompt|input|request|message)s? (?:is |are )?too (?:long|large)|too many (?:input |prompt )?tokens|prompt tokens too many|exceed\w* .{0,30}(?:context|token limit|input token)|input token count|max_input_tokens|range of input length|payload too large|entity too large/i;
131
+ function isContextOverflow(err) {
132
+ if (err instanceof ContextOverflowError) return true;
133
+ const s = errorStatus(err);
134
+ if (s === 401 || s === 402 || s === 403 || s === 404 || s === 429) return false;
135
+ if (s === 413) return true;
136
+ const code = err?.code;
137
+ if (code === "context_length_exceeded" || code === "context_overflow") return true;
138
+ return err instanceof Error && OVERFLOW_TEXT.test(err.message);
139
+ }
140
+ function overflowLimit(err) {
141
+ const text = err instanceof Error ? err.message : "";
142
+ const m = /its ([\d,]+) max_input_tokens|maximum context length is ([\d,]+)|> ?([\d,]+) maximum|context (?:window|length) of ([\d,]+)|token limit\D{0,5}([\d,]+)|\[1, ?([\d,]+)\]/i.exec(text);
143
+ const raw = m?.slice(1).find(Boolean);
144
+ const n = raw ? Number(raw.replace(/,/g, "")) : NaN;
145
+ return n >= 1e3 ? n : void 0;
146
+ }
111
147
  function errorStatus(err) {
112
148
  if (!err || typeof err !== "object") return void 0;
113
149
  const e = err;
@@ -342,7 +378,7 @@ function fitBudget(messages, opts) {
342
378
  if (over() && turns.length === 1) {
343
379
  const turn = turns[0];
344
380
  const toolIdx = turn.map((m, i) => m.role === "tool" ? i : -1).filter((i) => i >= 0);
345
- for (const i of toolIdx.slice(0, Math.max(0, toolIdx.length - 3))) {
381
+ for (const i of toolIdx.slice(0, Math.max(0, toolIdx.length - (opts.keepResults ?? 3)))) {
346
382
  if (!over()) break;
347
383
  const m = turn[i];
348
384
  const text = typeof m.content === "string" ? m.content : partsText(m.content);
@@ -3901,8 +3937,10 @@ var Agent = class {
3901
3937
  this._ended = null;
3902
3938
  this.emit("run_start", { runId, message: prefaced });
3903
3939
  const maxTurns = this.opts.maxTurns ?? DEFAULT_MAX_TURNS;
3904
- const { output: maxTokens, input: window } = await this.limits();
3905
- const compaction = resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {});
3940
+ const { output: maxTokens, input: catalogueWindow } = await this.limits();
3941
+ let window = catalogueWindow;
3942
+ let compaction = resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {});
3943
+ let overflowRetries = 0;
3906
3944
  try {
3907
3945
  if (prefaceError) throw prefaceError;
3908
3946
  for (let turn = 1; ; turn++) {
@@ -3952,10 +3990,25 @@ var Agent = class {
3952
3990
  const asked = Date.now();
3953
3991
  let completion;
3954
3992
  try {
3993
+ if (estimateTokens(this.history, fixed) > window * 2 && (typeof this.opts.maxInputTokens === "number" || typeof (await this.modelInfo())?.max_input_tokens === "number")) {
3994
+ throw new ProviderError(413, "the request is far larger than the model's context");
3995
+ }
3955
3996
  completion = await this.callModel(params, runId, signal);
3956
3997
  } catch (err) {
3957
3998
  this.emit("response", { runId, turn, durationMs: Date.now() - asked, error: err instanceof Error ? err.message : String(err) });
3958
- throw err;
3999
+ if (signal.aborted || !isContextOverflow(err)) throw err;
4000
+ const limit = overflowLimit(err);
4001
+ if (limit !== void 0 && limit < window) {
4002
+ window = limit;
4003
+ compaction = resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {});
4004
+ }
4005
+ let smaller = false;
4006
+ while (!smaller && overflowRetries < 2) smaller = await this.squeeze(window, overflowRetries++, compaction, fixed, runId, signal);
4007
+ if (smaller) {
4008
+ turn--;
4009
+ continue;
4010
+ }
4011
+ throw new ContextOverflowError({ cause: this.overflowCause(window, fixed), used: estimateTokens(this.history, fixed), window }, err instanceof Error ? err.message : String(err), errorStatus(err) ?? 400);
3959
4012
  }
3960
4013
  this.emit("response", { runId, turn, durationMs: Date.now() - asked, finishReason: completion.finishReason, usage: completion.usage, message: completion.message });
3961
4014
  if (completion.usage) this.addUsage(completion.usage);
@@ -4027,7 +4080,8 @@ var Agent = class {
4027
4080
  this.markRunUsage(historyBefore, usageBefore);
4028
4081
  this.committed = this.history.length;
4029
4082
  this.resetLoop();
4030
- this._ended = reason === "done" ? null : { reason, ...error ? { error: error.message } : {}, at: Date.now() };
4083
+ const overflow = error instanceof ContextOverflowError ? { code: error.code, overflow: error.overflow } : {};
4084
+ this._ended = reason === "done" ? null : { reason, ...error ? { error: error.message } : {}, ...overflow, at: Date.now() };
4031
4085
  await this.saveSession();
4032
4086
  const result = {
4033
4087
  runId,
@@ -4105,21 +4159,55 @@ var Agent = class {
4105
4159
  * all of them would fit in `keepRecentTokens`.
4106
4160
  */
4107
4161
  compact(focus) {
4108
- if (this.current) return Promise.reject(new Error("cannot compact while a run is active"));
4109
- const controller = new AbortController();
4110
- const work = this.chain.then(async () => {
4111
- await this.loaded;
4162
+ return this.exclusive("compact", async (signal) => {
4112
4163
  const window = await this.contextTokens();
4113
- let settings = resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {});
4114
- const h = this.history;
4115
- let last = h.length - 1;
4116
- while (last > 0 && !(h[last].role === "user" && summaryOf(h[last]) === null)) last--;
4117
- const latestTurn = last > 0 ? h.slice(last).reduce((n, m) => n + estimateTokens([m]), 0) : Math.floor(estimateTokens(h) / 2);
4118
- settings = { ...settings, keepRecentTokens: Math.min(settings.keepRecentTokens, latestTurn) };
4119
- const done = await this.compactWith(settings, void 0, controller.signal, focus);
4164
+ const settings = this.squeezed(resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {}));
4165
+ const done = await this.compactWith(settings, void 0, signal, focus);
4120
4166
  if (done) await this.saveSession();
4121
4167
  return done;
4122
4168
  });
4169
+ }
4170
+ /**
4171
+ * A summary of the conversation that stays out of it, to carry on in a new
4172
+ * one (`seed`): everything but `leaveOut`, usually the request to send again.
4173
+ * Null when there is nothing to summarise or the summary could not be written.
4174
+ */
4175
+ summarize(leaveOut) {
4176
+ return this.exclusive("summarize", async (signal) => {
4177
+ const rest = this.history.filter((m) => m !== leaveOut);
4178
+ const first = rest[0] ? summaryOf(rest[0]) : null;
4179
+ const toSummarize = first === null ? rest : rest.slice(1);
4180
+ if (!toSummarize.length) return first;
4181
+ const window = await this.contextTokens();
4182
+ const settings = resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {});
4183
+ this.emit("compaction_start", {});
4184
+ try {
4185
+ return await this.writeSummary({ toSummarize, previousSummary: first ?? void 0, kept: [] }, settings, void 0, signal);
4186
+ } catch (err) {
4187
+ if (signal.aborted) throw err;
4188
+ console.warn("[agent] summary failed:", err);
4189
+ return null;
4190
+ }
4191
+ });
4192
+ }
4193
+ /** Starts an empty conversation from the summary of another (`summarize`). */
4194
+ async seed(summary) {
4195
+ await this.loaded;
4196
+ if (this.current) throw new Error("cannot seed while a run is active");
4197
+ if (this.history.length) throw new Error("seed needs an empty conversation");
4198
+ this.history = [summaryMessage(summary)];
4199
+ this.committed = 1;
4200
+ this._ended = null;
4201
+ await this.saveSession();
4202
+ }
4203
+ /** Runs like a run: messages sent meanwhile queue behind it instead of being lost when the history is replaced. */
4204
+ exclusive(what, job) {
4205
+ if (this.current) return Promise.reject(new Error(`cannot ${what} while a run is active`));
4206
+ const controller = new AbortController();
4207
+ const work = this.chain.then(async () => {
4208
+ await this.loaded;
4209
+ return job(controller.signal);
4210
+ });
4123
4211
  const promise = work.then(() => ({ ...abortedResult(), reason: "done" }), () => abortedResult());
4124
4212
  this.current = { controller, promise };
4125
4213
  this.chain = promise;
@@ -4129,6 +4217,80 @@ var Agent = class {
4129
4217
  });
4130
4218
  return work;
4131
4219
  }
4220
+ /** Settings under which everything before the latest turn may be summarised, even when all of it would fit. */
4221
+ squeezed(settings) {
4222
+ const h = this.history;
4223
+ let last = h.length - 1;
4224
+ while (last > 0 && !(h[last].role === "user" && summaryOf(h[last]) === null)) last--;
4225
+ const latestTurn = last > 0 ? h.slice(last).reduce((n, m) => n + estimateTokens([m]), 0) : Math.floor(estimateTokens(h) / 2);
4226
+ return { ...settings, keepRecentTokens: Math.min(settings.keepRecentTokens, latestTurn) };
4227
+ }
4228
+ /**
4229
+ * The model refused the request as too large: make it smaller. Round 0
4230
+ * summarises what is older than the latest turn and trims to 70% of the
4231
+ * window (the estimate may run low); round 1 trims to 40%, big results of the
4232
+ * latest turn included. True when the request did get smaller.
4233
+ */
4234
+ async squeeze(window, round2, settings, fixed, runId, signal) {
4235
+ const before = estimateTokens(this.history, fixed);
4236
+ if (round2 === 0 && this.opts.compaction !== false) await this.compactWith(this.squeezed(settings), runId, signal);
4237
+ const pinned = this.history.length && summaryOf(this.history[0]) !== null ? [this.history[0]] : [];
4238
+ const rest = this.history.slice(pinned.length);
4239
+ const budget = Math.floor(window * (round2 === 0 ? 0.7 : 0.4)) - estimateTokens(pinned);
4240
+ const fit = fitBudget(rest, { budget, keepTurns: 1, system: fixed, keepResults: round2 === 0 ? 3 : 0 });
4241
+ if (fit.droppedTurns || fit.elidedResults) {
4242
+ this.history = [...pinned, ...fit.messages];
4243
+ this.droppedTurns += fit.droppedTurns;
4244
+ this.committed = Math.min(this.committed, this.history.length);
4245
+ this.emit("compaction", { runId, summary: false, tokensBefore: before, tokensAfter: estimateTokens(this.history, fixed), droppedTurns: fit.droppedTurns, elidedResults: fit.elidedResults });
4246
+ }
4247
+ return estimateTokens(this.history, fixed) < before;
4248
+ }
4249
+ /** What takes up the room in a request that cannot be made smaller. */
4250
+ overflowCause(window, fixed) {
4251
+ const tools = this.tools.length ? estimateTokens([], JSON.stringify(this.tools.map((t) => toChatTool(t)))) : 0;
4252
+ const latest = [...this.history].reverse().find((m) => m.role === "user" && summaryOf(m) === null);
4253
+ const asked = latest ? estimateTokens([latest]) : 0;
4254
+ const others = estimateTokens(this.history) - asked;
4255
+ const biggest = Math.max(tools, asked, others);
4256
+ if (biggest * 2 < window) return "model";
4257
+ if (biggest === asked) {
4258
+ const files = Array.isArray(latest.content) ? latest.content.length > 1 : /(^|\n)\[attachments\]/.test(String(latest.content ?? ""));
4259
+ return files ? "attachments" : "message";
4260
+ }
4261
+ return biggest === tools ? "tools" : "history";
4262
+ }
4263
+ /** The summary of a cut: the host's own summariser, or the model, piece by piece. */
4264
+ async writeSummary(plan, settings, runId, signal) {
4265
+ if (typeof this.opts.compaction === "function") return this.opts.compaction(plan, this);
4266
+ const limits = await this.limits();
4267
+ const maxTokens = Math.min(limits.output, Math.max(1024, Math.floor(settings.reserveTokens * 0.8)));
4268
+ const room = Math.max(6e3, (limits.input - maxTokens - 1500) * 3);
4269
+ let previous = plan.previousSummary;
4270
+ for (const piece of splitForSummary(serializeConversation(plan.toSummarize), room)) {
4271
+ const params = { model: this.opts.model ?? "", messages: summarizationMessages(piece, previous, plan.focus), max_tokens: maxTokens };
4272
+ if (!params.model) delete params.model;
4273
+ const tag = { runId: runId ?? "", turn: this.turnNow, purpose: "compaction" };
4274
+ this.emit("request", { ...tag, params });
4275
+ signal.throwIfAborted();
4276
+ const asked = Date.now();
4277
+ let res;
4278
+ try {
4279
+ res = this.provider.complete ? await this.provider.complete(params, { signal }) : await collectCompletion((p, init) => this.provider.stream(p, init), params, { signal }).then((c) => ({ choices: [{ message: { ...c.message, content: typeof c.message.content === "string" ? c.message.content : null }, finish_reason: c.finishReason }], usage: c.usage }));
4280
+ } catch (err) {
4281
+ this.emit("response", { ...tag, durationMs: Date.now() - asked, error: err instanceof Error ? err.message : String(err) });
4282
+ throw err;
4283
+ }
4284
+ if (res.usage) this.addUsage(res.usage);
4285
+ const choice = res.choices[0];
4286
+ this.emit("response", { ...tag, durationMs: Date.now() - asked, finishReason: choice?.finish_reason ?? void 0, usage: res.usage ?? void 0, message: choice?.message });
4287
+ if (!choice || choice.finish_reason === "length") throw new Error("the summary is incomplete");
4288
+ if (choice.message.tool_calls?.length) throw new Error("the summariser attempted to call a tool");
4289
+ previous = (choice.message.content ?? "").trim();
4290
+ if (!previous) throw new Error("empty summary");
4291
+ }
4292
+ return previous;
4293
+ }
4132
4294
  async compactWith(settings, runId, signal, focus) {
4133
4295
  const plan = planCut(this.history, settings.keepRecentTokens);
4134
4296
  if (!plan) return false;
@@ -4137,37 +4299,7 @@ var Agent = class {
4137
4299
  const tokensBefore = estimateTokens(this.history);
4138
4300
  let summary;
4139
4301
  try {
4140
- if (typeof this.opts.compaction === "function") {
4141
- summary = await this.opts.compaction(plan, this);
4142
- } else {
4143
- const limits = await this.limits();
4144
- const maxTokens = Math.min(limits.output, Math.max(1024, Math.floor(settings.reserveTokens * 0.8)));
4145
- const room = Math.max(6e3, (limits.input - maxTokens - 1500) * 3);
4146
- let previous = plan.previousSummary;
4147
- for (const piece of splitForSummary(serializeConversation(plan.toSummarize), room)) {
4148
- const params = { model: this.opts.model ?? "", messages: summarizationMessages(piece, previous, plan.focus), max_tokens: maxTokens };
4149
- if (!params.model) delete params.model;
4150
- const tag = { runId: runId ?? "", turn: this.turnNow, purpose: "compaction" };
4151
- this.emit("request", { ...tag, params });
4152
- signal.throwIfAborted();
4153
- const asked = Date.now();
4154
- let res;
4155
- try {
4156
- res = this.provider.complete ? await this.provider.complete(params, { signal }) : await collectCompletion((p, init) => this.provider.stream(p, init), params, { signal }).then((c) => ({ choices: [{ message: { ...c.message, content: typeof c.message.content === "string" ? c.message.content : null }, finish_reason: c.finishReason }], usage: c.usage }));
4157
- } catch (err) {
4158
- this.emit("response", { ...tag, durationMs: Date.now() - asked, error: err instanceof Error ? err.message : String(err) });
4159
- throw err;
4160
- }
4161
- if (res.usage) this.addUsage(res.usage);
4162
- const choice = res.choices[0];
4163
- this.emit("response", { ...tag, durationMs: Date.now() - asked, finishReason: choice?.finish_reason ?? void 0, usage: res.usage ?? void 0, message: choice?.message });
4164
- if (!choice || choice.finish_reason === "length") throw new Error("the summary is incomplete");
4165
- if (choice.message.tool_calls?.length) throw new Error("the summariser attempted to call a tool");
4166
- previous = (choice.message.content ?? "").trim();
4167
- if (!previous) throw new Error("empty summary");
4168
- }
4169
- summary = previous;
4170
- }
4302
+ summary = await this.writeSummary(plan, settings, runId, signal);
4171
4303
  } catch (err) {
4172
4304
  if (signal.aborted) throw err;
4173
4305
  console.warn("[agent] compaction summary failed, falling back to trimming:", err);
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { Agent, type PromptContent } from "./agent.js";
2
- export { openAIProvider, runappsProvider, toProvider, ProviderError, sseData, modelAccepts, type ModelProvider, type ModelInfo, type ModelPrice, type InputKind, type OpenAIProviderOptions, type RunAppsClientLike } from "./provider.js";
2
+ export { openAIProvider, runappsProvider, toProvider, ProviderError, ContextOverflowError, isContextOverflow, sseData, modelAccepts, type ContextOverflow, type OverflowCause, type ModelProvider, type ModelInfo, type ModelPrice, type InputKind, type OpenAIProviderOptions, type RunAppsClientLike } from "./provider.js";
3
3
  export type { ChatMessage, ContentPart, ChatTool, ChatToolCall, ChatCompletionParams, ChatCompletionChunk, ChatCompletion, Usage } from "./llm.js";
4
4
  import { Agent } from "./agent.js";
5
5
  import type { AgentOptions } from "./types.js";