@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/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // (a folder as the directory, storage on disk, terminal dialogs) are
5
5
  // `@runappsai/agent/node`.
6
6
  export { Agent } from "./agent.js";
7
- export { openAIProvider, runappsProvider, toProvider, ProviderError, sseData, modelAccepts } from "./provider.js";
7
+ export { openAIProvider, runappsProvider, toProvider, ProviderError, ContextOverflowError, isContextOverflow, sseData, modelAccepts } from "./provider.js";
8
8
  import { Agent } from "./agent.js";
9
9
  import { Workspace } from "./workspace.js";
10
10
  import { toProvider } from "./provider.js";
@@ -86,6 +86,28 @@ export declare class ProviderError extends Error {
86
86
  /** The RunApps SDK's name for `status`. */
87
87
  get statusCode(): number;
88
88
  }
89
+ /** What takes up the room when a request does not fit the model's context. */
90
+ export type OverflowCause = "attachments" | "message" | "tools" | "history" | "model";
91
+ /** Why a request did not fit: the biggest part of it, and its size against the window (estimated tokens). */
92
+ export interface ContextOverflow {
93
+ cause: OverflowCause;
94
+ used: number;
95
+ window: number;
96
+ }
97
+ /**
98
+ * A request that still did not fit after the agent compacted and trimmed the
99
+ * conversation. `overflow` says what takes up the room; `detail` is the
100
+ * provider's own words, when it was the provider that refused.
101
+ */
102
+ export declare class ContextOverflowError extends ProviderError {
103
+ readonly overflow: ContextOverflow;
104
+ readonly detail?: string;
105
+ constructor(overflow: ContextOverflow, detail?: string, status?: number);
106
+ }
107
+ /** Whether a failed model call means the request is larger than the model's context. */
108
+ export declare function isContextOverflow(err: unknown): boolean;
109
+ /** The model's real limit, when the provider's refusal states it. */
110
+ export declare function overflowLimit(err: unknown): number | undefined;
89
111
  /** The status of any provider's error: ProviderError, the RunApps SDK's APIError, or anything with a `status`. */
90
112
  export declare function errorStatus(err: unknown): number | undefined;
91
113
  /** The parts of the RunApps SDK client a provider needs. */
package/dist/provider.js CHANGED
@@ -33,6 +33,52 @@ export class ProviderError extends Error {
33
33
  /** The RunApps SDK's name for `status`. */
34
34
  get statusCode() { return this.status; }
35
35
  }
36
+ const OVERFLOW_MESSAGES = {
37
+ attachments: "The attachments on this message are too large for the model's context",
38
+ message: "This message is too long for the model's context",
39
+ tools: "The connected tools take up too much of the model's context",
40
+ history: "This conversation is too long for the model's context",
41
+ model: "This request does not fit the model's context",
42
+ };
43
+ /**
44
+ * A request that still did not fit after the agent compacted and trimmed the
45
+ * conversation. `overflow` says what takes up the room; `detail` is the
46
+ * provider's own words, when it was the provider that refused.
47
+ */
48
+ export class ContextOverflowError extends ProviderError {
49
+ overflow;
50
+ detail;
51
+ constructor(overflow, detail, status = 400) {
52
+ super(status, OVERFLOW_MESSAGES[overflow.cause], { code: "context_overflow" });
53
+ this.name = "ContextOverflowError";
54
+ this.overflow = overflow;
55
+ this.detail = detail;
56
+ }
57
+ }
58
+ // Each provider's wording for "the prompt is larger than the model takes". Limits on the reply (max_tokens) and rate limits per minute are something else.
59
+ const 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;
60
+ /** Whether a failed model call means the request is larger than the model's context. */
61
+ export function isContextOverflow(err) {
62
+ if (err instanceof ContextOverflowError)
63
+ return true;
64
+ const s = errorStatus(err);
65
+ if (s === 401 || s === 402 || s === 403 || s === 404 || s === 429)
66
+ return false;
67
+ if (s === 413)
68
+ return true;
69
+ const code = err?.code;
70
+ if (code === "context_length_exceeded" || code === "context_overflow")
71
+ return true;
72
+ return err instanceof Error && OVERFLOW_TEXT.test(err.message);
73
+ }
74
+ /** The model's real limit, when the provider's refusal states it. */
75
+ export function overflowLimit(err) {
76
+ const text = err instanceof Error ? err.message : "";
77
+ 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);
78
+ const raw = m?.slice(1).find(Boolean);
79
+ const n = raw ? Number(raw.replace(/,/g, "")) : NaN;
80
+ return n >= 1000 ? n : undefined;
81
+ }
36
82
  /** The status of any provider's error: ProviderError, the RunApps SDK's APIError, or anything with a `status`. */
37
83
  export function errorStatus(err) {
38
84
  if (!err || typeof err !== "object")
package/dist/types.d.ts CHANGED
@@ -2,6 +2,7 @@ import type { ChatCompletionParams, ChatMessage, ContentPart } from "./llm.js";
2
2
  import type { Usage } from "./llm.js";
3
3
  import type { Agent } from "./agent.js";
4
4
  import type { CompactionSettings, CutPlan } from "./compaction.js";
5
+ import type { ContextOverflow } from "./provider.js";
5
6
  import type { Workspace } from "./workspace.js";
6
7
  import type { TextEdit } from "./edit.js";
7
8
  /** A JSON Schema object (draft 7 / 2020-12 subset — see json-schema.ts). */
@@ -439,7 +440,9 @@ export interface SessionData {
439
440
  /** A run that did not finish: why, and when. */
440
441
  export interface RunEnd {
441
442
  reason: Exclude<RunEndReason, "done">;
442
- error?: string;
443
+ error?: string; /** `"context_overflow"`: the request did not fit the model's context; `overflow` says why. */
444
+ code?: string;
445
+ overflow?: ContextOverflow;
443
446
  at: number;
444
447
  }
445
448
  /** What a workspace lists for each saved session. */
package/dist/ui.cjs CHANGED
@@ -2040,6 +2040,19 @@ var STRINGS = {
2040
2040
  maxTurns: "Paused at the turn limit ({n})",
2041
2041
  retry: "Retry",
2042
2042
  messages: "messages",
2043
+ ovAttachments: "The attachments on this message are too large for the model.",
2044
+ ovMessage: "This message is too long for the model.",
2045
+ ovHistory: "This conversation has grown too long for the model.",
2046
+ ovTools: "The connected tools take up too much of the model's context.",
2047
+ ovModel: "This request does not fit the current model.",
2048
+ ovDropFiles: "Resend without attachments",
2049
+ ovEdit: "Edit the message",
2050
+ ovCompact: "Compact and continue",
2051
+ ovNew: "Continue in a new chat",
2052
+ ovToolSettings: "Tool settings",
2053
+ ovUseModel: "Retry with {name}",
2054
+ ovNoText: "The message had only attachments: type what you want to ask.",
2055
+ ovNoSummary: "Could not summarise the conversation; the new chat starts without it.",
2043
2056
  skill: "Skill",
2044
2057
  template: "Template",
2045
2058
  delete: "Delete",
@@ -2276,6 +2289,19 @@ var STRINGS = {
2276
2289
  maxTurns: "\u5DF2\u8FBE\u6700\u5927\u8F6E\u6570 {n}\uFF0C\u6682\u505C",
2277
2290
  retry: "\u91CD\u8BD5",
2278
2291
  messages: "\u6761\u6D88\u606F",
2292
+ ovAttachments: "\u8FD9\u6761\u6D88\u606F\u7684\u9644\u4EF6\u592A\u5927\uFF0C\u8D85\u51FA\u4E86\u6A21\u578B\u80FD\u5904\u7406\u7684\u957F\u5EA6\u3002",
2293
+ ovMessage: "\u8FD9\u6761\u6D88\u606F\u592A\u957F\uFF0C\u8D85\u51FA\u4E86\u6A21\u578B\u80FD\u5904\u7406\u7684\u957F\u5EA6\u3002",
2294
+ ovHistory: "\u8FD9\u6BB5\u5BF9\u8BDD\u592A\u957F\uFF0C\u6A21\u578B\u653E\u4E0D\u4E0B\u4E86\u3002",
2295
+ ovTools: "\u5DF2\u8FDE\u63A5\u7684\u5DE5\u5177\u592A\u591A\uFF0C\u5360\u6EE1\u4E86\u6A21\u578B\u7684\u4E0A\u4E0B\u6587\u3002",
2296
+ ovModel: "\u5F53\u524D\u6A21\u578B\u653E\u4E0D\u4E0B\u8FD9\u6B21\u8BF7\u6C42\u3002",
2297
+ ovDropFiles: "\u53BB\u6389\u9644\u4EF6\u540E\u91CD\u53D1",
2298
+ ovEdit: "\u4FEE\u6539\u8FD9\u6761\u6D88\u606F",
2299
+ ovCompact: "\u538B\u7F29\u540E\u7EE7\u7EED",
2300
+ ovNew: "\u5F00\u65B0\u5BF9\u8BDD\u7EE7\u7EED",
2301
+ ovToolSettings: "\u6253\u5F00\u5DE5\u5177\u8BBE\u7F6E",
2302
+ ovUseModel: "\u6362\u7528 {name} \u91CD\u8BD5",
2303
+ ovNoText: "\u8FD9\u6761\u6D88\u606F\u53EA\u6709\u9644\u4EF6\uFF0C\u8BF7\u8F93\u5165\u60F3\u95EE\u7684\u5185\u5BB9\u3002",
2304
+ ovNoSummary: "\u8FD9\u6BB5\u5BF9\u8BDD\u6CA1\u80FD\u751F\u6210\u6458\u8981\uFF0C\u65B0\u5BF9\u8BDD\u4E0D\u4F1A\u5E26\u4E0A\u4E4B\u524D\u7684\u5185\u5BB9\u3002",
2279
2305
  skill: "Skill",
2280
2306
  template: "\u6A21\u677F",
2281
2307
  delete: "\u5220\u9664",
@@ -2738,6 +2764,10 @@ var CSS = tokenCSS() + `
2738
2764
  .ra-card .ra-md{font-size:13px}
2739
2765
  .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}
2740
2766
  .ra-err .ra-btn{margin-top:6px}
2767
+ .ra-chat .ra-over{border-color:var(--ra-warn-border);background:var(--ra-warn-bg);color:var(--ra-warn-fg)}
2768
+ .ra-over .ra-acts{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}
2769
+ .ra-chat .ra-over .ra-btn{margin:0;border-color:var(--ra-warn-border);background:transparent;color:inherit}
2770
+ .ra-chat .ra-over .ra-btn:hover{background:var(--ra-warn-border)}
2741
2771
  .ra-ask{flex-shrink:0;max-height:45%;overflow-y:auto}
2742
2772
  .ra-ask .ra-col{display:flex;flex-direction:column;gap:8px;padding-top:8px;padding-bottom:8px}
2743
2773
  .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}
@@ -3281,7 +3311,7 @@ function renderChat(target, opts) {
3281
3311
  injectStyles();
3282
3312
  const lang = pickLocale(opts.locale);
3283
3313
  const t = STRINGS[lang];
3284
- 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;
3314
+ 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;
3285
3315
  const uploadsDir = "/" + (uploadsOpt ?? "/uploads").replace(/^\/+|\/+$/g, "");
3286
3316
  const provider = providerOpt ? (0, import_index2.toProvider)(providerOpt) : clientOpt ? (0, import_index2.toProvider)(clientOpt) : givenAgent?.provider ?? null;
3287
3317
  const project = provider?.name ?? agentOpts.appName ?? "app";
@@ -5534,6 +5564,174 @@ ${c.text}` })));
5534
5564
  }
5535
5565
  return out.join("\n");
5536
5566
  };
5567
+ const useModel = (m) => {
5568
+ const next = { ...userSettings };
5569
+ if (m.is_default && !agentOpts.model) delete next.model;
5570
+ else next.model = m.id;
5571
+ const eff = effortOf(m);
5572
+ if (next.reasoningEffort && !eff?.levels.includes(next.reasoningEffort)) delete next.reasoningEffort;
5573
+ saveSettings(next);
5574
+ };
5575
+ const compactNow = async (focus) => {
5576
+ const a = agent;
5577
+ if (a.busy) {
5578
+ ui.notify(t.busyCmd, "warning");
5579
+ return false;
5580
+ }
5581
+ compacting = true;
5582
+ try {
5583
+ const done = await a.compact(focus);
5584
+ if (!done) ui.notify(t.nothingToCompact);
5585
+ return done;
5586
+ } catch (err) {
5587
+ if (!/abort/i.test(err.message ?? "") && err.name !== "AbortError") throw err;
5588
+ ui.notify(t.stopped);
5589
+ return false;
5590
+ } finally {
5591
+ compacting = false;
5592
+ if (agent === a) {
5593
+ closeActive();
5594
+ showUsage_(a);
5595
+ setTimeout(() => {
5596
+ if (agent === a && !a.busy) setBusy(false);
5597
+ }, 0);
5598
+ }
5599
+ }
5600
+ };
5601
+ const latestAsked = (a) => {
5602
+ const list2 = a.messages;
5603
+ let index = list2.length - 1;
5604
+ while (index >= 0 && !(list2[index].role === "user" && (0, import_index2.summaryOf)(list2[index]) === null)) index--;
5605
+ const msg = list2[index];
5606
+ if (!msg) return null;
5607
+ const typed = msg.typed ?? textOfContent(msg.content).replace(/\s*\[attachments\][\s\S]*$/, "").replace(/(^|\n)\[context\] [\s\S]*$/, "");
5608
+ const files2 = Array.isArray(msg.content) ? msg.content.length > 1 : /(^|\n)\[attachments\]/.test(String(msg.content ?? ""));
5609
+ return { index, msg, text: typed.trim(), files: files2 };
5610
+ };
5611
+ const roomierModel = async (a, used, window2) => {
5612
+ const current = a.model || (await a.modelInfo())?.id;
5613
+ const asked2 = latestAsked(a)?.msg.content;
5614
+ const pictures = Array.isArray(asked2) && asked2.some((p) => p.type === "image_url");
5615
+ const larger = (await loadModels()).filter((m) => m.id !== current && (m.max_input_tokens ?? 0) > window2 && (!pictures || (0, import_index2.modelAccepts)(m, "image") !== false)).sort((x, y) => x.max_input_tokens - y.max_input_tokens);
5616
+ return larger.find((m) => m.max_input_tokens >= used * 1.2) ?? larger[larger.length - 1];
5617
+ };
5618
+ const takeBack = async (a) => {
5619
+ const asked2 = latestAsked(a);
5620
+ if (!asked2) return null;
5621
+ await a.rewind(asked2.index);
5622
+ if (agent === a) {
5623
+ renderHistory(a.messages);
5624
+ showUsage_(a);
5625
+ }
5626
+ return asked2;
5627
+ };
5628
+ const sendText = async (a, text) => {
5629
+ if (agent === a && !a.busy) awaitingRow = addUser(text);
5630
+ await a.prompt(text);
5631
+ };
5632
+ const continueInNew = async (a) => {
5633
+ const asked2 = latestAsked(a);
5634
+ compacting = true;
5635
+ let summary = null;
5636
+ try {
5637
+ summary = await a.summarize(asked2?.msg);
5638
+ } finally {
5639
+ compacting = false;
5640
+ closeActive();
5641
+ }
5642
+ await new Promise((r) => setTimeout(r, 0));
5643
+ await (clearBtn.style.display === "none" ? newSession().then(() => void 0) : clearConversation());
5644
+ const b = agent;
5645
+ if (summary) {
5646
+ await b.seed(summary);
5647
+ renderHistory(b.messages);
5648
+ showUsage_(b);
5649
+ } else if (a.messages.length > 1) ui.notify(t.ovNoSummary, "warning");
5650
+ setBusy(false);
5651
+ if (!asked2) return;
5652
+ if (asked2.files) {
5653
+ await reattach(asked2.msg);
5654
+ ta.value = asked2.text;
5655
+ syncSend();
5656
+ ta.focus();
5657
+ } else if (asked2.text) await sendText(b, asked2.text);
5658
+ };
5659
+ const addOverflow = async (a, ov) => {
5660
+ const go = async () => {
5661
+ await new Promise((r) => setTimeout(r, 0));
5662
+ await a.continue();
5663
+ };
5664
+ const before = a.messages.slice(0, latestAsked(a)?.index ?? 0);
5665
+ const older = before.some((m) => (0, import_index2.summaryOf)(m) === null);
5666
+ const actions = [];
5667
+ const editMessage = { label: t.ovEdit, run: async () => {
5668
+ const asked2 = await takeBack(a);
5669
+ if (asked2) {
5670
+ ta.value = asked2.text;
5671
+ syncSend();
5672
+ ta.focus();
5673
+ }
5674
+ } };
5675
+ const compact = { label: t.ovCompact, run: async () => {
5676
+ await compactNow();
5677
+ await go();
5678
+ } };
5679
+ const fresh = { label: t.ovNew, run: () => continueInNew(a) };
5680
+ if (ov.cause === "attachments") actions.push({ label: t.ovDropFiles, run: async () => {
5681
+ const asked2 = await takeBack(a);
5682
+ if (!asked2) return;
5683
+ if (asked2.text) await sendText(a, asked2.text);
5684
+ else {
5685
+ ui.notify(t.ovNoText, "warning");
5686
+ ta.focus();
5687
+ }
5688
+ } });
5689
+ else if (ov.cause === "message") actions.push(editMessage);
5690
+ else if (ov.cause === "tools") {
5691
+ if (toolSettings) actions.push({ label: t.ovToolSettings, run: async () => toolSettings() });
5692
+ } else if (ov.cause === "history") {
5693
+ if (older) actions.push(compact);
5694
+ actions.push(fresh);
5695
+ } else {
5696
+ if (older) actions.push(compact);
5697
+ if (before.length) actions.push(fresh);
5698
+ actions.push(editMessage);
5699
+ }
5700
+ const roomier = await roomierModel(a, ov.used, ov.window).catch(() => void 0);
5701
+ if (roomier) actions.push({ label: t.ovUseModel.replace("{name}", roomier.id), run: async () => {
5702
+ useModel(roomier);
5703
+ await go();
5704
+ } });
5705
+ if (agent !== a) return;
5706
+ const text = { attachments: t.ovAttachments, message: t.ovMessage, tools: t.ovTools, history: t.ovHistory, model: t.ovModel }[ov.cause];
5707
+ const row = {
5708
+ render: () => {
5709
+ const card = h("div", "ra-err ra-over", text);
5710
+ card.setAttribute("role", "alert");
5711
+ const bar2 = h("div", "ra-acts");
5712
+ for (const act of actions) {
5713
+ const b = h("button", "ra-btn xs", act.label);
5714
+ b.type = "button";
5715
+ b.addEventListener("click", () => {
5716
+ if (a.busy) {
5717
+ ui.notify(t.busyCmd, "warning");
5718
+ return;
5719
+ }
5720
+ list.remove(row);
5721
+ void act.run().catch((err) => {
5722
+ addError(err.message);
5723
+ setBusy(false);
5724
+ });
5725
+ });
5726
+ bar2.append(b);
5727
+ }
5728
+ if (actions.length) card.append(bar2);
5729
+ return card;
5730
+ }
5731
+ };
5732
+ addRow(row);
5733
+ list.schedule();
5734
+ };
5537
5735
  const pickModel = (models, q) => {
5538
5736
  const l = q.toLowerCase();
5539
5737
  const exact = models.find((m) => m.id.toLowerCase() === l);
@@ -5552,27 +5750,7 @@ ${c.text}` })));
5552
5750
  } },
5553
5751
  { name: "resume", run: () => openMenu() },
5554
5752
  { name: "compact", args: t.cmdArgs.compact, run: async (focus) => {
5555
- const a = agent;
5556
- if (a.busy) {
5557
- ui.notify(t.busyCmd, "warning");
5558
- return;
5559
- }
5560
- compacting = true;
5561
- try {
5562
- if (!await a.compact(focus)) ui.notify(t.nothingToCompact);
5563
- } catch (err) {
5564
- if (!/abort/i.test(err.message ?? "") && err.name !== "AbortError") throw err;
5565
- ui.notify(t.stopped);
5566
- } finally {
5567
- compacting = false;
5568
- if (agent === a) {
5569
- closeActive();
5570
- showUsage_(a);
5571
- setTimeout(() => {
5572
- if (agent === a && !a.busy) setBusy(false);
5573
- }, 0);
5574
- }
5575
- }
5753
+ await compactNow(focus);
5576
5754
  } },
5577
5755
  { name: "continue", run: async () => {
5578
5756
  if (agent.busy) {
@@ -5592,12 +5770,7 @@ ${c.text}` })));
5592
5770
  ui.notify(t.unknownModel.replace("{name}", q), "warning");
5593
5771
  return;
5594
5772
  }
5595
- const next = { ...userSettings };
5596
- if (m.is_default && !agentOpts.model) delete next.model;
5597
- else next.model = m.id;
5598
- const eff = effortOf(m);
5599
- if (next.reasoningEffort && !eff?.levels.includes(next.reasoningEffort)) delete next.reasoningEffort;
5600
- saveSettings(next);
5773
+ useModel(m);
5601
5774
  ui.notify(t.modelSet.replace("{name}", m.id));
5602
5775
  } },
5603
5776
  { name: "effort", args: t.cmdArgs.effort, run: async (q) => {
@@ -5764,7 +5937,8 @@ ${c.text}` })));
5764
5937
  ui.notify(e.message, "error");
5765
5938
  }
5766
5939
  };
5767
- if (end.reason === "error") addError(end.error ?? t.error, a.messages.length ? go : void 0);
5940
+ if (end.overflow) void addOverflow(a, end.overflow);
5941
+ else if (end.reason === "error") addError(end.error ?? t.error, a.messages.length ? go : void 0);
5768
5942
  else if (end.reason === "max_turns") addWarn(t.maxTurns.replace("{n}", String(a.settings.maxTurns)), { label: t.continueRun, onClick: go }, t.maxTurnsHint);
5769
5943
  else addNote(t.stopped);
5770
5944
  };
@@ -5948,7 +6122,7 @@ ${c.text}` })));
5948
6122
  list.schedule();
5949
6123
  }
5950
6124
  ui.cancelAll();
5951
- addEnd(a, r.reason === "done" ? null : { reason: r.reason, error: r.error?.message, at: Date.now() });
6125
+ addEnd(a, r.reason === "done" ? null : a.lastEnd ?? { reason: r.reason, error: r.error?.message, at: Date.now() });
5952
6126
  setBusy(false);
5953
6127
  showUsage_(a);
5954
6128
  void refreshCommands();
package/docs/agent.md CHANGED
@@ -145,7 +145,7 @@ await workspace.sessions.delete("chat-41");
145
145
  - A session's `title` is the user's first words (what they typed, for a slash command), kept once known.
146
146
  - `persist: false` keeps a conversation in memory only.
147
147
  - `agent.export()` returns the session (`SessionData`) for storage of your own; `createAgent(provider, { restore: data })` continues it.
148
- - `agent.lastEnd` says how the last run ended when it did not finish (`{ reason, error?, at }`), and is saved with the session until the next run starts.
148
+ - `agent.lastEnd` says how the last run ended when it did not finish (`{ reason, error?, code?, overflow?, at }`), and is saved with the session until the next run starts.
149
149
  - `agent.clear()` starts the conversation over under the same id — stops a run, drops the queue, messages, title, usage — and saves that; the workspace's files stay. `agent.reset()` forgets the messages in memory only (not while running).
150
150
 
151
151
  ## Context and compaction
@@ -164,6 +164,27 @@ createAgent(provider, {
164
164
  await agent.compact("keep every API name we discussed"); // now, with a focus
165
165
  ```
166
166
 
167
+ ### When a request does not fit
168
+
169
+ 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.
170
+
171
+ When nothing more can go, the run ends with `reason: "error"` and a `ContextOverflowError`. Its `code` is `"context_overflow"`, its `detail` the provider's words, and its `overflow` says what takes up the room; `agent.lastEnd` carries the same and is saved with the session:
172
+
173
+ ```js
174
+ const r = await agent.prompt(text);
175
+ if (r.error?.code === "context_overflow") r.error.overflow; // { cause, used, window }
176
+ ```
177
+
178
+ | `cause` | The biggest part of the request |
179
+ |---|---|
180
+ | `attachments` | What is attached to the latest message |
181
+ | `message` | The latest message's own text |
182
+ | `tools` | The tools' schemas |
183
+ | `history` | The rest of the conversation |
184
+ | `model` | Nothing stands out: this model is too small for it |
185
+
186
+ `renderChat` turns this into a card with one-click ways out (see [the chat UI](chat-ui.md)). Without it, these are the pieces: `agent.rewind(index)` takes a message back, `agent.compact()` then `agent.continue()` carries on, `agent.configure({ model })` changes the model, and `agent.summarize(leaveOut?)` writes a summary that stays out of the conversation, for `seed(summary)` to start an empty one from.
187
+
167
188
  ## Pictures and models that see them
168
189
 
169
190
  Some models see pictures, some only read text. The agent asks the catalogue (`input_modalities`, see [Providers](providers.md#telling-the-agent-about-models)) and acts on the answer:
package/docs/chat-ui.md CHANGED
@@ -34,10 +34,24 @@
34
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).
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
- - **How a run ended** — *Stopped.*, the turn limit with *Continue*, an error with *Retry*; kept across reloads until the next run.
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.
38
38
  - **Context and spending** — a ring in the header shows how full the model's window is; a click opens a panel with the figures (used / window, model), what the conversation has cost (cost, input and output tokens, calls), when it compacts on its own, and *Compact now*. Older turns are summarised automatically.
39
39
  - **Time** — "Today 22:15" above messages that start a conversation or follow a pause.
40
40
 
41
+ ### A request too large for the model
42
+
43
+ The agent first makes the request smaller by itself; the user only sees a note that the context was compacted. When that is not enough, the chat says why in its language and offers what solves it, one click each:
44
+
45
+ | Why | Buttons |
46
+ |---|---|
47
+ | The attachments are too large | *Resend without attachments* |
48
+ | The message is too long | *Edit the message* |
49
+ | The conversation is too long | *Compact and continue*, *Continue in a new chat* |
50
+ | The tools take up too much | *Tool settings*, when you pass `toolSettings` |
51
+ | The model is too small | whichever of *Compact and continue*, *Continue in a new chat*, *Edit the message* can help |
52
+
53
+ Any of them also gets *Retry with \<model\>* when the catalogue has a model with a larger window (the smallest that can take the request). *Continue in a new chat* starts from a summary of this conversation; the latest message is sent again, or put back in the composer when it had attachments, for the user to decide. With `sessions: false` there is one conversation, so it starts that one over.
54
+
41
55
  ## Slash commands
42
56
 
43
57
  Typing `/` lists the built-in commands, then the directory's prompt templates and skills.
@@ -88,6 +102,7 @@ Typing `/` lists the built-in commands, then the directory's prompt templates an
88
102
  | `nextPrompt` | `false` | Suggest the user's next message: the model calls a built-in `suggest_next_prompt` tool with its final reply when an obvious next request follows (it ends the run, so no further call); the suggestion shows greyed in the empty input, Tab takes it, typing or Esc drops it. Needs the chat to own its agent. |
89
103
  | `onLink(href, text)` | | Called when a link in the conversation (a reply, its thinking, a tool card) is clicked, before the chat's own handling; return `true` when you handled it (e.g. your app's own documentation links open in your viewer). |
90
104
  | `files` | on with a workspace | The *Files* button and panel; `false` for a host with its own file view (links go to `onOpenFile`). |
105
+ | `toolSettings` | | Opens your own tool settings; offered when the connected tools leave no room for a request. |
91
106
  | `headerActions` | | Buttons of your own for the header, placed before the settings gear. |
92
107
  | `headerEnd` | | Buttons of your own after the settings gear (a close button). |
93
108
  | `composerActions` | | Buttons of your own in the composer's toolbar (see below). |
package/docs/providers.md CHANGED
@@ -171,6 +171,7 @@ Throw a `ProviderError(status, message, { code, retryAfter })` — or any error
171
171
  | Status | What the agent does |
172
172
  |---|---|
173
173
  | `408`, `429`, `5xx`, `0` (no answer, network) | Tries again with backoff — three attempts in all — waiting `retryAfter` seconds when given. Text already shown is discarded first (`message_reset` event). |
174
+ | A request too large for the model, in any provider's words, or `413` | Makes it smaller and sends it again; see [Context and compaction](agent.md#when-a-request-does-not-fit). |
174
175
  | anything else | Ends the run with `reason: "error"`; the chat shows the message with a Retry button. |
175
176
 
176
177
  Errors without a status are retried only when they look like network failures.
package/docs/reference.md CHANGED
@@ -17,6 +17,8 @@ Three entry points:
17
17
  | `runappsProvider(client)` | The RunApps SDK client. |
18
18
  | `toProvider(providerOrClient)` | A provider as is, a RunApps client wrapped. |
19
19
  | `ProviderError(status, message, { code?, retryAfter? })` | Throw from your provider; 408 / 429 / 5xx / 0 are retried. |
20
+ | `ContextOverflowError` | How a run ends when a request cannot be made to fit: `code` `"context_overflow"`, `overflow` `{ cause, used, window }`, `detail`. |
21
+ | `isContextOverflow(err)` | Whether an error means the request is larger than the model's context. |
20
22
  | `sseData(body, signal?)` | Yields the `data:` payloads of a server-sent event stream. |
21
23
  | `modelAccepts(model, kind)` | Whether a catalogue entry takes `"image"` / `"video"` / `"audio"` (from `input_modalities`, or a `vision` capability). |
22
24
  | types | `ModelProvider`, `ModelInfo`, `InputKind`, `OpenAIProviderOptions`, `RunAppsClientLike`, `ChatMessage`, `ContentPart`, `ChatTool`, `ChatToolCall`, `ChatCompletionParams`, `ChatCompletionChunk`, `ChatCompletion`, `Usage` |
@@ -37,6 +39,8 @@ Three entry points:
37
39
  | `clear()` | Start over under the same id (messages, queue, usage), saved. |
38
40
  | `modelInfo()`, `accepts(kind)` | The catalogue's entry for the model in use; whether it takes `"image"` / `"video"` / `"audio"` (`true` / `false` / `undefined`). |
39
41
  | `compact(focus?)` | Summarise older turns now. → `boolean` |
42
+ | `summarize(leaveOut?)` | A summary of the conversation that stays out of it. → `string \| null` |
43
+ | `seed(summary)` | Start an empty conversation from a summary. |
40
44
  | `queued`, `dequeue(message)`, `clearQueue()` | What waits. |
41
45
  | `on(event, handler)` / `on("*", (name, event) => …)` | Subscribe; returns an unsubscribe function. |
42
46
  | `ready()` | Resolves once a saved session is loaded. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runappsai/agent",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
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",