@runappsai/agent 0.2.1 → 0.3.1
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 +66 -57
- package/dist/agent.d.ts +2 -0
- package/dist/agent.js +10 -3
- package/dist/agent.umd.js +145 -113
- package/dist/chat.js +297 -25
- package/dist/dialogs.d.ts +1 -1
- package/dist/dialogs.js +117 -38
- package/dist/index.cjs +208 -29
- package/dist/index.d.ts +1 -1
- 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 +27 -5
- package/dist/ui.cjs +293 -21
- package/dist/ui.d.ts +1 -1
- package/docs/chat-ui.md +6 -1
- package/docs/tools.md +2 -2
- package/package.json +1 -1
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;
|
|
@@ -3481,29 +3590,88 @@ function domUI() {
|
|
|
3481
3590
|
async form(title, fields, opts = {}) {
|
|
3482
3591
|
const zh = isZh();
|
|
3483
3592
|
const v = await openDialog((d, done) => {
|
|
3484
|
-
d.append(el("div", "font-weight:600;font-size:15px;margin-bottom:6px", title));
|
|
3593
|
+
if (title) d.append(el("div", "font-weight:600;font-size:15px;margin-bottom:6px", title));
|
|
3485
3594
|
if (opts.message) d.append(el("div", "white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:10px", opts.message));
|
|
3486
|
-
|
|
3487
|
-
|
|
3488
|
-
|
|
3489
|
-
|
|
3490
|
-
|
|
3491
|
-
|
|
3492
|
-
|
|
3493
|
-
|
|
3494
|
-
|
|
3495
|
-
d.append(
|
|
3496
|
-
|
|
3595
|
+
d.style.maxHeight = "calc(100vh - 48px)";
|
|
3596
|
+
d.style.overflowY = "auto";
|
|
3597
|
+
const fieldStyle = "font:inherit;padding:8px 10px;border:1px solid rgba(127,127,127,.35);border-radius:8px;background:transparent;color:inherit;width:100%;box-sizing:border-box";
|
|
3598
|
+
const BAD = /* @__PURE__ */ Symbol("bad");
|
|
3599
|
+
const readers = fields.map((f) => {
|
|
3600
|
+
const choice = !!f.options?.length;
|
|
3601
|
+
const required = choice ? f.required !== false : !!f.required && f.type !== "boolean";
|
|
3602
|
+
const wrap = el(choice ? "div" : "label", "display:block;font-size:13px;margin:10px 0");
|
|
3603
|
+
wrap.append(el("div", "opacity:.8;margin-bottom:4px", (f.label ?? f.name) + (required ? " *" : "")));
|
|
3604
|
+
d.append(wrap);
|
|
3605
|
+
if (f.type === "boolean" && !choice) {
|
|
3606
|
+
const row2 = el("label", "display:flex;gap:8px;align-items:center;cursor:pointer");
|
|
3607
|
+
const input = el("input");
|
|
3608
|
+
input.type = "checkbox";
|
|
3609
|
+
input.checked = f.initial === true || f.initial === "true";
|
|
3610
|
+
row2.append(input, el("span", "", zh ? "\u662F" : "Yes"));
|
|
3611
|
+
wrap.append(row2);
|
|
3612
|
+
return { focus: input, read: () => input.checked };
|
|
3613
|
+
}
|
|
3614
|
+
if (!choice) {
|
|
3615
|
+
const area = f.type === "textarea";
|
|
3616
|
+
const input = area ? el("textarea", fieldStyle + ";min-height:80px;resize:vertical") : el("input", fieldStyle);
|
|
3617
|
+
if (input instanceof HTMLInputElement) {
|
|
3618
|
+
input.type = f.type === "number" ? "number" : f.type === "date" ? "date" : f.type === "datetime" ? "datetime-local" : "text";
|
|
3619
|
+
if (f.type === "number") input.step = "any";
|
|
3620
|
+
}
|
|
3621
|
+
if (f.placeholder) input.placeholder = f.placeholder;
|
|
3622
|
+
if (f.initial !== void 0 && typeof f.initial !== "boolean") input.value = String(f.initial);
|
|
3623
|
+
wrap.append(input);
|
|
3624
|
+
return { focus: input, read: () => {
|
|
3625
|
+
const raw = area ? input.value.replace(/\s+$/, "") : input.value.trim();
|
|
3626
|
+
if (!raw) return required ? BAD : void 0;
|
|
3627
|
+
if (f.type === "number") return Number.isFinite(Number(raw)) ? Number(raw) : BAD;
|
|
3628
|
+
return raw;
|
|
3629
|
+
} };
|
|
3630
|
+
}
|
|
3631
|
+
const name = "ra_frm_" + Math.random().toString(36).slice(2, 8);
|
|
3632
|
+
const inputs = [];
|
|
3633
|
+
const add = (value, label, description) => {
|
|
3634
|
+
const row2 = el("label", "display:flex;gap:8px;align-items:flex-start;padding:6px 10px;border:1px solid rgba(127,127,127,.3);border-radius:8px;cursor:pointer;margin-top:4px");
|
|
3635
|
+
const input = el("input", "margin-top:3px");
|
|
3636
|
+
input.type = f.multi ? "checkbox" : "radio";
|
|
3637
|
+
input.name = name;
|
|
3638
|
+
input.value = value;
|
|
3639
|
+
inputs.push(input);
|
|
3640
|
+
const text = el("div");
|
|
3641
|
+
text.append(el("div", "", label));
|
|
3642
|
+
if (description) text.append(el("div", "opacity:.7;font-size:12px", description));
|
|
3643
|
+
row2.append(input, text);
|
|
3644
|
+
wrap.append(row2);
|
|
3645
|
+
};
|
|
3646
|
+
for (const o of f.options) add(o.value, o.label ?? o.value, o.description);
|
|
3647
|
+
let other = null;
|
|
3648
|
+
if (f.allowOther) {
|
|
3649
|
+
add("__other__", zh ? "\u5176\u4ED6\u2026" : "Other\u2026");
|
|
3650
|
+
other = el("input", fieldStyle + ";margin-top:4px");
|
|
3651
|
+
other.placeholder = zh ? "\u8BF7\u8F93\u5165" : "Type your answer";
|
|
3652
|
+
other.addEventListener("focus", () => {
|
|
3653
|
+
const o = inputs.find((i) => i.value === "__other__");
|
|
3654
|
+
if (o) o.checked = true;
|
|
3655
|
+
});
|
|
3656
|
+
wrap.append(other);
|
|
3657
|
+
}
|
|
3658
|
+
return { focus: inputs[0], read: () => {
|
|
3659
|
+
const checked = inputs.filter((i) => i.checked);
|
|
3660
|
+
if (checked.some((i) => i.value === "__other__") && !other?.value.trim()) return BAD;
|
|
3661
|
+
const vals = checked.map((i) => i.value === "__other__" ? other.value.trim() : i.value);
|
|
3662
|
+
if (!vals.length) return required ? BAD : void 0;
|
|
3663
|
+
return f.multi ? vals : vals[0];
|
|
3664
|
+
} };
|
|
3497
3665
|
});
|
|
3498
3666
|
const submit = () => {
|
|
3499
3667
|
const out = {};
|
|
3500
|
-
for (
|
|
3501
|
-
const
|
|
3502
|
-
if (
|
|
3503
|
-
|
|
3668
|
+
for (let i = 0; i < fields.length; i++) {
|
|
3669
|
+
const v2 = readers[i].read();
|
|
3670
|
+
if (v2 === BAD) {
|
|
3671
|
+
readers[i].focus.focus();
|
|
3504
3672
|
return;
|
|
3505
3673
|
}
|
|
3506
|
-
if (
|
|
3674
|
+
if (v2 !== void 0) out[fields[i].name] = v2;
|
|
3507
3675
|
}
|
|
3508
3676
|
done(out);
|
|
3509
3677
|
};
|
|
@@ -3513,7 +3681,7 @@ function domUI() {
|
|
|
3513
3681
|
button(opts.ok ?? (zh ? "\u786E\u5B9A" : "OK"), true, false, submit)
|
|
3514
3682
|
);
|
|
3515
3683
|
d.append(row);
|
|
3516
|
-
queueMicrotask(() =>
|
|
3684
|
+
queueMicrotask(() => readers[0]?.focus.focus());
|
|
3517
3685
|
}, opts.signal, null);
|
|
3518
3686
|
return v && typeof v === "object" && !Array.isArray(v) ? v : null;
|
|
3519
3687
|
},
|
|
@@ -3553,14 +3721,14 @@ function askUserTool() {
|
|
|
3553
3721
|
name: "ask_user",
|
|
3554
3722
|
// The model asks, between its steps; code in the middle of a run does not.
|
|
3555
3723
|
callableFromCode: false,
|
|
3556
|
-
description: "Ask the user one to
|
|
3724
|
+
description: "Ask the user one to four questions when the request is genuinely ambiguous and the answer changes what you would do. Put everything you need to know in one call (they are asked together), not one question per call. Give 2\u20135 short options when there are natural choices (allow_other adds a free-text choice); leave options out for a free-text answer. Do not ask what you can reasonably decide yourself.",
|
|
3557
3725
|
parameters: {
|
|
3558
3726
|
type: "object",
|
|
3559
3727
|
properties: {
|
|
3560
3728
|
questions: {
|
|
3561
3729
|
type: "array",
|
|
3562
3730
|
minItems: 1,
|
|
3563
|
-
maxItems:
|
|
3731
|
+
maxItems: 4,
|
|
3564
3732
|
items: {
|
|
3565
3733
|
type: "object",
|
|
3566
3734
|
properties: {
|
|
@@ -3589,7 +3757,14 @@ function askUserTool() {
|
|
|
3589
3757
|
},
|
|
3590
3758
|
async execute({ questions }, ctx) {
|
|
3591
3759
|
const answers = [];
|
|
3592
|
-
|
|
3760
|
+
if (ctx.ui.form && questions.length > 1) {
|
|
3761
|
+
const fields = questions.map((q, i) => q.options && q.options.length ? { name: `q${i + 1}`, label: q.question, options: q.options.map((o) => ({ value: o.label, label: o.label, description: o.description })), multi: !!q.multi, allowOther: q.allow_other !== false } : { name: `q${i + 1}`, label: q.question, required: true });
|
|
3762
|
+
const values = await ctx.ui.form("", fields, { signal: ctx.signal });
|
|
3763
|
+
questions.forEach((q, i) => {
|
|
3764
|
+
const v = values?.[`q${i + 1}`];
|
|
3765
|
+
answers.push({ question: q.question, answer: v === void 0 ? null : Array.isArray(v) ? v : String(v) });
|
|
3766
|
+
});
|
|
3767
|
+
} else for (const q of questions) {
|
|
3593
3768
|
ctx.signal.throwIfAborted();
|
|
3594
3769
|
let answer;
|
|
3595
3770
|
if (q.options && q.options.length) {
|
|
@@ -3733,6 +3908,7 @@ var Agent = class {
|
|
|
3733
3908
|
/** The platform's web tools, loaded the first time they are offered. */
|
|
3734
3909
|
__publicField(this, "webCache", null);
|
|
3735
3910
|
__publicField(this, "history", []);
|
|
3911
|
+
__publicField(this, "recall", null);
|
|
3736
3912
|
__publicField(this, "committed", 0);
|
|
3737
3913
|
__publicField(this, "droppedTurns", 0);
|
|
3738
3914
|
__publicField(this, "_usage", emptyUsage());
|
|
@@ -4173,7 +4349,7 @@ var Agent = class {
|
|
|
4173
4349
|
const params = {
|
|
4174
4350
|
...this.opts.extra ?? {},
|
|
4175
4351
|
model: this.opts.model ?? "",
|
|
4176
|
-
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)],
|
|
4177
4353
|
max_tokens: maxTokens
|
|
4178
4354
|
};
|
|
4179
4355
|
if (!params.model) delete params.model;
|
|
@@ -4299,13 +4475,15 @@ var Agent = class {
|
|
|
4299
4475
|
this.loop.warned = false;
|
|
4300
4476
|
this.emit("steered", { runId, messages: steer });
|
|
4301
4477
|
}
|
|
4302
|
-
|
|
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) {
|
|
4303
4480
|
let lastUser = -1;
|
|
4304
4481
|
for (let i = this.history.length - 1; i >= 0; i--) if (this.history[i].role === "user") {
|
|
4305
4482
|
lastUser = i;
|
|
4306
4483
|
break;
|
|
4307
4484
|
}
|
|
4308
|
-
|
|
4485
|
+
const wire = shapeResults(this.history.map((m, i) => toWire(m, i < lastUser)), budget, system);
|
|
4486
|
+
return withoutMedia(moveToolImages(wire), media, this.opts.model);
|
|
4309
4487
|
}
|
|
4310
4488
|
/** What the model in use takes besides text (undefined: not known — then it is sent). */
|
|
4311
4489
|
async mediaSupport() {
|
|
@@ -4323,6 +4501,7 @@ var Agent = class {
|
|
|
4323
4501
|
/** The tools offered this turn: `vision` tools only while the model is known to take pictures, the web tools while they are on. */
|
|
4324
4502
|
async activeTools() {
|
|
4325
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))];
|
|
4326
4505
|
if (tools.some((t) => t.vision)) {
|
|
4327
4506
|
const sees = await this.accepts("image");
|
|
4328
4507
|
tools = tools.filter((t) => !t.vision || sees === true);
|
package/dist/index.d.ts
CHANGED
|
@@ -36,4 +36,4 @@ export { buildSystemPrompt, estimateTokens, fitBudget, groupTurns } from "./cont
|
|
|
36
36
|
export { validateSchema } from "./json-schema.js";
|
|
37
37
|
export { listZip, readZipEntry, buildZip, type ZipEntry, type Inflate } from "./zip.js";
|
|
38
38
|
export { skillZipFS, skillFoldersOf, subFS } from "./skill-zips.js";
|
|
39
|
-
export type { AgentEventMap, AgentEventName, AgentFS, AgentOptions, AgentUI, FormField, AgentUsage, FileStat, JSONSchema, Permissions, RunEnd, RunEndReason, RunResult, SelectOption, SessionData, SessionSummary, Skill, Tool, ToolCallHookEvent, ToolContext, ToolDefinition, ToolConfirm, ToolResultValue, ToolStatus, ToolDisplay, } from "./types.js";
|
|
39
|
+
export type { AgentEventMap, AgentEventName, AgentFS, AgentOptions, AgentUI, FormField, FormValues, AgentUsage, FileStat, JSONSchema, Permissions, RunEnd, RunEndReason, RunResult, SelectOption, SessionData, SessionSummary, Skill, Tool, ToolCallHookEvent, ToolContext, ToolDefinition, ToolConfirm, ToolResultValue, ToolStatus, ToolDisplay, } from "./types.js";
|
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;
|
|
@@ -245,17 +245,39 @@ export interface AgentUI {
|
|
|
245
245
|
message?: string;
|
|
246
246
|
ok?: string;
|
|
247
247
|
signal?: AbortSignal;
|
|
248
|
-
}): Promise<
|
|
248
|
+
}): Promise<FormValues | null>;
|
|
249
249
|
notify(message: string, level?: "info" | "warning" | "error"): void;
|
|
250
250
|
}
|
|
251
|
-
/**
|
|
251
|
+
/**
|
|
252
|
+
* What `AgentUI.form` resolves: a value per answered field — a number for a `number` field, true or false
|
|
253
|
+
* for a `boolean` one, `YYYY-MM-DD` for a `date`, `YYYY-MM-DDTHH:mm` for a `datetime`, the picked values
|
|
254
|
+
* for a `multi` choice, text for the rest.
|
|
255
|
+
*/
|
|
256
|
+
export type FormValues = Record<string, string | number | boolean | string[]>;
|
|
257
|
+
/**
|
|
258
|
+
* One field of `AgentUI.form`. A field with `options` is a choice question
|
|
259
|
+
* (answered by default; `required: false` lets it go unanswered); one without
|
|
260
|
+
* is a text or number box. In the built-in chat a form with a choice in it is
|
|
261
|
+
* asked one question at a time.
|
|
262
|
+
*/
|
|
252
263
|
export interface FormField {
|
|
253
264
|
name: string;
|
|
254
265
|
label?: string;
|
|
255
|
-
|
|
266
|
+
/**
|
|
267
|
+
* The input when there are no `options`: a one-line box (`text`, the default), `number`, `textarea`
|
|
268
|
+
* (several lines), `date`, `datetime` (date and time) or `boolean` (a switch, always answered).
|
|
269
|
+
*/
|
|
270
|
+
type?: "text" | "number" | "textarea" | "date" | "datetime" | "boolean";
|
|
256
271
|
required?: boolean;
|
|
257
272
|
placeholder?: string;
|
|
258
|
-
|
|
273
|
+
/** The starting value: text, a number, a date as `YYYY-MM-DD`, or true / false for a switch. */
|
|
274
|
+
initial?: string | number | boolean;
|
|
275
|
+
/** The choices; the answer is the picked option's `value`. */
|
|
276
|
+
options?: SelectOption[];
|
|
277
|
+
/** Several may be picked (a choice only): the answer is an array. */
|
|
278
|
+
multi?: boolean;
|
|
279
|
+
/** Adds "Other…" with a box for the user's own answer (a choice only). */
|
|
280
|
+
allowOther?: boolean;
|
|
259
281
|
}
|
|
260
282
|
export interface FileStat {
|
|
261
283
|
/** Absolute POSIX path inside the workspace. */
|