@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/agent-core.umd.js +60 -60
- package/dist/agent.d.ts +23 -0
- package/dist/agent.js +169 -63
- package/dist/agent.umd.js +116 -112
- package/dist/chat.d.ts +2 -0
- package/dist/chat.js +222 -47
- package/dist/context.d.ts +1 -0
- package/dist/context.js +1 -1
- package/dist/index.cjs +179 -47
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/provider.d.ts +22 -0
- package/dist/provider.js +46 -0
- package/dist/types.d.ts +4 -1
- package/dist/ui.cjs +214 -33
- package/docs/agent.md +22 -1
- package/docs/chat-ui.md +17 -2
- package/docs/providers.md +1 -0
- package/docs/reference.md +4 -0
- package/package.json +1 -1
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:
|
|
3905
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
4114
|
-
const
|
|
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
|
-
|
|
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";
|
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";
|
package/dist/provider.d.ts
CHANGED
|
@@ -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. */
|