@runappsai/agent 0.3.0 → 0.3.2
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 +76 -67
- package/dist/agent.d.ts +2 -0
- package/dist/agent.js +14 -3
- package/dist/agent.umd.js +103 -94
- package/dist/chat.js +7 -4
- package/dist/index.cjs +125 -9
- package/dist/llm.d.ts +4 -0
- package/dist/mcp.d.ts +1 -1
- package/dist/results.d.ts +9 -0
- package/dist/results.js +130 -0
- package/dist/tool.d.ts +1 -1
- package/dist/tool.js +2 -1
- package/dist/types.d.ts +3 -1
- package/dist/ui.cjs +8 -2
- package/docs/tools.md +1 -1
- package/package.json +1 -1
package/dist/chat.js
CHANGED
|
@@ -45,7 +45,7 @@ const STRINGS = {
|
|
|
45
45
|
runCode: "Run code", ingRead: "Reading", ingList: "Listing", ingSearch: "Searching", ingWrite: "Writing", ingEdit: "Editing", ingDelete: "Deleting", ingRun: "Running code", ingAsk: "Asking you", ingOther: "Running", current: "Current", jumpEnd: "Jump to the latest",
|
|
46
46
|
sTabModel: "Model", sTabContext: "Context", sCompact: "When the context is nearly full", sCompactSummary: "Summarise older turns (one extra model call)", sCompactTrim: "Only trim: drop old tool results, then the oldest turns", sCompactAt: "Start when fewer tokens than this are left", sKeepRecent: "Keep this many of the newest tokens word for word", sDefaultN: "Default ({n})", sCompactNote: "{model}: starts with {at} tokens left and keeps about {keep} word for word (capped at 20% / 40% of its {window} window)", sCompactNoteTrim: "{model}: trims with fewer than {at} tokens left (capped at 20% of its {window} window)", autoTrim: "Auto-trim", debug: "Debug", dCalls: "Calls", dRequests: "Requests", dEvents: "Events", dContext: "Context", dTools: "Tools", dClear: "Clear the record", dFilter: "Filter by type",
|
|
47
47
|
dNoCalls: "No tool calls yet.", dNoRequests: "No model requests yet. Each call to the model is listed here with what was sent and what came back.", dNoEvents: "No events yet.",
|
|
48
|
-
dSystem: "System prompt", dMessages: "Messages sent to the model", dPayload: "Request", dResponse: "Response", dRun: "Run", dTurn: "Turn {n}", sent: "sent", justNow: "Just now", minutesAgo: "{n} min ago", hoursAgo: "{n} h ago", context: "context", copy: "Copy", copied: "Copied", rewind: "Rewind to here", rewindTitle: "Rewind to this message", regen: "Answer again", regenTitle: "Answer this question again", regenMsg: "This answer and what follows are dropped and the question is sent again.", delTurn: "Delete", delTurnTitle: "Delete this question and its answer?", delTurnMsg: "They are removed from the conversation; files stay as they are.", replyCost: "Cost: {cost}", replyUsage: "{in} in · {out} out · {calls} calls",
|
|
48
|
+
dSystem: "System prompt", dMessages: "Messages sent to the model", dPayload: "Request", dResponse: "Response", dRun: "Run", dTurn: "Turn {n}", sent: "sent", justNow: "Just now", minutesAgo: "{n} min ago", hoursAgo: "{n} h ago", context: "context", copy: "Copy", copied: "Copied", rewind: "Rewind to here", rewindTitle: "Rewind to this message", regen: "Answer again", regenTitle: "Answer this question again", regenMsg: "This answer and what follows are dropped and the question is sent again.", delTurn: "Delete", delTurnTitle: "Delete this question and its answer?", delTurnMsg: "They are removed from the conversation; files stay as they are.", replyCost: "Cost: {cost}", replyUsage: "{in} in · {out} out · {calls} calls", replyCache: "cache hit {p}%", replyCached: " ({n} from cache)",
|
|
49
49
|
older: "Load earlier messages", olderBusy: "Wait for the reply to finish, then load earlier messages.",
|
|
50
50
|
rewindMsg: "The conversation after it is dropped and the message goes back into the composer.", rewindFiles: "Also restore the directory's files to that moment", rewindGone: "This message is no longer in the conversation.", rewindSnapshot: "{n} files ({size}) as they were at {time}", rewindPartial: "Files over 2 MB were not in the snapshot and stay as they are.", rewindGoneFile: "{path} is no longer in the directory.",
|
|
51
51
|
running: "running", waitingAnswer: "waiting for your answer", finished: "finished", bgLimit: "{n} conversations are already running in the background; stop one before switching away from this one.",
|
|
@@ -86,7 +86,7 @@ const STRINGS = {
|
|
|
86
86
|
runCode: "运行代码", ingRead: "正在读取", ingList: "正在查看", ingSearch: "正在搜索", ingWrite: "正在写入", ingEdit: "正在修改", ingDelete: "正在删除", ingRun: "正在运行代码", ingAsk: "正在询问你", ingOther: "正在执行", current: "当前", jumpEnd: "回到最新",
|
|
87
87
|
sTabModel: "模型", sTabContext: "上下文", sCompact: "上下文快满时", sCompactSummary: "把较早的对话写成摘要(多一次模型调用)", sCompactTrim: "只裁剪:先删旧的工具结果,再删最早的对话", sCompactAt: "剩余少于多少 tokens 时开始", sKeepRecent: "原样保留最近多少 tokens", sDefaultN: "默认({n})", sCompactNote: "{model}:剩余 {at} tokens 时开始,原样保留约 {keep} tokens(最多为上下文 {window} 的 20% / 40%)", sCompactNoteTrim: "{model}:剩余少于 {at} tokens 时裁剪(最多为上下文 {window} 的 20%)", autoTrim: "自动裁剪", debug: "调试", dCalls: "调用", dRequests: "请求", dEvents: "事件", dContext: "上下文", dTools: "工具", dClear: "清空记录", dFilter: "按类型过滤",
|
|
88
88
|
dNoCalls: "还没有工具调用。", dNoRequests: "还没有模型请求。每次调用模型都会记在这里,包括发了什么、收到什么。", dNoEvents: "还没有事件。",
|
|
89
|
-
dSystem: "系统提示词", dMessages: "发给模型的消息", dPayload: "请求内容", dResponse: "响应", dRun: "运行", dTurn: "第 {n} 轮", sent: "已发送", justNow: "刚刚", minutesAgo: "{n} 分钟前", hoursAgo: "{n} 小时前", context: "上下文", copy: "复制", copied: "已复制", rewind: "回退到这里", rewindTitle: "回退到这条消息", regen: "重新回答", regenTitle: "重新回答这个问题", regenMsg: "这个回答及之后的对话会被删除,问题重新发送。", delTurn: "删除", delTurnTitle: "删除这一轮问答?", delTurnMsg: "这条提问和它的回答会从对话中删除,文件不受影响。", replyCost: "费用:{cost}", replyUsage: "输入 {in} · 输出 {out} · {calls} 次调用",
|
|
89
|
+
dSystem: "系统提示词", dMessages: "发给模型的消息", dPayload: "请求内容", dResponse: "响应", dRun: "运行", dTurn: "第 {n} 轮", sent: "已发送", justNow: "刚刚", minutesAgo: "{n} 分钟前", hoursAgo: "{n} 小时前", context: "上下文", copy: "复制", copied: "已复制", rewind: "回退到这里", rewindTitle: "回退到这条消息", regen: "重新回答", regenTitle: "重新回答这个问题", regenMsg: "这个回答及之后的对话会被删除,问题重新发送。", delTurn: "删除", delTurnTitle: "删除这一轮问答?", delTurnMsg: "这条提问和它的回答会从对话中删除,文件不受影响。", replyCost: "费用:{cost}", replyUsage: "输入 {in} · 输出 {out} · {calls} 次调用", replyCache: "缓存命中 {p}%", replyCached: "(其中缓存 {n})",
|
|
90
90
|
older: "加载更早的消息", olderBusy: "等这次回复结束后再加载更早的消息。",
|
|
91
91
|
rewindMsg: "它之后的对话会被删除,消息内容放回输入框。", rewindFiles: "同时把目录里的文件恢复到那一刻", rewindGone: "这条消息已不在对话里(可能已被压缩)。", rewindSnapshot: "{time} 时的 {n} 个文件({size})", rewindPartial: "超过 2 MB 的文件没进快照,会保持原样。", rewindGoneFile: "{path} 已不在目录里。",
|
|
92
92
|
running: "运行中", waitingAnswer: "等待你回答", finished: "已完成", bgLimit: "后台已有 {n} 个会话在运行,先停掉一个再切换。",
|
|
@@ -2183,7 +2183,10 @@ export function renderChat(target, opts) {
|
|
|
2183
2183
|
foot.append(copy, ...(replyActions?.retry === false ? [] : [again]), ...(replyActions?.delete === false ? [] : [del]));
|
|
2184
2184
|
const u = last.runUsage;
|
|
2185
2185
|
if (u && u.calls) {
|
|
2186
|
-
|
|
2186
|
+
// The share of the input read from the provider's prompt cache, on the line itself: it is most of what decides the cost.
|
|
2187
|
+
const cached = u.cached_tokens ?? 0;
|
|
2188
|
+
const hit = cached > 0 && u.prompt_tokens > 0 ? " · " + t.replyCache.replace("{p}", String(Math.round((cached / u.prompt_tokens) * 100))) : "";
|
|
2189
|
+
const show = (currency) => { cost.textContent = t.replyCost.replace("{cost}", fmtCost(u.total_cost, currency)) + hit; };
|
|
2187
2190
|
const cost = h("span", "ra-cost");
|
|
2188
2191
|
show(costCurrency);
|
|
2189
2192
|
// In the model's currency: asked of its catalogue entry when not known yet.
|
|
@@ -2191,7 +2194,7 @@ export function renderChat(target, opts) {
|
|
|
2191
2194
|
if (costCurrency === undefined && a)
|
|
2192
2195
|
void a.modelInfo().then((info) => { if (info?.price?.currency)
|
|
2193
2196
|
show(info.price.currency); }).catch(() => undefined);
|
|
2194
|
-
cost.title = t.replyUsage.replace("{in}", fmtTokens(u.prompt_tokens)).replace("{out}", fmtTokens(u.completion_tokens)).replace("{calls}", String(u.calls));
|
|
2197
|
+
cost.title = t.replyUsage.replace("{in}", fmtTokens(u.prompt_tokens) + (cached > 0 ? t.replyCached.replace("{n}", fmtTokens(cached)) : "")).replace("{out}", fmtTokens(u.completion_tokens)).replace("{calls}", String(u.calls));
|
|
2195
2198
|
foot.append(cost);
|
|
2196
2199
|
}
|
|
2197
2200
|
return foot;
|
package/dist/index.cjs
CHANGED
|
@@ -811,7 +811,7 @@ function firstLine(body) {
|
|
|
811
811
|
|
|
812
812
|
// src/tool.ts
|
|
813
813
|
var NAME_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
814
|
-
var DEFAULT_MAX_RESULT_CHARS =
|
|
814
|
+
var DEFAULT_MAX_RESULT_CHARS = 12e4;
|
|
815
815
|
function defineTool(def) {
|
|
816
816
|
if (!NAME_RE.test(def.name)) {
|
|
817
817
|
throw new Error(`tool name "${def.name}" must match ${NAME_RE}`);
|
|
@@ -2732,17 +2732,17 @@ function fileTools(ws, opts = {}) {
|
|
|
2732
2732
|
}
|
|
2733
2733
|
const fresh = await files.saw(normalizePath(path), { start, end, total, text: doc.kind === "text" ? text : void 0 });
|
|
2734
2734
|
if (fresh !== void 0) ctx.progress?.(fresh);
|
|
2735
|
-
let
|
|
2735
|
+
let notice2 = "";
|
|
2736
2736
|
if (end < total) {
|
|
2737
2737
|
const next = end + 1;
|
|
2738
|
-
if (bytes >= MAX_READ_BYTES || limit === void 0 && out.length >= MAX_READ_LINES)
|
|
2738
|
+
if (bytes >= MAX_READ_BYTES || limit === void 0 && out.length >= MAX_READ_LINES) notice2 = `
|
|
2739
2739
|
|
|
2740
2740
|
[Showing lines ${start}-${end} of ${total}${bytes >= MAX_READ_BYTES ? " (50.0KB limit)" : ""}. Use offset=${next} to continue.]`;
|
|
2741
|
-
else
|
|
2741
|
+
else notice2 = `
|
|
2742
2742
|
|
|
2743
2743
|
[${total - end} more lines in file. Use offset=${next} to continue.]`;
|
|
2744
2744
|
}
|
|
2745
|
-
return out.join("\n") +
|
|
2745
|
+
return out.join("\n") + notice2;
|
|
2746
2746
|
}
|
|
2747
2747
|
}),
|
|
2748
2748
|
defineTool({
|
|
@@ -3329,6 +3329,115 @@ async function webTools(platform, opts = {}) {
|
|
|
3329
3329
|
return out;
|
|
3330
3330
|
}
|
|
3331
3331
|
|
|
3332
|
+
// src/results.ts
|
|
3333
|
+
var SEND_MAX = 2e4;
|
|
3334
|
+
var HEAD = 16e3;
|
|
3335
|
+
var TAIL = 3e3;
|
|
3336
|
+
var KEEP_OLD = 2e3;
|
|
3337
|
+
var KEEP_RECENT = 4;
|
|
3338
|
+
var RECALL_MAX = 18e3;
|
|
3339
|
+
var RECALL_TOOL = "recall_result";
|
|
3340
|
+
function callIndex(messages) {
|
|
3341
|
+
const calls = /* @__PURE__ */ new Map();
|
|
3342
|
+
for (const m of messages) for (const c of m.tool_calls ?? []) calls.set(c.id ?? "", { name: c.function.name, args: c.function.arguments ?? "" });
|
|
3343
|
+
return calls;
|
|
3344
|
+
}
|
|
3345
|
+
function notice(m, text, call) {
|
|
3346
|
+
let args = call?.args ?? "";
|
|
3347
|
+
if (args.length > 200) args = `${args.slice(0, 200)}\u2026`;
|
|
3348
|
+
return { ...m, content: `[The result of ${call?.name ?? "this call"} ${args} is not repeated here (${text.length} characters). ${RECALL_TOOL} {"id":"${m.tool_call_id}"} reads it again; give offset or grep for a part of it.]` };
|
|
3349
|
+
}
|
|
3350
|
+
function clip(m, text) {
|
|
3351
|
+
if (text.length <= SEND_MAX) return m;
|
|
3352
|
+
return { ...m, content: `${text.slice(0, HEAD)}
|
|
3353
|
+
|
|
3354
|
+
[\u2026 ${text.length - HEAD - TAIL} characters left out of ${text.length}. ${RECALL_TOOL} {"id":"${m.tool_call_id}","offset":${HEAD}} reads on from here; grep finds lines.]
|
|
3355
|
+
|
|
3356
|
+
${text.slice(text.length - TAIL)}` };
|
|
3357
|
+
}
|
|
3358
|
+
function shapeResults(messages, budget, system) {
|
|
3359
|
+
let start = 0;
|
|
3360
|
+
for (let i = messages.length - 1; i >= 0; i--) if (messages[i].role === "user") {
|
|
3361
|
+
start = i;
|
|
3362
|
+
break;
|
|
3363
|
+
}
|
|
3364
|
+
let calls = null;
|
|
3365
|
+
const out = messages.map((m, i) => {
|
|
3366
|
+
if (m.role !== "tool" || typeof m.content !== "string") return m;
|
|
3367
|
+
if (i < start && m.content.length > KEEP_OLD) return notice(m, m.content, (calls ?? (calls = callIndex(messages))).get(m.tool_call_id ?? ""));
|
|
3368
|
+
return clip(m, m.content);
|
|
3369
|
+
});
|
|
3370
|
+
if (!(budget > 0) || estimateTokens(out, system) <= budget) return out;
|
|
3371
|
+
const mine = [];
|
|
3372
|
+
for (let i = start; i < out.length; i++) {
|
|
3373
|
+
const m = messages[i];
|
|
3374
|
+
if (m.role === "tool" && typeof m.content === "string" && m.content.length > KEEP_OLD) mine.push(i);
|
|
3375
|
+
}
|
|
3376
|
+
for (let q = 0; q < mine.length - KEEP_RECENT; q++) {
|
|
3377
|
+
const i = mine[q], m = messages[i];
|
|
3378
|
+
out[i] = notice(m, m.content, (calls ?? (calls = callIndex(messages))).get(m.tool_call_id ?? ""));
|
|
3379
|
+
if (estimateTokens(out, system) <= budget) break;
|
|
3380
|
+
}
|
|
3381
|
+
return out;
|
|
3382
|
+
}
|
|
3383
|
+
function textOf2(content) {
|
|
3384
|
+
if (typeof content === "string") return content;
|
|
3385
|
+
return (content ?? []).map((p) => p.type === "text" ? p.text : "").join("");
|
|
3386
|
+
}
|
|
3387
|
+
function needsRecall(messages) {
|
|
3388
|
+
return messages.some((m) => m.role === "tool" && typeof m.content === "string" && m.content.length > KEEP_OLD);
|
|
3389
|
+
}
|
|
3390
|
+
function recallTool(history) {
|
|
3391
|
+
return defineTool({
|
|
3392
|
+
name: RECALL_TOOL,
|
|
3393
|
+
description: "Read again a tool result of this conversation that was shortened or left out of what you were sent (the notice in its place gives the id). Without offset or grep it returns the start; offset continues from a character position; grep returns only the lines that contain the text, numbered.",
|
|
3394
|
+
parameters: {
|
|
3395
|
+
type: "object",
|
|
3396
|
+
properties: {
|
|
3397
|
+
id: { type: "string", description: "The tool call id from the notice" },
|
|
3398
|
+
offset: { type: "number", description: "Character position to read from (default 0)" },
|
|
3399
|
+
grep: { type: "string", description: "Only the lines containing this text (case-insensitive)" }
|
|
3400
|
+
},
|
|
3401
|
+
required: ["id"],
|
|
3402
|
+
additionalProperties: false
|
|
3403
|
+
},
|
|
3404
|
+
readOnly: true,
|
|
3405
|
+
maxResultChars: RECALL_MAX + 200,
|
|
3406
|
+
execute({ id, offset, grep }) {
|
|
3407
|
+
const found = [...history()].reverse().find((m) => m.role === "tool" && m.tool_call_id === id);
|
|
3408
|
+
if (!found) throw new Error(`no result with id ${id} in this conversation (it may be from before a compaction): call the original tool again`);
|
|
3409
|
+
const c = textOf2(found.content);
|
|
3410
|
+
if (grep) {
|
|
3411
|
+
let text = c;
|
|
3412
|
+
if (!text.includes("\n")) {
|
|
3413
|
+
try {
|
|
3414
|
+
text = JSON.stringify(JSON.parse(text), null, 1);
|
|
3415
|
+
} catch {
|
|
3416
|
+
}
|
|
3417
|
+
}
|
|
3418
|
+
const lines = text.split("\n"), want = grep.toLowerCase(), hits = [];
|
|
3419
|
+
let size = 0, n = 0;
|
|
3420
|
+
lines.forEach((l, i) => {
|
|
3421
|
+
if (!l.toLowerCase().includes(want)) return;
|
|
3422
|
+
n++;
|
|
3423
|
+
const line = `${i + 1}: ${l.length > 500 ? `${l.slice(0, 500)}\u2026` : l}`;
|
|
3424
|
+
if (size + line.length > RECALL_MAX) return;
|
|
3425
|
+
hits.push(line);
|
|
3426
|
+
size += line.length + 1;
|
|
3427
|
+
});
|
|
3428
|
+
if (!n) return `No line of the ${lines.length} contains "${grep}".`;
|
|
3429
|
+
return hits.join("\n") + (hits.length < n ? `
|
|
3430
|
+
[${n - hits.length} more matching lines left out: narrow the text]` : "");
|
|
3431
|
+
}
|
|
3432
|
+
const from = Math.max(0, Math.floor(offset ?? 0));
|
|
3433
|
+
if (from >= c.length) return `The result is ${c.length} characters long; offset ${from} is past its end.`;
|
|
3434
|
+
const part = c.slice(from, from + RECALL_MAX), end = from + part.length;
|
|
3435
|
+
return part + (end < c.length ? `
|
|
3436
|
+
[characters ${from}-${end} of ${c.length}; offset ${end} reads on]` : "");
|
|
3437
|
+
}
|
|
3438
|
+
});
|
|
3439
|
+
}
|
|
3440
|
+
|
|
3332
3441
|
// src/dialogs.ts
|
|
3333
3442
|
function isZh() {
|
|
3334
3443
|
if (typeof document === "undefined") return false;
|
|
@@ -3799,6 +3908,7 @@ var Agent = class {
|
|
|
3799
3908
|
/** The platform's web tools, loaded the first time they are offered. */
|
|
3800
3909
|
__publicField(this, "webCache", null);
|
|
3801
3910
|
__publicField(this, "history", []);
|
|
3911
|
+
__publicField(this, "recall", null);
|
|
3802
3912
|
__publicField(this, "committed", 0);
|
|
3803
3913
|
__publicField(this, "droppedTurns", 0);
|
|
3804
3914
|
__publicField(this, "_usage", emptyUsage());
|
|
@@ -4239,7 +4349,7 @@ var Agent = class {
|
|
|
4239
4349
|
const params = {
|
|
4240
4350
|
...this.opts.extra ?? {},
|
|
4241
4351
|
model: this.opts.model ?? "",
|
|
4242
|
-
messages: [{ role: "system", content: system }, ...this.toWireHistory(await this.mediaSupport())],
|
|
4352
|
+
messages: [{ role: "system", content: system }, ...this.toWireHistory(await this.mediaSupport(), Math.floor(window2 * 0.6), fixed)],
|
|
4243
4353
|
max_tokens: maxTokens
|
|
4244
4354
|
};
|
|
4245
4355
|
if (!params.model) delete params.model;
|
|
@@ -4365,13 +4475,15 @@ var Agent = class {
|
|
|
4365
4475
|
this.loop.warned = false;
|
|
4366
4476
|
this.emit("steered", { runId, messages: steer });
|
|
4367
4477
|
}
|
|
4368
|
-
|
|
4478
|
+
/** `budget`: tokens a request should stay under (tool results are left out to get there, see results.ts); 0 for none. */
|
|
4479
|
+
toWireHistory(media = {}, budget = 0, system) {
|
|
4369
4480
|
let lastUser = -1;
|
|
4370
4481
|
for (let i = this.history.length - 1; i >= 0; i--) if (this.history[i].role === "user") {
|
|
4371
4482
|
lastUser = i;
|
|
4372
4483
|
break;
|
|
4373
4484
|
}
|
|
4374
|
-
|
|
4485
|
+
const wire = shapeResults(this.history.map((m, i) => toWire(m, i < lastUser)), budget, system);
|
|
4486
|
+
return withoutMedia(moveToolImages(wire), media, this.opts.model);
|
|
4375
4487
|
}
|
|
4376
4488
|
/** What the model in use takes besides text (undefined: not known — then it is sent). */
|
|
4377
4489
|
async mediaSupport() {
|
|
@@ -4389,6 +4501,7 @@ var Agent = class {
|
|
|
4389
4501
|
/** The tools offered this turn: `vision` tools only while the model is known to take pictures, the web tools while they are on. */
|
|
4390
4502
|
async activeTools() {
|
|
4391
4503
|
let tools = this.tools;
|
|
4504
|
+
if (needsRecall(this.history) && !tools.some((t) => t.name === RECALL_TOOL)) tools = [...tools, this.recall ?? (this.recall = recallTool(() => this.history))];
|
|
4392
4505
|
if (tools.some((t) => t.vision)) {
|
|
4393
4506
|
const sees = await this.accepts("image");
|
|
4394
4507
|
tools = tools.filter((t) => !t.vision || sees === true);
|
|
@@ -4855,7 +4968,8 @@ Fix the call and try again.`);
|
|
|
4855
4968
|
total_cost: round(u.total_cost - before.total_cost),
|
|
4856
4969
|
prompt_tokens: u.prompt_tokens - before.prompt_tokens,
|
|
4857
4970
|
completion_tokens: u.completion_tokens - before.completion_tokens,
|
|
4858
|
-
calls: u.calls - before.calls
|
|
4971
|
+
calls: u.calls - before.calls,
|
|
4972
|
+
...(u.cached_tokens ?? 0) > (before.cached_tokens ?? 0) ? { cached_tokens: (u.cached_tokens ?? 0) - (before.cached_tokens ?? 0) } : {}
|
|
4859
4973
|
};
|
|
4860
4974
|
return;
|
|
4861
4975
|
}
|
|
@@ -4868,6 +4982,8 @@ Fix the call and try again.`);
|
|
|
4868
4982
|
this._usage.total_cost = round(this._usage.total_cost + (u.total_cost ?? 0));
|
|
4869
4983
|
this._usage.prompt_tokens += u.prompt_tokens ?? 0;
|
|
4870
4984
|
this._usage.completion_tokens += u.completion_tokens ?? 0;
|
|
4985
|
+
const cached = u.prompt_tokens_details?.cached_tokens ?? 0;
|
|
4986
|
+
if (cached > 0) this._usage.cached_tokens = (this._usage.cached_tokens ?? 0) + cached;
|
|
4871
4987
|
this._usage.calls++;
|
|
4872
4988
|
}
|
|
4873
4989
|
/** How full the model's context is: tokens the next call would send (estimated) against the window. */
|
package/dist/llm.d.ts
CHANGED
|
@@ -59,6 +59,10 @@ export interface Usage {
|
|
|
59
59
|
prompt_tokens?: number;
|
|
60
60
|
completion_tokens?: number;
|
|
61
61
|
total_tokens?: number;
|
|
62
|
+
/** cached_tokens: the part of prompt_tokens the provider read from its prompt cache. */
|
|
63
|
+
prompt_tokens_details?: {
|
|
64
|
+
cached_tokens?: number;
|
|
65
|
+
};
|
|
62
66
|
/** What the call cost in USD, when the provider says (RunApps does). */
|
|
63
67
|
total_cost?: number;
|
|
64
68
|
}
|
package/dist/mcp.d.ts
CHANGED
|
@@ -23,7 +23,7 @@ export interface MCPOptions {
|
|
|
23
23
|
timeoutMs?: number;
|
|
24
24
|
/** Most tools taken from the server (default 64). */
|
|
25
25
|
maxTools?: number;
|
|
26
|
-
/** Longest tool result
|
|
26
|
+
/** Longest tool result kept in the conversation, in characters (default 120 000). */
|
|
27
27
|
maxResultChars?: number;
|
|
28
28
|
/** Your own fetch (a proxy, tests). */
|
|
29
29
|
fetch?: typeof fetch;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ChatMessage } from "./llm.js";
|
|
2
|
+
import type { Tool } from "./types.js";
|
|
3
|
+
export declare const RECALL_TOOL = "recall_result";
|
|
4
|
+
/** `messages` as the model is sent them (see the top of this file); `budget` in tokens, 0 for none. */
|
|
5
|
+
export declare function shapeResults(messages: ChatMessage[], budget: number, system?: string): ChatMessage[];
|
|
6
|
+
/** Whether the conversation has a result that a request may carry only part of (recall_result is offered then). */
|
|
7
|
+
export declare function needsRecall(messages: ChatMessage[]): boolean;
|
|
8
|
+
/** recall_result: a tool result of the conversation read again, whole or in part. */
|
|
9
|
+
export declare function recallTool(history: () => ChatMessage[]): Tool;
|
package/dist/results.js
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// What a request carries of tool results. The conversation keeps every result as the
|
|
2
|
+
// tool returned it (up to its maxResultChars); each request is shaped here, so one big
|
|
3
|
+
// result does not ride along in every later call:
|
|
4
|
+
// - a result over SEND_MAX characters goes as its head and tail, with a note;
|
|
5
|
+
// - a result from before the latest user message over KEEP_OLD goes as a one-line notice;
|
|
6
|
+
// - while a request is over its budget, this run's older results get the notice too,
|
|
7
|
+
// all but the newest KEEP_RECENT.
|
|
8
|
+
// Earlier turns are shaped the same way for the whole run, so the start of what is sent
|
|
9
|
+
// stays the same from one call to the next (the provider's prompt cache keeps hitting).
|
|
10
|
+
// recall_result reads any of them again from the conversation.
|
|
11
|
+
import { estimateTokens } from "./context.js";
|
|
12
|
+
import { defineTool } from "./tool.js";
|
|
13
|
+
const SEND_MAX = 20_000, HEAD = 16_000, TAIL = 3_000;
|
|
14
|
+
const KEEP_OLD = 2_000;
|
|
15
|
+
const KEEP_RECENT = 4;
|
|
16
|
+
const RECALL_MAX = 18_000;
|
|
17
|
+
export const RECALL_TOOL = "recall_result";
|
|
18
|
+
function callIndex(messages) {
|
|
19
|
+
const calls = new Map();
|
|
20
|
+
for (const m of messages)
|
|
21
|
+
for (const c of m.tool_calls ?? [])
|
|
22
|
+
calls.set(c.id ?? "", { name: c.function.name, args: c.function.arguments ?? "" });
|
|
23
|
+
return calls;
|
|
24
|
+
}
|
|
25
|
+
function notice(m, text, call) {
|
|
26
|
+
let args = call?.args ?? "";
|
|
27
|
+
if (args.length > 200)
|
|
28
|
+
args = `${args.slice(0, 200)}…`;
|
|
29
|
+
return { ...m, content: `[The result of ${call?.name ?? "this call"} ${args} is not repeated here (${text.length} characters). ${RECALL_TOOL} {"id":"${m.tool_call_id}"} reads it again; give offset or grep for a part of it.]` };
|
|
30
|
+
}
|
|
31
|
+
function clip(m, text) {
|
|
32
|
+
if (text.length <= SEND_MAX)
|
|
33
|
+
return m;
|
|
34
|
+
return { ...m, content: `${text.slice(0, HEAD)}\n\n[… ${text.length - HEAD - TAIL} characters left out of ${text.length}. ${RECALL_TOOL} {"id":"${m.tool_call_id}","offset":${HEAD}} reads on from here; grep finds lines.]\n\n${text.slice(text.length - TAIL)}` };
|
|
35
|
+
}
|
|
36
|
+
/** `messages` as the model is sent them (see the top of this file); `budget` in tokens, 0 for none. */
|
|
37
|
+
export function shapeResults(messages, budget, system) {
|
|
38
|
+
let start = 0;
|
|
39
|
+
for (let i = messages.length - 1; i >= 0; i--)
|
|
40
|
+
if (messages[i].role === "user") {
|
|
41
|
+
start = i;
|
|
42
|
+
break;
|
|
43
|
+
}
|
|
44
|
+
let calls = null;
|
|
45
|
+
const out = messages.map((m, i) => {
|
|
46
|
+
if (m.role !== "tool" || typeof m.content !== "string")
|
|
47
|
+
return m; // pictures are moved and dropped elsewhere
|
|
48
|
+
if (i < start && m.content.length > KEEP_OLD)
|
|
49
|
+
return notice(m, m.content, (calls ??= callIndex(messages)).get(m.tool_call_id ?? ""));
|
|
50
|
+
return clip(m, m.content);
|
|
51
|
+
});
|
|
52
|
+
if (!(budget > 0) || estimateTokens(out, system) <= budget)
|
|
53
|
+
return out;
|
|
54
|
+
const mine = [];
|
|
55
|
+
for (let i = start; i < out.length; i++) {
|
|
56
|
+
const m = messages[i];
|
|
57
|
+
if (m.role === "tool" && typeof m.content === "string" && m.content.length > KEEP_OLD)
|
|
58
|
+
mine.push(i);
|
|
59
|
+
}
|
|
60
|
+
for (let q = 0; q < mine.length - KEEP_RECENT; q++) {
|
|
61
|
+
const i = mine[q], m = messages[i];
|
|
62
|
+
out[i] = notice(m, m.content, (calls ??= callIndex(messages)).get(m.tool_call_id ?? ""));
|
|
63
|
+
if (estimateTokens(out, system) <= budget)
|
|
64
|
+
break;
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
function textOf(content) {
|
|
69
|
+
if (typeof content === "string")
|
|
70
|
+
return content;
|
|
71
|
+
return (content ?? []).map((p) => (p.type === "text" ? p.text : "")).join("");
|
|
72
|
+
}
|
|
73
|
+
/** Whether the conversation has a result that a request may carry only part of (recall_result is offered then). */
|
|
74
|
+
export function needsRecall(messages) {
|
|
75
|
+
return messages.some((m) => m.role === "tool" && typeof m.content === "string" && m.content.length > KEEP_OLD);
|
|
76
|
+
}
|
|
77
|
+
/** recall_result: a tool result of the conversation read again, whole or in part. */
|
|
78
|
+
export function recallTool(history) {
|
|
79
|
+
return defineTool({
|
|
80
|
+
name: RECALL_TOOL,
|
|
81
|
+
description: "Read again a tool result of this conversation that was shortened or left out of what you were sent (the notice in its place gives the id). Without offset or grep it returns the start; offset continues from a character position; grep returns only the lines that contain the text, numbered.",
|
|
82
|
+
parameters: {
|
|
83
|
+
type: "object",
|
|
84
|
+
properties: {
|
|
85
|
+
id: { type: "string", description: "The tool call id from the notice" },
|
|
86
|
+
offset: { type: "number", description: "Character position to read from (default 0)" },
|
|
87
|
+
grep: { type: "string", description: "Only the lines containing this text (case-insensitive)" },
|
|
88
|
+
},
|
|
89
|
+
required: ["id"],
|
|
90
|
+
additionalProperties: false,
|
|
91
|
+
},
|
|
92
|
+
readOnly: true,
|
|
93
|
+
maxResultChars: RECALL_MAX + 200,
|
|
94
|
+
execute({ id, offset, grep }) {
|
|
95
|
+
const found = [...history()].reverse().find((m) => m.role === "tool" && m.tool_call_id === id);
|
|
96
|
+
if (!found)
|
|
97
|
+
throw new Error(`no result with id ${id} in this conversation (it may be from before a compaction): call the original tool again`);
|
|
98
|
+
const c = textOf(found.content);
|
|
99
|
+
if (grep) {
|
|
100
|
+
let text = c;
|
|
101
|
+
if (!text.includes("\n")) {
|
|
102
|
+
try {
|
|
103
|
+
text = JSON.stringify(JSON.parse(text), null, 1);
|
|
104
|
+
}
|
|
105
|
+
catch { /* not JSON */ }
|
|
106
|
+
} // one-line JSON: a field a line
|
|
107
|
+
const lines = text.split("\n"), want = grep.toLowerCase(), hits = [];
|
|
108
|
+
let size = 0, n = 0;
|
|
109
|
+
lines.forEach((l, i) => {
|
|
110
|
+
if (!l.toLowerCase().includes(want))
|
|
111
|
+
return;
|
|
112
|
+
n++;
|
|
113
|
+
const line = `${i + 1}: ${l.length > 500 ? `${l.slice(0, 500)}…` : l}`;
|
|
114
|
+
if (size + line.length > RECALL_MAX)
|
|
115
|
+
return;
|
|
116
|
+
hits.push(line);
|
|
117
|
+
size += line.length + 1;
|
|
118
|
+
});
|
|
119
|
+
if (!n)
|
|
120
|
+
return `No line of the ${lines.length} contains "${grep}".`;
|
|
121
|
+
return hits.join("\n") + (hits.length < n ? `\n[${n - hits.length} more matching lines left out: narrow the text]` : "");
|
|
122
|
+
}
|
|
123
|
+
const from = Math.max(0, Math.floor(offset ?? 0));
|
|
124
|
+
if (from >= c.length)
|
|
125
|
+
return `The result is ${c.length} characters long; offset ${from} is past its end.`;
|
|
126
|
+
const part = c.slice(from, from + RECALL_MAX), end = from + part.length;
|
|
127
|
+
return part + (end < c.length ? `\n[characters ${from}-${end} of ${c.length}; offset ${end} reads on]` : "");
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
}
|
package/dist/tool.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { ChatTool, ContentPart } from "./llm.js";
|
|
2
2
|
import type { Tool, ToolDefinition, ToolResultValue } from "./types.js";
|
|
3
|
-
export declare const DEFAULT_MAX_RESULT_CHARS =
|
|
3
|
+
export declare const DEFAULT_MAX_RESULT_CHARS = 120000;
|
|
4
4
|
/**
|
|
5
5
|
* Declares a tool. Checks the name and fills in an empty-object schema
|
|
6
6
|
* when the tool takes no arguments. The JSON Schema in `parameters`
|
package/dist/tool.js
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
// helpers the loop uses to turn a tool into the chat schema and a tool's
|
|
3
3
|
// return value into what the model reads.
|
|
4
4
|
const NAME_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
5
|
-
|
|
5
|
+
// What the conversation keeps of a result; what each request carries of it is cut shorter (results.ts).
|
|
6
|
+
export const DEFAULT_MAX_RESULT_CHARS = 120_000;
|
|
6
7
|
/**
|
|
7
8
|
* Declares a tool. Checks the name and fills in an empty-object schema
|
|
8
9
|
* when the tool takes no arguments. The JSON Schema in `parameters`
|
package/dist/types.d.ts
CHANGED
|
@@ -112,7 +112,7 @@ export interface ToolDefinition<A = Record<string, unknown>> {
|
|
|
112
112
|
* with no text, the run goes on as usual.
|
|
113
113
|
*/
|
|
114
114
|
endsRun?: boolean;
|
|
115
|
-
/** Longest result
|
|
115
|
+
/** Longest result kept in the conversation, in characters (default 120 000); a request carries at most 20 000 of it, recall_result reads the rest. */
|
|
116
116
|
maxResultChars?: number;
|
|
117
117
|
/** `false`: the model may call it, code in `run_js` may not (`tools.x()` says so). Default: both. */
|
|
118
118
|
callableFromCode?: boolean;
|
|
@@ -344,6 +344,8 @@ export interface AgentUsage {
|
|
|
344
344
|
completion_tokens: number;
|
|
345
345
|
/** Model calls made (turns), including retries that returned usage. */
|
|
346
346
|
calls: number;
|
|
347
|
+
/** Of prompt_tokens, those the provider read from its prompt cache (usage.prompt_tokens_details.cached_tokens), when it says. */
|
|
348
|
+
cached_tokens?: number;
|
|
347
349
|
}
|
|
348
350
|
export interface RunResult {
|
|
349
351
|
runId: string;
|
package/dist/ui.cjs
CHANGED
|
@@ -2709,6 +2709,8 @@ var STRINGS = {
|
|
|
2709
2709
|
delTurnMsg: "They are removed from the conversation; files stay as they are.",
|
|
2710
2710
|
replyCost: "Cost: {cost}",
|
|
2711
2711
|
replyUsage: "{in} in \xB7 {out} out \xB7 {calls} calls",
|
|
2712
|
+
replyCache: "cache hit {p}%",
|
|
2713
|
+
replyCached: " ({n} from cache)",
|
|
2712
2714
|
older: "Load earlier messages",
|
|
2713
2715
|
olderBusy: "Wait for the reply to finish, then load earlier messages.",
|
|
2714
2716
|
rewindMsg: "The conversation after it is dropped and the message goes back into the composer.",
|
|
@@ -3030,6 +3032,8 @@ var STRINGS = {
|
|
|
3030
3032
|
delTurnMsg: "\u8FD9\u6761\u63D0\u95EE\u548C\u5B83\u7684\u56DE\u7B54\u4F1A\u4ECE\u5BF9\u8BDD\u4E2D\u5220\u9664\uFF0C\u6587\u4EF6\u4E0D\u53D7\u5F71\u54CD\u3002",
|
|
3031
3033
|
replyCost: "\u8D39\u7528\uFF1A{cost}",
|
|
3032
3034
|
replyUsage: "\u8F93\u5165 {in} \xB7 \u8F93\u51FA {out} \xB7 {calls} \u6B21\u8C03\u7528",
|
|
3035
|
+
replyCache: "\u7F13\u5B58\u547D\u4E2D {p}%",
|
|
3036
|
+
replyCached: "\uFF08\u5176\u4E2D\u7F13\u5B58 {n}\uFF09",
|
|
3033
3037
|
older: "\u52A0\u8F7D\u66F4\u65E9\u7684\u6D88\u606F",
|
|
3034
3038
|
olderBusy: "\u7B49\u8FD9\u6B21\u56DE\u590D\u7ED3\u675F\u540E\u518D\u52A0\u8F7D\u66F4\u65E9\u7684\u6D88\u606F\u3002",
|
|
3035
3039
|
rewindMsg: "\u5B83\u4E4B\u540E\u7684\u5BF9\u8BDD\u4F1A\u88AB\u5220\u9664\uFF0C\u6D88\u606F\u5185\u5BB9\u653E\u56DE\u8F93\u5165\u6846\u3002",
|
|
@@ -5091,8 +5095,10 @@ ${t.webHint}`;
|
|
|
5091
5095
|
foot.append(copy, ...replyActions?.retry === false ? [] : [again], ...replyActions?.delete === false ? [] : [del]);
|
|
5092
5096
|
const u = last.runUsage;
|
|
5093
5097
|
if (u && u.calls) {
|
|
5098
|
+
const cached = u.cached_tokens ?? 0;
|
|
5099
|
+
const hit = cached > 0 && u.prompt_tokens > 0 ? " \xB7 " + t.replyCache.replace("{p}", String(Math.round(cached / u.prompt_tokens * 100))) : "";
|
|
5094
5100
|
const show = (currency) => {
|
|
5095
|
-
cost.textContent = t.replyCost.replace("{cost}", fmtCost(u.total_cost, currency));
|
|
5101
|
+
cost.textContent = t.replyCost.replace("{cost}", fmtCost(u.total_cost, currency)) + hit;
|
|
5096
5102
|
};
|
|
5097
5103
|
const cost = h("span", "ra-cost");
|
|
5098
5104
|
show(costCurrency);
|
|
@@ -5100,7 +5106,7 @@ ${t.webHint}`;
|
|
|
5100
5106
|
if (costCurrency === void 0 && a) void a.modelInfo().then((info) => {
|
|
5101
5107
|
if (info?.price?.currency) show(info.price.currency);
|
|
5102
5108
|
}).catch(() => void 0);
|
|
5103
|
-
cost.title = t.replyUsage.replace("{in}", fmtTokens(u.prompt_tokens)).replace("{out}", fmtTokens(u.completion_tokens)).replace("{calls}", String(u.calls));
|
|
5109
|
+
cost.title = t.replyUsage.replace("{in}", fmtTokens(u.prompt_tokens) + (cached > 0 ? t.replyCached.replace("{n}", fmtTokens(cached)) : "")).replace("{out}", fmtTokens(u.completion_tokens)).replace("{calls}", String(u.calls));
|
|
5104
5110
|
foot.append(cost);
|
|
5105
5111
|
}
|
|
5106
5112
|
return foot;
|
package/docs/tools.md
CHANGED
|
@@ -76,7 +76,7 @@ const exportReport = defineTool({
|
|
|
76
76
|
| `{ content, details }` | `content` only; `details` stays for your app (in the `tool_end` event) |
|
|
77
77
|
| `undefined`, `null`, `""` | `"OK"` |
|
|
78
78
|
|
|
79
|
-
Results longer than `maxResultChars` (default
|
|
79
|
+
Results longer than `maxResultChars` (default 120 000 characters) are cut, with a note saying so. What each request carries is shorter: a result over 20 000 characters goes as its head and tail, a result from before the latest user message over 2 000 characters goes as a one-line notice, and while a request is over 60 % of the model's window the run's older results get the notice too (all but the newest four). The conversation keeps them whole, and the built-in `recall_result` tool reads any of them again, from an offset or only the lines containing a text. A thrown error is sent to the model as an error result.
|
|
80
80
|
|
|
81
81
|
A tool message can only carry text in the OpenAI format, so pictures (and audio or video) a tool returns go to the model in a user message right after the batch's results, each labelled with the call it came from. Only the latest two batches' pictures are sent again on later turns — each costs thousands of tokens; older ones are replaced by a note telling the model to call the tool again for the current state.
|
|
82
82
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@runappsai/agent",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
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",
|